xref: /freebsd/bin/ls/ls.c (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
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_timesort = 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 
570 	/* Select a sort function. */
571 	if (f_reversesort) {
572 		if (f_sizesort)
573 			sortfcn = revsizecmp;
574 		else if (f_verssort)
575 			sortfcn = revverscmp;
576 		else if (!f_timesort)
577 			sortfcn = revnamecmp;
578 		else if (f_accesstime)
579 			sortfcn = revacccmp;
580 		else if (f_birthtime)
581 			sortfcn = revbirthcmp;
582 		else if (f_statustime)
583 			sortfcn = revstatcmp;
584 		else		/* Use modification time. */
585 			sortfcn = revmodcmp;
586 	} else {
587 		if (f_sizesort)
588 			sortfcn = sizecmp;
589 		else if (f_verssort)
590 			sortfcn = verscmp;
591 		else if (!f_timesort)
592 			sortfcn = namecmp;
593 		else if (f_accesstime)
594 			sortfcn = acccmp;
595 		else if (f_birthtime)
596 			sortfcn = birthcmp;
597 		else if (f_statustime)
598 			sortfcn = statcmp;
599 		else		/* Use modification time. */
600 			sortfcn = modcmp;
601 	}
602 
603 	/* Select a print function. */
604 	if (f_singlecol)
605 		printfcn = printscol;
606 	else if (f_longform)
607 		printfcn = printlong;
608 	else if (f_stream)
609 		printfcn = printstream;
610 	else
611 		printfcn = printcol;
612 
613 	if (argc)
614 		traverse(argc, argv, fts_options);
615 	else
616 		traverse(1, dotav, fts_options);
617 	exit(rval);
618 }
619 
620 static int output;		/* If anything output. */
621 
622 /*
623  * Traverse() walks the logical directory structure specified by the argv list
624  * in the order specified by the mastercmp() comparison function.  During the
625  * traversal it passes linked lists of structures to display() which represent
626  * a superset (may be exact set) of the files to be displayed.
627  */
628 static void
629 traverse(int argc, char *argv[], int options)
630 {
631 	FTS *ftsp;
632 	FTSENT *p, *chp;
633 	int ch_options;
634 
635 	if ((ftsp =
636 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
637 		err(1, "fts_open");
638 
639 	/*
640 	 * We ignore errors from fts_children here since they will be
641 	 * replicated and signalled on the next call to fts_read() below.
642 	 */
643 	chp = fts_children(ftsp, 0);
644 	if (chp != NULL)
645 		display(NULL, chp, options);
646 	if (f_listdir)
647 		return;
648 
649 	/*
650 	 * If not recursing down this tree and don't need stat info, just get
651 	 * the names.
652 	 */
653 	ch_options = !f_recursive && !f_label &&
654 	    options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
655 
656 	while (errno = 0, (p = fts_read(ftsp)) != NULL)
657 		switch (p->fts_info) {
658 		case FTS_DC:
659 			warnx("%s: directory causes a cycle", p->fts_name);
660 			break;
661 		case FTS_DNR:
662 		case FTS_ERR:
663 			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
664 			rval = 1;
665 			break;
666 		case FTS_D:
667 			if (p->fts_level != FTS_ROOTLEVEL &&
668 			    p->fts_name[0] == '.' && !f_listdot)
669 				break;
670 
671 			/*
672 			 * If already output something, put out a newline as
673 			 * a separator.  If multiple arguments, precede each
674 			 * directory with its name.
675 			 */
676 			if (output) {
677 				putchar('\n');
678 				(void)printname(p->fts_path);
679 				puts(":");
680 			} else if (argc > 1) {
681 				(void)printname(p->fts_path);
682 				puts(":");
683 				output = 1;
684 			}
685 			chp = fts_children(ftsp, ch_options);
686 			display(p, chp, options);
687 
688 			if (!f_recursive && chp != NULL)
689 				(void)fts_set(ftsp, p, FTS_SKIP);
690 			break;
691 		default:
692 			break;
693 		}
694 	if (errno)
695 		err(1, "fts_read");
696 }
697 
698 /*
699  * Display() takes a linked list of FTSENT structures and passes the list
700  * along with any other necessary information to the print function.  P
701  * points to the parent directory of the display list.
702  */
703 static void
704 display(const FTSENT *p, FTSENT *list, int options)
705 {
706 	struct stat *sp;
707 	DISPLAY d;
708 	FTSENT *cur;
709 	NAMES *np;
710 	off_t maxsize;
711 	long maxblock;
712 	uintmax_t maxinode;
713 	u_long btotal, labelstrlen, maxlen, maxnlink;
714 	u_long maxlabelstr;
715 	u_int sizelen;
716 	int maxflags;
717 	gid_t maxgroup;
718 	uid_t maxuser;
719 	size_t flen, ulen, glen;
720 	char *initmax;
721 	int entries, needstats;
722 	const char *user, *group;
723 	char *flags, *labelstr = NULL;
724 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
725 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
726 	u_long width[9];
727 	int i;
728 
729 	needstats = f_inode || f_longform || f_size;
730 	flen = 0;
731 	btotal = 0;
732 
733 #define LS_COLWIDTHS_FIELDS	9
734 	initmax = getenv("LS_COLWIDTHS");
735 
736 	for (i = 0 ; i < LS_COLWIDTHS_FIELDS; i++)
737 		width[i] = 0;
738 
739 	if (initmax != NULL) {
740 		char *endp;
741 
742 		for (i = 0; i < LS_COLWIDTHS_FIELDS && *initmax != '\0'; i++) {
743 			if (*initmax == ':') {
744 				width[i] = 0;
745 			} else {
746 				width[i] = strtoul(initmax, &endp, 10);
747 				initmax = endp;
748 				while (isspace(*initmax))
749 					initmax++;
750 				if (*initmax != ':')
751 					break;
752 				initmax++;
753 			}
754 		}
755 		if (i < LS_COLWIDTHS_FIELDS)
756 #ifdef COLORLS
757 			if (!f_color)
758 #endif
759 				f_notabs = 0;
760 	}
761 
762 	/* Fields match -lios order.  New ones should be added at the end. */
763 	maxinode = width[0];
764 	maxblock = width[1];
765 	maxnlink = width[2];
766 	maxuser = width[3];
767 	maxgroup = width[4];
768 	maxflags = width[5];
769 	maxsize = width[6];
770 	maxlen = width[7];
771 	maxlabelstr = width[8];
772 
773 	MAKENINES(maxinode);
774 	MAKENINES(maxblock);
775 	MAKENINES(maxnlink);
776 	MAKENINES(maxsize);
777 
778 	d.s_size = 0;
779 	sizelen = 0;
780 	flags = NULL;
781 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
782 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
783 			warnx("%s: %s",
784 			    cur->fts_name, strerror(cur->fts_errno));
785 			cur->fts_number = NO_PRINT;
786 			rval = 1;
787 			continue;
788 		}
789 		/*
790 		 * P is NULL if list is the argv list, to which different rules
791 		 * apply.
792 		 */
793 		if (p == NULL) {
794 			/* Directories will be displayed later. */
795 			if (cur->fts_info == FTS_D && !f_listdir) {
796 				cur->fts_number = NO_PRINT;
797 				continue;
798 			}
799 		} else {
800 			/* Only display dot file if -a/-A set. */
801 			if (cur->fts_name[0] == '.' && !f_listdot) {
802 				cur->fts_number = NO_PRINT;
803 				continue;
804 			}
805 		}
806 		if (cur->fts_namelen > maxlen)
807 			maxlen = cur->fts_namelen;
808 		if (f_octal || f_octal_escape) {
809 			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
810 
811 			if (t > maxlen)
812 				maxlen = t;
813 		}
814 		if (needstats) {
815 			sp = cur->fts_statp;
816 			if (sp->st_blocks > maxblock)
817 				maxblock = sp->st_blocks;
818 			if (sp->st_ino > maxinode)
819 				maxinode = sp->st_ino;
820 			if (sp->st_nlink > maxnlink)
821 				maxnlink = sp->st_nlink;
822 			if (sp->st_size > maxsize)
823 				maxsize = sp->st_size;
824 
825 			btotal += sp->st_blocks;
826 			if (f_longform) {
827 				if (f_numericonly) {
828 					(void)snprintf(nuser, sizeof(nuser),
829 					    "%u", sp->st_uid);
830 					(void)snprintf(ngroup, sizeof(ngroup),
831 					    "%u", sp->st_gid);
832 					user = nuser;
833 					group = ngroup;
834 				} else {
835 					user = user_from_uid(sp->st_uid, 0);
836 					/*
837 					 * user_from_uid(..., 0) only returns
838 					 * NULL in OOM conditions.  We could
839 					 * format the uid here, but (1) in
840 					 * general ls(1) exits on OOM, and (2)
841 					 * there is another allocation/exit
842 					 * path directly below, which will
843 					 * likely exit anyway.
844 					 */
845 					if (user == NULL)
846 						err(1, "user_from_uid");
847 					group = group_from_gid(sp->st_gid, 0);
848 					/* Ditto. */
849 					if (group == NULL)
850 						err(1, "group_from_gid");
851 				}
852 				if ((ulen = strlen(user)) > maxuser)
853 					maxuser = ulen;
854 				if ((glen = strlen(group)) > maxgroup)
855 					maxgroup = glen;
856 				if (f_flags) {
857 					flags = fflagstostr(sp->st_flags);
858 					if (flags != NULL && *flags == '\0') {
859 						free(flags);
860 						flags = strdup("-");
861 					}
862 					if (flags == NULL)
863 						err(1, "fflagstostr");
864 					flen = strlen(flags);
865 					if (flen > (size_t)maxflags)
866 						maxflags = flen;
867 				} else
868 					flen = 0;
869 				labelstr = NULL;
870 				if (f_label) {
871 					char name[PATH_MAX + 1];
872 					mac_t label;
873 					int error;
874 
875 					error = mac_prepare_file_label(&label);
876 					if (error == -1) {
877 						warn("MAC label for %s/%s",
878 						    cur->fts_parent->fts_path,
879 						    cur->fts_name);
880 						goto label_out;
881 					}
882 
883 					if (cur->fts_level == FTS_ROOTLEVEL)
884 						snprintf(name, sizeof(name),
885 						    "%s", cur->fts_name);
886 					else
887 						snprintf(name, sizeof(name),
888 						    "%s/%s", cur->fts_parent->
889 						    fts_accpath, cur->fts_name);
890 
891 					if (options & FTS_LOGICAL)
892 						error = mac_get_file(name,
893 						    label);
894 					else
895 						error = mac_get_link(name,
896 						    label);
897 					if (error == -1) {
898 						warn("MAC label for %s/%s",
899 						    cur->fts_parent->fts_path,
900 						    cur->fts_name);
901 						mac_free(label);
902 						goto label_out;
903 					}
904 
905 					error = mac_to_text(label,
906 					    &labelstr);
907 					if (error == -1) {
908 						warn("MAC label for %s/%s",
909 						    cur->fts_parent->fts_path,
910 						    cur->fts_name);
911 						mac_free(label);
912 						goto label_out;
913 					}
914 					mac_free(label);
915 label_out:
916 					if (labelstr == NULL)
917 						labelstr = strdup("-");
918 					labelstrlen = strlen(labelstr);
919 					if (labelstrlen > maxlabelstr)
920 						maxlabelstr = labelstrlen;
921 				} else
922 					labelstrlen = 0;
923 
924 				if ((np = malloc(sizeof(NAMES) + labelstrlen +
925 				    ulen + glen + flen + 4)) == NULL)
926 					err(1, "malloc");
927 
928 				np->user = &np->data[0];
929 				(void)strcpy(np->user, user);
930 				np->group = &np->data[ulen + 1];
931 				(void)strcpy(np->group, group);
932 
933 				if (S_ISCHR(sp->st_mode) ||
934 				    S_ISBLK(sp->st_mode)) {
935 					sizelen = snprintf(NULL, 0,
936 					    "%#jx", (uintmax_t)sp->st_rdev);
937 					if (d.s_size < sizelen)
938 						d.s_size = sizelen;
939 				}
940 
941 				if (f_flags) {
942 					np->flags = &np->data[ulen + glen + 2];
943 					(void)strcpy(np->flags, flags);
944 					free(flags);
945 				}
946 				if (f_label) {
947 					np->label = &np->data[ulen + glen + 2
948 					    + (f_flags ? flen + 1 : 0)];
949 					(void)strcpy(np->label, labelstr);
950 					free(labelstr);
951 				}
952 				cur->fts_pointer = np;
953 			}
954 		}
955 		++entries;
956 	}
957 
958 	/*
959 	 * If there are no entries to display, we normally stop right
960 	 * here.  However, we must continue if we have to display the
961 	 * total block count.  In this case, we display the total only
962 	 * on the second (p != NULL) pass.
963 	 */
964 	if (!entries && (!(f_longform || f_size) || p == NULL))
965 		return;
966 
967 	d.list = list;
968 	d.entries = entries;
969 	d.maxlen = maxlen;
970 	if (needstats) {
971 		d.btotal = btotal;
972 		d.s_block = snprintf(NULL, 0, "%lu", howmany(maxblock, blocksize));
973 		d.s_flags = maxflags;
974 		d.s_label = maxlabelstr;
975 		d.s_group = maxgroup;
976 		d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
977 		d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
978 		sizelen = f_humanval ? HUMANVALSTR_LEN :
979 		    snprintf(NULL, 0, "%ju", maxsize);
980 		if (d.s_size < sizelen)
981 			d.s_size = sizelen;
982 		d.s_user = maxuser;
983 	}
984 	if (f_thousands)			/* make space for commas */
985 		d.s_size += (d.s_size - 1) / 3;
986 	printfcn(&d);
987 	output = 1;
988 
989 	if (f_longform)
990 		for (cur = list; cur; cur = cur->fts_link)
991 			free(cur->fts_pointer);
992 }
993 
994 /*
995  * Ordering for mastercmp:
996  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
997  * as larger than directories.  Within either group, use the sort function.
998  * All other levels use the sort function.  Error entries remain unsorted.
999  */
1000 static int
1001 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
1002 {
1003 	int a_info, b_info;
1004 
1005 	a_info = (*a)->fts_info;
1006 	if (a_info == FTS_ERR)
1007 		return (0);
1008 	b_info = (*b)->fts_info;
1009 	if (b_info == FTS_ERR)
1010 		return (0);
1011 
1012 	if (a_info == FTS_NS || b_info == FTS_NS)
1013 		return (namecmp(*a, *b));
1014 
1015 	if (a_info != b_info &&
1016 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
1017 		if (a_info == FTS_D)
1018 			return (1);
1019 		if (b_info == FTS_D)
1020 			return (-1);
1021 	}
1022 	return (sortfcn(*a, *b));
1023 }
1024