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