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