1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1989, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Michael Fischbein.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 #include <sys/param.h>
36 #include <sys/stat.h>
37 #include <sys/ioctl.h>
38 #include <sys/mac.h>
39
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fts.h>
45 #include <getopt.h>
46 #include <grp.h>
47 #include <inttypes.h>
48 #include <limits.h>
49 #include <locale.h>
50 #include <pwd.h>
51 #include <stdbool.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 #ifdef COLORLS
57 #include <termcap.h>
58 #include <signal.h>
59 #endif
60
61 #include "ls.h"
62 #include "extern.h"
63
64 /*
65 * Upward approximation of the maximum number of characters needed to
66 * represent a value of integral type t as a string, excluding the
67 * NUL terminator, with provision for a sign.
68 */
69 #define STRBUF_SIZEOF(t) (1 + CHAR_BIT * sizeof(t) / 3 + 1)
70
71 /*
72 * MAKENINES(n) turns n into (10**n)-1. This is useful for converting a width
73 * into a number that wide in decimal.
74 * XXX: Overflows are not considered.
75 */
76 #define MAKENINES(n) \
77 do { \
78 intmax_t __i; \
79 \
80 /* Use a loop as all values of n are small. */ \
81 for (__i = 1; n > 0; __i *= 10) \
82 n--; \
83 n = __i - 1; \
84 } while(0)
85
86 static void display(const FTSENT *, FTSENT *, int);
87 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
88 static void traverse(int, char **, int);
89
90 enum {
91 GRP_NONE = 0,
92 GRP_DIR_FIRST = -1,
93 GRP_DIR_LAST = 1
94 };
95
96 enum {
97 BIN_OPT = CHAR_MAX,
98 COLOR_OPT,
99 GROUP_OPT
100 };
101
102 static const struct option long_opts[] =
103 {
104 {"color", optional_argument, NULL, COLOR_OPT},
105 {"group-directories", optional_argument, NULL, GROUP_OPT},
106 {"group-directories-first", no_argument, NULL, GROUP_OPT},
107 {NULL, no_argument, NULL, 0}
108 };
109
110 static void (*printfcn)(const DISPLAY *);
111 static int (*sortfcn)(const FTSENT *, const FTSENT *);
112
113 long blocksize; /* block size units */
114 int termwidth = 80; /* default terminal width */
115
116 /* flags */
117 int f_accesstime; /* use time of last access */
118 int f_birthtime; /* use time of birth */
119 int f_flags; /* show flags associated with a file */
120 static int f_groupdir = GRP_NONE;/* group directories first/last */
121 int f_humanval; /* show human-readable file sizes */
122 int f_inode; /* print inode */
123 static int f_kblocks; /* print size in kilobytes */
124 int f_label; /* show MAC label */
125 static int f_listdir; /* list actual directory, not contents */
126 static int f_listdot; /* list files beginning with . */
127 int f_longform; /* long listing format */
128 static int f_noautodot; /* do not automatically enable -A for root */
129 static int f_nofollow; /* don't follow symbolic link arguments */
130 int f_nonprint; /* show unprintables as ? */
131 static int f_nosort; /* don't sort output */
132 int f_notabs; /* don't use tab-separated multi-col output */
133 static int f_numericonly; /* don't convert uid/gid to name */
134 int f_octal; /* show unprintables as \xxx */
135 int f_octal_escape; /* like f_octal but use C escapes if possible */
136 static int f_recursive; /* ls subdirectories also */
137 static int f_reversesort; /* reverse whatever sort is used */
138 static int f_verssort; /* sort names using strverscmp(3) rather than strcoll(3) */
139 int f_samesort; /* sort time and name in same direction */
140 int f_sectime; /* print full time information */
141 static int f_singlecol; /* use single column output */
142 int f_size; /* list size in short listing */
143 static int f_sizesort;
144 int f_slash; /* similar to f_type, but only for dirs */
145 int f_sortacross; /* sort across rows, not down columns */
146 int f_sowner; /* disable showing owner's name */
147 int f_statustime; /* use time of last mode change */
148 static int f_stream; /* stream the output, separate with commas */
149 int f_thousands; /* show file sizes with thousands separators */
150 char *f_timeformat; /* user-specified time format */
151 static int f_timesort; /* sort by time vice name */
152 int f_type; /* add type character for non-regular files */
153 static int f_whiteout; /* show whiteout entries */
154 #ifdef COLORLS
155 int colorflag = COLORFLAG_NEVER; /* passed in colorflag */
156 int f_color; /* add type in color for non-regular files */
157 bool explicitansi; /* Explicit ANSI sequences, no termcap(5) */
158 char *ansi_bgcol; /* ANSI sequence to set background colour */
159 char *ansi_fgcol; /* ANSI sequence to set foreground colour */
160 char *ansi_coloff; /* ANSI sequence to reset colours */
161 char *attrs_off; /* ANSI sequence to turn off attributes */
162 char *enter_bold; /* ANSI sequence to set color to bold mode */
163 char *enter_underline; /* ANSI sequence to enter underline mode */
164 #endif
165
166 static int rval;
167
168 static bool
do_color_from_env(void)169 do_color_from_env(void)
170 {
171 const char *p;
172 bool doit;
173
174 doit = false;
175 p = getenv("CLICOLOR");
176 if (p == NULL) {
177 /*
178 * COLORTERM is the more standard name for this variable. We'll
179 * honor it as long as it's both set and not empty.
180 */
181 p = getenv("COLORTERM");
182 if (p != NULL && *p != '\0')
183 doit = true;
184 } else
185 doit = true;
186
187 return (doit &&
188 (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")));
189 }
190
191 static bool
do_color(void)192 do_color(void)
193 {
194
195 #ifdef COLORLS
196 if (colorflag == COLORFLAG_NEVER)
197 return (false);
198 else if (colorflag == COLORFLAG_ALWAYS)
199 return (true);
200 #endif
201 return (do_color_from_env());
202 }
203
204 #ifdef COLORLS
205 static bool
do_color_always(const char * term)206 do_color_always(const char *term)
207 {
208
209 return (strcmp(term, "always") == 0 || strcmp(term, "yes") == 0 ||
210 strcmp(term, "force") == 0);
211 }
212
213 static bool
do_color_never(const char * term)214 do_color_never(const char *term)
215 {
216
217 return (strcmp(term, "never") == 0 || strcmp(term, "no") == 0 ||
218 strcmp(term, "none") == 0);
219 }
220
221 static bool
do_color_auto(const char * term)222 do_color_auto(const char *term)
223 {
224
225 return (strcmp(term, "auto") == 0 || strcmp(term, "tty") == 0 ||
226 strcmp(term, "if-tty") == 0);
227 }
228 #endif /* COLORLS */
229
230 int
main(int argc,char * argv[])231 main(int argc, char *argv[])
232 {
233 static char dot[] = ".", *dotav[] = {dot, NULL};
234 struct winsize win;
235 int ch, fts_options, notused;
236 char *p;
237 const char *errstr = NULL;
238 #ifdef COLORLS
239 char termcapbuf[1024]; /* termcap definition buffer */
240 char tcapbuf[512]; /* capability buffer */
241 char *bp = tcapbuf, *term;
242 #endif
243
244 (void)setlocale(LC_ALL, "");
245
246 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
247 if (isatty(STDOUT_FILENO)) {
248 termwidth = 80;
249 if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
250 termwidth = strtonum(p, 0, INT_MAX, &errstr);
251 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
252 win.ws_col > 0)
253 termwidth = win.ws_col;
254 f_nonprint = 1;
255 } else {
256 f_singlecol = 1;
257 /* retrieve environment variable, in case of explicit -C */
258 p = getenv("COLUMNS");
259 if (p)
260 termwidth = strtonum(p, 0, INT_MAX, &errstr);
261 }
262
263 if (errstr)
264 termwidth = 80;
265
266 fts_options = FTS_PHYSICAL;
267 if (getenv("LS_SAMESORT"))
268 f_samesort = 1;
269
270 /*
271 * For historical compatibility, we'll use our autodetection if CLICOLOR
272 * is set.
273 */
274 #ifdef COLORLS
275 if (getenv("CLICOLOR"))
276 colorflag = COLORFLAG_AUTO;
277 #endif
278 while ((ch = getopt_long(argc, argv,
279 "+1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuvwxy,", long_opts,
280 NULL)) != -1) {
281 switch (ch) {
282 /*
283 * The -1, -C, -x and -l options all override each other so
284 * shell aliasing works right.
285 */
286 case '1':
287 f_singlecol = 1;
288 f_longform = 0;
289 f_stream = 0;
290 break;
291 case 'C':
292 f_sortacross = f_longform = f_singlecol = 0;
293 break;
294 case 'l':
295 f_longform = 1;
296 f_singlecol = 0;
297 f_stream = 0;
298 break;
299 case 'x':
300 f_sortacross = 1;
301 f_longform = 0;
302 f_singlecol = 0;
303 break;
304 /* The -c, -u, and -U options override each other. */
305 case 'c':
306 f_statustime = 1;
307 f_accesstime = 0;
308 f_birthtime = 0;
309 break;
310 case 'u':
311 f_accesstime = 1;
312 f_statustime = 0;
313 f_birthtime = 0;
314 break;
315 case 'U':
316 f_birthtime = 1;
317 f_accesstime = 0;
318 f_statustime = 0;
319 break;
320 case 'f':
321 f_nosort = 1;
322 /* FALLTHROUGH */
323 case 'a':
324 fts_options |= FTS_SEEDOT;
325 /* FALLTHROUGH */
326 case 'A':
327 f_listdot = 1;
328 break;
329 /* The -S, -t and -v options override each other. */
330 case 'S':
331 f_sizesort = 1;
332 f_timesort = 0;
333 f_verssort = 0;
334 break;
335 case 't':
336 f_timesort = 1;
337 f_sizesort = 0;
338 f_verssort = 0;
339 break;
340 case 'v':
341 f_verssort = 1;
342 f_sizesort = 0;
343 f_timesort = 0;
344 break;
345 /* Other flags. Please keep alphabetic. */
346 case ',':
347 f_thousands = 1;
348 break;
349 case 'B':
350 f_nonprint = 0;
351 f_octal = 1;
352 f_octal_escape = 0;
353 break;
354 case 'D':
355 f_timeformat = optarg;
356 break;
357 case 'F':
358 f_type = 1;
359 f_slash = 0;
360 break;
361 case 'G':
362 /*
363 * We both set CLICOLOR here and set colorflag to
364 * COLORFLAG_AUTO, because -G should not force color if
365 * stdout isn't a tty.
366 */
367 setenv("CLICOLOR", "", 1);
368 #ifdef COLORLS
369 colorflag = COLORFLAG_AUTO;
370 #endif
371 break;
372 case 'H':
373 fts_options |= FTS_COMFOLLOW;
374 f_nofollow = 0;
375 break;
376 case 'I':
377 f_noautodot = 1;
378 break;
379 case 'L':
380 fts_options &= ~FTS_PHYSICAL;
381 fts_options |= FTS_LOGICAL;
382 f_nofollow = 0;
383 break;
384 case 'P':
385 fts_options &= ~FTS_COMFOLLOW;
386 fts_options &= ~FTS_LOGICAL;
387 fts_options |= FTS_PHYSICAL;
388 f_nofollow = 1;
389 break;
390 case 'R':
391 f_recursive = 1;
392 break;
393 case 'T':
394 f_sectime = 1;
395 break;
396 case 'W':
397 f_whiteout = 1;
398 break;
399 case 'Z':
400 f_label = 1;
401 break;
402 case 'b':
403 f_nonprint = 0;
404 f_octal = 0;
405 f_octal_escape = 1;
406 break;
407 /* The -d option turns off the -R option. */
408 case 'd':
409 f_listdir = 1;
410 f_recursive = 0;
411 break;
412 case 'g':
413 f_longform = 1;
414 f_singlecol = 0;
415 f_stream = 0;
416 f_sowner = 1;
417 break;
418 case 'h':
419 f_humanval = 1;
420 break;
421 case 'i':
422 f_inode = 1;
423 break;
424 case 'k':
425 f_humanval = 0;
426 f_kblocks = 1;
427 break;
428 case 'm':
429 f_stream = 1;
430 f_singlecol = 0;
431 f_longform = 0;
432 break;
433 case 'n':
434 f_numericonly = 1;
435 f_longform = 1;
436 f_singlecol = 0;
437 f_stream = 0;
438 break;
439 case 'o':
440 f_flags = 1;
441 break;
442 case 'p':
443 f_slash = 1;
444 f_type = 1;
445 break;
446 case 'q':
447 f_nonprint = 1;
448 f_octal = 0;
449 f_octal_escape = 0;
450 break;
451 case 'r':
452 f_reversesort = 1;
453 break;
454 case 's':
455 f_size = 1;
456 break;
457 case 'w':
458 f_nonprint = 0;
459 f_octal = 0;
460 f_octal_escape = 0;
461 break;
462 case 'y':
463 f_samesort = 1;
464 break;
465 case GROUP_OPT:
466 if (optarg == NULL || strcmp(optarg, "first") == 0)
467 f_groupdir = GRP_DIR_FIRST;
468 else if (strcmp(optarg, "last") == 0)
469 f_groupdir = GRP_DIR_LAST;
470 else
471 errx(2, "unsupported --group-directories value '%s' (must be first or last)",
472 optarg);
473 break;
474 case COLOR_OPT:
475 #ifdef COLORLS
476 if (optarg == NULL || do_color_always(optarg))
477 colorflag = COLORFLAG_ALWAYS;
478 else if (do_color_auto(optarg))
479 colorflag = COLORFLAG_AUTO;
480 else if (do_color_never(optarg))
481 colorflag = COLORFLAG_NEVER;
482 else
483 errx(2, "unsupported --color value '%s' (must be always, auto, or never)",
484 optarg);
485 break;
486 #else
487 warnx("color support not compiled in");
488 #endif
489 default:
490 case '?':
491 usage();
492 }
493 }
494 argc -= optind;
495 argv += optind;
496
497 /* Root is -A automatically unless -I. */
498 if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
499 f_listdot = 1;
500
501 /*
502 * Enabling of colours is conditional on the environment in conjunction
503 * with the --color and -G arguments, if supplied.
504 */
505 if (do_color()) {
506 #ifdef COLORLS
507 if ((term = getenv("TERM")) != NULL &&
508 tgetent(termcapbuf, term) == 1) {
509 ansi_fgcol = tgetstr("AF", &bp);
510 ansi_bgcol = tgetstr("AB", &bp);
511 attrs_off = tgetstr("me", &bp);
512 enter_bold = tgetstr("md", &bp);
513 enter_underline = tgetstr("us", &bp);
514
515 /* To switch colours off use 'op' if
516 * available, otherwise use 'oc', or
517 * don't do colours at all. */
518 ansi_coloff = tgetstr("op", &bp);
519 if (!ansi_coloff)
520 ansi_coloff = tgetstr("oc", &bp);
521 if (ansi_fgcol && ansi_bgcol && ansi_coloff)
522 f_color = 1;
523 } else if (colorflag == COLORFLAG_ALWAYS) {
524 /*
525 * If we're *always* doing color but we don't have
526 * a functional TERM supplied, we'll fallback to
527 * outputting raw ANSI sequences.
528 */
529 f_color = 1;
530 explicitansi = true;
531 }
532 #endif /*COLORLS*/
533 }
534
535 #ifdef COLORLS
536 if (f_color) {
537 /*
538 * We can't put tabs and color sequences together:
539 * column number will be incremented incorrectly
540 * for "stty oxtabs" mode.
541 */
542 f_notabs = 1;
543 (void)signal(SIGINT, colorquit);
544 (void)signal(SIGQUIT, colorquit);
545 parsecolors(getenv("LSCOLORS"));
546 }
547 #endif
548
549 /*
550 * If not -F, -i, -l, -s, -S, -t or --group-directories options,
551 * don't require stat information, unless in color mode in which case
552 * we do need this to determine which colors to display.
553 */
554 if (!f_inode && !f_longform && !f_size && !f_timesort &&
555 !f_sizesort && !f_type && f_groupdir == GRP_NONE
556 #ifdef COLORLS
557 && !f_color
558 #endif
559 )
560 fts_options |= FTS_NOSTAT;
561
562 /*
563 * If not -F, -P, -d or -l options, follow any symbolic links listed on
564 * the command line, unless in color mode in which case we need to
565 * distinguish file type for a symbolic link itself and its target.
566 */
567 if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash)
568 #ifdef COLORLS
569 && !f_color
570 #endif
571 )
572 fts_options |= FTS_COMFOLLOW;
573
574 /*
575 * If -W, show whiteout entries
576 */
577 #ifdef FTS_WHITEOUT
578 if (f_whiteout)
579 fts_options |= FTS_WHITEOUT;
580 #endif
581
582 /* If -i, -l or -s, figure out block size. */
583 if (f_inode || f_longform || f_size) {
584 if (f_kblocks)
585 blocksize = 2;
586 else {
587 (void)getbsize(¬used, &blocksize);
588 blocksize /= 512;
589 }
590 }
591
592 /* Select a sort function. */
593 if (f_reversesort) {
594 if (f_sizesort)
595 sortfcn = revsizecmp;
596 else if (f_verssort)
597 sortfcn = revverscmp;
598 else if (!f_timesort)
599 sortfcn = revnamecmp;
600 else if (f_accesstime)
601 sortfcn = revacccmp;
602 else if (f_birthtime)
603 sortfcn = revbirthcmp;
604 else if (f_statustime)
605 sortfcn = revstatcmp;
606 else /* Use modification time. */
607 sortfcn = revmodcmp;
608 } else {
609 if (f_sizesort)
610 sortfcn = sizecmp;
611 else if (f_verssort)
612 sortfcn = verscmp;
613 else if (!f_timesort)
614 sortfcn = namecmp;
615 else if (f_accesstime)
616 sortfcn = acccmp;
617 else if (f_birthtime)
618 sortfcn = birthcmp;
619 else if (f_statustime)
620 sortfcn = statcmp;
621 else /* Use modification time. */
622 sortfcn = modcmp;
623 }
624
625 /* Select a print function. */
626 if (f_singlecol)
627 printfcn = printscol;
628 else if (f_longform)
629 printfcn = printlong;
630 else if (f_stream)
631 printfcn = printstream;
632 else
633 printfcn = printcol;
634
635 if (argc)
636 traverse(argc, argv, fts_options);
637 else
638 traverse(1, dotav, fts_options);
639 exit(rval);
640 }
641
642 static int output; /* If anything output. */
643
644 /*
645 * Traverse() walks the logical directory structure specified by the argv list
646 * in the order specified by the mastercmp() comparison function. During the
647 * traversal it passes linked lists of structures to display() which represent
648 * a superset (may be exact set) of the files to be displayed.
649 */
650 static void
traverse(int argc,char * argv[],int options)651 traverse(int argc, char *argv[], int options)
652 {
653 FTS *ftsp;
654 FTSENT *p, *chp;
655 int ch_options;
656
657 if ((ftsp =
658 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
659 err(1, "fts_open");
660
661 /*
662 * We ignore errors from fts_children here since they will be
663 * replicated and signalled on the next call to fts_read() below.
664 */
665 chp = fts_children(ftsp, 0);
666 if (chp != NULL)
667 display(NULL, chp, options);
668 if (f_listdir) {
669 fts_close(ftsp);
670 return;
671 }
672
673 /*
674 * If not recursing down this tree and don't need stat info, just get
675 * the names.
676 */
677 ch_options = !f_recursive && !f_label &&
678 options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
679
680 while (errno = 0, (p = fts_read(ftsp)) != NULL)
681 switch (p->fts_info) {
682 case FTS_DC:
683 warnx("%s: directory causes a cycle", p->fts_name);
684 break;
685 case FTS_DNR:
686 case FTS_ERR:
687 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
688 rval = 1;
689 break;
690 case FTS_D:
691 if (p->fts_level != FTS_ROOTLEVEL &&
692 p->fts_name[0] == '.' && !f_listdot)
693 break;
694
695 /*
696 * If already output something, put out a newline as
697 * a separator. If multiple arguments, precede each
698 * directory with its name.
699 */
700 if (output) {
701 putchar('\n');
702 (void)printname(p->fts_path);
703 puts(":");
704 } else if (argc > 1) {
705 (void)printname(p->fts_path);
706 puts(":");
707 output = 1;
708 }
709 chp = fts_children(ftsp, ch_options);
710 if (chp == NULL && errno != 0) {
711 warn("%s", p->fts_path);
712 rval = 1;
713
714 /*
715 * Avoid further errors on this entry. We won't
716 * always get an FTS_ERR/FTS_DNR for errors
717 * in fts_children(), because opendir could
718 * have failed early on and that only flags an
719 * error for fts_read() when we try to recurse
720 * into it. We catch both the non-recursive and
721 * the recursive case here.
722 */
723 (void)fts_set(ftsp, p, FTS_SKIP);
724 break;
725 }
726
727 display(p, chp, options);
728
729 if (!f_recursive && chp != NULL)
730 (void)fts_set(ftsp, p, FTS_SKIP);
731 break;
732 default:
733 break;
734 }
735 if (errno)
736 err(1, "fts_read");
737 fts_close(ftsp);
738 }
739
740 /*
741 * Display() takes a linked list of FTSENT structures and passes the list
742 * along with any other necessary information to the print function. P
743 * points to the parent directory of the display list.
744 */
745 static void
display(const FTSENT * p,FTSENT * list,int options)746 display(const FTSENT *p, FTSENT *list, int options)
747 {
748 struct stat *sp;
749 DISPLAY d;
750 FTSENT *cur;
751 NAMES *np;
752 off_t maxsize;
753 long maxblock;
754 uintmax_t maxinode;
755 u_long btotal, labelstrlen, maxlen, maxnlink;
756 u_long maxlabelstr;
757 u_int sizelen;
758 int maxflags;
759 gid_t maxgroup;
760 uid_t maxuser;
761 size_t flen, ulen, glen;
762 char *initmax;
763 int entries, needstats;
764 const char *user, *group;
765 char *flags, *labelstr = NULL;
766 char ngroup[STRBUF_SIZEOF(uid_t) + 1];
767 char nuser[STRBUF_SIZEOF(gid_t) + 1];
768 u_long width[9];
769 int i;
770
771 needstats = f_inode || f_longform || f_size;
772 flen = 0;
773 btotal = 0;
774
775 #define LS_COLWIDTHS_FIELDS 9
776 initmax = getenv("LS_COLWIDTHS");
777
778 for (i = 0 ; i < LS_COLWIDTHS_FIELDS; i++)
779 width[i] = 0;
780
781 if (initmax != NULL) {
782 char *endp;
783
784 for (i = 0; i < LS_COLWIDTHS_FIELDS && *initmax != '\0'; i++) {
785 if (*initmax == ':') {
786 width[i] = 0;
787 } else {
788 width[i] = strtoul(initmax, &endp, 10);
789 initmax = endp;
790 while (isspace(*initmax))
791 initmax++;
792 if (*initmax != ':')
793 break;
794 initmax++;
795 }
796 }
797 if (i < LS_COLWIDTHS_FIELDS)
798 #ifdef COLORLS
799 if (!f_color)
800 #endif
801 f_notabs = 0;
802 }
803
804 /* Fields match -lios order. New ones should be added at the end. */
805 maxinode = width[0];
806 maxblock = width[1];
807 maxnlink = width[2];
808 maxuser = width[3];
809 maxgroup = width[4];
810 maxflags = width[5];
811 maxsize = width[6];
812 maxlen = width[7];
813 maxlabelstr = width[8];
814
815 MAKENINES(maxinode);
816 MAKENINES(maxblock);
817 MAKENINES(maxnlink);
818 MAKENINES(maxsize);
819
820 d.s_size = 0;
821 sizelen = 0;
822 flags = NULL;
823 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
824 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
825 warnx("%s: %s",
826 cur->fts_name, strerror(cur->fts_errno));
827 cur->fts_number = NO_PRINT;
828 rval = 1;
829 continue;
830 }
831 /*
832 * P is NULL if list is the argv list, to which different rules
833 * apply.
834 */
835 if (p == NULL) {
836 /* Directories will be displayed later. */
837 if (cur->fts_info == FTS_D && !f_listdir) {
838 cur->fts_number = NO_PRINT;
839 continue;
840 }
841 } else {
842 /* Only display dot file if -a/-A set. */
843 if (cur->fts_name[0] == '.' && !f_listdot) {
844 cur->fts_number = NO_PRINT;
845 continue;
846 }
847 }
848 if (cur->fts_namelen > maxlen)
849 maxlen = cur->fts_namelen;
850 if (f_octal || f_octal_escape) {
851 u_long t = len_octal(cur->fts_name, cur->fts_namelen);
852
853 if (t > maxlen)
854 maxlen = t;
855 }
856 if (needstats) {
857 sp = cur->fts_statp;
858 if (sp->st_blocks > maxblock)
859 maxblock = sp->st_blocks;
860 if (sp->st_ino > maxinode)
861 maxinode = sp->st_ino;
862 if (sp->st_nlink > maxnlink)
863 maxnlink = sp->st_nlink;
864 if (sp->st_size > maxsize)
865 maxsize = sp->st_size;
866
867 btotal += sp->st_blocks;
868 if (f_longform) {
869 if (f_numericonly) {
870 (void)snprintf(nuser, sizeof(nuser),
871 "%u", sp->st_uid);
872 (void)snprintf(ngroup, sizeof(ngroup),
873 "%u", sp->st_gid);
874 user = nuser;
875 group = ngroup;
876 } else {
877 user = user_from_uid(sp->st_uid, 0);
878 /*
879 * user_from_uid(..., 0) only returns
880 * NULL in OOM conditions. We could
881 * format the uid here, but (1) in
882 * general ls(1) exits on OOM, and (2)
883 * there is another allocation/exit
884 * path directly below, which will
885 * likely exit anyway.
886 */
887 if (user == NULL)
888 err(1, "user_from_uid");
889 group = group_from_gid(sp->st_gid, 0);
890 /* Ditto. */
891 if (group == NULL)
892 err(1, "group_from_gid");
893 }
894 if ((ulen = strlen(user)) > maxuser)
895 maxuser = ulen;
896 if ((glen = strlen(group)) > maxgroup)
897 maxgroup = glen;
898 if (f_flags) {
899 flags = fflagstostr(sp->st_flags);
900 if (flags != NULL && *flags == '\0') {
901 free(flags);
902 flags = strdup("-");
903 }
904 if (flags == NULL)
905 err(1, "fflagstostr");
906 flen = strlen(flags);
907 if (flen > (size_t)maxflags)
908 maxflags = flen;
909 } else
910 flen = 0;
911 labelstr = NULL;
912 if (f_label) {
913 char name[PATH_MAX + 1];
914 mac_t label;
915 int error;
916
917 error = mac_prepare_file_label(&label);
918 if (error == -1) {
919 warn("MAC label for %s/%s",
920 cur->fts_parent->fts_path,
921 cur->fts_name);
922 goto label_out;
923 }
924
925 if (cur->fts_level == FTS_ROOTLEVEL)
926 snprintf(name, sizeof(name),
927 "%s", cur->fts_name);
928 else
929 snprintf(name, sizeof(name),
930 "%s/%s", cur->fts_parent->
931 fts_accpath, cur->fts_name);
932
933 if (options & FTS_LOGICAL)
934 error = mac_get_file(name,
935 label);
936 else
937 error = mac_get_link(name,
938 label);
939 if (error == -1) {
940 warn("MAC label for %s/%s",
941 cur->fts_parent->fts_path,
942 cur->fts_name);
943 mac_free(label);
944 goto label_out;
945 }
946
947 error = mac_to_text(label,
948 &labelstr);
949 if (error == -1) {
950 warn("MAC label for %s/%s",
951 cur->fts_parent->fts_path,
952 cur->fts_name);
953 mac_free(label);
954 goto label_out;
955 }
956 mac_free(label);
957 label_out:
958 if (labelstr == NULL)
959 labelstr = strdup("-");
960 labelstrlen = strlen(labelstr);
961 if (labelstrlen > maxlabelstr)
962 maxlabelstr = labelstrlen;
963 } else
964 labelstrlen = 0;
965
966 if ((np = malloc(sizeof(NAMES) + labelstrlen +
967 ulen + glen + flen + 4)) == NULL)
968 err(1, "malloc");
969
970 np->user = &np->data[0];
971 (void)strcpy(np->user, user);
972 np->group = &np->data[ulen + 1];
973 (void)strcpy(np->group, group);
974
975 if (S_ISCHR(sp->st_mode) ||
976 S_ISBLK(sp->st_mode)) {
977 sizelen = snprintf(NULL, 0,
978 "%#jx", (uintmax_t)sp->st_rdev);
979 if (d.s_size < sizelen)
980 d.s_size = sizelen;
981 }
982
983 if (f_flags) {
984 np->flags = &np->data[ulen + glen + 2];
985 (void)strcpy(np->flags, flags);
986 free(flags);
987 }
988 if (f_label) {
989 np->label = &np->data[ulen + glen + 2
990 + (f_flags ? flen + 1 : 0)];
991 (void)strcpy(np->label, labelstr);
992 free(labelstr);
993 }
994 cur->fts_pointer = np;
995 }
996 }
997 ++entries;
998 }
999
1000 /*
1001 * If there are no entries to display, we normally stop right
1002 * here. However, we must continue if we have to display the
1003 * total block count. In this case, we display the total only
1004 * on the second (p != NULL) pass.
1005 */
1006 if (!entries && (!(f_longform || f_size) || p == NULL))
1007 return;
1008
1009 d.list = list;
1010 d.entries = entries;
1011 d.maxlen = maxlen;
1012 if (needstats) {
1013 d.btotal = btotal;
1014 d.s_block = snprintf(NULL, 0, f_thousands ? "%'ld" : "%ld",
1015 howmany(maxblock, blocksize));
1016 d.s_flags = maxflags;
1017 d.s_label = maxlabelstr;
1018 d.s_group = maxgroup;
1019 d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
1020 d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
1021 sizelen = f_humanval ? HUMANVALSTR_LEN :
1022 snprintf(NULL, 0, "%ju", maxsize);
1023 if (d.s_size < sizelen)
1024 d.s_size = sizelen;
1025 d.s_user = maxuser;
1026 }
1027 if (f_thousands) /* make space for commas */
1028 d.s_size += (d.s_size - 1) / 3;
1029 printfcn(&d);
1030 output = 1;
1031
1032 if (f_longform)
1033 for (cur = list; cur; cur = cur->fts_link)
1034 free(cur->fts_pointer);
1035 }
1036
1037 /*
1038 * Ordering for mastercmp:
1039 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
1040 * as larger than directories. Within either group, use the sort function.
1041 * All other levels use the sort function. Error entries remain unsorted.
1042 */
1043 static int
mastercmp(const FTSENT * const * a,const FTSENT * const * b)1044 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
1045 {
1046 int a_info, b_info, dir;
1047
1048 a_info = (*a)->fts_info;
1049 if (a_info == FTS_ERR)
1050 return (0);
1051 b_info = (*b)->fts_info;
1052 if (b_info == FTS_ERR)
1053 return (0);
1054
1055 if (a_info == FTS_NS || b_info == FTS_NS)
1056 return (namecmp(*a, *b));
1057
1058 if (a_info != b_info &&
1059 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
1060 if (a_info == FTS_D)
1061 return (1);
1062 if (b_info == FTS_D)
1063 return (-1);
1064 }
1065
1066 if (f_groupdir != GRP_NONE)
1067 if ((dir = (a_info == FTS_D) - (b_info == FTS_D)) != 0)
1068 return (f_groupdir * dir);
1069
1070 return (sortfcn(*a, *b));
1071 }
1072