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