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