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