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
37 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 static const char copyright[] =
43 "@(#) Copyright (c) 1989, 1993, 1994\n\
44 The Regents of the University of California. All rights reserved.\n";
49 static char sccsid[] = "@(#)ls.c 8.5 (Berkeley) 4/2/94";
53 #include <sys/types.h>
55 #include <sys/ioctl.h>
79 * Upward approximation of the maximum number of characters needed to
80 * represent a value of integral type t as a string, excluding the
81 * NUL terminator, with provision for a sign.
83 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
85 static void display(FTSENT *, FTSENT *);
86 static u_quad_t makenines(u_long);
87 static int mastercmp(const FTSENT **, const FTSENT **);
88 static void traverse(int, char **, int);
90 static void (*printfcn)(DISPLAY *);
91 static int (*sortfcn)(const FTSENT *, const FTSENT *);
93 long blocksize; /* block size units */
94 int termwidth = 80; /* default terminal width */
97 int f_accesstime; /* use time of last access */
98 int f_flags; /* show flags associated with a file */
99 int f_humanval; /* show human-readable file sizes */
100 int f_inode; /* print inode */
101 static int f_kblocks; /* print size in kilobytes */
102 static int f_listdir; /* list actual directory, not contents */
103 static int f_listdot; /* list files beginning with . */
104 int f_longform; /* long listing format */
105 int f_nonprint; /* show unprintables as ? */
106 static int f_nosort; /* don't sort output */
107 int f_notabs; /* don't use tab-separated multi-col output */
108 static int f_numericonly; /* don't convert uid/gid to name */
109 int f_octal; /* show unprintables as \xxx */
110 int f_octal_escape; /* like f_octal but use C escapes if possible */
111 static int f_recursive; /* ls subdirectories also */
112 static int f_reversesort; /* reverse whatever sort is used */
113 int f_sectime; /* print the real time for all files */
114 static int f_singlecol; /* use single column output */
115 int f_size; /* list size in short listing */
116 int f_statustime; /* use time of last mode change */
117 static int f_timesort; /* sort by time vice name */
118 int f_type; /* add type character for non-regular files */
119 static int f_whiteout; /* show whiteout entries */
120 int f_lomac; /* show LOMAC attributes */
122 int f_color; /* add type in color for non-regular files */
124 char *ansi_bgcol; /* ANSI sequence to set background colour */
125 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
126 char *ansi_coloff; /* ANSI sequence to reset colours */
127 char *attrs_off; /* ANSI sequence to turn off attributes */
128 char *enter_bold; /* ANSI sequence to set color to bold mode */
134 main(int argc, char *argv[])
136 static char dot[] = ".", *dotav[] = {dot, NULL};
138 int ch, fts_options, notused;
141 char termcapbuf[1024]; /* termcap definition buffer */
142 char tcapbuf[512]; /* capability buffer */
146 (void)setlocale(LC_ALL, "");
148 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
149 if (isatty(STDOUT_FILENO)) {
150 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
152 if ((p = getenv("COLUMNS")) != NULL)
155 termwidth = win.ws_col;
159 /* retrieve environment variable, in case of explicit -C */
160 p = getenv("COLUMNS");
165 /* Root is -A automatically. */
169 fts_options = FTS_PHYSICAL;
170 while ((ch = getopt(argc, argv, "1ABCFGHLPRTWZabcdfghiklnoqrstuw")) != -1) {
173 * The -1, -C and -l options all override each other so shell
174 * aliasing works right.
186 f_longform = f_singlecol = 0;
192 /* The -c and -u options override each other. */
205 fts_options |= FTS_COMFOLLOW;
208 setenv("CLICOLOR", "", 1);
211 fts_options &= ~FTS_PHYSICAL;
212 fts_options |= FTS_LOGICAL;
215 fts_options &= ~FTS_COMFOLLOW;
216 fts_options &= ~FTS_LOGICAL;
217 fts_options |= FTS_PHYSICAL;
223 fts_options |= FTS_SEEDOT;
228 /* The -d option turns off the -R option. */
236 case 'g': /* Compatibility with 4.3BSD. */
294 /* Enabling of colours is conditional on the environment. */
295 if (getenv("CLICOLOR") &&
296 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
298 if (tgetent(termcapbuf, getenv("TERM")) == 1) {
299 ansi_fgcol = tgetstr("AF", &bp);
300 ansi_bgcol = tgetstr("AB", &bp);
301 attrs_off = tgetstr("me", &bp);
302 enter_bold = tgetstr("md", &bp);
304 /* To switch colours off use 'op' if
305 * available, otherwise use 'oc', or
306 * don't do colours at all. */
307 ansi_coloff = tgetstr("op", &bp);
309 ansi_coloff = tgetstr("oc", &bp);
310 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
314 (void)fprintf(stderr, "Color support not compiled in.\n");
320 * We can't put tabs and color sequences together:
321 * column number will be incremented incorrectly
322 * for "stty oxtabs" mode.
325 (void)signal(SIGINT, colorquit);
326 (void)signal(SIGQUIT, colorquit);
327 parsecolors(getenv("LSCOLORS"));
332 * If not -F, -i, -l, -s or -t options, don't require stat
333 * information, unless in color mode in which case we do
334 * need this to determine which colors to display.
336 if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
341 fts_options |= FTS_NOSTAT;
344 * If not -F, -d or -l options, follow any symbolic links listed on
347 if (!f_longform && !f_listdir && !f_type)
348 fts_options |= FTS_COMFOLLOW;
351 * If -W, show whiteout entries
355 fts_options |= FTS_WHITEOUT;
358 /* If -l or -s, figure out block size. */
359 if (f_longform || f_size) {
363 (void)getbsize(¬used, &blocksize);
367 /* Select a sort function. */
370 sortfcn = revnamecmp;
371 else if (f_accesstime)
373 else if (f_statustime)
374 sortfcn = revstatcmp;
375 else /* Use modification time. */
380 else if (f_accesstime)
382 else if (f_statustime)
384 else /* Use modification time. */
388 /* Select a print function. */
390 printfcn = printscol;
392 printfcn = printlong;
397 traverse(argc, argv, fts_options);
399 traverse(1, dotav, fts_options);
403 static int output; /* If anything output. */
406 * Traverse() walks the logical directory structure specified by the argv list
407 * in the order specified by the mastercmp() comparison function. During the
408 * traversal it passes linked lists of structures to display() which represent
409 * a superset (may be exact set) of the files to be displayed.
412 traverse(int argc, char *argv[], int options)
419 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
422 display(NULL, fts_children(ftsp, 0));
427 * If not recursing down this tree and don't need stat info, just get
430 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
432 while ((p = fts_read(ftsp)) != NULL)
433 switch (p->fts_info) {
435 warnx("%s: directory causes a cycle", p->fts_name);
439 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
443 if (p->fts_level != FTS_ROOTLEVEL &&
444 p->fts_name[0] == '.' && !f_listdot)
448 * If already output something, put out a newline as
449 * a separator. If multiple arguments, precede each
450 * directory with its name.
453 (void)printf("\n%s:\n", p->fts_path);
455 (void)printf("%s:\n", p->fts_path);
458 chp = fts_children(ftsp, ch_options);
461 if (!f_recursive && chp != NULL)
462 (void)fts_set(ftsp, p, FTS_SKIP);
471 * Display() takes a linked list of FTSENT structures and passes the list
472 * along with any other necessary information to the print function. P
473 * points to the parent directory of the display list.
476 display(FTSENT *p, FTSENT *list)
483 u_long btotal, lattrlen, maxblock, maxinode, maxlen, maxnlink, maxlattr;
484 int bcfile, maxflags;
487 size_t flen, ulen, glen;
489 int entries, needstats;
490 char *user, *group, *flags, *lattr = NULL;
491 char buf[STRBUF_SIZEOF(u_quad_t) + 1];
492 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
493 char nuser[STRBUF_SIZEOF(gid_t) + 1];
496 * If list is NULL there are two possibilities: that the parent
497 * directory p has no children, or that fts_children() returned an
498 * error. We ignore the error case since it will be replicated
499 * on the next call to fts_read() on the post-order visit to the
500 * directory p, and will be signaled in traverse().
505 needstats = f_inode || f_longform || f_size;
508 initmax = getenv("LS_COLWIDTHS");
509 /* Fields match -lios order. New ones should be added at the end. */
510 maxlattr = maxblock = maxinode = maxlen = maxnlink =
511 maxuser = maxgroup = maxflags = maxsize = 0;
512 if (initmax != NULL && *initmax != '\0') {
513 char *initmax2, *jinitmax;
516 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
517 jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
518 if (jinitmax == NULL)
521 strcpy(initmax2, "0:"), initmax2 += 2;
523 *initmax2++ = *initmax, *initmax2 = '\0';
524 for (initmax++; *initmax != '\0'; initmax++) {
525 if (initmax[-1] == ':' && initmax[0] == ':') {
527 *initmax2++ = initmax[0];
530 *initmax2++ = initmax[0];
534 if (initmax2[-1] == ':')
535 strcpy(initmax2, "0");
537 ninitmax = sscanf(jinitmax,
538 " %lu : %lu : %lu : %i : %i : %i : %llu : %lu : %lu ",
539 &maxinode, &maxblock, &maxnlink, &maxuser,
540 &maxgroup, &maxflags, &maxsize, &maxlen, &maxlattr);
577 maxinode = makenines(maxinode);
578 maxblock = makenines(maxblock);
579 maxnlink = makenines(maxnlink);
580 maxsize = makenines(maxsize);
586 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
587 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
589 cur->fts_name, strerror(cur->fts_errno));
590 cur->fts_number = NO_PRINT;
595 * P is NULL if list is the argv list, to which different rules
599 /* Directories will be displayed later. */
600 if (cur->fts_info == FTS_D && !f_listdir) {
601 cur->fts_number = NO_PRINT;
605 /* Only display dot file if -a/-A set. */
606 if (cur->fts_name[0] == '.' && !f_listdot) {
607 cur->fts_number = NO_PRINT;
611 if (cur->fts_namelen > maxlen)
612 maxlen = cur->fts_namelen;
613 if (f_octal || f_octal_escape) {
614 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
621 if (sp->st_blocks > maxblock)
622 maxblock = sp->st_blocks;
623 if (sp->st_ino > maxinode)
624 maxinode = sp->st_ino;
625 if (sp->st_nlink > maxnlink)
626 maxnlink = sp->st_nlink;
627 if (sp->st_size > maxsize)
628 maxsize = sp->st_size;
630 btotal += sp->st_blocks;
633 (void)snprintf(nuser, sizeof(nuser),
635 (void)snprintf(ngroup, sizeof(ngroup),
640 user = user_from_uid(sp->st_uid, 0);
641 group = group_from_gid(sp->st_gid, 0);
643 if ((ulen = strlen(user)) > maxuser)
645 if ((glen = strlen(group)) > maxgroup)
648 flags = fflagstostr(sp->st_flags);
649 if (flags != NULL && *flags == '\0') {
655 flen = strlen(flags);
656 if (flen > (size_t)maxflags)
662 lattr = get_lattr(cur);
663 lattrlen = strlen(lattr);
664 if (lattrlen > maxlattr)
669 if ((np = malloc(sizeof(NAMES) + lattrlen +
670 ulen + glen + flen + 4)) == 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);
688 np->lattr = &np->data[ulen + glen + 2
689 + (f_flags ? flen + 1 : 0)];
690 (void)strcpy(np->lattr, lattr);
693 cur->fts_pointer = np;
708 (void)snprintf(buf, sizeof(buf), "%lu", maxblock);
709 d.s_block = strlen(buf);
710 d.s_flags = maxflags;
711 d.s_lattr = maxlattr;
712 d.s_group = maxgroup;
713 (void)snprintf(buf, sizeof(buf), "%lu", maxinode);
714 d.s_inode = strlen(buf);
715 (void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
716 d.s_nlink = strlen(buf);
717 (void)snprintf(buf, sizeof(buf), "%qu", maxsize);
718 d.s_size = strlen(buf);
725 for (cur = list; cur; cur = cur->fts_link)
726 free(cur->fts_pointer);
732 * Ordering for mastercmp:
733 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
734 * as larger than directories. Within either group, use the sort function.
735 * All other levels use the sort function. Error entries remain unsorted.
738 mastercmp(const FTSENT **a, const FTSENT **b)
742 a_info = (*a)->fts_info;
743 if (a_info == FTS_ERR)
745 b_info = (*b)->fts_info;
746 if (b_info == FTS_ERR)
749 if (a_info == FTS_NS || b_info == FTS_NS)
750 return (namecmp(*a, *b));
752 if (a_info != b_info &&
753 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
759 return (sortfcn(*a, *b));
763 * Makenines() returns (10**n)-1. This is useful for converting a width
764 * into a number that wide in decimal.
773 /* Use a loop instead of pow(), since all values of n are small. */
774 for (i = 0; i < n; i++)