ls.c revision 1.71 1 /* $NetBSD: ls.c,v 1.71 2014/02/20 18:56:36 christos Exp $ */
2
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/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
38 The Regents of the University of California. All rights reserved.");
39 #endif /* not lint */
40
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)ls.c 8.7 (Berkeley) 8/5/94";
44 #else
45 __RCSID("$NetBSD: ls.c,v 1.71 2014/02/20 18:56:36 christos Exp $");
46 #endif
47 #endif /* not lint */
48
49 #include <sys/param.h>
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53
54 #include <dirent.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fts.h>
58 #include <locale.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 #include <termios.h>
64 #include <pwd.h>
65 #include <grp.h>
66 #include <util.h>
67
68 #include "ls.h"
69 #include "extern.h"
70
71 static void display(FTSENT *, FTSENT *);
72 static int mastercmp(const FTSENT **, const FTSENT **);
73 static void traverse(int, char **, int);
74
75 static void (*printfcn)(DISPLAY *);
76 static int (*sortfcn)(const FTSENT *, const FTSENT *);
77
78 #define BY_NAME 0
79 #define BY_SIZE 1
80 #define BY_TIME 2
81
82 long blocksize; /* block size units */
83 int termwidth = 80; /* default terminal width */
84 int sortkey = BY_NAME;
85 int rval = EXIT_SUCCESS; /* exit value - set if error encountered */
86
87 /* flags */
88 int f_accesstime; /* use time of last access */
89 int f_column; /* columnated format */
90 int f_columnacross; /* columnated format, sorted across */
91 int f_flags; /* show flags associated with a file */
92 int f_grouponly; /* long listing without owner */
93 int f_humanize; /* humanize the size field */
94 int f_commas; /* separate size field with comma */
95 int f_inode; /* print inode */
96 int f_listdir; /* list actual directory, not contents */
97 int f_listdot; /* list files beginning with . */
98 int f_longform; /* long listing format */
99 int f_nonprint; /* show unprintables as ? */
100 int f_nosort; /* don't sort output */
101 int f_numericonly; /* don't convert uid/gid to name */
102 int f_octal; /* print octal escapes for nongraphic characters */
103 int f_octal_escape; /* like f_octal but use C escapes if possible */
104 int f_recursive; /* ls subdirectories also */
105 int f_reversesort; /* reverse whatever sort is used */
106 int f_sectime; /* print the real time for all files */
107 int f_singlecol; /* use single column output */
108 int f_size; /* list size in short listing */
109 int f_statustime; /* use time of last mode change */
110 int f_stream; /* stream format */
111 int f_type; /* add type character for non-regular files */
112 int f_typedir; /* add type character for directories */
113 int f_whiteout; /* show whiteout entries */
114 int f_fullpath; /* print full pathname, not filename */
115 int f_leafonly; /* when recursing, print leaf names only */
116
117 __dead static void
118 usage(void)
119 {
120
121 (void)fprintf(stderr,
122 "usage: %s [-1AaBbCcdFfghikLlMmnopqRrSsTtuWwx] [file ...]\n",
123 getprogname());
124 exit(EXIT_FAILURE);
125 /* NOTREACHED */
126 }
127
128 int
129 ls_main(int argc, char *argv[])
130 {
131 static char dot[] = ".", *dotav[] = { dot, NULL };
132 struct winsize win;
133 int ch, fts_options;
134 int kflag = 0;
135 const char *p;
136
137 setprogname(argv[0]);
138 (void)setlocale(LC_ALL, "");
139
140 /* Terminal defaults to -Cq, non-terminal defaults to -1. */
141 if (isatty(STDOUT_FILENO)) {
142 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
143 win.ws_col > 0)
144 termwidth = win.ws_col;
145 f_column = f_nonprint = 1;
146 } else
147 f_singlecol = 1;
148
149 /* Root is -A automatically. */
150 if (!getuid())
151 f_listdot = 1;
152
153 fts_options = FTS_PHYSICAL;
154 while ((ch = getopt(argc, argv, "1ABCFLMOPRSTWabcdfghiklmnopqrstuwx")) != -1) {
155 switch (ch) {
156 /*
157 * The -1, -C, -l, -m and -x options all override each other so
158 * shell aliasing works correctly.
159 */
160 case '1':
161 f_singlecol = 1;
162 f_column = f_columnacross = f_longform = f_stream = 0;
163 break;
164 case 'C':
165 f_column = 1;
166 f_columnacross = f_longform = f_singlecol = f_stream =
167 0;
168 break;
169 case 'g':
170 if (f_grouponly != -1)
171 f_grouponly = 1;
172 f_longform = 1;
173 f_column = f_columnacross = f_singlecol = f_stream = 0;
174 break;
175 case 'l':
176 f_longform = 1;
177 f_column = f_columnacross = f_singlecol = f_stream = 0;
178 /* Never let -g take precedence over -l. */
179 f_grouponly = -1;
180 break;
181 case 'm':
182 f_stream = 1;
183 f_column = f_columnacross = f_longform = f_singlecol =
184 0;
185 break;
186 case 'x':
187 f_columnacross = 1;
188 f_column = f_longform = f_singlecol = f_stream = 0;
189 break;
190 /* The -c and -u options override each other. */
191 case 'c':
192 f_statustime = 1;
193 f_accesstime = 0;
194 break;
195 case 'u':
196 f_accesstime = 1;
197 f_statustime = 0;
198 break;
199 case 'F':
200 f_type = 1;
201 break;
202 case 'L':
203 fts_options &= ~FTS_PHYSICAL;
204 fts_options |= FTS_LOGICAL;
205 break;
206 case 'R':
207 f_recursive = 1;
208 break;
209 case 'a':
210 fts_options |= FTS_SEEDOT;
211 /* FALLTHROUGH */
212 case 'A':
213 f_listdot = 1;
214 break;
215 /* The -B option turns off the -b, -q and -w options. */
216 case 'B':
217 f_nonprint = 0;
218 f_octal = 1;
219 f_octal_escape = 0;
220 break;
221 /* The -b option turns off the -B, -q and -w options. */
222 case 'b':
223 f_nonprint = 0;
224 f_octal = 0;
225 f_octal_escape = 1;
226 break;
227 /* The -d option turns off the -R option. */
228 case 'd':
229 f_listdir = 1;
230 f_recursive = 0;
231 break;
232 case 'f':
233 f_nosort = 1;
234 break;
235 case 'i':
236 f_inode = 1;
237 break;
238 case 'k':
239 blocksize = 1024;
240 kflag = 1;
241 f_humanize = 0;
242 break;
243 /* The -h option forces all sizes to be measured in bytes. */
244 case 'h':
245 f_humanize = 1;
246 kflag = 0;
247 f_commas = 0;
248 break;
249 case 'M':
250 f_humanize = 0;
251 f_commas = 1;
252 break;
253 case 'n':
254 f_numericonly = 1;
255 f_longform = 1;
256 f_column = f_columnacross = f_singlecol = f_stream = 0;
257 break;
258 case 'O':
259 f_leafonly = 1;
260 break;
261 case 'o':
262 f_flags = 1;
263 break;
264 case 'P':
265 f_fullpath = 1;
266 break;
267 case 'p':
268 f_typedir = 1;
269 break;
270 /* The -q option turns off the -B, -b and -w options. */
271 case 'q':
272 f_nonprint = 1;
273 f_octal = 0;
274 f_octal_escape = 0;
275 break;
276 case 'r':
277 f_reversesort = 1;
278 break;
279 case 'S':
280 sortkey = BY_SIZE;
281 break;
282 case 's':
283 f_size = 1;
284 break;
285 case 'T':
286 f_sectime = 1;
287 break;
288 case 't':
289 sortkey = BY_TIME;
290 break;
291 case 'W':
292 f_whiteout = 1;
293 break;
294 /* The -w option turns off the -B, -b and -q options. */
295 case 'w':
296 f_nonprint = 0;
297 f_octal = 0;
298 f_octal_escape = 0;
299 break;
300 default:
301 case '?':
302 usage();
303 }
304 }
305 argc -= optind;
306 argv += optind;
307
308 if (f_column || f_columnacross || f_stream) {
309 if ((p = getenv("COLUMNS")) != NULL)
310 termwidth = atoi(p);
311 }
312
313 /*
314 * If both -g and -l options, let -l take precedence.
315 */
316 if (f_grouponly == -1)
317 f_grouponly = 0;
318
319 /*
320 * If not -F, -i, -l, -p, -S, -s or -t options, don't require stat
321 * information.
322 */
323 if (!f_inode && !f_longform && !f_size && !f_type && !f_typedir &&
324 sortkey == BY_NAME)
325 fts_options |= FTS_NOSTAT;
326
327 /*
328 * If not -F, -d or -l options, follow any symbolic links listed on
329 * the command line.
330 */
331 if (!f_longform && !f_listdir && !f_type)
332 fts_options |= FTS_COMFOLLOW;
333
334 /*
335 * If -W, show whiteout entries
336 */
337 #ifdef FTS_WHITEOUT
338 if (f_whiteout)
339 fts_options |= FTS_WHITEOUT;
340 #endif
341
342 /* If -i, -l, or -s, figure out block size. */
343 if (f_inode || f_longform || f_size) {
344 if (!kflag)
345 (void)getbsize(NULL, &blocksize);
346 blocksize /= 512;
347 }
348
349 /* Select a sort function. */
350 if (f_reversesort) {
351 switch (sortkey) {
352 case BY_NAME:
353 sortfcn = revnamecmp;
354 break;
355 case BY_SIZE:
356 sortfcn = revsizecmp;
357 break;
358 case BY_TIME:
359 if (f_accesstime)
360 sortfcn = revacccmp;
361 else if (f_statustime)
362 sortfcn = revstatcmp;
363 else /* Use modification time. */
364 sortfcn = revmodcmp;
365 break;
366 }
367 } else {
368 switch (sortkey) {
369 case BY_NAME:
370 sortfcn = namecmp;
371 break;
372 case BY_SIZE:
373 sortfcn = sizecmp;
374 break;
375 case BY_TIME:
376 if (f_accesstime)
377 sortfcn = acccmp;
378 else if (f_statustime)
379 sortfcn = statcmp;
380 else /* Use modification time. */
381 sortfcn = modcmp;
382 break;
383 }
384 }
385
386 /* Select a print function. */
387 if (f_singlecol)
388 printfcn = printscol;
389 else if (f_columnacross)
390 printfcn = printacol;
391 else if (f_longform)
392 printfcn = printlong;
393 else if (f_stream)
394 printfcn = printstream;
395 else
396 printfcn = printcol;
397
398 if (argc)
399 traverse(argc, argv, fts_options);
400 else
401 traverse(1, dotav, fts_options);
402 return rval;
403 /* NOTREACHED */
404 }
405
406 static int output; /* If anything output. */
407
408 /*
409 * Traverse() walks the logical directory structure specified by the argv list
410 * in the order specified by the mastercmp() comparison function. During the
411 * traversal it passes linked lists of structures to display() which represent
412 * a superset (may be exact set) of the files to be displayed.
413 */
414 static void
415 traverse(int argc, char *argv[], int options)
416 {
417 FTS *ftsp;
418 FTSENT *p, *chp;
419 int ch_options, error;
420
421 if ((ftsp =
422 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
423 err(EXIT_FAILURE, NULL);
424
425 display(NULL, fts_children(ftsp, 0));
426 if (f_listdir) {
427 (void)fts_close(ftsp);
428 return;
429 }
430
431 /*
432 * If not recursing down this tree and don't need stat info, just get
433 * the names.
434 */
435 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
436
437 while ((p = fts_read(ftsp)) != NULL)
438 switch (p->fts_info) {
439 case FTS_DC:
440 warnx("%s: directory causes a cycle", p->fts_name);
441 break;
442 case FTS_DNR:
443 case FTS_ERR:
444 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
445 rval = EXIT_FAILURE;
446 break;
447 case FTS_D:
448 if (p->fts_level != FTS_ROOTLEVEL &&
449 p->fts_name[0] == '.' && !f_listdot)
450 break;
451
452 /*
453 * If already output something, put out a newline as
454 * a separator. If multiple arguments, precede each
455 * directory with its name.
456 */
457 if (!f_leafonly) {
458 if (output)
459 (void)printf("\n%s:\n", p->fts_path);
460 else if (argc > 1) {
461 (void)printf("%s:\n", p->fts_path);
462 output = 1;
463 }
464 }
465
466 chp = fts_children(ftsp, ch_options);
467 display(p, chp);
468
469 if (!f_recursive && chp != NULL)
470 (void)fts_set(ftsp, p, FTS_SKIP);
471 break;
472 }
473 error = errno;
474 (void)fts_close(ftsp);
475 errno = error;
476 if (errno)
477 err(EXIT_FAILURE, "fts_read");
478 }
479
480 /*
481 * Display() takes a linked list of FTSENT structures and passes the list
482 * along with any other necessary information to the print function. P
483 * points to the parent directory of the display list.
484 */
485 static void
486 display(FTSENT *p, FTSENT *list)
487 {
488 struct stat *sp;
489 DISPLAY d;
490 FTSENT *cur;
491 NAMES *np;
492 u_int64_t btotal, stotal;
493 off_t maxsize;
494 blkcnt_t maxblock;
495 ino_t maxinode;
496 int maxmajor, maxminor;
497 uint32_t maxnlink;
498 int bcfile, entries, flen, glen, ulen, maxflags, maxgroup;
499 unsigned int maxlen;
500 int maxuser, needstats;
501 const char *user, *group;
502 char buf[21]; /* 64 bits == 20 digits, +1 for NUL */
503 char nuser[12], ngroup[12];
504 char *flags = NULL;
505
506 /*
507 * If list is NULL there are two possibilities: that the parent
508 * directory p has no children, or that fts_children() returned an
509 * error. We ignore the error case since it will be replicated
510 * on the next call to fts_read() on the post-order visit to the
511 * directory p, and will be signalled in traverse().
512 */
513 if (list == NULL)
514 return;
515
516 needstats = f_inode || f_longform || f_size;
517 flen = 0;
518 maxinode = maxnlink = 0;
519 bcfile = 0;
520 maxuser = maxgroup = maxflags = maxlen = 0;
521 btotal = stotal = maxblock = maxsize = 0;
522 maxmajor = maxminor = 0;
523 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
524 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
525 warnx("%s: %s",
526 cur->fts_name, strerror(cur->fts_errno));
527 cur->fts_number = NO_PRINT;
528 rval = EXIT_FAILURE;
529 continue;
530 }
531
532 /*
533 * P is NULL if list is the argv list, to which different rules
534 * apply.
535 */
536 if (p == NULL) {
537 /* Directories will be displayed later. */
538 if (cur->fts_info == FTS_D && !f_listdir) {
539 cur->fts_number = NO_PRINT;
540 continue;
541 }
542 } else {
543 /* Only display dot file if -a/-A set. */
544 if (cur->fts_name[0] == '.' && !f_listdot) {
545 cur->fts_number = NO_PRINT;
546 continue;
547 }
548 }
549 if (cur->fts_namelen > maxlen)
550 maxlen = cur->fts_namelen;
551 if (needstats) {
552 sp = cur->fts_statp;
553 if (sp->st_blocks > maxblock)
554 maxblock = sp->st_blocks;
555 if (sp->st_ino > maxinode)
556 maxinode = sp->st_ino;
557 if (sp->st_nlink > maxnlink)
558 maxnlink = sp->st_nlink;
559 if (sp->st_size > maxsize)
560 maxsize = sp->st_size;
561 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode)) {
562 bcfile = 1;
563 if (major(sp->st_rdev) > maxmajor)
564 maxmajor = major(sp->st_rdev);
565 if (minor(sp->st_rdev) > maxminor)
566 maxminor = minor(sp->st_rdev);
567 }
568
569 btotal += sp->st_blocks;
570 stotal += sp->st_size;
571 if (f_longform) {
572 if (f_numericonly ||
573 (user = user_from_uid(sp->st_uid, 0)) ==
574 NULL) {
575 (void)snprintf(nuser, sizeof(nuser),
576 "%u", sp->st_uid);
577 user = nuser;
578 }
579 if (f_numericonly ||
580 (group = group_from_gid(sp->st_gid, 0)) ==
581 NULL) {
582 (void)snprintf(ngroup, sizeof(ngroup),
583 "%u", sp->st_gid);
584 group = ngroup;
585 }
586 if ((ulen = strlen(user)) > maxuser)
587 maxuser = ulen;
588 if ((glen = strlen(group)) > maxgroup)
589 maxgroup = glen;
590 if (f_flags) {
591 flags =
592 flags_to_string((u_long)sp->st_flags, "-");
593 if ((flen = strlen(flags)) > maxflags)
594 maxflags = flen;
595 } else
596 flen = 0;
597
598 if ((np = malloc(sizeof(NAMES) +
599 ulen + glen + flen + 2)) == NULL)
600 err(EXIT_FAILURE, NULL);
601
602 np->user = &np->data[0];
603 (void)strcpy(np->user, user);
604 np->group = &np->data[ulen + 1];
605 (void)strcpy(np->group, group);
606
607 if (f_flags) {
608 np->flags = &np->data[ulen + glen + 2];
609 (void)strcpy(np->flags, flags);
610 free(flags);
611 }
612 cur->fts_pointer = np;
613 }
614 }
615 ++entries;
616 }
617
618 if (!entries)
619 return;
620
621 d.list = list;
622 d.entries = entries;
623 d.maxlen = maxlen;
624 if (needstats) {
625 d.btotal = btotal;
626 d.stotal = stotal;
627 if (f_humanize) {
628 d.s_block = 4; /* min buf length for humanize_number */
629 } else {
630 (void)snprintf(buf, sizeof(buf), "%llu",
631 (long long)howmany(maxblock, blocksize));
632 d.s_block = strlen(buf);
633 if (f_commas) /* allow for commas before every third digit */
634 d.s_block += (d.s_block - 1) / 3;
635 }
636 d.s_flags = maxflags;
637 d.s_group = maxgroup;
638 (void)snprintf(buf, sizeof(buf), "%llu",
639 (unsigned long long)maxinode);
640 d.s_inode = strlen(buf);
641 (void)snprintf(buf, sizeof(buf), "%u", maxnlink);
642 d.s_nlink = strlen(buf);
643 if (f_humanize) {
644 d.s_size = 4; /* min buf length for humanize_number */
645 } else {
646 (void)snprintf(buf, sizeof(buf), "%llu",
647 (long long)maxsize);
648 d.s_size = strlen(buf);
649 if (f_commas) /* allow for commas before every third digit */
650 d.s_size += (d.s_size - 1) / 3;
651 }
652 d.s_user = maxuser;
653 if (bcfile) {
654 (void)snprintf(buf, sizeof(buf), "%u", maxmajor);
655 d.s_major = strlen(buf);
656 (void)snprintf(buf, sizeof(buf), "%u", maxminor);
657 d.s_minor = strlen(buf);
658 if (d.s_major + d.s_minor + 2 > d.s_size)
659 d.s_size = d.s_major + d.s_minor + 2;
660 else if (d.s_size - d.s_minor - 2 > d.s_major)
661 d.s_major = d.s_size - d.s_minor - 2;
662 } else {
663 d.s_major = 0;
664 d.s_minor = 0;
665 }
666 }
667
668 printfcn(&d);
669 output = 1;
670
671 if (f_longform)
672 for (cur = list; cur; cur = cur->fts_link)
673 free(cur->fts_pointer);
674 }
675
676 /*
677 * Ordering for mastercmp:
678 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
679 * as larger than directories. Within either group, use the sort function.
680 * All other levels use the sort function. Error entries remain unsorted.
681 */
682 static int
683 mastercmp(const FTSENT **a, const FTSENT **b)
684 {
685 int a_info, b_info;
686
687 a_info = (*a)->fts_info;
688 if (a_info == FTS_ERR)
689 return (0);
690 b_info = (*b)->fts_info;
691 if (b_info == FTS_ERR)
692 return (0);
693
694 if (a_info == FTS_NS || b_info == FTS_NS) {
695 if (b_info != FTS_NS)
696 return (1);
697 else if (a_info != FTS_NS)
698 return (-1);
699 else
700 return (namecmp(*a, *b));
701 }
702
703 if (a_info != b_info && !f_listdir &&
704 (*a)->fts_level == FTS_ROOTLEVEL) {
705 if (a_info == FTS_D)
706 return (1);
707 else if (b_info == FTS_D)
708 return (-1);
709 }
710 return (sortfcn(*a, *b));
711 }
712