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.7 2005/09/17 07:08:43 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_fsmid; /* show FSMID associated with a file */
88 int f_humanval; /* show human-readable file sizes */
89 int f_inode; /* print inode */
90 static int f_kblocks; /* print size in kilobytes */
91 static int f_listdir; /* list actual directory, not contents */
92 static int f_listdot; /* list files beginning with . */
93 int f_longform; /* long listing format */
94 int f_nonprint; /* show unprintables as ? */
95 static int f_nosort; /* don't sort output */
96 int f_notabs; /* don't use tab-separated multi-col output */
97 static int f_numericonly; /* don't convert uid/gid to name */
98 int f_octal; /* show unprintables as \xxx */
99 int f_octal_escape; /* like f_octal but use C escapes if possible */
100 static int f_recursive; /* ls subdirectories also */
101 static int f_reversesort; /* reverse whatever sort is used */
102 int f_sectime; /* print the real time for all files */
103 static int f_singlecol; /* use single column output */
104 int f_size; /* list size in short listing */
105 int f_slash; /* similar to f_type, but only for dirs */
106 int f_sortacross; /* sort across rows, not down columns */
107 int f_statustime; /* use time of last mode change */
108 static int f_stream; /* stream the output, separate with commas */
109 static int f_timesort; /* sort by time vice name */
110 int f_type; /* add type character for non-regular files */
111 static int f_whiteout; /* show whiteout entries */
113 int f_color; /* add type in color for non-regular files */
115 char *ansi_bgcol; /* ANSI sequence to set background colour */
116 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
117 char *ansi_coloff; /* ANSI sequence to reset colours */
118 char *attrs_off; /* ANSI sequence to turn off attributes */
119 char *enter_bold; /* ANSI sequence to set color to bold mode */
125 main(int argc, char *argv[])
127 static char dot[] = ".", *dotav[] = {dot, NULL};
129 int ch, fts_options, notused;
132 char termcapbuf[1024]; /* termcap definition buffer */
133 char tcapbuf[512]; /* capability buffer */
137 setlocale(LC_ALL, "");
139 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
140 if (isatty(STDOUT_FILENO)) {
142 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
144 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
146 termwidth = win.ws_col;
150 /* retrieve environment variable, in case of explicit -C */
151 p = getenv("COLUMNS");
156 /* Root is -A automatically. */
160 fts_options = FTS_PHYSICAL;
161 while ((ch = getopt(argc, argv, "1ABCFGHLPRTWabcdfghiklmnopqrstuwxy"))
165 * The -1, -C, -x and -l options all override each other so
166 * shell aliasing works right.
179 f_sortacross = f_longform = f_singlecol = 0;
192 #ifdef _ST_FSMID_PRESENT_
196 /* The -c and -u options override each other. */
210 fts_options |= FTS_COMFOLLOW;
213 setenv("CLICOLOR", "", 1);
216 fts_options &= ~FTS_PHYSICAL;
217 fts_options |= FTS_LOGICAL;
220 fts_options &= ~FTS_COMFOLLOW;
221 fts_options &= ~FTS_LOGICAL;
222 fts_options |= FTS_PHYSICAL;
228 fts_options |= FTS_SEEDOT;
233 /* The -d option turns off the -R option. */
241 case 'g': /* Compatibility with 4.3BSD. */
305 /* Enabling of colours is conditional on the environment. */
306 if (getenv("CLICOLOR") &&
307 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
309 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
310 ansi_fgcol = tgetstr("AF", &bp);
311 ansi_bgcol = tgetstr("AB", &bp);
312 attrs_off = tgetstr("me", &bp);
313 enter_bold = tgetstr("md", &bp);
315 /* To switch colours off use 'op' if
316 * available, otherwise use 'oc', or
317 * don't do colours at all. */
318 ansi_coloff = tgetstr("op", &bp);
320 ansi_coloff = tgetstr("oc", &bp);
321 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
325 fprintf(stderr, "Color support not compiled in.\n");
331 * We can't put tabs and color sequences together:
332 * column number will be incremented incorrectly
333 * for "stty oxtabs" mode.
336 signal(SIGINT, colorquit);
337 signal(SIGQUIT, colorquit);
338 parsecolors(getenv("LSCOLORS"));
343 * If not -F, -i, -l, -s or -t options, don't require stat
344 * information, unless in color mode in which case we do
345 * need this to determine which colors to display.
347 if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
352 fts_options |= FTS_NOSTAT;
355 * If not -F, -d or -l options, follow any symbolic links listed on
358 if (!f_longform && !f_listdir && !f_type)
359 fts_options |= FTS_COMFOLLOW;
362 * If -W, show whiteout entries
366 fts_options |= FTS_WHITEOUT;
369 /* If -l or -s, figure out block size. */
370 if (f_longform || f_size) {
374 getbsize(¬used, &blocksize);
378 /* Select a sort function. */
381 sortfcn = revnamecmp;
382 else if (f_accesstime)
384 else if (f_statustime)
385 sortfcn = revstatcmp;
386 else /* Use modification time. */
391 else if (f_accesstime)
393 else if (f_statustime)
395 else /* Use modification time. */
399 /* Select a print function. */
401 printfcn = printscol;
403 printfcn = printlong;
405 printfcn = printstream;
410 traverse(argc, argv, fts_options);
412 traverse(1, dotav, fts_options);
416 static int output; /* If anything output. */
419 * Traverse() walks the logical directory structure specified by the argv list
420 * in the order specified by the mastercmp() comparison function. During the
421 * traversal it passes linked lists of structures to display() which represent
422 * a superset (may be exact set) of the files to be displayed.
425 traverse(int argc, char *argv[], int options)
432 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
435 display(NULL, fts_children(ftsp, 0));
440 * If not recursing down this tree and don't need stat info, just get
443 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
445 while ((p = fts_read(ftsp)) != NULL)
446 switch (p->fts_info) {
448 warnx("%s: directory causes a cycle", p->fts_name);
452 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
456 if (p->fts_level != FTS_ROOTLEVEL &&
457 p->fts_name[0] == '.' && !f_listdot)
461 * If already output something, put out a newline as
462 * a separator. If multiple arguments, precede each
463 * directory with its name.
467 printname(p->fts_path);
469 } else if (argc > 1) {
470 printname(p->fts_path);
474 chp = fts_children(ftsp, ch_options);
477 if (!f_recursive && chp != NULL)
478 fts_set(ftsp, p, FTS_SKIP);
488 * Display() takes a linked list of FTSENT structures and passes the list
489 * along with any other necessary information to the print function. P
490 * points to the parent directory of the display list.
493 display(FTSENT *p, FTSENT *list)
500 u_long btotal, maxblock, maxinode, maxlen, maxnlink;
501 int bcfile, maxflags;
504 size_t fsmidlen, flen, ulen, glen;
506 int entries, needstats;
507 const char *user, *group;
510 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
511 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
512 char nuser[STRBUF_SIZEOF(gid_t) + 1];
515 * If list is NULL there are two possibilities: that the parent
516 * directory p has no children, or that fts_children() returned an
517 * error. We ignore the error case since it will be replicated
518 * on the next call to fts_read() on the post-order visit to the
519 * directory p, and will be signaled in traverse().
524 needstats = f_inode || f_longform || f_size;
527 initmax = getenv("LS_COLWIDTHS");
528 /* Fields match -lios order. New ones should be added at the end. */
529 maxblock = maxinode = maxlen = maxnlink =
530 maxuser = maxgroup = maxflags = maxsize = 0;
531 if (initmax != NULL && *initmax != '\0') {
532 char *initmax2, *jinitmax;
535 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
536 jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
537 if (jinitmax == NULL)
540 strcpy(initmax2, "0:"), initmax2 += 2;
542 *initmax2++ = *initmax, *initmax2 = '\0';
543 for (initmax++; *initmax != '\0'; initmax++) {
544 if (initmax[-1] == ':' && initmax[0] == ':') {
546 *initmax2++ = initmax[0];
549 *initmax2++ = initmax[0];
553 if (initmax2[-1] == ':')
554 strcpy(initmax2, "0");
556 ninitmax = sscanf(jinitmax,
557 " %lu : %lu : %lu : %i : %i : %i : %llu : %lu ",
558 &maxinode, &maxblock, &maxnlink, &maxuser,
559 &maxgroup, &maxflags, &maxsize, &maxlen);
594 maxinode = makenines(maxinode);
595 maxblock = makenines(maxblock);
596 maxnlink = makenines(maxnlink);
597 maxsize = makenines(maxsize);
602 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
603 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
605 cur->fts_name, strerror(cur->fts_errno));
606 cur->fts_number = NO_PRINT;
611 * P is NULL if list is the argv list, to which different rules
615 /* Directories will be displayed later. */
616 if (cur->fts_info == FTS_D && !f_listdir) {
617 cur->fts_number = NO_PRINT;
621 /* Only display dot file if -a/-A set. */
622 if (cur->fts_name[0] == '.' && !f_listdot) {
623 cur->fts_number = NO_PRINT;
627 if (cur->fts_namelen > maxlen)
628 maxlen = cur->fts_namelen;
629 if (f_octal || f_octal_escape) {
630 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
637 if (sp->st_blocks > maxblock)
638 maxblock = sp->st_blocks;
639 if (sp->st_ino > maxinode)
640 maxinode = sp->st_ino;
641 if (sp->st_nlink > maxnlink)
642 maxnlink = sp->st_nlink;
643 if (sp->st_size > maxsize)
644 maxsize = sp->st_size;
646 btotal += sp->st_blocks;
649 snprintf(nuser, sizeof(nuser),
651 snprintf(ngroup, sizeof(ngroup),
656 user = user_from_uid(sp->st_uid, 0);
657 group = group_from_gid(sp->st_gid, 0);
659 if ((ulen = strlen(user)) > maxuser)
661 if ((glen = strlen(group)) > maxgroup)
664 flags = fflagstostr(sp->st_flags);
665 if (flags != NULL && *flags == '\0') {
671 flen = strlen(flags);
672 if (flen > (size_t)maxflags)
677 #ifdef _ST_FSMID_PRESENT_
679 fsmid = sp->st_fsmid;
689 if ((np = malloc(sizeof(NAMES) +
690 ulen + glen + flen + fsmidlen + 4)) == NULL)
693 np->user = &np->data[0];
694 strcpy(np->user, user);
695 np->group = &np->data[ulen + 1];
696 strcpy(np->group, group);
698 if (S_ISCHR(sp->st_mode) ||
699 S_ISBLK(sp->st_mode))
703 np->flags = &np->data[ulen + glen + 2];
704 strcpy(np->flags, flags);
707 #ifdef _ST_FSMID_PRESENT_
709 np->fsmid = np->data + ulen + glen + flen + 3;
710 snprintf(np->fsmid, fsmidlen + 1,
714 cur->fts_pointer = np;
729 snprintf(buf, sizeof(buf), "%lu", maxblock);
730 d.s_block = strlen(buf);
731 d.s_flags = maxflags;
732 d.s_group = maxgroup;
733 snprintf(buf, sizeof(buf), "%lu", maxinode);
734 d.s_inode = strlen(buf);
735 snprintf(buf, sizeof(buf), "%lu", maxnlink);
736 d.s_nlink = strlen(buf);
737 snprintf(buf, sizeof(buf), "%llu", maxsize);
738 d.s_size = strlen(buf);
745 for (cur = list; cur; cur = cur->fts_link)
746 free(cur->fts_pointer);
750 * Ordering for mastercmp:
751 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
752 * as larger than directories. Within either group, use the sort function.
753 * All other levels use the sort function. Error entries remain unsorted.
756 mastercmp(const FTSENT **a, const FTSENT **b)
760 a_info = (*a)->fts_info;
761 if (a_info == FTS_ERR)
763 b_info = (*b)->fts_info;
764 if (b_info == FTS_ERR)
767 if (a_info == FTS_NS || b_info == FTS_NS)
768 return (namecmp(*a, *b));
770 if (a_info != b_info &&
771 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
777 return (sortfcn(*a, *b));
781 * Makenines() returns (10**n)-1. This is useful for converting a width
782 * into a number that wide in decimal.
791 /* Use a loop instead of pow(), since all values of n are small. */
792 for (i = 0; i < n; i++)