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