add getwd/chdir for multiple directory operands
[unix-history] / usr / src / bin / ls / ls.c
index 4a010db..b715761 100644 (file)
 /*
 /*
- * Written by Michael Fischbein, currently with Sun Microsystems, Inc.
- * (sun!sunbow!msf)
- * 16 June 1989 18:41
+ * Copyright (c) 1989 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Michael Fischbein.
+ *
+ * Redistribution and use in source and binary forms are permitted
+ * provided that the above copyright notice and this paragraph are
+ * duplicated in all such forms and that any documentation,
+ * advertising materials, and other materials related to such
+ * distribution and use acknowledge that the software was developed
+ * by the University of California, Berkeley.  The name of the
+ * University may not be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  */
  */
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/param.h>
-#include <dirent.h>
-#include <sys/sysmacros.h>
-#include <grp.h>
-#include <pwd.h>
-#include <time.h>
-#include <ctype.h>
 
 
-extern int getopt();
-extern char *optarg;
-extern int optind, opterr;
-extern int stat(), lstat();
+#ifndef lint
+char copyright[] =
+"@(#) Copyright (c) 1989 The Regents of the University of California.\n\
+ All rights reserved.\n";
+#endif /* not lint */
 
 
-int     namecmp();             /* name comparison for qsort */
-int     revnamecmp();
-int     acccmp();              /* access time comparison for qsort */
-int     revacccmp();
-int     modcmp();              /* modify time comparixon for qsort */
-int     revmodcmp();
-int     statcmp();             /* status time comparixon for qsort */
-int     revstatcmp();
-int     printfancy();
-int     prablelen();
-char   *emalloc();
+#ifndef lint
+static char sccsid[] = "@(#)ls.c       5.17 (Berkeley) %G%";
+#endif /* not lint */
 
 
-typedef struct lsstruct {
-       char   *name;           /* pointer to filename */
-       struct stat lstat;
-}       lsstruct;
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <strings.h>
+#include <errno.h>
+#include <stdio.h>
+#include "ls.h"
 
 
+int lstat(), strlen(), prablelen();
+char *emalloc();
 
 int    qflg, Aflg, Cflg, Fflg, Lflg, Rflg, Sflg;
 
 
 int    qflg, Aflg, Cflg, Fflg, Lflg, Rflg, Sflg;
 
