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