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