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 int f_nonprint; /* show unprintables as ? */
117 static int f_nosort; /* don't sort output */
118 int f_notabs; /* don't use tab-separated multi-col output */
119 static int f_numericonly; /* don't convert uid/gid to name */
120 int f_octal; /* show unprintables as \xxx */
121 int f_octal_escape; /* like f_octal but use C escapes if possible */
122 static int f_recursive; /* ls subdirectories also */
123 static int f_reversesort; /* reverse whatever sort is used */
124 int f_sectime; /* print the real time for all files */
125 static int f_singlecol; /* use single column output */
126 int f_size; /* list size in short listing */
127 int f_slash; /* similar to f_type, but only for dirs */
128 int f_sortacross; /* sort across rows, not down columns */
129 int f_statustime; /* use time of last mode change */
130 static int f_stream; /* stream the output, separate with commas */
131 static int f_timesort; /* sort by time vice name */
132 char *f_timeformat; /* user-specified time format */
133 static int f_sizesort;
134 int f_type; /* add type character for non-regular files */
135 static int f_whiteout; /* show whiteout entries */
136 int f_label; /* show MAC label */
138 int f_color; /* add type in color for non-regular files */
140 char *ansi_bgcol; /* ANSI sequence to set background colour */
141 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
142 char *ansi_coloff; /* ANSI sequence to reset colours */
143 char *attrs_off; /* ANSI sequence to turn off attributes */
144 char *enter_bold; /* ANSI sequence to set color to bold mode */
150 main(int argc, char *argv[])
152 static char dot[] = ".", *dotav[] = {dot, NULL};
154 int ch, fts_options, notused;
157 char termcapbuf[1024]; /* termcap definition buffer */
158 char tcapbuf[512]; /* capability buffer */
162 (void)setlocale(LC_ALL, "");
164 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
165 if (isatty(STDOUT_FILENO)) {
167 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
169 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
171 termwidth = win.ws_col;
175 /* retrieve environment variable, in case of explicit -C */
176 p = getenv("COLUMNS");
181 fts_options = FTS_PHYSICAL;
182 while ((ch = getopt(argc, argv,
183 "1ABCD:FGHILPRSTUWZabcdfghiklmnopqrstuwx")) != -1) {
186 * The -1, -C, -x and -l options all override each other so
187 * shell aliasing works right.
200 f_sortacross = f_longform = f_singlecol = 0;
203 f_timeformat = optarg;
215 /* The -c, -u, and -U options override each other. */
236 fts_options |= FTS_COMFOLLOW;
239 setenv("CLICOLOR", "", 1);
242 fts_options &= ~FTS_PHYSICAL;
243 fts_options |= FTS_LOGICAL;
246 fts_options &= ~FTS_COMFOLLOW;
247 fts_options &= ~FTS_LOGICAL;
248 fts_options |= FTS_PHYSICAL;
254 fts_options |= FTS_SEEDOT;
262 /* The -d option turns off the -R option. */
270 case 'g': /* Compatibility with 4.3BSD. */
311 /* The -t and -S options override each other. */
344 /* Root is -A automatically unless -I. */
345 if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
348 /* Enabling of colours is conditional on the environment. */
349 if (getenv("CLICOLOR") &&
350 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
352 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
353 ansi_fgcol = tgetstr("AF", &bp);
354 ansi_bgcol = tgetstr("AB", &bp);
355 attrs_off = tgetstr("me", &bp);
356 enter_bold = tgetstr("md", &bp);
358 /* To switch colours off use 'op' if
359 * available, otherwise use 'oc', or
360 * don't do colours at all. */
361 ansi_coloff = tgetstr("op", &bp);
363 ansi_coloff = tgetstr("oc", &bp);
364 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
368 warnx("color support not compiled in");
374 * We can't put tabs and color sequences together:
375 * column number will be incremented incorrectly
376 * for "stty oxtabs" mode.
379 (void)signal(SIGINT, colorquit);
380 (void)signal(SIGQUIT, colorquit);
381 parsecolors(getenv("LSCOLORS"));
386 * If not -F, -i, -l, -s, -S or -t options, don't require stat
387 * information, unless in color mode in which case we do
388 * need this to determine which colors to display.
390 if (!f_inode && !f_longform && !f_size && !f_timesort &&
391 !f_sizesort && !f_type
396 fts_options |= FTS_NOSTAT;
399 * If not -F, -d or -l options, follow any symbolic links listed on
402 if (!f_longform && !f_listdir && !f_type)
403 fts_options |= FTS_COMFOLLOW;
406 * If -W, show whiteout entries
410 fts_options |= FTS_WHITEOUT;
413 /* If -l or -s, figure out block size. */
414 if (f_longform || f_size) {
418 (void)getbsize(¬used, &blocksize);
422 /* Select a sort function. */
424 if (!f_timesort && !f_sizesort)
425 sortfcn = revnamecmp;
427 sortfcn = revsizecmp;
428 else if (f_accesstime)
430 else if (f_birthtime)
431 sortfcn = revbirthcmp;
432 else if (f_statustime)
433 sortfcn = revstatcmp;
434 else /* Use modification time. */
437 if (!f_timesort && !f_sizesort)
441 else if (f_accesstime)
443 else if (f_birthtime)
445 else if (f_statustime)
447 else /* Use modification time. */
451 /* Select a print function. */
453 printfcn = printscol;
455 printfcn = printlong;
457 printfcn = printstream;
462 traverse(argc, argv, fts_options);
464 traverse(1, dotav, fts_options);
468 static int output; /* If anything output. */
471 * Traverse() walks the logical directory structure specified by the argv list
472 * in the order specified by the mastercmp() comparison function. During the
473 * traversal it passes linked lists of structures to display() which represent
474 * a superset (may be exact set) of the files to be displayed.
477 traverse(int argc, char *argv[], int options)
484 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
488 * We ignore errors from fts_children here since they will be
489 * replicated and signalled on the next call to fts_read() below.
491 chp = fts_children(ftsp, 0);
493 display(NULL, chp, options);
498 * If not recursing down this tree and don't need stat info, just get
501 ch_options = !f_recursive && !f_label &&
502 options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
504 while ((p = fts_read(ftsp)) != NULL)
505 switch (p->fts_info) {
507 warnx("%s: directory causes a cycle", p->fts_name);
511 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
515 if (p->fts_level != FTS_ROOTLEVEL &&
516 p->fts_name[0] == '.' && !f_listdot)
520 * If already output something, put out a newline as
521 * a separator. If multiple arguments, precede each
522 * directory with its name.
526 (void)printname(p->fts_path);
528 } else if (argc > 1) {
529 (void)printname(p->fts_path);
533 chp = fts_children(ftsp, ch_options);
534 display(p, chp, options);
536 if (!f_recursive && chp != NULL)
537 (void)fts_set(ftsp, p, FTS_SKIP);
547 * Display() takes a linked list of FTSENT structures and passes the list
548 * along with any other necessary information to the print function. P
549 * points to the parent directory of the display list.
552 display(const FTSENT *p, FTSENT *list, int options)
560 u_long btotal, labelstrlen, maxinode, maxlen, maxnlink;
562 int bcfile, maxflags;
565 size_t flen, ulen, glen;
567 int entries, needstats;
568 const char *user, *group;
569 char *flags, *labelstr = NULL;
570 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
571 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
572 char nuser[STRBUF_SIZEOF(gid_t) + 1];
574 needstats = f_inode || f_longform || f_size;
577 initmax = getenv("LS_COLWIDTHS");
578 /* Fields match -lios order. New ones should be added at the end. */
579 maxlabelstr = maxblock = maxinode = maxlen = maxnlink =
580 maxuser = maxgroup = maxflags = maxsize = 0;
581 if (initmax != NULL && *initmax != '\0') {
582 char *initmax2, *jinitmax;
585 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
586 jinitmax = malloc(strlen(initmax) * 2 + 2);
587 if (jinitmax == NULL)
591 strcpy(initmax2, "0:"), initmax2 += 2;
593 *initmax2++ = *initmax, *initmax2 = '\0';
594 for (initmax++; *initmax != '\0'; initmax++) {
595 if (initmax[-1] == ':' && initmax[0] == ':') {
597 *initmax2++ = initmax[0];
600 *initmax2++ = initmax[0];
604 if (initmax2[-1] == ':')
605 strcpy(initmax2, "0");
607 ninitmax = sscanf(jinitmax,
608 " %lu : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
609 &maxinode, &maxblock, &maxnlink, &maxuser,
610 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
656 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
657 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
659 cur->fts_name, strerror(cur->fts_errno));
660 cur->fts_number = NO_PRINT;
665 * P is NULL if list is the argv list, to which different rules
669 /* Directories will be displayed later. */
670 if (cur->fts_info == FTS_D && !f_listdir) {
671 cur->fts_number = NO_PRINT;
675 /* Only display dot file if -a/-A set. */
676 if (cur->fts_name[0] == '.' && !f_listdot) {
677 cur->fts_number = NO_PRINT;
681 if (cur->fts_namelen > maxlen)
682 maxlen = cur->fts_namelen;
683 if (f_octal || f_octal_escape) {
684 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
691 if (sp->st_blocks > maxblock)
692 maxblock = sp->st_blocks;
693 if (sp->st_ino > maxinode)
694 maxinode = sp->st_ino;
695 if (sp->st_nlink > maxnlink)
696 maxnlink = sp->st_nlink;
697 if (sp->st_size > maxsize)
698 maxsize = sp->st_size;
700 btotal += sp->st_blocks;
703 (void)snprintf(nuser, sizeof(nuser),
705 (void)snprintf(ngroup, sizeof(ngroup),
710 user = user_from_uid(sp->st_uid, 0);
711 group = group_from_gid(sp->st_gid, 0);
713 if ((ulen = strlen(user)) > maxuser)
715 if ((glen = strlen(group)) > maxgroup)
718 flags = fflagstostr(sp->st_flags);
719 if (flags != NULL && *flags == '\0') {
724 err(1, "fflagstostr");
725 flen = strlen(flags);
726 if (flen > (size_t)maxflags)
732 char name[PATH_MAX + 1];
736 error = mac_prepare_file_label(&label);
738 warn("MAC label for %s/%s",
739 cur->fts_parent->fts_path,
744 if (cur->fts_level == FTS_ROOTLEVEL)
745 snprintf(name, sizeof(name),
746 "%s", cur->fts_name);
748 snprintf(name, sizeof(name),
749 "%s/%s", cur->fts_parent->
750 fts_accpath, cur->fts_name);
752 if (options & FTS_LOGICAL)
753 error = mac_get_file(name,
756 error = mac_get_link(name,
759 warn("MAC label for %s/%s",
760 cur->fts_parent->fts_path,
766 error = mac_to_text(label,
769 warn("MAC label for %s/%s",
770 cur->fts_parent->fts_path,
777 if (labelstr == NULL)
778 labelstr = strdup("-");
779 labelstrlen = strlen(labelstr);
780 if (labelstrlen > maxlabelstr)
781 maxlabelstr = labelstrlen;
785 if ((np = malloc(sizeof(NAMES) + labelstrlen +
786 ulen + glen + flen + 4)) == NULL)
789 np->user = &np->data[0];
790 (void)strcpy(np->user, user);
791 np->group = &np->data[ulen + 1];
792 (void)strcpy(np->group, group);
794 if (S_ISCHR(sp->st_mode) ||
795 S_ISBLK(sp->st_mode))
799 np->flags = &np->data[ulen + glen + 2];
800 (void)strcpy(np->flags, flags);
804 np->label = &np->data[ulen + glen + 2
805 + (f_flags ? flen + 1 : 0)];
806 (void)strcpy(np->label, labelstr);
809 cur->fts_pointer = np;
816 * If there are no entries to display, we normally stop right
817 * here. However, we must continue if we have to display the
818 * total block count. In this case, we display the total only
819 * on the second (p != NULL) pass.
821 if (!entries && (!(f_longform || f_size) || p == NULL))
830 (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
831 d.s_block = strlen(buf);
832 d.s_flags = maxflags;
833 d.s_label = maxlabelstr;
834 d.s_group = maxgroup;
835 (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
836 d.s_inode = strlen(buf);
837 (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
838 d.s_nlink = strlen(buf);
839 (void)snprintf(buf, sizeof(buf), "%ju", maxsize);
840 d.s_size = strlen(buf);
847 for (cur = list; cur; cur = cur->fts_link)
848 free(cur->fts_pointer);
852 * Ordering for mastercmp:
853 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
854 * as larger than directories. Within either group, use the sort function.
855 * All other levels use the sort function. Error entries remain unsorted.
858 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
862 a_info = (*a)->fts_info;
863 if (a_info == FTS_ERR)
865 b_info = (*b)->fts_info;
866 if (b_info == FTS_ERR)
869 if (a_info == FTS_NS || b_info == FTS_NS)
870 return (namecmp(*a, *b));
872 if (a_info != b_info &&
873 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
879 return (sortfcn(*a, *b));