]>
git.saurik.com Git - apple/file_cmds.git/blob - ls/ls.c
e07933392be74e12087450f8e03962c86e69a3f3
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 __used
static const char copyright
[] =
40 "@(#) Copyright (c) 1989, 1993, 1994\n\
41 The Regents of the University of California. All rights reserved.\n";
46 static char sccsid
[] = "@(#)ls.c 8.5 (Berkeley) 4/2/94";
49 #include <sys/cdefs.h>
50 __RCSID("$FreeBSD: src/bin/ls/ls.c,v 1.66 2002/09/21 01:28:36 wollman Exp $");
52 #include <sys/types.h>
54 #include <sys/ioctl.h>
74 #include <sys/xattr.h>
75 #include <sys/param.h>
76 #include <get_compat.h>
77 #include <sys/sysctl.h>
78 #include <System/sys/fsctl.h>
80 #define COMPAT_MODE(a,b) (1)
81 #endif /* __APPLE__ */
86 * Upward approximation of the maximum number of characters needed to
87 * represent a value of integral type t as a string, excluding the
88 * NUL terminator, with provision for a sign.
90 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
92 #define IS_DATALESS(sp) (f_dataless && (sp) && ((sp)->st_flags & SF_DATALESS))
94 static void display(FTSENT
*, FTSENT
*);
95 static u_quad_t
makenines(u_quad_t
);
96 static int mastercmp(const FTSENT
**, const FTSENT
**);
97 static void traverse(int, char **, int);
99 static void (*printfcn
)(DISPLAY
*);
100 static int (*sortfcn
)(const FTSENT
*, const FTSENT
*);
102 long blocksize
; /* block size units */
103 int termwidth
= 80; /* default terminal width */
106 int f_accesstime
; /* use time of last access */
107 int f_birthtime
; /* use time of file birth */
108 int f_flags
; /* show flags associated with a file */
109 int f_humanval
; /* show human-readable file sizes */
110 int f_inode
; /* print inode */
111 static int f_kblocks
; /* print size in kilobytes */
112 static int f_listdir
; /* list actual directory, not contents */
113 static int f_listdot
; /* list files beginning with . */
114 int f_longform
; /* long listing format */
115 int f_nonprint
; /* show unprintables as ? */
116 static int f_nosort
; /* don't sort output */
117 int f_notabs
; /* don't use tab-separated multi-col output */
118 int f_numericonly
; /* don't convert uid/gid to name */
119 int f_octal
; /* show unprintables as \xxx */
120 int f_octal_escape
; /* like f_octal but use C escapes if possible */
121 static int f_recursive
; /* ls subdirectories also */
122 static int f_reversesort
; /* reverse whatever sort is used */
123 int f_sectime
; /* print the real time for all files */
124 static int f_singlecol
; /* use single column output */
125 int f_size
; /* list size in short listing */
126 int f_slash
; /* similar to f_type, but only for dirs */
127 int f_sortacross
; /* sort across rows, not down columns */
128 int f_statustime
; /* use time of last mode change */
129 int f_stream
; /* stream the output, separate with commas */
130 static int f_timesort
; /* sort by time vice name */
131 static int f_sizesort
; /* sort by size */
132 int f_type
; /* add type character for non-regular files */
133 static int f_whiteout
; /* show whiteout entries */
134 int f_acl
; /* show ACLs in long listing */
135 int f_xattr
; /* show extended attributes in long listing */
136 int f_group
; /* show group */
137 int f_owner
; /* show owner */
138 int f_dataless
; /* distinguish dataless files in long listing,
139 and don't materialize dataless directories. */
141 int f_color
; /* add type in color for non-regular files */
143 char *ansi_bgcol
; /* ANSI sequence to set background colour */
144 char *ansi_fgcol
; /* ANSI sequence to set foreground colour */
145 char *ansi_coloff
; /* ANSI sequence to reset colours */
146 char *attrs_off
; /* ANSI sequence to turn off attributes */
147 char *enter_bold
; /* ANSI sequence to set color to bold mode */
153 main(int argc
, char *argv
[])
155 static char dot
[] = ".", *dotav
[] = {dot
, NULL
};
157 int ch
, fts_options
, notused
;
160 char termcapbuf
[1024]; /* termcap definition buffer */
161 char tcapbuf
[512]; /* capability buffer */
167 (void)setlocale(LC_ALL
, "");
169 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
170 if (isatty(STDOUT_FILENO
)) {
172 if ((p
= getenv("COLUMNS")) != NULL
&& *p
!= '\0')
174 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) != -1 &&
176 termwidth
= win
.ws_col
;
180 /* retrieve environment variable, in case of explicit -C */
181 p
= getenv("COLUMNS");
186 /* Root is -A automatically. */
190 fts_options
= FTS_PHYSICAL
;
191 while ((ch
= getopt(argc
, argv
, "1@ABCFGHLOPRSTUWabcdefghiklmnopqrstuvwx%"))
195 * The -1, -C, -x and -l options all override each other so
196 * shell aliasing works right.
209 f_sortacross
= f_longform
= f_singlecol
= 0;
221 /* The -c and -u options override each other. */
224 f_accesstime
= f_birthtime
= 0;
228 f_statustime
= f_birthtime
= 0;
232 f_statustime
= f_accesstime
= 0;
239 if (COMPAT_MODE("bin/ls", "Unix2003")) {
240 fts_options
&= ~FTS_LOGICAL
;
241 fts_options
|= FTS_PHYSICAL
;
242 fts_options
|= FTS_COMFOLLOWDIR
;
244 fts_options
|= FTS_COMFOLLOW
;
247 setenv("CLICOLOR", "", 1);
250 fts_options
&= ~FTS_PHYSICAL
;
251 fts_options
|= FTS_LOGICAL
;
252 if (COMPAT_MODE("bin/ls", "Unix2003")) {
253 fts_options
&= ~(FTS_COMFOLLOW
|FTS_COMFOLLOWDIR
);
257 fts_options
&= ~(FTS_COMFOLLOW
|FTS_COMFOLLOWDIR
);
258 fts_options
&= ~FTS_LOGICAL
;
259 fts_options
|= FTS_PHYSICAL
;
265 fts_options
|= FTS_SEEDOT
;
270 /* The -d option turns off the -R option. */
277 if (COMPAT_MODE("bin/ls", "Unix2003")) {
278 fts_options
|= FTS_SEEDOT
;
282 case 'g': /* Compatibility with Unix03 */
283 if (COMPAT_MODE("bin/ls", "Unix2003")) {
306 if (COMPAT_MODE("bin/ls", "Unix2003")) {
313 if (COMPAT_MODE("bin/ls", "Unix2003")) {
335 /* Darwin 1.4.1 compatibility */
351 /* Darwin 1.4.1 compatibility */
384 /* Enabling of colours is conditional on the environment. */
385 if (getenv("CLICOLOR") &&
386 (isatty(STDOUT_FILENO
) || getenv("CLICOLOR_FORCE")))
388 if (tgetent(termcapbuf
, getenv("TERM")) == 1) {
389 ansi_fgcol
= tgetstr("AF", &bp
);
390 ansi_bgcol
= tgetstr("AB", &bp
);
391 attrs_off
= tgetstr("me", &bp
);
392 enter_bold
= tgetstr("md", &bp
);
394 /* To switch colours off use 'op' if
395 * available, otherwise use 'oc', or
396 * don't do colours at all. */
397 ansi_coloff
= tgetstr("op", &bp
);
399 ansi_coloff
= tgetstr("oc", &bp
);
400 if (ansi_fgcol
&& ansi_bgcol
&& ansi_coloff
)
404 (void)fprintf(stderr
, "Color support not compiled in.\n");
410 * We can't put tabs and color sequences together:
411 * column number will be incremented incorrectly
412 * for "stty oxtabs" mode.
415 (void)signal(SIGINT
, colorquit
);
416 (void)signal(SIGQUIT
, colorquit
);
417 parsecolors(getenv("LSCOLORS"));
422 * If not -F, -i, -l, -s, -t or -% options, don't require stat
423 * information, unless in color mode in which case we do
424 * need this to determine which colors to display.
426 if (!f_inode
&& !f_longform
&& !f_size
&& !f_timesort
&& !f_type
&& !f_sizesort
&& !f_dataless
431 fts_options
|= FTS_NOSTAT
;
434 * If not -F, -d or -l options, follow any symbolic links listed on
437 if (!f_longform
&& !f_listdir
&& !f_type
&& !f_inode
)
438 fts_options
|= FTS_COMFOLLOW
;
441 * If -W, show whiteout entries
445 fts_options
|= FTS_WHITEOUT
;
448 /* If -l or -s, figure out block size. */
449 if (f_longform
|| f_size
) {
453 (void)getbsize(¬used
, &blocksize
);
457 /* Select a sort function. */
460 sortfcn
= revsizecmp
;
461 else if (!f_timesort
)
462 sortfcn
= revnamecmp
;
463 else if (f_accesstime
)
465 else if (f_statustime
)
466 sortfcn
= revstatcmp
;
467 else if (f_birthtime
)
468 sortfcn
= revbirthcmp
;
469 else /* Use modification time. */
474 else if (!f_timesort
)
476 else if (f_accesstime
)
478 else if (f_statustime
)
480 else if (f_birthtime
)
482 else /* Use modification time. */
486 /* Select a print function. */
488 printfcn
= printscol
;
490 printfcn
= printlong
;
492 printfcn
= printstream
;
498 // don't materialize dataless directories from the cloud
499 // (particularly usefull when listing recursively)
501 if (sysctlbyname("vfs.nspace.prevent_materialization", NULL
, NULL
, &state
, sizeof(state
)) < 0) {
502 err(1, "prevent_materialization");
505 #endif /* __APPLE__ */
508 traverse(argc
, argv
, fts_options
);
510 traverse(1, dotav
, fts_options
);
514 static int output
; /* If anything output. */
517 * Traverse() walks the logical directory structure specified by the argv list
518 * in the order specified by the mastercmp() comparison function. During the
519 * traversal it passes linked lists of structures to display() which represent
520 * a superset (may be exact set) of the files to be displayed.
523 traverse(int argc
, char *argv
[], int options
)
527 int ch_options
, error
;
530 fts_open(argv
, options
, f_nosort
? NULL
: mastercmp
)) == NULL
)
533 display(NULL
, fts_children(ftsp
, 0));
540 * If not recursing down this tree and don't need stat info, just get
543 ch_options
= !f_recursive
&& options
& FTS_NOSTAT
? FTS_NAMEONLY
: 0;
545 while ((p
= fts_read(ftsp
)) != NULL
)
546 switch (p
->fts_info
) {
548 warnx("%s: directory causes a cycle", p
->fts_name
);
549 if (COMPAT_MODE("bin/ls", "Unix2003")) {
555 warnx("%s: %s", p
->fts_name
, strerror(p
->fts_errno
));
559 if (p
->fts_level
!= FTS_ROOTLEVEL
&&
560 p
->fts_name
[0] == '.' && !f_listdot
) {
561 fts_set(ftsp
, p
, FTS_SKIP
);
565 if (IS_DATALESS(p
->fts_statp
)) {
566 fts_set(ftsp
, p
, FTS_SKIP
);
571 * If already output something, put out a newline as
572 * a separator. If multiple arguments, precede each
573 * directory with its name.
576 (void)printf("\n%s:\n", p
->fts_path
);
578 (void)printf("%s:\n", p
->fts_path
);
581 chp
= fts_children(ftsp
, ch_options
);
582 if (COMPAT_MODE("bin/ls", "Unix2003") && ((options
& FTS_LOGICAL
)!=0)) {
584 for (curr
= chp
; curr
; curr
= curr
->fts_link
) {
585 if (curr
->fts_info
== FTS_SLNONE
)
586 curr
->fts_number
= NO_PRINT
;
591 if (!f_recursive
&& chp
!= NULL
)
592 (void)fts_set(ftsp
, p
, FTS_SKIP
);
594 case FTS_SLNONE
: /* Same as default unless Unix conformance */
595 if (COMPAT_MODE("bin/ls", "Unix2003")) {
596 if ((options
& FTS_LOGICAL
)!=0) { /* -L was specified */
597 warnx("%s: %s", p
->fts_name
, strerror(p
->fts_errno
?: ENOENT
));
614 * Display() takes a linked list of FTSENT structures and passes the list
615 * along with any other necessary information to the print function. P
616 * points to the parent directory of the display list.
619 display(FTSENT
*p
, FTSENT
*list
)
626 u_int64_t btotal
, maxblock
;
627 u_long lattrlen
, maxlen
, maxnlink
, maxlattr
;
629 int bcfile
, maxflags
;
632 size_t flen
, ulen
, glen
;
634 int entries
, needstats
;
635 const char *user
, *group
;
636 char *flags
, *lattr
= NULL
;
637 char buf
[STRBUF_SIZEOF(u_quad_t
) + 1];
638 char ngroup
[STRBUF_SIZEOF(uid_t
) + 1];
639 char nuser
[STRBUF_SIZEOF(gid_t
) + 1];
644 char path
[MAXPATHLEN
+1];
647 * If list is NULL there are two possibilities: that the parent
648 * directory p has no children, or that fts_children() returned an
649 * error. We ignore the error case since it will be replicated
650 * on the next call to fts_read() on the post-order visit to the
651 * directory p, and will be signaled in traverse().
656 needstats
= f_inode
|| f_longform
|| f_size
;
658 initmax
= getenv("LS_COLWIDTHS");
659 /* Fields match -lios order. New ones should be added at the end. */
660 maxlattr
= maxblock
= maxinode
= maxlen
= maxnlink
=
661 maxuser
= maxgroup
= maxflags
= maxsize
= 0;
662 if (initmax
!= NULL
&& *initmax
!= '\0') {
663 char *initmax2
, *jinitmax
;
666 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
667 jinitmax
= initmax2
= malloc(strlen(initmax
) * 2 + 2);
668 if (jinitmax
== NULL
)
671 strcpy(initmax2
, "0:"), initmax2
+= 2;
673 *initmax2
++ = *initmax
, *initmax2
= '\0';
674 for (initmax
++; *initmax
!= '\0'; initmax
++) {
675 if (initmax
[-1] == ':' && initmax
[0] == ':') {
677 *initmax2
++ = initmax
[0];
680 *initmax2
++ = initmax
[0];
684 if (initmax2
[-1] == ':')
685 strcpy(initmax2
, "0");
687 ninitmax
= sscanf(jinitmax
,
688 #if _DARWIN_FEATURE_64_BIT_INODE
689 " %llu : %qu : %lu : %i : %i : %i : %qu : %lu : %lu ",
691 " %lu : %qu : %lu : %i : %i : %i : %qu : %lu : %lu ",
693 &maxinode
, &maxblock
, &maxnlink
, &maxuser
,
694 &maxgroup
, &maxflags
, &maxsize
, &maxlen
, &maxlattr
);
732 maxinode
= makenines(maxinode
);
733 maxblock
= makenines(maxblock
);
734 maxnlink
= makenines(maxnlink
);
735 maxsize
= makenines(maxsize
);
739 for (cur
= list
, entries
= 0; cur
; cur
= cur
->fts_link
) {
740 if (cur
->fts_info
== FTS_ERR
|| cur
->fts_info
== FTS_NS
) {
742 cur
->fts_name
, strerror(cur
->fts_errno
));
743 cur
->fts_number
= NO_PRINT
;
748 * P is NULL if list is the argv list, to which different rules
752 /* Directories will be displayed later. */
753 if (cur
->fts_info
== FTS_D
&& !f_listdir
) {
754 cur
->fts_number
= NO_PRINT
;
758 /* Only display dot file if -a/-A set. */
759 if (cur
->fts_name
[0] == '.' && !f_listdot
) {
760 cur
->fts_number
= NO_PRINT
;
764 if (cur
->fts_namelen
> maxlen
)
765 maxlen
= cur
->fts_namelen
;
766 if (f_octal
|| f_octal_escape
) {
767 u_long t
= len_octal(cur
->fts_name
, cur
->fts_namelen
);
774 if (sp
->st_blocks
> maxblock
)
775 maxblock
= sp
->st_blocks
;
776 if (sp
->st_ino
> maxinode
)
777 maxinode
= sp
->st_ino
;
778 if (sp
->st_nlink
> maxnlink
)
779 maxnlink
= sp
->st_nlink
;
780 if (sp
->st_size
> maxsize
)
781 maxsize
= sp
->st_size
;
783 btotal
+= sp
->st_blocks
;
786 (void)snprintf(nuser
, sizeof(nuser
),
788 (void)snprintf(ngroup
, sizeof(ngroup
),
793 user
= user_from_uid(sp
->st_uid
, 0);
794 group
= group_from_gid(sp
->st_gid
, 0);
796 if ((ulen
= strlen(user
)) > maxuser
)
798 if ((glen
= strlen(group
)) > maxgroup
)
801 flags
= fflagstostr(sp
->st_flags
);
802 if (flags
!= NULL
&& *flags
== '\0') {
807 err(1, "fflagstostr");
808 flen
= strlen(flags
);
809 if (flen
> (size_t)maxflags
)
816 if ((np
= calloc(1, sizeof(NAMES
) + lattrlen
+
817 ulen
+ glen
+ flen
+ 4)) == NULL
)
820 np
->user
= &np
->data
[0];
821 (void)strcpy(np
->user
, user
);
822 np
->group
= &np
->data
[ulen
+ 1];
823 (void)strcpy(np
->group
, group
);
825 if (cur
->fts_level
== FTS_ROOTLEVEL
) {
826 filename
= cur
->fts_name
;
828 snprintf(path
, sizeof(path
), "%s/%s", cur
->fts_parent
->fts_accpath
, cur
->fts_name
);
831 xattr_size
= listxattr(filename
, NULL
, 0, XATTR_NOFOLLOW
);
832 if (xattr_size
< 0) {
835 if ((xattr_size
> 0) && f_xattr
) {
837 np
->xattr_names
= malloc(xattr_size
);
838 listxattr(filename
, np
->xattr_names
, xattr_size
, XATTR_NOFOLLOW
);
839 for (char *name
= np
->xattr_names
; name
< np
->xattr_names
+ xattr_size
;
840 name
+= strlen(name
)+1) {
841 np
->xattr_sizes
= reallocf(np
->xattr_sizes
, (np
->xattr_count
+1) * sizeof(np
->xattr_sizes
[0]));
842 np
->xattr_sizes
[np
->xattr_count
] = getxattr(filename
, name
, 0, 0, 0, XATTR_NOFOLLOW
);
846 /* symlinks can not have ACLs */
847 np
->acl
= acl_get_link_np(filename
, ACL_TYPE_EXTENDED
);
849 if (acl_get_entry(np
->acl
, ACL_FIRST_ENTRY
, &dummy
) == -1) {
854 if (xattr_size
> 0) {
855 np
->mode_suffix
= '@';
856 } else if (np
->acl
) {
857 np
->mode_suffix
= '+';
859 np
->mode_suffix
= ' ';
861 if (IS_DATALESS(sp
)) {
862 np
->mode_suffix
= '%';
869 if (S_ISCHR(sp
->st_mode
) ||
870 S_ISBLK(sp
->st_mode
))
874 np
->flags
= &np
->data
[ulen
+ glen
+ 2];
875 (void)strcpy(np
->flags
, flags
);
878 cur
->fts_pointer
= np
;
893 (void)snprintf(buf
, sizeof(buf
), "%qu", (u_int64_t
)maxblock
);
894 d
.s_block
= strlen(buf
);
895 d
.s_flags
= maxflags
;
896 d
.s_lattr
= maxlattr
;
897 d
.s_group
= maxgroup
;
898 #if _DARWIN_FEATURE_64_BIT_INODE
899 (void)snprintf(buf
, sizeof(buf
), "%llu", maxinode
);
901 (void)snprintf(buf
, sizeof(buf
), "%lu", maxinode
);
903 d
.s_inode
= strlen(buf
);
904 (void)snprintf(buf
, sizeof(buf
), "%lu", maxnlink
);
905 d
.s_nlink
= strlen(buf
);
906 (void)snprintf(buf
, sizeof(buf
), "%qu", (u_int64_t
)maxsize
);
907 d
.s_size
= strlen(buf
);
914 for (cur
= list
; cur
; cur
= cur
->fts_link
) {
915 np
= cur
->fts_pointer
;
920 free(np
->xattr_names
);
921 free(np
->xattr_sizes
);
923 cur
->fts_pointer
= NULL
;
930 * Ordering for mastercmp:
931 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
932 * as larger than directories. Within either group, use the sort function.
933 * All other levels use the sort function. Error entries remain unsorted.
936 mastercmp(const FTSENT
**a
, const FTSENT
**b
)
940 a_info
= (*a
)->fts_info
;
941 if (a_info
== FTS_ERR
)
943 b_info
= (*b
)->fts_info
;
944 if (b_info
== FTS_ERR
)
947 if (a_info
== FTS_NS
|| b_info
== FTS_NS
)
948 return (namecmp(*a
, *b
));
950 if (a_info
!= b_info
&&
951 (*a
)->fts_level
== FTS_ROOTLEVEL
&& !f_listdir
) {
957 return (sortfcn(*a
, *b
));
961 * Makenines() returns (10**n)-1. This is useful for converting a width
962 * into a number that wide in decimal.
965 makenines(u_quad_t n
)
971 /* Use a loop instead of pow(), since all values of n are small. */
972 for (i
= 0; i
< n
; i
++)