xref: /freebsd/bin/ls/ls.c (revision eb69d1f144a6fcc765d1b9d44a5ae8082353e70b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Michael Fischbein.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
44 #endif /* not lint */
45 #endif
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/mac.h>
53 
54 #include <dirent.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fts.h>
58 #include <grp.h>
59 #include <inttypes.h>
60 #include <limits.h>
61 #include <locale.h>
62 #include <pwd.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #ifdef COLORLS
68 #include <termcap.h>
69 #include <signal.h>
70 #endif
71 
72 #include "ls.h"
73 #include "extern.h"
74 
75 /*
76  * Upward approximation of the maximum number of characters needed to
77  * represent a value of integral type t as a string, excluding the
78  * NUL terminator, with provision for a sign.
79  */
80 #define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
81 
82 /*
83  * MAKENINES(n) turns n into (10**n)-1.  This is useful for converting a width
84  * into a number that wide in decimal.
85  * XXX: Overflows are not considered.
86  */
87 #define MAKENINES(n)							\
88 	do {								\
89 		intmax_t i;						\
90 									\
91 		/* Use a loop as all values of n are small. */		\
92 		for (i = 1; n > 0; i *= 10)				\
93 			n--;						\
94 		n = i - 1;						\
95 	} while(0)
96 
97 static void	 display(const FTSENT *, FTSENT *, int);
98 static int	 mastercmp(const FTSENT * const *, const FTSENT * const *);
99 static void	 traverse(int, char **, int);
100 
101 static void (*printfcn)(const DISPLAY *);
102 static int (*sortfcn)(const FTSENT *, const FTSENT *);
103 
104 long blocksize;			/* block size units */
105 int termwidth = 80;		/* default terminal width */
106 
107 /* flags */
108        int f_accesstime;	/* use time of last access */
109        int f_birthtime;		/* use time of birth */
110        int f_flags;		/* show flags associated with a file */
111        int f_humanval;		/* show human-readable file sizes */
112        int f_inode;		/* print inode */
113 static int f_kblocks;		/* print size in kilobytes */
114        int f_label;		/* show MAC label */
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 static int f_noautodot;		/* do not automatically enable -A for root */
119 static int f_nofollow;		/* don't follow symbolic link arguments */
120        int f_nonprint;		/* show unprintables as ? */
121 static int f_nosort;		/* don't sort output */
122        int f_notabs;		/* don't use tab-separated multi-col output */
123 static int f_numericonly;	/* don't convert uid/gid to name */
124        int f_octal;		/* show unprintables as \xxx */
125        int f_octal_escape;	/* like f_octal but use C escapes if possible */
126 static int f_recursive;		/* ls subdirectories also */
127 static int f_reversesort;	/* reverse whatever sort is used */
128        int f_samesort;		/* sort time and name in same direction */
129        int f_sectime;		/* print full time information */
130 static int f_singlecol;		/* use single column output */
131        int f_size;		/* list size in short listing */
132 static int f_sizesort;
133        int f_slash;		/* similar to f_type, but only for dirs */
134        int f_sortacross;	/* sort across rows, not down columns */
135        int f_statustime;	/* use time of last mode change */
136 static int f_stream;		/* stream the output, separate with commas */
137        int f_thousands;		/* show file sizes with thousands separators */
138        char *f_timeformat;	/* user-specified time format */
139 static int f_timesort;		/* sort by time vice name */
140        int f_type;		/* add type character for non-regular files */
141 static int f_whiteout;		/* show whiteout entries */
142 
143 #ifdef COLORLS
144        int f_color;		/* add type in color for non-regular files */
145 
146 char *ansi_bgcol;		/* ANSI sequence to set background colour */
147 char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
148 char *ansi_coloff;		/* ANSI sequence to reset colours */
149 char *attrs_off;		/* ANSI sequence to turn off attributes */
150 char *enter_bold;		/* ANSI sequence to set color to bold mode */
151 #endif
152 
153 static int rval;
154 
155 int
156 main(int argc, char *argv[])
157 {
158 	static char dot[] = ".", *dotav[] = {dot, NULL};
159 	struct winsize win;
160 	int ch, fts_options, notused;
161 	char *p;
162 	const char *errstr = NULL;
163 #ifdef COLORLS
164 	char termcapbuf[1024];	/* termcap definition buffer */
165 	char tcapbuf[512];	/* capability buffer */
166 	char *bp = tcapbuf;
167 #endif
168 
169 	(void)setlocale(LC_ALL, "");
170 
171 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
172 	if (isatty(STDOUT_FILENO)) {
173 		termwidth = 80;
174 		if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
175 			termwidth = strtonum(p, 0, INT_MAX, &errstr);
176 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
177 		    win.ws_col > 0)
178 			termwidth = win.ws_col;
179 		f_nonprint = 1;
180 	} else {
181 		f_singlecol = 1;
182 		/* retrieve environment variable, in case of explicit -C */
183 		p = getenv("COLUMNS");
184 		if (p)
185 			termwidth = strtonum(p, 0, INT_MAX, &errstr);
186 	}
187 
188 	if (errstr)
189 		termwidth = 80;
190 
191 	fts_options = FTS_PHYSICAL;
192 	if (getenv("LS_SAMESORT"))
193 		f_samesort = 1;
194 	while ((ch = getopt(argc, argv,
195 	    "1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuwxy,")) != -1) {
196 		switch (ch) {
197 		/*
198 		 * The -1, -C, -x and -l options all override each other so
199 		 * shell aliasing works right.
200 		 */
201 		case '1':
202 			f_singlecol = 1;
203 			f_longform = 0;
204 			f_stream = 0;
205 			break;
206 		case 'C':
207 			f_sortacross = f_longform = f_singlecol = 0;
208 			break;
209 		case 'l':
210 			f_longform = 1;
211 			f_singlecol = 0;
212 			f_stream = 0;
213 			break;
214 		case 'x':
215 			f_sortacross = 1;
216 			f_longform = 0;
217 			f_singlecol = 0;
218 			break;
219 		/* The -c, -u, and -U options override each other. */
220 		case 'c':
221 			f_statustime = 1;
222 			f_accesstime = 0;
223 			f_birthtime = 0;
224 			break;
225 		case 'u':
226 			f_accesstime = 1;
227 			f_statustime = 0;
228 			f_birthtime = 0;
229 			break;
230 		case 'U':
231 			f_birthtime = 1;
232 			f_accesstime = 0;
233 			f_statustime = 0;
234 			break;
235 		case 'f':
236 			f_nosort = 1;
237 		       /* FALLTHROUGH */
238 		case 'a':
239 			fts_options |= FTS_SEEDOT;
240 			/* FALLTHROUGH */
241 		case 'A':
242 			f_listdot = 1;
243 			break;
244 		/* The -t and -S options override each other. */
245 		case 'S':
246 			f_sizesort = 1;
247 			f_timesort = 0;
248 			break;
249 		case 't':
250 			f_timesort = 1;
251 			f_sizesort = 0;
252 			break;
253 		/* Other flags.  Please keep alphabetic. */
254 		case ',':
255 			f_thousands = 1;
256 			break;
257 		case 'B':
258 			f_nonprint = 0;
259 			f_octal = 1;
260 			f_octal_escape = 0;
261 			break;
262 		case 'D':
263 			f_timeformat = optarg;
264 			break;
265 		case 'F':
266 			f_type = 1;
267 			f_slash = 0;
268 			break;
269 		case 'G':
270 			setenv("CLICOLOR", "", 1);
271 			break;
272 		case 'H':
273 			fts_options |= FTS_COMFOLLOW;
274 			f_nofollow = 0;
275 			break;
276 		case 'I':
277 			f_noautodot = 1;
278 			break;
279 		case 'L':
280 			fts_options &= ~FTS_PHYSICAL;
281 			fts_options |= FTS_LOGICAL;
282 			f_nofollow = 0;
283 			break;
284 		case 'P':
285 			fts_options &= ~FTS_COMFOLLOW;
286 			fts_options &= ~FTS_LOGICAL;
287 			fts_options |= FTS_PHYSICAL;
288 			f_nofollow = 1;
289 			break;
290 		case 'R':
291 			f_recursive = 1;
292 			break;
293 		case 'T':
294 			f_sectime = 1;
295 			break;
296 		case 'W':
297 			f_whiteout = 1;
298 			break;
299 		case 'Z':
300 			f_label = 1;
301 			break;
302 		case 'b':
303 			f_nonprint = 0;
304 			f_octal = 0;
305 			f_octal_escape = 1;
306 			break;
307 		/* The -d option turns off the -R option. */
308 		case 'd':
309 			f_listdir = 1;
310 			f_recursive = 0;
311 			break;
312 		case 'g':	/* Compatibility with 4.3BSD. */
313 			break;
314 		case 'h':
315 			f_humanval = 1;
316 			break;
317 		case 'i':
318 			f_inode = 1;
319 			break;
320 		case 'k':
321 			f_humanval = 0;
322 			f_kblocks = 1;
323 			break;
324 		case 'm':
325 			f_stream = 1;
326 			f_singlecol = 0;
327 			f_longform = 0;
328 			break;
329 		case 'n':
330 			f_numericonly = 1;
331 			break;
332 		case 'o':
333 			f_flags = 1;
334 			break;
335 		case 'p':
336 			f_slash = 1;
337 			f_type = 1;
338 			break;
339 		case 'q':
340 			f_nonprint = 1;
341 			f_octal = 0;
342 			f_octal_escape = 0;
343 			break;
344 		case 'r':
345 			f_reversesort = 1;
346 			break;
347 		case 's':
348 			f_size = 1;
349 			break;
350 		case 'w':
351 			f_nonprint = 0;
352 			f_octal = 0;
353 			f_octal_escape = 0;
354 			break;
355 		case 'y':
356 			f_samesort = 1;
357 			break;
358 		default:
359 		case '?':
360 			usage();
361 		}
362 	}
363 	argc -= optind;
364 	argv += optind;
365 
366 	/* Root is -A automatically unless -I. */
367 	if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
368 		f_listdot = 1;
369 
370 	/* Enabling of colours is conditional on the environment. */
371 	if (getenv("CLICOLOR") &&
372 	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
373 #ifdef COLORLS
374 		if (tgetent(termcapbuf, getenv("TERM")) == 1) {
375 			ansi_fgcol = tgetstr("AF", &bp);
376 			ansi_bgcol = tgetstr("AB", &bp);
377 			attrs_off = tgetstr("me", &bp);
378 			enter_bold = tgetstr("md", &bp);
379 
380 			/* To switch colours off use 'op' if
381 			 * available, otherwise use 'oc', or
382 			 * don't do colours at all. */
383 			ansi_coloff = tgetstr("op", &bp);
384 			if (!ansi_coloff)
385 				ansi_coloff = tgetstr("oc", &bp);
386 			if (ansi_fgcol && ansi_bgcol && ansi_coloff)
387 				f_color = 1;
388 		}
389 #else
390 		warnx("color support not compiled in");
391 #endif /*COLORLS*/
392 
393 #ifdef COLORLS
394 	if (f_color) {
395 		/*
396 		 * We can't put tabs and color sequences together:
397 		 * column number will be incremented incorrectly
398 		 * for "stty oxtabs" mode.
399 		 */
400 		f_notabs = 1;
401 		(void)signal(SIGINT, colorquit);
402 		(void)signal(SIGQUIT, colorquit);
403 		parsecolors(getenv("LSCOLORS"));
404 	}
405 #endif
406 
407 	/*
408 	 * If not -F, -i, -l, -s, -S or -t options, don't require stat
409 	 * information, unless in color mode in which case we do
410 	 * need this to determine which colors to display.
411 	 */
412 	if (!f_inode && !f_longform && !f_size && !f_timesort &&
413 	    !f_sizesort && !f_type
414 #ifdef COLORLS
415 	    && !f_color
416 #endif
417 	    )
418 		fts_options |= FTS_NOSTAT;
419 
420 	/*
421 	 * If not -F, -P, -d or -l options, follow any symbolic links listed on
422 	 * the command line, unless in color mode in which case we need to
423 	 * distinguish file type for a symbolic link itself and its target.
424 	 */
425 	if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash)
426 #ifdef COLORLS
427 	    && !f_color
428 #endif
429 	    )
430 		fts_options |= FTS_COMFOLLOW;
431 
432 	/*
433 	 * If -W, show whiteout entries
434 	 */
435 #ifdef FTS_WHITEOUT
436 	if (f_whiteout)
437 		fts_options |= FTS_WHITEOUT;
438 #endif
439 
440 	/* If -i, -l or -s, figure out block size. */
441 	if (f_inode || f_longform || f_size) {
442 		if (f_kblocks)
443 			blocksize = 2;
444 		else {
445 			(void)getbsize(&notused, &blocksize);
446 			blocksize /= 512;
447 		}
448 	}
449 	/* Select a sort function. */
450 	if (f_reversesort) {
451 		if (!f_timesort && !f_sizesort)
452 			sortfcn = revnamecmp;
453 		else if (f_sizesort)
454 			sortfcn = revsizecmp;
455 		else if (f_accesstime)
456 			sortfcn = revacccmp;
457 		else if (f_birthtime)
458 			sortfcn = revbirthcmp;
459 		else if (f_statustime)
460 			sortfcn = revstatcmp;
461 		else		/* Use modification time. */
462 			sortfcn = revmodcmp;
463 	} else {
464 		if (!f_timesort && !f_sizesort)
465 			sortfcn = namecmp;
466 		else if (f_sizesort)
467 			sortfcn = sizecmp;
468 		else if (f_accesstime)
469 			sortfcn = acccmp;
470 		else if (f_birthtime)
471 			sortfcn = birthcmp;
472 		else if (f_statustime)
473 			sortfcn = statcmp;
474 		else		/* Use modification time. */
475 			sortfcn = modcmp;
476 	}
477 
478 	/* Select a print function. */
479 	if (f_singlecol)
480 		printfcn = printscol;
481 	else if (f_longform)
482 		printfcn = printlong;
483 	else if (f_stream)
484 		printfcn = printstream;
485 	else
486 		printfcn = printcol;
487 
488 	if (argc)
489 		traverse(argc, argv, fts_options);
490 	else
491 		traverse(1, dotav, fts_options);
492 	exit(rval);
493 }
494 
495 static int output;		/* If anything output. */
496 
497 /*
498  * Traverse() walks the logical directory structure specified by the argv list
499  * in the order specified by the mastercmp() comparison function.  During the
500  * traversal it passes linked lists of structures to display() which represent
501  * a superset (may be exact set) of the files to be displayed.
502  */
503 static void
504 traverse(int argc, char *argv[], int options)
505 {
506 	FTS *ftsp;
507 	FTSENT *p, *chp;
508 	int ch_options;
509 
510 	if ((ftsp =
511 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
512 		err(1, "fts_open");
513 
514 	/*
515 	 * We ignore errors from fts_children here since they will be
516 	 * replicated and signalled on the next call to fts_read() below.
517 	 */
518 	chp = fts_children(ftsp, 0);
519 	if (chp != NULL)
520 		display(NULL, chp, options);
521 	if (f_listdir)
522 		return;
523 
524 	/*
525 	 * If not recursing down this tree and don't need stat info, just get
526 	 * the names.
527 	 */
528 	ch_options = !f_recursive && !f_label &&
529 	    options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
530 
531 	while ((p = fts_read(ftsp)) != NULL)
532 		switch (p->fts_info) {
533 		case FTS_DC:
534 			warnx("%s: directory causes a cycle", p->fts_name);
535 			break;
536 		case FTS_DNR:
537 		case FTS_ERR:
538 			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
539 			rval = 1;
540 			break;
541 		case FTS_D:
542 			if (p->fts_level != FTS_ROOTLEVEL &&
543 			    p->fts_name[0] == '.' && !f_listdot)
544 				break;
545 
546 			/*
547 			 * If already output something, put out a newline as
548 			 * a separator.  If multiple arguments, precede each
549 			 * directory with its name.
550 			 */
551 			if (output) {
552 				putchar('\n');
553 				(void)printname(p->fts_path);
554 				puts(":");
555 			} else if (argc > 1) {
556 				(void)printname(p->fts_path);
557 				puts(":");
558 				output = 1;
559 			}
560 			chp = fts_children(ftsp, ch_options);
561 			display(p, chp, options);
562 
563 			if (!f_recursive && chp != NULL)
564 				(void)fts_set(ftsp, p, FTS_SKIP);
565 			break;
566 		default:
567 			break;
568 		}
569 	if (errno)
570 		err(1, "fts_read");
571 }
572 
573 /*
574  * Display() takes a linked list of FTSENT structures and passes the list
575  * along with any other necessary information to the print function.  P
576  * points to the parent directory of the display list.
577  */
578 static void
579 display(const FTSENT *p, FTSENT *list, int options)
580 {
581 	struct stat *sp;
582 	DISPLAY d;
583 	FTSENT *cur;
584 	NAMES *np;
585 	off_t maxsize;
586 	long maxblock;
587 	uintmax_t maxinode;
588 	u_long btotal, labelstrlen, maxlen, maxnlink;
589 	u_long maxlabelstr;
590 	u_int sizelen;
591 	int maxflags;
592 	gid_t maxgroup;
593 	uid_t maxuser;
594 	size_t flen, ulen, glen;
595 	char *initmax;
596 	int entries, needstats;
597 	const char *user, *group;
598 	char *flags, *labelstr = NULL;
599 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
600 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
601 
602 	needstats = f_inode || f_longform || f_size;
603 	flen = 0;
604 	btotal = 0;
605 	initmax = getenv("LS_COLWIDTHS");
606 	/* Fields match -lios order.  New ones should be added at the end. */
607 	maxlabelstr = maxblock = maxlen = maxnlink = 0;
608 	maxuser = maxgroup = maxflags = maxsize = 0;
609 	maxinode = 0;
610 	if (initmax != NULL && *initmax != '\0') {
611 		char *initmax2, *jinitmax;
612 		int ninitmax;
613 
614 		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
615 		jinitmax = malloc(strlen(initmax) * 2 + 2);
616 		if (jinitmax == NULL)
617 			err(1, "malloc");
618 		initmax2 = jinitmax;
619 		if (*initmax == ':')
620 			strcpy(initmax2, "0:"), initmax2 += 2;
621 		else
622 			*initmax2++ = *initmax, *initmax2 = '\0';
623 		for (initmax++; *initmax != '\0'; initmax++) {
624 			if (initmax[-1] == ':' && initmax[0] == ':') {
625 				*initmax2++ = '0';
626 				*initmax2++ = initmax[0];
627 				initmax2[1] = '\0';
628 			} else {
629 				*initmax2++ = initmax[0];
630 				initmax2[1] = '\0';
631 			}
632 		}
633 		if (initmax2[-1] == ':')
634 			strcpy(initmax2, "0");
635 
636 		ninitmax = sscanf(jinitmax,
637 		    " %ju : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
638 		    &maxinode, &maxblock, &maxnlink, &maxuser,
639 		    &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
640 		f_notabs = 1;
641 		switch (ninitmax) {
642 		case 0:
643 			maxinode = 0;
644 			/* FALLTHROUGH */
645 		case 1:
646 			maxblock = 0;
647 			/* FALLTHROUGH */
648 		case 2:
649 			maxnlink = 0;
650 			/* FALLTHROUGH */
651 		case 3:
652 			maxuser = 0;
653 			/* FALLTHROUGH */
654 		case 4:
655 			maxgroup = 0;
656 			/* FALLTHROUGH */
657 		case 5:
658 			maxflags = 0;
659 			/* FALLTHROUGH */
660 		case 6:
661 			maxsize = 0;
662 			/* FALLTHROUGH */
663 		case 7:
664 			maxlen = 0;
665 			/* FALLTHROUGH */
666 		case 8:
667 			maxlabelstr = 0;
668 			/* FALLTHROUGH */
669 #ifdef COLORLS
670 			if (!f_color)
671 #endif
672 				f_notabs = 0;
673 			/* FALLTHROUGH */
674 		default:
675 			break;
676 		}
677 		MAKENINES(maxinode);
678 		MAKENINES(maxblock);
679 		MAKENINES(maxnlink);
680 		MAKENINES(maxsize);
681 		free(jinitmax);
682 	}
683 	d.s_size = 0;
684 	sizelen = 0;
685 	flags = NULL;
686 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
687 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
688 			warnx("%s: %s",
689 			    cur->fts_name, strerror(cur->fts_errno));
690 			cur->fts_number = NO_PRINT;
691 			rval = 1;
692 			continue;
693 		}
694 		/*
695 		 * P is NULL if list is the argv list, to which different rules
696 		 * apply.
697 		 */
698 		if (p == NULL) {
699 			/* Directories will be displayed later. */
700 			if (cur->fts_info == FTS_D && !f_listdir) {
701 				cur->fts_number = NO_PRINT;
702 				continue;
703 			}
704 		} else {
705 			/* Only display dot file if -a/-A set. */
706 			if (cur->fts_name[0] == '.' && !f_listdot) {
707 				cur->fts_number = NO_PRINT;
708 				continue;
709 			}
710 		}
711 		if (cur->fts_namelen > maxlen)
712 			maxlen = cur->fts_namelen;
713 		if (f_octal || f_octal_escape) {
714 			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
715 
716 			if (t > maxlen)
717 				maxlen = t;
718 		}
719 		if (needstats) {
720 			sp = cur->fts_statp;
721 			if (sp->st_blocks > maxblock)
722 				maxblock = sp->st_blocks;
723 			if (sp->st_ino > maxinode)
724 				maxinode = sp->st_ino;
725 			if (sp->st_nlink > maxnlink)
726 				maxnlink = sp->st_nlink;
727 			if (sp->st_size > maxsize)
728 				maxsize = sp->st_size;
729 
730 			btotal += sp->st_blocks;
731 			if (f_longform) {
732 				if (f_numericonly) {
733 					(void)snprintf(nuser, sizeof(nuser),
734 					    "%u", sp->st_uid);
735 					(void)snprintf(ngroup, sizeof(ngroup),
736 					    "%u", sp->st_gid);
737 					user = nuser;
738 					group = ngroup;
739 				} else {
740 					user = user_from_uid(sp->st_uid, 0);
741 					group = group_from_gid(sp->st_gid, 0);
742 				}
743 				if ((ulen = strlen(user)) > maxuser)
744 					maxuser = ulen;
745 				if ((glen = strlen(group)) > maxgroup)
746 					maxgroup = glen;
747 				if (f_flags) {
748 					flags = fflagstostr(sp->st_flags);
749 					if (flags != NULL && *flags == '\0') {
750 						free(flags);
751 						flags = strdup("-");
752 					}
753 					if (flags == NULL)
754 						err(1, "fflagstostr");
755 					flen = strlen(flags);
756 					if (flen > (size_t)maxflags)
757 						maxflags = flen;
758 				} else
759 					flen = 0;
760 				labelstr = NULL;
761 				if (f_label) {
762 					char name[PATH_MAX + 1];
763 					mac_t label;
764 					int error;
765 
766 					error = mac_prepare_file_label(&label);
767 					if (error == -1) {
768 						warn("MAC label for %s/%s",
769 						    cur->fts_parent->fts_path,
770 						    cur->fts_name);
771 						goto label_out;
772 					}
773 
774 					if (cur->fts_level == FTS_ROOTLEVEL)
775 						snprintf(name, sizeof(name),
776 						    "%s", cur->fts_name);
777 					else
778 						snprintf(name, sizeof(name),
779 						    "%s/%s", cur->fts_parent->
780 						    fts_accpath, cur->fts_name);
781 
782 					if (options & FTS_LOGICAL)
783 						error = mac_get_file(name,
784 						    label);
785 					else
786 						error = mac_get_link(name,
787 						    label);
788 					if (error == -1) {
789 						warn("MAC label for %s/%s",
790 						    cur->fts_parent->fts_path,
791 						    cur->fts_name);
792 						mac_free(label);
793 						goto label_out;
794 					}
795 
796 					error = mac_to_text(label,
797 					    &labelstr);
798 					if (error == -1) {
799 						warn("MAC label for %s/%s",
800 						    cur->fts_parent->fts_path,
801 						    cur->fts_name);
802 						mac_free(label);
803 						goto label_out;
804 					}
805 					mac_free(label);
806 label_out:
807 					if (labelstr == NULL)
808 						labelstr = strdup("-");
809 					labelstrlen = strlen(labelstr);
810 					if (labelstrlen > maxlabelstr)
811 						maxlabelstr = labelstrlen;
812 				} else
813 					labelstrlen = 0;
814 
815 				if ((np = malloc(sizeof(NAMES) + labelstrlen +
816 				    ulen + glen + flen + 4)) == NULL)
817 					err(1, "malloc");
818 
819 				np->user = &np->data[0];
820 				(void)strcpy(np->user, user);
821 				np->group = &np->data[ulen + 1];
822 				(void)strcpy(np->group, group);
823 
824 				if (S_ISCHR(sp->st_mode) ||
825 				    S_ISBLK(sp->st_mode)) {
826 					sizelen = snprintf(NULL, 0,
827 					    "%#jx", (uintmax_t)sp->st_rdev);
828 					if (d.s_size < sizelen)
829 						d.s_size = sizelen;
830 				}
831 
832 				if (f_flags) {
833 					np->flags = &np->data[ulen + glen + 2];
834 					(void)strcpy(np->flags, flags);
835 					free(flags);
836 				}
837 				if (f_label) {
838 					np->label = &np->data[ulen + glen + 2
839 					    + (f_flags ? flen + 1 : 0)];
840 					(void)strcpy(np->label, labelstr);
841 					free(labelstr);
842 				}
843 				cur->fts_pointer = np;
844 			}
845 		}
846 		++entries;
847 	}
848 
849 	/*
850 	 * If there are no entries to display, we normally stop right
851 	 * here.  However, we must continue if we have to display the
852 	 * total block count.  In this case, we display the total only
853 	 * on the second (p != NULL) pass.
854 	 */
855 	if (!entries && (!(f_longform || f_size) || p == NULL))
856 		return;
857 
858 	d.list = list;
859 	d.entries = entries;
860 	d.maxlen = maxlen;
861 	if (needstats) {
862 		d.btotal = btotal;
863 		d.s_block = snprintf(NULL, 0, "%lu", howmany(maxblock, blocksize));
864 		d.s_flags = maxflags;
865 		d.s_label = maxlabelstr;
866 		d.s_group = maxgroup;
867 		d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
868 		d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
869 		sizelen = f_humanval ? HUMANVALSTR_LEN :
870 		    snprintf(NULL, 0, "%ju", maxsize);
871 		if (d.s_size < sizelen)
872 			d.s_size = sizelen;
873 		d.s_user = maxuser;
874 	}
875 	if (f_thousands)			/* make space for commas */
876 		d.s_size += (d.s_size - 1) / 3;
877 	printfcn(&d);
878 	output = 1;
879 
880 	if (f_longform)
881 		for (cur = list; cur; cur = cur->fts_link)
882 			free(cur->fts_pointer);
883 }
884 
885 /*
886  * Ordering for mastercmp:
887  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
888  * as larger than directories.  Within either group, use the sort function.
889  * All other levels use the sort function.  Error entries remain unsorted.
890  */
891 static int
892 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
893 {
894 	int a_info, b_info;
895 
896 	a_info = (*a)->fts_info;
897 	if (a_info == FTS_ERR)
898 		return (0);
899 	b_info = (*b)->fts_info;
900 	if (b_info == FTS_ERR)
901 		return (0);
902 
903 	if (a_info == FTS_NS || b_info == FTS_NS)
904 		return (namecmp(*a, *b));
905 
906 	if (a_info != b_info &&
907 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
908 		if (a_info == FTS_D)
909 			return (1);
910 		if (b_info == FTS_D)
911 			return (-1);
912 	}
913 	return (sortfcn(*a, *b));
914 }
915