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