]>
git.cameronkatri.com Git - apple_cmds.git/blob - file_cmds/ls/ls.c
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>
79 #define COMPAT_MODE(a,b) (1)
80 #endif /* __APPLE__ */
85 * Upward approximation of the maximum number of characters needed to
86 * represent a value of integral type t as a string, excluding the
87 * NUL terminator, with provision for a sign.
89 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
91 #define IS_DATALESS(sp) (f_dataless && (sp) && ((sp)->st_flags & SF_DATALESS))
93 static void display(FTSENT
*, FTSENT
*);
94 static u_quad_t
makenines(u_quad_t
);
95 static int mastercmp(const FTSENT
**, const FTSENT
**);
96 static void traverse(int, char **, int);
98 static void (*printfcn
)(DISPLAY
*);
99 static int (*sortfcn
)(const FTSENT
*, const FTSENT
*);
101 long blocksize
; /* block size units */
102 int termwidth
= 80; /* default terminal width */
105 int f_accesstime
; /* use time of last access */
106 int f_birthtime
; /* use time of file birth */
107 int f_flags
; /* show flags associated with a file */
108 int f_humanval
; /* show human-readable file sizes */
109 int f_inode
; /* print inode */
110 static int f_kblocks
; /* print size in kilobytes */
111 static int f_listdir
; /* list actual directory, not contents */
112 static int f_listdot
; /* list files beginning with . */
113 int f_longform
; /* long listing format */
114 int f_nonprint
; /* show unprintables as ? */
115 static int f_nosort
; /* don't sort output */
116 int f_notabs
; /* don't use tab-separated multi-col output */
117 int f_numericonly
; /* don't convert uid/gid to name */
118 int f_octal
; /* show unprintables as \xxx */
119 int f_octal_escape
; /* like f_octal but use C escapes if possible */
120 static int f_recursive
; /* ls subdirectories also */
121 static int f_reversesort
; /* reverse whatever sort is used */
122 int f_sectime
; /* print the real time for all files */
123 static int f_singlecol
; /* use single column output */
124 int f_size
; /* list size in short listing */
125 int f_slash
; /* similar to f_type, but only for dirs */
126 int f_sortacross
; /* sort across rows, not down columns */
127 int f_statustime
; /* use time of last mode change */
128 int f_stream
; /* stream the output, separate with commas */
129 static int f_timesort
; /* sort by time vice name */
130 static int f_sizesort
; /* sort by size */
131 int f_type
; /* add type character for non-regular files */
132 static int f_whiteout
; /* show whiteout entries */
133 int f_acl
; /* show ACLs in long listing */
134 int f_xattr
; /* show extended attributes in long listing */
135 int f_group
; /* show group */
136 int f_owner
; /* show owner */
137 int f_dataless
; /* distinguish dataless files in long listing,
138 and don't materialize dataless directories. */
140 int f_color
; /* add type in color for non-regular files */
142 char *ansi_bgcol
; /* ANSI sequence to set background colour */
143 char *ansi_fgcol
; /* ANSI sequence to set foreground colour */
144 char *ansi_coloff
; /* ANSI sequence to reset colours */
145 char *attrs_off
; /* ANSI sequence to turn off attributes */
146 char *enter_bold
; /* ANSI sequence to set color to bold mode */
152 main(int argc
, char *argv
[])
154 static char dot
[] = ".", *dotav
[] = {dot
, NULL
};
156 int ch
, fts_options
, notused
;
159 char termcapbuf
[1024]; /* termcap definition buffer */
160 char tcapbuf
[512]; /* capability buffer */
166 (void)setlocale(LC_ALL
, "");
168 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
169 if (isatty(STDOUT_FILENO
)) {
171 if ((p
= getenv("COLUMNS")) != NULL
&& *p
!= '\0')
173 else if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &win
) != -1 &&
175 termwidth
= win
.ws_col
;
179 /* retrieve environment variable, in case of explicit -C */
180 p
= getenv("COLUMNS");
185 /* Root is -A automatically. */
189 fts_options
= FTS_PHYSICAL
;
190 while ((ch
= getopt(argc
, argv
, "1@ABCFGHLOPRSTUWabcdefghiklmnopqrstuvwx%"))
194 * The -1, -C, -x and -l options all override each other so
195 * shell aliasing works right.
208 f_sortacross
= f_longform
= f_singlecol
= 0;
220 /* The -c and -u options override each other. */
223 f_accesstime
= f_birthtime
= 0;
227 f_statustime
= f_birthtime
= 0;
231 f_statustime
= f_accesstime
= 0;
238 if (COMPAT_MODE("bin/ls", "Unix2003")) {
239 fts_options
&= ~FTS_LOGICAL
;
240 fts_options
|= FTS_PHYSICAL
;
241 fts_options
|= FTS_COMFOLLOWDIR
;
243 fts_options
|= FTS_COMFOLLOW
;
246 setenv("CLICOLOR", "", 1);
249 fts_options
&= ~FTS_PHYSICAL
;
250 fts_options
|= FTS_LOGICAL
;
251 if (COMPAT_MODE("bin/ls", "Unix2003")) {
252 fts_options
&= ~(FTS_COMFOLLOW
|FTS_COMFOLLOWDIR
);
256 fts_options
&= ~(FTS_COMFOLLOW
|FTS_COMFOLLOWDIR
);
257 fts_options
&= ~FTS_LOGICAL
;
258 fts_options
|= FTS_PHYSICAL
;
264 fts_options
|= FTS_SEEDOT
;
269 /* The -d option turns off the -R option. */
276 if (COMPAT_MODE("bin/ls", "Unix2003")) {
277 fts_options
|= FTS_SEEDOT
;
281 case 'g': /* Compatibility with Unix03 */
282 if (COMPAT_MODE("bin/ls", "Unix2003")) {
305 if (COMPAT_MODE("bin/ls", "Unix2003")) {
312 if (COMPAT_MODE("bin/ls", "Unix2003")) {
334 /* Darwin 1.4.1 compatibility */
350 /* Darwin 1.4.1 compatibility */
383 /* Enabling of colours is conditional on the environment. */
384 if (getenv("CLICOLOR") &&
385 (isatty(STDOUT_FILENO
) || getenv("CLICOLOR_FORCE")))
387 if (tgetent(termcapbuf
, getenv("TERM")) == 1) {
388 ansi_fgcol
= tgetstr("AF", &bp
);
389 ansi_bgcol
= tgetstr("AB", &bp
);
390 attrs_off
= tgetstr("me", &bp
);
391 enter_bold
= tgetstr("md", &bp
);
393 /* To switch colours off use 'op' if
394 * available, otherwise use 'oc', or
395 * don't do colours at all. */
396 ansi_coloff
= tgetstr("op", &bp
);
398 ansi_coloff
= tgetstr("oc", &bp
);
399 if (ansi_fgcol
&& ansi_bgcol
&& ansi_coloff
)
403 (void)fprintf(stderr
, "Color support not compiled in.\n");
409 * We can't put tabs and color sequences together:
410 * column number will be incremented incorrectly
411 * for "stty oxtabs" mode.
414 (void)signal(SIGINT
, colorquit
);
415 (void)signal(SIGQUIT
, colorquit
);
416 parsecolors(getenv("LSCOLORS"));
421 * If not -F, -i, -l, -s, -t or -% options, don't require stat
422 * information, unless in color mode in which case we do
423 * need this to determine which colors to display.
425 if (!f_inode
&& !f_longform
&& !f_size
&& !f_timesort
&& !f_type
&& !f_sizesort
&& !f_dataless
430 fts_options
|= FTS_NOSTAT
;
433 * If not -F, -d or -l options, follow any symbolic links listed on
436 if (!f_longform
&& !f_listdir
&& !f_type
&& !f_inode
)
437 fts_options
|= FTS_COMFOLLOW
;
440 * If -W, show whiteout entries
444 fts_options
|= FTS_WHITEOUT
;
447 /* If -l or -s, figure out block size. */
448 if (f_longform
|| f_size
) {
452 (void)getbsize(¬used
, &blocksize
);
456 /* Select a sort function. */
459 sortfcn
= revsizecmp
;
460 else if (!f_timesort
)
461 sortfcn
= revnamecmp
;
462 else if (f_accesstime
)
464 else if (f_statustime
)
465 sortfcn
= revstatcmp
;
466 else if (f_birthtime
)
467 sortfcn
= revbirthcmp
;
468 else /* Use modification time. */
473 else if (!f_timesort
)
475 else if (f_accesstime
)
477 else if (f_statustime
)
479 else if (f_birthtime
)
481 else /* Use modification time. */
485 /* Select a print function. */
487 printfcn
= printscol
;
489 printfcn
= printlong
;
491 printfcn
= printstream
;
497 // don't materialize dataless directories from the cloud
498 // (particularly usefull when listing recursively)
500 if (sysctlbyname("vfs.nspace.prevent_materialization", NULL
, NULL
, &state
, sizeof(state
)) < 0) {
501 err(1, "prevent_materialization");
504 #endif /* __APPLE__ */
507 traverse(argc
, argv
, fts_options
);
509 traverse(1, dotav
, fts_options
);
513 static int output
; /* If anything output. */
516 * Traverse() walks the logical directory structure specified by the argv list
517 * in the order specified by the mastercmp() comparison function. During the
518 * traversal it passes linked lists of structures to display() which represent
519 * a superset (may be exact set) of the files to be displayed.
522 traverse(int argc
, char *argv
[], int options
)
526 int ch_options
, error
;
529 fts_open(argv
, options
, f_nosort
? NULL
: mastercmp
)) == NULL
)
532 display(NULL
, fts_children(ftsp
, 0));
539 * If not recursing down this tree and don't need stat info, just get
542 ch_options
= !f_recursive
&& options
& FTS_NOSTAT
? FTS_NAMEONLY
: 0;
544 while ((p
= fts_read(ftsp
)) != NULL
)
545 switch (p
->fts_info
) {
547 warnx("%s: directory causes a cycle", p
->fts_name
);
548 if (COMPAT_MODE("bin/ls", "Unix2003")) {
554 warnx("%s: %s", p
->fts_name
, strerror(p
->fts_errno
));
558 if (p
->fts_level
!= FTS_ROOTLEVEL
&&
559 p
->fts_name
[0] == '.' && !f_listdot
) {
560 fts_set(ftsp
, p
, FTS_SKIP
);
564 if (IS_DATALESS(p
->fts_statp
)) {
565 fts_set(ftsp
, p
, FTS_SKIP
);
570 * If already output something, put out a newline as
571 * a separator. If multiple arguments, precede each
572 * directory with its name.
575 (void)printf("\n%s:\n", p
->fts_path
);
577 (void)printf("%s:\n", p
->fts_path
);
580 chp
= fts_children(ftsp
, ch_options
);
581 if (COMPAT_MODE("bin/ls", "Unix2003") && ((options
& FTS_LOGICAL
)!=0)) {
583 for (curr
= chp
; curr
; curr
= curr
->fts_link
) {
584 if (curr
->fts_info
== FTS_SLNONE
)
585 curr
->fts_number
= NO_PRINT
;
590 if (!f_recursive
&& chp
!= NULL
)
591 (void)fts_set(ftsp
, p
, FTS_SKIP
);
593 case FTS_SLNONE
: /* Same as default unless Unix conformance */
594 if (COMPAT_MODE("bin/ls", "Unix2003")) {
595 if ((options
& FTS_LOGICAL
)!=0) { /* -L was specified */
596 warnx("%s: %s", p
->fts_name
, strerror(p
->fts_errno
?: ENOENT
));
613 * Display() takes a linked list of FTSENT structures and passes the list
614 * along with any other necessary information to the print function. P
615 * points to the parent directory of the display list.
618 display(FTSENT
*p
, FTSENT
*list
)
625 u_int64_t btotal
, maxblock
;
626 u_long lattrlen
, maxlen
, maxnlink
, maxlattr
;
628 int bcfile
, maxflags
;
631 size_t flen
, ulen
, glen
;
633 int entries
, needstats
;
634 const char *user
, *group
;
635 char *flags
, *lattr
= NULL
;
636 char buf
[STRBUF_SIZEOF(u_quad_t
) + 1];
637 char ngroup
[STRBUF_SIZEOF(uid_t
) + 1];
638 char nuser
[STRBUF_SIZEOF(gid_t
) + 1];
643 char path
[MAXPATHLEN
+1];
646 * If list is NULL there are two possibilities: that the parent
647 * directory p has no children, or that fts_children() returned an
648 * error. We ignore the error case since it will be replicated
649 * on the next call to fts_read() on the post-order visit to the
650 * directory p, and will be signaled in traverse().
655 needstats
= f_inode
|| f_longform
|| f_size
;
657 initmax
= getenv("LS_COLWIDTHS");
658 /* Fields match -lios order. New ones should be added at the end. */
659 maxlattr
= maxblock
= maxinode
= maxlen
= maxnlink
=
660 maxuser
= maxgroup
= maxflags
= maxsize
= 0;
661 if (initmax
!= NULL
&& *initmax
!= '\0') {
662 char *initmax2
, *jinitmax
;
665 /* Fill-in "::" as "0:0:0" for the sake of scanf. */
666 jinitmax
= initmax2
= malloc(strlen(initmax
) * 2 + 2);
667 if (jinitmax
== NULL
)
670 strcpy(initmax2
, "0:"), initmax2
+= 2;
672 *initmax2
++ = *initmax
, *initmax2
= '\0';
673 for (initmax
++; *initmax
!= '\0'; initmax
++) {
674 if (initmax
[-1] == ':' && initmax
[0] == ':') {
676 *initmax2
++ = initmax
[0];
679 *initmax2
++ = initmax
[0];
683 if (initmax2
[-1] == ':')
684 strcpy(initmax2
, "0");
686 ninitmax
= sscanf(jinitmax
,
687 #if _DARWIN_FEATURE_64_BIT_INODE
688 " %llu : %qu : %lu : %i : %i : %i : %qu : %lu : %lu ",
690 " %lu : %qu : %lu : %i : %i : %i : %qu : %lu : %lu ",
692 &maxinode
, &maxblock
, &maxnlink
, &maxuser
,
693 &maxgroup
, &maxflags
, &maxsize
, &maxlen
, &maxlattr
);
731 maxinode
= makenines(maxinode
);
732 maxblock
= makenines(maxblock
);
733 maxnlink
= makenines(maxnlink
);
734 maxsize
= makenines(maxsize
);
738 for (cur
= list
, entries
= 0; cur
; cur
= cur
->fts_link
) {
739 if (cur
->fts_info
== FTS_ERR
|| cur
->fts_info
== FTS_NS
) {
741 cur
->fts_name
, strerror(cur
->fts_errno
));
742 cur
->fts_number
= NO_PRINT
;
747 * P is NULL if list is the argv list, to which different rules
751 /* Directories will be displayed later. */
752 if (cur
->fts_info
== FTS_D
&& !f_listdir
) {
753 cur
->fts_number
= NO_PRINT
;
757 /* Only display dot file if -a/-A set. */
758 if (cur
->fts_name
[0] == '.' && !f_listdot
) {
759 cur
->fts_number
= NO_PRINT
;
763 if (cur
->fts_namelen
> maxlen
)
764 maxlen
= cur
->fts_namelen
;
765 if (f_octal
|| f_octal_escape
) {
766 u_long t
= len_octal(cur
->fts_name
, cur
->fts_namelen
);
773 if (sp
->st_blocks
> maxblock
)
774 maxblock
= sp
->st_blocks
;
775 if (sp
->st_ino
> maxinode
)
776 maxinode
= sp
->st_ino
;
777 if (sp
->st_nlink
> maxnlink
)
778 maxnlink
= sp
->st_nlink
;
779 if (sp
->st_size
> maxsize
)
780 maxsize
= sp
->st_size
;
782 btotal
+= sp
->st_blocks
;
785 (void)snprintf(nuser
, sizeof(nuser
),
787 (void)snprintf(ngroup
, sizeof(ngroup
),
792 user
= user_from_uid(sp
->st_uid
, 0);
793 group
= group_from_gid(sp
->st_gid
, 0);
795 if ((ulen
= strlen(user
)) > maxuser
)
797 if ((glen
= strlen(group
)) > maxgroup
)
800 flags
= fflagstostr(sp
->st_flags
);
801 if (flags
!= NULL
&& *flags
== '\0') {
806 err(1, "fflagstostr");
807 flen
= strlen(flags
);
808 if (flen
> (size_t)maxflags
)
815 if ((np
= calloc(1, sizeof(NAMES
) + lattrlen
+
816 ulen
+ glen
+ flen
+ 4)) == NULL
)
819 np
->user
= &np
->data
[0];
820 (void)strcpy(np
->user
, user
);
821 np
->group
= &np
->data
[ulen
+ 1];
822 (void)strcpy(np
->group
, group
);
824 if (cur
->fts_level
== FTS_ROOTLEVEL
) {
825 filename
= cur
->fts_name
;
827 snprintf(path
, sizeof(path
), "%s/%s", cur
->fts_parent
->fts_accpath
, cur
->fts_name
);
830 xattr_size
= listxattr(filename
, NULL
, 0, XATTR_NOFOLLOW
);
831 if (xattr_size
< 0) {
834 if ((xattr_size
> 0) && f_xattr
) {
836 np
->xattr_names
= malloc(xattr_size
);
837 listxattr(filename
, np
->xattr_names
, xattr_size
, XATTR_NOFOLLOW
);
838 for (char *name
= np
->xattr_names
; name
< np
->xattr_names
+ xattr_size
;
839 name
+= strlen(name
)+1) {
840 np
->xattr_sizes
= reallocf(np
->xattr_sizes
, (np
->xattr_count
+1) * sizeof(np
->xattr_sizes
[0]));
841 np
->xattr_sizes
[np
->xattr_count
] = getxattr(filename
, name
, 0, 0, 0, XATTR_NOFOLLOW
);
845 /* symlinks can not have ACLs */
846 np
->acl
= acl_get_link_np(filename
, ACL_TYPE_EXTENDED
);
848 if (acl_get_entry(np
->acl
, ACL_FIRST_ENTRY
, &dummy
) == -1) {
853 if (xattr_size
> 0) {
854 np
->mode_suffix
= '@';
855 } else if (np
->acl
) {
856 np
->mode_suffix
= '+';
858 np
->mode_suffix
= ' ';
860 if (IS_DATALESS(sp
)) {
861 np
->mode_suffix
= '%';
868 if (S_ISCHR(sp
->st_mode
) ||
869 S_ISBLK(sp
->st_mode
))
873 np
->flags
= &np
->data
[ulen
+ glen
+ 2];
874 (void)strcpy(np
->flags
, flags
);
877 cur
->fts_pointer
= np
;
892 (void)snprintf(buf
, sizeof(buf
), "%qu", (u_int64_t
)maxblock
);
893 d
.s_block
= strlen(buf
);
894 d
.s_flags
= maxflags
;
895 d
.s_lattr
= maxlattr
;
896 d
.s_group
= maxgroup
;
897 #if _DARWIN_FEATURE_64_BIT_INODE
898 (void)snprintf(buf
, sizeof(buf
), "%llu", maxinode
);
900 (void)snprintf(buf
, sizeof(buf
), "%lu", maxinode
);
902 d
.s_inode
= strlen(buf
);
903 (void)snprintf(buf
, sizeof(buf
), "%lu", maxnlink
);
904 d
.s_nlink
= strlen(buf
);
905 (void)snprintf(buf
, sizeof(buf
), "%qu", (u_int64_t
)maxsize
);
906 d
.s_size
= strlen(buf
);
913 for (cur
= list
; cur
; cur
= cur
->fts_link
) {
914 np
= cur
->fts_pointer
;
919 free(np
->xattr_names
);
920 free(np
->xattr_sizes
);
922 cur
->fts_pointer
= NULL
;
929 * Ordering for mastercmp:
930 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
931 * as larger than directories. Within either group, use the sort function.
932 * All other levels use the sort function. Error entries remain unsorted.
935 mastercmp(const FTSENT
**a
, const FTSENT
**b
)
939 a_info
= (*a
)->fts_info
;
940 if (a_info
== FTS_ERR
)
942 b_info
= (*b
)->fts_info
;
943 if (b_info
== FTS_ERR
)
946 if (a_info
== FTS_NS
|| b_info
== FTS_NS
)
947 return (namecmp(*a
, *b
));
949 if (a_info
!= b_info
&&
950 (*a
)->fts_level
== FTS_ROOTLEVEL
&& !f_listdir
) {
956 return (sortfcn(*a
, *b
));
960 * Makenines() returns (10**n)-1. This is useful for converting a width
961 * into a number that wide in decimal.
964 makenines(u_quad_t n
)
970 /* Use a loop instead of pow(), since all values of n are small. */
971 for (i
= 0; i
< n
; i
++)