xref: /dragonfly/bin/ls/ls.c (revision 5ca0a96d6c3bf50926197b4bb92af7969ed3528a)
1 /*-
2  * Copyright (c) 1989, 1993, 1994
3  *        The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Michael Fischbein.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#) Copyright (c) 1989, 1993, 1994 The Regents of the University of California.  All rights reserved.
33  * @(#)ls.c         8.5 (Berkeley) 4/2/94
34  * $FreeBSD: src/bin/ls/ls.c,v 1.78 2004/06/08 09:30:10 das Exp $
35  */
36 
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <sys/ioctl.h>
40 
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fts.h>
45 #include <grp.h>
46 #include <inttypes.h>
47 #include <limits.h>
48 #include <locale.h>
49 #include <pwd.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #ifdef COLORLS
55 #include <termcap.h>
56 #include <signal.h>
57 #endif
58 
59 #include "ls.h"
60 #include "extern.h"
61 
62 /*
63  * Upward approximation of the maximum number of characters needed to
64  * represent a value of integral type t as a string, excluding the
65  * NUL terminator, with provision for a sign.
66  */
67 #define   STRBUF_SIZEOF(t)    (1 + CHAR_BIT * sizeof(t) / 3 + 1)
68 
69 /*
70  * MAKENINES(n) turns n into (10**n)-1.  This is useful for converting a width
71  * into a number that wide in decimal.
72  * XXX: Overflows are not considered.
73  */
74 #define MAKENINES(n)                                                                      \
75           do {                                                                            \
76                     intmax_t i;                                                           \
77                                                                                           \
78                     /* Use a loop as all values of n are small. */              \
79                     for (i = 1; n > 0; i *= 10)                                 \
80                               n--;                                                        \
81                     n = i - 1;                                                            \
82           } while(0)
83 
84 static void          display(const FTSENT *, FTSENT *);
85 static int           mastercmp(const FTSENT * const *, const FTSENT * const *);
86 static void          traverse(int, char **, int);
87 
88 static void (*printfcn)(const DISPLAY *);
89 static int (*sortfcn)(const FTSENT *, const FTSENT *);
90 
91 long blocksize;                         /* block size units */
92 int termwidth = 80;           /* default terminal width */
93 
94 /* flags */
95        int f_accesstime;      /* use time of last access */
96        int f_flags;           /* show flags associated with a file */
97        int f_humanval;                  /* show human-readable file sizes */
98        int f_inode;           /* print inode */
99 static int f_kblocks;                   /* print size in kilobytes */
100 static int f_listdir;                   /* list actual directory, not contents */
101 static int f_listdot;                   /* list files beginning with . */
102        int f_longform;                  /* long listing format */
103        int f_nanotime;                  /* include nanotime in long format */
104        int f_nonprint;                  /* show unprintables as ? */
105 static int f_nosort;                    /* don't sort output */
106        int f_notabs;                    /* don't use tab-separated multi-col output */
107 static int f_numericonly;     /* don't convert uid/gid to name */
108        int f_octal;           /* show unprintables as \xxx */
109        int f_octal_escape;    /* like f_octal but use C escapes if possible */
110 static int f_recursive;                 /* ls subdirectories also */
111 static int f_reversesort;     /* reverse whatever sort is used */
112        int f_sectime;                   /* print the real time for all files */
113 static int f_singlecol;                 /* use single column output */
114        int f_size;            /* list size in short listing */
115 static int f_sizesort;                  /* Sort by size */
116        int f_slash;           /* similar to f_type, but only for dirs */
117        int f_sortacross;      /* sort across rows, not down columns */
118        int f_statustime;      /* use time of last mode change */
119 static int f_stream;                    /* stream the output, separate with commas */
120        const char *f_timeformat;        /* user-specified time format */
121 static int f_timesort;                  /* sort by time vice name */
122        int f_type;            /* add type character for non-regular files */
123 static int f_whiteout;                  /* show whiteout entries */
124 #ifdef COLORLS
125        int f_color;           /* add type in color for non-regular files */
126 
127 char *ansi_bgcol;             /* ANSI sequence to set background colour */
128 char *ansi_fgcol;             /* ANSI sequence to set foreground colour */
129 char *ansi_coloff;            /* ANSI sequence to reset colours */
130 char *attrs_off;              /* ANSI sequence to turn off attributes */
131 char *enter_bold;             /* ANSI sequence to set color to bold mode */
132 #endif
133 
134 static int rval;
135 
136 int
main(int argc,char * argv[])137 main(int argc, char *argv[])
138 {
139           static char dot[] = ".", *dotav[] = {dot, NULL};
140           struct winsize win;
141           int ch, fts_options, notused;
142           char *p;
143           const char nanotime_format[] = "%Y-%m-%d %H:%M:%S";
144 #ifdef COLORLS
145           char termcapbuf[1024];        /* termcap definition buffer */
146           char tcapbuf[512];  /* capability buffer */
147           char *bp = tcapbuf;
148 #endif
149 
150           setlocale(LC_ALL, "");
151 
152           /* Terminal defaults to -Cq, non-terminal defaults to -1. */
153           if (isatty(STDOUT_FILENO)) {
154                     termwidth = 80;
155                     if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
156                               termwidth = atoi(p);
157                     else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
158                         win.ws_col > 0)
159                               termwidth = win.ws_col;
160                     f_nonprint = 1;
161           } else {
162                     f_singlecol = 1;
163                     /* retrieve environment variable, in case of explicit -C */
164                     p = getenv("COLUMNS");
165                     if (p)
166                               termwidth = atoi(p);
167           }
168 
169           /*
170            * Root is -A automatically.  Turn off if -I specified.
171            */
172           if (getuid() == 0)
173                     f_listdot = 1;
174 
175           fts_options = FTS_PHYSICAL;
176           while ((ch = getopt(argc, argv,
177               "1ABCD:FGHILPRSTW_abcdfghiklmnopqrstuwx")) != -1) {
178                     switch (ch) {
179                     /*
180                      * The -1, -C, -x and -l options all override each other so
181                      * shell aliasing works right.
182                      */
183                     case '1':
184                               f_singlecol = 1;
185                               f_longform = 0;
186                               f_stream = 0;
187                               break;
188                     case 'B':
189                               f_nonprint = 0;
190                               f_octal = 1;
191                               f_octal_escape = 0;
192                               break;
193                     case 'C':
194                               f_sortacross = f_longform = f_singlecol = 0;
195                               break;
196                     case 'l':
197                               f_longform = 1;
198                               f_singlecol = 0;
199                               f_stream = 0;
200                               break;
201                     case 'x':
202                               f_sortacross = 1;
203                               f_longform = 0;
204                               f_singlecol = 0;
205                               break;
206                     /* The -c and -u options override each other. */
207                     case 'c':
208                               f_statustime = 1;
209                               f_accesstime = 0;
210                               break;
211                     case 'u':
212                               f_accesstime = 1;
213                               f_statustime = 0;
214                               break;
215                     case 'D':
216                               f_timeformat = optarg;
217                               break;
218                     case 'F':
219                               f_type = 1;
220                               f_slash = 0;
221                               break;
222                     case 'H':
223                               fts_options |= FTS_COMFOLLOW;
224                               break;
225                     case 'I':
226                               f_listdot = 0;
227                               break;
228                     case 'G':
229                               if (setenv("CLICOLOR", "", 1) != 0)
230                                         warn("setenv: cannot set CLICOLOR");
231                               break;
232                     case 'L':
233                               fts_options &= ~FTS_PHYSICAL;
234                               fts_options |= FTS_LOGICAL;
235                               break;
236                     case 'P':
237                               fts_options &= ~FTS_COMFOLLOW;
238                               fts_options &= ~FTS_LOGICAL;
239                               fts_options |= FTS_PHYSICAL;
240                               break;
241                     case 'R':
242                               f_recursive = 1;
243                               break;
244                     /* The -t and -S options override each other. */
245                     case 'S':
246                               f_sizesort = 1;
247                               f_timesort = 0;
248                               break;
249                     case 't':
250                               f_timesort = 1;
251                               f_sizesort = 0;
252                               break;
253                     case 'f':
254                               f_nosort = 1;
255                               /* FALLTHROUGH */
256                     case 'a':
257                               fts_options |= FTS_SEEDOT;
258                               /* FALLTHROUGH */
259                     case 'A':
260                               f_listdot = 1;
261                               break;
262                     /* The -d option turns off the -R option. */
263                     case 'd':
264                               f_listdir = 1;
265                               f_recursive = 0;
266                               break;
267                     case 'g': /* Compatibility with 4.3BSD. */
268                               break;
269                     case 'h':
270                               f_humanval = 1;
271                               break;
272                     case 'i':
273                               f_inode = 1;
274                               break;
275                     case 'k':
276                               f_humanval = 0;
277                               f_kblocks = 1;
278                               break;
279                     case 'm':
280                               f_stream = 1;
281                               f_singlecol = 0;
282                               f_longform = 0;
283                               break;
284                     case 'n':
285                               f_numericonly = 1;
286                               break;
287                     case 'o':
288                               f_flags = 1;
289                               break;
290                     case 'p':
291                               f_slash = 1;
292                               f_type = 1;
293                               break;
294                     case 'q':
295                               f_nonprint = 1;
296                               f_octal = 0;
297                               f_octal_escape = 0;
298                               break;
299                     case 'r':
300                               f_reversesort = 1;
301                               break;
302                     case 's':
303                               f_size = 1;
304                               break;
305                     case 'T':
306                               f_sectime = 1;
307                               break;
308                     case 'W':
309                               f_whiteout = 1;
310                               break;
311                     case 'b':
312                               f_nonprint = 0;
313                               f_octal = 0;
314                               f_octal_escape = 1;
315                               break;
316                     case 'w':
317                               f_nonprint = 0;
318                               f_octal = 0;
319                               f_octal_escape = 0;
320                               break;
321                     case '_':
322                               f_nanotime = 1;
323                               f_timeformat = nanotime_format;
324                               break;
325                     default:
326                     case '?':
327                               usage();
328                     }
329           }
330           argc -= optind;
331           argv += optind;
332 
333           /* Enabling of colours is conditional on the environment. */
334           if (getenv("CLICOLOR") &&
335               (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
336 #ifdef COLORLS
337                     if (tgetent(termcapbuf, getenv("TERM")) == 1) {
338                               ansi_fgcol = tgetstr("AF", &bp);
339                               ansi_bgcol = tgetstr("AB", &bp);
340                               attrs_off = tgetstr("me", &bp);
341                               enter_bold = tgetstr("md", &bp);
342 
343                               /* To switch colours off use 'op' if
344                                * available, otherwise use 'oc', or
345                                * don't do colours at all. */
346                               ansi_coloff = tgetstr("op", &bp);
347                               if (!ansi_coloff)
348                                         ansi_coloff = tgetstr("oc", &bp);
349                               if (ansi_fgcol && ansi_bgcol && ansi_coloff)
350                                         f_color = 1;
351                     }
352 #else
353                     fprintf(stderr, "Color support not compiled in.\n");
354 #endif /*COLORLS*/
355 
356 #ifdef COLORLS
357           if (f_color) {
358                     /*
359                      * We can't put tabs and color sequences together:
360                      * column number will be incremented incorrectly
361                      * for "stty oxtabs" mode.
362                      */
363                     f_notabs = 1;
364                     signal(SIGINT, colorquit);
365                     signal(SIGQUIT, colorquit);
366                     parsecolors(getenv("LSCOLORS"));
367           }
368 #endif
369 
370           /*
371            * If not -F, -i, -l, -s, -S or -t options, don't require stat
372            * information, unless in color mode in which case we do
373            * need this to determine which colors to display.
374            */
375           if (!f_inode && !f_longform && !f_size && !f_timesort &&
376               !f_sizesort && !f_type
377 #ifdef COLORLS
378               && !f_color
379 #endif
380               )
381                     fts_options |= FTS_NOSTAT;
382 
383           /*
384            * If not -F, -d or -l options, follow any symbolic links listed on
385            * the command line.
386            */
387           if (!f_longform && !f_listdir && !f_type)
388                     fts_options |= FTS_COMFOLLOW;
389 
390           /*
391            * If -W, show whiteout entries
392            */
393 #ifdef FTS_WHITEOUT
394           if (f_whiteout)
395                     fts_options |= FTS_WHITEOUT;
396 #endif
397 
398           /* If -l or -s, figure out block size. */
399           if (f_longform || f_size) {
400                     if (f_kblocks)
401                               blocksize = 2;
402                     else {
403                               getbsize(&notused, &blocksize);
404                               blocksize /= 512;
405                     }
406           }
407           /* Select a sort function. */
408           if (f_reversesort) {
409                     if (!f_timesort && !f_sizesort)
410                               sortfcn = revnamecmp;
411                     else if (f_sizesort)
412                               sortfcn = revsizecmp;
413                     else if (f_accesstime)
414                               sortfcn = revacccmp;
415                     else if (f_statustime)
416                               sortfcn = revstatcmp;
417                     else                /* Use modification time. */
418                               sortfcn = revmodcmp;
419           } else {
420                     if (!f_timesort && !f_sizesort)
421                               sortfcn = namecmp;
422                     else if (f_sizesort)
423                               sortfcn = sizecmp;
424                     else if (f_accesstime)
425                               sortfcn = acccmp;
426                     else if (f_statustime)
427                               sortfcn = statcmp;
428                     else                /* Use modification time. */
429                               sortfcn = modcmp;
430           }
431 
432           /* Select a print function. */
433           if (f_singlecol)
434                     printfcn = printscol;
435           else if (f_longform)
436                     printfcn = printlong;
437           else if (f_stream)
438                     printfcn = printstream;
439           else
440                     printfcn = printcol;
441 
442           if (argc)
443                     traverse(argc, argv, fts_options);
444           else
445                     traverse(1, dotav, fts_options);
446           exit(rval);
447 }
448 
449 static int output;            /* If anything output. */
450 
451 /*
452  * Traverse() walks the logical directory structure specified by the argv list
453  * in the order specified by the mastercmp() comparison function.  During the
454  * traversal it passes linked lists of structures to display() which represent
455  * a superset (may be exact set) of the files to be displayed.
456  */
457 static void
traverse(int argc,char * argv[],int options)458 traverse(int argc, char *argv[], int options)
459 {
460           FTS *ftsp;
461           FTSENT *p, *chp;
462           int ch_options, error;
463 
464           if ((ftsp =
465               fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
466                     err(1, "fts_open");
467 
468           /*
469            * We ignore errors from fts_children here since they will be
470            * replicated and signalled on the next call to fts_read() below.
471            */
472           chp = fts_children(ftsp, 0);
473           if (chp != NULL)
474                     display(NULL, chp);
475           if (f_listdir) {
476                     fts_close(ftsp);
477                     return;
478           }
479 
480           /*
481            * If not recursing down this tree and don't need stat info, just get
482            * the names.
483            */
484           ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
485 
486           while ((p = fts_read(ftsp)) != NULL)
487                     switch (p->fts_info) {
488                     case FTS_DC:
489                               warnx("%s: directory causes a cycle", p->fts_name);
490                               break;
491                     case FTS_DNR:
492                     case FTS_ERR:
493                               warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
494                               rval = 1;
495                               break;
496                     case FTS_D:
497                               if (p->fts_level != FTS_ROOTLEVEL &&
498                                   p->fts_name[0] == '.' && !f_listdot)
499                                         break;
500 
501                               /*
502                                * If already output something, put out a newline as
503                                * a separator.  If multiple arguments, precede each
504                                * directory with its name.
505                                */
506                               if (output) {
507                                         putchar('\n');
508                                         printname(p->fts_path);
509                                         puts(":");
510                               } else if (argc > 1) {
511                                         printname(p->fts_path);
512                                         puts(":");
513                                         output = 1;
514                               }
515                               chp = fts_children(ftsp, ch_options);
516                               display(p, chp);
517 
518                               if (!f_recursive && chp != NULL)
519                                         fts_set(ftsp, p, FTS_SKIP);
520                               break;
521                     default:
522                               break;
523                     }
524           error = errno;
525           fts_close(ftsp);
526           errno = error;
527           if (errno)
528                     err(1, "fts_read");
529 }
530 
531 /*
532  * Display() takes a linked list of FTSENT structures and passes the list
533  * along with any other necessary information to the print function.  P
534  * points to the parent directory of the display list.
535  */
536 static void
display(const FTSENT * p,FTSENT * list)537 display(const FTSENT *p, FTSENT *list)
538 {
539           struct stat *sp;
540           DISPLAY d;
541           FTSENT *cur;
542           NAMES *np;
543           off_t maxsize;
544           u_long btotal, maxlen;
545           int64_t maxblock;
546           ino_t maxinode;
547           nlink_t maxnlink;
548           int bcfile, maxflags;
549           gid_t maxgroup;
550           uid_t maxuser;
551           size_t flen, ulen, glen;
552           char *initmax;
553           int entries, needstats;
554           const char *user, *group;
555           char *flags;
556           char buf[STRBUF_SIZEOF(u_quad_t) + 1];
557           char ngroup[STRBUF_SIZEOF(uid_t) + 1];
558           char nuser[STRBUF_SIZEOF(gid_t) + 1];
559 
560           needstats = f_inode || f_longform || f_size;
561           btotal = 0;
562           initmax = getenv("LS_COLWIDTHS");
563           /* Fields match -lios order.  New ones should be added at the end. */
564           maxblock = maxinode = maxlen = maxnlink =
565               maxuser = maxgroup = maxflags = maxsize = 0;
566           if (initmax != NULL && *initmax != '\0') {
567                     char *initmax2, *jinitmax;
568                     int ninitmax;
569 
570                     /* Fill-in "::" as "0:0:0" for the sake of scanf. */
571                     jinitmax = malloc(strlen(initmax) * 2 + 2);
572                     if (jinitmax == NULL)
573                               err(1, "malloc");
574                     initmax2 = jinitmax;
575                     if (*initmax == ':')
576                               strcpy(initmax2, "0:"), initmax2 += 2;
577                     else
578                               *initmax2++ = *initmax, *initmax2 = '\0';
579                     for (initmax++; *initmax != '\0'; initmax++) {
580                               if (initmax[-1] == ':' && initmax[0] == ':') {
581                                         *initmax2++ = '0';
582                                         *initmax2++ = initmax[0];
583                                         initmax2[1] = '\0';
584                               } else {
585                                         *initmax2++ = initmax[0];
586                                         initmax2[1] = '\0';
587                               }
588                     }
589                     if (initmax2[-1] == ':')
590                               strcpy(initmax2, "0");
591 
592                     ninitmax = sscanf(jinitmax,
593                         " %ju : %jd : %u : %i : %i : %i : %jd : %lu ",
594                         &maxinode, &maxblock, &maxnlink, &maxuser,
595                         &maxgroup, &maxflags, &maxsize, &maxlen);
596                     f_notabs = 1;
597                     switch (ninitmax) {
598                     case 0:
599                               maxinode = 0;
600                               /* FALLTHROUGH */
601                     case 1:
602                               maxblock = 0;
603                               /* FALLTHROUGH */
604                     case 2:
605                               maxnlink = 0;
606                               /* FALLTHROUGH */
607                     case 3:
608                               maxuser = 0;
609                               /* FALLTHROUGH */
610                     case 4:
611                               maxgroup = 0;
612                               /* FALLTHROUGH */
613                     case 5:
614                               maxflags = 0;
615                               /* FALLTHROUGH */
616                     case 6:
617                               maxsize = 0;
618                               /* FALLTHROUGH */
619                     case 7:
620                               maxlen = 0;
621                               /* FALLTHROUGH */
622 #ifdef COLORLS
623                               if (!f_color)
624 #endif
625                                         f_notabs = 0;
626                               /* FALLTHROUGH */
627                     default:
628                               break;
629                     }
630                     MAKENINES(maxinode);
631                     MAKENINES(maxblock);
632                     MAKENINES(maxnlink);
633                     MAKENINES(maxsize);
634                     free(jinitmax);
635           }
636           bcfile = 0;
637           flags = NULL;
638           for (cur = list, entries = 0; cur; cur = cur->fts_link) {
639                     if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
640                               warnx("%s: %s",
641                                   cur->fts_name, strerror(cur->fts_errno));
642                               cur->fts_number = NO_PRINT;
643                               rval = 1;
644                               continue;
645                     }
646                     /*
647                      * P is NULL if list is the argv list, to which different rules
648                      * apply.
649                      */
650                     if (p == NULL) {
651                               /* Directories will be displayed later. */
652                               if (cur->fts_info == FTS_D && !f_listdir) {
653                                         cur->fts_number = NO_PRINT;
654                                         continue;
655                               }
656                     } else {
657                               /* Only display dot file if -a/-A set. */
658                               if (cur->fts_name[0] == '.' && !f_listdot) {
659                                         cur->fts_number = NO_PRINT;
660                                         continue;
661                               }
662                     }
663                     if (cur->fts_namelen > maxlen)
664                               maxlen = cur->fts_namelen;
665                     if (f_octal || f_octal_escape) {
666                               u_long t = len_octal(cur->fts_name, cur->fts_namelen);
667 
668                               if (t > maxlen)
669                                         maxlen = t;
670                     }
671                     if (needstats) {
672                               sp = cur->fts_statp;
673                               if (sp->st_blocks > maxblock)
674                                         maxblock = sp->st_blocks;
675                               if (sp->st_ino > maxinode)
676                                         maxinode = sp->st_ino;
677                               if (sp->st_nlink > maxnlink)
678                                         maxnlink = sp->st_nlink;
679                               if (sp->st_size > maxsize)
680                                         maxsize = sp->st_size;
681 
682                               btotal += sp->st_blocks;
683                               if (f_longform) {
684                                         if (f_numericonly) {
685                                                   snprintf(nuser, sizeof(nuser),
686                                                       "%u", sp->st_uid);
687                                                   snprintf(ngroup, sizeof(ngroup),
688                                                       "%u", sp->st_gid);
689                                                   user = nuser;
690                                                   group = ngroup;
691                                         } else {
692                                                   user = user_from_uid(sp->st_uid, 0);
693                                                   group = group_from_gid(sp->st_gid, 0);
694                                         }
695                                         if ((ulen = strlen(user)) > maxuser)
696                                                   maxuser = ulen;
697                                         if ((glen = strlen(group)) > maxgroup)
698                                                   maxgroup = glen;
699                                         if (f_flags) {
700                                                   flags = fflagstostr(sp->st_flags);
701                                                   if (flags != NULL && *flags == '\0') {
702                                                             free(flags);
703                                                             flags = strdup("-");
704                                                   }
705                                                   if (flags == NULL)
706                                                             err(1, "flagstostr");
707                                                   flen = strlen(flags);
708                                                   if (flen > (size_t)maxflags)
709                                                             maxflags = flen;
710                                         } else {
711                                                   flen = 0;
712                                         }
713 
714                                         if ((np = malloc(sizeof(NAMES) +
715                                             ulen + glen + flen + 3)) == NULL)
716                                                   err(1, "malloc");
717 
718                                         np->user = &np->data[0];
719                                         strcpy(np->user, user);
720                                         np->group = &np->data[ulen + 1];
721                                         strcpy(np->group, group);
722 
723                                         if (S_ISCHR(sp->st_mode) ||
724                                             S_ISBLK(sp->st_mode))
725                                                   bcfile = 1;
726 
727                                         if (f_flags) {
728                                                   np->flags = &np->data[ulen + glen + 2];
729                                                   strcpy(np->flags, flags);
730                                                   free(flags);
731                                         }
732                                         cur->fts_pointer = np;
733                               }
734                     }
735                     ++entries;
736           }
737 
738           /*
739            * If there are no entries to display, we normally stop right
740            * here.  However, we must continue if we have to display the
741            * total block count.  In this case, we display the total only
742            * on the second (p != NULL) pass.
743            */
744           if (!entries && (!(f_longform || f_size) || p == NULL))
745                     return;
746 
747           d.list = list;
748           d.entries = entries;
749           d.maxlen = maxlen;
750           if (needstats) {
751                     d.bcfile = bcfile;
752                     d.btotal = btotal;
753                     snprintf(buf, sizeof(buf), "%ji", (intmax_t)maxblock);
754                     d.s_block = strlen(buf);
755                     d.s_flags = maxflags;
756                     d.s_group = maxgroup;
757                     snprintf(buf, sizeof(buf), "%ju", (uintmax_t)maxinode);
758                     d.s_inode = strlen(buf);
759                     snprintf(buf, sizeof(buf), "%u", maxnlink);
760                     d.s_nlink = strlen(buf);
761                     snprintf(buf, sizeof(buf), "%jd", (intmax_t)maxsize);
762                     d.s_size = strlen(buf);
763                     d.s_user = maxuser;
764           }
765           printfcn(&d);
766           output = 1;
767 
768           if (f_longform)
769                     for (cur = list; cur; cur = cur->fts_link)
770                               free(cur->fts_pointer);
771 }
772 
773 /*
774  * Ordering for mastercmp:
775  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
776  * as larger than directories.  Within either group, use the sort function.
777  * All other levels use the sort function.  Error entries remain unsorted.
778  */
779 static int
mastercmp(const FTSENT * const * a,const FTSENT * const * b)780 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
781 {
782           int a_info, b_info;
783 
784           a_info = (*a)->fts_info;
785           if (a_info == FTS_ERR)
786                     return (0);
787           b_info = (*b)->fts_info;
788           if (b_info == FTS_ERR)
789                     return (0);
790 
791           if (a_info == FTS_NS || b_info == FTS_NS)
792                     return (namecmp(*a, *b));
793 
794           if (a_info != b_info &&
795               (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
796                     if (a_info == FTS_D)
797                               return (1);
798                     if (b_info == FTS_D)
799                               return (-1);
800           }
801           return (sortfcn(*a, *b));
802 }
803