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