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