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