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