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