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