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