]> git.saurik.com Git - apple/file_cmds.git/blob - ls/ls.c
c943b9c91a6957448311538bd522e03212e9e755
[apple/file_cmds.git] / ls / ls.c
1 /* $NetBSD: ls.c,v 1.31 1998/08/19 01:44:19 thorpej 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.31 1998/08/19 01:44:19 thorpej Exp $");
50 #endif
51 #endif /* not lint */
52
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 #include <sys/ioctl.h>
56 #include <sys/param.h>
57
58 #include <dirent.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fts.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.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, "1ACFLRSTWacdfgiklnoqrstuxv")) != -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 case 'v':
229 f_nonprint = 0;
230 break;
231 default:
232 case '?':
233 usage();
234 }
235 }
236 argc -= optind;
237 argv += optind;
238
239 /*
240 * If not -F, -i, -l, -S, -s or -t options, don't require stat
241 * information.
242 */
243 if (!f_inode && !f_longform && !f_size && !f_type &&
244 sortkey == BY_NAME)
245 fts_options |= FTS_NOSTAT;
246
247 /*
248 * If not -F, -d or -l options, follow any symbolic links listed on
249 * the command line.
250 */
251 if (!f_longform && !f_listdir && !f_type)
252 fts_options |= FTS_COMFOLLOW;
253
254 /*
255 * If -W, show whiteout entries
256 */
257 #ifdef FTS_WHITEOUT
258 if (f_whiteout)
259 fts_options |= FTS_WHITEOUT;
260 #endif
261
262 /* If -l or -s, figure out block size. */
263 if (f_longform || f_size) {
264 if (!kflag)
265 (void)getbsize(&notused, &blocksize);
266 blocksize /= 512;
267 }
268
269 /* Select a sort function. */
270 if (f_reversesort) {
271 switch (sortkey) {
272 case BY_NAME:
273 sortfcn = revnamecmp;
274 break;
275 case BY_SIZE:
276 sortfcn = revsizecmp;
277 break;
278 case BY_TIME:
279 if (f_accesstime)
280 sortfcn = revacccmp;
281 else if (f_statustime)
282 sortfcn = revstatcmp;
283 else /* Use modification time. */
284 sortfcn = revmodcmp;
285 break;
286 }
287 } else {
288 switch (sortkey) {
289 case BY_NAME:
290 sortfcn = namecmp;
291 break;
292 case BY_SIZE:
293 sortfcn = sizecmp;
294 break;
295 case BY_TIME:
296 if (f_accesstime)
297 sortfcn = acccmp;
298 else if (f_statustime)
299 sortfcn = statcmp;
300 else /* Use modification time. */
301 sortfcn = modcmp;
302 break;
303 }
304 }
305
306 /* Select a print function. */
307 if (f_singlecol)
308 printfcn = printscol;
309 else if (f_columnacross)
310 printfcn = printacol;
311 else if (f_longform)
312 printfcn = printlong;
313 else
314 printfcn = printcol;
315
316 if (argc)
317 traverse(argc, argv, fts_options);
318 else
319 traverse(1, dotav, fts_options);
320 exit(0);
321 /* NOTREACHED */
322 }
323
324 static int output; /* If anything output. */
325
326 /*
327 * Traverse() walks the logical directory structure specified by the argv list
328 * in the order specified by the mastercmp() comparison function. During the
329 * traversal it passes linked lists of structures to display() which represent
330 * a superset (may be exact set) of the files to be displayed.
331 */
332 static void
333 traverse(argc, argv, options)
334 int argc, options;
335 char *argv[];
336 {
337 FTS *ftsp;
338 FTSENT *p, *chp;
339 int ch_options;
340 char pbuf[MAXPATHLEN + 1], *path;
341
342 if ((ftsp =
343 fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
344 err(1, "%s", "");
345
346 display(NULL, fts_children(ftsp, 0));
347 if (f_listdir)
348 return;
349
350 /*
351 * If not recursing down this tree and don't need stat info, just get
352 * the names.
353 */
354 ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
355
356 while ((p = fts_read(ftsp)) != NULL)
357 switch (p->fts_info) {
358 case FTS_DC:
359 warnx("%s: directory causes a cycle", p->fts_name);
360 break;
361 case FTS_DNR:
362 case FTS_ERR:
363 warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
364 break;
365 case FTS_D:
366 if (p->fts_level != FTS_ROOTLEVEL &&
367 p->fts_name[0] == '.' && !f_listdot)
368 break;
369
370 /*
371 * If already output something, put out a newline as
372 * a separator. If multiple arguments, precede each
373 * directory with its name.
374 */
375 if (f_nonprint) {
376 prcopy(p->fts_path, pbuf, p->fts_pathlen+1);
377 path = pbuf;
378 } else
379 path = p->fts_path;
380
381 if (output)
382 (void)printf("\n%s:\n", path);
383 else if (argc > 1) {
384 (void)printf("%s:\n", path);
385 output = 1;
386 }
387
388 chp = fts_children(ftsp, ch_options);
389 display(p, chp);
390
391 if (!f_recursive && chp != NULL)
392 (void)fts_set(ftsp, p, FTS_SKIP);
393 break;
394 }
395 if (errno)
396 err(1, "fts_read");
397 }
398
399 /*
400 * Display() takes a linked list of FTSENT structures and passes the list
401 * along with any other necessary information to the print function. P
402 * points to the parent directory of the display list.
403 */
404 static void
405 display(p, list)
406 FTSENT *p, *list;
407 {
408 struct stat *sp;
409 DISPLAY d;
410 FTSENT *cur;
411 NAMES *np;
412 u_int64_t btotal, maxblock, maxsize;
413 int maxinode, maxnlink, maxmajor, maxminor;
414 int bcfile, entries, flen, glen, ulen, maxflags, maxgroup, maxlen;
415 int maxuser, needstats;
416 const char *user, *group;
417 char ubuf[21]="", gbuf[21]="", buf[21]; /* 64 bits == 20 digits, +1 for NUL */
418 char nuser[12], ngroup[12];
419 char *flags = NULL;
420
421 #ifdef __GNUC__
422 /* This outrageous construct just to shut up a GCC warning. */
423 (void) &maxsize;
424 #endif
425
426 /*
427 * If list is NULL there are two possibilities: that the parent
428 * directory p has no children, or that fts_children() returned an
429 * error. We ignore the error case since it will be replicated
430 * on the next call to fts_read() on the post-order visit to the
431 * directory p, and will be signalled in traverse().
432 */
433 if (list == NULL)
434 return;
435
436 needstats = f_inode || f_longform || f_size;
437 flen = 0;
438 maxinode = maxnlink = 0;
439 bcfile = 0;
440 maxuser = maxgroup = maxflags = maxlen = 0;
441 btotal = maxblock = maxsize = 0;
442 maxmajor = maxminor = 0;
443 for (cur = list, entries = 0; cur; cur = cur->fts_link) {
444 if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
445 warnx("%s: %s",
446 cur->fts_name, strerror(cur->fts_errno));
447 cur->fts_number = NO_PRINT;
448 continue;
449 }
450
451 /*
452 * P is NULL if list is the argv list, to which different rules
453 * apply.
454 */
455 if (p == NULL) {
456 /* Directories will be displayed later. */
457 if (cur->fts_info == FTS_D && !f_listdir) {
458 cur->fts_number = NO_PRINT;
459 continue;
460 }
461 } else {
462 /* Only display dot file if -a/-A set. */
463 if (cur->fts_name[0] == '.' && !f_listdot) {
464 cur->fts_number = NO_PRINT;
465 continue;
466 }
467 }
468 if (cur->fts_namelen > maxlen)
469 maxlen = cur->fts_namelen;
470 if (needstats) {
471 sp = cur->fts_statp;
472 if (sp->st_blocks > maxblock)
473 maxblock = sp->st_blocks;
474 if (sp->st_ino > maxinode)
475 maxinode = sp->st_ino;
476 if (sp->st_nlink > maxnlink)
477 maxnlink = sp->st_nlink;
478 if (sp->st_size > maxsize)
479 maxsize = sp->st_size;
480 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode)) {
481 bcfile = 1;
482 if (major(sp->st_rdev) > maxmajor)
483 maxmajor = major(sp->st_rdev);
484 if (minor(sp->st_rdev) > maxminor)
485 maxminor = minor(sp->st_rdev);
486 }
487
488 btotal += sp->st_blocks;
489 if (f_longform) {
490 if (f_numericonly) {
491 (void)snprintf(nuser, sizeof(nuser),
492 "%u", sp->st_uid);
493 (void)snprintf(ngroup, sizeof(ngroup),
494 "%u", sp->st_gid);
495 user = nuser;
496 group = ngroup;
497 } else {
498 if ((user = user_from_uid(sp->st_uid, 0)) == NULL) {
499 (void)snprintf(ubuf, sizeof(ubuf), "%d", (int)sp->st_uid);
500 user = ubuf;
501 }
502 if ((group = group_from_gid(sp->st_gid, 0)) == NULL) {
503 (void)snprintf(gbuf, sizeof(gbuf), "%d", (int)sp->st_gid);
504 group = gbuf;
505 }
506 }
507 if ((ulen = strlen(user)) > maxuser)
508 maxuser = ulen;
509 if ((glen = strlen(group)) > maxgroup)
510 maxgroup = glen;
511 if (f_flags) {
512 flags =
513 flags_to_string(sp->st_flags, "-");
514 if ((flen = strlen(flags)) > maxflags)
515 maxflags = flen;
516 } else
517 flen = 0;
518
519 if ((np = malloc(sizeof(NAMES) +
520 ulen + glen + flen + 3)) == NULL)
521 err(1, "%s", "");
522
523 np->user = &np->data[0];
524 (void)strcpy(np->user, user);
525 np->group = &np->data[ulen + 1];
526 (void)strcpy(np->group, group);
527
528 if (f_flags) {
529 np->flags = &np->data[ulen + glen + 2];
530 (void)strcpy(np->flags, flags);
531 }
532 cur->fts_pointer = np;
533 }
534 }
535 ++entries;
536 }
537
538 if (!entries)
539 return;
540
541 d.list = list;
542 d.entries = entries;
543 d.maxlen = maxlen;
544 if (needstats) {
545 d.btotal = btotal;
546 (void)snprintf(buf, sizeof(buf), "%qu", (long long)maxblock);
547 d.s_block = strlen(buf);
548 d.s_flags = maxflags;
549 d.s_group = maxgroup;
550 (void)snprintf(buf, sizeof(buf), "%u", maxinode);
551 d.s_inode = strlen(buf);
552 (void)snprintf(buf, sizeof(buf), "%u", maxnlink);
553 d.s_nlink = strlen(buf);
554 (void)snprintf(buf, sizeof(buf), "%qu", (long long)maxsize);
555 d.s_size = strlen(buf);
556 d.s_user = maxuser;
557 if (bcfile) {
558 (void)snprintf(buf, sizeof(buf), "%u", maxmajor);
559 d.s_major = strlen(buf);
560 (void)snprintf(buf, sizeof(buf), "%u", maxminor);
561 d.s_minor = strlen(buf);
562 if (d.s_major + d.s_minor + 2 > d.s_size)
563 d.s_size = d.s_major + d.s_minor + 2;
564 else if (d.s_size - d.s_minor - 2 > d.s_major)
565 d.s_major = d.s_size - d.s_minor - 2;
566 } else {
567 d.s_major = 0;
568 d.s_minor = 0;
569 }
570 }
571
572 printfcn(&d);
573 output = 1;
574
575 if (f_longform)
576 for (cur = list; cur; cur = cur->fts_link)
577 free(cur->fts_pointer);
578 }
579
580 /*
581 * Ordering for mastercmp:
582 * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
583 * as larger than directories. Within either group, use the sort function.
584 * All other levels use the sort function. Error entries remain unsorted.
585 */
586 static int
587 mastercmp(a, b)
588 const FTSENT **a, **b;
589 {
590 int a_info, b_info;
591
592 a_info = (*a)->fts_info;
593 if (a_info == FTS_ERR)
594 return (0);
595 b_info = (*b)->fts_info;
596 if (b_info == FTS_ERR)
597 return (0);
598
599 if (a_info == FTS_NS || b_info == FTS_NS) {
600 if (b_info != FTS_NS)
601 return (1);
602 else if (a_info != FTS_NS)
603 return (-1);
604 else
605 return (namecmp(*a, *b));
606 }
607
608 if (a_info != b_info && !f_listdir &&
609 (*a)->fts_level == FTS_ROOTLEVEL) {
610 if (a_info == FTS_D)
611 return (1);
612 else if (b_info == FTS_D)
613 return (-1);
614 }
615 return (sortfcn(*a, *b));
616 }