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