xref: /freebsd/bin/ls/ls.c (revision d2387d42b8da231a5b95cbc313825fb2aadf26f6)
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
38 static 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
45 static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
46 #endif /* not lint */
47 #endif
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
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 
99 static void	 display(const FTSENT *, FTSENT *, int);
100 static int	 mastercmp(const FTSENT * const *, const FTSENT * const *);
101 static void	 traverse(int, char **, int);
102 
103 static void (*printfcn)(const DISPLAY *);
104 static int (*sortfcn)(const FTSENT *, const FTSENT *);
105 
106 long blocksize;			/* block size units */
107 int 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 */
114 static int f_kblocks;		/* print size in kilobytes */
115 static int f_listdir;		/* list actual directory, not contents */
116 static int f_listdot;		/* list files beginning with . */
117        int f_longform;		/* long listing format */
118        int f_nonprint;		/* show unprintables as ? */
119 static int f_nosort;		/* don't sort output */
120        int f_notabs;		/* don't use tab-separated multi-col output */
121 static 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 */
124 static int f_recursive;		/* ls subdirectories also */
125 static int f_reversesort;	/* reverse whatever sort is used */
126        int f_sectime;		/* print the real time for all files */
127 static 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 */
132 static int f_stream;		/* stream the output, separate with commas */
133 static int f_timesort;		/* sort by time vice name */
134        int f_type;		/* add type character for non-regular files */
135 static 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 
140 char *ansi_bgcol;		/* ANSI sequence to set background colour */
141 char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
142 char *ansi_coloff;		/* ANSI sequence to reset colours */
143 char *attrs_off;		/* ANSI sequence to turn off attributes */
144 char *enter_bold;		/* ANSI sequence to set color to bold mode */
145 #endif
146 
147 static int rval;
148 
149 int
150 main(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_humanval = 0;
271 			f_kblocks = 1;
272 			break;
273 		case 'm':
274 			f_stream = 1;
275 			f_singlecol = 0;
276 			f_longform = 0;
277 			break;
278 		case 'n':
279 			f_numericonly = 1;
280 			break;
281 		case 'o':
282 			f_flags = 1;
283 			break;
284 		case 'p':
285 			f_slash = 1;
286 			f_type = 1;
287 			break;
288 		case 'q':
289 			f_nonprint = 1;
290 			f_octal = 0;
291 			f_octal_escape = 0;
292 			break;
293 		case 'r':
294 			f_reversesort = 1;
295 			break;
296 		case 's':
297 			f_size = 1;
298 			break;
299 		case 'T':
300 			f_sectime = 1;
301 			break;
302 		case 't':
303 			f_timesort = 1;
304 			break;
305 		case 'W':
306 			f_whiteout = 1;
307 			break;
308 		case 'b':
309 			f_nonprint = 0;
310 			f_octal = 0;
311 			f_octal_escape = 1;
312 			break;
313 		case 'w':
314 			f_nonprint = 0;
315 			f_octal = 0;
316 			f_octal_escape = 0;
317 			break;
318 		case 'Z':
319 			f_label = 1;
320 			break;
321 		default:
322 		case '?':
323 			usage();
324 		}
325 	}
326 	argc -= optind;
327 	argv += optind;
328 
329 	/* Enabling of colours is conditional on the environment. */
330 	if (getenv("CLICOLOR") &&
331 	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
332 #ifdef COLORLS
333 		if (tgetent(termcapbuf, getenv("TERM")) == 1) {
334 			ansi_fgcol = tgetstr("AF", &bp);
335 			ansi_bgcol = tgetstr("AB", &bp);
336 			attrs_off = tgetstr("me", &bp);
337 			enter_bold = tgetstr("md", &bp);
338 
339 			/* To switch colours off use 'op' if
340 			 * available, otherwise use 'oc', or
341 			 * don't do colours at all. */
342 			ansi_coloff = tgetstr("op", &bp);
343 			if (!ansi_coloff)
344 				ansi_coloff = tgetstr("oc", &bp);
345 			if (ansi_fgcol && ansi_bgcol && ansi_coloff)
346 				f_color = 1;
347 		}
348 #else
349 		warnx("color support not compiled in");
350 #endif /*COLORLS*/
351 
352 #ifdef COLORLS
353 	if (f_color) {
354 		/*
355 		 * We can't put tabs and color sequences together:
356 		 * column number will be incremented incorrectly
357 		 * for "stty oxtabs" mode.
358 		 */
359 		f_notabs = 1;
360 		(void)signal(SIGINT, colorquit);
361 		(void)signal(SIGQUIT, colorquit);
362 		parsecolors(getenv("LSCOLORS"));
363 	}
364 #endif
365 
366 	/*
367 	 * If not -F, -i, -l, -s or -t options, don't require stat
368 	 * information, unless in color mode in which case we do
369 	 * need this to determine which colors to display.
370 	 */
371 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
372 #ifdef COLORLS
373 	    && !f_color
374 #endif
375 	    )
376 		fts_options |= FTS_NOSTAT;
377 
378 	/*
379 	 * If not -F, -d or -l options, follow any symbolic links listed on
380 	 * the command line.
381 	 */
382 	if (!f_longform && !f_listdir && !f_type)
383 		fts_options |= FTS_COMFOLLOW;
384 
385 	/*
386 	 * If -W, show whiteout entries
387 	 */
388 #ifdef FTS_WHITEOUT
389 	if (f_whiteout)
390 		fts_options |= FTS_WHITEOUT;
391 #endif
392 
393 	/* If -l or -s, figure out block size. */
394 	if (f_longform || f_size) {
395 		if (f_kblocks)
396 			blocksize = 2;
397 		else {
398 			(void)getbsize(&notused, &blocksize);
399 			blocksize /= 512;
400 		}
401 	}
402 	/* Select a sort function. */
403 	if (f_reversesort) {
404 		if (!f_timesort)
405 			sortfcn = revnamecmp;
406 		else if (f_accesstime)
407 			sortfcn = revacccmp;
408 		else if (f_statustime)
409 			sortfcn = revstatcmp;
410 		else		/* Use modification time. */
411 			sortfcn = revmodcmp;
412 	} else {
413 		if (!f_timesort)
414 			sortfcn = namecmp;
415 		else if (f_accesstime)
416 			sortfcn = acccmp;
417 		else if (f_statustime)
418 			sortfcn = statcmp;
419 		else		/* Use modification time. */
420 			sortfcn = modcmp;
421 	}
422 
423 	/* Select a print function. */
424 	if (f_singlecol)
425 		printfcn = printscol;
426 	else if (f_longform)
427 		printfcn = printlong;
428 	else if (f_stream)
429 		printfcn = printstream;
430 	else
431 		printfcn = printcol;
432 
433 	if (argc)
434 		traverse(argc, argv, fts_options);
435 	else
436 		traverse(1, dotav, fts_options);
437 	exit(rval);
438 }
439 
440 static int output;		/* If anything output. */
441 
442 /*
443  * Traverse() walks the logical directory structure specified by the argv list
444  * in the order specified by the mastercmp() comparison function.  During the
445  * traversal it passes linked lists of structures to display() which represent
446  * a superset (may be exact set) of the files to be displayed.
447  */
448 static void
449 traverse(int argc, char *argv[], int options)
450 {
451 	FTS *ftsp;
452 	FTSENT *p, *chp;
453 	int ch_options;
454 
455 	if ((ftsp =
456 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
457 		err(1, "fts_open");
458 
459 	display(NULL, fts_children(ftsp, 0), options);
460 	if (f_listdir)
461 		return;
462 
463 	/*
464 	 * If not recursing down this tree and don't need stat info, just get
465 	 * the names.
466 	 */
467 	ch_options = !f_recursive && !f_label &&
468 	    options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
469 
470 	while ((p = fts_read(ftsp)) != NULL)
471 		switch (p->fts_info) {
472 		case FTS_DC:
473 			warnx("%s: directory causes a cycle", p->fts_name);
474 			break;
475 		case FTS_DNR:
476 		case FTS_ERR:
477 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
478 			rval = 1;
479 			break;
480 		case FTS_D:
481 			if (p->fts_level != FTS_ROOTLEVEL &&
482 			    p->fts_name[0] == '.' && !f_listdot)
483 				break;
484 
485 			/*
486 			 * If already output something, put out a newline as
487 			 * a separator.  If multiple arguments, precede each
488 			 * directory with its name.
489 			 */
490 			if (output) {
491 				putchar('\n');
492 				(void)printname(p->fts_path);
493 				puts(":");
494 			} else if (argc > 1) {
495 				(void)printname(p->fts_path);
496 				puts(":");
497 				output = 1;
498 			}
499 			chp = fts_children(ftsp, ch_options);
500 			display(p, chp, options);
501 
502 			if (!f_recursive && chp != NULL)
503 				(void)fts_set(ftsp, p, FTS_SKIP);
504 			break;
505 		default:
506 			break;
507 		}
508 	if (errno)
509 		err(1, "fts_read");
510 }
511 
512 /*
513  * Display() takes a linked list of FTSENT structures and passes the list
514  * along with any other necessary information to the print function.  P
515  * points to the parent directory of the display list.
516  */
517 static void
518 display(const FTSENT *p, FTSENT *list, int options)
519 {
520 	struct stat *sp;
521 	DISPLAY d;
522 	FTSENT *cur;
523 	NAMES *np;
524 	off_t maxsize;
525 	long maxblock;
526 	u_long btotal, labelstrlen, maxinode, maxlen, maxnlink;
527 	u_long maxlabelstr;
528 	int bcfile, maxflags;
529 	gid_t maxgroup;
530 	uid_t maxuser;
531 	size_t flen, ulen, glen;
532 	char *initmax;
533 	int entries, needstats;
534 	const char *user, *group;
535 	char *flags, *labelstr = NULL;
536 	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
537 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
538 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
539 
540 	/*
541 	 * If list is NULL there are two possibilities: that the parent
542 	 * directory p has no children, or that fts_children() returned an
543 	 * error.  We ignore the error case since it will be replicated
544 	 * on the next call to fts_read() on the post-order visit to the
545 	 * directory p, and will be signaled in traverse().
546 	 */
547 	if (list == NULL)
548 		return;
549 
550 	needstats = f_inode || f_longform || f_size;
551 	flen = 0;
552 	btotal = 0;
553 	initmax = getenv("LS_COLWIDTHS");
554 	/* Fields match -lios order.  New ones should be added at the end. */
555 	maxlabelstr = maxblock = maxinode = maxlen = maxnlink =
556 	    maxuser = maxgroup = maxflags = maxsize = 0;
557 	if (initmax != NULL && *initmax != '\0') {
558 		char *initmax2, *jinitmax;
559 		int ninitmax;
560 
561 		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
562 		jinitmax = malloc(strlen(initmax) * 2 + 2);
563 		if (jinitmax == NULL)
564 			err(1, "malloc");
565 		initmax2 = jinitmax;
566 		if (*initmax == ':')
567 			strcpy(initmax2, "0:"), initmax2 += 2;
568 		else
569 			*initmax2++ = *initmax, *initmax2 = '\0';
570 		for (initmax++; *initmax != '\0'; initmax++) {
571 			if (initmax[-1] == ':' && initmax[0] == ':') {
572 				*initmax2++ = '0';
573 				*initmax2++ = initmax[0];
574 				initmax2[1] = '\0';
575 			} else {
576 				*initmax2++ = initmax[0];
577 				initmax2[1] = '\0';
578 			}
579 		}
580 		if (initmax2[-1] == ':')
581 			strcpy(initmax2, "0");
582 
583 		ninitmax = sscanf(jinitmax,
584 		    " %lu : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
585 		    &maxinode, &maxblock, &maxnlink, &maxuser,
586 		    &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
587 		f_notabs = 1;
588 		switch (ninitmax) {
589 		case 0:
590 			maxinode = 0;
591 			/* FALLTHROUGH */
592 		case 1:
593 			maxblock = 0;
594 			/* FALLTHROUGH */
595 		case 2:
596 			maxnlink = 0;
597 			/* FALLTHROUGH */
598 		case 3:
599 			maxuser = 0;
600 			/* FALLTHROUGH */
601 		case 4:
602 			maxgroup = 0;
603 			/* FALLTHROUGH */
604 		case 5:
605 			maxflags = 0;
606 			/* FALLTHROUGH */
607 		case 6:
608 			maxsize = 0;
609 			/* FALLTHROUGH */
610 		case 7:
611 			maxlen = 0;
612 			/* FALLTHROUGH */
613 		case 8:
614 			maxlabelstr = 0;
615 			/* FALLTHROUGH */
616 #ifdef COLORLS
617 			if (!f_color)
618 #endif
619 				f_notabs = 0;
620 			/* FALLTHROUGH */
621 		default:
622 			break;
623 		}
624 		MAKENINES(maxinode);
625 		MAKENINES(maxblock);
626 		MAKENINES(maxnlink);
627 		MAKENINES(maxsize);
628 	}
629 	bcfile = 0;
630 	flags = NULL;
631 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
632 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
633 			warnx("%s: %s",
634 			    cur->fts_name, strerror(cur->fts_errno));
635 			cur->fts_number = NO_PRINT;
636 			rval = 1;
637 			continue;
638 		}
639 		/*
640 		 * P is NULL if list is the argv list, to which different rules
641 		 * apply.
642 		 */
643 		if (p == NULL) {
644 			/* Directories will be displayed later. */
645 			if (cur->fts_info == FTS_D && !f_listdir) {
646 				cur->fts_number = NO_PRINT;
647 				continue;
648 			}
649 		} else {
650 			/* Only display dot file if -a/-A set. */
651 			if (cur->fts_name[0] == '.' && !f_listdot) {
652 				cur->fts_number = NO_PRINT;
653 				continue;
654 			}
655 		}
656 		if (cur->fts_namelen > maxlen)
657 			maxlen = cur->fts_namelen;
658 		if (f_octal || f_octal_escape) {
659 			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
660 
661 			if (t > maxlen)
662 				maxlen = t;
663 		}
664 		if (needstats) {
665 			sp = cur->fts_statp;
666 			if (sp->st_blocks > maxblock)
667 				maxblock = sp->st_blocks;
668 			if (sp->st_ino > maxinode)
669 				maxinode = sp->st_ino;
670 			if (sp->st_nlink > maxnlink)
671 				maxnlink = sp->st_nlink;
672 			if (sp->st_size > maxsize)
673 				maxsize = sp->st_size;
674 
675 			btotal += sp->st_blocks;
676 			if (f_longform) {
677 				if (f_numericonly) {
678 					(void)snprintf(nuser, sizeof(nuser),
679 					    "%u", sp->st_uid);
680 					(void)snprintf(ngroup, sizeof(ngroup),
681 					    "%u", sp->st_gid);
682 					user = nuser;
683 					group = ngroup;
684 				} else {
685 					user = user_from_uid(sp->st_uid, 0);
686 					group = group_from_gid(sp->st_gid, 0);
687 				}
688 				if ((ulen = strlen(user)) > maxuser)
689 					maxuser = ulen;
690 				if ((glen = strlen(group)) > maxgroup)
691 					maxgroup = glen;
692 				if (f_flags) {
693 					flags = fflagstostr(sp->st_flags);
694 					if (flags != NULL && *flags == '\0') {
695 						free(flags);
696 						flags = strdup("-");
697 					}
698 					if (flags == NULL)
699 						err(1, "fflagstostr");
700 					flen = strlen(flags);
701 					if (flen > (size_t)maxflags)
702 						maxflags = flen;
703 				} else
704 					flen = 0;
705 				labelstr = NULL;
706 				if (f_label) {
707 					char name[PATH_MAX + 1];
708 					mac_t label;
709 					int error;
710 
711 					error = mac_prepare_file_label(&label);
712 					if (error == -1) {
713 						warn("MAC label for %s/%s",
714 						    cur->fts_parent->fts_path,
715 						    cur->fts_name);
716 						goto label_out;
717 					}
718 
719 					if (cur->fts_level == FTS_ROOTLEVEL)
720 						snprintf(name, sizeof(name),
721 						    "%s", cur->fts_name);
722 					else
723 						snprintf(name, sizeof(name),
724 						    "%s/%s", cur->fts_parent->
725 						    fts_accpath, cur->fts_name);
726 
727 					if (options & FTS_LOGICAL)
728 						error = mac_get_file(name,
729 						    label);
730 					else
731 						error = mac_get_link(name,
732 						    label);
733 					if (error == -1) {
734 						warn("MAC label for %s/%s",
735 						    cur->fts_parent->fts_path,
736 						    cur->fts_name);
737 						mac_free(label);
738 						goto label_out;
739 					}
740 
741 					error = mac_to_text(label,
742 					    &labelstr);
743 					if (error == -1) {
744 						warn("MAC label for %s/%s",
745 						    cur->fts_parent->fts_path,
746 						    cur->fts_name);
747 						mac_free(label);
748 						goto label_out;
749 					}
750 					mac_free(label);
751 label_out:
752 					if (labelstr == NULL)
753 						labelstr = strdup("-");
754 					labelstrlen = strlen(labelstr);
755 					if (labelstrlen > maxlabelstr)
756 						maxlabelstr = labelstrlen;
757 				} else
758 					labelstrlen = 0;
759 
760 				if ((np = malloc(sizeof(NAMES) + labelstrlen +
761 				    ulen + glen + flen + 4)) == NULL)
762 					err(1, "malloc");
763 
764 				np->user = &np->data[0];
765 				(void)strcpy(np->user, user);
766 				np->group = &np->data[ulen + 1];
767 				(void)strcpy(np->group, group);
768 
769 				if (S_ISCHR(sp->st_mode) ||
770 				    S_ISBLK(sp->st_mode))
771 					bcfile = 1;
772 
773 				if (f_flags) {
774 					np->flags = &np->data[ulen + glen + 2];
775 					(void)strcpy(np->flags, flags);
776 					free(flags);
777 				}
778 				if (f_label) {
779 					np->label = &np->data[ulen + glen + 2
780 					    + (f_flags ? flen + 1 : 0)];
781 					(void)strcpy(np->label, labelstr);
782 					free(labelstr);
783 				}
784 				cur->fts_pointer = np;
785 			}
786 		}
787 		++entries;
788 	}
789 
790 	if (!entries)
791 		return;
792 
793 	d.list = list;
794 	d.entries = entries;
795 	d.maxlen = maxlen;
796 	if (needstats) {
797 		d.bcfile = bcfile;
798 		d.btotal = btotal;
799 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
800 		d.s_block = strlen(buf);
801 		d.s_flags = maxflags;
802 		d.s_label = maxlabelstr;
803 		d.s_group = maxgroup;
804 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
805 		d.s_inode = strlen(buf);
806 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
807 		d.s_nlink = strlen(buf);
808 		(void)snprintf(buf, sizeof(buf), "%ju", maxsize);
809 		d.s_size = strlen(buf);
810 		d.s_user = maxuser;
811 	}
812 	printfcn(&d);
813 	output = 1;
814 
815 	if (f_longform)
816 		for (cur = list; cur; cur = cur->fts_link)
817 			free(cur->fts_pointer);
818 }
819 
820 /*
821  * Ordering for mastercmp:
822  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
823  * as larger than directories.  Within either group, use the sort function.
824  * All other levels use the sort function.  Error entries remain unsorted.
825  */
826 static int
827 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
828 {
829 	int a_info, b_info;
830 
831 	a_info = (*a)->fts_info;
832 	if (a_info == FTS_ERR)
833 		return (0);
834 	b_info = (*b)->fts_info;
835 	if (b_info == FTS_ERR)
836 		return (0);
837 
838 	if (a_info == FTS_NS || b_info == FTS_NS)
839 		return (namecmp(*a, *b));
840 
841 	if (a_info != b_info &&
842 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
843 		if (a_info == FTS_D)
844 			return (1);
845 		if (b_info == FTS_D)
846 			return (-1);
847 	}
848 	return (sortfcn(*a, *b));
849 }
850