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>
77 * Upward approximation of the maximum number of characters needed to
78 * represent a value of integral type t as a string, excluding the
79 * NUL terminator, with provision for a sign.
81 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
84 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
85 * into a number that wide in decimal.
86 * XXX: Overflows are not considered.
88 #define MAKENINES(n) \
92 /* Use a loop as all values of n are small. */ \
93 for (i = 1; n > 0; i *= 10) \
98 static void display(const FTSENT *, FTSENT *, int);
99 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
100 static void traverse(int, char **, int);
102 static void (*printfcn)(const DISPLAY *);
103 static int (*sortfcn)(const FTSENT *, const FTSENT *);
105 long blocksize; /* block size units */
106 int termwidth = 80; /* default terminal width */
109 int f_accesstime; /* use time of last access */
110 int f_birthtime; /* use time of birth */
111 int f_flags; /* show flags associated with a file */
112 int f_humanval; /* show human-readable file sizes */
113 int f_inode; /* print inode */
114 static int f_kblocks; /* print size in kilobytes */
115 int f_label; /* show MAC label */
116 static int f_listdir; /* list actual directory, not contents */
117 static int f_listdot; /* list files beginning with . */
118 int f_longform; /* long listing format */
119 static int f_noautodot; /* do not automatically enable -A for root */
120 static int f_nofollow; /* don't follow symbolic link arguments */
121 int f_nonprint; /* show unprintables as ? */
122 static int f_nosort; /* don't sort output */
123 int f_notabs; /* don't use tab-separated multi-col output */
124 int f_numericonly; /* don't convert uid/gid to name */
125 int f_octal; /* show unprintables as \xxx */
126 int f_octal_escape; /* like f_octal but use C escapes if possible */
127 static int f_recursive; /* ls subdirectories also */
128 static int f_reversesort; /* reverse whatever sort is used */
129 int f_samesort; /* sort time and name in same direction */
130 int f_sectime; /* print full time information */
131 static int f_singlecol; /* use single column output */
132 int f_size; /* list size in short listing */
133 static int f_sizesort;
134 int f_slash; /* similar to f_type, but only for dirs */
135 int f_sortacross; /* sort across rows, not down columns */
136 int f_statustime; /* use time of last mode change */
137 static int f_stream; /* stream the output, separate with commas */
138 int f_thousands; /* show file sizes with thousands separators */
139 char *f_timeformat; /* user-specified time format */
140 static int f_timesort; /* sort by time vice name */
141 int f_type; /* add type character for non-regular files */
142 static int f_whiteout; /* show whiteout entries */
145 int f_color; /* add type in color for non-regular files */
147 char *ansi_bgcol; /* ANSI sequence to set background colour */
148 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
149 char *ansi_coloff; /* ANSI sequence to reset colours */
150 char *attrs_off; /* ANSI sequence to turn off attributes */
151 char *enter_bold; /* ANSI sequence to set color to bold mode */
157 main(int argc, char *argv[])
159 static char dot[] = ".", *dotav[] = {dot, NULL};
161 int ch, fts_options, notused;
163 const char *errstr = NULL;
165 char termcapbuf[1024]; /* termcap definition buffer */
166 char tcapbuf[512]; /* capability buffer */
170 (void)setlocale(LC_ALL, "");
172 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
173 if (isatty(STDOUT_FILENO)) {
175 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
176 termwidth = strtonum(p, 0, INT_MAX, &errstr);
177 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
179 termwidth = win.ws_col;
183 /* retrieve environment variable, in case of explicit -C */
184 p = getenv("COLUMNS");
186 termwidth = strtonum(p, 0, INT_MAX, &errstr);
192 fts_options = FTS_PHYSICAL;
193 if (getenv("LS_SAMESORT"))
196 argc = xo_parse_args(argc, argv);
199 xo_set_flags(NULL, XOF_COLUMNS);
200 xo_set_version(LS_XO_VERSION);
202 while ((ch = getopt(argc, argv,
203 "1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuwxy,")) != -1) {
206 * The -1, -C, -x and -l options all override each other so
207 * shell aliasing works right.
215 f_sortacross = f_longform = f_singlecol = 0;
227 /* The -c, -u, and -U options override each other. */
247 fts_options |= FTS_SEEDOT;
252 /* The -t and -S options override each other. */
261 /* Other flags. Please keep alphabetic. */
271 f_timeformat = optarg;
278 setenv("CLICOLOR", "", 1);
281 fts_options |= FTS_COMFOLLOW;
288 fts_options &= ~FTS_PHYSICAL;
289 fts_options |= FTS_LOGICAL;
293 fts_options &= ~FTS_COMFOLLOW;
294 fts_options &= ~FTS_LOGICAL;
295 fts_options |= FTS_PHYSICAL;
315 /* The -d option turns off the -R option. */
320 case 'g': /* Compatibility with 4.3BSD. */
374 /* Root is -A automatically unless -I. */
375 if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
378 /* Enabling of colours is conditional on the environment. */
379 if (getenv("CLICOLOR") &&
380 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
382 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
383 ansi_fgcol = tgetstr("AF", &bp);
384 ansi_bgcol = tgetstr("AB", &bp);
385 attrs_off = tgetstr("me", &bp);
386 enter_bold = tgetstr("md", &bp);
388 /* To switch colours off use 'op' if
389 * available, otherwise use 'oc', or
390 * don't do colours at all. */
391 ansi_coloff = tgetstr("op", &bp);
393 ansi_coloff = tgetstr("oc", &bp);
394 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
398 xo_warnx("color support not compiled in");
404 * We can't put tabs and color sequences together:
405 * column number will be incremented incorrectly
406 * for "stty oxtabs" mode.
409 (void)signal(SIGINT, colorquit);
410 (void)signal(SIGQUIT, colorquit);
411 parsecolors(getenv("LSCOLORS"));
416 * If not -F, -i, -l, -s, -S or -t options, don't require stat
417 * information, unless in color mode in which case we do
418 * need this to determine which colors to display.
420 if (!f_inode && !f_longform && !f_size && !f_timesort &&
421 !f_sizesort && !f_type
426 fts_options |= FTS_NOSTAT;
429 * If not -F, -P, -d or -l options, follow any symbolic links listed on
430 * the command line, unless in color mode in which case we need to
431 * distinguish file type for a symbolic link itself and its target.
433 if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash)
438 fts_options |= FTS_COMFOLLOW;
441 * If -W, show whiteout entries
445 fts_options |= FTS_WHITEOUT;
448 /* If -i, -l or -s, figure out block size. */
449 if (f_inode || f_longform || f_size) {
453 (void)getbsize(¬used, &blocksize);
457 /* Select a sort function. */
459 if (!f_timesort && !f_sizesort)
460 sortfcn = revnamecmp;
462 sortfcn = revsizecmp;
463 else if (f_accesstime)
465 else if (f_birthtime)
466 sortfcn = revbirthcmp;
467 else if (f_statustime)
468 sortfcn = revstatcmp;
469 else /* Use modification time. */
472 if (!f_timesort && !f_sizesort)
476 else if (f_accesstime)
478 else if (f_birthtime)
480 else if (f_statustime)
482 else /* Use modification time. */
486 /* Select a print function. */
488 printfcn = printscol;
490 printfcn = printlong;
492 printfcn = printstream;
496 xo_open_container("file-information");
498 traverse(argc, argv, fts_options);
500 traverse(1, dotav, fts_options);
501 xo_close_container("file-information");
506 static int output; /* If anything output. */
509 * Traverse() walks the logical directory structure specified by the argv list
510 * in the order specified by the mastercmp() comparison function. During the
511 * traversal it passes linked lists of structures to display() which represent
512 * a superset (may be exact set) of the files to be displayed.
515 traverse(int argc, char *argv[], int options)
523 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
524 xo_err(1, "fts_open");
527 * We ignore errors from fts_children here since they will be
528 * replicated and signalled on the next call to fts_read() below.
530 chp = fts_children(ftsp, 0);
532 display(NULL, chp, options);
537 * If not recursing down this tree and don't need stat info, just get
540 ch_options = !f_recursive && !f_label &&
541 options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
543 while ((p = fts_read(ftsp)) != NULL)
544 switch (p->fts_info) {
546 xo_warnx("%s: directory causes a cycle", p->fts_name);
550 xo_warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
554 if (p->fts_level != FTS_ROOTLEVEL &&
555 p->fts_name[0] == '.' && !f_listdot)
560 xo_open_list("directory");
562 xo_open_instance("directory");
565 * If already output something, put out a newline as
566 * a separator. If multiple arguments, precede each
567 * directory with its name.
571 (void)printname("path", p->fts_path);
573 } else if (argc > 1) {
574 (void)printname("path", p->fts_path);
578 chp = fts_children(ftsp, ch_options);
579 display(p, chp, options);
581 xo_close_instance("directory");
582 if (!f_recursive && chp != NULL)
583 (void)fts_set(ftsp, p, FTS_SKIP);
589 xo_close_list("directory");
591 xo_err(1, "fts_read");
595 * Display() takes a linked list of FTSENT structures and passes the list
596 * along with any other necessary information to the print function. P
597 * points to the parent directory of the display list.
600 display(const FTSENT *p, FTSENT *list, int options)
609 u_long btotal, labelstrlen, maxlen, maxnlink;
615 size_t flen, ulen, glen;
617 int entries, needstats;
618 const char *user, *group;
619 char *flags, *labelstr = NULL;
620 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
621 char nuser[STRBUF_SIZEOF(gid_t) + 1];
623 needstats = f_inode || f_longform || f_size;
626 initmax = getenv("LS_COLWIDTHS");
627 /* Fields match -lios order. New ones should be added at the end. */
628 maxlabelstr = maxblock = maxlen = maxnlink = 0;
629 maxuser = maxgroup = maxflags = maxsize = 0;
631 if (initmax != NULL && *initmax != '\0') {
632 char *initmax2, *jinitmax;
635 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
636 jinitmax = malloc(strlen(initmax) * 2 + 2);
637 if (jinitmax == NULL)
641 strcpy(initmax2, "0:"), initmax2 += 2;
643 *initmax2++ = *initmax, *initmax2 = '\0';
644 for (initmax++; *initmax != '\0'; initmax++) {
645 if (initmax[-1] == ':' && initmax[0] == ':') {
647 *initmax2++ = initmax[0];
650 *initmax2++ = initmax[0];
654 if (initmax2[-1] == ':')
655 strcpy(initmax2, "0");
657 ninitmax = sscanf(jinitmax,
658 " %ju : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
659 &maxinode, &maxblock, &maxnlink, &maxuser,
660 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
707 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
708 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
710 cur->fts_name, strerror(cur->fts_errno));
711 cur->fts_number = NO_PRINT;
716 * P is NULL if list is the argv list, to which different rules
720 /* Directories will be displayed later. */
721 if (cur->fts_info == FTS_D && !f_listdir) {
722 cur->fts_number = NO_PRINT;
726 /* Only display dot file if -a/-A set. */
727 if (cur->fts_name[0] == '.' && !f_listdot) {
728 cur->fts_number = NO_PRINT;
732 if (cur->fts_namelen > maxlen)
733 maxlen = cur->fts_namelen;
734 if (f_octal || f_octal_escape) {
735 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
742 if (sp->st_blocks > maxblock)
743 maxblock = sp->st_blocks;
744 if (sp->st_ino > maxinode)
745 maxinode = sp->st_ino;
746 if (sp->st_nlink > maxnlink)
747 maxnlink = sp->st_nlink;
748 if (sp->st_size > maxsize)
749 maxsize = sp->st_size;
751 btotal += sp->st_blocks;
754 (void)snprintf(nuser, sizeof(nuser),
756 (void)snprintf(ngroup, sizeof(ngroup),
761 user = user_from_uid(sp->st_uid, 0);
762 group = group_from_gid(sp->st_gid, 0);
764 if ((ulen = strlen(user)) > maxuser)
766 if ((glen = strlen(group)) > maxgroup)
769 flags = fflagstostr(sp->st_flags);
770 if (flags != NULL && *flags == '\0') {
775 xo_err(1, "fflagstostr");
776 flen = strlen(flags);
777 if (flen > (size_t)maxflags)
783 char name[PATH_MAX + 1];
787 error = mac_prepare_file_label(&label);
789 xo_warn("MAC label for %s/%s",
790 cur->fts_parent->fts_path,
795 if (cur->fts_level == FTS_ROOTLEVEL)
796 snprintf(name, sizeof(name),
797 "%s", cur->fts_name);
799 snprintf(name, sizeof(name),
800 "%s/%s", cur->fts_parent->
801 fts_accpath, cur->fts_name);
803 if (options & FTS_LOGICAL)
804 error = mac_get_file(name,
807 error = mac_get_link(name,
810 xo_warn("MAC label for %s/%s",
811 cur->fts_parent->fts_path,
817 error = mac_to_text(label,
820 xo_warn("MAC label for %s/%s",
821 cur->fts_parent->fts_path,
828 if (labelstr == NULL)
829 labelstr = strdup("-");
830 labelstrlen = strlen(labelstr);
831 if (labelstrlen > maxlabelstr)
832 maxlabelstr = labelstrlen;
836 if ((np = malloc(sizeof(NAMES) + labelstrlen +
837 ulen + glen + flen + 4)) == NULL)
840 np->user = &np->data[0];
841 (void)strcpy(np->user, user);
842 np->group = &np->data[ulen + 1];
843 (void)strcpy(np->group, group);
845 if (S_ISCHR(sp->st_mode) ||
846 S_ISBLK(sp->st_mode)) {
847 sizelen = snprintf(NULL, 0,
848 "%#jx", (uintmax_t)sp->st_rdev);
849 if (d.s_size < sizelen)
854 np->flags = &np->data[ulen + glen + 2];
855 (void)strcpy(np->flags, flags);
859 np->label = &np->data[ulen + glen + 2
860 + (f_flags ? flen + 1 : 0)];
861 (void)strcpy(np->label, labelstr);
864 cur->fts_pointer = np;
871 * If there are no entries to display, we normally stop right
872 * here. However, we must continue if we have to display the
873 * total block count. In this case, we display the total only
874 * on the second (p != NULL) pass.
876 if (!entries && (!(f_longform || f_size) || p == NULL))
884 d.s_block = snprintf(NULL, 0, "%lu", howmany(maxblock, blocksize));
885 d.s_flags = maxflags;
886 d.s_label = maxlabelstr;
887 d.s_group = maxgroup;
888 d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
889 d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
890 sizelen = f_humanval ? HUMANVALSTR_LEN :
891 snprintf(NULL, 0, "%ju", maxsize);
892 if (d.s_size < sizelen)
896 if (f_thousands) /* make space for commas */
897 d.s_size += (d.s_size - 1) / 3;
902 for (cur = list; cur; cur = cur->fts_link)
903 free(cur->fts_pointer);
907 * Ordering for mastercmp:
908 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
909 * as larger than directories. Within either group, use the sort function.
910 * All other levels use the sort function. Error entries remain unsorted.
913 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
917 a_info = (*a)->fts_info;
918 if (a_info == FTS_ERR)
920 b_info = (*b)->fts_info;
921 if (b_info == FTS_ERR)
924 if (a_info == FTS_NS || b_info == FTS_NS)
925 return (namecmp(*a, *b));
927 if (a_info != b_info &&
928 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
934 return (sortfcn(*a, *b));