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