ls.c revision 61338
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 61338 2000-06-06 13:02:52Z 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 */
124#endif
125
126int rval;
127
128int
129main(argc, argv)
130	int argc;
131	char *argv[];
132{
133	static char dot[] = ".", *dotav[] = { dot, NULL };
134	struct winsize win;
135	int ch, fts_options, notused;
136	char *p;
137
138#ifdef COLORLS
139	char termcapbuf[1024];		/* termcap definition buffer */
140	char tcapbuf[512];		/* capability buffer */
141	char *bp = tcapbuf;
142#endif
143
144	(void) setlocale(LC_ALL, "");
145
146	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
147	if (isatty(STDOUT_FILENO)) {
148		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
149		    !win.ws_col) {
150			if ((p = getenv("COLUMNS")) != NULL)
151				termwidth = atoi(p);
152		}
153		else
154			termwidth = win.ws_col;
155		f_column = f_nonprint = 1;
156	} else {
157		f_singlecol = 1;
158		/* retrieve environment variable, in case of explicit -C */
159		if ((p = getenv("COLUMNS")))
160			termwidth = atoi(p);
161	}
162
163	/* Root is -A automatically. */
164	if (!getuid())
165		f_listdot = 1;
166
167	fts_options = FTS_PHYSICAL;
168	while ((ch = getopt(argc, argv, "1ABCFGHLPRTWabcdfgiklnoqrstu")) != -1) {
169		switch (ch) {
170		/*
171		 * The -1, -C and -l options all override each other so shell
172		 * aliasing works right.
173		 */
174		case '1':
175			f_singlecol = 1;
176			f_column = f_longform = 0;
177			break;
178		case 'B':
179			f_nonprint = 0;
180			f_octal = 1;
181		        f_octal_escape = 0;
182			break;
183		case 'C':
184			f_column = 1;
185			f_longform = f_singlecol = 0;
186			break;
187		case 'l':
188			f_longform = 1;
189			f_column = f_singlecol = 0;
190			break;
191		/* The -c and -u options override each other. */
192		case 'c':
193			f_statustime = 1;
194			f_accesstime = 0;
195			break;
196		case 'u':
197			f_accesstime = 1;
198			f_statustime = 0;
199			break;
200		case 'F':
201			f_type = 1;
202			break;
203		case 'H':
204		        fts_options |= FTS_COMFOLLOW;
205			break;
206		case 'G':
207			if (isatty(STDOUT_FILENO))
208#ifdef COLORLS
209				if (tgetent(termcapbuf, getenv("TERM")) == 1) {
210					ansi_fgcol = tgetstr("AF", &bp);
211					ansi_bgcol = tgetstr("AB", &bp);
212
213					/* To switch colours off use 'op' if
214					 * available, otherwise use 'oc', or
215					 * don't do colours at all. */
216					ansi_coloff = tgetstr("op", &bp);
217					if (!ansi_coloff)
218						ansi_coloff = tgetstr("oc", &bp);
219					if (ansi_fgcol && ansi_bgcol && ansi_coloff)
220						f_color = 1;
221				}
222#else
223				(void)fprintf(stderr, "Color support not compiled in.\n");
224#endif
225			break;
226		case 'L':
227			fts_options &= ~FTS_PHYSICAL;
228			fts_options |= FTS_LOGICAL;
229			break;
230		case 'P':
231		        fts_options &= ~FTS_COMFOLLOW;
232			fts_options &= ~FTS_LOGICAL;
233			fts_options |= FTS_PHYSICAL;
234			break;
235		case 'R':
236			f_recursive = 1;
237			break;
238		case 'a':
239			fts_options |= FTS_SEEDOT;
240			/* FALLTHROUGH */
241		case 'A':
242			f_listdot = 1;
243			break;
244		/* The -d option turns off the -R option. */
245		case 'd':
246			f_listdir = 1;
247			f_recursive = 0;
248			break;
249		case 'f':
250			f_nosort = 1;
251			break;
252		case 'g':		/* Compatibility with 4.3BSD. */
253			break;
254		case 'i':
255			f_inode = 1;
256			break;
257		case 'k':
258			f_kblocks = 1;
259			break;
260		case 'n':
261			f_numericonly = 1;
262			break;
263		case 'o':
264			f_flags = 1;
265			break;
266		case 'q':
267			f_nonprint = 1;
268			f_octal = 0;
269		        f_octal_escape = 0;
270			break;
271		case 'r':
272			f_reversesort = 1;
273			break;
274		case 's':
275			f_size = 1;
276			break;
277		case 'T':
278			f_sectime = 1;
279			break;
280		case 't':
281			f_timesort = 1;
282			break;
283		case 'W':
284			f_whiteout = 1;
285			break;
286		case 'b':
287			f_nonprint = 0;
288		        f_octal = 0;
289			f_octal_escape = 1;
290			break;
291		default:
292		case '?':
293			usage();
294		}
295	}
296	argc -= optind;
297	argv += optind;
298
299#ifdef COLORLS
300	if (f_color) {
301		/*
302		 * We can't put tabs and color sequences together:
303		 * column number will be incremented incorrectly
304		 * for "stty oxtabs" mode.
305		 */
306		f_notabs = 1;
307		(void) signal(SIGINT, colorquit);
308		(void) signal(SIGQUIT, colorquit);
309		parsecolors(getenv("LSCOLORS"));
310	}
311#endif
312
313	/*
314	 * If not -F, -i, -l, -s or -t options, don't require stat
315	 * information, unless in color mode in which case we do
316	 * need this to determine which colors to display.
317	 */
318	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
319#ifdef COLORLS
320	    && !f_color
321#endif
322	   )
323		fts_options |= FTS_NOSTAT;
324
325	/*
326	 * If not -F, -d or -l options, follow any symbolic links listed on
327	 * the command line.
328	 */
329	if (!f_longform && !f_listdir && !f_type)
330		fts_options |= FTS_COMFOLLOW;
331
332	/*
333	 * If -W, show whiteout entries
334	 */
335#ifdef FTS_WHITEOUT
336	if (f_whiteout)
337		fts_options |= FTS_WHITEOUT;
338#endif
339
340	/* If -l or -s, figure out block size. */
341	if (f_longform || f_size) {
342		if (f_kblocks)
343			blocksize = 2;
344		else {
345			(void)getbsize(&notused, &blocksize);
346			blocksize /= 512;
347		}
348	}
349
350	/* Select a sort function. */
351	if (f_reversesort) {
352		if (!f_timesort)
353			sortfcn = revnamecmp;
354		else if (f_accesstime)
355			sortfcn = revacccmp;
356		else if (f_statustime)
357			sortfcn = revstatcmp;
358		else /* Use modification time. */
359			sortfcn = revmodcmp;
360	} else {
361		if (!f_timesort)
362			sortfcn = namecmp;
363		else if (f_accesstime)
364			sortfcn = acccmp;
365		else if (f_statustime)
366			sortfcn = statcmp;
367		else /* Use modification time. */
368			sortfcn = modcmp;
369	}
370
371	/* Select a print function. */
372	if (f_singlecol)
373		printfcn = printscol;
374	else if (f_longform)
375		printfcn = printlong;
376	else
377		printfcn = printcol;
378
379	if (argc)
380		traverse(argc, argv, fts_options);
381	else
382		traverse(1, dotav, fts_options);
383	exit(rval);
384}
385
386static int output;			/* If anything output. */
387
388/*
389 * Traverse() walks the logical directory structure specified by the argv list
390 * in the order specified by the mastercmp() comparison function.  During the
391 * traversal it passes linked lists of structures to display() which represent
392 * a superset (may be exact set) of the files to be displayed.
393 */
394static void
395traverse(argc, argv, options)
396	int argc, options;
397	char *argv[];
398{
399	FTS *ftsp;
400	FTSENT *p, *chp;
401	int ch_options;
402
403	if ((ftsp =
404	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
405		err(1, NULL);
406
407	display(NULL, fts_children(ftsp, 0));
408	if (f_listdir)
409		return;
410
411	/*
412	 * If not recursing down this tree and don't need stat info, just get
413	 * the names.
414	 */
415	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
416
417	while ((p = fts_read(ftsp)) != NULL)
418		switch (p->fts_info) {
419		case FTS_DC:
420			warnx("%s: directory causes a cycle", p->fts_name);
421			break;
422		case FTS_DNR:
423		case FTS_ERR:
424			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
425			rval = 1;
426			break;
427		case FTS_D:
428			if (p->fts_level != FTS_ROOTLEVEL &&
429			    p->fts_name[0] == '.' && !f_listdot)
430				break;
431
432			/*
433			 * If already output something, put out a newline as
434			 * a separator.  If multiple arguments, precede each
435			 * directory with its name.
436			 */
437			if (output)
438				(void)printf("\n%s:\n", p->fts_path);
439			else if (argc > 1) {
440				(void)printf("%s:\n", p->fts_path);
441				output = 1;
442			}
443
444			chp = fts_children(ftsp, ch_options);
445			display(p, chp);
446
447			if (!f_recursive && chp != NULL)
448				(void)fts_set(ftsp, p, FTS_SKIP);
449			break;
450		}
451	if (errno)
452		err(1, "fts_read");
453}
454
455/*
456 * Display() takes a linked list of FTSENT structures and passes the list
457 * along with any other necessary information to the print function.  P
458 * points to the parent directory of the display list.
459 */
460static void
461display(p, list)
462	FTSENT *p, *list;
463{
464	struct stat *sp;
465	DISPLAY d;
466	FTSENT *cur;
467	NAMES *np;
468	u_quad_t maxsize;
469	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
470	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
471	char *initmax;
472	int entries, needstats;
473	char *user, *group, *flags;
474	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
475	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
476	char nuser[STRBUF_SIZEOF(gid_t) + 1];
477
478	/*
479	 * If list is NULL there are two possibilities: that the parent
480	 * directory p has no children, or that fts_children() returned an
481	 * error.  We ignore the error case since it will be replicated
482	 * on the next call to fts_read() on the post-order visit to the
483	 * directory p, and will be signaled in traverse().
484	 */
485	if (list == NULL)
486		return;
487
488	needstats = f_inode || f_longform || f_size;
489	flen = 0;
490	btotal = 0;
491	initmax = getenv("LS_COLWIDTHS");
492	/* Fields match -lios order.  New ones should be added at the end. */
493	if (initmax != NULL && *initmax != '\0') {
494		char *initmax2, *jinitmax;
495		int ninitmax;
496
497		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
498		jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
499		if (jinitmax == NULL)
500			err(1, NULL);
501		if (*initmax == ':')
502			strcpy(initmax2, "0:"), initmax2 += 2;
503		else
504			*initmax2++ = *initmax, *initmax2 = '\0';
505		for (initmax++; *initmax != '\0'; initmax++) {
506			if (initmax[-1] == ':' && initmax[0] == ':') {
507				*initmax2++ = '0';
508				*initmax2++ = initmax[0];
509				initmax2[1] = '\0';
510			} else {
511				*initmax2++ = initmax[0];
512				initmax2[1] = '\0';
513			}
514		}
515		if (initmax2[-1] == ':') strcpy(initmax2, "0");
516
517		ninitmax = sscanf(jinitmax,
518		    " %lu : %lu : %lu : %i : %i : %i : %qu : %lu ",
519		    &maxinode, &maxblock, &maxnlink, &maxuser,
520		    &maxgroup, &maxflags, &maxsize, &maxlen);
521		f_notabs = 1;
522		switch (ninitmax) {
523		 case 0: maxinode = 0;
524		 case 1: maxblock = 0;
525		 case 2: maxnlink = 0;
526		 case 3: maxuser  = 0;
527		 case 4: maxgroup = 0;
528		 case 5: maxflags = 0;
529		 case 6: maxsize  = 0;
530		 case 7: maxlen   = 0;
531#ifdef COLORLS
532		 if (!f_color)
533#endif
534			 f_notabs = 0;
535		}
536		maxinode = makenines(maxinode);
537		maxblock = makenines(maxblock);
538		maxnlink = makenines(maxnlink);
539		maxsize = makenines(maxsize);
540	} else if (initmax == NULL || *initmax == '\0')
541		maxblock = maxinode = maxlen = maxnlink =
542		    maxuser = maxgroup = maxflags = maxsize = 0;
543	bcfile = 0;
544	flags = NULL;
545	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
546		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
547			warnx("%s: %s",
548			    cur->fts_name, strerror(cur->fts_errno));
549			cur->fts_number = NO_PRINT;
550			rval = 1;
551			continue;
552		}
553
554		/*
555		 * P is NULL if list is the argv list, to which different rules
556		 * apply.
557		 */
558		if (p == NULL) {
559			/* Directories will be displayed later. */
560			if (cur->fts_info == FTS_D && !f_listdir) {
561				cur->fts_number = NO_PRINT;
562				continue;
563			}
564		} else {
565			/* Only display dot file if -a/-A set. */
566			if (cur->fts_name[0] == '.' && !f_listdot) {
567				cur->fts_number = NO_PRINT;
568				continue;
569			}
570		}
571		if (f_nonprint)
572			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
573		if (cur->fts_namelen > maxlen)
574			maxlen = cur->fts_namelen;
575		if (f_octal || f_octal_escape) {
576		        int t = len_octal(cur->fts_name, cur->fts_namelen);
577			if (t > maxlen) maxlen = t;
578		}
579		if (needstats) {
580			sp = cur->fts_statp;
581			if (sp->st_blocks > maxblock)
582				maxblock = sp->st_blocks;
583			if (sp->st_ino > maxinode)
584				maxinode = sp->st_ino;
585			if (sp->st_nlink > maxnlink)
586				maxnlink = sp->st_nlink;
587			if (sp->st_size > maxsize)
588				maxsize = sp->st_size;
589
590			btotal += sp->st_blocks;
591			if (f_longform) {
592				if (f_numericonly) {
593					(void)snprintf(nuser, sizeof(nuser),
594					    "%u", sp->st_uid);
595					(void)snprintf(ngroup, sizeof(ngroup),
596					    "%u", sp->st_gid);
597					user = nuser;
598					group = ngroup;
599				} else {
600					user = user_from_uid(sp->st_uid, 0);
601					group = group_from_gid(sp->st_gid, 0);
602				}
603				if ((ulen = strlen(user)) > maxuser)
604					maxuser = ulen;
605				if ((glen = strlen(group)) > maxgroup)
606					maxgroup = glen;
607				if (f_flags) {
608					flags = getflags(sp->st_flags, "-");
609					if ((flen = strlen(flags)) > maxflags)
610						maxflags = flen;
611				} else
612					flen = 0;
613
614				if ((np = malloc(sizeof(NAMES) +
615				    ulen + glen + flen + 3)) == NULL)
616					err(1, NULL);
617
618				np->user = &np->data[0];
619				(void)strcpy(np->user, user);
620				np->group = &np->data[ulen + 1];
621				(void)strcpy(np->group, group);
622
623				if (S_ISCHR(sp->st_mode) ||
624				    S_ISBLK(sp->st_mode))
625					bcfile = 1;
626
627				if (f_flags) {
628					np->flags = &np->data[ulen + glen + 2];
629				  	(void)strcpy(np->flags, flags);
630				}
631				cur->fts_pointer = np;
632			}
633		}
634		++entries;
635	}
636
637	if (!entries)
638		return;
639
640	d.list = list;
641	d.entries = entries;
642	d.maxlen = maxlen;
643	if (needstats) {
644		d.bcfile = bcfile;
645		d.btotal = btotal;
646		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
647		d.s_block = strlen(buf);
648		d.s_flags = maxflags;
649		d.s_group = maxgroup;
650		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
651		d.s_inode = strlen(buf);
652		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
653		d.s_nlink = strlen(buf);
654		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
655		d.s_size = strlen(buf);
656		d.s_user = maxuser;
657	}
658
659	printfcn(&d);
660	output = 1;
661
662	if (f_longform)
663		for (cur = list; cur; cur = cur->fts_link)
664			free(cur->fts_pointer);
665}
666
667/*
668 * Ordering for mastercmp:
669 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
670 * as larger than directories.  Within either group, use the sort function.
671 * All other levels use the sort function.  Error entries remain unsorted.
672 */
673static int
674mastercmp(a, b)
675	const FTSENT **a, **b;
676{
677	int a_info, b_info;
678
679	a_info = (*a)->fts_info;
680	if (a_info == FTS_ERR)
681		return (0);
682	b_info = (*b)->fts_info;
683	if (b_info == FTS_ERR)
684		return (0);
685
686	if (a_info == FTS_NS || b_info == FTS_NS)
687		return (namecmp(*a, *b));
688
689	if (a_info != b_info &&
690	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
691		if (a_info == FTS_D)
692			return (1);
693		if (b_info == FTS_D)
694			return (-1);
695	}
696	return (sortfcn(*a, *b));
697}
698
699/*
700 * Makenines() returns (10**n)-1.  This is useful for converting a width
701 * into a number that wide in decimal.
702 */
703static u_quad_t
704makenines(n)
705	u_long n;
706{
707	u_long i;
708	u_quad_t reg;
709
710	reg = 1;
711	/* Use a loop instead of pow(), since all values of n are small. */
712	for (i = 0; i < n; i++)
713		reg *= 10;
714	reg--;
715
716	return reg;
717}
718