ls.c revision 61289
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  "$FreeBSD: head/bin/ls/ls.c 61289 2000-06-05 19:36:06Z ache $";
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 <limits.h>
61#include <locale.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <unistd.h>
66#ifdef COLORLS
67#include <termcap.h>
68#include <signal.h>
69#endif
70
71#include "ls.h"
72#include "extern.h"
73
74/*
75 * Upward approximation of the maximum number of characters needed to
76 * represent a value of integral type t as a string, excluding the
77 * NUL terminator, with provision for a sign.
78 */
79#define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
80
81char *getflags __P((u_long, char *));
82
83static void	 display __P((FTSENT *, FTSENT *));
84static u_quad_t	 makenines __P((u_long));
85static int	 mastercmp __P((const FTSENT **, const FTSENT **));
86static void	 traverse __P((int, char **, int));
87
88static void (*printfcn) __P((DISPLAY *));
89static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
90
91long blocksize;			/* block size units */
92int termwidth = 80;		/* default terminal width */
93
94/* flags */
95int f_accesstime;		/* use time of last access */
96int f_column;			/* columnated format */
97int f_flags;			/* show flags associated with a file */
98int f_inode;			/* print inode */
99int f_kblocks;			/* print size in kilobytes */
100int f_listdir;			/* list actual directory, not contents */
101int f_listdot;			/* list files beginning with . */
102int f_longform;			/* long listing format */
103int f_nonprint;			/* show unprintables as ? */
104int f_nosort;			/* don't sort output */
105int f_notabs;			/* don't use tab-separated multi-col output */
106int f_numericonly;		/* don't convert uid/gid to name */
107int f_octal;			/* show unprintables as \xxx */
108int f_octal_escape;		/* like f_octal but use C escapes if possible */
109int f_recursive;		/* ls subdirectories also */
110int f_reversesort;		/* reverse whatever sort is used */
111int f_sectime;			/* print the real time for all files */
112int f_singlecol;		/* use single column output */
113int f_size;			/* list size in short listing */
114int f_statustime;		/* use time of last mode change */
115int f_timesort;			/* sort by time vice name */
116int f_type;			/* add type character for non-regular files */
117int f_whiteout;			/* show whiteout entries */
118#ifdef COLORLS
119int f_color;			/* add type in color for non-regular files */
120
121char *ansi_bgcol;		/* ANSI sequence to set background colour */
122char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
123char *ansi_coloff;		/* ANSI sequence to reset colours */
124extern void colorquit __P((int));
125#endif
126
127int rval;
128
129int
130main(argc, argv)
131	int argc;
132	char *argv[];
133{
134	static char dot[] = ".", *dotav[] = { dot, NULL };
135	struct winsize win;
136	int ch, fts_options, notused;
137	char *p;
138
139#ifdef COLORLS
140	char termcapbuf[1024];		/* termcap definition buffer */
141	char tcapbuf[512];		/* capability buffer */
142	char *bp = tcapbuf;
143#endif
144
145	(void) setlocale(LC_ALL, "");
146
147	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
148	if (isatty(STDOUT_FILENO)) {
149		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
150		    !win.ws_col) {
151			if ((p = getenv("COLUMNS")) != NULL)
152				termwidth = atoi(p);
153		}
154		else
155			termwidth = win.ws_col;
156		f_column = f_nonprint = 1;
157	} else {
158		f_singlecol = 1;
159		/* retrieve environment variable, in case of explicit -C */
160		if ((p = getenv("COLUMNS")))
161			termwidth = atoi(p);
162	}
163
164	/* Root is -A automatically. */
165	if (!getuid())
166		f_listdot = 1;
167
168	fts_options = FTS_PHYSICAL;
169	while ((ch = getopt(argc, argv, "1ABCFGHLPRTWabcdfgiklnoqrstu")) != -1) {
170		switch (ch) {
171		/*
172		 * The -1, -C and -l options all override each other so shell
173		 * aliasing works right.
174		 */
175		case '1':
176			f_singlecol = 1;
177			f_column = f_longform = 0;
178			break;
179		case 'B':
180			f_nonprint = 0;
181			f_octal = 1;
182		        f_octal_escape = 0;
183			break;
184		case 'C':
185			f_column = 1;
186			f_longform = f_singlecol = 0;
187			break;
188		case 'l':
189			f_longform = 1;
190			f_column = f_singlecol = 0;
191			break;
192		/* The -c and -u options override each other. */
193		case 'c':
194			f_statustime = 1;
195			f_accesstime = 0;
196			break;
197		case 'u':
198			f_accesstime = 1;
199			f_statustime = 0;
200			break;
201		case 'F':
202			f_type = 1;
203			break;
204		case 'H':
205		        fts_options |= FTS_COMFOLLOW;
206			break;
207		case 'G':
208			if (isatty(STDOUT_FILENO))
209#ifdef COLORLS
210				if (tgetent(termcapbuf, getenv("TERM")) == 1) {
211					ansi_fgcol = tgetstr("AF", &bp);
212					ansi_bgcol = tgetstr("AB", &bp);
213
214					/* To switch colours off use 'op' if
215					 * available, otherwise use 'oc', or
216					 * don't do colours at all. */
217					ansi_coloff = tgetstr("op", &bp);
218					if (!ansi_coloff)
219						ansi_coloff = tgetstr("oc", &bp);
220					if (ansi_fgcol && ansi_bgcol && ansi_coloff)
221						f_color = 1;
222				}
223#else
224				(void)fprintf(stderr, "Color support not compiled in.\n");
225#endif
226			break;
227		case 'L':
228			fts_options &= ~FTS_PHYSICAL;
229			fts_options |= FTS_LOGICAL;
230			break;
231		case 'P':
232		        fts_options &= ~FTS_COMFOLLOW;
233			fts_options &= ~FTS_LOGICAL;
234			fts_options |= FTS_PHYSICAL;
235			break;
236		case 'R':
237			f_recursive = 1;
238			break;
239		case 'a':
240			fts_options |= FTS_SEEDOT;
241			/* FALLTHROUGH */
242		case 'A':
243			f_listdot = 1;
244			break;
245		/* The -d option turns off the -R option. */
246		case 'd':
247			f_listdir = 1;
248			f_recursive = 0;
249			break;
250		case 'f':
251			f_nosort = 1;
252			break;
253		case 'g':		/* Compatibility with 4.3BSD. */
254			break;
255		case 'i':
256			f_inode = 1;
257			break;
258		case 'k':
259			f_kblocks = 1;
260			break;
261		case 'n':
262			f_numericonly = 1;
263			break;
264		case 'o':
265			f_flags = 1;
266			break;
267		case 'q':
268			f_nonprint = 1;
269			f_octal = 0;
270		        f_octal_escape = 0;
271			break;
272		case 'r':
273			f_reversesort = 1;
274			break;
275		case 's':
276			f_size = 1;
277			break;
278		case 'T':
279			f_sectime = 1;
280			break;
281		case 't':
282			f_timesort = 1;
283			break;
284		case 'W':
285			f_whiteout = 1;
286			break;
287		case 'b':
288			f_nonprint = 0;
289		        f_octal = 0;
290			f_octal_escape = 1;
291			break;
292		default:
293		case '?':
294			usage();
295		}
296	}
297	argc -= optind;
298	argv += optind;
299
300#ifdef COLORLS
301	if (f_color) {
302		(void) signal(SIGINT, colorquit);
303		parsecolors(getenv("LSCOLORS"));
304	}
305#endif
306
307	/*
308	 * If not -F, -i, -l, -s or -t options, don't require stat
309	 * information, unless in color mode in which case we do
310	 * need this to determine which colors to display.
311	 */
312	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
313#ifdef COLORLS
314	    && !f_color
315#endif
316	   )
317		fts_options |= FTS_NOSTAT;
318
319	/*
320	 * If not -F, -d or -l options, follow any symbolic links listed on
321	 * the command line.
322	 */
323	if (!f_longform && !f_listdir && !f_type)
324		fts_options |= FTS_COMFOLLOW;
325
326	/*
327	 * If -W, show whiteout entries
328	 */
329#ifdef FTS_WHITEOUT
330	if (f_whiteout)
331		fts_options |= FTS_WHITEOUT;
332#endif
333
334	/* If -l or -s, figure out block size. */
335	if (f_longform || f_size) {
336		if (f_kblocks)
337			blocksize = 2;
338		else {
339			(void)getbsize(&notused, &blocksize);
340			blocksize /= 512;
341		}
342	}
343
344	/* Select a sort function. */
345	if (f_reversesort) {
346		if (!f_timesort)
347			sortfcn = revnamecmp;
348		else if (f_accesstime)
349			sortfcn = revacccmp;
350		else if (f_statustime)
351			sortfcn = revstatcmp;
352		else /* Use modification time. */
353			sortfcn = revmodcmp;
354	} else {
355		if (!f_timesort)
356			sortfcn = namecmp;
357		else if (f_accesstime)
358			sortfcn = acccmp;
359		else if (f_statustime)
360			sortfcn = statcmp;
361		else /* Use modification time. */
362			sortfcn = modcmp;
363	}
364
365	/* Select a print function. */
366	if (f_singlecol)
367		printfcn = printscol;
368	else if (f_longform)
369		printfcn = printlong;
370	else
371		printfcn = printcol;
372
373	if (argc)
374		traverse(argc, argv, fts_options);
375	else
376		traverse(1, dotav, fts_options);
377	exit(rval);
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(argc, argv, options)
390	int argc, options;
391	char *argv[];
392{
393	FTS *ftsp;
394	FTSENT *p, *chp;
395	int ch_options;
396
397	if ((ftsp =
398	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
399		err(1, NULL);
400
401	display(NULL, fts_children(ftsp, 0));
402	if (f_listdir)
403		return;
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 = 1;
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	if (errno)
446		err(1, "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(p, list)
456	FTSENT *p, *list;
457{
458	struct stat *sp;
459	DISPLAY d;
460	FTSENT *cur;
461	NAMES *np;
462	u_quad_t maxsize;
463	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
464	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
465	char *initmax;
466	int entries, needstats;
467	char *user, *group, *flags;
468	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
469	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
470	char nuser[STRBUF_SIZEOF(gid_t) + 1];
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 signaled in traverse().
478	 */
479	if (list == NULL)
480		return;
481
482	needstats = f_inode || f_longform || f_size;
483	flen = 0;
484	btotal = 0;
485	initmax = getenv("LS_COLWIDTHS");
486	/* Fields match -lios order.  New ones should be added at the end. */
487	if (initmax != NULL && *initmax != '\0') {
488		char *initmax2, *jinitmax;
489		int ninitmax;
490
491		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
492		jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
493		if (jinitmax == NULL)
494			err(1, NULL);
495		if (*initmax == ':')
496			strcpy(initmax2, "0:"), initmax2 += 2;
497		else
498			*initmax2++ = *initmax, *initmax2 = '\0';
499		for (initmax++; *initmax != '\0'; initmax++) {
500			if (initmax[-1] == ':' && initmax[0] == ':') {
501				*initmax2++ = '0';
502				*initmax2++ = initmax[0];
503				initmax2[1] = '\0';
504			} else {
505				*initmax2++ = initmax[0];
506				initmax2[1] = '\0';
507			}
508		}
509		if (initmax2[-1] == ':') strcpy(initmax2, "0");
510
511		ninitmax = sscanf(jinitmax,
512		    " %lu : %lu : %lu : %i : %i : %i : %qu : %lu ",
513		    &maxinode, &maxblock, &maxnlink, &maxuser,
514		    &maxgroup, &maxflags, &maxsize, &maxlen);
515		f_notabs = 1;
516		switch (ninitmax) {
517		 case 0: maxinode = 0;
518		 case 1: maxblock = 0;
519		 case 2: maxnlink = 0;
520		 case 3: maxuser  = 0;
521		 case 4: maxgroup = 0;
522		 case 5: maxflags = 0;
523		 case 6: maxsize  = 0;
524		 case 7: maxlen   = 0, f_notabs = 0;
525		}
526		maxinode = makenines(maxinode);
527		maxblock = makenines(maxblock);
528		maxnlink = makenines(maxnlink);
529		maxsize = makenines(maxsize);
530	} else if (initmax == NULL || *initmax == '\0')
531		maxblock = maxinode = maxlen = maxnlink =
532		    maxuser = maxgroup = maxflags = maxsize = 0;
533	bcfile = 0;
534	flags = NULL;
535	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
536		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
537			warnx("%s: %s",
538			    cur->fts_name, strerror(cur->fts_errno));
539			cur->fts_number = NO_PRINT;
540			rval = 1;
541			continue;
542		}
543
544		/*
545		 * P is NULL if list is the argv list, to which different rules
546		 * apply.
547		 */
548		if (p == NULL) {
549			/* Directories will be displayed later. */
550			if (cur->fts_info == FTS_D && !f_listdir) {
551				cur->fts_number = NO_PRINT;
552				continue;
553			}
554		} else {
555			/* Only display dot file if -a/-A set. */
556			if (cur->fts_name[0] == '.' && !f_listdot) {
557				cur->fts_number = NO_PRINT;
558				continue;
559			}
560		}
561		if (f_nonprint)
562			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
563		if (cur->fts_namelen > maxlen)
564			maxlen = cur->fts_namelen;
565		if (f_octal || f_octal_escape) {
566		        int t = len_octal(cur->fts_name, cur->fts_namelen);
567			if (t > maxlen) maxlen = t;
568		}
569		if (needstats) {
570			sp = cur->fts_statp;
571			if (sp->st_blocks > maxblock)
572				maxblock = sp->st_blocks;
573			if (sp->st_ino > maxinode)
574				maxinode = sp->st_ino;
575			if (sp->st_nlink > maxnlink)
576				maxnlink = sp->st_nlink;
577			if (sp->st_size > maxsize)
578				maxsize = sp->st_size;
579
580			btotal += sp->st_blocks;
581			if (f_longform) {
582				if (f_numericonly) {
583					(void)snprintf(nuser, sizeof(nuser),
584					    "%u", sp->st_uid);
585					(void)snprintf(ngroup, sizeof(ngroup),
586					    "%u", sp->st_gid);
587					user = nuser;
588					group = ngroup;
589				} else {
590					user = user_from_uid(sp->st_uid, 0);
591					group = group_from_gid(sp->st_gid, 0);
592				}
593				if ((ulen = strlen(user)) > maxuser)
594					maxuser = ulen;
595				if ((glen = strlen(group)) > maxgroup)
596					maxgroup = glen;
597				if (f_flags) {
598					flags = getflags(sp->st_flags, "-");
599					if ((flen = strlen(flags)) > maxflags)
600						maxflags = flen;
601				} else
602					flen = 0;
603
604				if ((np = malloc(sizeof(NAMES) +
605				    ulen + glen + flen + 3)) == NULL)
606					err(1, NULL);
607
608				np->user = &np->data[0];
609				(void)strcpy(np->user, user);
610				np->group = &np->data[ulen + 1];
611				(void)strcpy(np->group, group);
612
613				if (S_ISCHR(sp->st_mode) ||
614				    S_ISBLK(sp->st_mode))
615					bcfile = 1;
616
617				if (f_flags) {
618					np->flags = &np->data[ulen + glen + 2];
619				  	(void)strcpy(np->flags, flags);
620				}
621				cur->fts_pointer = np;
622			}
623		}
624		++entries;
625	}
626
627	if (!entries)
628		return;
629
630	d.list = list;
631	d.entries = entries;
632	d.maxlen = maxlen;
633	if (needstats) {
634		d.bcfile = bcfile;
635		d.btotal = btotal;
636		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
637		d.s_block = strlen(buf);
638		d.s_flags = maxflags;
639		d.s_group = maxgroup;
640		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
641		d.s_inode = strlen(buf);
642		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
643		d.s_nlink = strlen(buf);
644		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
645		d.s_size = strlen(buf);
646		d.s_user = maxuser;
647	}
648
649	printfcn(&d);
650	output = 1;
651
652	if (f_longform)
653		for (cur = list; cur; cur = cur->fts_link)
654			free(cur->fts_pointer);
655}
656
657/*
658 * Ordering for mastercmp:
659 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
660 * as larger than directories.  Within either group, use the sort function.
661 * All other levels use the sort function.  Error entries remain unsorted.
662 */
663static int
664mastercmp(a, b)
665	const FTSENT **a, **b;
666{
667	int a_info, b_info;
668
669	a_info = (*a)->fts_info;
670	if (a_info == FTS_ERR)
671		return (0);
672	b_info = (*b)->fts_info;
673	if (b_info == FTS_ERR)
674		return (0);
675
676	if (a_info == FTS_NS || b_info == FTS_NS)
677		return (namecmp(*a, *b));
678
679	if (a_info != b_info &&
680	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
681		if (a_info == FTS_D)
682			return (1);
683		if (b_info == FTS_D)
684			return (-1);
685	}
686	return (sortfcn(*a, *b));
687}
688
689/*
690 * Makenines() returns (10**n)-1.  This is useful for converting a width
691 * into a number that wide in decimal.
692 */
693static u_quad_t
694makenines(n)
695	u_long n;
696{
697	u_long i;
698	u_quad_t reg;
699
700	reg = 1;
701	/* Use a loop instead of pow(), since all values of n are small. */
702	for (i = 0; i < n; i++)
703		reg *= 10;
704	reg--;
705
706	return reg;
707}
708