ls.c revision 202945
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 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34static const char copyright[] =
35"@(#) Copyright (c) 1989, 1993, 1994\n\
36	The Regents of the University of California.  All rights reserved.\n";
37#endif /* not lint */
38
39#if 0
40#ifndef lint
41static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
42#endif /* not lint */
43#endif
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/bin/ls/ls.c 202945 2010-01-24 19:23:07Z jh $");
46
47#include <sys/types.h>
48#include <sys/stat.h>
49#include <sys/ioctl.h>
50#include <sys/mac.h>
51
52#include <dirent.h>
53#include <err.h>
54#include <errno.h>
55#include <fts.h>
56#include <grp.h>
57#include <inttypes.h>
58#include <limits.h>
59#include <locale.h>
60#include <pwd.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65#ifdef COLORLS
66#include <termcap.h>
67#include <signal.h>
68#endif
69
70#include "ls.h"
71#include "extern.h"
72
73/*
74 * Upward approximation of the maximum number of characters needed to
75 * represent a value of integral type t as a string, excluding the
76 * NUL terminator, with provision for a sign.
77 */
78#define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
79
80/*
81 * MAKENINES(n) turns n into (10**n)-1.  This is useful for converting a width
82 * into a number that wide in decimal.
83 * XXX: Overflows are not considered.
84 */
85#define MAKENINES(n)							\
86	do {								\
87		intmax_t i;						\
88									\
89		/* Use a loop as all values of n are small. */		\
90		for (i = 1; n > 0; i *= 10)				\
91			n--;						\
92		n = i - 1;						\
93	} while(0)
94
95static void	 display(const FTSENT *, FTSENT *, int);
96static int	 mastercmp(const FTSENT * const *, const FTSENT * const *);
97static void	 traverse(int, char **, int);
98
99static void (*printfcn)(const DISPLAY *);
100static int (*sortfcn)(const FTSENT *, const FTSENT *);
101
102long blocksize;			/* block size units */
103int termwidth = 80;		/* default terminal width */
104
105/* flags */
106       int f_accesstime;	/* use time of last access */
107       int f_birthtime;		/* use time of birth */
108       int f_flags;		/* show flags associated with a file */
109       int f_humanval;		/* show human-readable file sizes */
110       int f_inode;		/* print inode */
111static int f_kblocks;		/* print size in kilobytes */
112static int f_listdir;		/* list actual directory, not contents */
113static int f_listdot;		/* list files beginning with . */
114static int f_noautodot;		/* do not automatically enable -A for root */
115       int f_longform;		/* long listing format */
116       int f_nonprint;		/* show unprintables as ? */
117static int f_nosort;		/* don't sort output */
118       int f_notabs;		/* don't use tab-separated multi-col output */
119static int f_numericonly;	/* don't convert uid/gid to name */
120       int f_octal;		/* show unprintables as \xxx */
121       int f_octal_escape;	/* like f_octal but use C escapes if possible */
122static int f_recursive;		/* ls subdirectories also */
123static int f_reversesort;	/* reverse whatever sort is used */
124       int f_sectime;		/* print the real time for all files */
125static int f_singlecol;		/* use single column output */
126       int f_size;		/* list size in short listing */
127       int f_slash;		/* similar to f_type, but only for dirs */
128       int f_sortacross;	/* sort across rows, not down columns */
129       int f_statustime;	/* use time of last mode change */
130static int f_stream;		/* stream the output, separate with commas */
131static int f_timesort;		/* sort by time vice name */
132       char *f_timeformat;      /* user-specified time format */
133static int f_sizesort;
134       int f_type;		/* add type character for non-regular files */
135static int f_whiteout;		/* show whiteout entries */
136       int f_label;		/* show MAC label */
137#ifdef COLORLS
138       int f_color;		/* add type in color for non-regular files */
139
140char *ansi_bgcol;		/* ANSI sequence to set background colour */
141char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
142char *ansi_coloff;		/* ANSI sequence to reset colours */
143char *attrs_off;		/* ANSI sequence to turn off attributes */
144char *enter_bold;		/* ANSI sequence to set color to bold mode */
145#endif
146
147static int rval;
148
149int
150main(int argc, char *argv[])
151{
152	static char dot[] = ".", *dotav[] = {dot, NULL};
153	struct winsize win;
154	int ch, fts_options, notused;
155	char *p;
156#ifdef COLORLS
157	char termcapbuf[1024];	/* termcap definition buffer */
158	char tcapbuf[512];	/* capability buffer */
159	char *bp = tcapbuf;
160#endif
161
162	(void)setlocale(LC_ALL, "");
163
164	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
165	if (isatty(STDOUT_FILENO)) {
166		termwidth = 80;
167		if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
168			termwidth = atoi(p);
169		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
170		    win.ws_col > 0)
171			termwidth = win.ws_col;
172		f_nonprint = 1;
173	} else {
174		f_singlecol = 1;
175		/* retrieve environment variable, in case of explicit -C */
176		p = getenv("COLUMNS");
177		if (p)
178			termwidth = atoi(p);
179	}
180
181	fts_options = FTS_PHYSICAL;
182 	while ((ch = getopt(argc, argv,
183	    "1ABCD:FGHILPRSTUWZabcdfghiklmnopqrstuwx")) != -1) {
184		switch (ch) {
185		/*
186		 * The -1, -C, -x and -l options all override each other so
187		 * shell aliasing works right.
188		 */
189		case '1':
190			f_singlecol = 1;
191			f_longform = 0;
192			f_stream = 0;
193			break;
194		case 'B':
195			f_nonprint = 0;
196			f_octal = 1;
197			f_octal_escape = 0;
198			break;
199		case 'C':
200			f_sortacross = f_longform = f_singlecol = 0;
201			break;
202                case 'D':
203                        f_timeformat = optarg;
204                        break;
205		case 'l':
206			f_longform = 1;
207			f_singlecol = 0;
208			f_stream = 0;
209			break;
210		case 'x':
211			f_sortacross = 1;
212			f_longform = 0;
213			f_singlecol = 0;
214			break;
215		/* The -c, -u, and -U options override each other. */
216		case 'c':
217			f_statustime = 1;
218			f_accesstime = 0;
219			f_birthtime = 0;
220			break;
221		case 'u':
222			f_accesstime = 1;
223			f_statustime = 0;
224			f_birthtime = 0;
225			break;
226		case 'U':
227			f_birthtime = 1;
228			f_accesstime = 0;
229			f_statustime = 0;
230			break;
231		case 'F':
232			f_type = 1;
233			f_slash = 0;
234			break;
235		case 'H':
236			fts_options |= FTS_COMFOLLOW;
237			break;
238		case 'G':
239			setenv("CLICOLOR", "", 1);
240			break;
241		case 'L':
242			fts_options &= ~FTS_PHYSICAL;
243			fts_options |= FTS_LOGICAL;
244			break;
245		case 'P':
246			fts_options &= ~FTS_COMFOLLOW;
247			fts_options &= ~FTS_LOGICAL;
248			fts_options |= FTS_PHYSICAL;
249			break;
250		case 'R':
251			f_recursive = 1;
252			break;
253		case 'a':
254			fts_options |= FTS_SEEDOT;
255			/* FALLTHROUGH */
256		case 'A':
257			f_listdot = 1;
258			break;
259		case 'I':
260			f_noautodot = 1;
261			break;
262		/* The -d option turns off the -R option. */
263		case 'd':
264			f_listdir = 1;
265			f_recursive = 0;
266			break;
267		case 'f':
268			f_nosort = 1;
269			break;
270		case 'g':	/* Compatibility with 4.3BSD. */
271			break;
272		case 'h':
273			f_humanval = 1;
274			break;
275		case 'i':
276			f_inode = 1;
277			break;
278		case 'k':
279			f_humanval = 0;
280			f_kblocks = 1;
281			break;
282		case 'm':
283			f_stream = 1;
284			f_singlecol = 0;
285			f_longform = 0;
286			break;
287		case 'n':
288			f_numericonly = 1;
289			break;
290		case 'o':
291			f_flags = 1;
292			break;
293		case 'p':
294			f_slash = 1;
295			f_type = 1;
296			break;
297		case 'q':
298			f_nonprint = 1;
299			f_octal = 0;
300			f_octal_escape = 0;
301			break;
302		case 'r':
303			f_reversesort = 1;
304			break;
305		case 's':
306			f_size = 1;
307			break;
308		case 'T':
309			f_sectime = 1;
310			break;
311		/* The -t and -S options override each other. */
312		case 't':
313			f_timesort = 1;
314			f_sizesort = 0;
315			break;
316		case 'S':
317			f_sizesort = 1;
318			f_timesort = 0;
319			break;
320		case 'W':
321			f_whiteout = 1;
322			break;
323		case 'b':
324			f_nonprint = 0;
325			f_octal = 0;
326			f_octal_escape = 1;
327			break;
328		case 'w':
329			f_nonprint = 0;
330			f_octal = 0;
331			f_octal_escape = 0;
332			break;
333		case 'Z':
334			f_label = 1;
335			break;
336		default:
337		case '?':
338			usage();
339		}
340	}
341	argc -= optind;
342	argv += optind;
343
344	/* Root is -A automatically unless -I. */
345	if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
346		f_listdot = 1;
347
348	/* Enabling of colours is conditional on the environment. */
349	if (getenv("CLICOLOR") &&
350	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
351#ifdef COLORLS
352		if (tgetent(termcapbuf, getenv("TERM")) == 1) {
353			ansi_fgcol = tgetstr("AF", &bp);
354			ansi_bgcol = tgetstr("AB", &bp);
355			attrs_off = tgetstr("me", &bp);
356			enter_bold = tgetstr("md", &bp);
357
358			/* To switch colours off use 'op' if
359			 * available, otherwise use 'oc', or
360			 * don't do colours at all. */
361			ansi_coloff = tgetstr("op", &bp);
362			if (!ansi_coloff)
363				ansi_coloff = tgetstr("oc", &bp);
364			if (ansi_fgcol && ansi_bgcol && ansi_coloff)
365				f_color = 1;
366		}
367#else
368		warnx("color support not compiled in");
369#endif /*COLORLS*/
370
371#ifdef COLORLS
372	if (f_color) {
373		/*
374		 * We can't put tabs and color sequences together:
375		 * column number will be incremented incorrectly
376		 * for "stty oxtabs" mode.
377		 */
378		f_notabs = 1;
379		(void)signal(SIGINT, colorquit);
380		(void)signal(SIGQUIT, colorquit);
381		parsecolors(getenv("LSCOLORS"));
382	}
383#endif
384
385	/*
386	 * If not -F, -i, -l, -s, -S or -t options, don't require stat
387	 * information, unless in color mode in which case we do
388	 * need this to determine which colors to display.
389	 */
390	if (!f_inode && !f_longform && !f_size && !f_timesort &&
391	    !f_sizesort && !f_type
392#ifdef COLORLS
393	    && !f_color
394#endif
395	    )
396		fts_options |= FTS_NOSTAT;
397
398	/*
399	 * If not -F, -d or -l options, follow any symbolic links listed on
400	 * the command line.
401	 */
402	if (!f_longform && !f_listdir && (!f_type || f_slash))
403		fts_options |= FTS_COMFOLLOW;
404
405	/*
406	 * If -W, show whiteout entries
407	 */
408#ifdef FTS_WHITEOUT
409	if (f_whiteout)
410		fts_options |= FTS_WHITEOUT;
411#endif
412
413	/* If -l or -s, figure out block size. */
414	if (f_longform || f_size) {
415		if (f_kblocks)
416			blocksize = 2;
417		else {
418			(void)getbsize(&notused, &blocksize);
419			blocksize /= 512;
420		}
421	}
422	/* Select a sort function. */
423	if (f_reversesort) {
424		if (!f_timesort && !f_sizesort)
425			sortfcn = revnamecmp;
426		else if (f_sizesort)
427			sortfcn = revsizecmp;
428		else if (f_accesstime)
429			sortfcn = revacccmp;
430		else if (f_birthtime)
431			sortfcn = revbirthcmp;
432		else if (f_statustime)
433			sortfcn = revstatcmp;
434		else		/* Use modification time. */
435			sortfcn = revmodcmp;
436	} else {
437		if (!f_timesort && !f_sizesort)
438			sortfcn = namecmp;
439		else if (f_sizesort)
440			sortfcn = sizecmp;
441		else if (f_accesstime)
442			sortfcn = acccmp;
443		else if (f_birthtime)
444			sortfcn = birthcmp;
445		else if (f_statustime)
446			sortfcn = statcmp;
447		else		/* Use modification time. */
448			sortfcn = modcmp;
449	}
450
451	/* Select a print function. */
452	if (f_singlecol)
453		printfcn = printscol;
454	else if (f_longform)
455		printfcn = printlong;
456	else if (f_stream)
457		printfcn = printstream;
458	else
459		printfcn = printcol;
460
461	if (argc)
462		traverse(argc, argv, fts_options);
463	else
464		traverse(1, dotav, fts_options);
465	exit(rval);
466}
467
468static int output;		/* If anything output. */
469
470/*
471 * Traverse() walks the logical directory structure specified by the argv list
472 * in the order specified by the mastercmp() comparison function.  During the
473 * traversal it passes linked lists of structures to display() which represent
474 * a superset (may be exact set) of the files to be displayed.
475 */
476static void
477traverse(int argc, char *argv[], int options)
478{
479	FTS *ftsp;
480	FTSENT *p, *chp;
481	int ch_options;
482
483	if ((ftsp =
484	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
485		err(1, "fts_open");
486
487	/*
488	 * We ignore errors from fts_children here since they will be
489	 * replicated and signalled on the next call to fts_read() below.
490	 */
491	chp = fts_children(ftsp, 0);
492	if (chp != NULL)
493		display(NULL, chp, options);
494	if (f_listdir)
495		return;
496
497	/*
498	 * If not recursing down this tree and don't need stat info, just get
499	 * the names.
500	 */
501	ch_options = !f_recursive && !f_label &&
502	    options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
503
504	while ((p = fts_read(ftsp)) != NULL)
505		switch (p->fts_info) {
506		case FTS_DC:
507			warnx("%s: directory causes a cycle", p->fts_name);
508			break;
509		case FTS_DNR:
510		case FTS_ERR:
511			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
512			rval = 1;
513			break;
514		case FTS_D:
515			if (p->fts_level != FTS_ROOTLEVEL &&
516			    p->fts_name[0] == '.' && !f_listdot)
517				break;
518
519			/*
520			 * If already output something, put out a newline as
521			 * a separator.  If multiple arguments, precede each
522			 * directory with its name.
523			 */
524			if (output) {
525				putchar('\n');
526				(void)printname(p->fts_path);
527				puts(":");
528			} else if (argc > 1) {
529				(void)printname(p->fts_path);
530				puts(":");
531				output = 1;
532			}
533			chp = fts_children(ftsp, ch_options);
534			display(p, chp, options);
535
536			if (!f_recursive && chp != NULL)
537				(void)fts_set(ftsp, p, FTS_SKIP);
538			break;
539		default:
540			break;
541		}
542	if (errno)
543		err(1, "fts_read");
544}
545
546/*
547 * Display() takes a linked list of FTSENT structures and passes the list
548 * along with any other necessary information to the print function.  P
549 * points to the parent directory of the display list.
550 */
551static void
552display(const FTSENT *p, FTSENT *list, int options)
553{
554	struct stat *sp;
555	DISPLAY d;
556	FTSENT *cur;
557	NAMES *np;
558	off_t maxsize;
559	long maxblock;
560	u_long btotal, labelstrlen, maxinode, maxlen, maxnlink;
561	u_long maxlabelstr;
562	u_int devstrlen;
563	int maxflags;
564	gid_t maxgroup;
565	uid_t maxuser;
566	size_t flen, ulen, glen;
567	char *initmax;
568	int entries, needstats;
569	const char *user, *group;
570	char *flags, *labelstr = NULL;
571	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
572	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
573	char nuser[STRBUF_SIZEOF(gid_t) + 1];
574
575	needstats = f_inode || f_longform || f_size;
576	flen = 0;
577	btotal = 0;
578	initmax = getenv("LS_COLWIDTHS");
579	/* Fields match -lios order.  New ones should be added at the end. */
580	maxlabelstr = maxblock = maxinode = maxlen = maxnlink =
581	    maxuser = maxgroup = maxflags = maxsize = 0;
582	if (initmax != NULL && *initmax != '\0') {
583		char *initmax2, *jinitmax;
584		int ninitmax;
585
586		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
587		jinitmax = malloc(strlen(initmax) * 2 + 2);
588		if (jinitmax == NULL)
589			err(1, "malloc");
590		initmax2 = jinitmax;
591		if (*initmax == ':')
592			strcpy(initmax2, "0:"), initmax2 += 2;
593		else
594			*initmax2++ = *initmax, *initmax2 = '\0';
595		for (initmax++; *initmax != '\0'; initmax++) {
596			if (initmax[-1] == ':' && initmax[0] == ':') {
597				*initmax2++ = '0';
598				*initmax2++ = initmax[0];
599				initmax2[1] = '\0';
600			} else {
601				*initmax2++ = initmax[0];
602				initmax2[1] = '\0';
603			}
604		}
605		if (initmax2[-1] == ':')
606			strcpy(initmax2, "0");
607
608		ninitmax = sscanf(jinitmax,
609		    " %lu : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
610		    &maxinode, &maxblock, &maxnlink, &maxuser,
611		    &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
612		f_notabs = 1;
613		switch (ninitmax) {
614		case 0:
615			maxinode = 0;
616			/* FALLTHROUGH */
617		case 1:
618			maxblock = 0;
619			/* FALLTHROUGH */
620		case 2:
621			maxnlink = 0;
622			/* FALLTHROUGH */
623		case 3:
624			maxuser = 0;
625			/* FALLTHROUGH */
626		case 4:
627			maxgroup = 0;
628			/* FALLTHROUGH */
629		case 5:
630			maxflags = 0;
631			/* FALLTHROUGH */
632		case 6:
633			maxsize = 0;
634			/* FALLTHROUGH */
635		case 7:
636			maxlen = 0;
637			/* FALLTHROUGH */
638		case 8:
639			maxlabelstr = 0;
640			/* FALLTHROUGH */
641#ifdef COLORLS
642			if (!f_color)
643#endif
644				f_notabs = 0;
645			/* FALLTHROUGH */
646		default:
647			break;
648		}
649		MAKENINES(maxinode);
650		MAKENINES(maxblock);
651		MAKENINES(maxnlink);
652		MAKENINES(maxsize);
653		free(jinitmax);
654	}
655	devstrlen = 0;
656	flags = NULL;
657	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
658		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
659			warnx("%s: %s",
660			    cur->fts_name, strerror(cur->fts_errno));
661			cur->fts_number = NO_PRINT;
662			rval = 1;
663			continue;
664		}
665		/*
666		 * P is NULL if list is the argv list, to which different rules
667		 * apply.
668		 */
669		if (p == NULL) {
670			/* Directories will be displayed later. */
671			if (cur->fts_info == FTS_D && !f_listdir) {
672				cur->fts_number = NO_PRINT;
673				continue;
674			}
675		} else {
676			/* Only display dot file if -a/-A set. */
677			if (cur->fts_name[0] == '.' && !f_listdot) {
678				cur->fts_number = NO_PRINT;
679				continue;
680			}
681		}
682		if (cur->fts_namelen > maxlen)
683			maxlen = cur->fts_namelen;
684		if (f_octal || f_octal_escape) {
685			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
686
687			if (t > maxlen)
688				maxlen = t;
689		}
690		if (needstats) {
691			sp = cur->fts_statp;
692			if (sp->st_blocks > maxblock)
693				maxblock = sp->st_blocks;
694			if (sp->st_ino > maxinode)
695				maxinode = sp->st_ino;
696			if (sp->st_nlink > maxnlink)
697				maxnlink = sp->st_nlink;
698			if (sp->st_size > maxsize)
699				maxsize = sp->st_size;
700
701			btotal += sp->st_blocks;
702			if (f_longform) {
703				if (f_numericonly) {
704					(void)snprintf(nuser, sizeof(nuser),
705					    "%u", sp->st_uid);
706					(void)snprintf(ngroup, sizeof(ngroup),
707					    "%u", sp->st_gid);
708					user = nuser;
709					group = ngroup;
710				} else {
711					user = user_from_uid(sp->st_uid, 0);
712					group = group_from_gid(sp->st_gid, 0);
713				}
714				if ((ulen = strlen(user)) > maxuser)
715					maxuser = ulen;
716				if ((glen = strlen(group)) > maxgroup)
717					maxgroup = glen;
718				if (f_flags) {
719					flags = fflagstostr(sp->st_flags);
720					if (flags != NULL && *flags == '\0') {
721						free(flags);
722						flags = strdup("-");
723					}
724					if (flags == NULL)
725						err(1, "fflagstostr");
726					flen = strlen(flags);
727					if (flen > (size_t)maxflags)
728						maxflags = flen;
729				} else
730					flen = 0;
731				labelstr = NULL;
732				if (f_label) {
733					char name[PATH_MAX + 1];
734					mac_t label;
735					int error;
736
737					error = mac_prepare_file_label(&label);
738					if (error == -1) {
739						warn("MAC label for %s/%s",
740						    cur->fts_parent->fts_path,
741						    cur->fts_name);
742						goto label_out;
743					}
744
745					if (cur->fts_level == FTS_ROOTLEVEL)
746						snprintf(name, sizeof(name),
747						    "%s", cur->fts_name);
748					else
749						snprintf(name, sizeof(name),
750						    "%s/%s", cur->fts_parent->
751						    fts_accpath, cur->fts_name);
752
753					if (options & FTS_LOGICAL)
754						error = mac_get_file(name,
755						    label);
756					else
757						error = mac_get_link(name,
758						    label);
759					if (error == -1) {
760						warn("MAC label for %s/%s",
761						    cur->fts_parent->fts_path,
762						    cur->fts_name);
763						mac_free(label);
764						goto label_out;
765					}
766
767					error = mac_to_text(label,
768					    &labelstr);
769					if (error == -1) {
770						warn("MAC label for %s/%s",
771						    cur->fts_parent->fts_path,
772						    cur->fts_name);
773						mac_free(label);
774						goto label_out;
775					}
776					mac_free(label);
777label_out:
778					if (labelstr == NULL)
779						labelstr = strdup("-");
780					labelstrlen = strlen(labelstr);
781					if (labelstrlen > maxlabelstr)
782						maxlabelstr = labelstrlen;
783				} else
784					labelstrlen = 0;
785
786				if ((np = malloc(sizeof(NAMES) + labelstrlen +
787				    ulen + glen + flen + 4)) == NULL)
788					err(1, "malloc");
789
790				np->user = &np->data[0];
791				(void)strcpy(np->user, user);
792				np->group = &np->data[ulen + 1];
793				(void)strcpy(np->group, group);
794
795				if ((S_ISCHR(sp->st_mode) ||
796				    S_ISBLK(sp->st_mode)) &&
797				    devstrlen < DEVSTR_HEX_LEN) {
798					if (minor(sp->st_rdev) > 255 ||
799					    minor(sp->st_rdev) < 0)
800						devstrlen = DEVSTR_HEX_LEN;
801					else
802						devstrlen = DEVSTR_LEN;
803				}
804
805				if (f_flags) {
806					np->flags = &np->data[ulen + glen + 2];
807					(void)strcpy(np->flags, flags);
808					free(flags);
809				}
810				if (f_label) {
811					np->label = &np->data[ulen + glen + 2
812					    + (f_flags ? flen + 1 : 0)];
813					(void)strcpy(np->label, labelstr);
814					free(labelstr);
815				}
816				cur->fts_pointer = np;
817			}
818		}
819		++entries;
820	}
821
822	/*
823	 * If there are no entries to display, we normally stop right
824	 * here.  However, we must continue if we have to display the
825	 * total block count.  In this case, we display the total only
826	 * on the second (p != NULL) pass.
827	 */
828	if (!entries && (!(f_longform || f_size) || p == NULL))
829		return;
830
831	d.list = list;
832	d.entries = entries;
833	d.maxlen = maxlen;
834	if (needstats) {
835		d.btotal = btotal;
836		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
837		d.s_block = strlen(buf);
838		d.s_flags = maxflags;
839		d.s_label = maxlabelstr;
840		d.s_group = maxgroup;
841		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
842		d.s_inode = strlen(buf);
843		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
844		d.s_nlink = strlen(buf);
845		if (f_humanval)
846			d.s_size = HUMANVALSTR_LEN;
847		else {
848			(void)snprintf(buf, sizeof(buf), "%ju", maxsize);
849			d.s_size = strlen(buf);
850		}
851		if (d.s_size < devstrlen)
852			d.s_size = devstrlen;
853		d.s_user = maxuser;
854	}
855	printfcn(&d);
856	output = 1;
857
858	if (f_longform)
859		for (cur = list; cur; cur = cur->fts_link)
860			free(cur->fts_pointer);
861}
862
863/*
864 * Ordering for mastercmp:
865 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
866 * as larger than directories.  Within either group, use the sort function.
867 * All other levels use the sort function.  Error entries remain unsorted.
868 */
869static int
870mastercmp(const FTSENT * const *a, const FTSENT * const *b)
871{
872	int a_info, b_info;
873
874	a_info = (*a)->fts_info;
875	if (a_info == FTS_ERR)
876		return (0);
877	b_info = (*b)->fts_info;
878	if (b_info == FTS_ERR)
879		return (0);
880
881	if (a_info == FTS_NS || b_info == FTS_NS)
882		return (namecmp(*a, *b));
883
884	if (a_info != b_info &&
885	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
886		if (a_info == FTS_D)
887			return (1);
888		if (b_info == FTS_D)
889			return (-1);
890	}
891	return (sortfcn(*a, *b));
892}
893