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