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