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