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