ls.c revision 61295
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 61295 2000-06-05 20:38:47Z cracauer $";
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		(void) signal(SIGQUIT, colorquit);
304		parsecolors(getenv("LSCOLORS"));
305	}
306#endif
307
308	/*
309	 * If not -F, -i, -l, -s or -t options, don't require stat
310	 * information, unless in color mode in which case we do
311	 * need this to determine which colors to display.
312	 */
313	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
314#ifdef COLORLS
315	    && !f_color
316#endif
317	   )
318		fts_options |= FTS_NOSTAT;
319
320	/*
321	 * If not -F, -d or -l options, follow any symbolic links listed on
322	 * the command line.
323	 */
324	if (!f_longform && !f_listdir && !f_type)
325		fts_options |= FTS_COMFOLLOW;
326
327	/*
328	 * If -W, show whiteout entries
329	 */
330#ifdef FTS_WHITEOUT
331	if (f_whiteout)
332		fts_options |= FTS_WHITEOUT;
333#endif
334
335	/* If -l or -s, figure out block size. */
336	if (f_longform || f_size) {
337		if (f_kblocks)
338			blocksize = 2;
339		else {
340			(void)getbsize(&notused, &blocksize);
341			blocksize /= 512;
342		}
343	}
344
345	/* Select a sort function. */
346	if (f_reversesort) {
347		if (!f_timesort)
348			sortfcn = revnamecmp;
349		else if (f_accesstime)
350			sortfcn = revacccmp;
351		else if (f_statustime)
352			sortfcn = revstatcmp;
353		else /* Use modification time. */
354			sortfcn = revmodcmp;
355	} else {
356		if (!f_timesort)
357			sortfcn = namecmp;
358		else if (f_accesstime)
359			sortfcn = acccmp;
360		else if (f_statustime)
361			sortfcn = statcmp;
362		else /* Use modification time. */
363			sortfcn = modcmp;
364	}
365
366	/* Select a print function. */
367	if (f_singlecol)
368		printfcn = printscol;
369	else if (f_longform)
370		printfcn = printlong;
371	else
372		printfcn = printcol;
373
374	if (argc)
375		traverse(argc, argv, fts_options);
376	else
377		traverse(1, dotav, fts_options);
378	exit(rval);
379}
380
381static int output;			/* If anything output. */
382
383/*
384 * Traverse() walks the logical directory structure specified by the argv list
385 * in the order specified by the mastercmp() comparison function.  During the
386 * traversal it passes linked lists of structures to display() which represent
387 * a superset (may be exact set) of the files to be displayed.
388 */
389static void
390traverse(argc, argv, options)
391	int argc, options;
392	char *argv[];
393{
394	FTS *ftsp;
395	FTSENT *p, *chp;
396	int ch_options;
397
398	if ((ftsp =
399	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
400		err(1, NULL);
401
402	display(NULL, fts_children(ftsp, 0));
403	if (f_listdir)
404		return;
405
406	/*
407	 * If not recursing down this tree and don't need stat info, just get
408	 * the names.
409	 */
410	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
411
412	while ((p = fts_read(ftsp)) != NULL)
413		switch (p->fts_info) {
414		case FTS_DC:
415			warnx("%s: directory causes a cycle", p->fts_name);
416			break;
417		case FTS_DNR:
418		case FTS_ERR:
419			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
420			rval = 1;
421			break;
422		case FTS_D:
423			if (p->fts_level != FTS_ROOTLEVEL &&
424			    p->fts_name[0] == '.' && !f_listdot)
425				break;
426
427			/*
428			 * If already output something, put out a newline as
429			 * a separator.  If multiple arguments, precede each
430			 * directory with its name.
431			 */
432			if (output)
433				(void)printf("\n%s:\n", p->fts_path);
434			else if (argc > 1) {
435				(void)printf("%s:\n", p->fts_path);
436				output = 1;
437			}
438
439			chp = fts_children(ftsp, ch_options);
440			display(p, chp);
441
442			if (!f_recursive && chp != NULL)
443				(void)fts_set(ftsp, p, FTS_SKIP);
444			break;
445		}
446	if (errno)
447		err(1, "fts_read");
448}
449
450/*
451 * Display() takes a linked list of FTSENT structures and passes the list
452 * along with any other necessary information to the print function.  P
453 * points to the parent directory of the display list.
454 */
455static void
456display(p, list)
457	FTSENT *p, *list;
458{
459	struct stat *sp;
460	DISPLAY d;
461	FTSENT *cur;
462	NAMES *np;
463	u_quad_t maxsize;
464	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
465	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
466	char *initmax;
467	int entries, needstats;
468	char *user, *group, *flags;
469	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
470	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
471	char nuser[STRBUF_SIZEOF(gid_t) + 1];
472
473	/*
474	 * If list is NULL there are two possibilities: that the parent
475	 * directory p has no children, or that fts_children() returned an
476	 * error.  We ignore the error case since it will be replicated
477	 * on the next call to fts_read() on the post-order visit to the
478	 * directory p, and will be signaled in traverse().
479	 */
480	if (list == NULL)
481		return;
482
483	needstats = f_inode || f_longform || f_size;
484	flen = 0;
485	btotal = 0;
486	initmax = getenv("LS_COLWIDTHS");
487	/* Fields match -lios order.  New ones should be added at the end. */
488	if (initmax != NULL && *initmax != '\0') {
489		char *initmax2, *jinitmax;
490		int ninitmax;
491
492		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
493		jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
494		if (jinitmax == NULL)
495			err(1, NULL);
496		if (*initmax == ':')
497			strcpy(initmax2, "0:"), initmax2 += 2;
498		else
499			*initmax2++ = *initmax, *initmax2 = '\0';
500		for (initmax++; *initmax != '\0'; initmax++) {
501			if (initmax[-1] == ':' && initmax[0] == ':') {
502				*initmax2++ = '0';
503				*initmax2++ = initmax[0];
504				initmax2[1] = '\0';
505			} else {
506				*initmax2++ = initmax[0];
507				initmax2[1] = '\0';
508			}
509		}
510		if (initmax2[-1] == ':') strcpy(initmax2, "0");
511
512		ninitmax = sscanf(jinitmax,
513		    " %lu : %lu : %lu : %i : %i : %i : %qu : %lu ",
514		    &maxinode, &maxblock, &maxnlink, &maxuser,
515		    &maxgroup, &maxflags, &maxsize, &maxlen);
516		f_notabs = 1;
517		switch (ninitmax) {
518		 case 0: maxinode = 0;
519		 case 1: maxblock = 0;
520		 case 2: maxnlink = 0;
521		 case 3: maxuser  = 0;
522		 case 4: maxgroup = 0;
523		 case 5: maxflags = 0;
524		 case 6: maxsize  = 0;
525		 case 7: maxlen   = 0, f_notabs = 0;
526		}
527		maxinode = makenines(maxinode);
528		maxblock = makenines(maxblock);
529		maxnlink = makenines(maxnlink);
530		maxsize = makenines(maxsize);
531	} else if (initmax == NULL || *initmax == '\0')
532		maxblock = maxinode = maxlen = maxnlink =
533		    maxuser = maxgroup = maxflags = maxsize = 0;
534	bcfile = 0;
535	flags = NULL;
536	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
537		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
538			warnx("%s: %s",
539			    cur->fts_name, strerror(cur->fts_errno));
540			cur->fts_number = NO_PRINT;
541			rval = 1;
542			continue;
543		}
544
545		/*
546		 * P is NULL if list is the argv list, to which different rules
547		 * apply.
548		 */
549		if (p == NULL) {
550			/* Directories will be displayed later. */
551			if (cur->fts_info == FTS_D && !f_listdir) {
552				cur->fts_number = NO_PRINT;
553				continue;
554			}
555		} else {
556			/* Only display dot file if -a/-A set. */
557			if (cur->fts_name[0] == '.' && !f_listdot) {
558				cur->fts_number = NO_PRINT;
559				continue;
560			}
561		}
562		if (f_nonprint)
563			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
564		if (cur->fts_namelen > maxlen)
565			maxlen = cur->fts_namelen;
566		if (f_octal || f_octal_escape) {
567		        int t = len_octal(cur->fts_name, cur->fts_namelen);
568			if (t > maxlen) maxlen = t;
569		}
570		if (needstats) {
571			sp = cur->fts_statp;
572			if (sp->st_blocks > maxblock)
573				maxblock = sp->st_blocks;
574			if (sp->st_ino > maxinode)
575				maxinode = sp->st_ino;
576			if (sp->st_nlink > maxnlink)
577				maxnlink = sp->st_nlink;
578			if (sp->st_size > maxsize)
579				maxsize = sp->st_size;
580
581			btotal += sp->st_blocks;
582			if (f_longform) {
583				if (f_numericonly) {
584					(void)snprintf(nuser, sizeof(nuser),
585					    "%u", sp->st_uid);
586					(void)snprintf(ngroup, sizeof(ngroup),
587					    "%u", sp->st_gid);
588					user = nuser;
589					group = ngroup;
590				} else {
591					user = user_from_uid(sp->st_uid, 0);
592					group = group_from_gid(sp->st_gid, 0);
593				}
594				if ((ulen = strlen(user)) > maxuser)
595					maxuser = ulen;
596				if ((glen = strlen(group)) > maxgroup)
597					maxgroup = glen;
598				if (f_flags) {
599					flags = getflags(sp->st_flags, "-");
600					if ((flen = strlen(flags)) > maxflags)
601						maxflags = flen;
602				} else
603					flen = 0;
604
605				if ((np = malloc(sizeof(NAMES) +
606				    ulen + glen + flen + 3)) == NULL)
607					err(1, NULL);
608
609				np->user = &np->data[0];
610				(void)strcpy(np->user, user);
611				np->group = &np->data[ulen + 1];
612				(void)strcpy(np->group, group);
613
614				if (S_ISCHR(sp->st_mode) ||
615				    S_ISBLK(sp->st_mode))
616					bcfile = 1;
617
618				if (f_flags) {
619					np->flags = &np->data[ulen + glen + 2];
620				  	(void)strcpy(np->flags, flags);
621				}
622				cur->fts_pointer = np;
623			}
624		}
625		++entries;
626	}
627
628	if (!entries)
629		return;
630
631	d.list = list;
632	d.entries = entries;
633	d.maxlen = maxlen;
634	if (needstats) {
635		d.bcfile = bcfile;
636		d.btotal = btotal;
637		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
638		d.s_block = strlen(buf);
639		d.s_flags = maxflags;
640		d.s_group = maxgroup;
641		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
642		d.s_inode = strlen(buf);
643		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
644		d.s_nlink = strlen(buf);
645		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
646		d.s_size = strlen(buf);
647		d.s_user = maxuser;
648	}
649
650	printfcn(&d);
651	output = 1;
652
653	if (f_longform)
654		for (cur = list; cur; cur = cur->fts_link)
655			free(cur->fts_pointer);
656}
657
658/*
659 * Ordering for mastercmp:
660 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
661 * as larger than directories.  Within either group, use the sort function.
662 * All other levels use the sort function.  Error entries remain unsorted.
663 */
664static int
665mastercmp(a, b)
666	const FTSENT **a, **b;
667{
668	int a_info, b_info;
669
670	a_info = (*a)->fts_info;
671	if (a_info == FTS_ERR)
672		return (0);
673	b_info = (*b)->fts_info;
674	if (b_info == FTS_ERR)
675		return (0);
676
677	if (a_info == FTS_NS || b_info == FTS_NS)
678		return (namecmp(*a, *b));
679
680	if (a_info != b_info &&
681	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
682		if (a_info == FTS_D)
683			return (1);
684		if (b_info == FTS_D)
685			return (-1);
686	}
687	return (sortfcn(*a, *b));
688}
689
690/*
691 * Makenines() returns (10**n)-1.  This is useful for converting a width
692 * into a number that wide in decimal.
693 */
694static u_quad_t
695makenines(n)
696	u_long n;
697{
698	u_long i;
699	u_quad_t reg;
700
701	reg = 1;
702	/* Use a loop instead of pow(), since all values of n are small. */
703	for (i = 0; i < n; i++)
704		reg *= 10;
705	reg--;
706
707	return reg;
708}
709