ls.c revision 1.16.4.1
1/*	$NetBSD: ls.c,v 1.16.4.1 1996/12/10 05:41:44 mycroft 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#ifndef lint
40static char copyright[] =
41"@(#) 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
49static char rcsid[] = "$NetBSD: ls.c,v 1.16.4.1 1996/12/10 05:41:44 mycroft 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 <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65
66#include "ls.h"
67#include "extern.h"
68
69char	*group_from_gid __P((u_int, int));
70char	*user_from_uid __P((u_int, int));
71
72static void	 display __P((FTSENT *, FTSENT *));
73static int	 mastercmp __P((const FTSENT **, const FTSENT **));
74static void	 traverse __P((int, char **, int));
75
76static void (*printfcn) __P((DISPLAY *));
77static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
78
79#define	BY_NAME 0
80#define	BY_SIZE 1
81#define	BY_TIME	2
82
83long blocksize;			/* block size units */
84int termwidth = 80;		/* default terminal width */
85int sortkey = BY_NAME;
86
87/* flags */
88int f_accesstime;		/* use time of last access */
89int f_column;			/* columnated format */
90int f_flags;			/* show flags associated with a file */
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_newline;			/* if precede with newline */
96int f_nonprint;			/* show unprintables as ? */
97int f_nosort;			/* don't sort output */
98int f_recursive;		/* ls subdirectories also */
99int f_reversesort;		/* reverse whatever sort is used */
100int f_sectime;			/* print the real time for all files */
101int f_singlecol;		/* use single column output */
102int f_size;			/* list size in short listing */
103int f_statustime;		/* use time of last mode change */
104int f_dirname;			/* if precede with directory name */
105int f_type;			/* add type character for non-regular files */
106int f_whiteout;			/* show whiteout entries */
107
108int
109main(argc, argv)
110	int argc;
111	char *argv[];
112{
113	static char dot[] = ".", *dotav[] = { dot, NULL };
114	struct winsize win;
115	int ch, fts_options, notused;
116	int kflag = 0;
117	char *p;
118
119	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
120	if (isatty(STDOUT_FILENO)) {
121		if ((p = getenv("COLUMNS")) != NULL)
122			termwidth = atoi(p);
123		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
124		    win.ws_col > 0)
125			termwidth = win.ws_col;
126		f_column = f_nonprint = 1;
127	} else
128		f_singlecol = 1;
129
130	/* Root is -A automatically. */
131	if (!getuid())
132		f_listdot = 1;
133
134	fts_options = FTS_PHYSICAL;
135	while ((ch = getopt(argc, argv, "1ACFLRSTWacdfgikloqrstu")) != -1) {
136		switch (ch) {
137		/*
138		 * The -1, -C and -l options all override each other so shell
139		 * aliasing works right.
140		 */
141		case '1':
142			f_singlecol = 1;
143			f_column = f_longform = 0;
144			break;
145		case 'C':
146			f_column = 1;
147			f_longform = f_singlecol = 0;
148			break;
149		case 'l':
150			f_longform = 1;
151			f_column = f_singlecol = 0;
152			break;
153		/* The -c and -u options override each other. */
154		case 'c':
155			f_statustime = 1;
156			f_accesstime = 0;
157			break;
158		case 'u':
159			f_accesstime = 1;
160			f_statustime = 0;
161			break;
162		case 'F':
163			f_type = 1;
164			break;
165		case 'L':
166			fts_options &= ~FTS_PHYSICAL;
167			fts_options |= FTS_LOGICAL;
168			break;
169		case 'R':
170			f_recursive = 1;
171			break;
172		case 'a':
173			fts_options |= FTS_SEEDOT;
174			/* FALLTHROUGH */
175		case 'A':
176			f_listdot = 1;
177			break;
178		/* The -d option turns off the -R option. */
179		case 'd':
180			f_listdir = 1;
181			f_recursive = 0;
182			break;
183		case 'f':
184			f_nosort = 1;
185			break;
186		case 'g':		/* Compatibility with 4.3BSD. */
187			break;
188		case 'i':
189			f_inode = 1;
190			break;
191		case 'k':
192			blocksize = 1024;
193			kflag = 1;
194			break;
195		case 'o':
196			f_flags = 1;
197			break;
198		case 'q':
199			f_nonprint = 1;
200			break;
201		case 'r':
202			f_reversesort = 1;
203			break;
204		case 'S':
205			sortkey = BY_SIZE;
206			break;
207		case 's':
208			f_size = 1;
209			break;
210		case 'T':
211			f_sectime = 1;
212			break;
213		case 't':
214			sortkey = BY_TIME;
215			break;
216		case 'W':
217			f_whiteout = 1;
218			break;
219		default:
220		case '?':
221			usage();
222		}
223	}
224	argc -= optind;
225	argv += optind;
226
227	/*
228	 * If not -F, -i, -l, -S, -s or -t options, don't require stat
229	 * information.
230	 */
231	if (!f_inode && !f_longform && !f_size && !f_type &&
232	    sortkey == BY_NAME)
233		fts_options |= FTS_NOSTAT;
234
235	/*
236	 * If not -F, -d or -l options, follow any symbolic links listed on
237	 * the command line.
238	 */
239	if (!f_longform && !f_listdir && !f_type)
240		fts_options |= FTS_COMFOLLOW;
241
242	/*
243	 * If -W, show whiteout entries
244	 */
245#ifdef FTS_WHITEOUT
246	if (f_whiteout)
247		fts_options |= FTS_WHITEOUT;
248#endif
249
250	/* If -l or -s, figure out block size. */
251	if (f_longform || f_size) {
252		if (!kflag)
253			(void)getbsize(&notused, &blocksize);
254		blocksize /= 512;
255	}
256
257	/* Select a sort function. */
258	if (f_reversesort) {
259		switch (sortkey) {
260		case BY_NAME:
261			sortfcn = revnamecmp;
262			break;
263		case BY_SIZE:
264			sortfcn = revsizecmp;
265			break;
266		case BY_TIME:
267			if (f_accesstime)
268				sortfcn = revacccmp;
269			else if (f_statustime)
270				sortfcn = revstatcmp;
271			else /* Use modification time. */
272				sortfcn = revmodcmp;
273			break;
274		}
275	} else {
276		switch (sortkey) {
277		case BY_NAME:
278			sortfcn = namecmp;
279			break;
280		case BY_SIZE:
281			sortfcn = sizecmp;
282			break;
283		case BY_TIME:
284			if (f_accesstime)
285				sortfcn = acccmp;
286			else if (f_statustime)
287				sortfcn = statcmp;
288			else /* Use modification time. */
289				sortfcn = modcmp;
290			break;
291		}
292	}
293
294	/* Select a print function. */
295	if (f_singlecol)
296		printfcn = printscol;
297	else if (f_longform)
298		printfcn = printlong;
299	else
300		printfcn = printcol;
301
302	if (argc)
303		traverse(argc, argv, fts_options);
304	else
305		traverse(1, dotav, fts_options);
306	exit(0);
307}
308
309static int output;			/* If anything output. */
310
311/*
312 * Traverse() walks the logical directory structure specified by the argv list
313 * in the order specified by the mastercmp() comparison function.  During the
314 * traversal it passes linked lists of structures to display() which represent
315 * a superset (may be exact set) of the files to be displayed.
316 */
317static void
318traverse(argc, argv, options)
319	int argc, options;
320	char *argv[];
321{
322	FTS *ftsp;
323	FTSENT *p, *chp;
324	int ch_options;
325
326	if ((ftsp =
327	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
328		err(1, NULL);
329
330	display(NULL, fts_children(ftsp, 0));
331	if (f_listdir)
332		return;
333
334	/*
335	 * If not recursing down this tree and don't need stat info, just get
336	 * the names.
337	 */
338	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
339
340	while ((p = fts_read(ftsp)) != NULL)
341		switch (p->fts_info) {
342		case FTS_DC:
343			warnx("%s: directory causes a cycle", p->fts_name);
344			break;
345		case FTS_DNR:
346		case FTS_ERR:
347			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
348			break;
349		case FTS_D:
350			if (p->fts_level != FTS_ROOTLEVEL &&
351			    p->fts_name[0] == '.' && !f_listdot)
352				break;
353
354			/*
355			 * If already output something, put out a newline as
356			 * a separator.  If multiple arguments, precede each
357			 * directory with its name.
358			 */
359			if (output)
360				(void)printf("\n%s:\n", p->fts_path);
361			else if (argc > 1) {
362				(void)printf("%s:\n", p->fts_path);
363				output = 1;
364			}
365
366			chp = fts_children(ftsp, ch_options);
367			display(p, chp);
368
369			if (!f_recursive && chp != NULL)
370				(void)fts_set(ftsp, p, FTS_SKIP);
371			break;
372		}
373	if (errno)
374		err(1, "fts_read");
375}
376
377/*
378 * Display() takes a linked list of FTSENT structures and passes the list
379 * along with any other necessary information to the print function.  P
380 * points to the parent directory of the display list.
381 */
382static void
383display(p, list)
384	FTSENT *p, *list;
385{
386	struct stat *sp;
387	DISPLAY d;
388	FTSENT *cur;
389	NAMES *np;
390	u_quad_t maxsize;
391	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
392	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
393	int entries, needstats;
394	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
395
396	/*
397	 * If list is NULL there are two possibilities: that the parent
398	 * directory p has no children, or that fts_children() returned an
399	 * error.  We ignore the error case since it will be replicated
400	 * on the next call to fts_read() on the post-order visit to the
401	 * directory p, and will be signalled in traverse().
402	 */
403	if (list == NULL)
404		return;
405
406	needstats = f_inode || f_longform || f_size;
407	flen = 0;
408	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
409	bcfile = 0;
410	maxuser = maxgroup = maxflags = 0;
411	maxsize = 0;
412	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
413		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
414			warnx("%s: %s",
415			    cur->fts_name, strerror(cur->fts_errno));
416			cur->fts_number = NO_PRINT;
417			continue;
418		}
419
420		/*
421		 * P is NULL if list is the argv list, to which different rules
422		 * apply.
423		 */
424		if (p == NULL) {
425			/* Directories will be displayed later. */
426			if (cur->fts_info == FTS_D && !f_listdir) {
427				cur->fts_number = NO_PRINT;
428				continue;
429			}
430		} else {
431			/* Only display dot file if -a/-A set. */
432			if (cur->fts_name[0] == '.' && !f_listdot) {
433				cur->fts_number = NO_PRINT;
434				continue;
435			}
436		}
437		if (f_nonprint)
438			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
439		if (cur->fts_namelen > maxlen)
440			maxlen = cur->fts_namelen;
441		if (needstats) {
442			sp = cur->fts_statp;
443			if (sp->st_blocks > maxblock)
444				maxblock = sp->st_blocks;
445			if (sp->st_ino > maxinode)
446				maxinode = sp->st_ino;
447			if (sp->st_nlink > maxnlink)
448				maxnlink = sp->st_nlink;
449			if (sp->st_size > maxsize)
450				maxsize = sp->st_size;
451
452			btotal += sp->st_blocks;
453			if (f_longform) {
454				user = user_from_uid(sp->st_uid, 0);
455				if ((ulen = strlen(user)) > maxuser)
456					maxuser = ulen;
457				group = group_from_gid(sp->st_gid, 0);
458				if ((glen = strlen(group)) > maxgroup)
459					maxgroup = glen;
460				if (f_flags) {
461					flags =
462					    flags_to_string(sp->st_flags, "-");
463					if ((flen = strlen(flags)) > maxflags)
464						maxflags = flen;
465				} else
466					flen = 0;
467
468				if ((np = malloc(sizeof(NAMES) +
469				    ulen + glen + flen + 3)) == NULL)
470					err(1, NULL);
471
472				np->user = &np->data[0];
473				(void)strcpy(np->user, user);
474				np->group = &np->data[ulen + 1];
475				(void)strcpy(np->group, group);
476
477				if (S_ISCHR(sp->st_mode) ||
478				    S_ISBLK(sp->st_mode))
479					bcfile = 1;
480
481				if (f_flags) {
482					np->flags = &np->data[ulen + glen + 2];
483				  	(void)strcpy(np->flags, flags);
484				}
485				cur->fts_pointer = np;
486			}
487		}
488		++entries;
489	}
490
491	if (!entries)
492		return;
493
494	d.list = list;
495	d.entries = entries;
496	d.maxlen = maxlen;
497	if (needstats) {
498		d.bcfile = bcfile;
499		d.btotal = btotal;
500		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
501		d.s_block = strlen(buf);
502		d.s_flags = maxflags;
503		d.s_group = maxgroup;
504		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
505		d.s_inode = strlen(buf);
506		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
507		d.s_nlink = strlen(buf);
508		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
509		d.s_size = strlen(buf);
510		d.s_user = maxuser;
511	}
512
513	printfcn(&d);
514	output = 1;
515
516	if (f_longform)
517		for (cur = list; cur; cur = cur->fts_link)
518			free(cur->fts_pointer);
519}
520
521/*
522 * Ordering for mastercmp:
523 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
524 * as larger than directories.  Within either group, use the sort function.
525 * All other levels use the sort function.  Error entries remain unsorted.
526 */
527static int
528mastercmp(a, b)
529	const FTSENT **a, **b;
530{
531	int a_info, b_info;
532
533	a_info = (*a)->fts_info;
534	if (a_info == FTS_ERR)
535		return (0);
536	b_info = (*b)->fts_info;
537	if (b_info == FTS_ERR)
538		return (0);
539
540	if (a_info == FTS_NS || b_info == FTS_NS)
541		if (b_info != FTS_NS)
542			return (1);
543		else if (a_info != FTS_NS)
544			return (-1);
545		else
546			return (namecmp(*a, *b));
547
548	if (a_info == b_info)
549		return (sortfcn(*a, *b));
550
551	if ((*a)->fts_level == FTS_ROOTLEVEL)
552		if (a_info == FTS_D)
553			return (1);
554		else if (b_info == FTS_D)
555			return (-1);
556		else
557			return (sortfcn(*a, *b));
558	else
559		return (sortfcn(*a, *b));
560}
561