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 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 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 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 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 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 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 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 display(p, chp, options); 711 712 if (!f_recursive && chp != NULL) 713 (void)fts_set(ftsp, p, FTS_SKIP); 714 break; 715 default: 716 break; 717 } 718 if (errno) 719 err(1, "fts_read"); 720 fts_close(ftsp); 721 } 722 723 /* 724 * Display() takes a linked list of FTSENT structures and passes the list 725 * along with any other necessary information to the print function. P 726 * points to the parent directory of the display list. 727 */ 728 static void 729 display(const FTSENT *p, FTSENT *list, int options) 730 { 731 struct stat *sp; 732 DISPLAY d; 733 FTSENT *cur; 734 NAMES *np; 735 off_t maxsize; 736 long maxblock; 737 uintmax_t maxinode; 738 u_long btotal, labelstrlen, maxlen, maxnlink; 739 u_long maxlabelstr; 740 u_int sizelen; 741 int maxflags; 742 gid_t maxgroup; 743 uid_t maxuser; 744 size_t flen, ulen, glen; 745 char *initmax; 746 int entries, needstats; 747 const char *user, *group; 748 char *flags, *labelstr = NULL; 749 char ngroup[STRBUF_SIZEOF(uid_t) + 1]; 750 char nuser[STRBUF_SIZEOF(gid_t) + 1]; 751 u_long width[9]; 752 int i; 753 754 needstats = f_inode || f_longform || f_size; 755 flen = 0; 756 btotal = 0; 757 758 #define LS_COLWIDTHS_FIELDS 9 759 initmax = getenv("LS_COLWIDTHS"); 760 761 for (i = 0 ; i < LS_COLWIDTHS_FIELDS; i++) 762 width[i] = 0; 763 764 if (initmax != NULL) { 765 char *endp; 766 767 for (i = 0; i < LS_COLWIDTHS_FIELDS && *initmax != '\0'; i++) { 768 if (*initmax == ':') { 769 width[i] = 0; 770 } else { 771 width[i] = strtoul(initmax, &endp, 10); 772 initmax = endp; 773 while (isspace(*initmax)) 774 initmax++; 775 if (*initmax != ':') 776 break; 777 initmax++; 778 } 779 } 780 if (i < LS_COLWIDTHS_FIELDS) 781 #ifdef COLORLS 782 if (!f_color) 783 #endif 784 f_notabs = 0; 785 } 786 787 /* Fields match -lios order. New ones should be added at the end. */ 788 maxinode = width[0]; 789 maxblock = width[1]; 790 maxnlink = width[2]; 791 maxuser = width[3]; 792 maxgroup = width[4]; 793 maxflags = width[5]; 794 maxsize = width[6]; 795 maxlen = width[7]; 796 maxlabelstr = width[8]; 797 798 MAKENINES(maxinode); 799 MAKENINES(maxblock); 800 MAKENINES(maxnlink); 801 MAKENINES(maxsize); 802 803 d.s_size = 0; 804 sizelen = 0; 805 flags = NULL; 806 for (cur = list, entries = 0; cur; cur = cur->fts_link) { 807 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) { 808 warnx("%s: %s", 809 cur->fts_name, strerror(cur->fts_errno)); 810 cur->fts_number = NO_PRINT; 811 rval = 1; 812 continue; 813 } 814 /* 815 * P is NULL if list is the argv list, to which different rules 816 * apply. 817 */ 818 if (p == NULL) { 819 /* Directories will be displayed later. */ 820 if (cur->fts_info == FTS_D && !f_listdir) { 821 cur->fts_number = NO_PRINT; 822 continue; 823 } 824 } else { 825 /* Only display dot file if -a/-A set. */ 826 if (cur->fts_name[0] == '.' && !f_listdot) { 827 cur->fts_number = NO_PRINT; 828 continue; 829 } 830 } 831 if (cur->fts_namelen > maxlen) 832 maxlen = cur->fts_namelen; 833 if (f_octal || f_octal_escape) { 834 u_long t = len_octal(cur->fts_name, cur->fts_namelen); 835 836 if (t > maxlen) 837 maxlen = t; 838 } 839 if (needstats) { 840 sp = cur->fts_statp; 841 if (sp->st_blocks > maxblock) 842 maxblock = sp->st_blocks; 843 if (sp->st_ino > maxinode) 844 maxinode = sp->st_ino; 845 if (sp->st_nlink > maxnlink) 846 maxnlink = sp->st_nlink; 847 if (sp->st_size > maxsize) 848 maxsize = sp->st_size; 849 850 btotal += sp->st_blocks; 851 if (f_longform) { 852 if (f_numericonly) { 853 (void)snprintf(nuser, sizeof(nuser), 854 "%u", sp->st_uid); 855 (void)snprintf(ngroup, sizeof(ngroup), 856 "%u", sp->st_gid); 857 user = nuser; 858 group = ngroup; 859 } else { 860 user = user_from_uid(sp->st_uid, 0); 861 /* 862 * user_from_uid(..., 0) only returns 863 * NULL in OOM conditions. We could 864 * format the uid here, but (1) in 865 * general ls(1) exits on OOM, and (2) 866 * there is another allocation/exit 867 * path directly below, which will 868 * likely exit anyway. 869 */ 870 if (user == NULL) 871 err(1, "user_from_uid"); 872 group = group_from_gid(sp->st_gid, 0); 873 /* Ditto. */ 874 if (group == NULL) 875 err(1, "group_from_gid"); 876 } 877 if ((ulen = strlen(user)) > maxuser) 878 maxuser = ulen; 879 if ((glen = strlen(group)) > maxgroup) 880 maxgroup = glen; 881 if (f_flags) { 882 flags = fflagstostr(sp->st_flags); 883 if (flags != NULL && *flags == '\0') { 884 free(flags); 885 flags = strdup("-"); 886 } 887 if (flags == NULL) 888 err(1, "fflagstostr"); 889 flen = strlen(flags); 890 if (flen > (size_t)maxflags) 891 maxflags = flen; 892 } else 893 flen = 0; 894 labelstr = NULL; 895 if (f_label) { 896 char name[PATH_MAX + 1]; 897 mac_t label; 898 int error; 899 900 error = mac_prepare_file_label(&label); 901 if (error == -1) { 902 warn("MAC label for %s/%s", 903 cur->fts_parent->fts_path, 904 cur->fts_name); 905 goto label_out; 906 } 907 908 if (cur->fts_level == FTS_ROOTLEVEL) 909 snprintf(name, sizeof(name), 910 "%s", cur->fts_name); 911 else 912 snprintf(name, sizeof(name), 913 "%s/%s", cur->fts_parent-> 914 fts_accpath, cur->fts_name); 915 916 if (options & FTS_LOGICAL) 917 error = mac_get_file(name, 918 label); 919 else 920 error = mac_get_link(name, 921 label); 922 if (error == -1) { 923 warn("MAC label for %s/%s", 924 cur->fts_parent->fts_path, 925 cur->fts_name); 926 mac_free(label); 927 goto label_out; 928 } 929 930 error = mac_to_text(label, 931 &labelstr); 932 if (error == -1) { 933 warn("MAC label for %s/%s", 934 cur->fts_parent->fts_path, 935 cur->fts_name); 936 mac_free(label); 937 goto label_out; 938 } 939 mac_free(label); 940 label_out: 941 if (labelstr == NULL) 942 labelstr = strdup("-"); 943 labelstrlen = strlen(labelstr); 944 if (labelstrlen > maxlabelstr) 945 maxlabelstr = labelstrlen; 946 } else 947 labelstrlen = 0; 948 949 if ((np = malloc(sizeof(NAMES) + labelstrlen + 950 ulen + glen + flen + 4)) == NULL) 951 err(1, "malloc"); 952 953 np->user = &np->data[0]; 954 (void)strcpy(np->user, user); 955 np->group = &np->data[ulen + 1]; 956 (void)strcpy(np->group, group); 957 958 if (S_ISCHR(sp->st_mode) || 959 S_ISBLK(sp->st_mode)) { 960 sizelen = snprintf(NULL, 0, 961 "%#jx", (uintmax_t)sp->st_rdev); 962 if (d.s_size < sizelen) 963 d.s_size = sizelen; 964 } 965 966 if (f_flags) { 967 np->flags = &np->data[ulen + glen + 2]; 968 (void)strcpy(np->flags, flags); 969 free(flags); 970 } 971 if (f_label) { 972 np->label = &np->data[ulen + glen + 2 973 + (f_flags ? flen + 1 : 0)]; 974 (void)strcpy(np->label, labelstr); 975 free(labelstr); 976 } 977 cur->fts_pointer = np; 978 } 979 } 980 ++entries; 981 } 982 983 /* 984 * If there are no entries to display, we normally stop right 985 * here. However, we must continue if we have to display the 986 * total block count. In this case, we display the total only 987 * on the second (p != NULL) pass. 988 */ 989 if (!entries && (!(f_longform || f_size) || p == NULL)) 990 return; 991 992 d.list = list; 993 d.entries = entries; 994 d.maxlen = maxlen; 995 if (needstats) { 996 d.btotal = btotal; 997 d.s_block = snprintf(NULL, 0, f_thousands ? "%'ld" : "%ld", 998 howmany(maxblock, blocksize)); 999 d.s_flags = maxflags; 1000 d.s_label = maxlabelstr; 1001 d.s_group = maxgroup; 1002 d.s_inode = snprintf(NULL, 0, "%ju", maxinode); 1003 d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink); 1004 sizelen = f_humanval ? HUMANVALSTR_LEN : 1005 snprintf(NULL, 0, "%ju", maxsize); 1006 if (d.s_size < sizelen) 1007 d.s_size = sizelen; 1008 d.s_user = maxuser; 1009 } 1010 if (f_thousands) /* make space for commas */ 1011 d.s_size += (d.s_size - 1) / 3; 1012 printfcn(&d); 1013 output = 1; 1014 1015 if (f_longform) 1016 for (cur = list; cur; cur = cur->fts_link) 1017 free(cur->fts_pointer); 1018 } 1019 1020 /* 1021 * Ordering for mastercmp: 1022 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories 1023 * as larger than directories. Within either group, use the sort function. 1024 * All other levels use the sort function. Error entries remain unsorted. 1025 */ 1026 static int 1027 mastercmp(const FTSENT * const *a, const FTSENT * const *b) 1028 { 1029 int a_info, b_info, dir; 1030 1031 a_info = (*a)->fts_info; 1032 if (a_info == FTS_ERR) 1033 return (0); 1034 b_info = (*b)->fts_info; 1035 if (b_info == FTS_ERR) 1036 return (0); 1037 1038 if (a_info == FTS_NS || b_info == FTS_NS) 1039 return (namecmp(*a, *b)); 1040 1041 if (a_info != b_info && 1042 (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) { 1043 if (a_info == FTS_D) 1044 return (1); 1045 if (b_info == FTS_D) 1046 return (-1); 1047 } 1048 1049 if (f_groupdir != GRP_NONE) 1050 if ((dir = (a_info == FTS_D) - (b_info == FTS_D)) != 0) 1051 return (f_groupdir * dir); 1052 1053 return (sortfcn(*a, *b)); 1054 } 1055