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