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