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/types.h>
49 #include <sys/ioctl.h>
74 * Upward approximation of the maximum number of characters needed to
75 * represent a value of integral type t as a string, excluding the
76 * NUL terminator, with provision for a sign.
78 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
81 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
82 * into a number that wide in decimal.
83 * XXX: Overflows are not considered.
85 #define MAKENINES(n) \
89 /* Use a loop as all values of n are small. */ \
90 for (i = 1; n > 0; i *= 10) \
95 static void display(const FTSENT *, FTSENT *, int);
96 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
97 static void traverse(int, char **, int);
99 static void (*printfcn)(const DISPLAY *);
100 static int (*sortfcn)(const FTSENT *, const FTSENT *);
102 long blocksize; /* block size units */
103 int termwidth = 80; /* default terminal width */
106 int f_accesstime; /* use time of last access */
107 int f_birthtime; /* use time of birth */
108 int f_flags; /* show flags associated with a file */
109 int f_humanval; /* show human-readable file sizes */
110 int f_inode; /* print inode */
111 static int f_kblocks; /* print size in kilobytes */
112 static int f_listdir; /* list actual directory, not contents */
113 static int f_listdot; /* list files beginning with . */
114 static int f_noautodot; /* do not automatically enable -A for root */
115 int f_longform; /* long listing format */
116 static int f_nofollow; /* don't follow symbolic link arguments */
117 int f_nonprint; /* show unprintables as ? */
118 static int f_nosort; /* don't sort output */
119 int f_notabs; /* don't use tab-separated multi-col output */
120 static int f_numericonly; /* don't convert uid/gid to name */
121 int f_octal; /* show unprintables as \xxx */
122 int f_octal_escape; /* like f_octal but use C escapes if possible */
123 static int f_recursive; /* ls subdirectories also */
124 static int f_reversesort; /* reverse whatever sort is used */
125 int f_sectime; /* print the real time for all files */
126 static int f_singlecol; /* use single column output */
127 int f_size; /* list size in short listing */
128 int f_slash; /* similar to f_type, but only for dirs */
129 int f_sortacross; /* sort across rows, not down columns */
130 int f_statustime; /* use time of last mode change */
131 static int f_stream; /* stream the output, separate with commas */
132 static int f_timesort; /* sort by time vice name */
133 char *f_timeformat; /* user-specified time format */
134 static int f_sizesort;
135 int f_type; /* add type character for non-regular files */
136 static int f_whiteout; /* show whiteout entries */
137 int f_label; /* show MAC label */
139 int f_color; /* add type in color for non-regular files */
141 char *ansi_bgcol; /* ANSI sequence to set background colour */
142 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
143 char *ansi_coloff; /* ANSI sequence to reset colours */
144 char *attrs_off; /* ANSI sequence to turn off attributes */
145 char *enter_bold; /* ANSI sequence to set color to bold mode */
151 main(int argc, char *argv[])
153 static char dot[] = ".", *dotav[] = {dot, NULL};
155 int ch, fts_options, notused;
158 char termcapbuf[1024]; /* termcap definition buffer */
159 char tcapbuf[512]; /* capability buffer */
163 (void)setlocale(LC_ALL, "");
165 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
166 if (isatty(STDOUT_FILENO)) {
168 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
170 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
172 termwidth = win.ws_col;
176 /* retrieve environment variable, in case of explicit -C */
177 p = getenv("COLUMNS");
182 fts_options = FTS_PHYSICAL;
183 while ((ch = getopt(argc, argv,
184 "1ABCD:FGHILPRSTUWZabcdfghiklmnopqrstuwx")) != -1) {
187 * The -1, -C, -x and -l options all override each other so
188 * shell aliasing works right.
201 f_sortacross = f_longform = f_singlecol = 0;
204 f_timeformat = optarg;
216 /* The -c, -u, and -U options override each other. */
237 fts_options |= FTS_COMFOLLOW;
241 setenv("CLICOLOR", "", 1);
244 fts_options &= ~FTS_PHYSICAL;
245 fts_options |= FTS_LOGICAL;
249 fts_options &= ~FTS_COMFOLLOW;
250 fts_options &= ~FTS_LOGICAL;
251 fts_options |= FTS_PHYSICAL;
258 fts_options |= FTS_SEEDOT;
266 /* The -d option turns off the -R option. */
274 case 'g': /* Compatibility with 4.3BSD. */
315 /* The -t and -S options override each other. */
348 /* Root is -A automatically unless -I. */
349 if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
352 /* Enabling of colours is conditional on the environment. */
353 if (getenv("CLICOLOR") &&
354 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
356 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
357 ansi_fgcol = tgetstr("AF", &bp);
358 ansi_bgcol = tgetstr("AB", &bp);
359 attrs_off = tgetstr("me", &bp);
360 enter_bold = tgetstr("md", &bp);
362 /* To switch colours off use 'op' if
363 * available, otherwise use 'oc', or
364 * don't do colours at all. */
365 ansi_coloff = tgetstr("op", &bp);
367 ansi_coloff = tgetstr("oc", &bp);
368 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
372 warnx("color support not compiled in");
378 * We can't put tabs and color sequences together:
379 * column number will be incremented incorrectly
380 * for "stty oxtabs" mode.
383 (void)signal(SIGINT, colorquit);
384 (void)signal(SIGQUIT, colorquit);
385 parsecolors(getenv("LSCOLORS"));
390 * If not -F, -i, -l, -s, -S or -t options, don't require stat
391 * information, unless in color mode in which case we do
392 * need this to determine which colors to display.
394 if (!f_inode && !f_longform && !f_size && !f_timesort &&
395 !f_sizesort && !f_type
400 fts_options |= FTS_NOSTAT;
403 * If not -F, -P, -d or -l options, follow any symbolic links listed on
406 if (!f_nofollow && !f_longform && !f_listdir && !f_type)
407 fts_options |= FTS_COMFOLLOW;
410 * If -W, show whiteout entries
414 fts_options |= FTS_WHITEOUT;
417 /* If -l or -s, figure out block size. */
418 if (f_longform || f_size) {
422 (void)getbsize(¬used, &blocksize);
426 /* Select a sort function. */
428 if (!f_timesort && !f_sizesort)
429 sortfcn = revnamecmp;
431 sortfcn = revsizecmp;
432 else if (f_accesstime)
434 else if (f_birthtime)
435 sortfcn = revbirthcmp;
436 else if (f_statustime)
437 sortfcn = revstatcmp;
438 else /* Use modification time. */
441 if (!f_timesort && !f_sizesort)
445 else if (f_accesstime)
447 else if (f_birthtime)
449 else if (f_statustime)
451 else /* Use modification time. */
455 /* Select a print function. */
457 printfcn = printscol;
459 printfcn = printlong;
461 printfcn = printstream;
466 traverse(argc, argv, fts_options);
468 traverse(1, dotav, fts_options);
472 static int output; /* If anything output. */
475 * Traverse() walks the logical directory structure specified by the argv list
476 * in the order specified by the mastercmp() comparison function. During the
477 * traversal it passes linked lists of structures to display() which represent
478 * a superset (may be exact set) of the files to be displayed.
481 traverse(int argc, char *argv[], int options)
488 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
492 * We ignore errors from fts_children here since they will be
493 * replicated and signalled on the next call to fts_read() below.
495 chp = fts_children(ftsp, 0);
497 display(NULL, chp, options);
502 * If not recursing down this tree and don't need stat info, just get
505 ch_options = !f_recursive && !f_label &&
506 options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
508 while ((p = fts_read(ftsp)) != NULL)
509 switch (p->fts_info) {
511 warnx("%s: directory causes a cycle", p->fts_name);
515 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
519 if (p->fts_level != FTS_ROOTLEVEL &&
520 p->fts_name[0] == '.' && !f_listdot)
524 * If already output something, put out a newline as
525 * a separator. If multiple arguments, precede each
526 * directory with its name.
530 (void)printname(p->fts_path);
532 } else if (argc > 1) {
533 (void)printname(p->fts_path);
537 chp = fts_children(ftsp, ch_options);
538 display(p, chp, options);
540 if (!f_recursive && chp != NULL)
541 (void)fts_set(ftsp, p, FTS_SKIP);
551 * Display() takes a linked list of FTSENT structures and passes the list
552 * along with any other necessary information to the print function. P
553 * points to the parent directory of the display list.
556 display(const FTSENT *p, FTSENT *list, int options)
564 u_long btotal, labelstrlen, maxinode, maxlen, maxnlink;
570 size_t flen, ulen, glen;
572 int entries, needstats;
573 const char *user, *group;
574 char *flags, *labelstr = NULL;
575 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
576 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
577 char nuser[STRBUF_SIZEOF(gid_t) + 1];
579 needstats = f_inode || f_longform || f_size;
582 initmax = getenv("LS_COLWIDTHS");
583 /* Fields match -lios order. New ones should be added at the end. */
584 maxlabelstr = maxblock = maxinode = maxlen = maxnlink =
585 maxuser = maxgroup = maxflags = maxsize = 0;
586 if (initmax != NULL && *initmax != '\0') {
587 char *initmax2, *jinitmax;
590 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
591 jinitmax = malloc(strlen(initmax) * 2 + 2);
592 if (jinitmax == NULL)
596 strcpy(initmax2, "0:"), initmax2 += 2;
598 *initmax2++ = *initmax, *initmax2 = '\0';
599 for (initmax++; *initmax != '\0'; initmax++) {
600 if (initmax[-1] == ':' && initmax[0] == ':') {
602 *initmax2++ = initmax[0];
605 *initmax2++ = initmax[0];
609 if (initmax2[-1] == ':')
610 strcpy(initmax2, "0");
612 ninitmax = sscanf(jinitmax,
613 " %lu : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
614 &maxinode, &maxblock, &maxnlink, &maxuser,
615 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
661 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
662 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
664 cur->fts_name, strerror(cur->fts_errno));
665 cur->fts_number = NO_PRINT;
670 * P is NULL if list is the argv list, to which different rules
674 /* Directories will be displayed later. */
675 if (cur->fts_info == FTS_D && !f_listdir) {
676 cur->fts_number = NO_PRINT;
680 /* Only display dot file if -a/-A set. */
681 if (cur->fts_name[0] == '.' && !f_listdot) {
682 cur->fts_number = NO_PRINT;
686 if (cur->fts_namelen > maxlen)
687 maxlen = cur->fts_namelen;
688 if (f_octal || f_octal_escape) {
689 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
696 if (sp->st_blocks > maxblock)
697 maxblock = sp->st_blocks;
698 if (sp->st_ino > maxinode)
699 maxinode = sp->st_ino;
700 if (sp->st_nlink > maxnlink)
701 maxnlink = sp->st_nlink;
702 if (sp->st_size > maxsize)
703 maxsize = sp->st_size;
705 btotal += sp->st_blocks;
708 (void)snprintf(nuser, sizeof(nuser),
710 (void)snprintf(ngroup, sizeof(ngroup),
715 user = user_from_uid(sp->st_uid, 0);
716 group = group_from_gid(sp->st_gid, 0);
718 if ((ulen = strlen(user)) > maxuser)
720 if ((glen = strlen(group)) > maxgroup)
723 flags = fflagstostr(sp->st_flags);
724 if (flags != NULL && *flags == '\0') {
729 err(1, "fflagstostr");
730 flen = strlen(flags);
731 if (flen > (size_t)maxflags)
737 char name[PATH_MAX + 1];
741 error = mac_prepare_file_label(&label);
743 warn("MAC label for %s/%s",
744 cur->fts_parent->fts_path,
749 if (cur->fts_level == FTS_ROOTLEVEL)
750 snprintf(name, sizeof(name),
751 "%s", cur->fts_name);
753 snprintf(name, sizeof(name),
754 "%s/%s", cur->fts_parent->
755 fts_accpath, cur->fts_name);
757 if (options & FTS_LOGICAL)
758 error = mac_get_file(name,
761 error = mac_get_link(name,
764 warn("MAC label for %s/%s",
765 cur->fts_parent->fts_path,
771 error = mac_to_text(label,
774 warn("MAC label for %s/%s",
775 cur->fts_parent->fts_path,
782 if (labelstr == NULL)
783 labelstr = strdup("-");
784 labelstrlen = strlen(labelstr);
785 if (labelstrlen > maxlabelstr)
786 maxlabelstr = labelstrlen;
790 if ((np = malloc(sizeof(NAMES) + labelstrlen +
791 ulen + glen + flen + 4)) == NULL)
794 np->user = &np->data[0];
795 (void)strcpy(np->user, user);
796 np->group = &np->data[ulen + 1];
797 (void)strcpy(np->group, group);
799 if ((S_ISCHR(sp->st_mode) ||
800 S_ISBLK(sp->st_mode)) &&
801 devstrlen < DEVSTR_HEX_LEN) {
802 if (minor(sp->st_rdev) > 255 ||
803 minor(sp->st_rdev) < 0)
804 devstrlen = DEVSTR_HEX_LEN;
806 devstrlen = DEVSTR_LEN;
810 np->flags = &np->data[ulen + glen + 2];
811 (void)strcpy(np->flags, flags);
815 np->label = &np->data[ulen + glen + 2
816 + (f_flags ? flen + 1 : 0)];
817 (void)strcpy(np->label, labelstr);
820 cur->fts_pointer = np;
827 * If there are no entries to display, we normally stop right
828 * here. However, we must continue if we have to display the
829 * total block count. In this case, we display the total only
830 * on the second (p != NULL) pass.
832 if (!entries && (!(f_longform || f_size) || p == NULL))
840 (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
841 d.s_block = strlen(buf);
842 d.s_flags = maxflags;
843 d.s_label = maxlabelstr;
844 d.s_group = maxgroup;
845 (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
846 d.s_inode = strlen(buf);
847 (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
848 d.s_nlink = strlen(buf);
850 d.s_size = HUMANVALSTR_LEN;
852 (void)snprintf(buf, sizeof(buf), "%ju", maxsize);
853 d.s_size = strlen(buf);
855 if (d.s_size < devstrlen)
856 d.s_size = devstrlen;
863 for (cur = list; cur; cur = cur->fts_link)
864 free(cur->fts_pointer);
868 * Ordering for mastercmp:
869 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
870 * as larger than directories. Within either group, use the sort function.
871 * All other levels use the sort function. Error entries remain unsorted.
874 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
878 a_info = (*a)->fts_info;
879 if (a_info == FTS_ERR)
881 b_info = (*b)->fts_info;
882 if (b_info == FTS_ERR)
885 if (a_info == FTS_NS || b_info == FTS_NS)
886 return (namecmp(*a, *b));
888 if (a_info != b_info &&
889 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
895 return (sortfcn(*a, *b));