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