-/*
- * entry point for ls.
- * Parse options and call appropriate subroutines
- */
-main(argc, argv)
-int     argc;
-char   *argv[];
+/* flags */
+int f_accesstime;              /* use time of last access */
+int f_firsttime = 1;           /* to control recursion */
+int f_group;                   /* show group ownership of a file */
+int f_ignorelink;              /* indirect through symbolic link operands */
+int f_inode;                   /* print inode */
+int f_listalldot;              /* list . and .. as well */
+int f_listdir;                 /* list actual directory, not contents */
+int f_listdot;                 /* list files beginning with . */
+int f_longform;                        /* long listing format */
+int f_nonprint;                        /* show unprintables as ? */
+int f_recursive;               /* ls subdirectories also */
+int f_reversesort;             /* reverse whatever sort is used */
+int f_singlecol;               /* use single column output */
+int f_size;                    /* list size in short listing */
+int f_specialdir;              /* force params to be directories */
+int f_statustime;              /* use time of last mode change */
+int f_timesort;                        /* sort by time vice name */
+int f_type;                    /* add type character for non-regular files */
 
 
+main(argc, argv)
+       int argc;
+       char **argv;
 {
 {
-       static char options[] = "aAcCdfFgilLqrRstu1";
-       int     inch;           /* input character */
-
- /* set up defaults for terminal/nonterminal stdout */
-       firsttimethruflag = 1;
+       extern int optind, stat();
+       int ch;
+       int namecmp(), revnamecmp(), acccmp(), revacccmp();
+       int modcmp(), revmodcmp(), statcmp(), revstatcmp();
+
+       /*
+        * terminal defaults to -C -q
+        * non-terminal defaults to -1
+        */
        if (isatty(1)) {
        if (isatty(1)) {
-               singlecolflag = 0;
-               sortacrossflag = 0;
-               nonprintflag++;
+               f_nonprint = 1;
                lengthfcn = prablelen;
                lengthfcn = prablelen;
-       } else {
-               singlecolflag++;
-       }
+       } else
+               f_singlecol = 1;
 
 
-       if (getuid() == 0) {
-               listallflag++;
-       }
-       while ((inch = getopt(argc, argv, options)) != -1) {
-               switch (inch) {
-               case 'a':
-                       listallflag++;
-                       listalwaysflag++;
+       /* root is -A automatically */
+       if (!getuid())
+               f_listdot = 1;
+
+       while ((ch = getopt(argc, argv, "1ACFLRacdfgilqrstu")) != EOF) {
+               switch (ch) {
+               /*
+                * -1, -C and -l all override each other
+                * so shell aliasing works right
+                */
+               case '1':
+                       f_singlecol = 1;
+                       f_longform = 0;
                        break;
                        break;
-               case 'A':
-                       listallflag++;
+               case 'C':
+                       f_longform = f_singlecol = 0;
                        break;
                        break;
+               case 'l':
+                       f_longform = 1;
+                       f_singlecol = 0;
+                       break;
+               /* -c and -u override each other */
                case 'c':
                case 'c':
-                       statustimeflag++;
-                       modtimeflag = 0;
-                       accesstimeflag = 0;
+                       f_statustime = 1;
+                       f_accesstime = 0;
                        break;
                        break;
-               case 'C':
-                       singlecolflag = 0;
-                       sortacrossflag = 0;
+               case 'u':
+                       f_accesstime = 1;
+                       f_statustime = 0;
+                       break;
+               case 'F':
+                       f_type = 1;
+                       break;
+               case 'L':
+                       f_ignorelink = 1;
+                       break;
+               case 'R':
+                       f_recursive = 1;
+                       break;
+               case 'a':
+                       f_listalldot = 1;
+                       /* FALLTHROUGH */
+               case 'A':
+                       f_listdot = 1;
                        break;
                case 'S':
                        Sflg++; /* fall into... */
                case 'd':
                        break;
                case 'S':
                        Sflg++; /* fall into... */
                case 'd':
-                       listdirflag++;
+                       f_listdir = 1;
                        break;
                case 'f':
                        break;
                case 'f':
-                       longformflag = 0;
-                       timesortflag = 0;
-                       sizeflag = 0;
-                       reversesortflag = 0;
-                       listallflag++;
-                       listalwaysflag++;
-                       specialdirflag++;
-                       break;
-               case 'F':
-                       fancyflag++;
+                       f_specialdir = 1;
                        break;
                case 'g':
                        break;
                case 'g':
-                       groupflag++;
+                       f_group = 1;
                        break;
                case 'i':
                        break;
                case 'i':
-                       inodeflag++;
-                       break;
-               case 'l':
-                       longformflag++;
-                       numberflag = 0;
-                       singlecolflag = 0;
-                       statfcn = lstat;
-                       if (accesstimeflag == 0 && statustimeflag == 0) {
-                               modtimeflag++;
-                       }
-                       break;
-               case 'L':
-                       statfcn = stat;
+                       f_inode = 1;
                        break;
                case 'q':
                        break;
                case 'q':
-                       nonprintflag++;
+                       f_nonprint = 1;
                        lengthfcn = prablelen;
                        break;
                case 'r':
                        lengthfcn = prablelen;
                        break;
                case 'r':
-                       reversesortflag++;
-                       break;
-               case 'R':
-                       recursiveflag++;
-                       statfcn = lstat;
+                       f_reversesort = 1;
                        break;
                case 's':
                        break;
                case 's':
-                       sizeflag++;
-                       statfcn = lstat;
+                       f_size = 1;
                        break;
                case 't':
                        break;
                case 't':
-                       timesortflag++;
-                       if (accesstimeflag == 0 && statustimeflag == 0) {
-                               modtimeflag++;
-                       }
-                       break;
-               case 'u':
-                       accesstimeflag++;
-                       modtimeflag = 0;
-                       statustimeflag = 0;
-                       break;
-               case '1':
-                       singlecolflag++;
+                       f_timesort = 1;
                        break;
                default:
                case '?':
                        break;
                default:
                case '?':
-                       (void) fprintf(stderr, "Usage: %s [-%s] [file ...]\n", argv[0], options);
-                       exit(1);
+                       usage();
                }
                }
-       }                       /* end of option loop */
- /* do the work */
-       if (argc > optind) {
-               lsdir(argc - optind, &argv[optind]);
-       } else {
-               char   *defname = ".";
-
-               lsdir(1, &defname);
        }
        }
-}
-
-/*
- * list the files in a directory
- */
-
-
-extern int errno;
-
-int     lsdir(argc, argv)
-int     argc;                  /* count of file names passed */
-char   *argv[];                        /* array of file names */
-
-{
-       int     curname;
-       int     goodcount = 0;
-       lsstruct *stats;
-       int     i;
-       static char curpath[MAXPATHLEN + 1];
-       char   *midpt;
-
- /* allocate memory to proceed. Lint complains, but emalloc is aligned */
-       stats = (lsstruct *) emalloc((unsigned) argc * (sizeof(struct lsstruct)));
-
-       for (curname = 0; curname < argc; ++curname) {
-               if (!firsttimethruflag) {
-
-               /*
-                * check for .xxx files. Note can't get listalways without
-                * listall being set
-                */
-                       if (argv[curname][0] == '.' && !listallflag) {
-                               continue;
-                       }
-               /* and now for listalways: . and .. */
-                       if ((argv[curname][0] == '.' && argv[curname][1] == '\0') ||
-                                       (argv[curname][0] == '.' && argv[curname][1] == '.' &&
-                                        argv[curname][2] == '\0')) {
-                               if (!listalwaysflag)
-                                       continue;
-                       }
-               }               /* end of not firsttimethru test */
-               if (firsttimethruflag || longformflag || recursiveflag || timesortflag || sizeflag || inodeflag || fancyflag) {
-                       if (statfcn(argv[curname], &stats[goodcount].lstat) == -1) {
-                               if (errno == ENOENT) {
-                                       (void) fprintf(stderr, "%s not found\n", argv[curname]);
-                                       continue;
-                               } else {
-                                       perror(argv[curname]);
-                                       exit(1);
-                               }
-                       }       /* end of stat error check */
-               }
-               stats[goodcount].name = argv[curname];
-               goodcount++;
-       }                       /* end of per name loop */
-
- /* sort the names */
-       if (goodcount > 1 && !specialdirflag) {
-               if (reversesortflag) {
-                       if (!timesortflag) {
-                               qsort((char *) stats, goodcount, sizeof(struct lsstruct), revnamecmp);
-                       } else {
-                               if (accesstimeflag) {
-                                       qsort((char *) stats, goodcount, sizeof(struct lsstruct), revacccmp);
-                               } else {
-                                       if (modtimeflag) {
-                                               qsort((char *) stats, goodcount, sizeof(struct lsstruct), revmodcmp);
-                                       } else {
-                                               if (statustimeflag) {
-                                                       qsort((char *) stats, goodcount, sizeof(struct lsstruct), revstatcmp);
-                                               } else {
-                                               }
-                                       }
-                               }
-                       }
-               } else {
-                       if (!timesortflag) {
-                               qsort((char *) stats, goodcount, sizeof(struct lsstruct), namecmp);
-                       } else {
-                               if (accesstimeflag) {
-                                       qsort((char *) stats, goodcount, sizeof(struct lsstruct), acccmp);
-                               } else {
-                                       if (modtimeflag) {
-                                               qsort((char *) stats, goodcount, sizeof(struct lsstruct), modcmp);
-                                       } else {
-                                               if (statustimeflag) {
-                                                       qsort((char *) stats, goodcount, sizeof(struct lsstruct), statcmp);
-                                               } else {
-                                               }
-                                       }
-                               }
-                       }
-               }
-       }                       /* end of sort conditionals */
-       prindir(stats, goodcount);
-
-       if ((firsttimethruflag && !listdirflag) || recursiveflag) {
-               for (i = 0; i < goodcount; ++i) {
-               /* recurse on directories */
-                       if ((stats[i].lstat.st_mode & S_IFMT) == S_IFDIR) {
-                       /* don't recurse on . or .. */
-                               if ((stats[i].name[0] == '.' && stats[i].name[1] == '\0') ||
-                                               (stats[i].name[0] == '.' && stats[i].name[1] == '.' && stats[i].name[2] == '\0')) {
-                                       if (!firsttimethruflag) {
-                                               continue;
-                                       }
-                               }
-                               if (chdir(stats[i].name) == -1) {
-                                       perror(stats[i].name);
-                                       break;
-                               }
-                               if (goodcount > 1 || !firsttimethruflag || recursiveflag) {
-                               /* add current name to path */
-                                       if ((midpt = strchr(curpath, (int) '\0')) != curpath) {
-                                               if (midpt[-1] != '/') {
-                                                       *midpt++ = '/';
-                                               }
-                                       }
-                                       (void) strcpy(midpt, stats[i].name);
-
-                                       if (goodcount > 1 || !firsttimethruflag) {
-                                               (void) printf("\n%s:\n", curpath);
-                                       }
-                               }
-                               recursedir(&stats[i]);
-                               if (goodcount > 1 || !firsttimethruflag) {
-                                       *midpt = '\0';
-                               }
-                               if (chdir("..") == -1) {
-                                       perror(stats[i].name);
-                               }
-                       }
-               }               /* end of for loop looking for directories */
-               firsttimethruflag = 0;
+       argc -= optind;
+       argv += optind;
+
+       /* -f turns off -F, -R, -l, -t, -s, -r, turns on -a */
+       if (f_specialdir) {
+               f_longform = f_recursive = f_reversesort = f_size =
+               f_timesort = f_type = 0;
+               f_listdot = f_listalldot = 1;
        }
        }
-       free((char *) stats);
-}
 
 
-/*
- * set up the call to lsdir (lsdir(count, argv-type array))
- * mutually recursive with lsdir
- */
+       /* -d turns off -R */
+       if (f_listdir)
+               f_recursive = 0;
+
+       /* if need to stat files */
+       needstat = f_longform || f_recursive || f_timesort || f_size ||
+           f_inode || f_type;
+
+       /* 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;
+       }
 
 
+       if (argc)
+               args(argc, argv);
+       else
+               curdir();
+       exit(0);
+}
 
 
-recursedir(orig)
-lsstruct *orig;
+curdir()
 {
 {
-       DIR    *dirp;
-       struct dirent *entry;
-       char   *argvblock;
-       char  **argv;
-       int     blocksub = 0;
-       int     vsub = 0;
-       int     oldfirsttimeflag;
+       LS local, *stats;
+       int num;
+       char *names;
 
 
-       if ((dirp = opendir(".")) == NULL) {
-       /* perror(orig->name); more info, less compatible */
-               (void) fprintf(stderr, "%s unreadable\n", orig->name);
-               return;
-       }
- /* wildly overestimate dynamic amount of memory needed */
- /* lint complains about casting off_t to unsigned int. */
-       argvblock = emalloc((unsigned) orig->lstat.st_size);
- /* lint also complains about this alignment.  It's OK */
-       argv = (char **) emalloc((unsigned) orig->lstat.st_size);
-
-       while ((entry = readdir(dirp)) != NULL) {
-               argv[vsub++] = strncpy(&argvblock[blocksub], entry->d_name, (int) entry->d_namlen);
-               blocksub += entry->d_namlen;
-               argvblock[blocksub++] = '\0';
+       if (lstat(local.name = ".", &local.lstat)) {
+               (void)fprintf(stderr, "ls: .: %s\n", strerror(errno));
+               exit(1);
        }
        }
