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