ls.c revision 1.59
1/*	$NetBSD: ls.c,v 1.59 2006/03/22 16:20:34 christos Exp $	*/
2
3/*
4 * Copyright (c) 1989, 1993, 1994
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Michael Fischbein.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include <sys/cdefs.h>
36#ifndef lint
37__COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
38	The Regents of the University of California.  All rights reserved.\n");
39#endif /* not lint */
40
41#ifndef lint
42#if 0
43static char sccsid[] = "@(#)ls.c	8.7 (Berkeley) 8/5/94";
44#else
45__RCSID("$NetBSD: ls.c,v 1.59 2006/03/22 16:20:34 christos Exp $");
46#endif
47#endif /* not lint */
48
49#include <sys/types.h>
50#include <sys/stat.h>
51#include <sys/ioctl.h>
52
53#include <dirent.h>
54#include <err.h>
55#include <errno.h>
56#include <fts.h>
57#include <locale.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <unistd.h>
62#include <termios.h>
63#include <pwd.h>
64#include <grp.h>
65
66#include "ls.h"
67#include "extern.h"
68
69static void	 display(FTSENT *, FTSENT *);
70static int	 mastercmp(const FTSENT **, const FTSENT **);
71static void	 traverse(int, char **, int);
72
73static void (*printfcn)(DISPLAY *);
74static int (*sortfcn)(const FTSENT *, const FTSENT *);
75
76#define	BY_NAME 0
77#define	BY_SIZE 1
78#define	BY_TIME	2
79
80long blocksize;			/* block size units */
81int termwidth = 80;		/* default terminal width */
82int sortkey = BY_NAME;
83int rval = EXIT_SUCCESS;	/* exit value - set if error encountered */
84
85/* flags */
86int f_accesstime;		/* use time of last access */
87int f_column;			/* columnated format */
88int f_columnacross;		/* columnated format, sorted across */
89int f_flags;			/* show flags associated with a file */
90int f_grouponly;		/* long listing without owner */
91int f_humanize;			/* humanize the size field */
92int f_inode;			/* print inode */
93int f_listdir;			/* list actual directory, not contents */
94int f_listdot;			/* list files beginning with . */
95int f_longform;			/* long listing format */
96int f_nonprint;			/* show unprintables as ? */
97int f_nosort;			/* don't sort output */
98int f_numericonly;		/* don't convert uid/gid to name */
99int f_octal;			/* print octal escapes for nongraphic characters */
100int f_octal_escape;		/* like f_octal but use C escapes if possible */
101int f_recursive;		/* ls subdirectories also */
102int f_reversesort;		/* reverse whatever sort is used */
103int f_sectime;			/* print the real time for all files */
104int f_singlecol;		/* use single column output */
105int f_size;			/* list size in short listing */
106int f_statustime;		/* use time of last mode change */
107int f_stream;			/* stream format */
108int f_type;			/* add type character for non-regular files */
109int f_typedir;			/* add type character for directories */
110int f_whiteout;			/* show whiteout entries */
111
112int
113ls_main(int argc, char *argv[])
114{
115	static char dot[] = ".", *dotav[] = { dot, NULL };
116	struct winsize win;
117	int ch, fts_options;
118	int kflag = 0;
119	const char *p;
120
121	setprogname(argv[0]);
122	setlocale(LC_ALL, "");
123
124	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
125	if (isatty(STDOUT_FILENO)) {
126		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
127		    win.ws_col > 0)
128			termwidth = win.ws_col;
129		f_column = f_nonprint = 1;
130	} else
131		f_singlecol = 1;
132
133	/* Root is -A automatically. */
134	if (!getuid())
135		f_listdot = 1;
136
137	fts_options = FTS_PHYSICAL;
138	while ((ch = getopt(argc, argv, "1ABCFLRSTWabcdfghiklmnopqrstuwx")) != -1) {
139		switch (ch) {
140		/*
141		 * The -1, -C, -l, -m and -x options all override each other so
142		 * shell aliasing works correctly.
143		 */
144		case '1':
145			f_singlecol = 1;
146			f_column = f_columnacross = f_longform = f_stream = 0;
147			break;
148		case 'C':
149			f_column = 1;
150			f_columnacross = f_longform = f_singlecol = f_stream =
151			    0;
152			break;
153		case 'g':
154			if (f_grouponly != -1)
155				f_grouponly = 1;
156			f_longform = 1;
157			f_column = f_columnacross = f_singlecol = f_stream = 0;
158			break;
159		case 'l':
160			f_longform = 1;
161			f_column = f_columnacross = f_singlecol = f_stream = 0;
162			/* Never let -g take precedence over -l. */
163			f_grouponly = -1;
164			break;
165		case 'm':
166			f_stream = 1;
167			f_column = f_columnacross = f_longform = f_singlecol =
168			    0;
169			break;
170		case 'x':
171			f_columnacross = 1;
172			f_column = f_longform = f_singlecol = f_stream = 0;
173			break;
174		/* The -c and -u options override each other. */
175		case 'c':
176			f_statustime = 1;
177			f_accesstime = 0;
178			break;
179		case 'u':
180			f_accesstime = 1;
181			f_statustime = 0;
182			break;
183		case 'F':
184			f_type = 1;
185			break;
186		case 'L':
187			fts_options &= ~FTS_PHYSICAL;
188			fts_options |= FTS_LOGICAL;
189			break;
190		case 'R':
191			f_recursive = 1;
192			break;
193		case 'a':
194			fts_options |= FTS_SEEDOT;
195			/* FALLTHROUGH */
196		case 'A':
197			f_listdot = 1;
198			break;
199		/* The -B option turns off the -b, -q and -w options. */
200		case 'B':
201			f_nonprint = 0;
202			f_octal = 1;
203			f_octal_escape = 0;
204			break;
205		/* The -b option turns off the -B, -q and -w options. */
206		case 'b':
207			f_nonprint = 0;
208			f_octal = 0;
209			f_octal_escape = 1;
210			break;
211		/* The -d option turns off the -R option. */
212		case 'd':
213			f_listdir = 1;
214			f_recursive = 0;
215			break;
216		case 'f':
217			f_nosort = 1;
218			break;
219		case 'i':
220			f_inode = 1;
221			break;
222		case 'k':
223			blocksize = 1024;
224			kflag = 1;
225			break;
226		/* The -h option forces all sizes to be measured in bytes. */
227		case 'h':
228			f_humanize = 1;
229			break;
230		case 'n':
231			f_numericonly = 1;
232			break;
233		case 'o':
234			f_flags = 1;
235			break;
236		case 'p':
237			f_typedir = 1;
238			break;
239		/* The -q option turns off the -B, -b and -w options. */
240		case 'q':
241			f_nonprint = 1;
242			f_octal = 0;
243			f_octal_escape = 0;
244			break;
245		case 'r':
246			f_reversesort = 1;
247			break;
248		case 'S':
249			sortkey = BY_SIZE;
250			break;
251		case 's':
252			f_size = 1;
253			break;
254		case 'T':
255			f_sectime = 1;
256			break;
257		case 't':
258			sortkey = BY_TIME;
259			break;
260		case 'W':
261			f_whiteout = 1;
262			break;
263		/* The -w option turns off the -B, -b and -q options. */
264		case 'w':
265			f_nonprint = 0;
266			f_octal = 0;
267			f_octal_escape = 0;
268			break;
269		default:
270		case '?':
271			usage();
272		}
273	}
274	argc -= optind;
275	argv += optind;
276
277	if (f_column || f_columnacross || f_stream) {
278		if ((p = getenv("COLUMNS")) != NULL)
279			termwidth = atoi(p);
280	}
281
282	/*
283	 * If both -g and -l options, let -l take precedence.
284	 */
285	if (f_grouponly == -1)
286		f_grouponly = 0;
287
288	/*
289	 * If not -F, -i, -l, -p, -S, -s or -t options, don't require stat
290	 * information.
291	 */
292	if (!f_inode && !f_longform && !f_size && !f_type && !f_typedir &&
293	    sortkey == BY_NAME)
294		fts_options |= FTS_NOSTAT;
295
296	/*
297	 * If not -F, -d or -l options, follow any symbolic links listed on
298	 * the command line.
299	 */
300	if (!f_longform && !f_listdir && !f_type)
301		fts_options |= FTS_COMFOLLOW;
302
303	/*
304	 * If -W, show whiteout entries
305	 */
306#ifdef FTS_WHITEOUT
307	if (f_whiteout)
308		fts_options |= FTS_WHITEOUT;
309#endif
310
311	/* If -l or -s, figure out block size. */
312	if (f_inode || f_longform || f_size) {
313		if (!kflag)
314			(void)getbsize(NULL, &blocksize);
315		blocksize /= 512;
316	}
317
318	/* Select a sort function. */
319	if (f_reversesort) {
320		switch (sortkey) {
321		case BY_NAME:
322			sortfcn = revnamecmp;
323			break;
324		case BY_SIZE:
325			sortfcn = revsizecmp;
326			break;
327		case BY_TIME:
328			if (f_accesstime)
329				sortfcn = revacccmp;
330			else if (f_statustime)
331				sortfcn = revstatcmp;
332			else /* Use modification time. */
333				sortfcn = revmodcmp;
334			break;
335		}
336	} else {
337		switch (sortkey) {
338		case BY_NAME:
339			sortfcn = namecmp;
340			break;
341		case BY_SIZE:
342			sortfcn = sizecmp;
343			break;
344		case BY_TIME:
345			if (f_accesstime)
346				sortfcn = acccmp;
347			else if (f_statustime)
348				sortfcn = statcmp;
349			else /* Use modification time. */
350				sortfcn = modcmp;
351			break;
352		}
353	}
354
355	/* Select a print function. */
356	if (f_singlecol)
357		printfcn = printscol;
358	else if (f_columnacross)
359		printfcn = printacol;
360	else if (f_longform)
361		printfcn = printlong;
362	else if (f_stream)
363		printfcn = printstream;
364	else
365		printfcn = printcol;
366
367	if (argc)
368		traverse(argc, argv, fts_options);
369	else
370		traverse(1, dotav, fts_options);
371	exit(rval);
372	/* NOTREACHED */
373}
374
375static int output;			/* If anything output. */
376
377/*
378 * Traverse() walks the logical directory structure specified by the argv list
379 * in the order specified by the mastercmp() comparison function.  During the
380 * traversal it passes linked lists of structures to display() which represent
381 * a superset (may be exact set) of the files to be displayed.
382 */
383static void
384traverse(int argc, char *argv[], int options)
385{
386	FTS *ftsp;
387	FTSENT *p, *chp;
388	int ch_options, error;
389
390	if ((ftsp =
391	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
392		err(EXIT_FAILURE, NULL);
393
394	display(NULL, fts_children(ftsp, 0));
395	if (f_listdir) {
396		fts_close(ftsp);
397		return;
398	}
399
400	/*
401	 * If not recursing down this tree and don't need stat info, just get
402	 * the names.
403	 */
404	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
405
406	while ((p = fts_read(ftsp)) != NULL)
407		switch (p->fts_info) {
408		case FTS_DC:
409			warnx("%s: directory causes a cycle", p->fts_name);
410			break;
411		case FTS_DNR:
412		case FTS_ERR:
413			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
414			rval = EXIT_FAILURE;
415			break;
416		case FTS_D:
417			if (p->fts_level != FTS_ROOTLEVEL &&
418			    p->fts_name[0] == '.' && !f_listdot)
419				break;
420
421			/*
422			 * If already output something, put out a newline as
423			 * a separator.  If multiple arguments, precede each
424			 * directory with its name.
425			 */
426			if (output)
427				(void)printf("\n%s:\n", p->fts_path);
428			else if (argc > 1) {
429				(void)printf("%s:\n", p->fts_path);
430				output = 1;
431			}
432
433			chp = fts_children(ftsp, ch_options);
434			display(p, chp);
435
436			if (!f_recursive && chp != NULL)
437				(void)fts_set(ftsp, p, FTS_SKIP);
438			break;
439		}
440	error = errno;
441	fts_close(ftsp);
442	errno = error;
443	if (errno)
444		err(EXIT_FAILURE, "fts_read");
445}
446
447/*
448 * Display() takes a linked list of FTSENT structures and passes the list
449 * along with any other necessary information to the print function.  P
450 * points to the parent directory of the display list.
451 */
452static void
453display(FTSENT *p, FTSENT *list)
454{
455	struct stat *sp;
456	DISPLAY d;
457	FTSENT *cur;
458	NAMES *np;
459	u_int64_t btotal, stotal, maxblock, maxsize;
460	int maxinode, maxnlink, maxmajor, maxminor;
461	int bcfile, entries, flen, glen, ulen, maxflags, maxgroup, maxlen;
462	int maxuser, needstats;
463	const char *user, *group;
464	char buf[21];		/* 64 bits == 20 digits, +1 for NUL */
465	char nuser[12], ngroup[12];
466	char *flags = NULL;
467
468#ifdef __GNUC__
469	/* This outrageous construct just to shut up a GCC warning. */
470	(void) &maxsize;
471#endif
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 signalled in traverse().
479	 */
480	if (list == NULL)
481		return;
482
483	needstats = f_inode || f_longform || f_size;
484	flen = 0;
485	maxinode = maxnlink = 0;
486	bcfile = 0;
487	maxuser = maxgroup = maxflags = maxlen = 0;
488	btotal = stotal = maxblock = maxsize = 0;
489	maxmajor = maxminor = 0;
490	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
491		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
492			warnx("%s: %s",
493			    cur->fts_name, strerror(cur->fts_errno));
494			cur->fts_number = NO_PRINT;
495			rval = EXIT_FAILURE;
496			continue;
497		}
498
499		/*
500		 * P is NULL if list is the argv list, to which different rules
501		 * apply.
502		 */
503		if (p == NULL) {
504			/* Directories will be displayed later. */
505			if (cur->fts_info == FTS_D && !f_listdir) {
506				cur->fts_number = NO_PRINT;
507				continue;
508			}
509		} else {
510			/* Only display dot file if -a/-A set. */
511			if (cur->fts_name[0] == '.' && !f_listdot) {
512				cur->fts_number = NO_PRINT;
513				continue;
514			}
515		}
516		if (cur->fts_namelen > maxlen)
517			maxlen = cur->fts_namelen;
518		if (needstats) {
519			sp = cur->fts_statp;
520			if (sp->st_blocks > maxblock)
521				maxblock = sp->st_blocks;
522			if (sp->st_ino > maxinode)
523				maxinode = sp->st_ino;
524			if (sp->st_nlink > maxnlink)
525				maxnlink = sp->st_nlink;
526			if (sp->st_size > maxsize)
527				maxsize = sp->st_size;
528			if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode)) {
529				bcfile = 1;
530				if (major(sp->st_rdev) > maxmajor)
531					maxmajor = major(sp->st_rdev);
532				if (minor(sp->st_rdev) > maxminor)
533					maxminor = minor(sp->st_rdev);
534			}
535
536			btotal += sp->st_blocks;
537			stotal += sp->st_size;
538			if (f_longform) {
539				if (f_numericonly ||
540				    (user = user_from_uid(sp->st_uid, 0)) ==
541				    NULL) {
542					(void)snprintf(nuser, sizeof(nuser),
543					    "%u", sp->st_uid);
544					user = nuser;
545				}
546				if (f_numericonly ||
547				    (group = group_from_gid(sp->st_gid, 0)) ==
548				    NULL) {
549					(void)snprintf(ngroup, sizeof(ngroup),
550					    "%u", sp->st_gid);
551					group = ngroup;
552				}
553				if ((ulen = strlen(user)) > maxuser)
554					maxuser = ulen;
555				if ((glen = strlen(group)) > maxgroup)
556					maxgroup = glen;
557				if (f_flags) {
558					flags =
559					    flags_to_string(sp->st_flags, "-");
560					if ((flen = strlen(flags)) > maxflags)
561						maxflags = flen;
562				} else
563					flen = 0;
564
565				if ((np = malloc(sizeof(NAMES) +
566				    ulen + glen + flen + 3)) == NULL)
567					err(EXIT_FAILURE, NULL);
568
569				np->user = &np->data[0];
570				(void)strcpy(np->user, user);
571				np->group = &np->data[ulen + 1];
572				(void)strcpy(np->group, group);
573
574				if (f_flags) {
575					np->flags = &np->data[ulen + glen + 2];
576				  	(void)strcpy(np->flags, flags);
577				}
578				cur->fts_pointer = np;
579			}
580		}
581		++entries;
582	}
583
584	if (!entries)
585		return;
586
587	d.list = list;
588	d.entries = entries;
589	d.maxlen = maxlen;
590	if (needstats) {
591		d.btotal = btotal;
592		d.stotal = stotal;
593		if (f_humanize) {
594			d.s_block = 4; /* min buf length for humanize_number */
595		} else {
596			(void)snprintf(buf, sizeof(buf), "%llu",
597			    (long long)howmany(maxblock, blocksize));
598			d.s_block = strlen(buf);
599		}
600		d.s_flags = maxflags;
601		d.s_group = maxgroup;
602		(void)snprintf(buf, sizeof(buf), "%u", maxinode);
603		d.s_inode = strlen(buf);
604		(void)snprintf(buf, sizeof(buf), "%u", maxnlink);
605		d.s_nlink = strlen(buf);
606		if (f_humanize) {
607			d.s_size = 4; /* min buf length for humanize_number */
608		} else {
609			(void)snprintf(buf, sizeof(buf), "%llu",
610			    (long long)maxsize);
611			d.s_size = strlen(buf);
612		}
613		d.s_user = maxuser;
614		if (bcfile) {
615			(void)snprintf(buf, sizeof(buf), "%u", maxmajor);
616			d.s_major = strlen(buf);
617			(void)snprintf(buf, sizeof(buf), "%u", maxminor);
618			d.s_minor = strlen(buf);
619			if (d.s_major + d.s_minor + 2 > d.s_size)
620				d.s_size = d.s_major + d.s_minor + 2;
621			else if (d.s_size - d.s_minor - 2 > d.s_major)
622				d.s_major = d.s_size - d.s_minor - 2;
623		} else {
624			d.s_major = 0;
625			d.s_minor = 0;
626		}
627	}
628
629	printfcn(&d);
630	output = 1;
631
632	if (f_longform)
633		for (cur = list; cur; cur = cur->fts_link)
634			free(cur->fts_pointer);
635}
636
637/*
638 * Ordering for mastercmp:
639 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
640 * as larger than directories.  Within either group, use the sort function.
641 * All other levels use the sort function.  Error entries remain unsorted.
642 */
643static int
644mastercmp(const FTSENT **a, const FTSENT **b)
645{
646	int a_info, b_info;
647
648	a_info = (*a)->fts_info;
649	if (a_info == FTS_ERR)
650		return (0);
651	b_info = (*b)->fts_info;
652	if (b_info == FTS_ERR)
653		return (0);
654
655	if (a_info == FTS_NS || b_info == FTS_NS) {
656		if (b_info != FTS_NS)
657			return (1);
658		else if (a_info != FTS_NS)
659			return (-1);
660		else
661			return (namecmp(*a, *b));
662	}
663
664	if (a_info != b_info && !f_listdir &&
665	    (*a)->fts_level == FTS_ROOTLEVEL) {
666		if (a_info == FTS_D)
667			return (1);
668		else if (b_info == FTS_D)
669			return (-1);
670	}
671	return (sortfcn(*a, *b));
672}
673