2 * Copyright (c) 1989, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1989, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)ls.c 8.5 (Berkeley) 4/2/94";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
47 #include <sys/param.h>
49 #include <sys/ioctl.h>
75 * Upward approximation of the maximum number of characters needed to
76 * represent a value of integral type t as a string, excluding the
77 * NUL terminator, with provision for a sign.
79 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
82 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
83 * into a number that wide in decimal.
84 * XXX: Overflows are not considered.
86 #define MAKENINES(n) \
90 /* Use a loop as all values of n are small. */ \
91 for (i = 1; n > 0; i *= 10) \
96 static void display(const FTSENT *, FTSENT *, int);
97 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
98 static void traverse(int, char **, int);
100 static void (*printfcn)(const DISPLAY *);
101 static int (*sortfcn)(const FTSENT *, const FTSENT *);
103 long blocksize; /* block size units */
104 int termwidth = 80; /* default terminal width */
107 int f_accesstime; /* use time of last access */
108 int f_birthtime; /* use time of birth */
109 int f_flags; /* show flags associated with a file */
110 int f_humanval; /* show human-readable file sizes */
111 int f_inode; /* print inode */
112 static int f_kblocks; /* print size in kilobytes */
113 int f_label; /* show MAC label */
114 static int f_listdir; /* list actual directory, not contents */
115 static int f_listdot; /* list files beginning with . */
116 int f_longform; /* long listing format */
117 static int f_noautodot; /* do not automatically enable -A for root */
118 static int f_nofollow; /* don't follow symbolic link arguments */
119 int f_nonprint; /* show unprintables as ? */
120 static int f_nosort; /* don't sort output */
121 int f_notabs; /* don't use tab-separated multi-col output */
122 int f_numericonly; /* don't convert uid/gid to name */
123 int f_octal; /* show unprintables as \xxx */
124 int f_octal_escape; /* like f_octal but use C escapes if possible */
125 static int f_recursive; /* ls subdirectories also */
126 static int f_reversesort; /* reverse whatever sort is used */
127 int f_samesort; /* sort time and name in same direction */
128 int f_sectime; /* print full time information */
129 static int f_singlecol; /* use single column output */
130 int f_size; /* list size in short listing */
131 static int f_sizesort;
132 int f_slash; /* similar to f_type, but only for dirs */
133 int f_sortacross; /* sort across rows, not down columns */
134 int f_statustime; /* use time of last mode change */
135 static int f_stream; /* stream the output, separate with commas */
136 int f_thousands; /* show file sizes with thousands separators */
137 char *f_timeformat; /* user-specified time format */
138 static int f_timesort; /* sort by time vice name */
139 int f_type; /* add type character for non-regular files */
140 static int f_whiteout; /* show whiteout entries */
143 int f_color; /* add type in color for non-regular files */
145 char *ansi_bgcol; /* ANSI sequence to set background colour */
146 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
147 char *ansi_coloff; /* ANSI sequence to reset colours */
148 char *attrs_off; /* ANSI sequence to turn off attributes */
149 char *enter_bold; /* ANSI sequence to set color to bold mode */
155 main(int argc, char *argv[])
157 static char dot[] = ".", *dotav[] = {dot, NULL};
159 int ch, fts_options, notused;
161 const char *errstr = NULL;
163 char termcapbuf[1024]; /* termcap definition buffer */
164 char tcapbuf[512]; /* capability buffer */
168 (void)setlocale(LC_ALL, "");
170 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
171 if (isatty(STDOUT_FILENO)) {
173 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
174 termwidth = strtonum(p, 0, INT_MAX, &errstr);
175 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
177 termwidth = win.ws_col;
181 /* retrieve environment variable, in case of explicit -C */
182 p = getenv("COLUMNS");
184 termwidth = strtonum(p, 0, INT_MAX, &errstr);
190 fts_options = FTS_PHYSICAL;
191 if (getenv("LS_SAMESORT"))
194 argc = xo_parse_args(argc, argv);
197 xo_set_flags(NULL, XOF_COLUMNS);
198 xo_set_version(LS_XO_VERSION);
200 while ((ch = getopt(argc, argv,
201 "1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuwxy,")) != -1) {
204 * The -1, -C, -x and -l options all override each other so
205 * shell aliasing works right.
213 f_sortacross = f_longform = f_singlecol = 0;
225 /* The -c, -u, and -U options override each other. */
245 fts_options |= FTS_SEEDOT;
250 /* The -t and -S options override each other. */
259 /* Other flags. Please keep alphabetic. */
269 f_timeformat = optarg;
276 setenv("CLICOLOR", "", 1);
279 fts_options |= FTS_COMFOLLOW;
286 fts_options &= ~FTS_PHYSICAL;
287 fts_options |= FTS_LOGICAL;
291 fts_options &= ~FTS_COMFOLLOW;
292 fts_options &= ~FTS_LOGICAL;
293 fts_options |= FTS_PHYSICAL;
313 /* The -d option turns off the -R option. */
318 case 'g': /* Compatibility with 4.3BSD. */
372 /* Root is -A automatically unless -I. */
373 if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
376 /* Enabling of colours is conditional on the environment. */
377 if (getenv("CLICOLOR") &&
378 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
380 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
381 ansi_fgcol = tgetstr("AF", &bp);
382 ansi_bgcol = tgetstr("AB", &bp);
383 attrs_off = tgetstr("me", &bp);
384 enter_bold = tgetstr("md", &bp);
386 /* To switch colours off use 'op' if
387 * available, otherwise use 'oc', or
388 * don't do colours at all. */
389 ansi_coloff = tgetstr("op", &bp);
391 ansi_coloff = tgetstr("oc", &bp);
392 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
396 xo_warnx("color support not compiled in");
402 * We can't put tabs and color sequences together:
403 * column number will be incremented incorrectly
404 * for "stty oxtabs" mode.
407 (void)signal(SIGINT, colorquit);
408 (void)signal(SIGQUIT, colorquit);
409 parsecolors(getenv("LSCOLORS"));
414 * If not -F, -i, -l, -s, -S or -t options, don't require stat
415 * information, unless in color mode in which case we do
416 * need this to determine which colors to display.
418 if (!f_inode && !f_longform && !f_size && !f_timesort &&
419 !f_sizesort && !f_type
424 fts_options |= FTS_NOSTAT;
427 * If not -F, -P, -d or -l options, follow any symbolic links listed on
428 * the command line, unless in color mode in which case we need to
429 * distinguish file type for a symbolic link itself and its target.
431 if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash)
436 fts_options |= FTS_COMFOLLOW;
439 * If -W, show whiteout entries
443 fts_options |= FTS_WHITEOUT;
446 /* If -i, -l or -s, figure out block size. */
447 if (f_inode || f_longform || f_size) {
451 (void)getbsize(¬used, &blocksize);
455 /* Select a sort function. */
457 if (!f_timesort && !f_sizesort)
458 sortfcn = revnamecmp;
460 sortfcn = revsizecmp;
461 else if (f_accesstime)
463 else if (f_birthtime)
464 sortfcn = revbirthcmp;
465 else if (f_statustime)
466 sortfcn = revstatcmp;
467 else /* Use modification time. */
470 if (!f_timesort && !f_sizesort)
474 else if (f_accesstime)
476 else if (f_birthtime)
478 else if (f_statustime)
480 else /* Use modification time. */
484 /* Select a print function. */
486 printfcn = printscol;
488 printfcn = printlong;
490 printfcn = printstream;
494 xo_open_container("file-information");
496 traverse(argc, argv, fts_options);
498 traverse(1, dotav, fts_options);
499 xo_close_container("file-information");
504 static int output; /* If anything output. */
507 * Traverse() walks the logical directory structure specified by the argv list
508 * in the order specified by the mastercmp() comparison function. During the
509 * traversal it passes linked lists of structures to display() which represent
510 * a superset (may be exact set) of the files to be displayed.
513 traverse(int argc, char *argv[], int options)
521 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
522 xo_err(1, "fts_open");
525 * We ignore errors from fts_children here since they will be
526 * replicated and signalled on the next call to fts_read() below.
528 chp = fts_children(ftsp, 0);
530 display(NULL, chp, options);
535 * If not recursing down this tree and don't need stat info, just get
538 ch_options = !f_recursive && !f_label &&
539 options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
541 while ((p = fts_read(ftsp)) != NULL)
542 switch (p->fts_info) {
544 xo_warnx("%s: directory causes a cycle", p->fts_name);
548 xo_warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
552 if (p->fts_level != FTS_ROOTLEVEL &&
553 p->fts_name[0] == '.' && !f_listdot)
558 xo_open_list("directory");
560 xo_open_instance("directory");
563 * If already output something, put out a newline as
564 * a separator. If multiple arguments, precede each
565 * directory with its name.
569 (void)printname("path", p->fts_path);
571 } else if (argc > 1) {
572 (void)printname("path", p->fts_path);
576 chp = fts_children(ftsp, ch_options);
577 display(p, chp, options);
579 xo_close_instance("directory");
580 if (!f_recursive && chp != NULL)
581 (void)fts_set(ftsp, p, FTS_SKIP);
587 xo_close_list("directory");
589 xo_err(1, "fts_read");
593 * Display() takes a linked list of FTSENT structures and passes the list
594 * along with any other necessary information to the print function. P
595 * points to the parent directory of the display list.
598 display(const FTSENT *p, FTSENT *list, int options)
607 u_long btotal, labelstrlen, maxlen, maxnlink;
613 size_t flen, ulen, glen;
615 int entries, needstats;
616 const char *user, *group;
617 char *flags, *labelstr = NULL;
618 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
619 char nuser[STRBUF_SIZEOF(gid_t) + 1];
621 needstats = f_inode || f_longform || f_size;
624 initmax = getenv("LS_COLWIDTHS");
625 /* Fields match -lios order. New ones should be added at the end. */
626 maxlabelstr = maxblock = maxlen = maxnlink = 0;
627 maxuser = maxgroup = maxflags = maxsize = 0;
629 if (initmax != NULL && *initmax != '\0') {
630 char *initmax2, *jinitmax;
633 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
634 jinitmax = malloc(strlen(initmax) * 2 + 2);
635 if (jinitmax == NULL)
639 strcpy(initmax2, "0:"), initmax2 += 2;
641 *initmax2++ = *initmax, *initmax2 = '\0';
642 for (initmax++; *initmax != '\0'; initmax++) {
643 if (initmax[-1] == ':' && initmax[0] == ':') {
645 *initmax2++ = initmax[0];
648 *initmax2++ = initmax[0];
652 if (initmax2[-1] == ':')
653 strcpy(initmax2, "0");
655 ninitmax = sscanf(jinitmax,
656 " %ju : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
657 &maxinode, &maxblock, &maxnlink, &maxuser,
658 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
705 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
706 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
708 cur->fts_name, strerror(cur->fts_errno));
709 cur->fts_number = NO_PRINT;
714 * P is NULL if list is the argv list, to which different rules
718 /* Directories will be displayed later. */
719 if (cur->fts_info == FTS_D && !f_listdir) {
720 cur->fts_number = NO_PRINT;
724 /* Only display dot file if -a/-A set. */
725 if (cur->fts_name[0] == '.' && !f_listdot) {
726 cur->fts_number = NO_PRINT;
730 if (cur->fts_namelen > maxlen)
731 maxlen = cur->fts_namelen;
732 if (f_octal || f_octal_escape) {
733 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
740 if (sp->st_blocks > maxblock)
741 maxblock = sp->st_blocks;
742 if (sp->st_ino > maxinode)
743 maxinode = sp->st_ino;
744 if (sp->st_nlink > maxnlink)
745 maxnlink = sp->st_nlink;
746 if (sp->st_size > maxsize)
747 maxsize = sp->st_size;
749 btotal += sp->st_blocks;
752 (void)snprintf(nuser, sizeof(nuser),
754 (void)snprintf(ngroup, sizeof(ngroup),
759 user = user_from_uid(sp->st_uid, 0);
760 group = group_from_gid(sp->st_gid, 0);
762 if ((ulen = strlen(user)) > maxuser)
764 if ((glen = strlen(group)) > maxgroup)
767 flags = fflagstostr(sp->st_flags);
768 if (flags != NULL && *flags == '\0') {
773 xo_err(1, "fflagstostr");
774 flen = strlen(flags);
775 if (flen > (size_t)maxflags)
781 char name[PATH_MAX + 1];
785 error = mac_prepare_file_label(&label);
787 xo_warn("MAC label for %s/%s",
788 cur->fts_parent->fts_path,
793 if (cur->fts_level == FTS_ROOTLEVEL)
794 snprintf(name, sizeof(name),
795 "%s", cur->fts_name);
797 snprintf(name, sizeof(name),
798 "%s/%s", cur->fts_parent->
799 fts_accpath, cur->fts_name);
801 if (options & FTS_LOGICAL)
802 error = mac_get_file(name,
805 error = mac_get_link(name,
808 xo_warn("MAC label for %s/%s",
809 cur->fts_parent->fts_path,
815 error = mac_to_text(label,
818 xo_warn("MAC label for %s/%s",
819 cur->fts_parent->fts_path,
826 if (labelstr == NULL)
827 labelstr = strdup("-");
828 labelstrlen = strlen(labelstr);
829 if (labelstrlen > maxlabelstr)
830 maxlabelstr = labelstrlen;
834 if ((np = malloc(sizeof(NAMES) + labelstrlen +
835 ulen + glen + flen + 4)) == NULL)
838 np->user = &np->data[0];
839 (void)strcpy(np->user, user);
840 np->group = &np->data[ulen + 1];
841 (void)strcpy(np->group, group);
843 if (S_ISCHR(sp->st_mode) ||
844 S_ISBLK(sp->st_mode)) {
845 sizelen = snprintf(NULL, 0,
846 "%#jx", (uintmax_t)sp->st_rdev);
847 if (d.s_size < sizelen)
852 np->flags = &np->data[ulen + glen + 2];
853 (void)strcpy(np->flags, flags);
857 np->label = &np->data[ulen + glen + 2
858 + (f_flags ? flen + 1 : 0)];
859 (void)strcpy(np->label, labelstr);
862 cur->fts_pointer = np;
869 * If there are no entries to display, we normally stop right
870 * here. However, we must continue if we have to display the
871 * total block count. In this case, we display the total only
872 * on the second (p != NULL) pass.
874 if (!entries && (!(f_longform || f_size) || p == NULL))
882 d.s_block = snprintf(NULL, 0, "%lu", howmany(maxblock, blocksize));
883 d.s_flags = maxflags;
884 d.s_label = maxlabelstr;
885 d.s_group = maxgroup;
886 d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
887 d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
888 sizelen = f_humanval ? HUMANVALSTR_LEN :
889 snprintf(NULL, 0, "%ju", maxsize);
890 if (d.s_size < sizelen)
894 if (f_thousands) /* make space for commas */
895 d.s_size += (d.s_size - 1) / 3;
900 for (cur = list; cur; cur = cur->fts_link)
901 free(cur->fts_pointer);
905 * Ordering for mastercmp:
906 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
907 * as larger than directories. Within either group, use the sort function.
908 * All other levels use the sort function. Error entries remain unsorted.
911 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
915 a_info = (*a)->fts_info;
916 if (a_info == FTS_ERR)
918 b_info = (*b)->fts_info;
919 if (b_info == FTS_ERR)
922 if (a_info == FTS_NS || b_info == FTS_NS)
923 return (namecmp(*a, *b));
925 if (a_info != b_info &&
926 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
932 return (sortfcn(*a, *b));