ls.c revision 7165
1/*
2 * Copyright (c) 1989, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Michael Fischbein.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *	$Id: ls.c,v 1.4 1994/12/18 19:00:01 joerg Exp $
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
46static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
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 <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <unistd.h>
61
62#include "ls.h"
63#include "extern.h"
64
65static void	 display __P((FTSENT *, FTSENT *));
66static int	 mastercmp __P((const FTSENT **, const FTSENT **));
67static void	 traverse __P((int, char **, int));
68
69static void (*printfcn) __P((DISPLAY *));
70static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
71
72long blocksize;			/* block size units */
73int termwidth = 80;		/* default terminal width */
74
75/* flags */
76int f_accesstime;		/* use time of last access */
77int f_column;			/* columnated format */
78int f_flags;			/* show flags associated with a file */
79int f_inode;			/* print inode */
80int f_kblocks;			/* print size in kilobytes */
81int f_listdir;			/* list actual directory, not contents */
82int f_listdot;			/* list files beginning with . */
83int f_longform;			/* long listing format */
84int f_newline;			/* if precede with newline */
85int f_nonprint;			/* show unprintables as ? */
86int f_nosort;			/* don't sort output */
87int f_recursive;		/* ls subdirectories also */
88int f_reversesort;		/* reverse whatever sort is used */
89int f_sectime;			/* print the real time for all files */
90int f_singlecol;		/* use single column output */
91int f_size;			/* list size in short listing */
92int f_statustime;		/* use time of last mode change */
93int f_dirname;			/* if precede with directory name */
94int f_timesort;			/* sort by time vice name */
95int f_type;			/* add type character for non-regular files */
96
97int
98main(argc, argv)
99	int argc;
100	char *argv[];
101{
102	static char dot[] = ".", *dotav[] = { dot, NULL };
103	struct winsize win;
104	int ch, fts_options, notused;
105	char *p;
106
107	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
108	if (isatty(STDOUT_FILENO)) {
109		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
110		    !win.ws_col) {
111			if ((p = getenv("COLUMNS")) != NULL)
112				termwidth = atoi(p);
113		}
114		else
115			termwidth = win.ws_col;
116		f_column = f_nonprint = 1;
117	} else {
118		f_singlecol = 1;
119		/* retrieve environment variable, in case of explicit -C */
120		if ((p = getenv("COLUMNS")))
121			termwidth = atoi(p);
122	}
123
124	/* Root is -A automatically. */
125	if (!getuid())
126		f_listdot = 1;
127
128	fts_options = FTS_PHYSICAL;
129	while ((ch = getopt(argc, argv, "1ACFLRTacdfgikloqrstu")) != EOF) {
130		switch (ch) {
131		/*
132		 * The -1, -C and -l options all override each other so shell
133		 * aliasing works right.
134		 */
135		case '1':
136			f_singlecol = 1;
137			f_column = f_longform = 0;
138			break;
139		case 'C':
140			f_column = 1;
141			f_longform = f_singlecol = 0;
142			break;
143		case 'l':
144			f_longform = 1;
145			f_column = f_singlecol = 0;
146			break;
147		/* The -c and -u options override each other. */
148		case 'c':
149			f_statustime = 1;
150			f_accesstime = 0;
151			break;
152		case 'u':
153			f_accesstime = 1;
154			f_statustime = 0;
155			break;
156		case 'F':
157			f_type = 1;
158			break;
159		case 'L':
160			fts_options &= ~FTS_PHYSICAL;
161			fts_options |= FTS_LOGICAL;
162			break;
163		case 'R':
164			f_recursive = 1;
165			break;
166		case 'a':
167			fts_options |= FTS_SEEDOT;
168			/* FALLTHROUGH */
169		case 'A':
170			f_listdot = 1;
171			break;
172		/* The -d option turns off the -R option. */
173		case 'd':
174			f_listdir = 1;
175			f_recursive = 0;
176			break;
177		case 'f':
178			f_nosort = 1;
179			break;
180		case 'g':		/* Compatibility with 4.3BSD. */
181			break;
182		case 'i':
183			f_inode = 1;
184			break;
185		case 'k':
186			f_kblocks = 1;
187			break;
188		case 'o':
189			f_flags = 1;
190			break;
191		case 'q':
192			f_nonprint = 1;
193			break;
194		case 'r':
195			f_reversesort = 1;
196			break;
197		case 's':
198			f_size = 1;
199			break;
200		case 'T':
201			f_sectime = 1;
202			break;
203		case 't':
204			f_timesort = 1;
205			break;
206		default:
207		case '?':
208			usage();
209		}
210	}
211	argc -= optind;
212	argv += optind;
213
214	/*
215	 * If not -F, -i, -l, -s or -t options, don't require stat
216	 * information.
217	 */
218	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
219		fts_options |= FTS_NOSTAT;
220
221	/*
222	 * If not -F, -d or -l options, follow any symbolic links listed on
223	 * the command line.
224	 */
225	if (!f_longform && !f_listdir && !f_type)
226		fts_options |= FTS_COMFOLLOW;
227
228	/* If -l or -s, figure out block size. */
229	if (f_longform || f_size) {
230		(void)getbsize(&notused, &blocksize);
231		    blocksize /= 512;
232		if (f_kblocks)
233		    blocksize *= 2;
234	}
235
236	/* Select a sort function. */
237	if (f_reversesort) {
238		if (!f_timesort)
239			sortfcn = revnamecmp;
240		else if (f_accesstime)
241			sortfcn = revacccmp;
242		else if (f_statustime)
243			sortfcn = revstatcmp;
244		else /* Use modification time. */
245			sortfcn = revmodcmp;
246	} else {
247		if (!f_timesort)
248			sortfcn = namecmp;
249		else if (f_accesstime)
250			sortfcn = acccmp;
251		else if (f_statustime)
252			sortfcn = statcmp;
253		else /* Use modification time. */
254			sortfcn = modcmp;
255	}
256
257	/* Select a print function. */
258	if (f_singlecol)
259		printfcn = printscol;
260	else if (f_longform)
261		printfcn = printlong;
262	else
263		printfcn = printcol;
264
265	if (argc)
266		traverse(argc, argv, fts_options);
267	else
268		traverse(1, dotav, fts_options);
269	exit(0);
270}
271
272static int output;			/* If anything output. */
273
274/*
275 * Traverse() walks the logical directory structure specified by the argv list
276 * in the order specified by the mastercmp() comparison function.  During the
277 * traversal it passes linked lists of structures to display() which represent
278 * a superset (may be exact set) of the files to be displayed.
279 */
280static void
281traverse(argc, argv, options)
282	int argc, options;
283	char *argv[];
284{
285	FTS *ftsp;
286	FTSENT *p, *chp;
287	int ch_options;
288
289	if ((ftsp =
290	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
291		err(1, NULL);
292
293	display(NULL, fts_children(ftsp, 0));
294	if (f_listdir)
295		return;
296
297	/*
298	 * If not recursing down this tree and don't need stat info, just get
299	 * the names.
300	 */
301	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
302
303	while ((p = fts_read(ftsp)) != NULL)
304		switch (p->fts_info) {
305		case FTS_DC:
306			warnx("%s: directory causes a cycle", p->fts_name);
307			break;
308		case FTS_DNR:
309		case FTS_ERR:
310			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
311			break;
312		case FTS_D:
313			if (p->fts_level != FTS_ROOTLEVEL &&
314			    p->fts_name[0] == '.' && !f_listdot)
315				break;
316
317			/*
318			 * If already output something, put out a newline as
319			 * a separator.  If multiple arguments, precede each
320			 * directory with its name.
321			 */
322			if (output)
323				(void)printf("\n%s:\n", p->fts_path);
324			else if (argc > 1) {
325				(void)printf("%s:\n", p->fts_path);
326				output = 1;
327			}
328
329			chp = fts_children(ftsp, ch_options);
330			display(p, chp);
331
332			if (!f_recursive && chp != NULL)
333				(void)fts_set(ftsp, p, FTS_SKIP);
334			break;
335		}
336	if (errno)
337		err(1, "fts_read");
338}
339
340/*
341 * Display() takes a linked list of FTSENT structures and passes the list
342 * along with any other necessary information to the print function.  P
343 * points to the parent directory of the display list.
344 */
345static void
346display(p, list)
347	FTSENT *p, *list;
348{
349	struct stat *sp;
350	DISPLAY d;
351	FTSENT *cur;
352	NAMES *np;
353	u_quad_t maxsize;
354	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
355	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
356	int entries, needstats;
357	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
358
359	/*
360	 * If list is NULL there are two possibilities: that the parent
361	 * directory p has no children, or that fts_children() returned an
362	 * error.  We ignore the error case since it will be replicated
363	 * on the next call to fts_read() on the post-order visit to the
364	 * directory p, and will be signalled in traverse().
365	 */
366	if (list == NULL)
367		return;
368
369	needstats = f_inode || f_longform || f_size;
370	flen = 0;
371	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
372	bcfile = 0;
373	maxuser = maxgroup = maxflags = 0;
374	flags = NULL;
375	maxsize = 0;
376	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
377		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
378			warnx("%s: %s",
379			    cur->fts_name, strerror(cur->fts_errno));
380			cur->fts_number = NO_PRINT;
381			continue;
382		}
383
384		/*
385		 * P is NULL if list is the argv list, to which different rules
386		 * apply.
387		 */
388		if (p == NULL) {
389			/* Directories will be displayed later. */
390			if (cur->fts_info == FTS_D && !f_listdir) {
391				cur->fts_number = NO_PRINT;
392				continue;
393			}
394		} else {
395			/* Only display dot file if -a/-A set. */
396			if (cur->fts_name[0] == '.' && !f_listdot) {
397				cur->fts_number = NO_PRINT;
398				continue;
399			}
400		}
401		if (f_nonprint)
402			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
403		if (cur->fts_namelen > maxlen)
404			maxlen = cur->fts_namelen;
405		if (needstats) {
406			sp = cur->fts_statp;
407			if (sp->st_blocks > maxblock)
408				maxblock = sp->st_blocks;
409			if (sp->st_ino > maxinode)
410				maxinode = sp->st_ino;
411			if (sp->st_nlink > maxnlink)
412				maxnlink = sp->st_nlink;
413			if (sp->st_size > maxsize)
414				maxsize = sp->st_size;
415
416			btotal += sp->st_blocks;
417			if (f_longform) {
418				user = user_from_uid(sp->st_uid, 0);
419				if ((ulen = strlen(user)) > maxuser)
420					maxuser = ulen;
421				group = group_from_gid(sp->st_gid, 0);
422				if ((glen = strlen(group)) > maxgroup)
423					maxgroup = glen;
424				if (f_flags) {
425					flags =
426					    flags_to_string(sp->st_flags, "-");
427					if ((flen = strlen(flags)) > maxflags)
428						maxflags = flen;
429				} else
430					flen = 0;
431
432				if ((np = malloc(sizeof(NAMES) +
433				    ulen + glen + flen + 3)) == NULL)
434					err(1, NULL);
435
436				np->user = &np->data[0];
437				(void)strcpy(np->user, user);
438				np->group = &np->data[ulen + 1];
439				(void)strcpy(np->group, group);
440
441				if (S_ISCHR(sp->st_mode) ||
442				    S_ISBLK(sp->st_mode))
443					bcfile = 1;
444
445				if (f_flags) {
446					np->flags = &np->data[ulen + glen + 2];
447				  	(void)strcpy(np->flags, flags);
448				}
449				cur->fts_pointer = np;
450			}
451		}
452		++entries;
453	}
454
455	if (!entries)
456		return;
457
458	d.list = list;
459	d.entries = entries;
460	d.maxlen = maxlen;
461	if (needstats) {
462		d.bcfile = bcfile;
463		d.btotal = btotal;
464		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
465		d.s_block = strlen(buf);
466		d.s_flags = maxflags;
467		d.s_group = maxgroup;
468		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
469		d.s_inode = strlen(buf);
470		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
471		d.s_nlink = strlen(buf);
472		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
473		d.s_size = strlen(buf);
474		d.s_user = maxuser;
475	}
476
477	printfcn(&d);
478	output = 1;
479
480	if (f_longform)
481		for (cur = list; cur; cur = cur->fts_link)
482			free(cur->fts_pointer);
483}
484
485/*
486 * Ordering for mastercmp:
487 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
488 * as larger than directories.  Within either group, use the sort function.
489 * All other levels use the sort function.  Error entries remain unsorted.
490 */
491static int
492mastercmp(a, b)
493	const FTSENT **a, **b;
494{
495	int a_info, b_info;
496
497	a_info = (*a)->fts_info;
498	if (a_info == FTS_ERR)
499		return (0);
500	b_info = (*b)->fts_info;
501	if (b_info == FTS_ERR)
502		return (0);
503
504	if (a_info == FTS_NS || b_info == FTS_NS)
505		return (namecmp(*a, *b));
506
507	if (a_info == b_info)
508		return (sortfcn(*a, *b));
509
510	if ((*a)->fts_level == FTS_ROOTLEVEL)
511		if (a_info == FTS_D)
512			return (1);
513		else if (b_info == FTS_D)
514			return (-1);
515		else
516			return (sortfcn(*a, *b));
517	else
518		return (sortfcn(*a, *b));
519}
520