ls.c revision 1.52
1/*	$NetBSD: ls.c,v 1.52 2003/09/22 02:43:20 jschauma 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.52 2003/09/22 02:43:20 jschauma 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_inode;			/* print inode */
92int f_listdir;			/* list actual directory, not contents */
93int f_listdot;			/* list files beginning with . */
94int f_longform;			/* long listing format */
95int f_nonprint;			/* show unprintables as ? */
96int f_nosort;			/* don't sort output */
97int f_numericonly;		/* don't convert uid/gid to name */
98int f_octal;			/* print octal escapes for nongraphic characters */
99int f_octal_escape;		/* like f_octal but use C escapes if possible */
100int f_recursive;		/* ls subdirectories also */
101int f_reversesort;		/* reverse whatever sort is used */
102int f_sectime;			/* print the real time for all files */
103int f_singlecol;		/* use single column output */
104int f_size;			/* list size in short listing */
105int f_statustime;		/* use time of last mode change */
106int f_stream;			/* stream format */
107int f_type;			/* add type character for non-regular files */
108int f_typedir;			/* add type character for directories */
109int f_whiteout;			/* show whiteout entries */
110
111int
112ls_main(int argc, char *argv[])
113{
114	static char dot[] = ".", *dotav[] = { dot, NULL };
115	struct winsize win;
116	int ch, fts_options;
117	int kflag = 0;
118	const char *p;
119
120	setlocale(LC_ALL, "");
121
122	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
123	if (isatty(STDOUT_FILENO)) {
124		if ((p = getenv("COLUMNS")) != NULL)
125			termwidth = atoi(p);
126		else 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, "1ABCFLRSTWabcdfgiklmnopqrstuwx")) != -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		case 'n':
227			f_numericonly = 1;
228			break;
229		case 'o':
230			f_flags = 1;
231			break;
232		case 'p':
233			f_typedir = 1;
234			break;
235		/* the -q option turns off the -B, -b and -w options. */
236		case 'q':
237			f_nonprint = 1;
238			f_octal = 0;
239			f_octal_escape = 0;
240			break;
241		case 'r':
242			f_reversesort = 1;
243			break;
244		case 'S':
245			sortkey = BY_SIZE;
246			break;
247		case 's':
248			f_size = 1;
249			break;
250		case 'T':
251			f_sectime = 1;
252			break;
253		case 't':
254			sortkey = BY_TIME;
255			break;
256		case 'W':
257			f_whiteout = 1;
258			break;
259		/* the -w option turns off the -B, -b and -q options. */
260		case 'w':
261			f_nonprint = 0;
262			f_octal = 0;
263			f_octal_escape = 0;
264			break;
265		default:
266		case '?':
267			usage();
268		}
269	}
270	argc -= optind;
271	argv += optind;
272
273	/*
274	 * If both -g and -l options, let -l take precedence.
275	 */
276	if (f_grouponly == -1)
277		f_grouponly = 0;
278
279	/*
280	 * If not -F, -i, -l, -p, -S, -s or -t options, don't require stat
281	 * information.
282	 */
283	if (!f_inode && !f_longform && !f_size && !f_type && !f_typedir &&
284	    sortkey == BY_NAME)
285		fts_options |= FTS_NOSTAT;
286
287	/*
288	 * If not -F, -d or -l options, follow any symbolic links listed on
289	 * the command line.
290	 */
291	if (!f_longform && !f_listdir && !f_type)
292		fts_options |= FTS_COMFOLLOW;
293
294	/*
295	 * If -W, show whiteout entries
296	 */
297#ifdef FTS_WHITEOUT
298	if (f_whiteout)
299		fts_options |= FTS_WHITEOUT;
300#endif
301
302	/* If -l or -s, figure out block size. */
303	if (f_inode || f_longform || f_size) {
304		if (!kflag)
305			(void)getbsize(NULL, &blocksize);
306		blocksize /= 512;
307	}
308
309	/* Select a sort function. */
310	if (f_reversesort) {
311		switch (sortkey) {
312		case BY_NAME:
313			sortfcn = revnamecmp;
314			break;
315		case BY_SIZE:
316			sortfcn = revsizecmp;
317			break;
318		case BY_TIME:
319			if (f_accesstime)
320				sortfcn = revacccmp;
321			else if (f_statustime)
322				sortfcn = revstatcmp;
323			else /* Use modification time. */
324				sortfcn = revmodcmp;
325			break;
326		}
327	} else {
328		switch (sortkey) {
329		case BY_NAME:
330			sortfcn = namecmp;
331			break;
332		case BY_SIZE:
333			sortfcn = sizecmp;
334			break;
335		case BY_TIME:
336			if (f_accesstime)
337				sortfcn = acccmp;
338			else if (f_statustime)
339				sortfcn = statcmp;
340			else /* Use modification time. */
341				sortfcn = modcmp;
342			break;
343		}
344	}
345
346	/* Select a print function. */
347	if (f_singlecol)
348		printfcn = printscol;
349	else if (f_columnacross)
350		printfcn = printacol;
351	else if (f_longform)
352		printfcn = printlong;
353	else if (f_stream)
354		printfcn = printstream;
355	else
356		printfcn = printcol;
357
358	if (argc)
359		traverse(argc, argv, fts_options);
360	else
361		traverse(1, dotav, fts_options);
362	exit(rval);
363	/* NOTREACHED */
364}
365
366static int output;			/* If anything output. */
367
368/*
369 * Traverse() walks the logical directory structure specified by the argv list
370 * in the order specified by the mastercmp() comparison function.  During the
371 * traversal it passes linked lists of structures to display() which represent
372 * a superset (may be exact set) of the files to be displayed.
373 */
374static void
375traverse(int argc, char *argv[], int options)
376{
377	FTS *ftsp;
378	FTSENT *p, *chp;
379	int ch_options;
380
381	if ((ftsp =
382	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
383		err(EXIT_FAILURE, NULL);
384
385	display(NULL, fts_children(ftsp, 0));
386	if (f_listdir)
387		return;
388
389	/*
390	 * If not recursing down this tree and don't need stat info, just get
391	 * the names.
392	 */
393	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
394
395	while ((p = fts_read(ftsp)) != NULL)
396		switch (p->fts_info) {
397		case FTS_DC:
398			warnx("%s: directory causes a cycle", p->fts_name);
399			break;
400		case FTS_DNR:
401		case FTS_ERR:
402			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
403			rval = EXIT_FAILURE;
404			break;
405		case FTS_D:
406			if (p->fts_level != FTS_ROOTLEVEL &&
407			    p->fts_name[0] == '.' && !f_listdot)
408				break;
409
410			/*
411			 * If already output something, put out a newline as
412			 * a separator.  If multiple arguments, precede each
413			 * directory with its name.
414			 */
415			if (output)
416				(void)printf("\n%s:\n", p->fts_path);
417			else if (argc > 1) {
418				(void)printf("%s:\n", p->fts_path);
419				output = 1;
420			}
421
422			chp = fts_children(ftsp, ch_options);
423			display(p, chp);
424
425			if (!f_recursive && chp != NULL)
426				(void)fts_set(ftsp, p, FTS_SKIP);
427			break;
428		}
429	if (errno)
430		err(EXIT_FAILURE, "fts_read");
431}
432
433/*
434 * Display() takes a linked list of FTSENT structures and passes the list
435 * along with any other necessary information to the print function.  P
436 * points to the parent directory of the display list.
437 */
438static void
439display(FTSENT *p, FTSENT *list)
440{
441	struct stat *sp;
442	DISPLAY d;
443	FTSENT *cur;
444	NAMES *np;
445	u_int64_t btotal, maxblock, maxsize;
446	int maxinode, maxnlink, maxmajor, maxminor;
447	int bcfile, entries, flen, glen, ulen, maxflags, maxgroup, maxlen;
448	int maxuser, needstats;
449	const char *user, *group;
450	char buf[21];		/* 64 bits == 20 digits, +1 for NUL */
451	char nuser[12], ngroup[12];
452	char *flags = NULL;
453
454#ifdef __GNUC__
455	/* This outrageous construct just to shut up a GCC warning. */
456	(void) &maxsize;
457#endif
458
459	/*
460	 * If list is NULL there are two possibilities: that the parent
461	 * directory p has no children, or that fts_children() returned an
462	 * error.  We ignore the error case since it will be replicated
463	 * on the next call to fts_read() on the post-order visit to the
464	 * directory p, and will be signalled in traverse().
465	 */
466	if (list == NULL)
467		return;
468
469	needstats = f_inode || f_longform || f_size;
470	flen = 0;
471	maxinode = maxnlink = 0;
472	bcfile = 0;
473	maxuser = maxgroup = maxflags = maxlen = 0;
474	btotal = maxblock = maxsize = 0;
475	maxmajor = maxminor = 0;
476	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
477		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
478			warnx("%s: %s",
479			    cur->fts_name, strerror(cur->fts_errno));
480			cur->fts_number = NO_PRINT;
481			rval = EXIT_FAILURE;
482			continue;
483		}
484
485		/*
486		 * P is NULL if list is the argv list, to which different rules
487		 * apply.
488		 */
489		if (p == NULL) {
490			/* Directories will be displayed later. */
491			if (cur->fts_info == FTS_D && !f_listdir) {
492				cur->fts_number = NO_PRINT;
493				continue;
494			}
495		} else {
496			/* Only display dot file if -a/-A set. */
497			if (cur->fts_name[0] == '.' && !f_listdot) {
498				cur->fts_number = NO_PRINT;
499				continue;
500			}
501		}
502		if (cur->fts_namelen > maxlen)
503			maxlen = cur->fts_namelen;
504		if (needstats) {
505			sp = cur->fts_statp;
506			if (sp->st_blocks > maxblock)
507				maxblock = sp->st_blocks;
508			if (sp->st_ino > maxinode)
509				maxinode = sp->st_ino;
510			if (sp->st_nlink > maxnlink)
511				maxnlink = sp->st_nlink;
512			if (sp->st_size > maxsize)
513				maxsize = sp->st_size;
514			if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode)) {
515				bcfile = 1;
516				if (major(sp->st_rdev) > maxmajor)
517					maxmajor = major(sp->st_rdev);
518				if (minor(sp->st_rdev) > maxminor)
519					maxminor = minor(sp->st_rdev);
520			}
521
522			btotal += sp->st_blocks;
523			if (f_longform) {
524				if (f_numericonly ||
525				    (user = user_from_uid(sp->st_uid, 0)) ==
526				    NULL) {
527					(void)snprintf(nuser, sizeof(nuser),
528					    "%u", sp->st_uid);
529					user = nuser;
530				}
531				if (f_numericonly ||
532				    (group = group_from_gid(sp->st_gid, 0)) ==
533				    NULL) {
534					(void)snprintf(ngroup, sizeof(ngroup),
535					    "%u", sp->st_gid);
536					group = ngroup;
537				}
538				if ((ulen = strlen(user)) > maxuser)
539					maxuser = ulen;
540				if ((glen = strlen(group)) > maxgroup)
541					maxgroup = glen;
542				if (f_flags) {
543					flags =
544					    flags_to_string(sp->st_flags, "-");
545					if ((flen = strlen(flags)) > maxflags)
546						maxflags = flen;
547				} else
548					flen = 0;
549
550				if ((np = malloc(sizeof(NAMES) +
551				    ulen + glen + flen + 3)) == NULL)
552					err(EXIT_FAILURE, NULL);
553
554				np->user = &np->data[0];
555				(void)strcpy(np->user, user);
556				np->group = &np->data[ulen + 1];
557				(void)strcpy(np->group, group);
558
559				if (f_flags) {
560					np->flags = &np->data[ulen + glen + 2];
561				  	(void)strcpy(np->flags, flags);
562				}
563				cur->fts_pointer = np;
564			}
565		}
566		++entries;
567	}
568
569	if (!entries)
570		return;
571
572	d.list = list;
573	d.entries = entries;
574	d.maxlen = maxlen;
575	if (needstats) {
576		d.btotal = btotal;
577		(void)snprintf(buf, sizeof(buf), "%llu",
578		    (long long)howmany(maxblock, blocksize));
579		d.s_block = strlen(buf);
580		d.s_flags = maxflags;
581		d.s_group = maxgroup;
582		(void)snprintf(buf, sizeof(buf), "%u", maxinode);
583		d.s_inode = strlen(buf);
584		(void)snprintf(buf, sizeof(buf), "%u", maxnlink);
585		d.s_nlink = strlen(buf);
586		(void)snprintf(buf, sizeof(buf), "%llu", (long long)maxsize);
587		d.s_size = strlen(buf);
588		d.s_user = maxuser;
589		if (bcfile) {
590			(void)snprintf(buf, sizeof(buf), "%u", maxmajor);
591			d.s_major = strlen(buf);
592			(void)snprintf(buf, sizeof(buf), "%u", maxminor);
593			d.s_minor = strlen(buf);
594			if (d.s_major + d.s_minor + 2 > d.s_size)
595				d.s_size = d.s_major + d.s_minor + 2;
596			else if (d.s_size - d.s_minor - 2 > d.s_major)
597				d.s_major = d.s_size - d.s_minor - 2;
598		} else {
599			d.s_major = 0;
600			d.s_minor = 0;
601		}
602	}
603
604	printfcn(&d);
605	output = 1;
606
607	if (f_longform)
608		for (cur = list; cur; cur = cur->fts_link)
609			free(cur->fts_pointer);
610}
611
612/*
613 * Ordering for mastercmp:
614 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
615 * as larger than directories.  Within either group, use the sort function.
616 * All other levels use the sort function.  Error entries remain unsorted.
617 */
618static int
619mastercmp(const FTSENT **a, const FTSENT **b)
620{
621	int a_info, b_info;
622
623	a_info = (*a)->fts_info;
624	if (a_info == FTS_ERR)
625		return (0);
626	b_info = (*b)->fts_info;
627	if (b_info == FTS_ERR)
628		return (0);
629
630	if (a_info == FTS_NS || b_info == FTS_NS) {
631		if (b_info != FTS_NS)
632			return (1);
633		else if (a_info != FTS_NS)
634			return (-1);
635		else
636			return (namecmp(*a, *b));
637	}
638
639	if (a_info != b_info && !f_listdir &&
640	    (*a)->fts_level == FTS_ROOTLEVEL) {
641		if (a_info == FTS_D)
642			return (1);
643		else if (b_info == FTS_D)
644			return (-1);
645	}
646	return (sortfcn(*a, *b));
647}
648