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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 static const char copyright[] =
39 "@(#) Copyright (c) 1989, 1993, 1994\n\
40 The Regents of the University of California. All rights reserved.\n";
45 static char sccsid[] = "@(#)ls.c 8.5 (Berkeley) 4/2/94";
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
51 #include <sys/types.h>
53 #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)
83 static void display(FTSENT *, FTSENT *);
84 static u_quad_t makenines(u_long);
85 static int mastercmp(const FTSENT **, const FTSENT **);
86 static void traverse(int, char **, int);
88 static void (*printfcn)(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_humanval; /* show human-readable file sizes */
98 int f_inode; /* print inode */
99 static int f_kblocks; /* print size in kilobytes */
100 static int f_listdir; /* list actual directory, not contents */
101 static int f_listdot; /* list files beginning with . */
102 int f_longform; /* long listing format */
103 int f_nonprint; /* show unprintables as ? */
104 static int f_nosort; /* don't sort output */
105 int f_notabs; /* don't use tab-separated multi-col output */
106 static int f_numericonly; /* don't convert uid/gid to name */
107 int f_octal; /* show unprintables as \xxx */
108 int f_octal_escape; /* like f_octal but use C escapes if possible */
109 static int f_recursive; /* ls subdirectories also */
110 static int f_reversesort; /* reverse whatever sort is used */
111 int f_sectime; /* print the real time for all files */
112 static int f_singlecol; /* use single column output */
113 int f_size; /* list size in short listing */
114 int f_slash; /* similar to f_type, but only for dirs */
115 int f_sortacross; /* sort across rows, not down columns */
116 int f_statustime; /* use time of last mode change */
117 int f_stream; /* stream the output, seperate with commas */
118 static int f_timesort; /* sort by time vice name */
119 int f_type; /* add type character for non-regular files */
120 static int f_whiteout; /* show whiteout entries */
121 int f_lomac; /* show LOMAC attributes */
123 int f_color; /* add type in color for non-regular files */
125 char *ansi_bgcol; /* ANSI sequence to set background colour */
126 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
127 char *ansi_coloff; /* ANSI sequence to reset colours */
128 char *attrs_off; /* ANSI sequence to turn off attributes */
129 char *enter_bold; /* ANSI sequence to set color to bold mode */
135 main(int argc, char *argv[])
137 static char dot[] = ".", *dotav[] = {dot, NULL};
139 int ch, fts_options, notused;
142 char termcapbuf[1024]; /* termcap definition buffer */
143 char tcapbuf[512]; /* capability buffer */
147 (void)setlocale(LC_ALL, "");
149 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
150 if (isatty(STDOUT_FILENO)) {
152 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
154 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
156 termwidth = win.ws_col;
160 /* retrieve environment variable, in case of explicit -C */
161 p = getenv("COLUMNS");
166 /* Root is -A automatically. */
170 fts_options = FTS_PHYSICAL;
171 while ((ch = getopt(argc, argv, "1ABCFGHLPRTWZabcdfghiklmnopqrstuwx"))
175 * The -1, -C, -x and -l options all override each other so
176 * shell aliasing works right.
189 f_sortacross = f_longform = f_singlecol = 0;
201 /* The -c and -u options override each other. */
215 fts_options |= FTS_COMFOLLOW;
218 setenv("CLICOLOR", "", 1);
221 fts_options &= ~FTS_PHYSICAL;
222 fts_options |= FTS_LOGICAL;
225 fts_options &= ~FTS_COMFOLLOW;
226 fts_options &= ~FTS_LOGICAL;
227 fts_options |= FTS_PHYSICAL;
233 fts_options |= FTS_SEEDOT;
238 /* The -d option turns off the -R option. */
246 case 'g': /* Compatibility with 4.3BSD. */
313 /* Enabling of colours is conditional on the environment. */
314 if (getenv("CLICOLOR") &&
315 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
317 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
318 ansi_fgcol = tgetstr("AF", &bp);
319 ansi_bgcol = tgetstr("AB", &bp);
320 attrs_off = tgetstr("me", &bp);
321 enter_bold = tgetstr("md", &bp);
323 /* To switch colours off use 'op' if
324 * available, otherwise use 'oc', or
325 * don't do colours at all. */
326 ansi_coloff = tgetstr("op", &bp);
328 ansi_coloff = tgetstr("oc", &bp);
329 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
333 (void)fprintf(stderr, "Color support not compiled in.\n");
339 * We can't put tabs and color sequences together:
340 * column number will be incremented incorrectly
341 * for "stty oxtabs" mode.
344 (void)signal(SIGINT, colorquit);
345 (void)signal(SIGQUIT, colorquit);
346 parsecolors(getenv("LSCOLORS"));
351 * If not -F, -i, -l, -s or -t options, don't require stat
352 * information, unless in color mode in which case we do
353 * need this to determine which colors to display.
355 if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
360 fts_options |= FTS_NOSTAT;
363 * If not -F, -d or -l options, follow any symbolic links listed on
366 if (!f_longform && !f_listdir && !f_type)
367 fts_options |= FTS_COMFOLLOW;
370 * If -W, show whiteout entries
374 fts_options |= FTS_WHITEOUT;
377 /* If -l or -s, figure out block size. */
378 if (f_longform || f_size) {
382 (void)getbsize(¬used, &blocksize);
386 /* Select a sort function. */
389 sortfcn = revnamecmp;
390 else if (f_accesstime)
392 else if (f_statustime)
393 sortfcn = revstatcmp;
394 else /* Use modification time. */
399 else if (f_accesstime)
401 else if (f_statustime)
403 else /* Use modification time. */
407 /* Select a print function. */
409 printfcn = printscol;
411 printfcn = printlong;
413 printfcn = printstream;
418 traverse(argc, argv, fts_options);
420 traverse(1, dotav, fts_options);
424 static int output; /* If anything output. */
427 * Traverse() walks the logical directory structure specified by the argv list
428 * in the order specified by the mastercmp() comparison function. During the
429 * traversal it passes linked lists of structures to display() which represent
430 * a superset (may be exact set) of the files to be displayed.
433 traverse(int argc, char *argv[], int options)
440 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
443 display(NULL, fts_children(ftsp, 0));
448 * If not recursing down this tree and don't need stat info, just get
451 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
453 while ((p = fts_read(ftsp)) != NULL)
454 switch (p->fts_info) {
456 warnx("%s: directory causes a cycle", p->fts_name);
460 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
464 if (p->fts_level != FTS_ROOTLEVEL &&
465 p->fts_name[0] == '.' && !f_listdot)
469 * If already output something, put out a newline as
470 * a separator. If multiple arguments, precede each
471 * directory with its name.
474 (void)printf("\n%s:\n", p->fts_path);
476 (void)printf("%s:\n", p->fts_path);
479 chp = fts_children(ftsp, ch_options);
482 if (!f_recursive && chp != NULL)
483 (void)fts_set(ftsp, p, FTS_SKIP);
493 * Display() takes a linked list of FTSENT structures and passes the list
494 * along with any other necessary information to the print function. P
495 * points to the parent directory of the display list.
498 display(FTSENT *p, FTSENT *list)
505 u_long btotal, lattrlen, maxblock, maxinode, maxlen, maxnlink, maxlattr;
506 int bcfile, maxflags;
509 size_t flen, ulen, glen;
511 int entries, needstats;
512 const char *user, *group;
513 char *flags, *lattr = NULL;
514 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
515 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
516 char nuser[STRBUF_SIZEOF(gid_t) + 1];
519 * If list is NULL there are two possibilities: that the parent
520 * directory p has no children, or that fts_children() returned an
521 * error. We ignore the error case since it will be replicated
522 * on the next call to fts_read() on the post-order visit to the
523 * directory p, and will be signaled in traverse().
528 needstats = f_inode || f_longform || f_size;
531 initmax = getenv("LS_COLWIDTHS");
532 /* Fields match -lios order. New ones should be added at the end. */
533 maxlattr = maxblock = maxinode = maxlen = maxnlink =
534 maxuser = maxgroup = maxflags = maxsize = 0;
535 if (initmax != NULL && *initmax != '\0') {
536 char *initmax2, *jinitmax;
539 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
540 jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
541 if (jinitmax == NULL)
544 strcpy(initmax2, "0:"), initmax2 += 2;
546 *initmax2++ = *initmax, *initmax2 = '\0';
547 for (initmax++; *initmax != '\0'; initmax++) {
548 if (initmax[-1] == ':' && initmax[0] == ':') {
550 *initmax2++ = initmax[0];
553 *initmax2++ = initmax[0];
557 if (initmax2[-1] == ':')
558 strcpy(initmax2, "0");
560 ninitmax = sscanf(jinitmax,
561 " %lu : %lu : %lu : %i : %i : %i : %llu : %lu : %lu ",
562 &maxinode, &maxblock, &maxnlink, &maxuser,
563 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlattr);
601 maxinode = makenines(maxinode);
602 maxblock = makenines(maxblock);
603 maxnlink = makenines(maxnlink);
604 maxsize = makenines(maxsize);
610 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
611 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
613 cur->fts_name, strerror(cur->fts_errno));
614 cur->fts_number = NO_PRINT;
619 * P is NULL if list is the argv list, to which different rules
623 /* Directories will be displayed later. */
624 if (cur->fts_info == FTS_D && !f_listdir) {
625 cur->fts_number = NO_PRINT;
629 /* Only display dot file if -a/-A set. */
630 if (cur->fts_name[0] == '.' && !f_listdot) {
631 cur->fts_number = NO_PRINT;
635 if (cur->fts_namelen > maxlen)
636 maxlen = cur->fts_namelen;
637 if (f_octal || f_octal_escape) {
638 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
645 if (sp->st_blocks > maxblock)
646 maxblock = sp->st_blocks;
647 if (sp->st_ino > maxinode)
648 maxinode = sp->st_ino;
649 if (sp->st_nlink > maxnlink)
650 maxnlink = sp->st_nlink;
651 if (sp->st_size > maxsize)
652 maxsize = sp->st_size;
654 btotal += sp->st_blocks;
657 (void)snprintf(nuser, sizeof(nuser),
659 (void)snprintf(ngroup, sizeof(ngroup),
664 user = user_from_uid(sp->st_uid, 0);
665 group = group_from_gid(sp->st_gid, 0);
667 if ((ulen = strlen(user)) > maxuser)
669 if ((glen = strlen(group)) > maxgroup)
672 flags = fflagstostr(sp->st_flags);
673 if (flags != NULL && *flags == '\0') {
678 err(1, "fflagstostr");
679 flen = strlen(flags);
680 if (flen > (size_t)maxflags)
686 lattr = get_lattr(cur);
687 lattrlen = strlen(lattr);
688 if (lattrlen > maxlattr)
693 if ((np = malloc(sizeof(NAMES) + lattrlen +
694 ulen + glen + flen + 4)) == NULL)
697 np->user = &np->data[0];
698 (void)strcpy(np->user, user);
699 np->group = &np->data[ulen + 1];
700 (void)strcpy(np->group, group);
702 if (S_ISCHR(sp->st_mode) ||
703 S_ISBLK(sp->st_mode))
707 np->flags = &np->data[ulen + glen + 2];
708 (void)strcpy(np->flags, flags);
712 np->lattr = &np->data[ulen + glen + 2
713 + (f_flags ? flen + 1 : 0)];
714 (void)strcpy(np->lattr, lattr);
717 cur->fts_pointer = np;
732 (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
733 d.s_block = strlen(buf);
734 d.s_flags = maxflags;
735 d.s_lattr = maxlattr;
736 d.s_group = maxgroup;
737 (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
738 d.s_inode = strlen(buf);
739 (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
740 d.s_nlink = strlen(buf);
741 (void)snprintf(buf, sizeof(buf), "%qu", maxsize);
742 d.s_size = strlen(buf);
749 for (cur = list; cur; cur = cur->fts_link)
750 free(cur->fts_pointer);
756 * Ordering for mastercmp:
757 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
758 * as larger than directories. Within either group, use the sort function.
759 * All other levels use the sort function. Error entries remain unsorted.
762 mastercmp(const FTSENT **a, const FTSENT **b)
766 a_info = (*a)->fts_info;
767 if (a_info == FTS_ERR)
769 b_info = (*b)->fts_info;
770 if (b_info == FTS_ERR)
773 if (a_info == FTS_NS || b_info == FTS_NS)
774 return (namecmp(*a, *b));
776 if (a_info != b_info &&
777 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
783 return (sortfcn(*a, *b));
787 * Makenines() returns (10**n)-1. This is useful for converting a width
788 * into a number that wide in decimal.
797 /* Use a loop instead of pow(), since all values of n are small. */
798 for (i = 0; i < n; i++)