xref: /freebsd-13-stable/bin/ls/ls.c (revision 600504767528cce6b0e4f9eb44e9d4cec856abc8)
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 #include <sys/param.h>
48 #include <sys/stat.h>
49 #include <sys/ioctl.h>
50 #include <sys/mac.h>
51 
52 #include <ctype.h>
53 #include <dirent.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fts.h>
57 #include <getopt.h>
58 #include <grp.h>
59 #include <inttypes.h>
60 #include <limits.h>
61 #include <locale.h>
62 #include <pwd.h>
63 #include <stdbool.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #ifdef COLORLS
69 #include <termcap.h>
70 #include <signal.h>
71 #endif
72 
73 #include "ls.h"
74 #include "extern.h"
75 
76 /*
77  * Upward approximation of the maximum number of characters needed to
78  * represent a value of integral type t as a string, excluding the
79  * NUL terminator, with provision for a sign.
80  */
81 #define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
82 
83 /*
84  * MAKENINES(n) turns n into (10**n)-1.  This is useful for converting a width
85  * into a number that wide in decimal.
86  * XXX: Overflows are not considered.
87  */
88 #define MAKENINES(n)							\
89 	do {								\
90 		intmax_t __i;						\
91 									\
92 		/* Use a loop as all values of n are small. */		\
93 		for (__i = 1; n > 0; __i *= 10)				\
94 			n--;						\
95 		n = __i - 1;						\
96 	} while(0)
97 
98 static void	 display(const FTSENT *, FTSENT *, int);
99 static int	 mastercmp(const FTSENT * const *, const FTSENT * const *);
100 static void	 traverse(int, char **, int);
101 
102 #define	COLOR_OPT	(CHAR_MAX + 1)
103 
104 static const struct option long_opts[] =
105 {
106         {"color",       optional_argument,      NULL, COLOR_OPT},
107         {NULL,          no_argument,            NULL, 0}
108 };
109 
110 static void (*printfcn)(const DISPLAY *);
111 static int (*sortfcn)(const FTSENT *, const FTSENT *);
112 
113 long blocksize;			/* block size units */
114 int termwidth = 80;		/* default terminal width */
115 
116 /* flags */
117        int f_accesstime;	/* use time of last access */
118        int f_birthtime;		/* use time of birth */
119        int f_flags;		/* show flags associated with a file */
120        int f_humanval;		/* show human-readable file sizes */
121        int f_inode;		/* print inode */
122 static int f_kblocks;		/* print size in kilobytes */
123        int f_label;		/* show MAC label */
124 static int f_listdir;		/* list actual directory, not contents */
125 static int f_listdot;		/* list files beginning with . */
126        int f_longform;		/* long listing format */
127 static int f_noautodot;		/* do not automatically enable -A for root */
128 static int f_nofollow;		/* don't follow symbolic link arguments */
129        int f_nonprint;		/* show unprintables as ? */
130 static int f_nosort;		/* don't sort output */
131        int f_notabs;		/* don't use tab-separated multi-col output */
132 static int f_numericonly;	/* don't convert uid/gid to name */
133        int f_octal;		/* show unprintables as \xxx */
134        int f_octal_escape;	/* like f_octal but use C escapes if possible */
135 static int f_recursive;		/* ls subdirectories also */
136 static int f_reversesort;	/* reverse whatever sort is used */
137 static int f_verssort;		/* sort names using strverscmp(3) rather than strcoll(3) */
138        int f_samesort;		/* sort time and name in same direction */
139        int f_sectime;		/* print full time information */
140 static int f_singlecol;		/* use single column output */
141        int f_size;		/* list size in short listing */
142 static int f_sizesort;
143        int f_slash;		/* similar to f_type, but only for dirs */
144        int f_sortacross;	/* sort across rows, not down columns */
145        int f_statustime;	/* use time of last mode change */
146 static int f_stream;		/* stream the output, separate with commas */
147        int f_thousands;		/* show file sizes with thousands separators */
148        char *f_timeformat;	/* user-specified time format */
149 static int f_timesort;		/* sort by time vice name */
150        int f_type;		/* add type character for non-regular files */
151 static int f_whiteout;		/* show whiteout entries */
152 #ifdef COLORLS
153        int colorflag = COLORFLAG_NEVER;		/* passed in colorflag */
154        int f_color;		/* add type in color for non-regular files */
155        bool explicitansi;	/* Explicit ANSI sequences, no termcap(5) */
156 char *ansi_bgcol;		/* ANSI sequence to set background colour */
157 char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
158 char *ansi_coloff;		/* ANSI sequence to reset colours */
159 char *attrs_off;		/* ANSI sequence to turn off attributes */
160 char *enter_bold;		/* ANSI sequence to set color to bold mode */
161 char *enter_underline;		/* ANSI sequence to enter underline mode */
162 #endif
163 
164 static int rval;
165 
166 static bool
do_color_from_env(void)167 do_color_from_env(void)
168 {
169 	const char *p;
170 	bool doit;
171 
172 	doit = false;
173 	p = getenv("CLICOLOR");
174 	if (p == NULL) {
175 		/*
176 		 * COLORTERM is the more standard name for this variable.  We'll
177 		 * honor it as long as it's both set and not empty.
178 		 */
179 		p = getenv("COLORTERM");
180 		if (p != NULL && *p != '\0')
181 			doit = true;
182 	} else
183 		doit = true;
184 
185 	return (doit &&
186 	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")));
187 }
188 
189 static bool
do_color(void)190 do_color(void)
191 {
192 
193 #ifdef COLORLS
194 	if (colorflag == COLORFLAG_NEVER)
195 		return (false);
196 	else if (colorflag == COLORFLAG_ALWAYS)
197 		return (true);
198 #endif
199 	return (do_color_from_env());
200 }
201 
202 #ifdef COLORLS
203 static bool
do_color_always(const char * term)204 do_color_always(const char *term)
205 {
206 
207 	return (strcmp(term, "always") == 0 || strcmp(term, "yes") == 0 ||
208 	    strcmp(term, "force") == 0);
209 }
210 
211 static bool
do_color_never(const char * term)212 do_color_never(const char *term)
213 {
214 
215 	return (strcmp(term, "never") == 0 || strcmp(term, "no") == 0 ||
216 	    strcmp(term, "none") == 0);
217 }
218 
219 static bool
do_color_auto(const char * term)220 do_color_auto(const char *term)
221 {
222 
223 	return (strcmp(term, "auto") == 0 || strcmp(term, "tty") == 0 ||
224 	    strcmp(term, "if-tty") == 0);
225 }
226 #endif	/* COLORLS */
227 
228 int
main(int argc,char * argv[])229 main(int argc, char *argv[])
230 {
231 	static char dot[] = ".", *dotav[] = {dot, NULL};
232 	struct winsize win;
233 	int ch, fts_options, notused;
234 	char *p;
235 	const char *errstr = NULL;
236 #ifdef COLORLS
237 	char termcapbuf[1024];	/* termcap definition buffer */
238 	char tcapbuf[512];	/* capability buffer */
239 	char *bp = tcapbuf, *term;
240 #endif
241 
242 	(void)setlocale(LC_ALL, "");
243 
244 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
245 	if (isatty(STDOUT_FILENO)) {
246 		termwidth = 80;
247 		if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
248 			termwidth = strtonum(p, 0, INT_MAX, &errstr);
249 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
250 		    win.ws_col > 0)
251 			termwidth = win.ws_col;
252 		f_nonprint = 1;
253 	} else {
254 		f_singlecol = 1;
255 		/* retrieve environment variable, in case of explicit -C */
256 		p = getenv("COLUMNS");
257 		if (p)
258 			termwidth = strtonum(p, 0, INT_MAX, &errstr);
259 	}
260 
261 	if (errstr)
262 		termwidth = 80;
263 
264 	fts_options = FTS_PHYSICAL;
265 	if (getenv("LS_SAMESORT"))
266 		f_samesort = 1;
267 
268 	/*
269 	 * For historical compatibility, we'll use our autodetection if CLICOLOR
270 	 * is set.
271 	 */
272 #ifdef COLORLS
273 	if (getenv("CLICOLOR"))
274 		colorflag = COLORFLAG_AUTO;
275 #endif
276 	while ((ch = getopt_long(argc, argv,
277 	    "+1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuvwxy,", long_opts,
278 	    NULL)) != -1) {
279 		switch (ch) {
280 		/*
281 		 * The -1, -C, -x and -l options all override each other so
282 		 * shell aliasing works right.
283 		 */
284 		case '1':
285 			f_singlecol = 1;
286 			f_longform = 0;
287 			f_stream = 0;
288 			break;
289 		case 'C':
290 			f_sortacross = f_longform = f_singlecol = 0;
291 			break;
292 		case 'l':
293 			f_longform = 1;
294 			f_singlecol = 0;
295 			f_stream = 0;
296 			break;
297 		case 'x':
298 			f_sortacross = 1;
299 			f_longform = 0;
300 			f_singlecol = 0;
301 			break;
302 		/* The -c, -u, and -U options override each other. */
303 		case 'c':
304 			f_statustime = 1;
305 			f_accesstime = 0;
306 			f_birthtime = 0;
307 			break;
308 		case 'u':
309 			f_accesstime = 1;
310 			f_statustime = 0;
311 			f_birthtime = 0;
312 			break;
313 		case 'U':
314 			f_birthtime = 1;
315 			f_accesstime = 0;
316 			f_statustime = 0;
317 			break;
318 		case 'f':
319 			f_nosort = 1;
320 		       /* FALLTHROUGH */
321 		case 'a':
322 			fts_options |= FTS_SEEDOT;
323 			/* FALLTHROUGH */
324 		case 'A':
325 			f_listdot = 1;
326 			break;
327 		/* The -t and -S options override each other. */
328 		case 'S':
329 			f_sizesort = 1;
330 			f_timesort = 0;
331 			break;
332 		case 't':
333 			f_timesort = 1;
334 			f_sizesort = 0;
335 			break;
336 		/* Other flags.  Please keep alphabetic. */
337 		case ',':
338 			f_thousands = 1;
339 			break;
340 		case 'B':
341 			f_nonprint = 0;
342 			f_octal = 1;
343 			f_octal_escape = 0;
344 			break;
345 		case 'D':
346 			f_timeformat = optarg;
347 			break;
348 		case 'F':
349 			f_type = 1;
350 			f_slash = 0;
351 			break;
352 		case 'G':
353 			/*
354 			 * We both set CLICOLOR here and set colorflag to
355 			 * COLORFLAG_AUTO, because -G should not force color if
356 			 * stdout isn't a tty.
357 			 */
358 			setenv("CLICOLOR", "", 1);
359 #ifdef COLORLS
360 			colorflag = COLORFLAG_AUTO;
361 #endif
362 			break;
363 		case 'H':
364 			fts_options |= FTS_COMFOLLOW;
365 			f_nofollow = 0;
366 			break;
367 		case 'I':
368 			f_noautodot = 1;
369 			break;
370 		case 'L':
371 			fts_options &= ~FTS_PHYSICAL;
372 			fts_options |= FTS_LOGICAL;
373 			f_nofollow = 0;
374 			break;
375 		case 'P':
376 			fts_options &= ~FTS_COMFOLLOW;
377 			fts_options &= ~FTS_LOGICAL;
378 			fts_options |= FTS_PHYSICAL;
379 			f_nofollow = 1;
380 			break;
381 		case 'R':
382 			f_recursive = 1;
383 			break;
384 		case 'T':
385 			f_sectime = 1;
386 			break;
387 		case 'W':
388 			f_whiteout = 1;
389 			break;
390 		case 'Z':
391 			f_label = 1;
392 			break;
393 		case 'b':
394 			f_nonprint = 0;
395 			f_octal = 0;
396 			f_octal_escape = 1;
397 			break;
398 		/* The -d option turns off the -R option. */
399 		case 'd':
400 			f_listdir = 1;
401 			f_recursive = 0;
402 			break;
403 		case 'g':	/* Compatibility with 4.3BSD. */
404 			break;
405 		case 'h':
406 			f_humanval = 1;
407 			break;
408 		case 'i':
409 			f_inode = 1;
410 			break;
411 		case 'k':
412 			f_humanval = 0;
413 			f_kblocks = 1;
414 			break;
415 		case 'm':
416 			f_stream = 1;
417 			f_singlecol = 0;
418 			f_longform = 0;
419 			break;
420 		case 'n':
421 			f_numericonly = 1;
422 			break;
423 		case 'o':
424 			f_flags = 1;
425 			break;
426 		case 'p':
427 			f_slash = 1;
428 			f_type = 1;
429 			break;
430 		case 'q':
431 			f_nonprint = 1;
432 			f_octal = 0;
433 			f_octal_escape = 0;
434 			break;
435 		case 'r':
436 			f_reversesort = 1;
437 			break;
438 		case 's':
439 			f_size = 1;
440 			break;
441 		case 'v':
442 			f_verssort = 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
traverse(int argc,char * argv[],int options)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
display(const FTSENT * p,FTSENT * list,int options)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, f_thousands ? "%'ld" : "%ld",
972 		    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
mastercmp(const FTSENT * const * a,const FTSENT * const * b)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