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