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