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
36 * @(#) Copyright (c) 1989, 1993, 1994 The Regents of the University of California. All rights reserved.
37 * @(#)ls.c 8.5 (Berkeley) 4/2/94
38 * $FreeBSD: src/bin/ls/ls.c,v 1.32.2.8 2002/11/17 10:27:34 tjr Exp $
39 * $DragonFly: src/bin/ls/ls.c,v 1.2 2003/06/17 04:22:50 dillon Exp $
42 #include <sys/types.h>
44 #include <sys/ioctl.h>
67 * Upward approximation of the maximum number of characters needed to
68 * represent a value of integral type t as a string, excluding the
69 * NUL terminator, with provision for a sign.
71 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
73 static void display(FTSENT *, FTSENT *);
74 static u_quad_t makenines(u_long);
75 static int mastercmp(const FTSENT **, const FTSENT **);
76 static void traverse(int, char **, int);
78 static void (*printfcn)(DISPLAY *);
79 static int (*sortfcn)(const FTSENT *, const FTSENT *);
81 long blocksize; /* block size units */
82 int termwidth = 80; /* default terminal width */
85 int f_accesstime; /* use time of last access */
86 int f_flags; /* show flags associated with a file */
87 int f_humanval; /* show human-readable file sizes */
88 int f_inode; /* print inode */
89 static int f_kblocks; /* print size in kilobytes */
90 static int f_listdir; /* list actual directory, not contents */
91 static int f_listdot; /* list files beginning with . */
92 int f_longform; /* long listing format */
93 int f_nonprint; /* show unprintables as ? */
94 static int f_nosort; /* don't sort output */
95 int f_notabs; /* don't use tab-separated multi-col output */
96 static int f_numericonly; /* don't convert uid/gid to name */
97 int f_octal; /* show unprintables as \xxx */
98 int f_octal_escape; /* like f_octal but use C escapes if possible */
99 static int f_recursive; /* ls subdirectories also */
100 static int f_reversesort; /* reverse whatever sort is used */
101 int f_sectime; /* print the real time for all files */
102 static int f_singlecol; /* use single column output */
103 int f_size; /* list size in short listing */
104 int f_slash; /* similar to f_type, but only for dirs */
105 int f_sortacross; /* sort across rows, not down columns */
106 int f_statustime; /* use time of last mode change */
107 int f_stream; /* stream the output, separate with commas */
108 static int f_timesort; /* sort by time vice name */
109 int f_type; /* add type character for non-regular files */
110 static int f_whiteout; /* show whiteout entries */
112 int f_color; /* add type in color for non-regular files */
114 char *ansi_bgcol; /* ANSI sequence to set background colour */
115 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
116 char *ansi_coloff; /* ANSI sequence to reset colours */
117 char *attrs_off; /* ANSI sequence to turn off attributes */
118 char *enter_bold; /* ANSI sequence to set color to bold mode */
124 main(int argc, char *argv[])
126 static char dot[] = ".", *dotav[] = {dot, NULL};
128 int ch, fts_options, notused;
131 char termcapbuf[1024]; /* termcap definition buffer */
132 char tcapbuf[512]; /* capability buffer */
136 (void)setlocale(LC_ALL, "");
138 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
139 if (isatty(STDOUT_FILENO)) {
141 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
143 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
145 termwidth = win.ws_col;
149 /* retrieve environment variable, in case of explicit -C */
150 p = getenv("COLUMNS");
155 /* Root is -A automatically. */
159 fts_options = FTS_PHYSICAL;
160 while ((ch = getopt(argc, argv, "1ABCFGHLPRTWabcdfghiklmnopqrstuwx"))
164 * The -1, -C, -x and -l options all override each other so
165 * shell aliasing works right.
178 f_sortacross = f_longform = f_singlecol = 0;
190 /* The -c and -u options override each other. */
204 fts_options |= FTS_COMFOLLOW;
207 setenv("CLICOLOR", "", 1);
210 fts_options &= ~FTS_PHYSICAL;
211 fts_options |= FTS_LOGICAL;
214 fts_options &= ~FTS_COMFOLLOW;
215 fts_options &= ~FTS_LOGICAL;
216 fts_options |= FTS_PHYSICAL;
222 fts_options |= FTS_SEEDOT;
227 /* The -d option turns off the -R option. */
235 case 'g': /* Compatibility with 4.3BSD. */
299 /* Enabling of colours is conditional on the environment. */
300 if (getenv("CLICOLOR") &&
301 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
303 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
304 ansi_fgcol = tgetstr("AF", &bp);
305 ansi_bgcol = tgetstr("AB", &bp);
306 attrs_off = tgetstr("me", &bp);
307 enter_bold = tgetstr("md", &bp);
309 /* To switch colours off use 'op' if
310 * available, otherwise use 'oc', or
311 * don't do colours at all. */
312 ansi_coloff = tgetstr("op", &bp);
314 ansi_coloff = tgetstr("oc", &bp);
315 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
319 (void)fprintf(stderr, "Color support not compiled in.\n");
325 * We can't put tabs and color sequences together:
326 * column number will be incremented incorrectly
327 * for "stty oxtabs" mode.
330 (void)signal(SIGINT, colorquit);
331 (void)signal(SIGQUIT, colorquit);
332 parsecolors(getenv("LSCOLORS"));
337 * If not -F, -i, -l, -s or -t options, don't require stat
338 * information, unless in color mode in which case we do
339 * need this to determine which colors to display.
341 if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
346 fts_options |= FTS_NOSTAT;
349 * If not -F, -d or -l options, follow any symbolic links listed on
352 if (!f_longform && !f_listdir && !f_type)
353 fts_options |= FTS_COMFOLLOW;
356 * If -W, show whiteout entries
360 fts_options |= FTS_WHITEOUT;
363 /* If -l or -s, figure out block size. */
364 if (f_longform || f_size) {
368 (void)getbsize(¬used, &blocksize);
372 /* Select a sort function. */
375 sortfcn = revnamecmp;
376 else if (f_accesstime)
378 else if (f_statustime)
379 sortfcn = revstatcmp;
380 else /* Use modification time. */
385 else if (f_accesstime)
387 else if (f_statustime)
389 else /* Use modification time. */
393 /* Select a print function. */
395 printfcn = printscol;
397 printfcn = printlong;
399 printfcn = printstream;
404 traverse(argc, argv, fts_options);
406 traverse(1, dotav, fts_options);
410 static int output; /* If anything output. */
413 * Traverse() walks the logical directory structure specified by the argv list
414 * in the order specified by the mastercmp() comparison function. During the
415 * traversal it passes linked lists of structures to display() which represent
416 * a superset (may be exact set) of the files to be displayed.
419 traverse(int argc, char *argv[], int options)
426 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
429 display(NULL, fts_children(ftsp, 0));
434 * If not recursing down this tree and don't need stat info, just get
437 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
439 while ((p = fts_read(ftsp)) != NULL)
440 switch (p->fts_info) {
442 warnx("%s: directory causes a cycle", p->fts_name);
446 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
450 if (p->fts_level != FTS_ROOTLEVEL &&
451 p->fts_name[0] == '.' && !f_listdot)
455 * If already output something, put out a newline as
456 * a separator. If multiple arguments, precede each
457 * directory with its name.
461 printname(p->fts_path);
463 } else if (argc > 1) {
464 printname(p->fts_path);
468 chp = fts_children(ftsp, ch_options);
471 if (!f_recursive && chp != NULL)
472 (void)fts_set(ftsp, p, FTS_SKIP);
482 * Display() takes a linked list of FTSENT structures and passes the list
483 * along with any other necessary information to the print function. P
484 * points to the parent directory of the display list.
487 display(FTSENT *p, FTSENT *list)
494 u_long btotal, maxblock, maxinode, maxlen, maxnlink;
495 int bcfile, maxflags;
498 size_t flen, ulen, glen;
500 int entries, needstats;
501 const char *user, *group;
503 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
504 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
505 char nuser[STRBUF_SIZEOF(gid_t) + 1];
508 * If list is NULL there are two possibilities: that the parent
509 * directory p has no children, or that fts_children() returned an
510 * error. We ignore the error case since it will be replicated
511 * on the next call to fts_read() on the post-order visit to the
512 * directory p, and will be signaled in traverse().
517 needstats = f_inode || f_longform || f_size;
520 initmax = getenv("LS_COLWIDTHS");
521 /* Fields match -lios order. New ones should be added at the end. */
522 maxblock = maxinode = maxlen = maxnlink =
523 maxuser = maxgroup = maxflags = maxsize = 0;
524 if (initmax != NULL && *initmax != '\0') {
525 char *initmax2, *jinitmax;
528 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
529 jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
530 if (jinitmax == NULL)
533 strcpy(initmax2, "0:"), initmax2 += 2;
535 *initmax2++ = *initmax, *initmax2 = '\0';
536 for (initmax++; *initmax != '\0'; initmax++) {
537 if (initmax[-1] == ':' && initmax[0] == ':') {
539 *initmax2++ = initmax[0];
542 *initmax2++ = initmax[0];
546 if (initmax2[-1] == ':')
547 strcpy(initmax2, "0");
549 ninitmax = sscanf(jinitmax,
550 " %lu : %lu : %lu : %i : %i : %i : %llu : %lu ",
551 &maxinode, &maxblock, &maxnlink, &maxuser,
552 &maxgroup, &maxflags, &maxsize, &maxlen);
587 maxinode = makenines(maxinode);
588 maxblock = makenines(maxblock);
589 maxnlink = makenines(maxnlink);
590 maxsize = makenines(maxsize);
594 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
595 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
597 cur->fts_name, strerror(cur->fts_errno));
598 cur->fts_number = NO_PRINT;
603 * P is NULL if list is the argv list, to which different rules
607 /* Directories will be displayed later. */
608 if (cur->fts_info == FTS_D && !f_listdir) {
609 cur->fts_number = NO_PRINT;
613 /* Only display dot file if -a/-A set. */
614 if (cur->fts_name[0] == '.' && !f_listdot) {
615 cur->fts_number = NO_PRINT;
619 if (cur->fts_namelen > maxlen)
620 maxlen = cur->fts_namelen;
621 if (f_octal || f_octal_escape) {
622 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
629 if (sp->st_blocks > maxblock)
630 maxblock = sp->st_blocks;
631 if (sp->st_ino > maxinode)
632 maxinode = sp->st_ino;
633 if (sp->st_nlink > maxnlink)
634 maxnlink = sp->st_nlink;
635 if (sp->st_size > maxsize)
636 maxsize = sp->st_size;
638 btotal += sp->st_blocks;
641 (void)snprintf(nuser, sizeof(nuser),
643 (void)snprintf(ngroup, sizeof(ngroup),
648 user = user_from_uid(sp->st_uid, 0);
649 group = group_from_gid(sp->st_gid, 0);
651 if ((ulen = strlen(user)) > maxuser)
653 if ((glen = strlen(group)) > maxgroup)
656 flags = fflagstostr(sp->st_flags);
657 if (flags != NULL && *flags == '\0') {
663 flen = strlen(flags);
664 if (flen > (size_t)maxflags)
669 if ((np = malloc(sizeof(NAMES) +
670 ulen + glen + flen + 3)) == NULL)
673 np->user = &np->data[0];
674 (void)strcpy(np->user, user);
675 np->group = &np->data[ulen + 1];
676 (void)strcpy(np->group, group);
678 if (S_ISCHR(sp->st_mode) ||
679 S_ISBLK(sp->st_mode))
683 np->flags = &np->data[ulen + glen + 2];
684 (void)strcpy(np->flags, flags);
687 cur->fts_pointer = np;
702 (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
703 d.s_block = strlen(buf);
704 d.s_flags = maxflags;
705 d.s_group = maxgroup;
706 (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
707 d.s_inode = strlen(buf);
708 (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
709 d.s_nlink = strlen(buf);
710 (void)snprintf(buf, sizeof(buf), "%qu", maxsize);
711 d.s_size = strlen(buf);
718 for (cur = list; cur; cur = cur->fts_link)
719 free(cur->fts_pointer);
723 * Ordering for mastercmp:
724 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
725 * as larger than directories. Within either group, use the sort function.
726 * All other levels use the sort function. Error entries remain unsorted.
729 mastercmp(const FTSENT **a, const FTSENT **b)
733 a_info = (*a)->fts_info;
734 if (a_info == FTS_ERR)
736 b_info = (*b)->fts_info;
737 if (b_info == FTS_ERR)
740 if (a_info == FTS_NS || b_info == FTS_NS)
741 return (namecmp(*a, *b));
743 if (a_info != b_info &&
744 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
750 return (sortfcn(*a, *b));
754 * Makenines() returns (10**n)-1. This is useful for converting a width
755 * into a number that wide in decimal.
764 /* Use a loop instead of pow(), since all values of n are small. */
765 for (i = 0; i < n; i++)