Partial synch with FreeBSD 1.74:
[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.65 2002/08/25 13:01:45 charnier Exp $
35  * $DragonFly: src/bin/ls/ls.c,v 1.13 2005/09/18 16:59:54 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)(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_kblocks = 1;
262                         break;
263                 case 'm':
264                         f_stream = 1;
265                         f_singlecol = 0;
266                         f_longform = 0;
267                         break;
268                 case 'n':
269                         f_numericonly = 1;
270                         break;
271                 case 'o':
272                         f_flags = 1;
273                         break;
274                 case 'p':
275                         f_slash = 1;
276                         f_type = 1;
277                         break;
278                 case 'q':
279                         f_nonprint = 1;
280                         f_octal = 0;
281                         f_octal_escape = 0;
282                         break;
283                 case 'r':
284                         f_reversesort = 1;
285                         break;
286                 case 's':
287                         f_size = 1;
288                         break;
289                 case 'T':
290                         f_sectime = 1;
291                         break;
292                 case 't':
293                         f_timesort = 1;
294                         break;
295                 case 'W':
296                         f_whiteout = 1;
297                         break;
298                 case 'b':
299                         f_nonprint = 0;
300                         f_octal = 0;
301                         f_octal_escape = 1;
302                         break;
303                 case 'w':
304                         f_nonprint = 0;
305                         f_octal = 0;
306                         f_octal_escape = 0;
307                         break;
308                 default:
309                 case '?':
310                         usage();
311                 }
312         }
313         argc -= optind;
314         argv += optind;
315
316         /* Enabling of colours is conditional on the environment. */
317         if (getenv("CLICOLOR") &&
318             (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
319 #ifdef COLORLS
320                 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
321                         ansi_fgcol = tgetstr("AF", &bp);
322                         ansi_bgcol = tgetstr("AB", &bp);
323                         attrs_off = tgetstr("me", &bp);
324                         enter_bold = tgetstr("md", &bp);
325
326                         /* To switch colours off use 'op' if
327                          * available, otherwise use 'oc', or
328                          * don't do colours at all. */
329                         ansi_coloff = tgetstr("op", &bp);
330                         if (!ansi_coloff)
331                                 ansi_coloff = tgetstr("oc", &bp);
332                         if (ansi_fgcol && ansi_bgcol && ansi_coloff)
333                                 f_color = 1;
334                 }
335 #else
336                 fprintf(stderr, "Color support not compiled in.\n");
337 #endif /*COLORLS*/
338
339 #ifdef COLORLS
340         if (f_color) {
341                 /*
342                  * We can't put tabs and color sequences together:
343                  * column number will be incremented incorrectly
344                  * for "stty oxtabs" mode.
345                  */
346                 f_notabs = 1;
347                 signal(SIGINT, colorquit);
348                 signal(SIGQUIT, colorquit);
349                 parsecolors(getenv("LSCOLORS"));
350         }
351 #endif
352
353         /*
354          * If not -F, -i, -l, -s or -t options, don't require stat
355          * information, unless in color mode in which case we do
356          * need this to determine which colors to display.
357          */
358         if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
359 #ifdef COLORLS
360             && !f_color
361 #endif
362             )
363                 fts_options |= FTS_NOSTAT;
364
365         /*
366          * If not -F, -d or -l options, follow any symbolic links listed on
367          * the command line.
368          */
369         if (!f_longform && !f_listdir && !f_type)
370                 fts_options |= FTS_COMFOLLOW;
371
372         /*
373          * If -W, show whiteout entries
374          */
375 #ifdef FTS_WHITEOUT
376         if (f_whiteout)
377                 fts_options |= FTS_WHITEOUT;
378 #endif
379
380         /* If -l or -s, figure out block size. */
381         if (f_longform || f_size) {
382                 if (f_kblocks)
383                         blocksize = 2;
384                 else {
385                         getbsize(&notused, &blocksize);
386                         blocksize /= 512;
387                 }
388         }
389         /* Select a sort function. */
390         if (f_reversesort) {
391                 if (!f_timesort)
392                         sortfcn = revnamecmp;
393                 else if (f_accesstime)
394                         sortfcn = revacccmp;
395                 else if (f_statustime)
396                         sortfcn = revstatcmp;
397                 else            /* Use modification time. */
398                         sortfcn = revmodcmp;
399         } else {
400                 if (!f_timesort)
401                         sortfcn = namecmp;
402                 else if (f_accesstime)
403                         sortfcn = acccmp;
404                 else if (f_statustime)
405                         sortfcn = statcmp;
406                 else            /* Use modification time. */
407                         sortfcn = modcmp;
408         }
409
410         /* Select a print function. */
411         if (f_singlecol)
412                 printfcn = printscol;
413         else if (f_longform)
414                 printfcn = printlong;
415         else if (f_stream)
416                 printfcn = printstream;
417         else
418                 printfcn = printcol;
419
420         if (argc)
421                 traverse(argc, argv, fts_options);
422         else
423                 traverse(1, dotav, fts_options);
424         exit(rval);
425 }
426
427 static int output;              /* If anything output. */
428
429 /*
430  * Traverse() walks the logical directory structure specified by the argv list
431  * in the order specified by the mastercmp() comparison function.  During the
432  * traversal it passes linked lists of structures to display() which represent
433  * a superset (may be exact set) of the files to be displayed.
434  */
435 static void
436 traverse(int argc, char *argv[], int options)
437 {
438         FTS *ftsp;
439         FTSENT *p, *chp;
440         int ch_options;
441
442         if ((ftsp =
443             fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
444                 err(1, "fts_open");
445
446         display(NULL, fts_children(ftsp, 0));
447         if (f_listdir)
448                 return;
449
450         /*
451          * If not recursing down this tree and don't need stat info, just get
452          * the names.
453          */
454         ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
455
456         while ((p = fts_read(ftsp)) != NULL)
457                 switch (p->fts_info) {
458                 case FTS_DC:
459                         warnx("%s: directory causes a cycle", p->fts_name);
460                         break;
461                 case FTS_DNR:
462                 case FTS_ERR:
463                         warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
464                         rval = 1;
465                         break;
466                 case FTS_D:
467                         if (p->fts_level != FTS_ROOTLEVEL &&
468                             p->fts_name[0] == '.' && !f_listdot)
469                                 break;
470
471                         /*
472                          * If already output something, put out a newline as
473                          * a separator.  If multiple arguments, precede each
474                          * directory with its name.
475                          */
476                         if (output) {
477                                 putchar('\n');
478                                 printname(p->fts_path);
479                                 puts(":");
480                         } else if (argc > 1) {
481                                 printname(p->fts_path);
482                                 puts(":");
483                                 output = 1;
484                         }
485                         chp = fts_children(ftsp, ch_options);
486                         display(p, chp);
487
488                         if (!f_recursive && chp != NULL)
489                                 fts_set(ftsp, p, FTS_SKIP);
490                         break;
491                 default:
492                         break;
493                 }
494         if (errno)
495                 err(1, "fts_read");
496 }
497
498 /*
499  * Display() takes a linked list of FTSENT structures and passes the list
500  * along with any other necessary information to the print function.  P
501  * points to the parent directory of the display list.
502  */
503 static void
504 display(const FTSENT *p, FTSENT *list)
505 {
506         struct stat *sp;
507         DISPLAY d;
508         FTSENT *cur;
509         NAMES *np;
510         off_t maxsize;
511         u_long btotal, maxlen;
512         int64_t maxblock;
513         ino_t maxinode;
514         nlink_t maxnlink;
515         int bcfile, maxflags;
516         gid_t maxgroup;
517         uid_t maxuser;
518         size_t fsmidlen, flen, ulen, glen;
519         char *initmax;
520         int entries, needstats;
521         const char *user, *group;
522         char *flags;
523         int64_t fsmid;
524         char buf[STRBUF_SIZEOF(u_quad_t) + 1];
525         char ngroup[STRBUF_SIZEOF(uid_t) + 1];
526         char nuser[STRBUF_SIZEOF(gid_t) + 1];
527
528         /*
529          * If list is NULL there are two possibilities: that the parent
530          * directory p has no children, or that fts_children() returned an
531          * error.  We ignore the error case since it will be replicated
532          * on the next call to fts_read() on the post-order visit to the
533          * directory p, and will be signaled in traverse().
534          */
535         if (list == NULL)
536                 return;
537
538         needstats = f_inode || f_longform || f_size;
539         flen = 0;
540         btotal = 0;
541         initmax = getenv("LS_COLWIDTHS");
542         /* Fields match -lios order.  New ones should be added at the end. */
543         maxblock = maxinode = maxlen = maxnlink =
544             maxuser = maxgroup = maxflags = maxsize = 0;
545         if (initmax != NULL && *initmax != '\0') {
546                 char *initmax2, *jinitmax;
547                 int ninitmax;
548
549                 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
550                 jinitmax = malloc(strlen(initmax) * 2 + 2);
551                 if (jinitmax == NULL)
552                         err(1, "malloc");
553                 initmax2 = jinitmax;
554                 if (*initmax == ':')
555                         strcpy(initmax2, "0:"), initmax2 += 2;
556                 else
557                         *initmax2++ = *initmax, *initmax2 = '\0';
558                 for (initmax++; *initmax != '\0'; initmax++) {
559                         if (initmax[-1] == ':' && initmax[0] == ':') {
560                                 *initmax2++ = '0';
561                                 *initmax2++ = initmax[0];
562                                 initmax2[1] = '\0';
563                         } else {
564                                 *initmax2++ = initmax[0];
565                                 initmax2[1] = '\0';
566                         }
567                 }
568                 if (initmax2[-1] == ':')
569                         strcpy(initmax2, "0");
570
571                 ninitmax = sscanf(jinitmax,
572                     " %llu : %lli : %u : %i : %i : %i : %llu : %lu ",
573                     &maxinode, &maxblock, &maxnlink, &maxuser,
574                     &maxgroup, &maxflags, &maxsize, &maxlen);
575                 f_notabs = 1;
576                 switch (ninitmax) {
577                 case 0:
578                         maxinode = 0;
579                         /* FALLTHROUGH */
580                 case 1:
581                         maxblock = 0;
582                         /* FALLTHROUGH */
583                 case 2:
584                         maxnlink = 0;
585                         /* FALLTHROUGH */
586                 case 3:
587                         maxuser = 0;
588                         /* FALLTHROUGH */
589                 case 4:
590                         maxgroup = 0;
591                         /* FALLTHROUGH */
592                 case 5:
593                         maxflags = 0;
594                         /* FALLTHROUGH */
595                 case 6:
596                         maxsize = 0;
597                         /* FALLTHROUGH */
598                 case 7:
599                         maxlen = 0;
600                         /* FALLTHROUGH */
601 #ifdef COLORLS
602                         if (!f_color)
603 #endif
604                                 f_notabs = 0;
605                         /* FALLTHROUGH */
606                 default:
607                         break;
608                 }
609                 MAKENINES(maxinode);
610                 MAKENINES(maxblock);
611                 MAKENINES(maxnlink);
612                 MAKENINES(maxsize);
613                 free(jinitmax);
614         }
615         bcfile = 0;
616         flags = NULL;
617         for (cur = list, entries = 0; cur; cur = cur->fts_link) {
618                 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
619                         warnx("%s: %s",
620                             cur->fts_name, strerror(cur->fts_errno));
621                         cur->fts_number = NO_PRINT;
622                         rval = 1;
623                         continue;
624                 }
625                 /*
626                  * P is NULL if list is the argv list, to which different rules
627                  * apply.
628                  */
629                 if (p == NULL) {
630                         /* Directories will be displayed later. */
631                         if (cur->fts_info == FTS_D && !f_listdir) {
632                                 cur->fts_number = NO_PRINT;
633                                 continue;
634                         }
635                 } else {
636                         /* Only display dot file if -a/-A set. */
637                         if (cur->fts_name[0] == '.' && !f_listdot) {
638                                 cur->fts_number = NO_PRINT;
639                                 continue;
640                         }
641                 }
642                 if (cur->fts_namelen > maxlen)
643                         maxlen = cur->fts_namelen;
644                 if (f_octal || f_octal_escape) {
645                         u_long t = len_octal(cur->fts_name, cur->fts_namelen);
646
647                         if (t > maxlen)
648                                 maxlen = t;
649                 }
650                 if (needstats) {
651                         sp = cur->fts_statp;
652                         if (sp->st_blocks > maxblock)
653                                 maxblock = sp->st_blocks;
654                         if (sp->st_ino > maxinode)
655                                 maxinode = sp->st_ino;
656                         if (sp->st_nlink > maxnlink)
657                                 maxnlink = sp->st_nlink;
658                         if (sp->st_size > maxsize)
659                                 maxsize = sp->st_size;
660
661                         btotal += sp->st_blocks;
662                         if (f_longform) {
663                                 if (f_numericonly) {
664                                         snprintf(nuser, sizeof(nuser),
665                                             "%u", sp->st_uid);
666                                         snprintf(ngroup, sizeof(ngroup),
667                                             "%u", sp->st_gid);
668                                         user = nuser;
669                                         group = ngroup;
670                                 } else {
671                                         user = user_from_uid(sp->st_uid, 0);
672                                         group = group_from_gid(sp->st_gid, 0);
673                                 }
674                                 if ((ulen = strlen(user)) > maxuser)
675                                         maxuser = ulen;
676                                 if ((glen = strlen(group)) > maxgroup)
677                                         maxgroup = glen;
678                                 if (f_flags) {
679                                         flags = fflagstostr(sp->st_flags);
680                                         if (flags != NULL && *flags == '\0') {
681                                                 free(flags);
682                                                 flags = strdup("-");
683                                         }
684                                         if (flags == NULL)
685                                                 err(1, "flagstostr");
686                                         flen = strlen(flags);
687                                         if (flen > (size_t)maxflags)
688                                                 maxflags = flen;
689                                 } else {
690                                         flen = 0;
691                                 }
692 #ifdef _ST_FSMID_PRESENT_
693                                 if (f_fsmid) {
694                                         fsmid = sp->st_fsmid;
695                                         fsmidlen = 18;
696                                 } else {
697                                         fsmid = 0;
698                                         fsmidlen = 0;
699                                 } 
700 #else
701                                 fsmidlen = 0;
702 #endif
703
704                                 if ((np = malloc(sizeof(NAMES) +
705                                     ulen + glen + flen + fsmidlen + 4)) == NULL)
706                                         err(1, "malloc");
707
708                                 np->user = &np->data[0];
709                                 strcpy(np->user, user);
710                                 np->group = &np->data[ulen + 1];
711                                 strcpy(np->group, group);
712
713                                 if (S_ISCHR(sp->st_mode) ||
714                                     S_ISBLK(sp->st_mode))
715                                         bcfile = 1;
716
717                                 if (f_flags) {
718                                         np->flags = &np->data[ulen + glen + 2];
719                                         strcpy(np->flags, flags);
720                                         free(flags);
721                                 }
722 #ifdef _ST_FSMID_PRESENT_
723                                 if (f_fsmid) {
724                                         np->fsmid = np->data + ulen + glen + flen + 3;
725                                         snprintf(np->fsmid, fsmidlen + 1,  
726                                                  "%016llx", fsmid);
727                                 }
728 #endif
729                                 cur->fts_pointer = np;
730                         }
731                 }
732                 ++entries;
733         }
734
735         if (!entries)
736                 return;
737
738         d.list = list;
739         d.entries = entries;
740         d.maxlen = maxlen;
741         if (needstats) {
742                 d.bcfile = bcfile;
743                 d.btotal = btotal;
744                 snprintf(buf, sizeof(buf), "%lli", maxblock);
745                 d.s_block = strlen(buf);
746                 d.s_flags = maxflags;
747                 d.s_group = maxgroup;
748                 snprintf(buf, sizeof(buf), "%llu", maxinode);
749                 d.s_inode = strlen(buf);
750                 snprintf(buf, sizeof(buf), "%u", maxnlink);
751                 d.s_nlink = strlen(buf);
752                 snprintf(buf, sizeof(buf), "%llu", maxsize);
753                 d.s_size = strlen(buf);
754                 d.s_user = maxuser;
755         }
756         printfcn(&d);
757         output = 1;
758
759         if (f_longform)
760                 for (cur = list; cur; cur = cur->fts_link)
761                         free(cur->fts_pointer);
762 }
763
764 /*
765  * Ordering for mastercmp:
766  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
767  * as larger than directories.  Within either group, use the sort function.
768  * All other levels use the sort function.  Error entries remain unsorted.
769  */
770 static int
771 mastercmp(const FTSENT **a, const FTSENT **b)
772 {
773         int a_info, b_info;
774
775         a_info = (*a)->fts_info;
776         if (a_info == FTS_ERR)
777                 return (0);
778         b_info = (*b)->fts_info;
779         if (b_info == FTS_ERR)
780                 return (0);
781
782         if (a_info == FTS_NS || b_info == FTS_NS)
783                 return (namecmp(*a, *b));
784
785         if (a_info != b_info &&
786             (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
787                 if (a_info == FTS_D)
788                         return (1);
789                 if (b_info == FTS_D)
790                         return (-1);
791         }
792         return (sortfcn(*a, *b));
793 }