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