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