xref: /freebsd/bin/ls/ls.c (revision 23f282aa31e9b6fceacd449020e936e98d6f2298)
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Michael Fischbein.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1989, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
46 #else
47 static const char rcsid[] =
48   "$FreeBSD$";
49 #endif
50 #endif /* not lint */
51 
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 
56 #include <dirent.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fts.h>
60 #include <limits.h>
61 #include <locale.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 #include "ls.h"
68 #include "extern.h"
69 
70 /*
71  * Upward approximation of the maximum number of characters needed to
72  * represent a value of integral type t as a string, excluding the
73  * NUL terminator, with provision for a sign.
74  */
75 #define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
76 
77 char *getflags __P((u_long, char *));
78 
79 static void	 display __P((FTSENT *, FTSENT *));
80 static u_quad_t	 makenines __P((u_long));
81 static int	 mastercmp __P((const FTSENT **, const FTSENT **));
82 static void	 traverse __P((int, char **, int));
83 
84 static void (*printfcn) __P((DISPLAY *));
85 static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
86 
87 long blocksize;			/* block size units */
88 int termwidth = 80;		/* default terminal width */
89 
90 /* flags */
91 int f_accesstime;		/* use time of last access */
92 int f_column;			/* columnated format */
93 int f_flags;			/* show flags associated with a file */
94 int f_inode;			/* print inode */
95 int f_kblocks;			/* print size in kilobytes */
96 int f_listdir;			/* list actual directory, not contents */
97 int f_listdot;			/* list files beginning with . */
98 int f_longform;			/* long listing format */
99 int f_nonprint;			/* show unprintables as ? */
100 int f_nosort;			/* don't sort output */
101 int f_notabs;			/* don't use tab-separated multi-col output */
102 int f_numericonly;		/* don't convert uid/gid to name */
103 int f_octal;			/* show unprintables as \xxx */
104 int f_octal_escape;		/* like f_octal but use C escapes if possible */
105 int f_recursive;		/* ls subdirectories also */
106 int f_reversesort;		/* reverse whatever sort is used */
107 int f_sectime;			/* print the real time for all files */
108 int f_singlecol;		/* use single column output */
109 int f_size;			/* list size in short listing */
110 int f_statustime;		/* use time of last mode change */
111 int f_timesort;			/* sort by time vice name */
112 int f_type;			/* add type character for non-regular files */
113 int f_whiteout;			/* show whiteout entries */
114 
115 int rval;
116 
117 int
118 main(argc, argv)
119 	int argc;
120 	char *argv[];
121 {
122 	static char dot[] = ".", *dotav[] = { dot, NULL };
123 	struct winsize win;
124 	int ch, fts_options, notused;
125 	char *p;
126 
127 	(void) setlocale(LC_ALL, "");
128 
129 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
130 	if (isatty(STDOUT_FILENO)) {
131 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
132 		    !win.ws_col) {
133 			if ((p = getenv("COLUMNS")) != NULL)
134 				termwidth = atoi(p);
135 		}
136 		else
137 			termwidth = win.ws_col;
138 		f_column = f_nonprint = 1;
139 	} else {
140 		f_singlecol = 1;
141 		/* retrieve environment variable, in case of explicit -C */
142 		if ((p = getenv("COLUMNS")))
143 			termwidth = atoi(p);
144 	}
145 
146 	/* Root is -A automatically. */
147 	if (!getuid())
148 		f_listdot = 1;
149 
150 	fts_options = FTS_PHYSICAL;
151 	while ((ch = getopt(argc, argv, "1ABCFHLPRTWabcdfgiklnoqrstu")) != -1) {
152 		switch (ch) {
153 		/*
154 		 * The -1, -C and -l options all override each other so shell
155 		 * aliasing works right.
156 		 */
157 		case '1':
158 			f_singlecol = 1;
159 			f_column = f_longform = 0;
160 			break;
161 		case 'B':
162 			f_nonprint = 0;
163 			f_octal = 1;
164 		        f_octal_escape = 0;
165 			break;
166 		case 'C':
167 			f_column = 1;
168 			f_longform = f_singlecol = 0;
169 			break;
170 		case 'l':
171 			f_longform = 1;
172 			f_column = f_singlecol = 0;
173 			break;
174 		/* The -c and -u options override each other. */
175 		case 'c':
176 			f_statustime = 1;
177 			f_accesstime = 0;
178 			break;
179 		case 'u':
180 			f_accesstime = 1;
181 			f_statustime = 0;
182 			break;
183 		case 'F':
184 			f_type = 1;
185 			break;
186 		case 'H':
187 		        fts_options |= FTS_COMFOLLOW;
188 			break;
189 		case 'L':
190 			fts_options &= ~FTS_PHYSICAL;
191 			fts_options |= FTS_LOGICAL;
192 			break;
193 		case 'P':
194 		        fts_options &= ~FTS_COMFOLLOW;
195 			fts_options &= ~FTS_LOGICAL;
196 			fts_options |= FTS_PHYSICAL;
197 			break;
198 		case 'R':
199 			f_recursive = 1;
200 			break;
201 		case 'a':
202 			fts_options |= FTS_SEEDOT;
203 			/* FALLTHROUGH */
204 		case 'A':
205 			f_listdot = 1;
206 			break;
207 		/* The -d option turns off the -R option. */
208 		case 'd':
209 			f_listdir = 1;
210 			f_recursive = 0;
211 			break;
212 		case 'f':
213 			f_nosort = 1;
214 			break;
215 		case 'g':		/* Compatibility with 4.3BSD. */
216 			break;
217 		case 'i':
218 			f_inode = 1;
219 			break;
220 		case 'k':
221 			f_kblocks = 1;
222 			break;
223 		case 'n':
224 			f_numericonly = 1;
225 			break;
226 		case 'o':
227 			f_flags = 1;
228 			break;
229 		case 'q':
230 			f_nonprint = 1;
231 			f_octal = 0;
232 		        f_octal_escape = 0;
233 			break;
234 		case 'r':
235 			f_reversesort = 1;
236 			break;
237 		case 's':
238 			f_size = 1;
239 			break;
240 		case 'T':
241 			f_sectime = 1;
242 			break;
243 		case 't':
244 			f_timesort = 1;
245 			break;
246 		case 'W':
247 			f_whiteout = 1;
248 			break;
249 		case 'b':
250 			f_nonprint = 0;
251 		        f_octal = 0;
252 			f_octal_escape = 1;
253 			break;
254 		default:
255 		case '?':
256 			usage();
257 		}
258 	}
259 	argc -= optind;
260 	argv += optind;
261 
262 	/*
263 	 * If not -F, -i, -l, -s or -t options, don't require stat
264 	 * information.
265 	 */
266 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
267 		fts_options |= FTS_NOSTAT;
268 
269 	/*
270 	 * If not -F, -d or -l options, follow any symbolic links listed on
271 	 * the command line.
272 	 */
273 	if (!f_longform && !f_listdir && !f_type)
274 		fts_options |= FTS_COMFOLLOW;
275 
276 	/*
277 	 * If -W, show whiteout entries
278 	 */
279 #ifdef FTS_WHITEOUT
280 	if (f_whiteout)
281 		fts_options |= FTS_WHITEOUT;
282 #endif
283 
284 	/* If -l or -s, figure out block size. */
285 	if (f_longform || f_size) {
286 		if (f_kblocks)
287 			blocksize = 2;
288 		else {
289 			(void)getbsize(&notused, &blocksize);
290 			blocksize /= 512;
291 		}
292 	}
293 
294 	/* Select a sort function. */
295 	if (f_reversesort) {
296 		if (!f_timesort)
297 			sortfcn = revnamecmp;
298 		else if (f_accesstime)
299 			sortfcn = revacccmp;
300 		else if (f_statustime)
301 			sortfcn = revstatcmp;
302 		else /* Use modification time. */
303 			sortfcn = revmodcmp;
304 	} else {
305 		if (!f_timesort)
306 			sortfcn = namecmp;
307 		else if (f_accesstime)
308 			sortfcn = acccmp;
309 		else if (f_statustime)
310 			sortfcn = statcmp;
311 		else /* Use modification time. */
312 			sortfcn = modcmp;
313 	}
314 
315 	/* Select a print function. */
316 	if (f_singlecol)
317 		printfcn = printscol;
318 	else if (f_longform)
319 		printfcn = printlong;
320 	else
321 		printfcn = printcol;
322 
323 	if (argc)
324 		traverse(argc, argv, fts_options);
325 	else
326 		traverse(1, dotav, fts_options);
327 	exit(rval);
328 }
329 
330 static int output;			/* If anything output. */
331 
332 /*
333  * Traverse() walks the logical directory structure specified by the argv list
334  * in the order specified by the mastercmp() comparison function.  During the
335  * traversal it passes linked lists of structures to display() which represent
336  * a superset (may be exact set) of the files to be displayed.
337  */
338 static void
339 traverse(argc, argv, options)
340 	int argc, options;
341 	char *argv[];
342 {
343 	FTS *ftsp;
344 	FTSENT *p, *chp;
345 	int ch_options;
346 
347 	if ((ftsp =
348 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
349 		err(1, NULL);
350 
351 	display(NULL, fts_children(ftsp, 0));
352 	if (f_listdir)
353 		return;
354 
355 	/*
356 	 * If not recursing down this tree and don't need stat info, just get
357 	 * the names.
358 	 */
359 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
360 
361 	while ((p = fts_read(ftsp)) != NULL)
362 		switch (p->fts_info) {
363 		case FTS_DC:
364 			warnx("%s: directory causes a cycle", p->fts_name);
365 			break;
366 		case FTS_DNR:
367 		case FTS_ERR:
368 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
369 			rval = 1;
370 			break;
371 		case FTS_D:
372 			if (p->fts_level != FTS_ROOTLEVEL &&
373 			    p->fts_name[0] == '.' && !f_listdot)
374 				break;
375 
376 			/*
377 			 * If already output something, put out a newline as
378 			 * a separator.  If multiple arguments, precede each
379 			 * directory with its name.
380 			 */
381 			if (output)
382 				(void)printf("\n%s:\n", p->fts_path);
383 			else if (argc > 1) {
384 				(void)printf("%s:\n", p->fts_path);
385 				output = 1;
386 			}
387 
388 			chp = fts_children(ftsp, ch_options);
389 			display(p, chp);
390 
391 			if (!f_recursive && chp != NULL)
392 				(void)fts_set(ftsp, p, FTS_SKIP);
393 			break;
394 		}
395 	if (errno)
396 		err(1, "fts_read");
397 }
398 
399 /*
400  * Display() takes a linked list of FTSENT structures and passes the list
401  * along with any other necessary information to the print function.  P
402  * points to the parent directory of the display list.
403  */
404 static void
405 display(p, list)
406 	FTSENT *p, *list;
407 {
408 	struct stat *sp;
409 	DISPLAY d;
410 	FTSENT *cur;
411 	NAMES *np;
412 	u_quad_t maxsize;
413 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
414 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
415 	char *initmax;
416 	int entries, needstats;
417 	char *user, *group, *flags;
418 	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
419 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
420 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
421 
422 	/*
423 	 * If list is NULL there are two possibilities: that the parent
424 	 * directory p has no children, or that fts_children() returned an
425 	 * error.  We ignore the error case since it will be replicated
426 	 * on the next call to fts_read() on the post-order visit to the
427 	 * directory p, and will be signaled in traverse().
428 	 */
429 	if (list == NULL)
430 		return;
431 
432 	needstats = f_inode || f_longform || f_size;
433 	flen = 0;
434 	btotal = 0;
435 	initmax = getenv("LS_COLWIDTHS");
436 	/* Fields match -lios order.  New ones should be added at the end. */
437 	if (initmax != NULL && *initmax != '\0') {
438 		char *initmax2, *jinitmax;
439 		int ninitmax;
440 
441 		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
442 		jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
443 		if (jinitmax == NULL)
444 			err(1, NULL);
445 		if (*initmax == ':')
446 			strcpy(initmax2, "0:"), initmax2 += 2;
447 		else
448 			*initmax2++ = *initmax, *initmax2 = '\0';
449 		for (initmax++; *initmax != '\0'; initmax++) {
450 			if (initmax[-1] == ':' && initmax[0] == ':') {
451 				*initmax2++ = '0';
452 				*initmax2++ = initmax[0];
453 				initmax2[1] = '\0';
454 			} else {
455 				*initmax2++ = initmax[0];
456 				initmax2[1] = '\0';
457 			}
458 		}
459 		if (initmax2[-1] == ':') strcpy(initmax2, "0");
460 
461 		ninitmax = sscanf(jinitmax,
462 		    " %lu : %lu : %lu : %i : %i : %i : %qu : %lu ",
463 		    &maxinode, &maxblock, &maxnlink, &maxuser,
464 		    &maxgroup, &maxflags, &maxsize, &maxlen);
465 		f_notabs = 1;
466 		switch (ninitmax) {
467 		 case 0: maxinode = 0;
468 		 case 1: maxblock = 0;
469 		 case 2: maxnlink = 0;
470 		 case 3: maxuser  = 0;
471 		 case 4: maxgroup = 0;
472 		 case 5: maxflags = 0;
473 		 case 6: maxsize  = 0;
474 		 case 7: maxlen   = 0, f_notabs = 0;
475 		}
476 		maxinode = makenines(maxinode);
477 		maxblock = makenines(maxblock);
478 		maxnlink = makenines(maxnlink);
479 		maxsize = makenines(maxsize);
480 	} else if (initmax == NULL || *initmax == '\0')
481 		maxblock = maxinode = maxlen = maxnlink =
482 		    maxuser = maxgroup = maxflags = maxsize = 0;
483 	bcfile = 0;
484 	flags = NULL;
485 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
486 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
487 			warnx("%s: %s",
488 			    cur->fts_name, strerror(cur->fts_errno));
489 			cur->fts_number = NO_PRINT;
490 			rval = 1;
491 			continue;
492 		}
493 
494 		/*
495 		 * P is NULL if list is the argv list, to which different rules
496 		 * apply.
497 		 */
498 		if (p == NULL) {
499 			/* Directories will be displayed later. */
500 			if (cur->fts_info == FTS_D && !f_listdir) {
501 				cur->fts_number = NO_PRINT;
502 				continue;
503 			}
504 		} else {
505 			/* Only display dot file if -a/-A set. */
506 			if (cur->fts_name[0] == '.' && !f_listdot) {
507 				cur->fts_number = NO_PRINT;
508 				continue;
509 			}
510 		}
511 		if (f_nonprint)
512 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
513 		if (cur->fts_namelen > maxlen)
514 			maxlen = cur->fts_namelen;
515 		if (f_octal || f_octal_escape) {
516 		        int t = len_octal(cur->fts_name, cur->fts_namelen);
517 			if (t > maxlen) maxlen = t;
518 		}
519 		if (needstats) {
520 			sp = cur->fts_statp;
521 			if (sp->st_blocks > maxblock)
522 				maxblock = sp->st_blocks;
523 			if (sp->st_ino > maxinode)
524 				maxinode = sp->st_ino;
525 			if (sp->st_nlink > maxnlink)
526 				maxnlink = sp->st_nlink;
527 			if (sp->st_size > maxsize)
528 				maxsize = sp->st_size;
529 
530 			btotal += sp->st_blocks;
531 			if (f_longform) {
532 				if (f_numericonly) {
533 					(void)snprintf(nuser, sizeof(nuser),
534 					    "%u", sp->st_uid);
535 					(void)snprintf(ngroup, sizeof(ngroup),
536 					    "%u", sp->st_gid);
537 					user = nuser;
538 					group = ngroup;
539 				} else {
540 					user = user_from_uid(sp->st_uid, 0);
541 					group = group_from_gid(sp->st_gid, 0);
542 				}
543 				if ((ulen = strlen(user)) > maxuser)
544 					maxuser = ulen;
545 				if ((glen = strlen(group)) > maxgroup)
546 					maxgroup = glen;
547 				if (f_flags) {
548 					flags = getflags(sp->st_flags, "-");
549 					if ((flen = strlen(flags)) > maxflags)
550 						maxflags = flen;
551 				} else
552 					flen = 0;
553 
554 				if ((np = malloc(sizeof(NAMES) +
555 				    ulen + glen + flen + 3)) == NULL)
556 					err(1, NULL);
557 
558 				np->user = &np->data[0];
559 				(void)strcpy(np->user, user);
560 				np->group = &np->data[ulen + 1];
561 				(void)strcpy(np->group, group);
562 
563 				if (S_ISCHR(sp->st_mode) ||
564 				    S_ISBLK(sp->st_mode))
565 					bcfile = 1;
566 
567 				if (f_flags) {
568 					np->flags = &np->data[ulen + glen + 2];
569 				  	(void)strcpy(np->flags, flags);
570 				}
571 				cur->fts_pointer = np;
572 			}
573 		}
574 		++entries;
575 	}
576 
577 	if (!entries)
578 		return;
579 
580 	d.list = list;
581 	d.entries = entries;
582 	d.maxlen = maxlen;
583 	if (needstats) {
584 		d.bcfile = bcfile;
585 		d.btotal = btotal;
586 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
587 		d.s_block = strlen(buf);
588 		d.s_flags = maxflags;
589 		d.s_group = maxgroup;
590 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
591 		d.s_inode = strlen(buf);
592 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
593 		d.s_nlink = strlen(buf);
594 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
595 		d.s_size = strlen(buf);
596 		d.s_user = maxuser;
597 	}
598 
599 	printfcn(&d);
600 	output = 1;
601 
602 	if (f_longform)
603 		for (cur = list; cur; cur = cur->fts_link)
604 			free(cur->fts_pointer);
605 }
606 
607 /*
608  * Ordering for mastercmp:
609  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
610  * as larger than directories.  Within either group, use the sort function.
611  * All other levels use the sort function.  Error entries remain unsorted.
612  */
613 static int
614 mastercmp(a, b)
615 	const FTSENT **a, **b;
616 {
617 	int a_info, b_info;
618 
619 	a_info = (*a)->fts_info;
620 	if (a_info == FTS_ERR)
621 		return (0);
622 	b_info = (*b)->fts_info;
623 	if (b_info == FTS_ERR)
624 		return (0);
625 
626 	if (a_info == FTS_NS || b_info == FTS_NS)
627 		return (namecmp(*a, *b));
628 
629 	if (a_info != b_info &&
630 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
631 		if (a_info == FTS_D)
632 			return (1);
633 		if (b_info == FTS_D)
634 			return (-1);
635 	}
636 	return (sortfcn(*a, *b));
637 }
638 
639 /*
640  * Makenines() returns (10**n)-1.  This is useful for converting a width
641  * into a number that wide in decimal.
642  */
643 static u_quad_t
644 makenines(n)
645 	u_long n;
646 {
647 	u_long i;
648 	u_quad_t reg;
649 
650 	reg = 1;
651 	/* Use a loop instead of pow(), since all values of n are small. */
652 	for (i = 0; i < n; i++)
653 		reg *= 10;
654 	reg--;
655 
656 	return reg;
657 }
658