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