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