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