home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / bin / ls / ls.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-12-05  |  13.6 KB  |  543 lines

  1. /*
  2.  * Copyright (c) 1989 The Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * This code is derived from software contributed to Berkeley by
  6.  * Michael Fischbein.
  7.  *
  8.  * Redistribution and use in source and binary forms, with or without
  9.  * modification, are permitted provided that the following conditions
  10.  * are met:
  11.  * 1. Redistributions of source code must retain the above copyright
  12.  *    notice, this list of conditions and the following disclaimer.
  13.  * 2. Redistributions in binary form must reproduce the above copyright
  14.  *    notice, this list of conditions and the following disclaimer in the
  15.  *    documentation and/or other materials provided with the distribution.
  16.  * 3. All advertising materials mentioning features or use of this software
  17.  *    must display the following acknowledgement:
  18.  *    This product includes software developed by the University of
  19.  *    California, Berkeley and its contributors.
  20.  * 4. Neither the name of the University nor the names of its contributors
  21.  *    may be used to endorse or promote products derived from this software
  22.  *    without specific prior written permission.
  23.  *
  24.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  25.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  28.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  29.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  30.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  31.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  33.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  34.  * SUCH DAMAGE.
  35.  */
  36.  
  37. #ifndef lint
  38. static char copyright[] =
  39. "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
  40.  All rights reserved.\n";
  41. #endif /* not lint */
  42.  
  43. #ifndef lint
  44. static char sccsid[] = "@(#)ls.c    5.69 (Berkeley) 10/17/92";
  45. #endif /* not lint */
  46.  
  47. #include <sys/types.h>
  48. #include <sys/stat.h>
  49. #include <sys/ioctl.h>
  50. #include <dirent.h>
  51. #include <unistd.h>
  52. #include <fts.h>
  53. #include <stdlib.h>
  54. #include <string.h>
  55. #include <errno.h>
  56. #include <stdio.h>
  57. #include "ls.h"
  58. #include "extern.h"
  59.  
  60. char    *getbsize __P((char *, int *, long *));
  61. char    *group_from_gid __P((u_int, int));
  62. char    *user_from_uid __P((u_int, int));
  63.  
  64. static void     display __P((FTSENT *, FTSENT *));
  65. static char    *flags_from_fid __P((u_long));
  66. static int     mastercmp __P((const FTSENT **, const FTSENT **));
  67. static void     traverse __P((int, char **, int));
  68.  
  69. static void (*printfcn) __P((DISPLAY *));
  70. static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
  71.  
  72. long blocksize;            /* block size units */
  73. int termwidth = 80;        /* default terminal width */
  74.  
  75. /* flags */
  76. int f_accesstime;        /* use time of last access */
  77. int f_column;            /* columnated format */
  78. int f_flags;            /* show flags associated with a file */
  79. int f_inode;            /* print inode */
  80. int f_listdir;            /* list actual directory, not contents */
  81. int f_listdot;            /* list files beginning with . */
  82. int f_longform;            /* long listing format */
  83. int f_newline;            /* if precede with newline */
  84. int f_nonprint;            /* show unprintables as ? */
  85. int f_nosort;            /* don't sort output */
  86. int f_recursive;        /* ls subdirectories also */
  87. int f_reversesort;        /* reverse whatever sort is used */
  88. int f_sectime;            /* print the real time for all files */
  89. int f_singlecol;        /* use single column output */
  90. int f_size;            /* list size in short listing */
  91. int f_statustime;        /* use time of last mode change */
  92. int f_dirname;            /* if precede with directory name */
  93. int f_timesort;            /* sort by time vice name */
  94. int f_type;            /* add type character for non-regular files */
  95.  
  96. int
  97. main(argc, argv)
  98.     int argc;
  99.     char *argv[];
  100. {
  101.     static char dot[] = ".", *dotav[] = { dot, NULL };
  102.     struct winsize win;
  103.     int ch, fts_options, notused;
  104.     char *p;
  105.  
  106.     /* Terminal defaults to -Cq, non-terminal defaults to -1. */
  107.     if (isatty(STDOUT_FILENO)) {
  108.         if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
  109.             !win.ws_col) {
  110.             if (p = getenv("COLUMNS"))
  111.                 termwidth = atoi(p);
  112.         }
  113.         else
  114.             termwidth = win.ws_col;
  115.         f_column = f_nonprint = 1;
  116.     } else
  117.         f_singlecol = 1;
  118.  
  119.     /* Root is -A automatically. */
  120.     if (!getuid())
  121.         f_listdot = 1;
  122.  
  123.     fts_options = FTS_PHYSICAL;
  124.     while ((ch = getopt(argc, argv, "1ACFLRTacdfgikloqrstu")) != EOF) {
  125.         switch (ch) {
  126.         /*
  127.          * The -1, -C and -l options all override each other so shell
  128.          * aliasing works right.
  129.          */
  130.         case '1':
  131.             f_singlecol = 1;
  132.             f_column = f_longform = 0;
  133.             break;
  134.         case 'C':
  135.             f_column = 1;
  136.             f_longform = f_singlecol = 0;
  137.             break;
  138.         case 'l':
  139.             f_longform = 1;
  140.             f_column = f_singlecol = 0;
  141.             break;
  142.         /* The -c and -u options override each other. */
  143.         case 'c':
  144.             f_statustime = 1;
  145.             f_accesstime = 0;
  146.             break;
  147.         case 'u':
  148.             f_accesstime = 1;
  149.             f_statustime = 0;
  150.             break;
  151.         case 'F':
  152.             f_type = 1;
  153.             break;
  154.         case 'L':
  155.             fts_options &= ~FTS_PHYSICAL;
  156.             fts_options |= FTS_LOGICAL;
  157.             break;
  158.         case 'R':
  159.             f_recursive = 1;
  160.             break;
  161.         case 'a':
  162.             fts_options |= FTS_SEEDOT;
  163.             /* FALLTHROUGH */
  164.         case 'A':
  165.             f_listdot = 1;
  166.             break;
  167.         /* The -d option turns off the -R option. */
  168.         case 'd':
  169.             f_listdir = 1;
  170.             f_recursive = 0;
  171.             break;
  172.         case 'f':
  173.             f_nosort = 1;
  174.             break;
  175.         case 'g':        /* Compatibility with 4.3BSD. */
  176.             break;
  177.         case 'i':
  178.             f_inode = 1;
  179.             break;
  180.         case 'k':        /* Delete before 4.4BSD. */
  181.             (void)fprintf(stderr, "ls: -k no longer supported\n");
  182.             break;
  183.         case 'o':
  184.             f_flags = 1;
  185.             break;
  186.         case 'q':
  187.             f_nonprint = 1;
  188.             break;
  189.         case 'r':
  190.             f_reversesort = 1;
  191.             break;
  192.         case 's':
  193.             f_size = 1;
  194.             break;
  195.         case 'T':
  196.             f_sectime = 1;
  197.             break;
  198.         case 't':
  199.             f_timesort = 1;
  200.             break;
  201.         default:
  202.         case '?':
  203.             usage();
  204.         }
  205.     }
  206.     argc -= optind;
  207.     argv += optind;
  208.  
  209.     /*
  210.      * If not -F, -i, -l, -s or -t options, don't require stat
  211.      * information.
  212.      */
  213.     if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
  214.         fts_options |= FTS_NOSTAT;
  215.  
  216.     /*
  217.      * If not -F, -d or -l options, follow any symbolic links listed on
  218.      * the command line.
  219.      */
  220.     if (!f_longform && !f_listdir && !f_type)
  221.         fts_options |= FTS_COMFOLLOW;
  222.  
  223.     /* If -l or -s, figure out block size. */
  224.     if (f_longform || f_size) {
  225.         (void)getbsize("ls", ¬used, &blocksize);
  226.         blocksize /= 512;
  227.     }
  228.  
  229.     /* Select a sort function. */
  230.     if (f_reversesort) {
  231.         if (!f_timesort)
  232.             sortfcn = revnamecmp;
  233.         else if (f_accesstime)
  234.             sortfcn = revacccmp;
  235.         else if (f_statustime)
  236.             sortfcn = revstatcmp;
  237.         else /* Use modification time. */
  238.             sortfcn = revmodcmp;
  239.     } else {
  240.         if (!f_timesort)
  241.             sortfcn = namecmp;
  242.         else if (f_accesstime)
  243.             sortfcn = acccmp;
  244.         else if (f_statustime)
  245.             sortfcn = statcmp;
  246.         else /* Use modification time. */
  247.             sortfcn = modcmp;
  248.     }
  249.  
  250.     /* Select a print function. */
  251.     if (f_singlecol)
  252.         printfcn = printscol;
  253.     else if (f_longform)
  254.         printfcn = printlong;
  255.     else
  256.         printfcn = printcol;
  257.  
  258.     if (argc)
  259.         traverse(argc, argv, fts_options);
  260.     else
  261.         traverse(1, dotav, fts_options);
  262.     exit(0);
  263. }
  264.  
  265. static int output;            /* If anything output. */
  266.  
  267. /*
  268.  * Traverse() walks the logical directory structure specified by the argv list
  269.  * in the order specified by the mastercmp() comparison function.  During the
  270.  * traversal it passes linked lists of structures to display() which represent
  271.  * a superset (may be exact set) of the files to be displayed.
  272.  */
  273. static void
  274. traverse(argc, argv, options)
  275.     int argc, options;
  276.     char *argv[];
  277. {
  278.     register FTS *ftsp;
  279.     register FTSENT *p;
  280.     int ch_options;
  281.  
  282.     if ((ftsp =
  283.         fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
  284.         err(1, "%s", strerror(errno));
  285.  
  286.     display(NULL, fts_children(ftsp, 0));
  287.     if (f_listdir)
  288.         return;
  289.  
  290.     /*
  291.      * If not recursing down this tree and don't need stat info, just get
  292.      * the names.
  293.      */
  294.     ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
  295.  
  296.     while (p = fts_read(ftsp))
  297.         switch(p->fts_info) {
  298.         case FTS_DC:
  299.             err(0, "%s: directory causes a cycle", p->fts_name);
  300.             break;
  301.         case FTS_DNR:
  302.         case FTS_ERR:
  303.             err(0, "%s: %s",
  304.                 p->fts_name, strerror(p->fts_errno));
  305.             break;
  306.         case FTS_D:
  307.             if (p->fts_level != FTS_ROOTLEVEL &&
  308.                 p->fts_name[0] == '.' && !f_listdot)
  309.                 break;
  310.  
  311.             /*
  312.              * If already output something, put out a newline as
  313.              * a separator.  If multiple arguments, precede each
  314.              * directory with its name.
  315.              */
  316.             if (output)
  317.                 (void)printf("\n%s:\n", p->fts_path);
  318.             else if (argc > 1) {
  319.                 (void)printf("%s:\n", p->fts_path);
  320.                 output = 1;
  321.             }
  322.  
  323.             display(p, fts_children(ftsp, ch_options));
  324.  
  325.             if (!f_recursive)
  326.                 (void)fts_set(ftsp, p, FTS_SKIP);
  327.             break;
  328.         }
  329.     (void)fts_close(ftsp);
  330. }
  331.  
  332. /*
  333.  * Display() takes a linked list of FTSENT structures and passes the list
  334.  * along with any other necessary information to the print function.  P
  335.  * points to the parent directory of the display list.
  336.  */
  337. static void
  338. display(p, list)
  339.     register FTSENT *p;
  340.     FTSENT *list;
  341. {
  342.     register FTSENT *cur;
  343.     struct stat *sp;
  344.     DISPLAY d;
  345.     NAMES *np;
  346.     u_long btotal, maxblock, maxinode, maxlen, maxnlink;
  347.     u_quad_t maxsize;
  348.     int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
  349.     int entries, needstats;
  350.     char *user, *group, *flags, buf[20];    /* 32 bits == 10 digits */
  351.  
  352.     /*
  353.      * If list is NULL there are two possibilities: that the parent
  354.      * directory p has no children, or that fts_children() returned an
  355.      * error.  We ignore the error case since it will be replicated
  356.      * on the next call to fts_read() on the post-order visit to the
  357.      * directory p, and will be signalled in traverse().
  358.      */
  359.     if (list == NULL)
  360.         return;
  361.  
  362.     needstats = f_inode || f_longform || f_size;
  363.     flen = 0;
  364.     btotal = maxblock = maxinode = maxlen = maxnlink = 0;
  365.     bcfile = 0;
  366.     maxuser = maxgroup = maxflags = 0;
  367.     maxsize = 0;
  368.     for (cur = list, entries = 0; cur; cur = cur->fts_link) {
  369.         if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
  370.             err(0, "%s: %s",
  371.                 cur->fts_name, strerror(cur->fts_errno));
  372.             cur->fts_number = NO_PRINT;
  373.             continue;
  374.         }
  375.  
  376.         /*
  377.          * P is NULL if list is the argv list, to which different rules
  378.          * apply.
  379.          */
  380.         if (p == NULL) {
  381.             /* Directories will be displayed later. */
  382.             if (cur->fts_info == FTS_D && !f_listdir) {
  383.                 cur->fts_number = NO_PRINT;
  384.                 continue;
  385.             }
  386.         } else {
  387.             /* Only display dot file if -a/-A set. */
  388.             if (cur->fts_name[0] == '.' && !f_listdot) {
  389.                 cur->fts_number = NO_PRINT;
  390.                 continue;
  391.             }
  392.         }
  393.         if (f_nonprint)
  394.             prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
  395.         if (cur->fts_namelen > maxlen)
  396.             maxlen = cur->fts_namelen;
  397.         if (needstats) {
  398.             sp = cur->fts_statp;
  399.             if (sp->st_blocks > maxblock)
  400.                 maxblock = sp->st_blocks;
  401.             if (sp->st_ino > maxinode)
  402.                 maxinode = sp->st_ino;
  403.             if (sp->st_nlink > maxnlink)
  404.                 maxnlink = sp->st_nlink;
  405.             if (sp->st_size > maxsize)
  406.                 maxsize = sp->st_size;
  407.  
  408.             btotal += sp->st_blocks;
  409.             if (f_longform) {
  410.                 user = user_from_uid(sp->st_uid, 0);
  411.                 if ((ulen = strlen(user)) > maxuser)
  412.                     maxuser = ulen;
  413.                 group = group_from_gid(sp->st_gid, 0);
  414.                 if ((glen = strlen(group)) > maxgroup)
  415.                     maxgroup = glen;
  416.                 if (f_flags) {
  417.                     flags = flags_from_fid(sp->st_flags);
  418.                     if ((flen = strlen(flags)) > maxflags)
  419.                         maxflags = flen;
  420.                 } else
  421.                     flen = 0;
  422.  
  423.                 if ((np = malloc(sizeof(NAMES) +
  424.                     ulen + glen + flen + 3)) == NULL)
  425.                     err(1, "%s", strerror(errno));
  426.  
  427.                 np->user = &np->data[0];
  428.                 (void)strcpy(np->user, user);
  429.                 np->group = &np->data[ulen + 1];
  430.                 (void)strcpy(np->group, group);
  431.  
  432.                 if (S_ISCHR(sp->st_mode) ||
  433.                     S_ISBLK(sp->st_mode))
  434.                     bcfile = 1;
  435.  
  436.                 if (f_flags) {
  437.                     np->flags = &np->data[ulen + glen + 2];
  438.                       (void)strcpy(np->flags, flags);
  439.                 }
  440.                 cur->fts_pointer = np;
  441.             }
  442.         }
  443.         ++entries;
  444.     }
  445.  
  446.     if (!entries)
  447.         return;
  448.  
  449.     d.list = list;
  450.     d.entries = entries;
  451.     d.maxlen = maxlen;
  452.     if (needstats) {
  453.         d.bcfile = bcfile;
  454.         d.btotal = btotal;
  455.         (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
  456.         d.s_block = strlen(buf);
  457.         d.s_flags = maxflags;
  458.         d.s_group = maxgroup;
  459.         (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
  460.         d.s_inode = strlen(buf);
  461.         (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
  462.         d.s_nlink = strlen(buf);
  463.         (void)snprintf(buf, sizeof(buf), "%qu", maxsize);
  464.         d.s_size = strlen(buf);
  465.         d.s_user = maxuser;
  466.     }
  467.  
  468.     printfcn(&d);
  469.     output = 1;
  470.  
  471.     if (f_longform)
  472.         for (cur = list; cur; cur = cur->fts_link)
  473.             free(cur->fts_pointer);
  474. }
  475.  
  476. /*
  477.  * Ordering for mastercmp:
  478.  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
  479.  * as larger than directories.  Within either group, use the sort function.
  480.  * All other levels use the sort function.  Error entries remain unsorted.
  481.  */
  482. static int
  483. mastercmp(a, b)
  484.     const FTSENT **a, **b;
  485. {
  486.     register int a_info, b_info;
  487.  
  488.     a_info = (*a)->fts_info;
  489.     if (a_info == FTS_ERR)
  490.         return (0);
  491.     b_info = (*b)->fts_info;
  492.     if (b_info == FTS_ERR)
  493.         return (0);
  494.  
  495.     if (a_info == FTS_NS || b_info == FTS_NS)
  496.         return (namecmp(*a, *b));
  497.  
  498.     if (a_info == b_info)
  499.         return (sortfcn(*a, *b));
  500.  
  501.     if ((*a)->fts_level == FTS_ROOTLEVEL)
  502.         if (a_info == FTS_D)
  503.             return (1);
  504.         else if (b_info == FTS_D)
  505.             return (-1);
  506.         else
  507.             return (sortfcn(*a, *b));
  508.     else
  509.         return (sortfcn(*a, *b));
  510. }
  511.  
  512. static char *
  513. flags_from_fid(flags)
  514.     u_long flags;
  515. {
  516.     static char buf[20];
  517.     register int comma;
  518.     register char *p;
  519.  
  520.     p = buf;
  521.     if (flags & ARCHIVED) {
  522.         (void)strcpy(p, "arch");
  523.         p += sizeof("arch") - 1;
  524.         comma = 1;
  525.     } else
  526.         comma = 0;
  527.     if (flags & NODUMP) {
  528.         if (comma++)
  529.             *p++ = ',';
  530.         (void)strcpy(p, "nodump");
  531.         p += sizeof("nodump") - 1;
  532.     }
  533.     if (flags & IMMUTABLE) {
  534.         if (comma++)
  535.             *p++ = ',';
  536.         (void)strcpy(p, "nochg");
  537.         p += sizeof("nochg") - 1;
  538.     }
  539.     if (!comma)
  540.         (void)strcpy(p, "-");
  541.     return (buf);
  542. }
  543.