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