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