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