2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
43 static char sccsid[] = "@(#)ls.c 8.5 (Berkeley) 4/2/94";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 #include <sys/param.h>
51 #include <sys/ioctl.h>
78 * Upward approximation of the maximum number of characters needed to
79 * represent a value of integral type t as a string, excluding the
80 * NUL terminator, with provision for a sign.
82 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
85 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
86 * into a number that wide in decimal.
87 * XXX: Overflows are not considered.
89 #define MAKENINES(n) \
93 /* Use a loop as all values of n are small. */ \
94 for (i = 1; n > 0; i *= 10) \
99 static void display(const FTSENT *, FTSENT *, int);
100 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
101 static void traverse(int, char **, int);
103 #define COLOR_OPT (CHAR_MAX + 1)
105 static const struct option long_opts[] =
108 {"color", optional_argument, NULL, COLOR_OPT},
110 {NULL, no_argument, NULL, 0}
113 static void (*printfcn)(const DISPLAY *);
114 static int (*sortfcn)(const FTSENT *, const FTSENT *);
116 long blocksize; /* block size units */
117 int termwidth = 80; /* default terminal width */
120 int f_accesstime; /* use time of last access */
121 int f_birthtime; /* use time of birth */
122 int f_flags; /* show flags associated with a file */
123 int f_humanval; /* show human-readable file sizes */
124 int f_inode; /* print inode */
125 static int f_kblocks; /* print size in kilobytes */
126 int f_label; /* show MAC label */
127 static int f_listdir; /* list actual directory, not contents */
128 static int f_listdot; /* list files beginning with . */
129 int f_longform; /* long listing format */
130 static int f_noautodot; /* do not automatically enable -A for root */
131 static int f_nofollow; /* don't follow symbolic link arguments */
132 int f_nonprint; /* show unprintables as ? */
133 static int f_nosort; /* don't sort output */
134 int f_notabs; /* don't use tab-separated multi-col output */
135 static int f_numericonly; /* don't convert uid/gid to name */
136 int f_octal; /* show unprintables as \xxx */
137 int f_octal_escape; /* like f_octal but use C escapes if possible */
138 static int f_recursive; /* ls subdirectories also */
139 static int f_reversesort; /* reverse whatever sort is used */
140 int f_samesort; /* sort time and name in same direction */
141 int f_sectime; /* print full time information */
142 static int f_singlecol; /* use single column output */
143 int f_size; /* list size in short listing */
144 static int f_sizesort;
145 int f_slash; /* similar to f_type, but only for dirs */
146 int f_sortacross; /* sort across rows, not down columns */
147 int f_statustime; /* use time of last mode change */
148 static int f_stream; /* stream the output, separate with commas */
149 int f_thousands; /* show file sizes with thousands separators */
150 char *f_timeformat; /* user-specified time format */
151 static int f_timesort; /* sort by time vice name */
152 int f_type; /* add type character for non-regular files */
153 static int f_whiteout; /* show whiteout entries */
155 int colorflag = COLORFLAG_NEVER; /* passed in colorflag */
156 int f_color; /* add type in color for non-regular files */
157 bool explicitansi; /* Explicit ANSI sequences, no termcap(5) */
158 char *ansi_bgcol; /* ANSI sequence to set background colour */
159 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
160 char *ansi_coloff; /* ANSI sequence to reset colours */
161 char *attrs_off; /* ANSI sequence to turn off attributes */
162 char *enter_bold; /* ANSI sequence to set color to bold mode */
168 do_color_from_env(void)
174 p = getenv("CLICOLOR");
177 * COLORTERM is the more standard name for this variable. We'll
178 * honor it as long as it's both set and not empty.
180 p = getenv("COLORTERM");
181 if (p != NULL && *p != '\0')
187 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")));
195 if (colorflag == COLORFLAG_NEVER)
197 else if (colorflag == COLORFLAG_ALWAYS)
200 return (do_color_from_env());
205 do_color_always(const char *term)
208 return (strcmp(term, "always") == 0 || strcmp(term, "yes") == 0 ||
209 strcmp(term, "force") == 0);
213 do_color_never(const char *term)
216 return (strcmp(term, "never") == 0 || strcmp(term, "no") == 0 ||
217 strcmp(term, "none") == 0);
221 do_color_auto(const char *term)
224 return (strcmp(term, "auto") == 0 || strcmp(term, "tty") == 0 ||
225 strcmp(term, "if-tty") == 0);
230 main(int argc, char *argv[])
232 static char dot[] = ".", *dotav[] = {dot, NULL};
234 int ch, fts_options, notused;
236 const char *errstr = NULL;
238 char termcapbuf[1024]; /* termcap definition buffer */
239 char tcapbuf[512]; /* capability buffer */
240 char *bp = tcapbuf, *term;
243 (void)setlocale(LC_ALL, "");
245 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
246 if (isatty(STDOUT_FILENO)) {
248 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
249 termwidth = strtonum(p, 0, INT_MAX, &errstr);
250 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
252 termwidth = win.ws_col;
256 /* retrieve environment variable, in case of explicit -C */
257 p = getenv("COLUMNS");
259 termwidth = strtonum(p, 0, INT_MAX, &errstr);
265 fts_options = FTS_PHYSICAL;
266 if (getenv("LS_SAMESORT"))
270 * For historical compatibility, we'll use our autodetection if CLICOLOR
274 if (getenv("CLICOLOR"))
275 colorflag = COLORFLAG_AUTO;
277 while ((ch = getopt_long(argc, argv,
278 "+1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuwxy,", long_opts,
282 * The -1, -C, -x and -l options all override each other so
283 * shell aliasing works right.
291 f_sortacross = f_longform = f_singlecol = 0;
303 /* The -c, -u, and -U options override each other. */
323 fts_options |= FTS_SEEDOT;
328 /* The -t and -S options override each other. */
337 /* Other flags. Please keep alphabetic. */
347 f_timeformat = optarg;
355 * We both set CLICOLOR here and set colorflag to
356 * COLORFLAG_AUTO, because -G should not force color if
357 * stdout isn't a tty.
359 setenv("CLICOLOR", "", 1);
361 colorflag = COLORFLAG_AUTO;
365 fts_options |= FTS_COMFOLLOW;
372 fts_options &= ~FTS_PHYSICAL;
373 fts_options |= FTS_LOGICAL;
377 fts_options &= ~FTS_COMFOLLOW;
378 fts_options &= ~FTS_LOGICAL;
379 fts_options |= FTS_PHYSICAL;
399 /* The -d option turns off the -R option. */
404 case 'g': /* Compatibility with 4.3BSD. */
452 if (optarg == NULL || do_color_always(optarg))
453 colorflag = COLORFLAG_ALWAYS;
454 else if (do_color_auto(optarg))
455 colorflag = COLORFLAG_AUTO;
456 else if (do_color_never(optarg))
457 colorflag = COLORFLAG_NEVER;
459 errx(2, "unsupported --color value '%s' (must be always, auto, or never)",
471 /* Root is -A automatically unless -I. */
472 if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
476 * Enabling of colours is conditional on the environment in conjunction
477 * with the --color and -G arguments, if supplied.
481 if ((term = getenv("TERM")) != NULL &&
482 tgetent(termcapbuf, term) == 1) {
483 ansi_fgcol = tgetstr("AF", &bp);
484 ansi_bgcol = tgetstr("AB", &bp);
485 attrs_off = tgetstr("me", &bp);
486 enter_bold = tgetstr("md", &bp);
488 /* To switch colours off use 'op' if
489 * available, otherwise use 'oc', or
490 * don't do colours at all. */
491 ansi_coloff = tgetstr("op", &bp);
493 ansi_coloff = tgetstr("oc", &bp);
494 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
496 } else if (colorflag == COLORFLAG_ALWAYS) {
498 * If we're *always* doing color but we don't have
499 * a functional TERM supplied, we'll fallback to
500 * outputting raw ANSI sequences.
506 warnx("color support not compiled in");
513 * We can't put tabs and color sequences together:
514 * column number will be incremented incorrectly
515 * for "stty oxtabs" mode.
518 (void)signal(SIGINT, colorquit);
519 (void)signal(SIGQUIT, colorquit);
520 parsecolors(getenv("LSCOLORS"));
525 * If not -F, -i, -l, -s, -S or -t options, don't require stat
526 * information, unless in color mode in which case we do
527 * need this to determine which colors to display.
529 if (!f_inode && !f_longform && !f_size && !f_timesort &&
530 !f_sizesort && !f_type
535 fts_options |= FTS_NOSTAT;
538 * If not -F, -P, -d or -l options, follow any symbolic links listed on
539 * the command line, unless in color mode in which case we need to
540 * distinguish file type for a symbolic link itself and its target.
542 if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash)
547 fts_options |= FTS_COMFOLLOW;
550 * If -W, show whiteout entries
554 fts_options |= FTS_WHITEOUT;
557 /* If -i, -l or -s, figure out block size. */
558 if (f_inode || f_longform || f_size) {
562 (void)getbsize(¬used, &blocksize);
566 /* Select a sort function. */
568 if (!f_timesort && !f_sizesort)
569 sortfcn = revnamecmp;
571 sortfcn = revsizecmp;
572 else if (f_accesstime)
574 else if (f_birthtime)
575 sortfcn = revbirthcmp;
576 else if (f_statustime)
577 sortfcn = revstatcmp;
578 else /* Use modification time. */
581 if (!f_timesort && !f_sizesort)
585 else if (f_accesstime)
587 else if (f_birthtime)
589 else if (f_statustime)
591 else /* Use modification time. */
595 /* Select a print function. */
597 printfcn = printscol;
599 printfcn = printlong;
601 printfcn = printstream;
606 traverse(argc, argv, fts_options);
608 traverse(1, dotav, fts_options);
612 static int output; /* If anything output. */
615 * Traverse() walks the logical directory structure specified by the argv list
616 * in the order specified by the mastercmp() comparison function. During the
617 * traversal it passes linked lists of structures to display() which represent
618 * a superset (may be exact set) of the files to be displayed.
621 traverse(int argc, char *argv[], int options)
628 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
632 * We ignore errors from fts_children here since they will be
633 * replicated and signalled on the next call to fts_read() below.
635 chp = fts_children(ftsp, 0);
637 display(NULL, chp, options);
642 * If not recursing down this tree and don't need stat info, just get
645 ch_options = !f_recursive && !f_label &&
646 options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
648 while ((p = fts_read(ftsp)) != NULL)
649 switch (p->fts_info) {
651 warnx("%s: directory causes a cycle", p->fts_name);
655 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
659 if (p->fts_level != FTS_ROOTLEVEL &&
660 p->fts_name[0] == '.' && !f_listdot)
664 * If already output something, put out a newline as
665 * a separator. If multiple arguments, precede each
666 * directory with its name.
670 (void)printname(p->fts_path);
672 } else if (argc > 1) {
673 (void)printname(p->fts_path);
677 chp = fts_children(ftsp, ch_options);
678 display(p, chp, options);
680 if (!f_recursive && chp != NULL)
681 (void)fts_set(ftsp, p, FTS_SKIP);
691 * Display() takes a linked list of FTSENT structures and passes the list
692 * along with any other necessary information to the print function. P
693 * points to the parent directory of the display list.
696 display(const FTSENT *p, FTSENT *list, int options)
705 u_long btotal, labelstrlen, maxlen, maxnlink;
711 size_t flen, ulen, glen;
713 int entries, needstats;
714 const char *user, *group;
715 char *flags, *labelstr = NULL;
716 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
717 char nuser[STRBUF_SIZEOF(gid_t) + 1];
719 needstats = f_inode || f_longform || f_size;
722 initmax = getenv("LS_COLWIDTHS");
723 /* Fields match -lios order. New ones should be added at the end. */
724 maxlabelstr = maxblock = maxlen = maxnlink = 0;
725 maxuser = maxgroup = maxflags = maxsize = 0;
727 if (initmax != NULL && *initmax != '\0') {
728 char *initmax2, *jinitmax;
731 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
732 jinitmax = malloc(strlen(initmax) * 2 + 2);
733 if (jinitmax == NULL)
737 strcpy(initmax2, "0:"), initmax2 += 2;
739 *initmax2++ = *initmax, *initmax2 = '\0';
740 for (initmax++; *initmax != '\0'; initmax++) {
741 if (initmax[-1] == ':' && initmax[0] == ':') {
743 *initmax2++ = initmax[0];
746 *initmax2++ = initmax[0];
750 if (initmax2[-1] == ':')
751 strcpy(initmax2, "0");
753 ninitmax = sscanf(jinitmax,
754 " %ju : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
755 &maxinode, &maxblock, &maxnlink, &maxuser,
756 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
803 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
804 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
806 cur->fts_name, strerror(cur->fts_errno));
807 cur->fts_number = NO_PRINT;
812 * P is NULL if list is the argv list, to which different rules
816 /* Directories will be displayed later. */
817 if (cur->fts_info == FTS_D && !f_listdir) {
818 cur->fts_number = NO_PRINT;
822 /* Only display dot file if -a/-A set. */
823 if (cur->fts_name[0] == '.' && !f_listdot) {
824 cur->fts_number = NO_PRINT;
828 if (cur->fts_namelen > maxlen)
829 maxlen = cur->fts_namelen;
830 if (f_octal || f_octal_escape) {
831 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
838 if (sp->st_blocks > maxblock)
839 maxblock = sp->st_blocks;
840 if (sp->st_ino > maxinode)
841 maxinode = sp->st_ino;
842 if (sp->st_nlink > maxnlink)
843 maxnlink = sp->st_nlink;
844 if (sp->st_size > maxsize)
845 maxsize = sp->st_size;
847 btotal += sp->st_blocks;
850 (void)snprintf(nuser, sizeof(nuser),
852 (void)snprintf(ngroup, sizeof(ngroup),
857 user = user_from_uid(sp->st_uid, 0);
859 * user_from_uid(..., 0) only returns
860 * NULL in OOM conditions. We could
861 * format the uid here, but (1) in
862 * general ls(1) exits on OOM, and (2)
863 * there is another allocation/exit
864 * path directly below, which will
865 * likely exit anyway.
868 err(1, "user_from_uid");
869 group = group_from_gid(sp->st_gid, 0);
872 err(1, "group_from_gid");
874 if ((ulen = strlen(user)) > maxuser)
876 if ((glen = strlen(group)) > maxgroup)
879 flags = fflagstostr(sp->st_flags);
880 if (flags != NULL && *flags == '\0') {
885 err(1, "fflagstostr");
886 flen = strlen(flags);
887 if (flen > (size_t)maxflags)
893 char name[PATH_MAX + 1];
897 error = mac_prepare_file_label(&label);
899 warn("MAC label for %s/%s",
900 cur->fts_parent->fts_path,
905 if (cur->fts_level == FTS_ROOTLEVEL)
906 snprintf(name, sizeof(name),
907 "%s", cur->fts_name);
909 snprintf(name, sizeof(name),
910 "%s/%s", cur->fts_parent->
911 fts_accpath, cur->fts_name);
913 if (options & FTS_LOGICAL)
914 error = mac_get_file(name,
917 error = mac_get_link(name,
920 warn("MAC label for %s/%s",
921 cur->fts_parent->fts_path,
927 error = mac_to_text(label,
930 warn("MAC label for %s/%s",
931 cur->fts_parent->fts_path,
938 if (labelstr == NULL)
939 labelstr = strdup("-");
940 labelstrlen = strlen(labelstr);
941 if (labelstrlen > maxlabelstr)
942 maxlabelstr = labelstrlen;
946 if ((np = malloc(sizeof(NAMES) + labelstrlen +
947 ulen + glen + flen + 4)) == NULL)
950 np->user = &np->data[0];
951 (void)strcpy(np->user, user);
952 np->group = &np->data[ulen + 1];
953 (void)strcpy(np->group, group);
955 if (S_ISCHR(sp->st_mode) ||
956 S_ISBLK(sp->st_mode)) {
957 sizelen = snprintf(NULL, 0,
958 "%#jx", (uintmax_t)sp->st_rdev);
959 if (d.s_size < sizelen)
964 np->flags = &np->data[ulen + glen + 2];
965 (void)strcpy(np->flags, flags);
969 np->label = &np->data[ulen + glen + 2
970 + (f_flags ? flen + 1 : 0)];
971 (void)strcpy(np->label, labelstr);
974 cur->fts_pointer = np;
981 * If there are no entries to display, we normally stop right
982 * here. However, we must continue if we have to display the
983 * total block count. In this case, we display the total only
984 * on the second (p != NULL) pass.
986 if (!entries && (!(f_longform || f_size) || p == NULL))
994 d.s_block = snprintf(NULL, 0, "%lu", howmany(maxblock, blocksize));
995 d.s_flags = maxflags;
996 d.s_label = maxlabelstr;
997 d.s_group = maxgroup;
998 d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
999 d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
1000 sizelen = f_humanval ? HUMANVALSTR_LEN :
1001 snprintf(NULL, 0, "%ju", maxsize);
1002 if (d.s_size < sizelen)
1006 if (f_thousands) /* make space for commas */
1007 d.s_size += (d.s_size - 1) / 3;
1012 for (cur = list; cur; cur = cur->fts_link)
1013 free(cur->fts_pointer);
1017 * Ordering for mastercmp:
1018 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
1019 * as larger than directories. Within either group, use the sort function.
1020 * All other levels use the sort function. Error entries remain unsorted.
1023 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
1027 a_info = (*a)->fts_info;
1028 if (a_info == FTS_ERR)
1030 b_info = (*b)->fts_info;
1031 if (b_info == FTS_ERR)
1034 if (a_info == FTS_NS || b_info == FTS_NS)
1035 return (namecmp(*a, *b));
1037 if (a_info != b_info &&
1038 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
1039 if (a_info == FTS_D)
1041 if (b_info == FTS_D)
1044 return (sortfcn(*a, *b));