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 __RCSID("$FreeBSD: src/bin/ls/ls.c,v 1.66 2002/09/21 01:28:36 wollman Exp $");
51 #include <sys/types.h>
53 #include <sys/ioctl.h>
76 #endif /* __APPLE__ */
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 *, const FTSENT
* const *);
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_slash
; /* similar to f_type, but only for dirs */
117 int f_sortacross
; /* sort across rows, not down columns */
118 int f_statustime
; /* use time of last mode change */
119 int f_stream
; /* stream the output, separate with commas */
120 static int f_timesort
; /* sort by time vice name */
121 static int f_sizesort
; /* sort by size */
122 int f_type
; /* add type character for non-regular files */
123 static int f_whiteout
; /* show whiteout entries */
124 int f_lomac
; /* show LOMAC attributes */
126 int f_color
; /* add type in color for non-regular files */
128 char *ansi_bgcol
; /* ANSI sequence to set background colour */
129 char *ansi_fgcol
; /* ANSI sequence to set foreground colour */
130 char *ansi_coloff
; /* ANSI sequence to reset colours */
131 char *attrs_off
; /* ANSI sequence to turn off attributes */
132 char *enter_bold
; /* ANSI sequence to set color to bold mode */
138 main(int argc
, char *argv
[])
140 static char dot
[] = ".", *dotav
[] = {dot
, NULL
};
142 int ch
, fts_options
, notused
;
145 char termcapbuf
[1024]; /* termcap definition buffer */
146 char tcapbuf
[512]; /* capability buffer */
150 (void)setlocale(LC_ALL
, "");
152 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
153 if (isatty(STDOUT_FILENO
)) {
155 if ((p
= getenv("COLUMNS")) != NULL
&& *p
!= '\0')
157 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) != -1 &&
159 termwidth
= win
.ws_col
;
163 /* retrieve environment variable, in case of explicit -C */
164 p
= getenv("COLUMNS");
169 /* Root is -A automatically. */
173 fts_options
= FTS_PHYSICAL
;
174 while ((ch
= getopt(argc
, argv
, "1ABCFGHLPRSTWZabcdfghiklmnopqrstuvwx"))
178 * The -1, -C, -x and -l options all override each other so
179 * shell aliasing works right.
192 f_sortacross
= f_longform
= f_singlecol
= 0;
204 /* The -c and -u options override each other. */
218 fts_options
|= FTS_COMFOLLOW
;
221 setenv("CLICOLOR", "", 1);
224 fts_options
&= ~FTS_PHYSICAL
;
225 fts_options
|= FTS_LOGICAL
;
228 fts_options
&= ~FTS_COMFOLLOW
;
229 fts_options
&= ~FTS_LOGICAL
;
230 fts_options
|= FTS_PHYSICAL
;
236 fts_options
|= FTS_SEEDOT
;
241 /* The -d option turns off the -R option. */
249 case 'g': /* Compatibility with 4.3BSD. */
284 /* Darwin 1.4.1 compatibility */
300 /* Darwin 1.4.1 compatibility */
324 /* Enabling of colours is conditional on the environment. */
325 if (getenv("CLICOLOR") &&
326 (isatty(STDOUT_FILENO
) || getenv("CLICOLOR_FORCE")))
328 if (tgetent(termcapbuf
, getenv("TERM")) == 1) {
329 ansi_fgcol
= tgetstr("AF", &bp
);
330 ansi_bgcol
= tgetstr("AB", &bp
);
331 attrs_off
= tgetstr("me", &bp
);
332 enter_bold
= tgetstr("md", &bp
);
334 /* To switch colours off use 'op' if
335 * available, otherwise use 'oc', or
336 * don't do colours at all. */
337 ansi_coloff
= tgetstr("op", &bp
);
339 ansi_coloff
= tgetstr("oc", &bp
);
340 if (ansi_fgcol
&& ansi_bgcol
&& ansi_coloff
)
344 (void)fprintf(stderr
, "Color support not compiled in.\n");
350 * We can't put tabs and color sequences together:
351 * column number will be incremented incorrectly
352 * for "stty oxtabs" mode.
355 (void)signal(SIGINT
, colorquit
);
356 (void)signal(SIGQUIT
, colorquit
);
357 parsecolors(getenv("LSCOLORS"));
362 * If not -F, -i, -l, -s or -t options, don't require stat
363 * information, unless in color mode in which case we do
364 * need this to determine which colors to display.
366 if (!f_inode
&& !f_longform
&& !f_size
&& !f_timesort
&& !f_type
&& !f_sizesort
371 fts_options
|= FTS_NOSTAT
;
374 * If not -F, -d or -l options, follow any symbolic links listed on
377 if (!f_longform
&& !f_listdir
&& !f_type
)
378 fts_options
|= FTS_COMFOLLOW
;
381 * If -W, show whiteout entries
385 fts_options
|= FTS_WHITEOUT
;
388 /* If -l or -s, figure out block size. */
389 if (f_longform
|| f_size
) {
393 (void)getbsize(¬used
, &blocksize
);
397 /* Select a sort function. */
400 sortfcn
= revsizecmp
;
401 else if (!f_timesort
)
402 sortfcn
= revnamecmp
;
403 else if (f_accesstime
)
405 else if (f_statustime
)
406 sortfcn
= revstatcmp
;
407 else /* Use modification time. */
412 else if (!f_timesort
)
414 else if (f_accesstime
)
416 else if (f_statustime
)
418 else /* Use modification time. */
422 /* Select a print function. */
424 printfcn
= printscol
;
426 printfcn
= printlong
;
428 printfcn
= printstream
;
433 traverse(argc
, argv
, fts_options
);
435 traverse(1, dotav
, fts_options
);
439 static int output
; /* If anything output. */
442 * Traverse() walks the logical directory structure specified by the argv list
443 * in the order specified by the mastercmp() comparison function. During the
444 * traversal it passes linked lists of structures to display() which represent
445 * a superset (may be exact set) of the files to be displayed.
448 traverse(int argc
, char *argv
[], int options
)
455 fts_open(argv
, options
, f_nosort ? NULL
: mastercmp
)) == NULL
)
458 display(NULL
, fts_children(ftsp
, 0));
463 * If not recursing down this tree and don't need stat info, just get
466 ch_options
= !f_recursive
&& options
& FTS_NOSTAT ? FTS_NAMEONLY
: 0;
468 while ((p
= fts_read(ftsp
)) != NULL
)
469 switch (p
->fts_info
) {
471 warnx("%s: directory causes a cycle", p
->fts_name
);
475 warnx("%s: %s", p
->fts_name
, strerror(p
->fts_errno
));
479 if (p
->fts_level
!= FTS_ROOTLEVEL
&&
480 p
->fts_name
[0] == '.' && !f_listdot
)
484 * If already output something, put out a newline as
485 * a separator. If multiple arguments, precede each
486 * directory with its name.
489 (void)printf("\n%s:\n", p
->fts_path
);
491 (void)printf("%s:\n", p
->fts_path
);
494 chp
= fts_children(ftsp
, ch_options
);
497 if (!f_recursive
&& chp
!= NULL
)
498 (void)fts_set(ftsp
, p
, FTS_SKIP
);
508 * Display() takes a linked list of FTSENT structures and passes the list
509 * along with any other necessary information to the print function. P
510 * points to the parent directory of the display list.
513 display(FTSENT
*p
, FTSENT
*list
)
520 u_int64_t btotal
, maxblock
;
521 u_long lattrlen
, maxinode
, maxlen
, maxnlink
, maxlattr
;
522 int bcfile
, maxflags
;
525 size_t flen
, ulen
, glen
;
527 int entries
, needstats
;
528 const char *user
, *group
;
529 char *flags
, *lattr
= NULL
;
530 char buf
[STRBUF_SIZEOF(u_quad_t
) + 1];
531 char ngroup
[STRBUF_SIZEOF(uid_t
) + 1];
532 char nuser
[STRBUF_SIZEOF(gid_t
) + 1];
535 * If list is NULL there are two possibilities: that the parent
536 * directory p has no children, or that fts_children() returned an
537 * error. We ignore the error case since it will be replicated
538 * on the next call to fts_read() on the post-order visit to the
539 * directory p, and will be signaled in traverse().
544 needstats
= f_inode
|| f_longform
|| f_size
;
547 initmax
= getenv("LS_COLWIDTHS");
548 /* Fields match -lios order. New ones should be added at the end. */
549 maxlattr
= maxblock
= maxinode
= maxlen
= maxnlink
=
550 maxuser
= maxgroup
= maxflags
= maxsize
= 0;
551 if (initmax
!= NULL
&& *initmax
!= '\0') {
552 char *initmax2
, *jinitmax
;
555 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
556 jinitmax
= initmax2
= malloc(strlen(initmax
) * 2 + 2);
557 if (jinitmax
== NULL
)
560 strcpy(initmax2
, "0:"), initmax2
+= 2;
562 *initmax2
++ = *initmax
, *initmax2
= '\0';
563 for (initmax
++; *initmax
!= '\0'; initmax
++) {
564 if (initmax
[-1] == ':' && initmax
[0] == ':') {
566 *initmax2
++ = initmax
[0];
569 *initmax2
++ = initmax
[0];
573 if (initmax2
[-1] == ':')
574 strcpy(initmax2
, "0");
576 ninitmax
= sscanf(jinitmax
,
577 " %lu : %qu : %lu : %i : %i : %i : %qu : %lu : %lu ",
578 &maxinode
, &maxblock
, &maxnlink
, &maxuser
,
579 &maxgroup
, &maxflags
, &maxsize
, &maxlen
, &maxlattr
);
617 maxinode
= makenines(maxinode
);
618 maxblock
= makenines(maxblock
);
619 maxnlink
= makenines(maxnlink
);
620 maxsize
= makenines(maxsize
);
625 #endif /* __APPLE__ */
628 for (cur
= list
, entries
= 0; cur
; cur
= cur
->fts_link
) {
629 if (cur
->fts_info
== FTS_ERR
|| cur
->fts_info
== FTS_NS
) {
631 cur
->fts_name
, strerror(cur
->fts_errno
));
632 cur
->fts_number
= NO_PRINT
;
634 /* Don't count this as an error. This is for
635 * binary compatibility with Matlab installer script.
643 * P is NULL if list is the argv list, to which different rules
647 /* Directories will be displayed later. */
648 if (cur
->fts_info
== FTS_D
&& !f_listdir
) {
649 cur
->fts_number
= NO_PRINT
;
653 /* Only display dot file if -a/-A set. */
654 if (cur
->fts_name
[0] == '.' && !f_listdot
) {
655 cur
->fts_number
= NO_PRINT
;
659 if (cur
->fts_namelen
> maxlen
)
660 maxlen
= cur
->fts_namelen
;
661 if (f_octal
|| f_octal_escape
) {
662 u_long t
= len_octal(cur
->fts_name
, cur
->fts_namelen
);
669 if (sp
->st_blocks
> maxblock
)
670 maxblock
= sp
->st_blocks
;
671 if (sp
->st_ino
> maxinode
)
672 maxinode
= sp
->st_ino
;
673 if (sp
->st_nlink
> maxnlink
)
674 maxnlink
= sp
->st_nlink
;
675 if (sp
->st_size
> maxsize
)
676 maxsize
= sp
->st_size
;
678 btotal
+= sp
->st_blocks
;
681 (void)snprintf(nuser
, sizeof(nuser
),
683 (void)snprintf(ngroup
, sizeof(ngroup
),
688 user
= user_from_uid(sp
->st_uid
, 0);
689 group
= group_from_gid(sp
->st_gid
, 0);
691 if ((ulen
= strlen(user
)) > maxuser
)
693 if ((glen
= strlen(group
)) > maxgroup
)
696 flags
= fflagstostr(sp
->st_flags
);
697 if (flags
!= NULL
&& *flags
== '\0') {
702 err(1, "fflagstostr");
703 flen
= strlen(flags
);
704 if (flen
> (size_t)maxflags
)
711 lattr
= get_lattr(cur
);
712 lattrlen
= strlen(lattr
);
713 if (lattrlen
> maxlattr
)
716 #endif /* __APPLE__ */
719 if ((np
= malloc(sizeof(NAMES
) + lattrlen
+
720 ulen
+ glen
+ flen
+ 4)) == NULL
)
723 np
->user
= &np
->data
[0];
724 (void)strcpy(np
->user
, user
);
725 np
->group
= &np
->data
[ulen
+ 1];
726 (void)strcpy(np
->group
, group
);
728 if (S_ISCHR(sp
->st_mode
) ||
729 S_ISBLK(sp
->st_mode
))
733 np
->flags
= &np
->data
[ulen
+ glen
+ 2];
734 (void)strcpy(np
->flags
, flags
);
739 np
->lattr
= &np
->data
[ulen
+ glen
+ 2
740 + (f_flags ? flen
+ 1 : 0)];
741 (void)strcpy(np
->lattr
, lattr
);
744 #endif /* __APPLE__ */
745 cur
->fts_pointer
= np
;
760 (void)snprintf(buf
, sizeof(buf
), "%qu", (u_int64_t
)maxblock
);
761 d
.s_block
= strlen(buf
);
762 d
.s_flags
= maxflags
;
763 d
.s_lattr
= maxlattr
;
764 d
.s_group
= maxgroup
;
765 (void)snprintf(buf
, sizeof(buf
), "%lu", maxinode
);
766 d
.s_inode
= strlen(buf
);
767 (void)snprintf(buf
, sizeof(buf
), "%lu", maxnlink
);
768 d
.s_nlink
= strlen(buf
);
769 (void)snprintf(buf
, sizeof(buf
), "%qu", (u_int64_t
)maxsize
);
770 d
.s_size
= strlen(buf
);
777 for (cur
= list
; cur
; cur
= cur
->fts_link
)
778 free(cur
->fts_pointer
);
782 #endif /* __APPLE__ */
786 * Ordering for mastercmp:
787 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
788 * as larger than directories. Within either group, use the sort function.
789 * All other levels use the sort function. Error entries remain unsorted.
792 mastercmp(const FTSENT
* const *a
, const FTSENT
* const *b
)
796 a_info
= (*a
)->fts_info
;
797 if (a_info
== FTS_ERR
)
799 b_info
= (*b
)->fts_info
;
800 if (b_info
== FTS_ERR
)
803 if (a_info
== FTS_NS
|| b_info
== FTS_NS
)
804 return (namecmp(*a
, *b
));
806 if (a_info
!= b_info
&&
807 (*a
)->fts_level
== FTS_ROOTLEVEL
&& !f_listdir
) {
813 return (sortfcn(*a
, *b
));
817 * Makenines() returns (10**n)-1. This is useful for converting a width
818 * into a number that wide in decimal.
827 /* Use a loop instead of pow(), since all values of n are small. */
828 for (i
= 0; i
< n
; i
++)