xref: /freebsd/bin/ls/ls.c (revision b6de9e91bd2c47efaeec72a08642f8fd99cc7b20)
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 static int f_sizesort;
131        int f_type;		/* add type character for non-regular files */
132 static int f_whiteout;		/* show whiteout entries */
133        int f_label;		/* show MAC label */
134 #ifdef COLORLS
135        int f_color;		/* add type in color for non-regular files */
136 
137 char *ansi_bgcol;		/* ANSI sequence to set background colour */
138 char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
139 char *ansi_coloff;		/* ANSI sequence to reset colours */
140 char *attrs_off;		/* ANSI sequence to turn off attributes */
141 char *enter_bold;		/* ANSI sequence to set color to bold mode */
142 #endif
143 
144 static int rval;
145 
146 int
147 main(int argc, char *argv[])
148 {
149 	static char dot[] = ".", *dotav[] = {dot, NULL};
150 	struct winsize win;
151 	int ch, fts_options, notused;
152 	char *p;
153 #ifdef COLORLS
154 	char termcapbuf[1024];	/* termcap definition buffer */
155 	char tcapbuf[512];	/* capability buffer */
156 	char *bp = tcapbuf;
157 #endif
158 
159 	(void)setlocale(LC_ALL, "");
160 
161 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
162 	if (isatty(STDOUT_FILENO)) {
163 		termwidth = 80;
164 		if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
165 			termwidth = atoi(p);
166 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
167 		    win.ws_col > 0)
168 			termwidth = win.ws_col;
169 		f_nonprint = 1;
170 	} else {
171 		f_singlecol = 1;
172 		/* retrieve environment variable, in case of explicit -C */
173 		p = getenv("COLUMNS");
174 		if (p)
175 			termwidth = atoi(p);
176 	}
177 
178 	/* Root is -A automatically. */
179 	if (!getuid())
180 		f_listdot = 1;
181 
182 	fts_options = FTS_PHYSICAL;
183  	while ((ch = getopt(argc, argv,
184 	    "1ABCFGHLPRSTWZabcdfghiklmnopqrstuwx")) != -1) {
185 		switch (ch) {
186 		/*
187 		 * The -1, -C, -x and -l options all override each other so
188 		 * shell aliasing works right.
189 		 */
190 		case '1':
191 			f_singlecol = 1;
192 			f_longform = 0;
193 			f_stream = 0;
194 			break;
195 		case 'B':
196 			f_nonprint = 0;
197 			f_octal = 1;
198 			f_octal_escape = 0;
199 			break;
200 		case 'C':
201 			f_sortacross = f_longform = f_singlecol = 0;
202 			break;
203 		case 'l':
204 			f_longform = 1;
205 			f_singlecol = 0;
206 			f_stream = 0;
207 			break;
208 		case 'x':
209 			f_sortacross = 1;
210 			f_longform = 0;
211 			f_singlecol = 0;
212 			break;
213 		/* The -c and -u options override each other. */
214 		case 'c':
215 			f_statustime = 1;
216 			f_accesstime = 0;
217 			break;
218 		case 'u':
219 			f_accesstime = 1;
220 			f_statustime = 0;
221 			break;
222 		case 'F':
223 			f_type = 1;
224 			f_slash = 0;
225 			break;
226 		case 'H':
227 			fts_options |= FTS_COMFOLLOW;
228 			break;
229 		case 'G':
230 			setenv("CLICOLOR", "", 1);
231 			break;
232 		case 'L':
233 			fts_options &= ~FTS_PHYSICAL;
234 			fts_options |= FTS_LOGICAL;
235 			break;
236 		case 'P':
237 			fts_options &= ~FTS_COMFOLLOW;
238 			fts_options &= ~FTS_LOGICAL;
239 			fts_options |= FTS_PHYSICAL;
240 			break;
241 		case 'R':
242 			f_recursive = 1;
243 			break;
244 		case 'a':
245 			fts_options |= FTS_SEEDOT;
246 			/* FALLTHROUGH */
247 		case 'A':
248 			f_listdot = 1;
249 			break;
250 		/* The -d option turns off the -R option. */
251 		case 'd':
252 			f_listdir = 1;
253 			f_recursive = 0;
254 			break;
255 		case 'f':
256 			f_nosort = 1;
257 			break;
258 		case 'g':	/* Compatibility with 4.3BSD. */
259 			break;
260 		case 'h':
261 			f_humanval = 1;
262 			break;
263 		case 'i':
264 			f_inode = 1;
265 			break;
266 		case 'k':
267 			f_humanval = 0;
268 			f_kblocks = 1;
269 			break;
270 		case 'm':
271 			f_stream = 1;
272 			f_singlecol = 0;
273 			f_longform = 0;
274 			break;
275 		case 'n':
276 			f_numericonly = 1;
277 			break;
278 		case 'o':
279 			f_flags = 1;
280 			break;
281 		case 'p':
282 			f_slash = 1;
283 			f_type = 1;
284 			break;
285 		case 'q':
286 			f_nonprint = 1;
287 			f_octal = 0;
288 			f_octal_escape = 0;
289 			break;
290 		case 'r':
291 			f_reversesort = 1;
292 			break;
293 		case 's':
294 			f_size = 1;
295 			break;
296 		case 'T':
297 			f_sectime = 1;
298 			break;
299 		case 't':
300 			f_timesort = 1;
301 			break;
302 		case 'S':
303 			f_sizesort = 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, -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 &&
372 	    !f_sizesort && !f_type
373 #ifdef COLORLS
374 	    && !f_color
375 #endif
376 	    )
377 		fts_options |= FTS_NOSTAT;
378 
379 	/*
380 	 * If not -F, -d or -l options, follow any symbolic links listed on
381 	 * the command line.
382 	 */
383 	if (!f_longform && !f_listdir && !f_type)
384 		fts_options |= FTS_COMFOLLOW;
385 
386 	/*
387 	 * If -W, show whiteout entries
388 	 */
389 #ifdef FTS_WHITEOUT
390 	if (f_whiteout)
391 		fts_options |= FTS_WHITEOUT;
392 #endif
393 
394 	/* If -l or -s, figure out block size. */
395 	if (f_longform || f_size) {
396 		if (f_kblocks)
397 			blocksize = 2;
398 		else {
399 			(void)getbsize(&notused, &blocksize);
400 			blocksize /= 512;
401 		}
402 	}
403 	/* Select a sort function. */
404 	if (f_reversesort) {
405 		if (!f_timesort && !f_sizesort)
406 			sortfcn = revnamecmp;
407 		else if (f_accesstime)
408 			sortfcn = revacccmp;
409 		else if (f_statustime)
410 			sortfcn = revstatcmp;
411 		else if (f_sizesort)
412 			sortfcn = revsizecmp;
413 		else		/* Use modification time. */
414 			sortfcn = revmodcmp;
415 	} else {
416 		if (!f_timesort && !f_sizesort)
417 			sortfcn = namecmp;
418 		else if (f_accesstime)
419 			sortfcn = acccmp;
420 		else if (f_statustime)
421 			sortfcn = statcmp;
422 		else if (f_sizesort)
423 			sortfcn = sizecmp;
424 		else		/* Use modification time. */
425 			sortfcn = modcmp;
426 	}
427 
428 	/* Select a print function. */
429 	if (f_singlecol)
430 		printfcn = printscol;
431 	else if (f_longform)
432 		printfcn = printlong;
433 	else if (f_stream)
434 		printfcn = printstream;
435 	else
436 		printfcn = printcol;
437 
438 	if (argc)
439 		traverse(argc, argv, fts_options);
440 	else
441 		traverse(1, dotav, fts_options);
442 	exit(rval);
443 }
444 
445 static int output;		/* If anything output. */
446 
447 /*
448  * Traverse() walks the logical directory structure specified by the argv list
449  * in the order specified by the mastercmp() comparison function.  During the
450  * traversal it passes linked lists of structures to display() which represent
451  * a superset (may be exact set) of the files to be displayed.
452  */
453 static void
454 traverse(int argc, char *argv[], int options)
455 {
456 	FTS *ftsp;
457 	FTSENT *p, *chp;
458 	int ch_options;
459 
460 	if ((ftsp =
461 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
462 		err(1, "fts_open");
463 
464 	/*
465 	 * We ignore errors from fts_children here since they will be
466 	 * replicated and signalled on the next call to fts_read() below.
467 	 */
468 	chp = fts_children(ftsp, 0);
469 	if (chp != NULL)
470 		display(NULL, chp, options);
471 	if (f_listdir)
472 		return;
473 
474 	/*
475 	 * If not recursing down this tree and don't need stat info, just get
476 	 * the names.
477 	 */
478 	ch_options = !f_recursive && !f_label &&
479 	    options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
480 
481 	while ((p = fts_read(ftsp)) != NULL)
482 		switch (p->fts_info) {
483 		case FTS_DC:
484 			warnx("%s: directory causes a cycle", p->fts_name);
485 			break;
486 		case FTS_DNR:
487 		case FTS_ERR:
488 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
489 			rval = 1;
490 			break;
491 		case FTS_D:
492 			if (p->fts_level != FTS_ROOTLEVEL &&
493 			    p->fts_name[0] == '.' && !f_listdot)
494 				break;
495 
496 			/*
497 			 * If already output something, put out a newline as
498 			 * a separator.  If multiple arguments, precede each
499 			 * directory with its name.
500 			 */
501 			if (output) {
502 				putchar('\n');
503 				(void)printname(p->fts_path);
504 				puts(":");
505 			} else if (argc > 1) {
506 				(void)printname(p->fts_path);
507 				puts(":");
508 				output = 1;
509 			}
510 			chp = fts_children(ftsp, ch_options);
511 			display(p, chp, options);
512 
513 			if (!f_recursive && chp != NULL)
514 				(void)fts_set(ftsp, p, FTS_SKIP);
515 			break;
516 		default:
517 			break;
518 		}
519 	if (errno)
520 		err(1, "fts_read");
521 }
522 
523 /*
524  * Display() takes a linked list of FTSENT structures and passes the list
525  * along with any other necessary information to the print function.  P
526  * points to the parent directory of the display list.
527  */
528 static void
529 display(const FTSENT *p, FTSENT *list, int options)
530 {
531 	struct stat *sp;
532 	DISPLAY d;
533 	FTSENT *cur;
534 	NAMES *np;
535 	off_t maxsize;
536 	long maxblock;
537 	u_long btotal, labelstrlen, maxinode, maxlen, maxnlink;
538 	u_long maxlabelstr;
539 	int bcfile, maxflags;
540 	gid_t maxgroup;
541 	uid_t maxuser;
542 	size_t flen, ulen, glen;
543 	char *initmax;
544 	int entries, needstats;
545 	const char *user, *group;
546 	char *flags, *labelstr = NULL;
547 	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
548 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
549 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
550 
551 	needstats = f_inode || f_longform || f_size;
552 	flen = 0;
553 	btotal = 0;
554 	initmax = getenv("LS_COLWIDTHS");
555 	/* Fields match -lios order.  New ones should be added at the end. */
556 	maxlabelstr = maxblock = maxinode = maxlen = maxnlink =
557 	    maxuser = maxgroup = maxflags = maxsize = 0;
558 	if (initmax != NULL && *initmax != '\0') {
559 		char *initmax2, *jinitmax;
560 		int ninitmax;
561 
562 		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
563 		jinitmax = malloc(strlen(initmax) * 2 + 2);
564 		if (jinitmax == NULL)
565 			err(1, "malloc");
566 		initmax2 = jinitmax;
567 		if (*initmax == ':')
568 			strcpy(initmax2, "0:"), initmax2 += 2;
569 		else
570 			*initmax2++ = *initmax, *initmax2 = '\0';
571 		for (initmax++; *initmax != '\0'; initmax++) {
572 			if (initmax[-1] == ':' && initmax[0] == ':') {
573 				*initmax2++ = '0';
574 				*initmax2++ = initmax[0];
575 				initmax2[1] = '\0';
576 			} else {
577 				*initmax2++ = initmax[0];
578 				initmax2[1] = '\0';
579 			}
580 		}
581 		if (initmax2[-1] == ':')
582 			strcpy(initmax2, "0");
583 
584 		ninitmax = sscanf(jinitmax,
585 		    " %lu : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
586 		    &maxinode, &maxblock, &maxnlink, &maxuser,
587 		    &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
588 		f_notabs = 1;
589 		switch (ninitmax) {
590 		case 0:
591 			maxinode = 0;
592 			/* FALLTHROUGH */
593 		case 1:
594 			maxblock = 0;
595 			/* FALLTHROUGH */
596 		case 2:
597 			maxnlink = 0;
598 			/* FALLTHROUGH */
599 		case 3:
600 			maxuser = 0;
601 			/* FALLTHROUGH */
602 		case 4:
603 			maxgroup = 0;
604 			/* FALLTHROUGH */
605 		case 5:
606 			maxflags = 0;
607 			/* FALLTHROUGH */
608 		case 6:
609 			maxsize = 0;
610 			/* FALLTHROUGH */
611 		case 7:
612 			maxlen = 0;
613 			/* FALLTHROUGH */
614 		case 8:
615 			maxlabelstr = 0;
616 			/* FALLTHROUGH */
617 #ifdef COLORLS
618 			if (!f_color)
619 #endif
620 				f_notabs = 0;
621 			/* FALLTHROUGH */
622 		default:
623 			break;
624 		}
625 		MAKENINES(maxinode);
626 		MAKENINES(maxblock);
627 		MAKENINES(maxnlink);
628 		MAKENINES(maxsize);
629 		free(jinitmax);
630 	}
631 	bcfile = 0;
632 	flags = NULL;
633 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
634 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
635 			warnx("%s: %s",
636 			    cur->fts_name, strerror(cur->fts_errno));
637 			cur->fts_number = NO_PRINT;
638 			rval = 1;
639 			continue;
640 		}
641 		/*
642 		 * P is NULL if list is the argv list, to which different rules
643 		 * apply.
644 		 */
645 		if (p == NULL) {
646 			/* Directories will be displayed later. */
647 			if (cur->fts_info == FTS_D && !f_listdir) {
648 				cur->fts_number = NO_PRINT;
649 				continue;
650 			}
651 		} else {
652 			/* Only display dot file if -a/-A set. */
653 			if (cur->fts_name[0] == '.' && !f_listdot) {
654 				cur->fts_number = NO_PRINT;
655 				continue;
656 			}
657 		}
658 		if (cur->fts_namelen > maxlen)
659 			maxlen = cur->fts_namelen;
660 		if (f_octal || f_octal_escape) {
661 			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
662 
663 			if (t > maxlen)
664 				maxlen = t;
665 		}
666 		if (needstats) {
667 			sp = cur->fts_statp;
668 			if (sp->st_blocks > maxblock)
669 				maxblock = sp->st_blocks;
670 			if (sp->st_ino > maxinode)
671 				maxinode = sp->st_ino;
672 			if (sp->st_nlink > maxnlink)
673 				maxnlink = sp->st_nlink;
674 			if (sp->st_size > maxsize)
675 				maxsize = sp->st_size;
676 
677 			btotal += sp->st_blocks;
678 			if (f_longform) {
679 				if (f_numericonly) {
680 					(void)snprintf(nuser, sizeof(nuser),
681 					    "%u", sp->st_uid);
682 					(void)snprintf(ngroup, sizeof(ngroup),
683 					    "%u", sp->st_gid);
684 					user = nuser;
685 					group = ngroup;
686 				} else {
687 					user = user_from_uid(sp->st_uid, 0);
688 					group = group_from_gid(sp->st_gid, 0);
689 				}
690 				if ((ulen = strlen(user)) > maxuser)
691 					maxuser = ulen;
692 				if ((glen = strlen(group)) > maxgroup)
693 					maxgroup = glen;
694 				if (f_flags) {
695 					flags = fflagstostr(sp->st_flags);
696 					if (flags != NULL && *flags == '\0') {
697 						free(flags);
698 						flags = strdup("-");
699 					}
700 					if (flags == NULL)
701 						err(1, "fflagstostr");
702 					flen = strlen(flags);
703 					if (flen > (size_t)maxflags)
704 						maxflags = flen;
705 				} else
706 					flen = 0;
707 				labelstr = NULL;
708 				if (f_label) {
709 					char name[PATH_MAX + 1];
710 					mac_t label;
711 					int error;
712 
713 					error = mac_prepare_file_label(&label);
714 					if (error == -1) {
715 						warn("MAC label for %s/%s",
716 						    cur->fts_parent->fts_path,
717 						    cur->fts_name);
718 						goto label_out;
719 					}
720 
721 					if (cur->fts_level == FTS_ROOTLEVEL)
722 						snprintf(name, sizeof(name),
723 						    "%s", cur->fts_name);
724 					else
725 						snprintf(name, sizeof(name),
726 						    "%s/%s", cur->fts_parent->
727 						    fts_accpath, cur->fts_name);
728 
729 					if (options & FTS_LOGICAL)
730 						error = mac_get_file(name,
731 						    label);
732 					else
733 						error = mac_get_link(name,
734 						    label);
735 					if (error == -1) {
736 						warn("MAC label for %s/%s",
737 						    cur->fts_parent->fts_path,
738 						    cur->fts_name);
739 						mac_free(label);
740 						goto label_out;
741 					}
742 
743 					error = mac_to_text(label,
744 					    &labelstr);
745 					if (error == -1) {
746 						warn("MAC label for %s/%s",
747 						    cur->fts_parent->fts_path,
748 						    cur->fts_name);
749 						mac_free(label);
750 						goto label_out;
751 					}
752 					mac_free(label);
753 label_out:
754 					if (labelstr == NULL)
755 						labelstr = strdup("-");
756 					labelstrlen = strlen(labelstr);
757 					if (labelstrlen > maxlabelstr)
758 						maxlabelstr = labelstrlen;
759 				} else
760 					labelstrlen = 0;
761 
762 				if ((np = malloc(sizeof(NAMES) + labelstrlen +
763 				    ulen + glen + flen + 4)) == NULL)
764 					err(1, "malloc");
765 
766 				np->user = &np->data[0];
767 				(void)strcpy(np->user, user);
768 				np->group = &np->data[ulen + 1];
769 				(void)strcpy(np->group, group);
770 
771 				if (S_ISCHR(sp->st_mode) ||
772 				    S_ISBLK(sp->st_mode))
773 					bcfile = 1;
774 
775 				if (f_flags) {
776 					np->flags = &np->data[ulen + glen + 2];
777 					(void)strcpy(np->flags, flags);
778 					free(flags);
779 				}
780 				if (f_label) {
781 					np->label = &np->data[ulen + glen + 2
782 					    + (f_flags ? flen + 1 : 0)];
783 					(void)strcpy(np->label, labelstr);
784 					free(labelstr);
785 				}
786 				cur->fts_pointer = np;
787 			}
788 		}
789 		++entries;
790 	}
791 
792 	/*
793 	 * If there are no entries to display, we normally stop right
794 	 * here.  However, we must continue if we have to display the
795 	 * total block count.  In this case, we display the total only
796 	 * on the second (p != NULL) pass.
797 	 */
798 	if (!entries && (!(f_longform || f_size) || p == NULL))
799 		return;
800 
801 	d.list = list;
802 	d.entries = entries;
803 	d.maxlen = maxlen;
804 	if (needstats) {
805 		d.bcfile = bcfile;
806 		d.btotal = btotal;
807 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
808 		d.s_block = strlen(buf);
809 		d.s_flags = maxflags;
810 		d.s_label = maxlabelstr;
811 		d.s_group = maxgroup;
812 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
813 		d.s_inode = strlen(buf);
814 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
815 		d.s_nlink = strlen(buf);
816 		(void)snprintf(buf, sizeof(buf), "%ju", maxsize);
817 		d.s_size = strlen(buf);
818 		d.s_user = maxuser;
819 	}
820 	printfcn(&d);
821 	output = 1;
822 
823 	if (f_longform)
824 		for (cur = list; cur; cur = cur->fts_link)
825 			free(cur->fts_pointer);
826 }
827 
828 /*
829  * Ordering for mastercmp:
830  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
831  * as larger than directories.  Within either group, use the sort function.
832  * All other levels use the sort function.  Error entries remain unsorted.
833  */
834 static int
835 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
836 {
837 	int a_info, b_info;
838 
839 	a_info = (*a)->fts_info;
840 	if (a_info == FTS_ERR)
841 		return (0);
842 	b_info = (*b)->fts_info;
843 	if (b_info == FTS_ERR)
844 		return (0);
845 
846 	if (a_info == FTS_NS || b_info == FTS_NS)
847 		return (namecmp(*a, *b));
848 
849 	if (a_info != b_info &&
850 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
851 		if (a_info == FTS_D)
852 			return (1);
853 		if (b_info == FTS_D)
854 			return (-1);
855 	}
856 	return (sortfcn(*a, *b));
857 }
858