prettyness police
[unix-history] / usr / src / bin / ls / ls.c
index 41db782..0c49aa4 100644 (file)
-#ifndef lint
-static char *sccsid = "@(#)ls.c        4.17 (Berkeley) %G%";
-#endif
-
 /*
 /*
- * ls
+ * Copyright (c) 1989, 1993
+ *     The Regents of the University of California.  All rights reserved.
  *
  *
- * 4.2bsd version for symbolic links, variable length
- * directory entries, block size in the inode, etc.
+ * This code is derived from software contributed to Berkeley by
+ * Michael Fischbein.
+ *
+ * %sccs.include.redist.c%
  */
  */
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/dir.h>
-#include <stdio.h>
-#include <sgtty.h>
-
-#define        kbytes(size)    (((size) + 1023) / 1024)
-
-struct afile {
-       char    ftype;          /* file type, e.g. 'd', 'c', 'f' */
-       ino_t   fnum;           /* inode number of file */
-       short   fflags;         /* mode&~S_IFMT, perhaps ISARG */
-       short   fnl;            /* number of links */
-       short   fuid;           /* owner id */
-       short   fgid;           /* group id */
-       long    fsize;          /* file size */
-       long    fblks;          /* number of blocks used */
-       time_t  fmtime;         /* time (modify or access or create) */
-       char    *fname;         /* file name */
-       char    *flinkto;       /* symbolic link value */
-};
 
 
-#define ISARG  0x8000          /* extra ``mode'' */
-
-struct subdirs {
-       char    *sd_name;
-       struct  subdirs *sd_next;
-} *subdirs;
-
-int    aflg, dflg, gflg, lflg, sflg, tflg, uflg, iflg, fflg, cflg, rflg = 1;
-int    qflg, Aflg, Cflg, Fflg, Lflg, Rflg;
-
-int    usetabs;
-
-time_t now, sixmonthsago;
-
-char   *dotp = ".";
+#ifndef lint
+static char copyright[] =
+"@(#) Copyright (c) 1989, 1993\n\
+       The Regents of the University of California.  All rights reserved.\n";
+#endif /* not lint */
 
 
-struct afile *gstat();
-int    fcmp();
-char   *cat(), *savestr();
-char   *fmtentry();
-char   *getname(), *getgroup();
+#ifndef lint
+static char sccsid[] = "@(#)ls.c       8.2 (Berkeley) %G%";
+#endif /* not lint */
 
 
-char   *ctime();
-char   *malloc(), *calloc(), *realloc();
-char   *sprintf(), *strcpy(), *strcat();
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
 
 
+#include <dirent.h>
+#include <err.h>
+#include <errno.h>
+#include <fts.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "ls.h"
+#include "extern.h"
+
+static void     display __P((FTSENT *, FTSENT *));
+static int      mastercmp __P((const FTSENT **, const FTSENT **));
+static void     traverse __P((int, char **, int));
+
+static void (*printfcn) __P((DISPLAY *));
+static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
+
+long blocksize;                        /* block size units */
+int termwidth = 80;            /* default terminal width */
+
+/* flags */
+int f_accesstime;              /* use time of last access */
+int f_column;                  /* columnated format */
+int f_flags;                   /* show flags associated with a file */
+int f_inode;                   /* print inode */
+int f_listdir;                 /* list actual directory, not contents */
+int f_listdot;                 /* list files beginning with . */
+int f_longform;                        /* long listing format */
+int f_newline;                 /* if precede with newline */
+int f_nonprint;                        /* show unprintables as ? */
+int f_nosort;                  /* don't sort output */
+int f_recursive;               /* ls subdirectories also */
+int f_reversesort;             /* reverse whatever sort is used */
+int f_sectime;                 /* print the real time for all files */
+int f_singlecol;               /* use single column output */
+int f_size;                    /* list size in short listing */
+int f_statustime;              /* use time of last mode change */
+int f_dirname;                 /* if precede with directory name */
+int f_timesort;                        /* sort by time vice name */
+int f_type;                    /* add type character for non-regular files */
+
+int
 main(argc, argv)
        int argc;
        char *argv[];
 {
 main(argc, argv)
        int argc;
        char *argv[];
 {
-       int i;
-       struct afile *fp0, *fplast;
-       register struct afile *fp;
-       struct sgttyb sgbuf;
-
-       argc--, argv++;
-       if (getuid() == 0)
-               Aflg++;
-       (void) time(&now); sixmonthsago = now - 6L*30L*24L*60L*60L; now += 60;
-       if (isatty(1)) {
-               qflg = Cflg = 1;
-               (void) gtty(1, &sgbuf);
-               if ((sgbuf.sg_flags & XTABS) == 0)
-                       usetabs = 1;
+       static char dot[] = ".", *dotav[] = { dot, NULL };
+       struct winsize win;
+       int ch, fts_options, notused;
+       char *p;
+
+       /* Terminal defaults to -Cq, non-terminal defaults to -1. */
+       if (isatty(STDOUT_FILENO)) {
+               if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
+                   !win.ws_col) {
+                       if ((p = getenv("COLUMNS")) != NULL)
+                               termwidth = atoi(p);
+               }
+               else
+                       termwidth = win.ws_col;
+               f_column = f_nonprint = 1;
        } else
        } else
-               usetabs = 1;
-       while (argc > 0 && **argv == '-') {
-               (*argv)++;
-               while (**argv) switch (*(*argv)++) {
-
-               case 'C':
-                       Cflg = 1; break;
-               case 'q':
-                       qflg = 1; break;
+               f_singlecol = 1;
+
+       /* Root is -A automatically. */
+       if (!getuid())
+               f_listdot = 1;
+
+       fts_options = FTS_PHYSICAL;
+       while ((ch = getopt(argc, argv, "1ACFLRTacdfgiloqrstu")) != EOF) {
+               switch (ch) {
+               /*
+                * The -1, -C and -l options all override each other so shell
+                * aliasing works right.
+                */
                case '1':
                case '1':
-                       Cflg = 0; break;
+                       f_singlecol = 1;
+                       f_column = f_longform = 0;
+                       break;
+               case 'C':
+                       f_column = 1;
+                       f_longform = f_singlecol = 0;
+                       break;
+               case 'l':
+                       f_longform = 1;
+                       f_column = f_singlecol = 0;
+                       break;
+               /* The -c and -u options override each other. */
+               case 'c':
+                       f_statustime = 1;
+                       f_accesstime = 0;
+                       break;
+               case 'u':
+                       f_accesstime = 1;
+                       f_statustime = 0;
+                       break;
+               case 'F':
+                       f_type = 1;
+                       break;
+               case 'L':
+                       fts_options &= ~FTS_PHYSICAL;
+                       fts_options |= FTS_LOGICAL;
+                       break;
+               case 'R':
+                       f_recursive = 1;
+                       break;
                case 'a':
                case 'a':
-                       aflg++; break;
+                       fts_options |= FTS_SEEDOT;
+                       /* FALLTHROUGH */
                case 'A':
                case 'A':
-                       Aflg++; break;
-               case 'c':
-                       cflg++; break;
-               case 's':
-                       sflg++; break;
+                       f_listdot = 1;
+                       break;
+               /* The -d option turns off the -R option. */
+               case 'S':
+                       Sflg++; /* fall into... */
                case 'd':
                case 'd':
-                       dflg++; break;
-               case 'g':
-                       gflg++; break;
-               case 'l':
-                       lflg++; break;
+                       f_listdir = 1;
+                       f_recursive = 0;
+                       break;
+               case 'f':
+                       f_nosort = 1;
+                       break;
+               case 'g':               /* Compatibility with 4.3BSD. */
+                       break;
+               case 'i':
+                       f_inode = 1;
+                       break;
+               case 'o':
+                       f_flags = 1;
+                       break;
+               case 'q':
+                       f_nonprint = 1;
+                       break;
                case 'r':
                case 'r':
-                       rflg = -1; break;
+                       f_reversesort = 1;
+                       break;
+               case 's':
+                       f_size = 1;
+                       break;
+               case 'T':
+                       f_sectime = 1;
+                       break;
                case 't':
                case 't':
-                       tflg++; break;
-               case 'u':
-                       uflg++; break;
-               case 'i':
-                       iflg++; break;
-               case 'f':
-                       fflg++; break;
-               case 'L':
-                       Lflg++; break;
-               case 'F':
-                       Fflg++; break;
-               case 'R':
-                       Rflg++; break;
-               }
-               argc--, argv++;
-       }
-       if (fflg) { 
-               aflg++; lflg = 0; sflg = 0; tflg = 0;
-       }
-       if (lflg)
-               Cflg = 0;
-       if (argc == 0) {
-               argc++;
-               argv = &dotp;
-       }
-       fp = (struct afile *)calloc(argc, sizeof (struct afile));
-       if (fp == 0) {
-               fprintf(stderr, "ls: out of memory\n");
-               exit(1);
-       }
-       fp0 = fp;
-       for (i = 0; i < argc; i++) {
-               if (gstat(fp, *argv, 1, (int *)0)) {
-                       fp->fname = *argv;
-                       fp->fflags |= ISARG;
-                       fp++;
+                       f_timesort = 1;
+                       break;
+               default:
+               case '?':
+                       usage();
                }
                }
-               argv++;
-       }
-       fplast = fp;
-       qsort(fp0, fplast - fp0, sizeof (struct afile), fcmp);
-       if (dflg) {
-               formatf(fp0, fplast);
-               exit(0);
        }
        }
-       if (fflg)
-               fp = fp0;
-       else {
-               for (fp = fp0; fp < fplast && fp->ftype != 'd'; fp++)
-                       continue;
-               formatf(fp0, fp);
+       argc -= optind;
+       argv += optind;
+
+       /*
+        * If not -F, -i, -l, -s or -t options, don't require stat
+        * information.
+        */
+       if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
+               fts_options |= FTS_NOSTAT;
+
+       /*
+        * If not -F, -d or -l options, follow any symbolic links listed on
+        * the command line.
+        */
+       if (!f_longform && !f_listdir && !f_type)
+               fts_options |= FTS_COMFOLLOW;
+
+       /* If -l or -s, figure out block size. */
+       if (f_longform || f_size) {
+               (void)getbsize(&notused, &blocksize);
+               blocksize /= 512;
        }
        }
-       if (fp < fplast) {
-               if (fp > fp0)
-                       printf("\n");
-               for (;;) {
-                       formatd(fp->fname, argc > 1);
-                       while (subdirs) {
-                               struct subdirs *t;
-
-                               t = subdirs; subdirs = t->sd_next;
-                               printf("\n");
-                               formatd(t->sd_name, 1);
-                               cfree(t->sd_name);
-                               cfree((char *)t);
-                       }
-                       if (++fp == fplast)
-                               break;
-                       printf("\n");
-               }
+
+       /* Select a sort function. */
+       if (f_reversesort) {
+               if (!f_timesort)
+                       sortfcn = revnamecmp;
+               else if (f_accesstime)
+                       sortfcn = revacccmp;
+               else if (f_statustime)
+                       sortfcn = revstatcmp;
+               else /* Use modification time. */
+                       sortfcn = revmodcmp;
+       } else {
+               if (!f_timesort)
+                       sortfcn = namecmp;
+               else if (f_accesstime)
+                       sortfcn = acccmp;
+               else if (f_statustime)
+                       sortfcn = statcmp;
+               else /* Use modification time. */
+                       sortfcn = modcmp;
        }
        }
+
+       /* Select a print function. */
+       if (f_singlecol)
+               printfcn = printscol;
+       else if (f_longform)
+               printfcn = printlong;
+       else
+               printfcn = printcol;
+
+       if (argc)
+               traverse(argc, argv, fts_options);
+       else
+               traverse(1, dotav, fts_options);
        exit(0);
 }
 
        exit(0);
 }
 
