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