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 * 4. 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 $
35 * $DragonFly: src/bin/ls/ls.c,v 1.17 2008/01/19 15:33:42 matthias Exp $
38 #include <sys/types.h>
40 #include <sys/ioctl.h>
64 * Upward approximation of the maximum number of characters needed to
65 * represent a value of integral type t as a string, excluding the
66 * NUL terminator, with provision for a sign.
68 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
71 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
72 * into a number that wide in decimal.
73 * XXX: Overflows are not considered.
75 #define MAKENINES(n) \
79 /* Use a loop as all values of n are small. */ \
80 for (i = 1; n > 0; i *= 10) \
85 static void display(const FTSENT
*, FTSENT
*);
86 static int mastercmp(const FTSENT
* const *, const FTSENT
* const *);
87 static void traverse(int, char **, int);
89 static void (*printfcn
)(const DISPLAY
*);
90 static int (*sortfcn
)(const FTSENT
*, const FTSENT
*);
92 long blocksize
; /* block size units */
93 int termwidth
= 80; /* default terminal width */
96 int f_accesstime
; /* use time of last access */
97 int f_flags
; /* show flags associated with a file */
98 int f_fsmid
; /* show FSMID 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_slash
; /* similar to f_type, but only for dirs */
117 int f_sortsize
; /* Sort by size */
118 int f_sortacross
; /* sort across rows, not down columns */
119 int f_statustime
; /* use time of last mode change */
120 static int f_stream
; /* stream the output, separate with commas */
121 static int f_timesort
; /* sort by time vice name */
122 int f_type
; /* add type character for non-regular files */
123 static int f_whiteout
; /* show whiteout entries */
125 int f_color
; /* add type in color for non-regular files */
127 char *ansi_bgcol
; /* ANSI sequence to set background colour */
128 char *ansi_fgcol
; /* ANSI sequence to set foreground colour */
129 char *ansi_coloff
; /* ANSI sequence to reset colours */
130 char *attrs_off
; /* ANSI sequence to turn off attributes */
131 char *enter_bold
; /* ANSI sequence to set color to bold mode */
137 main(int argc
, char *argv
[])
139 static char dot
[] = ".", *dotav
[] = {dot
, NULL
};
141 int ch
, fts_options
, notused
;
144 char termcapbuf
[1024]; /* termcap definition buffer */
145 char tcapbuf
[512]; /* capability buffer */
149 setlocale(LC_ALL
, "");
151 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
152 if (isatty(STDOUT_FILENO
)) {
154 if ((p
= getenv("COLUMNS")) != NULL
&& *p
!= '\0')
156 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) != -1 &&
158 termwidth
= win
.ws_col
;
162 /* retrieve environment variable, in case of explicit -C */
163 p
= getenv("COLUMNS");
168 /* Root is -A automatically. */
172 fts_options
= FTS_PHYSICAL
;
173 while ((ch
= getopt(argc
, argv
, "1ABCFGHLPSRTWabcdfghiklmnopqrstuwxy"))
177 * The -1, -C, -x and -l options all override each other so
178 * shell aliasing works right.
191 f_sortacross
= f_longform
= f_singlecol
= 0;
204 #ifdef _ST_FSMID_PRESENT_
208 /* The -c and -u options override each other. */
222 fts_options
|= FTS_COMFOLLOW
;
225 if (setenv("CLICOLOR", "", 1) != 0)
226 warn("setenv: cannot set CLICOLOR");
229 fts_options
&= ~FTS_PHYSICAL
;
230 fts_options
|= FTS_LOGICAL
;
233 fts_options
&= ~FTS_COMFOLLOW
;
234 fts_options
&= ~FTS_LOGICAL
;
235 fts_options
|= FTS_PHYSICAL
;
244 fts_options
|= FTS_SEEDOT
;
249 /* The -d option turns off the -R option. */
257 case 'g': /* Compatibility with 4.3BSD. */
322 /* Enabling of colours is conditional on the environment. */
323 if (getenv("CLICOLOR") &&
324 (isatty(STDOUT_FILENO
) || getenv("CLICOLOR_FORCE")))
326 if (tgetent(termcapbuf
, getenv("TERM")) == 1) {
327 ansi_fgcol
= tgetstr("AF", &bp
);
328 ansi_bgcol
= tgetstr("AB", &bp
);
329 attrs_off
= tgetstr("me", &bp
);
330 enter_bold
= tgetstr("md", &bp
);
332 /* To switch colours off use 'op' if
333 * available, otherwise use 'oc', or
334 * don't do colours at all. */
335 ansi_coloff
= tgetstr("op", &bp
);
337 ansi_coloff
= tgetstr("oc", &bp
);
338 if (ansi_fgcol
&& ansi_bgcol
&& ansi_coloff
)
342 fprintf(stderr
, "Color support not compiled in.\n");
348 * We can't put tabs and color sequences together:
349 * column number will be incremented incorrectly
350 * for "stty oxtabs" mode.
353 signal(SIGINT
, colorquit
);
354 signal(SIGQUIT
, colorquit
);
355 parsecolors(getenv("LSCOLORS"));
360 * If not -F, -i, -l, -s, -S or -t options, don't require stat
361 * information, unless in color mode in which case we do
362 * need this to determine which colors to display.
364 if (!f_inode
&& !f_longform
&& !f_size
&& !f_sortsize
&& !f_timesort
370 fts_options
|= FTS_NOSTAT
;
373 * If not -F, -d or -l options, follow any symbolic links listed on
376 if (!f_longform
&& !f_listdir
&& !f_type
)
377 fts_options
|= FTS_COMFOLLOW
;
380 * If -W, show whiteout entries
384 fts_options
|= FTS_WHITEOUT
;
387 /* If -l or -s, figure out block size. */
388 if (f_longform
|| f_size
) {
392 getbsize(¬used
, &blocksize
);
396 /* Select a sort function. */
399 sortfcn
= revnamecmp
;
400 else if (f_accesstime
)
403 sortfcn
= revsizecmp
;
404 else if (f_statustime
)
405 sortfcn
= revstatcmp
;
406 else /* Use modification time. */
411 else if (f_accesstime
)
415 else if (f_statustime
)
417 else /* Use modification time. */
421 /* Select a print function. */
423 printfcn
= printscol
;
425 printfcn
= printlong
;
427 printfcn
= printstream
;
432 traverse(argc
, argv
, fts_options
);
434 traverse(1, dotav
, fts_options
);
438 static int output
; /* If anything output. */
441 * Traverse() walks the logical directory structure specified by the argv list
442 * in the order specified by the mastercmp() comparison function. During the
443 * traversal it passes linked lists of structures to display() which represent
444 * a superset (may be exact set) of the files to be displayed.
447 traverse(int argc
, char *argv
[], int options
)
451 int ch_options
, error
;
454 fts_open(argv
, options
, f_nosort
? NULL
: mastercmp
)) == NULL
)
458 * We ignore errors from fts_children here since they will be
459 * replicated and signalled on the next call to fts_read() below.
461 chp
= fts_children(ftsp
, 0);
470 * If not recursing down this tree and don't need stat info, just get
473 ch_options
= !f_recursive
&& options
& FTS_NOSTAT
? FTS_NAMEONLY
: 0;
475 while ((p
= fts_read(ftsp
)) != NULL
)
476 switch (p
->fts_info
) {
478 warnx("%s: directory causes a cycle", p
->fts_name
);
482 warnx("%s: %s", p
->fts_name
, strerror(p
->fts_errno
));
486 if (p
->fts_level
!= FTS_ROOTLEVEL
&&
487 p
->fts_name
[0] == '.' && !f_listdot
)
491 * If already output something, put out a newline as
492 * a separator. If multiple arguments, precede each
493 * directory with its name.
497 printname(p
->fts_path
);
499 } else if (argc
> 1) {
500 printname(p
->fts_path
);
504 chp
= fts_children(ftsp
, ch_options
);
507 if (!f_recursive
&& chp
!= NULL
)
508 fts_set(ftsp
, p
, FTS_SKIP
);
521 * Display() takes a linked list of FTSENT structures and passes the list
522 * along with any other necessary information to the print function. P
523 * points to the parent directory of the display list.
526 display(const FTSENT
*p
, FTSENT
*list
)
533 u_long btotal
, maxlen
;
537 int bcfile
, maxflags
;
540 size_t fsmidlen
, flen
, ulen
, glen
;
542 int entries
, needstats
;
543 const char *user
, *group
;
546 char buf
[STRBUF_SIZEOF(u_quad_t
) + 1];
547 char ngroup
[STRBUF_SIZEOF(uid_t
) + 1];
548 char nuser
[STRBUF_SIZEOF(gid_t
) + 1];
550 needstats
= f_inode
|| f_longform
|| f_size
;
553 initmax
= getenv("LS_COLWIDTHS");
554 /* Fields match -lios order. New ones should be added at the end. */
555 maxblock
= maxinode
= maxlen
= maxnlink
=
556 maxuser
= maxgroup
= maxflags
= maxsize
= 0;
557 if (initmax
!= NULL
&& *initmax
!= '\0') {
558 char *initmax2
, *jinitmax
;
561 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
562 jinitmax
= malloc(strlen(initmax
) * 2 + 2);
563 if (jinitmax
== NULL
)
567 strcpy(initmax2
, "0:"), initmax2
+= 2;
569 *initmax2
++ = *initmax
, *initmax2
= '\0';
570 for (initmax
++; *initmax
!= '\0'; initmax
++) {
571 if (initmax
[-1] == ':' && initmax
[0] == ':') {
573 *initmax2
++ = initmax
[0];
576 *initmax2
++ = initmax
[0];
580 if (initmax2
[-1] == ':')
581 strcpy(initmax2
, "0");
583 ninitmax
= sscanf(jinitmax
,
584 " %ju : %jd : %u : %i : %i : %i : %jd : %lu ",
585 &maxinode
, &maxblock
, &maxnlink
, &maxuser
,
586 &maxgroup
, &maxflags
, &maxsize
, &maxlen
);
629 for (cur
= list
, entries
= 0; cur
; cur
= cur
->fts_link
) {
630 if (cur
->fts_info
== FTS_ERR
|| cur
->fts_info
== FTS_NS
) {
632 cur
->fts_name
, strerror(cur
->fts_errno
));
633 cur
->fts_number
= NO_PRINT
;
638 * P is NULL if list is the argv list, to which different rules
642 /* Directories will be displayed later. */
643 if (cur
->fts_info
== FTS_D
&& !f_listdir
) {
644 cur
->fts_number
= NO_PRINT
;
648 /* Only display dot file if -a/-A set. */
649 if (cur
->fts_name
[0] == '.' && !f_listdot
) {
650 cur
->fts_number
= NO_PRINT
;
654 if (cur
->fts_namelen
> maxlen
)
655 maxlen
= cur
->fts_namelen
;
656 if (f_octal
|| f_octal_escape
) {
657 u_long t
= len_octal(cur
->fts_name
, cur
->fts_namelen
);
664 if (sp
->st_blocks
> maxblock
)
665 maxblock
= sp
->st_blocks
;
666 if (sp
->st_ino
> maxinode
)
667 maxinode
= sp
->st_ino
;
668 if (sp
->st_nlink
> maxnlink
)
669 maxnlink
= sp
->st_nlink
;
670 if (sp
->st_size
> maxsize
)
671 maxsize
= sp
->st_size
;
673 btotal
+= sp
->st_blocks
;
676 snprintf(nuser
, sizeof(nuser
),
678 snprintf(ngroup
, sizeof(ngroup
),
683 user
= user_from_uid(sp
->st_uid
, 0);
684 group
= group_from_gid(sp
->st_gid
, 0);
686 if ((ulen
= strlen(user
)) > maxuser
)
688 if ((glen
= strlen(group
)) > maxgroup
)
691 flags
= fflagstostr(sp
->st_flags
);
692 if (flags
!= NULL
&& *flags
== '\0') {
697 err(1, "flagstostr");
698 flen
= strlen(flags
);
699 if (flen
> (size_t)maxflags
)
704 #ifdef _ST_FSMID_PRESENT_
706 fsmid
= sp
->st_fsmid
;
716 if ((np
= malloc(sizeof(NAMES
) +
717 ulen
+ glen
+ flen
+ fsmidlen
+ 4)) == NULL
)
720 np
->user
= &np
->data
[0];
721 strcpy(np
->user
, user
);
722 np
->group
= &np
->data
[ulen
+ 1];
723 strcpy(np
->group
, group
);
725 if (S_ISCHR(sp
->st_mode
) ||
726 S_ISBLK(sp
->st_mode
))
730 np
->flags
= &np
->data
[ulen
+ glen
+ 2];
731 strcpy(np
->flags
, flags
);
734 #ifdef _ST_FSMID_PRESENT_
736 np
->fsmid
= np
->data
+ ulen
+ glen
+ flen
+ 3;
737 snprintf(np
->fsmid
, fsmidlen
+ 1,
738 "%016jx", (intmax_t)fsmid
);
741 cur
->fts_pointer
= np
;
748 * If there are no entries to display, we normally stop right
749 * here. However, we must continue if we have to display the
750 * total block count. In this case, we display the total only
751 * on the second (p != NULL) pass.
753 if (!entries
&& (!(f_longform
|| f_size
) || p
== NULL
))
762 snprintf(buf
, sizeof(buf
), "%ji", (intmax_t)maxblock
);
763 d
.s_block
= strlen(buf
);
764 d
.s_flags
= maxflags
;
765 d
.s_group
= maxgroup
;
766 snprintf(buf
, sizeof(buf
), "%ju", (uintmax_t)maxinode
);
767 d
.s_inode
= strlen(buf
);
768 snprintf(buf
, sizeof(buf
), "%u", maxnlink
);
769 d
.s_nlink
= strlen(buf
);
770 snprintf(buf
, sizeof(buf
), "%jd", (intmax_t)maxsize
);
771 d
.s_size
= strlen(buf
);
778 for (cur
= list
; cur
; cur
= cur
->fts_link
)
779 free(cur
->fts_pointer
);
783 * Ordering for mastercmp:
784 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
785 * as larger than directories. Within either group, use the sort function.
786 * All other levels use the sort function. Error entries remain unsorted.
789 mastercmp(const FTSENT
* const *a
, const FTSENT
* const *b
)
793 a_info
= (*a
)->fts_info
;
794 if (a_info
== FTS_ERR
)
796 b_info
= (*b
)->fts_info
;
797 if (b_info
== FTS_ERR
)
800 if (a_info
== FTS_NS
|| b_info
== FTS_NS
)
801 return (namecmp(*a
, *b
));
803 if (a_info
!= b_info
&&
804 (*a
)->fts_level
== FTS_ROOTLEVEL
&& !f_listdir
) {
810 return (sortfcn(*a
, *b
));