-formatd(name, title)
-       char *name;
-       int title;
+static int output;                     /* If anything output. */
+
+/*
+ * Traverse() walks the logical directory structure specified by the argv list
+ * in the order specified by the mastercmp() comparison function.  During the
+ * traversal it passes linked lists of structures to display() which represent
+ * a superset (may be exact set) of the files to be displayed.
+ */
+static void
+traverse(argc, argv, options)
+       int argc, options;
+       char *argv[];
 {
 {
-       register struct afile *fp;
-       register struct subdirs *dp;
-       struct afile *dfp0, *dfplast;
-       int nkb;
+       FTS *ftsp;
+       FTSENT *p, *chp;
+       int ch_options;
 
 
-       nkb = getdir(name, &dfp0, &dfplast);
-       if (dfp0 == 0)
-               return;
-       if (fflg == 0)
-               qsort(dfp0, dfplast - dfp0, sizeof (struct afile), fcmp);
-       if (title)
-               printf("%s:\n", name);
-       if (lflg || sflg)
-               printf("total %ld\n", nkb);
-       formatf(dfp0, dfplast);
-       if (Rflg)
-               for (fp = dfplast; fp >= dfp0; fp--) {
-                       if (fp->ftype != 'd' ||
-                           !strcmp(fp->fname, ".") ||
-                           !strcmp(fp->fname, ".."))
-                               continue;
-                       dp = (struct subdirs *)malloc(sizeof (struct subdirs));
-                       dp->sd_name = savestr(cat(name, fp->fname));
-                       dp->sd_next = subdirs; subdirs = dp;
-               }
-       for (fp = dfp0; fp < dfplast; fp++) {
-               if ((fp->fflags&ISARG) == 0 && fp->fname)
-                       cfree(fp->fname);
-               if (fp->flinkto)
-                       cfree(fp->flinkto);
-       }
-       cfree((char *)dfp0);
-}
+       if ((ftsp =
+           fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
+               err(1, NULL);
 
 
-getdir(dir, pfp0, pfplast)
-       char *dir;
-       struct afile **pfp0, **pfplast;
-{
-       register struct afile *fp;
-       DIR *dirp;
-       register struct direct *dp;
-       int nb, nent = 20;
-
-       dirp = opendir(dir);
-       if (dirp == NULL) {
-               *pfp0 = *pfplast = NULL;
-               printf("%s unreadable\n", dir);         /* not stderr! */
-               return (0);
-       }
-       fp = *pfp0 = (struct afile *)calloc(nent, sizeof (struct afile));
-       *pfplast = *pfp0 + nent;
-       nb = 0;
-       while (dp = readdir(dirp)) {
-               if (dp->d_ino == 0)
-                       continue;
-               if (aflg == 0 && dp->d_name[0]=='.' &&
-                   (Aflg == 0 || dp->d_name[1]==0 ||
-                    dp->d_name[1]=='.' && dp->d_name[2]==0))
-                       continue;
-               if (gstat(fp, cat(dir, dp->d_name), Fflg+Rflg, &nb) == 0)
-                       continue;
-               fp->fnum = dp->d_ino;
-               fp->fname = savestr(dp->d_name);
-               fp++;
-               if (fp == *pfplast) {
-                       *pfp0 = (struct afile *)realloc((char *)*pfp0,
-                           2 * nent * sizeof (struct afile));
-                       if (*pfp0 == 0) {
-                               fprintf(stderr, "ls: out of memory\n");
-                               exit(1);
-                       }
-                       fp = *pfp0 + nent;
-                       *pfplast = fp + nent;
-                       nent *= 2;
-               }
-       }
-       closedir(dirp);
-       *pfplast = fp;
-       return (kbytes(dbtob(nb)));
-}
+       display(NULL, fts_children(ftsp, 0));
+       if (f_listdir)
+               return;
 
 
-int    stat(), lstat();
+       /*
+        * If not recursing down this tree and don't need stat info, just get
+        * the names.
+        */
+       ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
 
 
-struct afile *
-gstat(fp, file, statarg, pnb)
-       register struct afile *fp;
-       char *file;
-       int statarg, *pnb;
-{
-       int (*statf)() = Lflg ? stat : lstat;
-       char buf[BUFSIZ]; int cc;
-       static struct afile azerofile;
-
-       *fp = azerofile;
-       fp->fflags = 0;
-       fp->fnum = 0;
-       fp->ftype = '-';
-       if (statarg || sflg || lflg || tflg) {
-               struct stat stb, stb1;
-
-               if ((*statf)(file, &stb) < 0) {
-                       if (statf == stat && lstat(file, &stb) < 0) {
-                               fprintf(stderr, "%s not found\n", file);
-                               return (0);
-                       }
-               }
-               fp->fblks = stb.st_blocks;
-               fp->fsize = stb.st_size;
-               switch (stb.st_mode & S_IFMT) {
-
-               case S_IFDIR:
-                       fp->ftype = 'd'; break;
-               case S_IFBLK:
-                       fp->ftype = 'b'; fp->fsize = stb.st_rdev; break;
-               case S_IFCHR:
-                       fp->ftype = 'c'; fp->fsize = stb.st_rdev; break;
-               case S_IFSOCK:
-                       fp->ftype = 's'; fp->fsize = 0; break;
-               case S_IFLNK:
-                       fp->ftype = 'l';
-                       if (lflg) {
-                               cc = readlink(file, buf, BUFSIZ);
-                               if (cc >= 0) {
-                                       buf[cc] = 0;
-                                       fp->flinkto = savestr(buf);
-                               }
-                               break;
-                       }
-                       if (stat(file, &stb1) < 0)
+       while ((p = fts_read(ftsp)) != NULL)
+               switch (p->fts_info) {
+               case FTS_DC:
+                       warnx("%s: directory causes a cycle", p->fts_name);
+                       break;
+               case FTS_DNR:
+               case FTS_ERR:
+                       errno = p->fts_errno;
+                       warn("%s", p->fts_name);
+                       break;
+               case FTS_D:
+                       if (p->fts_level != FTS_ROOTLEVEL &&
+                           p->fts_name[0] == '.' && !f_listdot)
                                break;
                                break;
-                       if ((stb1.st_mode & S_IFMT) == S_IFDIR) {
-                               stb = stb1;
-                               fp->ftype = 'd';
-                               fp->fsize = stb.st_size;
-                               fp->fblks = stb.st_blocks;
+
+                       /*
+                        * If already output something, put out a newline as
+                        * a separator.  If multiple arguments, precede each
+                        * directory with its name.
+                        */
+                       if (output)
+                               (void)printf("\n%s:\n", p->fts_path);
+                       else if (argc > 1) {
+                               (void)printf("%s:\n", p->fts_path);
+                               output = 1;
                        }
                        }
+
+                       chp = fts_children(ftsp, ch_options);
+                       display(p, chp);
+
+                       if (!f_recursive && chp != NULL)
+                               (void)fts_set(ftsp, p, FTS_SKIP);
                        break;
                }
                        break;
                }
-               fp->fnum = stb.st_ino;
-               fp->fflags = stb.st_mode & ~S_IFMT;
-               fp->fnl = stb.st_nlink;
-               fp->fuid = stb.st_uid;
-               fp->fgid = stb.st_gid;
-               if (uflg)
-                       fp->fmtime = stb.st_atime;
-               else if (cflg)
-                       fp->fmtime = stb.st_ctime;
-               else
-                       fp->fmtime = stb.st_mtime;
-               if (pnb)
-                       *pnb += stb.st_blocks;
-       }
-       return (fp);
+       (void)fts_close(ftsp);
 }
 
 }
 
-formatf(fp0, fplast)
-       struct afile *fp0, *fplast;
+/*
+ * Display() takes a linked list of FTSENT structures and passes the list
+ * along with any other necessary information to the print function.  P
+ * points to the parent directory of the display list.
+ */
+static void
+display(p, list)
+       FTSENT *p, *list;
 {
 {
-       register struct afile *fp;
-       int width = 0, w, nentry = fplast - fp0;
-       int i, j, columns, lines;
-       char *cp;
-
-       if (fp0 == fplast)
+       struct stat *sp;
+       DISPLAY d;
+       FTSENT *cur;
+       NAMES *np;
+       u_quad_t maxsize;
+       u_long btotal, maxblock, maxinode, maxlen, maxnlink;
+       int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
+       int entries, needstats;
+       char *user, *group, *flags, buf[20];    /* 32 bits == 10 digits */
+
+       /*
+        * If list is NULL there are two possibilities: that the parent
+        * directory p has no children, or that fts_children() returned an
+        * error.  We ignore the error case since it will be replicated
+        * on the next call to fts_read() on the post-order visit to the
+        * directory p, and will be signalled in traverse().
+        */
+       if (list == NULL)
                return;
                return;
-       if (lflg || Cflg == 0)
-               columns = 1;
-       else {
-               for (fp = fp0; fp < fplast; fp++) {
-                       int len = strlen(fmtentry(fp));
-
-                       if (len > width)
-                               width = len;
-               }
-               if (usetabs)
-                       width = (width + 8) &~ 7;
-               else
-                       width += 2;
-               columns = 80 / width;
-               if (columns == 0)
-                       columns = 1;
-       }
-       lines = (nentry + columns - 1) / columns;
-       for (i = 0; i < lines; i++) {
-               for (j = 0; j < columns; j++) {
-                       fp = fp0 + j * lines + i;
-                       cp = fmtentry(fp);
-                       printf("%s", cp);
-                       if (fp + lines >= fplast) {
-                               printf("\n");
-                               break;
-                       }
-                       w = strlen(cp);
-                       while (w < width)
-                               if (usetabs) {
-                                       w = (w + 8) &~ 7;
-                                       putchar('\t');
-                               } else {
-                                       w++;
-                                       putchar(' ');
-                               }
-               }
-       }
-}
 
 
-fcmp(f1, f2)
-       register struct afile *f1, *f2;
-{
+       needstats = f_inode || f_longform || f_size;
+       flen = 0;
+       btotal = maxblock = maxinode = maxlen = maxnlink = 0;
+       bcfile = 0;
+       maxuser = maxgroup = maxflags = 0;
+       maxsize = 0;
+       for (cur = list, entries = 0; cur; cur = cur->fts_link) {
+               if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
+                       errno = cur->fts_errno;
+                       warn("%s", cur->fts_name);
+                       cur->fts_number = NO_PRINT;
+                       continue;
+               }
 
 
-       if (dflg == 0 && fflg == 0) {
-               if ((f1->fflags&ISARG) && f1->ftype == 'd') {
-                       if ((f2->fflags&ISARG) == 0 || f2->ftype != 'd')
-                               return (1);
+               /*
+                * P is NULL if list is the argv list, to which different rules
+                * apply.
+                */
+               if (p == NULL) {
+                       /* Directories will be displayed later. */
+                       if (cur->fts_info == FTS_D && !f_listdir) {
+                               cur->fts_number = NO_PRINT;
+                               continue;
+                       }
                } else {
                } else {
-                       if ((f2->fflags&ISARG) && f2->ftype == 'd')
-                               return (-1);
+                       /* Only display dot file if -a/-A set. */
+                       if (cur->fts_name[0] == '.' && !f_listdot) {
+                               cur->fts_number = NO_PRINT;
+                               continue;
+                       }
                }
                }
+               if (f_nonprint)
+                       prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
+               if (cur->fts_namelen > maxlen)
+                       maxlen = cur->fts_namelen;
+               if (needstats) {
+                       sp = cur->fts_statp;
+                       if (sp->st_blocks > maxblock)
+                               maxblock = sp->st_blocks;
+                       if (sp->st_ino > maxinode)
+                               maxinode = sp->st_ino;
+                       if (sp->st_nlink > maxnlink)
+                               maxnlink = sp->st_nlink;
+                       if (sp->st_size > maxsize)
+                               maxsize = sp->st_size;
+
+                       btotal += sp->st_blocks;
+                       if (f_longform) {
+                               user = user_from_uid(sp->st_uid, 0);
+                               if ((ulen = strlen(user)) > maxuser)
+                                       maxuser = ulen;
+                               group = group_from_gid(sp->st_gid, 0);
+                               if ((glen = strlen(group)) > maxgroup)
+                                       maxgroup = glen;
+                               if (f_flags) {
+                                       flags =
+                                           flags_to_string(sp->st_flags, "-");
+                                       if ((flen = strlen(flags)) > maxflags)
+                                               maxflags = flen;
+                               } else
+                                       flen = 0;
+
+                               if ((np = malloc(sizeof(NAMES) +
+                                   ulen + glen + flen + 3)) == NULL)
+                                       err(1, NULL);
+
+                               np->user = &np->data[0];
+                               (void)strcpy(np->user, user);
+                               np->group = &np->data[ulen + 1];
+                               (void)strcpy(np->group, group);
+
+                               if (S_ISCHR(sp->st_mode) ||
+                                   S_ISBLK(sp->st_mode))
+                                       bcfile = 1;
+
+                               if (f_flags) {
+                                       np->flags = &np->data[ulen + glen + 2];
+                                       (void)strcpy(np->flags, flags);
+                               }
+                               cur->fts_pointer = np;
+                       }
+               }
+               ++entries;
        }
        }
-       if (tflg) {
-               if (f2->fmtime == f1->fmtime)
-                       return (0);
-               if (f2->fmtime > f1->fmtime)
-                       return (rflg);
-               return (-rflg);
-       }
-       return (rflg * strcmp(f1->fname, f2->fname));
-}
-
-char *
-cat(dir, file)
-       char *dir, *file;
-{
-       static char dfile[BUFSIZ];
-
-       if (strlen(dir)+1+strlen(file)+1 > BUFSIZ) {
-               fprintf(stderr, "ls: filename too long\n");
-               exit(1);
-       }
-       if (!strcmp(dir, "") || !strcmp(dir, ".")) {
-               (void) strcpy(dfile, file);
-               return (dfile);
-       }
-       (void) strcpy(dfile, dir);
-       if (dir[strlen(dir) - 1] != '/' && *file != '/')
-               (void) strcat(dfile, "/");
-       (void) strcat(dfile, file);
-       return (dfile);
-}
 
 
-char *
-savestr(str)
-       char *str;
-{
-       char *cp = malloc(strlen(str) + 1);
+       if (!entries)
+               return;
 
 
-       if (cp == NULL) {
-               fprintf(stderr, "ls: out of memory\n");
-               exit(1);
+       d.list = list;
+       d.entries = entries;
+       d.maxlen = maxlen;
+       if (needstats) {
+               d.bcfile = bcfile;
+               d.btotal = btotal;
+               (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
+               d.s_block = strlen(buf);
+               d.s_flags = maxflags;
+               d.s_group = maxgroup;
+               (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
+               d.s_inode = strlen(buf);
+               (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
+               d.s_nlink = strlen(buf);
+               (void)snprintf(buf, sizeof(buf), "%qu", maxsize);
+               d.s_size = strlen(buf);
+               d.s_user = maxuser;
        }
        }
-       (void) strcpy(cp, str);
-       return (cp);
-}
 
 
-char   *fmtinum(), *fmtsize(), *fmtlstuff(), *fmtmode();
+       printfcn(&d);
+       output = 1;
 
 
-char *
-fmtentry(fp)
-       register struct afile *fp;
-{
-       static char fmtres[BUFSIZ];
-       register char *cp, *dp;
-
-       (void) sprintf(fmtres, "%s%s%s",
-           iflg ? fmtinum(fp) : "",
-           sflg ? fmtsize(fp) : "",
-           lflg ? fmtlstuff(fp) : "");
-       dp = &fmtres[strlen(fmtres)];
-       for (cp = fp->fname; *cp; cp++)
-               if (qflg && (*cp < ' ' || *cp >= 0177))
-                       *dp++ = '?';
-               else
-                       *dp++ = *cp;
-       if (Fflg) {
-               if (fp->ftype == 'd')
-                       *dp++ = '/';
-               else if (fp->ftype == 'l')
-                       *dp++ = '@';
-               else if (fp->ftype == 's')
-                       *dp++ = '=';
-               else if (fp->fflags & 0111)
-                       *dp++ = '*';
-       }
-       if (lflg && fp->flinkto) {
-               (void) strcpy(dp, " -> "); dp += 4;
-               for (cp = fp->flinkto; *cp; cp++)
-                       if (qflg && (*cp < ' ' || *cp >= 0177))
-                               *dp++ = '?';
-                       else
-                               *dp++ = *cp;
-       }
-       *dp++ = 0;
-       return (fmtres);
+       if (f_longform)
+               for (cur = list; cur; cur = cur->fts_link)
+                       free(cur->fts_pointer);
 }
 
 }
 
-char *
-fmtinum(p)
-       register struct afile *p;
+/*
+ * Ordering for mastercmp:
+ * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
+ * as larger than directories.  Within either group, use the sort function.
+ * All other levels use the sort function.  Error entries remain unsorted.
+ */
+static int
+mastercmp(a, b)
+       const FTSENT **a, **b;
 {
 {
-       static char inumbuf[8];
+       int a_info, b_info;
 
 
-       (void) sprintf(inumbuf, "%5d ", p->fnum);
-       return (inumbuf);
-}
+       a_info = (*a)->fts_info;
+       if (a_info == FTS_ERR)
+               return (0);
+       b_info = (*b)->fts_info;
+       if (b_info == FTS_ERR)
+               return (0);
 
 
-char *
-fmtsize(p)
-       register struct afile *p;
-{
-       static char sizebuf[32];
+       if (a_info == FTS_NS || b_info == FTS_NS)
+               return (namecmp(*a, *b));
 
 
-       (void) sprintf(sizebuf, "%4ld ", kbytes(dbtob(p->fblks)));
-       return (sizebuf);
-}
+       if (a_info == b_info)
+               return (sortfcn(*a, *b));
 
 
-char *
-fmtlstuff(p)
-       register struct afile *p;
-{
-       static char lstuffbuf[256];
-       char gname[32], uname[32], fsize[32], ftime[32];
-       register char *lp = lstuffbuf;
-
-       /* type mode uname gname fsize ftime */
-/* get uname */
-       { char *cp = getname(p->fuid);
-         if (cp)
-               (void) sprintf(uname, "%-9.9s", cp);
-         else
-               (void) sprintf(uname, "%-9d", p->fuid);
-       }
-/* get gname */
-       if (gflg) {
-         char *cp = getgroup(p->fgid);
-         if (cp)
-               (void) sprintf(gname, "%-9.9s", cp);
-         else
-               (void) sprintf(gname, "%-9d", p->fgid);
-       }
-/* get fsize */
-       if (p->ftype == 'b' || p->ftype == 'c')
-               (void) sprintf(fsize, "%3d,%4d",
-                   major(p->fsize), minor(p->fsize));
-       else if (p->ftype == 's')
-               (void) sprintf(fsize, "%8ld", 0);
+       if ((*a)->fts_level == FTS_ROOTLEVEL)
+               if (a_info == FTS_D)
+                       return (1);
+               else if (b_info == FTS_D)
+                       return (-1);
+               else
+                       return (sortfcn(*a, *b));
        else
        else
-               (void) sprintf(fsize, "%8ld", p->fsize);
-/* get ftime */
-       { char *cp = ctime(&p->fmtime);
-         if ((p->fmtime < sixmonthsago) || (p->fmtime > now))
-               (void) sprintf(ftime, " %-7.7s %-4.4s ", cp+4, cp+20);
-         else
-               (void) sprintf(ftime, " %-12.12s ", cp+4);
-       }
-/* splat */
-       *lp++ = p->ftype;
-       lp = fmtmode(lp, p->fflags);
-       (void) sprintf(lp, "%3d %s%s%s%s",
-           p->fnl, uname, gflg ? gname : "", fsize, ftime);
-       return (lstuffbuf);
-}
-
-int    m1[] = { 1, S_IREAD>>0, 'r', '-' };
-int    m2[] = { 1, S_IWRITE>>0, 'w', '-' };
-int    m3[] = { 2, S_ISUID, 's', S_IEXEC>>0, 'x', '-' };
-int    m4[] = { 1, S_IREAD>>3, 'r', '-' };
-int    m5[] = { 1, S_IWRITE>>3, 'w', '-' };
-int    m6[] = { 2, S_ISGID, 's', S_IEXEC>>3, 'x', '-' };
-int    m7[] = { 1, S_IREAD>>6, 'r', '-' };
-int    m8[] = { 1, S_IWRITE>>6, 'w', '-' };
-int    m9[] = { 2, S_ISVTX, 't', S_IEXEC>>6, 'x', '-' };
-
-int    *m[] = { m1, m2, m3, m4, m5, m6, m7, m8, m9};
-
-char *
-fmtmode(lp, flags)
-       char *lp;
-       int flags;
-{
-       int **mp;
-
-       for (mp = &m[0]; mp < &m[sizeof(m)/sizeof(m[0])]; ) {
-               register int *pairp = *mp++;
-               register int n = *pairp++;
-
-               while (--n >= 0 && (flags&*pairp++) == 0)
-                       pairp++;
-               *lp++ = *pairp;
-       }
-       return (lp);
-}
-
-/* rest should be done with nameserver or database */
-
-#include <pwd.h>
-#include <grp.h>
-#include <utmp.h>
-
-struct utmp utmp;
-
-#define NUID   2048
-#define NGID   300
-#define        NMAX    (sizeof (utmp.ut_name))
-
-char   names[NUID][NMAX+1];
-char   outrangename[NMAX+1];
-int    outrangeuid = -1;
-char   groups[NGID][NMAX+1];
-char   outrangegroup[NMAX+1];
-int    outrangegid = -1;
-
-char *
-getname(uid)
-{
-       register struct passwd *pw;
-       static init;
-       struct passwd *getpwent();
-
-       if (uid >= 0 && uid < NUID && names[uid][0])
-               return (&names[uid][0]);
-       if (uid >= 0 && uid == outrangeuid)
-               return (outrangename);
-       if (init == 2) {
-               if (uid < NUID)
-                       return (0);
-               setpwent();
-               while (pw = getpwent()) {
-                       if (pw->pw_uid != uid)
-                               continue;
-                       outrangeuid = pw->pw_uid;
-                       strncpy(outrangename, pw->pw_name, NUID);
-                       endpwent();
-                       return (outrangename);
-               }
-               endpwent();
-               return (0);
-       }
-       if (init == 0)
-               setpwent(), init = 1;
-       while (pw = getpwent()) {
-               if (pw->pw_uid < 0 || pw->pw_uid >= NUID) {
-                       if (pw->pw_uid == uid) {
-                               outrangeuid = pw->pw_uid;
-                               strncpy(outrangename, pw->pw_name, NUID);
-                               return (outrangename);
-                       }
-                       continue;
-               }
-               if (names[pw->pw_uid][0])
-                       continue;
-               strncpy(names[pw->pw_uid], pw->pw_name, NMAX);
-               if (pw->pw_uid == uid) {
-                       return (&names[uid][0]);
-               }
-       }
-       init = 2;
-       endpwent();
-       return (0);
-}
-
-char *
-getgroup(gid)
-{
-       register struct group *gr;
-       static init;
-       struct group *getgrent();
-
-       if (gid >= 0 && gid < NGID && groups[gid][0])
-               return (&groups[gid][0]);
-       if (gid >= 0 && gid == outrangegid)
-               return (outrangegroup);
-       if (init == 2) {
-               if (gid < NGID)
-                       return (0);
-               setgrent();
-               while (gr = getgrent()) {
-                       if (gr->gr_gid != gid)
-                               continue;
-                       outrangegid = gr->gr_gid;
-                       strncpy(outrangegroup, gr->gr_name, NGID);
-                       endgrent();
-                       return (outrangegroup);
-               }
-               endgrent();
-               return (0);
-       }
-       if (init == 0)
-               setgrent(), init = 1;
-       while (gr = getgrent()) {
-               if (gr->gr_gid < 0 || gr->gr_gid >= NGID) {
-                       if (gr->gr_gid == gid) {
-                               outrangegid = gr->gr_gid;
-                               strncpy(outrangegroup, gr->gr_name, NGID);
-                               return (outrangegroup);
-                       }
-                       continue;
-               }
-               if (groups[gr->gr_gid][0])
-                       continue;
-               strncpy(groups[gr->gr_gid], gr->gr_name, NMAX);
-               if (gr->gr_gid == gid) {
-                       return (&groups[gid][0]);
-               }
-       }
-       init = 2;
-       endgrent();
-       return (0);
+               return (sortfcn(*a, *b));
 }
 }