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 * 3. 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
32 * @(#) Copyright (c) 1989, 1993, 1994 The Regents of the University of California. All rights reserved.
33 * @(#)ls.c 8.5 (Berkeley) 4/2/94
34 * $FreeBSD: src/bin/ls/ls.c,v 1.78 2004/06/08 09:30:10 das Exp $
37 #include <sys/types.h>
39 #include <sys/ioctl.h>
63 * Upward approximation of the maximum number of characters needed to
64 * represent a value of integral type t as a string, excluding the
65 * NUL terminator, with provision for a sign.
67 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
70 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
71 * into a number that wide in decimal.
72 * XXX: Overflows are not considered.
74 #define MAKENINES(n) \
78 /* Use a loop as all values of n are small. */ \
79 for (i = 1; n > 0; i *= 10) \
84 static void display(const FTSENT *, FTSENT *);
85 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
86 static void traverse(int, char **, int);
88 static void (*printfcn)(const DISPLAY *);
89 static int (*sortfcn)(const FTSENT *, const FTSENT *);
91 long blocksize; /* block size units */
92 int termwidth = 80; /* default terminal width */
95 int f_accesstime; /* use time of last access */
96 int f_flags; /* show flags associated with a file */
97 int f_fsmid; /* show FSMID associated with a file */
98 int f_humanval; /* show human-readable file sizes */
99 int f_inode; /* print inode */
100 static int f_kblocks; /* print size in kilobytes */
101 static int f_listdir; /* list actual directory, not contents */
102 static int f_listdot; /* list files beginning with . */
103 int f_longform; /* long listing format */
104 int f_nonprint; /* show unprintables as ? */
105 static int f_nosort; /* don't sort output */
106 int f_notabs; /* don't use tab-separated multi-col output */
107 static int f_numericonly; /* don't convert uid/gid to name */
108 int f_octal; /* show unprintables as \xxx */
109 int f_octal_escape; /* like f_octal but use C escapes if possible */
110 static int f_recursive; /* ls subdirectories also */
111 static int f_reversesort; /* reverse whatever sort is used */
112 int f_sectime; /* print the real time for all files */
113 static int f_singlecol; /* use single column output */
114 int f_size; /* list size in short listing */
115 int f_slash; /* similar to f_type, but only for dirs */
116 int f_sizesort; /* Sort by size */
117 int f_sortacross; /* sort across rows, not down columns */
118 int f_statustime; /* use time of last mode change */
119 static int f_stream; /* stream the output, separate with commas */
120 static int f_timesort; /* sort by time vice name */
121 int f_type; /* add type character for non-regular files */
122 static int f_whiteout; /* show whiteout entries */
124 int f_color; /* add type in color for non-regular files */
126 char *ansi_bgcol; /* ANSI sequence to set background colour */
127 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
128 char *ansi_coloff; /* ANSI sequence to reset colours */
129 char *attrs_off; /* ANSI sequence to turn off attributes */
130 char *enter_bold; /* ANSI sequence to set color to bold mode */
136 main(int argc, char *argv[])
138 static char dot[] = ".", *dotav[] = {dot, NULL};
140 int ch, fts_options, notused;
143 char termcapbuf[1024]; /* termcap definition buffer */
144 char tcapbuf[512]; /* capability buffer */
148 setlocale(LC_ALL, "");
150 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
151 if (isatty(STDOUT_FILENO)) {
153 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
155 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
157 termwidth = win.ws_col;
161 /* retrieve environment variable, in case of explicit -C */
162 p = getenv("COLUMNS");
168 * Root is -A automatically. Turn off if -I specified.
173 fts_options = FTS_PHYSICAL;
174 while ((ch = getopt(argc, argv, "1ABCFGHILPSRTWabcdfghiklmnopqrstuwxy"))
178 * The -1, -C, -x and -l options all override each other so
179 * shell aliasing works right.
192 f_sortacross = f_longform = f_singlecol = 0;
205 #ifdef _ST_FSMID_PRESENT_
209 /* The -c and -u options override each other. */
223 fts_options |= FTS_COMFOLLOW;
229 if (setenv("CLICOLOR", "", 1) != 0)
230 warn("setenv: cannot set CLICOLOR");
233 fts_options &= ~FTS_PHYSICAL;
234 fts_options |= FTS_LOGICAL;
237 fts_options &= ~FTS_COMFOLLOW;
238 fts_options &= ~FTS_LOGICAL;
239 fts_options |= FTS_PHYSICAL;
244 /* The -t and -S options override each other. */
257 fts_options |= FTS_SEEDOT;
262 /* The -d option turns off the -R option. */
267 case 'g': /* Compatibility with 4.3BSD. */
329 /* Enabling of colours is conditional on the environment. */
330 if (getenv("CLICOLOR") &&
331 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
333 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
334 ansi_fgcol = tgetstr("AF", &bp);
335 ansi_bgcol = tgetstr("AB", &bp);
336 attrs_off = tgetstr("me", &bp);
337 enter_bold = tgetstr("md", &bp);
339 /* To switch colours off use 'op' if
340 * available, otherwise use 'oc', or
341 * don't do colours at all. */
342 ansi_coloff = tgetstr("op", &bp);
344 ansi_coloff = tgetstr("oc", &bp);
345 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
349 fprintf(stderr, "Color support not compiled in.\n");
355 * We can't put tabs and color sequences together:
356 * column number will be incremented incorrectly
357 * for "stty oxtabs" mode.
360 signal(SIGINT, colorquit);
361 signal(SIGQUIT, colorquit);
362 parsecolors(getenv("LSCOLORS"));
367 * If not -F, -i, -l, -s, -S or -t options, don't require stat
368 * information, unless in color mode in which case we do
369 * need this to determine which colors to display.
371 if (!f_inode && !f_longform && !f_size && !f_timesort &&
372 !f_sizesort && !f_type
377 fts_options |= FTS_NOSTAT;
380 * If not -F, -d or -l options, follow any symbolic links listed on
383 if (!f_longform && !f_listdir && !f_type)
384 fts_options |= FTS_COMFOLLOW;
387 * If -W, show whiteout entries
391 fts_options |= FTS_WHITEOUT;
394 /* If -l or -s, figure out block size. */
395 if (f_longform || f_size) {
399 getbsize(¬used, &blocksize);
403 /* Select a sort function. */
405 if (!f_timesort && !f_sizesort)
406 sortfcn = revnamecmp;
408 sortfcn = revsizecmp;
409 else if (f_accesstime)
411 else if (f_statustime)
412 sortfcn = revstatcmp;
413 else /* Use modification time. */
416 if (!f_timesort && !f_sizesort)
420 else if (f_accesstime)
422 else if (f_statustime)
424 else /* Use modification time. */
428 /* Select a print function. */
430 printfcn = printscol;
432 printfcn = printlong;
434 printfcn = printstream;
439 traverse(argc, argv, fts_options);
441 traverse(1, dotav, fts_options);
445 static int output; /* If anything output. */
448 * Traverse() walks the logical directory structure specified by the argv list
449 * in the order specified by the mastercmp() comparison function. During the
450 * traversal it passes linked lists of structures to display() which represent
451 * a superset (may be exact set) of the files to be displayed.
454 traverse(int argc, char *argv[], int options)
458 int ch_options, error;
461 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
465 * We ignore errors from fts_children here since they will be
466 * replicated and signalled on the next call to fts_read() below.
468 chp = fts_children(ftsp, 0);
477 * If not recursing down this tree and don't need stat info, just get
480 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
482 while ((p = fts_read(ftsp)) != NULL)
483 switch (p->fts_info) {
485 warnx("%s: directory causes a cycle", p->fts_name);
489 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
493 if (p->fts_level != FTS_ROOTLEVEL &&
494 p->fts_name[0] == '.' && !f_listdot)
498 * If already output something, put out a newline as
499 * a separator. If multiple arguments, precede each
500 * directory with its name.
504 printname(p->fts_path);
506 } else if (argc > 1) {
507 printname(p->fts_path);
511 chp = fts_children(ftsp, ch_options);
514 if (!f_recursive && chp != NULL)
515 fts_set(ftsp, p, FTS_SKIP);
528 * Display() takes a linked list of FTSENT structures and passes the list
529 * along with any other necessary information to the print function. P
530 * points to the parent directory of the display list.
533 display(const FTSENT *p, FTSENT *list)
540 u_long btotal, maxlen;
544 int bcfile, maxflags;
547 size_t fsmidlen, flen, ulen, glen;
549 int entries, needstats;
550 const char *user, *group;
552 #ifdef _ST_FSMID_PRESENT_
555 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
556 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
557 char nuser[STRBUF_SIZEOF(gid_t) + 1];
559 needstats = f_inode || f_longform || f_size;
561 initmax = getenv("LS_COLWIDTHS");
562 /* Fields match -lios order. New ones should be added at the end. */
563 maxblock = maxinode = maxlen = maxnlink =
564 maxuser = maxgroup = maxflags = maxsize = 0;
565 if (initmax != NULL && *initmax != '\0') {
566 char *initmax2, *jinitmax;
569 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
570 jinitmax = malloc(strlen(initmax) * 2 + 2);
571 if (jinitmax == NULL)
575 strcpy(initmax2, "0:"), initmax2 += 2;
577 *initmax2++ = *initmax, *initmax2 = '\0';
578 for (initmax++; *initmax != '\0'; initmax++) {
579 if (initmax[-1] == ':' && initmax[0] == ':') {
581 *initmax2++ = initmax[0];
584 *initmax2++ = initmax[0];
588 if (initmax2[-1] == ':')
589 strcpy(initmax2, "0");
591 ninitmax = sscanf(jinitmax,
592 " %ju : %jd : %u : %i : %i : %i : %jd : %lu ",
593 &maxinode, &maxblock, &maxnlink, &maxuser,
594 &maxgroup, &maxflags, &maxsize, &maxlen);
637 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
638 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
640 cur->fts_name, strerror(cur->fts_errno));
641 cur->fts_number = NO_PRINT;
646 * P is NULL if list is the argv list, to which different rules
650 /* Directories will be displayed later. */
651 if (cur->fts_info == FTS_D && !f_listdir) {
652 cur->fts_number = NO_PRINT;
656 /* Only display dot file if -a/-A set. */
657 if (cur->fts_name[0] == '.' && !f_listdot) {
658 cur->fts_number = NO_PRINT;
662 if (cur->fts_namelen > maxlen)
663 maxlen = cur->fts_namelen;
664 if (f_octal || f_octal_escape) {
665 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
672 if (sp->st_blocks > maxblock)
673 maxblock = sp->st_blocks;
674 if (sp->st_ino > maxinode)
675 maxinode = sp->st_ino;
676 if (sp->st_nlink > maxnlink)
677 maxnlink = sp->st_nlink;
678 if (sp->st_size > maxsize)
679 maxsize = sp->st_size;
681 btotal += sp->st_blocks;
684 snprintf(nuser, sizeof(nuser),
686 snprintf(ngroup, sizeof(ngroup),
691 user = user_from_uid(sp->st_uid, 0);
692 group = group_from_gid(sp->st_gid, 0);
694 if ((ulen = strlen(user)) > maxuser)
696 if ((glen = strlen(group)) > maxgroup)
699 flags = fflagstostr(sp->st_flags);
700 if (flags != NULL && *flags == '\0') {
705 err(1, "flagstostr");
706 flen = strlen(flags);
707 if (flen > (size_t)maxflags)
712 #ifdef _ST_FSMID_PRESENT_
714 fsmid = sp->st_fsmid;
724 if ((np = malloc(sizeof(NAMES) +
725 ulen + glen + flen + fsmidlen + 4)) == NULL)
728 np->user = &np->data[0];
729 strcpy(np->user, user);
730 np->group = &np->data[ulen + 1];
731 strcpy(np->group, group);
733 if (S_ISCHR(sp->st_mode) ||
734 S_ISBLK(sp->st_mode))
738 np->flags = &np->data[ulen + glen + 2];
739 strcpy(np->flags, flags);
742 #ifdef _ST_FSMID_PRESENT_
744 np->fsmid = np->data + ulen + glen + flen + 3;
745 snprintf(np->fsmid, fsmidlen + 1,
746 "%016jx", (intmax_t)fsmid);
749 cur->fts_pointer = np;
756 * If there are no entries to display, we normally stop right
757 * here. However, we must continue if we have to display the
758 * total block count. In this case, we display the total only
759 * on the second (p != NULL) pass.
761 if (!entries && (!(f_longform || f_size) || p == NULL))
770 snprintf(buf, sizeof(buf), "%ji", (intmax_t)maxblock);
771 d.s_block = strlen(buf);
772 d.s_flags = maxflags;
773 d.s_group = maxgroup;
774 snprintf(buf, sizeof(buf), "%ju", (uintmax_t)maxinode);
775 d.s_inode = strlen(buf);
776 snprintf(buf, sizeof(buf), "%u", maxnlink);
777 d.s_nlink = strlen(buf);
778 snprintf(buf, sizeof(buf), "%jd", (intmax_t)maxsize);
779 d.s_size = strlen(buf);
786 for (cur = list; cur; cur = cur->fts_link)
787 free(cur->fts_pointer);
791 * Ordering for mastercmp:
792 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
793 * as larger than directories. Within either group, use the sort function.
794 * All other levels use the sort function. Error entries remain unsorted.
797 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
801 a_info = (*a)->fts_info;
802 if (a_info == FTS_ERR)
804 b_info = (*b)->fts_info;
805 if (b_info == FTS_ERR)
808 if (a_info == FTS_NS || b_info == FTS_NS)
809 return (namecmp(*a, *b));
811 if (a_info != b_info &&
812 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
818 return (sortfcn(*a, *b));