-       (void) closedir(dirp);
-
-       oldfirsttimeflag = firsttimethruflag;
-       firsttimethruflag = 0;
-
-       lsdir(vsub, argv);
-
-       firsttimethruflag = oldfirsttimeflag;
-
-       free(argvblock);
-       free((char *) argv);
+       if (num = buildstats(&local, &stats, &names))
+               ls(stats, num);
 }
 
 }
 
-/*
- * print a statted (if necessary), sorted directory by listing option
- */
-
-int     printaname();
-
-prindir(stats, endcount)
-lsstruct stats[];              /* the statted, sorted directory */
-int     endcount;
+static char path[MAXPATHLEN + 1];
+static char *endofpath = path;
 
 
+args(argc, argv)
+       int argc;
+       char **argv;
 {
 {
-       int     i;              /* subscript to stats */
-       int     maxlen;         /* length of longest name string */
-       int     colwidth;       /* width of a printing column */
-       int     numcols;        /* number of columns */
-       int     collength;      /* lines in longest column */
-       int     base;           /* subscript for leftmost column */
-       int     offset;         /* delta from base to next column */
-       int     chcnt;          /* character count printed */
-       long    blocks;         /* sum of blocks in longform listing */
-
-       if (endcount <= 0) {    /* sanity check; also if only bad names given */
-               return;
+       register LS *dstats, *rstats;
+       register int cnt, dircnt, regcnt;
+       struct stat sb;
+       LS *stats;
+       int num, (*statfcn)(), stat(), lstat();
+       char *names, top[MAXPATHLEN + 1];
+
+       dstats = rstats = NULL;
+       statfcn = f_ignorelink ? stat : lstat;
+       for (dircnt = regcnt = 0; *argv; ++argv) {
+               if (statfcn(*argv, &sb)) {
+                       (void)fprintf(stderr, "ls: %s: %s\n",
+                           *argv, strerror(errno));
+                       if (errno == ENOENT)
+                               continue;
+                       exit(1);
+               }
+               if (!f_specialdir && !f_listdir && S_ISDIR(sb.st_mode)) {
+                       if (!dstats)
+                               dstats = (LS *)emalloc((u_int)argc *
+                                   (sizeof(LS)));
+                       dstats[dircnt].name = *argv;
+                       dstats[dircnt].lstat = sb;
+                       ++dircnt;
+               }
+               else {
+                       if (!rstats)
+                               rstats = (LS *)emalloc((u_int)argc *
+                                   (sizeof(LS)));
+                       rstats[regcnt].name = *argv;
+                       rstats[regcnt].lstat = sb;
+                       ++regcnt;
+               }
        }
        }
-/* don't print out a single directory name as argument first time around */
-       if (!((firsttimethruflag && !listdirflag) && (endcount == 1) && ((stats[0].lstat.st_mode & S_IFMT) == S_IFDIR))) {
-               if (singlecolflag) {
-                       for (i = 0; i < endcount; ++i) {
-                               (void) printaname(&stats[i]);
-                               (void) putchar('\n');
+       if (regcnt) {
+               if (f_specialdir) {
+                       for (cnt = 0; cnt < regcnt; ++cnt) {
+                               if (num = buildstats(rstats++, &stats, &names))
+                                       ls(stats, num);
+                               (void)free((char *)stats);
+                               (void)free((char *)names);
                        }
                        }
-               } else if (longformflag) {
-                       for (i = 0, blocks = 0; i < endcount; ++i) {
-                               blocks += stats[i].lstat.st_blocks;
-                       }
-                       (void) printf("total %ld\n", blocks / 2);
-                       for (i = 0; i < endcount; ++i) {
-                               if (inodeflag) {
-                                       (void) printf("%6d ", stats[i].lstat.st_ino);
-                               }
-                               if (sizeflag) {
-                                       (void) printf("%4d ", stats[i].lstat.st_blocks / 2);
-                               }
-                               printperms(stats[i].lstat.st_mode);
-                               (void) printf("%3d ", stats[i].lstat.st_nlink);
-                               printowner(stats[i].lstat.st_uid);
-                               if (groupflag) {
-                                       printgrp(stats[i].lstat.st_gid);
-                               }
-                               if (((stats[i].lstat.st_mode & S_IFMT) == S_IFCHR) ||
-                                               ((stats[i].lstat.st_mode & S_IFMT) == S_IFBLK)) {
-                                       (void) printf("%3d,%4d ", major(stats[i].lstat.st_rdev), minor(stats[i].lstat.st_rdev));
-                               } else {
-                                       (void) printf("%8d ", stats[i].lstat.st_size);
-                               }
-                               if (accesstimeflag) {
-                                       printtime(stats[i].lstat.st_atime);
-                               } else if (statustimeflag) {
-                                       printtime(stats[i].lstat.st_ctime);
-                               } else {
-                                       printtime(stats[i].lstat.st_mtime);
-                               }
-                               (void) printf("%s", stats[i].name);
-                               if (fancyflag) {
-                                       (void) printfancy(stats[i].lstat.st_mode);
-                               }
-                               if ((stats[i].lstat.st_mode & S_IFMT) == S_IFLNK) {
-                                       char    buf[MAXPATHLEN + 1];
-                                       int     j;
-
-                                       if ((j = readlink(stats[i].name, buf, MAXPATHLEN)) == -1) {
-                                               perror(stats[i].name);
-                                               (void) putchar('\n');
-                                               continue;
-                                       }
-                                       buf[j + 1] = '\0';
-                                       (void) printf(" -> %s", buf);
-                               }
-                               (void) putchar('\n');
-                       }
-               } else {
-
-               /*
-                * assume tabs every 8 columns WARNING: bad code (hard coded
-                * constants) follows:
-                */
-
-               /* figure out max width */
-                       maxlen = 0;
-                       for (i = 0; i < endcount; ++i) {
-                               if (maxlen < lengthfcn(stats[i].name)) {
-                                       maxlen = lengthfcn(stats[i].name);
-                               }
-                       }       /* end of determining max width of name */
+               } else
+                       ls(rstats, regcnt);
+               if (dircnt)
+                       (void)putchar('\n');
+       }
+       if (dircnt) {
+               register char *p;
 
 
-               /* add fudge factors to max name length */
-                       if (inodeflag) {
-                               maxlen += 6;
-                       }
-                       if (sizeflag) {
-                               maxlen += 5;
-                       }
-                       if (fancyflag) {
-                               maxlen += 1;
+               if (dircnt > 1) {
+                       (void)getwd(top);
+                       qsort((char *)dstats, dircnt, sizeof(LS), sortfcn);
+               }
+               for (cnt = 0; cnt < dircnt; ++dstats) {
+                       for (endofpath = path, p = dstats->name;
+                           *endofpath = *p++; ++endofpath);
+                       ls_dir(dstats, cnt, regcnt || dircnt > 1);
+                       if (++cnt < dircnt && chdir(top)) {
+                               (void)fprintf(stderr, "ls: %s: %s\n",
+                                   top, strerror(errno));
+                               exit(1);
                        }
                        }
-                       colwidth = (maxlen + 9) & ~0x7; /* one tab after maxlen */
-                       numcols = (80 + colwidth - maxlen) / colwidth;
-                       collength = (int) ((float) endcount / (float) numcols + 0.999);
-
-                       for (base = 0; base < collength; base++) {
-                               for (offset = 0, i = 0; i < numcols; ++i, offset += collength) {
-
-                                       if ((base + offset) >= endcount) {
-                                               break;
-                                       }
-                                       chcnt = printaname(&stats[base + offset]);
-
-                                       if ((base + offset + collength) < endcount) {
-                                               while (chcnt + 8 < colwidth) {
-                                                       (void) putchar('\t');
-                                                       chcnt += 8;
-                                               }
-                                               if (chcnt < colwidth) {
-                                                       (void) putchar('\t');
-                                               }
-                                               chcnt = (chcnt + 8) & ~0x7;
-                                       }
-                               }
-                               if (base + offset < endcount) {
-                                       (void) printaname(&stats[base + offset]);
-                               }
-                               (void) printf("\n");
-                       }       /* end of base and offset loop */
                }
        }
                }
        }
+#ifdef whybother
+       (void)free((char *)rstats);
+       (void)free((char *)dstats);
+#endif
 }
 
 }
 
