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