ls.c revision 49373
1/*
2 * Copyright (c) 1989, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Michael Fischbein.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1989, 1993, 1994\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44#if 0
45static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
46#else
47static const char rcsid[] =
48	"$Id: ls.c,v 1.24 1999/05/08 10:20:30 kris Exp $";
49#endif
50#endif /* not lint */
51
52#include <sys/types.h>
53#include <sys/stat.h>
54#include <sys/ioctl.h>
55
56#include <dirent.h>
57#include <err.h>
58#include <errno.h>
59#include <fts.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <unistd.h>
64#include <locale.h>
65
66#include "ls.h"
67#include "extern.h"
68
69static void	 display __P((FTSENT *, FTSENT *));
70static u_quad_t	 makenines __P((u_long));
71static int	 mastercmp __P((const FTSENT **, const FTSENT **));
72static void	 traverse __P((int, char **, int));
73
74static void (*printfcn) __P((DISPLAY *));
75static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
76
77long blocksize;			/* block size units */
78int termwidth = 80;		/* default terminal width */
79
80/* flags */
81int f_accesstime;		/* use time of last access */
82int f_column;			/* columnated format */
83int f_flags;			/* show flags associated with a file */
84int f_inode;			/* print inode */
85int f_kblocks;			/* print size in kilobytes */
86int f_listdir;			/* list actual directory, not contents */
87int f_listdot;			/* list files beginning with . */
88int f_longform;			/* long listing format */
89int f_nonprint;			/* show unprintables as ? */
90int f_nosort;			/* don't sort output */
91int f_numericonly;		/* don't convert uid/gid to name */
92int f_octal;			/* show unprintables as \xxx */
93int f_octal_escape;		/* like f_octal but use C escapes if possible */
94int f_recursive;		/* ls subdirectories also */
95int f_reversesort;		/* reverse whatever sort is used */
96int f_sectime;			/* print the real time for all files */
97int f_singlecol;		/* use single column output */
98int f_size;			/* list size in short listing */
99int f_statustime;		/* use time of last mode change */
100int f_notabs;			/* don't use tab-separated multi-col output */
101int f_timesort;			/* sort by time vice name */
102int f_type;			/* add type character for non-regular files */
103int f_whiteout;			/* show whiteout entries */
104
105int rval;
106
107int
108main(argc, argv)
109	int argc;
110	char *argv[];
111{
112	static char dot[] = ".", *dotav[] = { dot, NULL };
113	struct winsize win;
114	int ch, fts_options, notused;
115	char *p;
116
117	(void) setlocale(LC_ALL, "");
118
119	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
120	if (isatty(STDOUT_FILENO)) {
121		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
122		    !win.ws_col) {
123			if ((p = getenv("COLUMNS")) != NULL)
124				termwidth = atoi(p);
125		}
126		else
127			termwidth = win.ws_col;
128		f_column = f_nonprint = 1;
129	} else {
130		f_singlecol = 1;
131		/* retrieve environment variable, in case of explicit -C */
132		if ((p = getenv("COLUMNS")))
133			termwidth = atoi(p);
134	}
135
136	/* Root is -A automatically. */
137	if (!getuid())
138		f_listdot = 1;
139
140	fts_options = FTS_PHYSICAL;
141	while ((ch = getopt(argc, argv, "1ABCFHLPRTWabcdfgiklnoqrstu")) != -1) {
142		switch (ch) {
143		/*
144		 * The -1, -C and -l options all override each other so shell
145		 * aliasing works right.
146		 */
147		case '1':
148			f_singlecol = 1;
149			f_column = f_longform = 0;
150			break;
151		case 'B':
152			f_nonprint = 0;
153			f_octal = 1;
154		        f_octal_escape = 0;
155			break;
156		case 'C':
157			f_column = 1;
158			f_longform = f_singlecol = 0;
159			break;
160		case 'l':
161			f_longform = 1;
162			f_column = f_singlecol = 0;
163			break;
164		/* The -c and -u options override each other. */
165		case 'c':
166			f_statustime = 1;
167			f_accesstime = 0;
168			break;
169		case 'u':
170			f_accesstime = 1;
171			f_statustime = 0;
172			break;
173		case 'F':
174			f_type = 1;
175			break;
176		case 'H':
177		        fts_options |= FTS_COMFOLLOW;
178			break;
179		case 'L':
180			fts_options &= ~FTS_PHYSICAL;
181			fts_options |= FTS_LOGICAL;
182			break;
183		case 'P':
184		        fts_options &= ~FTS_COMFOLLOW;
185			fts_options &= ~FTS_LOGICAL;
186			fts_options |= FTS_PHYSICAL;
187			break;
188		case 'R':
189			f_recursive = 1;
190			break;
191		case 'a':
192			fts_options |= FTS_SEEDOT;
193			/* FALLTHROUGH */
194		case 'A':
195			f_listdot = 1;
196			break;
197		/* The -d option turns off the -R option. */
198		case 'd':
199			f_listdir = 1;
200			f_recursive = 0;
201			break;
202		case 'f':
203			f_nosort = 1;
204			break;
205		case 'g':		/* Compatibility with 4.3BSD. */
206			break;
207		case 'i':
208			f_inode = 1;
209			break;
210		case 'k':
211			f_kblocks = 1;
212			break;
213		case 'n':
214			f_numericonly = 1;
215			break;
216		case 'o':
217			f_flags = 1;
218			break;
219		case 'q':
220			f_nonprint = 1;
221			f_octal = 0;
222		        f_octal_escape = 0;
223			break;
224		case 'r':
225			f_reversesort = 1;
226			break;
227		case 's':
228			f_size = 1;
229			break;
230		case 'T':
231			f_sectime = 1;
232			break;
233		case 't':
234			f_timesort = 1;
235			break;
236		case 'W':
237			f_whiteout = 1;
238			break;
239		case 'b':
240			f_nonprint = 0;
241		        f_octal = 0;
242			f_octal_escape = 1;
243			break;
244		default:
245		case '?':
246			usage();
247		}
248	}
249	argc -= optind;
250	argv += optind;
251
252	/*
253	 * If not -F, -i, -l, -s or -t options, don't require stat
254	 * information.
255	 */
256	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
257		fts_options |= FTS_NOSTAT;
258
259	/*
260	 * If not -F, -d or -l options, follow any symbolic links listed on
261	 * the command line.
262	 */
263	if (!f_longform && !f_listdir && !f_type)
264		fts_options |= FTS_COMFOLLOW;
265
266	/*
267	 * If -W, show whiteout entries
268	 */
269#ifdef FTS_WHITEOUT
270	if (f_whiteout)
271		fts_options |= FTS_WHITEOUT;
272#endif
273
274	/* If -l or -s, figure out block size. */
275	if (f_longform || f_size) {
276		if (f_kblocks)
277			blocksize = 2;
278		else {
279			(void)getbsize(&notused, &blocksize);
280			blocksize /= 512;
281		}
282	}
283
284	/* Select a sort function. */
285	if (f_reversesort) {
286		if (!f_timesort)
287			sortfcn = revnamecmp;
288		else if (f_accesstime)
289			sortfcn = revacccmp;
290		else if (f_statustime)
291			sortfcn = revstatcmp;
292		else /* Use modification time. */
293			sortfcn = revmodcmp;
294	} else {
295		if (!f_timesort)
296			sortfcn = namecmp;
297		else if (f_accesstime)
298			sortfcn = acccmp;
299		else if (f_statustime)
300			sortfcn = statcmp;
301		else /* Use modification time. */
302			sortfcn = modcmp;
303	}
304
305	/* Select a print function. */
306	if (f_singlecol)
307		printfcn = printscol;
308	else if (f_longform)
309		printfcn = printlong;
310	else
311		printfcn = printcol;
312
313	if (argc)
314		traverse(argc, argv, fts_options);
315	else
316		traverse(1, dotav, fts_options);
317	exit(rval);
318}
319
320static int output;			/* If anything output. */
321
322/*
323 * Traverse() walks the logical directory structure specified by the argv list
324 * in the order specified by the mastercmp() comparison function.  During the
325 * traversal it passes linked lists of structures to display() which represent
326 * a superset (may be exact set) of the files to be displayed.
327 */
328static void
329traverse(argc, argv, options)
330	int argc, options;
331	char *argv[];
332{
333	FTS *ftsp;
334	FTSENT *p, *chp;
335	int ch_options;
336
337	if ((ftsp =
338	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
339		err(1, NULL);
340
341	display(NULL, fts_children(ftsp, 0));
342	if (f_listdir)
343		return;
344
345	/*
346	 * If not recursing down this tree and don't need stat info, just get
347	 * the names.
348	 */
349	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
350
351	while ((p = fts_read(ftsp)) != NULL)
352		switch (p->fts_info) {
353		case FTS_DC:
354			warnx("%s: directory causes a cycle", p->fts_name);
355			break;
356		case FTS_DNR:
357		case FTS_ERR:
358			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
359			rval = 1;
360			break;
361		case FTS_D:
362			if (p->fts_level != FTS_ROOTLEVEL &&
363			    p->fts_name[0] == '.' && !f_listdot)
364				break;
365
366			/*
367			 * If already output something, put out a newline as
368			 * a separator.  If multiple arguments, precede each
369			 * directory with its name.
370			 */
371			if (output)
372				(void)printf("\n%s:\n", p->fts_path);
373			else if (argc > 1) {
374				(void)printf("%s:\n", p->fts_path);
375				output = 1;
376			}
377
378			chp = fts_children(ftsp, ch_options);
379			display(p, chp);
380
381			if (!f_recursive && chp != NULL)
382				(void)fts_set(ftsp, p, FTS_SKIP);
383			break;
384		}
385	if (errno)
386		err(1, "fts_read");
387}
388
389/*
390 * Display() takes a linked list of FTSENT structures and passes the list
391 * along with any other necessary information to the print function.  P
392 * points to the parent directory of the display list.
393 */
394static void
395display(p, list)
396	FTSENT *p, *list;
397{
398	struct stat *sp;
399	DISPLAY d;
400	FTSENT *cur;
401	NAMES *np;
402	u_quad_t maxsize;
403	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
404	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
405	char *initmax;
406	int entries, needstats;
407	char *user, *group, *flags;
408	char nuser[12], ngroup[12], buf[21];	/* 32 bits == 10 digits */
409
410	/*
411	 * If list is NULL there are two possibilities: that the parent
412	 * directory p has no children, or that fts_children() returned an
413	 * error.  We ignore the error case since it will be replicated
414	 * on the next call to fts_read() on the post-order visit to the
415	 * directory p, and will be signaled in traverse().
416	 */
417	if (list == NULL)
418		return;
419
420	needstats = f_inode || f_longform || f_size;
421	flen = 0;
422	btotal = 0;
423	initmax = getenv("LS_COLWIDTHS");
424	/* Fields match -lios order.  New ones should be added at the end. */
425	if (initmax != NULL && *initmax != '\0') {
426		char *initmax2, *jinitmax;
427		int ninitmax;
428
429		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
430		jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
431		if (jinitmax == NULL)
432			err(1, NULL);
433		if (*initmax == ':')
434			strcpy(initmax2, "0:"), initmax2 += 2;
435		else
436			*initmax2++ = *initmax, *initmax2 = '\0';
437		for (initmax++; *initmax != '\0'; initmax++) {
438			if (initmax[-1] == ':' && initmax[0] == ':') {
439				*initmax2++ = '0';
440				*initmax2++ = initmax[0];
441				initmax2[1] = '\0';
442			} else {
443				*initmax2++ = initmax[0];
444				initmax2[1] = '\0';
445			}
446		}
447		if (initmax2[-1] == ':') strcpy(initmax2, "0");
448
449		ninitmax = sscanf(jinitmax,
450		    " %lu : %lu : %lu : %i : %i : %i : %qu : %lu ",
451		    &maxinode, &maxblock, &maxnlink, &maxuser,
452		    &maxgroup, &maxflags, &maxsize, &maxlen);
453		f_notabs = 1;
454		switch (ninitmax) {
455		 case 0: maxinode = 0;
456		 case 1: maxblock = 0;
457		 case 2: maxnlink = 0;
458		 case 3: maxuser  = 0;
459		 case 4: maxgroup = 0;
460		 case 5: maxflags = 0;
461		 case 6: maxsize  = 0;
462		 case 7: maxlen   = 0, f_notabs = 0;
463		}
464		maxinode = makenines(maxinode);
465		maxblock = makenines(maxblock);
466		maxnlink = makenines(maxnlink);
467		maxsize = makenines(maxsize);
468	} else if (initmax == NULL || *initmax == '\0')
469		maxblock = maxinode = maxlen = maxnlink =
470		    maxuser = maxgroup = maxflags = maxsize = 0;
471	bcfile = 0;
472	flags = NULL;
473	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
474		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
475			warnx("%s: %s",
476			    cur->fts_name, strerror(cur->fts_errno));
477			cur->fts_number = NO_PRINT;
478			rval = 1;
479			continue;
480		}
481
482		/*
483		 * P is NULL if list is the argv list, to which different rules
484		 * apply.
485		 */
486		if (p == NULL) {
487			/* Directories will be displayed later. */
488			if (cur->fts_info == FTS_D && !f_listdir) {
489				cur->fts_number = NO_PRINT;
490				continue;
491			}
492		} else {
493			/* Only display dot file if -a/-A set. */
494			if (cur->fts_name[0] == '.' && !f_listdot) {
495				cur->fts_number = NO_PRINT;
496				continue;
497			}
498		}
499		if (f_nonprint)
500			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
501		if (cur->fts_namelen > maxlen)
502			maxlen = cur->fts_namelen;
503		if (f_octal || f_octal_escape) {
504		        int t = len_octal(cur->fts_name, cur->fts_namelen);
505			if (t > maxlen) maxlen = t;
506		}
507		if (needstats) {
508			sp = cur->fts_statp;
509			if (sp->st_blocks > maxblock)
510				maxblock = sp->st_blocks;
511			if (sp->st_ino > maxinode)
512				maxinode = sp->st_ino;
513			if (sp->st_nlink > maxnlink)
514				maxnlink = sp->st_nlink;
515			if (sp->st_size > maxsize)
516				maxsize = sp->st_size;
517
518			btotal += sp->st_blocks;
519			if (f_longform) {
520				if (f_numericonly) {
521					(void)snprintf(nuser, sizeof(nuser),
522					    "%u", sp->st_uid);
523					(void)snprintf(ngroup, sizeof(ngroup),
524					    "%u", sp->st_gid);
525					user = nuser;
526					group = ngroup;
527				} else {
528					user = user_from_uid(sp->st_uid, 0);
529					group = group_from_gid(sp->st_gid, 0);
530				}
531				if ((ulen = strlen(user)) > maxuser)
532					maxuser = ulen;
533				if ((glen = strlen(group)) > maxgroup)
534					maxgroup = glen;
535				if (f_flags) {
536					flags =
537					    flags_to_string(sp->st_flags, "-");
538					if ((flen = strlen(flags)) > maxflags)
539						maxflags = flen;
540				} else
541					flen = 0;
542
543				if ((np = malloc(sizeof(NAMES) +
544				    ulen + glen + flen + 3)) == NULL)
545					err(1, NULL);
546
547				np->user = &np->data[0];
548				(void)strcpy(np->user, user);
549				np->group = &np->data[ulen + 1];
550				(void)strcpy(np->group, group);
551
552				if (S_ISCHR(sp->st_mode) ||
553				    S_ISBLK(sp->st_mode))
554					bcfile = 1;
555
556				if (f_flags) {
557					np->flags = &np->data[ulen + glen + 2];
558				  	(void)strcpy(np->flags, flags);
559				}
560				cur->fts_pointer = np;
561			}
562		}
563		++entries;
564	}
565
566	if (!entries)
567		return;
568
569	d.list = list;
570	d.entries = entries;
571	d.maxlen = maxlen;
572	if (needstats) {
573		d.bcfile = bcfile;
574		d.btotal = btotal;
575		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
576		d.s_block = strlen(buf);
577		d.s_flags = maxflags;
578		d.s_group = maxgroup;
579		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
580		d.s_inode = strlen(buf);
581		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
582		d.s_nlink = strlen(buf);
583		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
584		d.s_size = strlen(buf);
585		d.s_user = maxuser;
586	}
587
588	printfcn(&d);
589	output = 1;
590
591	if (f_longform)
592		for (cur = list; cur; cur = cur->fts_link)
593			free(cur->fts_pointer);
594}
595
596/*
597 * Ordering for mastercmp:
598 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
599 * as larger than directories.  Within either group, use the sort function.
600 * All other levels use the sort function.  Error entries remain unsorted.
601 */
602static int
603mastercmp(a, b)
604	const FTSENT **a, **b;
605{
606	int a_info, b_info;
607
608	a_info = (*a)->fts_info;
609	if (a_info == FTS_ERR)
610		return (0);
611	b_info = (*b)->fts_info;
612	if (b_info == FTS_ERR)
613		return (0);
614
615	if (a_info == FTS_NS || b_info == FTS_NS)
616		return (namecmp(*a, *b));
617
618	if (a_info != b_info &&
619	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
620		if (a_info == FTS_D)
621			return (1);
622		if (b_info == FTS_D)
623			return (-1);
624	}
625	return (sortfcn(*a, *b));
626}
627
628/*
629 * Makenines() returns (10**n)-1.  This is useful for converting a width
630 * into a number that wide in decimal.
631 */
632static u_quad_t
633makenines(n)
634	u_long n;
635{
636	u_long i;
637	u_quad_t reg;
638
639	reg = 1;
640	/* Use a loop instead of pow(), since all values of n are small. */
641	for (i = 0; i < n; i++)
642		reg *= 10;
643	reg--;
644
645	return reg;
646}
647