-/*
- * print [inode] [size] name
- * return # of characters printed
- * no trailing characters
- */
-int     printaname(entry)
-lsstruct *entry;
+ls(stats, num)
+       LS *stats;
+       register int num;
 {
 {
-       int     chcnt = 0;
-
-       if (inodeflag) {
-               chcnt += printf("%5d ", entry->lstat.st_ino);
-       }
-       if (sizeflag) {
-               chcnt += printf("%4d ", entry->lstat.st_blocks / 2);
-       }
-       chcnt += printf("%s", entry->name);
-
-       if (fancyflag) {
-               return (chcnt + printfancy(entry->lstat.st_mode));
-       }
-       return chcnt;
-}
+       register char *p, *savedpath;
+       LS *lp;
 
 
-/*
- * print group and user name
- */
+       if (num > 1 && !f_specialdir)
+               qsort((char *)stats, num, sizeof(LS), sortfcn);
 
 
+       printdir(stats, num);
 
 
-
-printgrp(groupid)
-short   groupid;
-{
-       struct group *groupentry;
-
-       if ((groupentry = getgrgid((int) groupid)) == NULL) {
-       /* can't find group, print out number instead */
-               (void) printf("%-9d ", groupid);
-               return;
+       if (f_recursive) {
+               savedpath = endofpath;
+               for (lp = stats; num--; ++lp) {
+                       if (!S_ISDIR(lp->lstat.st_mode))
+                               continue;
+                       p = lp->name;
+                       if (p[0] == '.' && (!p[1] || p[1] == '.' && !p[2]))
+                               continue;
+                       if (endofpath != path && endofpath[-1] != '/')
+                               *endofpath++ = '/';
+                       for (; *endofpath = *p++; ++endofpath);
+                       ls_dir(lp, 1, 1);
+                       *(endofpath = savedpath) = '\0';
+               }
        }
        }
-       (void) printf("%-9s", groupentry->gr_name);
-       (void) getgrent();      /* to rewind group file */
 }
 
 }
 
-
-printowner(uid)
-short   uid;
+ls_dir(lp, newline, tag)
+       LS *lp;
+       int newline, tag;
 {
 {
-       struct passwd *pwentry;
-
-       if ((pwentry = getpwuid((int) uid)) == NULL) {
-       /* can't find owner, print out number instead */
-               (void) printf("%-9d ", uid);
+       LS *stats;
+       int num;
+       char *names;
+
+       if (newline)
+               (void)putchar('\n');
+       if (tag)
+               (void)printf("%s:\n", path);
+
+       if (chdir(lp->name)) {
+               (void)fprintf(stderr, "ls: %s: %s\n",
+                   lp->name, strerror(errno));
                return;
        }
                return;
        }
-       (void) printf("%-9s", pwentry->pw_name);
-       (void) getpwent();
+       if (num = buildstats(lp, &stats, &names))
+               ls(stats, num);
+       (void)free((char *)stats);
+       (void)free((char *)names);
+       if (chdir("..")) {
+               (void)fprintf(stderr, "ls: ..: %s\n", strerror(errno));
+               exit(1);
+       }
 }
 
 }
 
-#define SIXMONTHS 6l*30l*24l*3600l
-time_t  time();
-
-printtime(ftime)
-time_t  ftime;
+static
+buildstats(lp, s_stats, s_names)
+       LS *lp, **s_stats;
+       char **s_names;
 {
 {
-       int     i;
-       char   *longstring;
-
-       longstring = ctime((long *) &ftime);
-
-       for (i = 4; i < 11; ++i) {
-               (void) putchar(longstring[i]);
+       register int cnt, maxentry;
+       register char *p, *names;
+       struct dirent *entry;
+       LS *stats;
+       DIR *dirp;
+
+       /* make this big so we don't realloc often */
+#define        DEFNUM  256
+       maxentry = DEFNUM;
+       *s_stats = stats = (LS *)emalloc((u_int)DEFNUM * sizeof(LS));
+       *s_names = names = emalloc((u_int)lp->lstat.st_size);
+
+       if (!(dirp = opendir(f_specialdir ? lp->name : "."))) {
+               (void)fprintf(stderr, "ls: %s: %s\n",
+                   lp->name, strerror(errno));
+               return(0);
        }
        }
-
-       if (ftime + SIXMONTHS > time((time_t *) NULL)) {
-               for (i = 11; i < 16; ++i) {
-                       (void) putchar(longstring[i]);
+       for (cnt = 0; entry = readdir(dirp);) {
+               p = entry->d_name;
+               if (p[0] == '.') {
+                       if (!f_listdot)
+                               continue;
+                       if (!f_listalldot && (!p[1] || p[1] == '.' && !p[2]))
+                               continue;
                }
                }
-       } else {
-               (void) putchar(' ');
-               for (i = 20; i < 24; ++i) {
-                       (void) putchar(longstring[i]);
+               if (cnt == maxentry) {
+                       maxentry += DEFNUM;
+                       if (!(stats = (LS *)realloc((char *)stats,
+                           (u_int)maxentry * sizeof(LS))))
+                               nomem();
                }
                }
-       }
-       (void) putchar(' ');
-}
-
-/*
- * act like strlen, but also translate non-printing chars to '?'
- */
-
-
-int     prablelen(cp)
-char   *cp;
-{
-       register int len = 0;
-
-       while (*cp != '\0') {
-               if (!isprint(*cp)) {
-                       *cp = '?';
+               if (needstat && lstat(entry->d_name, &stats[cnt].lstat)) {
+                       (void)fprintf(stderr, "ls: %s: %s\n",
+                           entry->d_name, strerror(errno));
+                       if (errno == ENOENT)
+                               continue;
+                       exit(1);
                }
                }
-               ++len;
-               ++cp;
-       }
-       return len;
-}
-
-/*
- * do the permissions printing, passed the mode
- */
-
-printperms(mode)
-u_short mode;
-{
- /* print type */
-       switch (mode & S_IFMT) {
-       case S_IFDIR:           /* directory */
-               (void) putchar('d');
-               break;
-       case S_IFCHR:           /* character special */
-               (void) putchar('c');
-               break;
-       case S_IFBLK:           /* block special */
-               (void) putchar('b');
-               break;
-       case S_IFREG:           /* regular */
-               (void) putchar('-');
-               break;
-       case S_IFLNK:           /* symbolic link */
-               (void) putchar('l');
-               break;
-       case S_IFSOCK:          /* socket */
-               (void) putchar('s');
-               break;
-#ifdef S_IFIFO
-       case S_IFIFO:           /* fifo */
-               (void) putchar('p');
-               break;
-#endif
-       default:                /* unknown */
-               (void) putchar('?');
-               break;
-       }
- /* usr */
-       if (mode & S_IRUSR) {
-               (void) putchar('r');
-       } else {
-               (void) putchar('-');
-       }
-       if (mode & S_IWUSR) {
-               (void) putchar('w');
-       } else {
-               (void) putchar('-');
-       }
-       switch (mode & (S_IXUSR | S_ISUID)) {
-       case 0:
-               (void) putchar('-');
-               break;
-       case S_IXUSR:
-               (void) putchar('x');
-               break;
-       case S_ISUID:
-               (void) putchar('S');
-               break;
-       case S_IXUSR | S_ISUID:
-               (void) putchar('s');
-               break;
-       }
- /* group */
-       if (mode & S_IRGRP) {
-               (void) putchar('r');
-       } else {
-               (void) putchar('-');
-       }
-       if (mode & S_IWGRP) {
-               (void) putchar('w');
-       } else {
-               (void) putchar('-');
-       }
-       switch (mode & (S_IXGRP | S_ISGID)) {
-       case 0:
-               (void) putchar('-');
-               break;
-       case S_IXGRP:
-               (void) putchar('x');
-               break;
-       case S_ISGID:
-               (void) putchar('S');
-               break;
-       case S_IXGRP | S_ISGID:
-               (void) putchar('s');
-               break;
-       }
- /* other */
-       if (mode & S_IROTH) {
-               (void) putchar('r');
-       } else {
-               (void) putchar('-');
-       }
-       if (mode & S_IWOTH) {
-               (void) putchar('w');
-       } else {
-               (void) putchar('-');
-       }
-       switch (mode & (S_IXOTH | S_ISVTX)) {
-       case 0:
-               (void) putchar('-');
-               break;
-       case S_IXOTH:
-               (void) putchar('x');
-               break;
-       case S_ISVTX:
-               (void) putchar('T');
-               break;
-       case S_IXOTH | S_ISVTX:
-               (void) putchar('t');
-               break;
-       }
-}
-
-int     printfancy(mode)
-u_short mode;
-{
-       if ((mode & S_IFMT) == S_IFDIR) {
-               (void) putchar('/');
-               return 1;
-       }
-       if ((mode & S_IFMT) == S_IFLNK && !longformflag) {
-               (void) putchar('@');
-               return 1;
-       }
-       if ((mode & S_IFMT) == S_IFSOCK) {
-               (void) putchar('=');
-               return 1;
-       }
-       if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
-               (void) putchar('*');
-               return 1;
-       }
-       return 0;
-}
-
-/*
- * error checks for dynamic memory;
- * comparison routines for various calls to qsort(3)
- */
-
-int     namecmp(a, b)
-lsstruct *a, *b;
-{
-       return strcmp(a->name, b->name);
-}
-
-int     revnamecmp(a, b)
-lsstruct *a, *b;
-{
-       return strcmp(b->name, a->name);
-}
-
-int     modcmp(a, b)
-lsstruct *a, *b;
-{
-       return (a->lstat.st_mtime < b->lstat.st_mtime);
-}
-
-int     revmodcmp(a, b)
-lsstruct *a, *b;
-{
-       return (b->lstat.st_mtime < a->lstat.st_mtime);
-}
-
-int     acccmp(a, b)
-lsstruct *a, *b;
-{
-       return (a->lstat.st_atime < b->lstat.st_atime);
-}
-
-int     revacccmp(a, b)
-lsstruct *a, *b;
-{
-       return (b->lstat.st_atime < a->lstat.st_atime);
-}
-
-int     statcmp(a, b)
-lsstruct *a, *b;
-{
-       return (a->lstat.st_ctime < b->lstat.st_ctime);
-}
-
-int     revstatcmp(a, b)
-lsstruct *a, *b;
-{
-       return (b->lstat.st_ctime < a->lstat.st_ctime);
-}
-
-char   *malloc();
-
-char   *emalloc(size)
-unsigned size;
-{
-       register char *retval;
-
-       if ((retval = malloc(size)) == NULL) {
-               perror("Can't find memory");
-               exit(1);
+               stats[cnt].name = names;
+               bcopy(entry->d_name, names, (int)entry->d_namlen);
+               names += entry->d_namlen;
+               *names++ = '\0';
+               ++cnt;
        }
        }
-       return retval;
+       closedir(dirp);
+       return(cnt);
 }
 }