1 /* ls.c - list files
2 *
3 * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
4 * Copyright 2012 Rob Landley <rob@landley.net>
5 *
6 * See http://opengroup.org/onlinepubs/9699919799/utilities/ls.html
7 *
8 * Deviations from posix:
9 * add -b (and default to it instead of -q for an unambiguous representation
10 * that doesn't cause collisions)
11 * add -Z -ll --color
12 * Posix says the -l date format should vary based on how recent it is
13 * and we do --time-style=long-iso instead
14
15 USE_LS(NEWTOY(ls, "(color):;(full-time)(show-control-chars)ZgoACFHLRSabcdfhikl@mnpqrstux1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL][!qb]", TOYFLAG_BIN|TOYFLAG_LOCALE))
16
17 config LS
18 bool "ls"
19 default y
20 help
21 usage: ls [-ACFHLRSZacdfhiklmnpqrstux1] [--color[=auto]] [directory...]
22
23 List files.
24
25 what to show:
26 -a all files including .hidden -b escape nongraphic chars
27 -c use ctime for timestamps -d directory, not contents
28 -i inode number -p put a '/' after dir names
29 -q unprintable chars as '?' -s storage used (1024 byte units)
30 -u use access time for timestamps -A list all files but . and ..
31 -H follow command line symlinks -L follow symlinks
32 -R recursively list in subdirs -F append /dir *exe @sym |FIFO
33 -Z security context
34
35 output formats:
36 -1 list one file per line -C columns (sorted vertically)
37 -g like -l but no owner -h human readable sizes
38 -l long (show full details) -m comma separated
39 -n like -l but numeric uid/gid -o like -l but no group
40 -x columns (horizontal sort) -ll long with nanoseconds (--full-time)
41 --color device=yellow symlink=turquoise/red dir=blue socket=purple
42 files: exe=green suid=red suidfile=redback stickydir=greenback
43 =auto means detect if output is a tty.
44
45 sorting (default is alphabetical):
46 -f unsorted -r reverse -t timestamp -S size
47 */
48
49 #define FOR_ls
50 #include "toys.h"
51
52 // test sst output (suid/sticky in ls flaglist)
53
54 // ls -lR starts .: then ./subdir:
55
56 GLOBALS(
57 long l;
58 char *color;
59
60 struct dirtree *files, *singledir;
61 unsigned screen_width;
62 int nl_title;
63 char *escmore;
64 )
65
66 // Callback from crunch_str to represent unprintable chars
crunch_qb(FILE * out,int cols,int wc)67 static int crunch_qb(FILE *out, int cols, int wc)
68 {
69 int len = 1;
70 char buf[32];
71
72 if (FLAG(q)) *buf = '?';
73 else {
74 if (wc<256) *buf = wc;
75 // scrute the inscrutable, eff the ineffable, print the unprintable
76 else if ((len = wcrtomb(buf, wc, 0) ) == -1) len = 1;
77 if (FLAG(b)) {
78 char *to = buf, *from = buf+24;
79 int i, j;
80
81 memcpy(from, to, 8);
82 for (i = 0; i<len; i++) {
83 *to++ = '\\';
84 if (strchr(TT.escmore, from[i])) *to++ = from[i];
85 else if (-1 != (j = stridx("\\\a\b\033\f\n\r\t\v", from[i])))
86 *to++ = "\\abefnrtv"[j];
87 else to += sprintf(to, "%03o", from[i]);
88 }
89 len = to-buf;
90 }
91 }
92
93 if (cols<len) len = cols;
94 if (out) fwrite(buf, len, 1, out);
95
96 return len;
97 }
98
99 // Returns wcwidth(utf8) version of strlen with -qb escapes
strwidth(char * s)100 static int strwidth(char *s)
101 {
102 return crunch_str(&s, INT_MAX, 0, TT.escmore, crunch_qb);
103 }
104
endtype(struct stat * st)105 static char endtype(struct stat *st)
106 {
107 mode_t mode = st->st_mode;
108 if ((FLAG(F)||FLAG(p)) && S_ISDIR(mode)) return '/';
109 if (FLAG(F)) {
110 if (S_ISLNK(mode)) return '@';
111 if (S_ISREG(mode) && (mode&0111)) return '*';
112 if (S_ISFIFO(mode)) return '|';
113 if (S_ISSOCK(mode)) return '=';
114 }
115 return 0;
116 }
117
numlen(long long ll)118 static int numlen(long long ll)
119 {
120 return snprintf(0, 0, "%llu", ll);
121 }
122
print_with_h(char * s,long long value,int units)123 static int print_with_h(char *s, long long value, int units)
124 {
125 if (FLAG(h)) return human_readable(s, value*units, 0);
126 else return sprintf(s, "%lld", value);
127 }
128
129 // Figure out size of printable entry fields for display indent/wrap
130
entrylen(struct dirtree * dt,unsigned * len)131 static void entrylen(struct dirtree *dt, unsigned *len)
132 {
133 struct stat *st = &(dt->st);
134 unsigned flags = toys.optflags;
135 char tmp[64];
136
137 *len = strwidth(dt->name);
138 if (endtype(st)) ++*len;
139 if (flags & FLAG_m) ++*len;
140
141 len[1] = (flags & FLAG_i) ? numlen(st->st_ino) : 0;
142 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
143 unsigned fn = flags & FLAG_n;
144
145 len[2] = numlen(st->st_nlink);
146 len[3] = fn ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
147 len[4] = fn ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
148 if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
149 // cheating slightly here: assuming minor is always 3 digits to avoid
150 // tracking another column
151 len[5] = numlen(dev_major(st->st_rdev))+5;
152 } else len[5] = print_with_h(tmp, st->st_size, 1);
153 }
154
155 len[6] = (flags & FLAG_s) ? print_with_h(tmp, st->st_blocks, 512) : 0;
156 len[7] = (flags & FLAG_Z) ? strwidth((char *)dt->extra) : 0;
157 }
158
compare(void * a,void * b)159 static int compare(void *a, void *b)
160 {
161 struct dirtree *dta = *(struct dirtree **)a;
162 struct dirtree *dtb = *(struct dirtree **)b;
163 int ret = 0, reverse = FLAG(r) ? -1 : 1;
164
165 if (FLAG(S)) {
166 if (dta->st.st_size > dtb->st.st_size) ret = -1;
167 else if (dta->st.st_size < dtb->st.st_size) ret = 1;
168 }
169 if (FLAG(t)) {
170 if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
171 else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
172 else if (dta->st.st_mtim.tv_nsec > dtb->st.st_mtim.tv_nsec) ret = -1;
173 else if (dta->st.st_mtim.tv_nsec < dtb->st.st_mtim.tv_nsec) ret = 1;
174 }
175 if (!ret) ret = strcmp(dta->name, dtb->name);
176 return ret * reverse;
177 }
178
179 // callback from dirtree_recurse() determining how to handle this entry.
180
filter(struct dirtree * new)181 static int filter(struct dirtree *new)
182 {
183 int flags = toys.optflags;
184
185 // Special case to handle enormous dirs without running out of memory.
186 if (flags == (FLAG_1|FLAG_f)) {
187 xprintf("%s\n", new->name);
188 return 0;
189 }
190
191 if (flags & FLAG_Z) {
192 if (!CFG_TOYBOX_LSM_NONE) {
193 #ifdef CUSTOM_GET_CONTEXT
194 const char * const path = dirtree_path(new, 0);
195
196 if (path) {
197 (FLAG(L) ? lsm_get_context : lsm_lget_context)(path, (char **)&new->extra);
198 }
199 #else
200 // (Wouldn't it be nice if the lsm functions worked like openat(),
201 // fchmodat(), mknodat(), readlinkat() so we could do this without
202 // even O_PATH? But no, this is 1990's tech.)
203 int fd = openat(dirtree_parentfd(new), new->name,
204 O_PATH|(O_NOFOLLOW*!FLAG(L)));
205
206 if (fd != -1) {
207 if (-1 == lsm_fget_context(fd, (char **)&new->extra) && errno == EBADF)
208 {
209 char hack[32];
210
211 // Work around kernel bug that won't let us read this "metadata" from
212 // the filehandle unless we have permission to read the data. (We can
213 // query the same data in by path, but can't do it through an O_PATH
214 // filehandle, because reasons. But for some reason, THIS is ok? If
215 // they ever fix the kernel, this should stop triggering.)
216
217 sprintf(hack, "/proc/self/fd/%d", fd);
218 lsm_lget_context(hack, (char **)&new->extra);
219 }
220 close(fd);
221 }
222 #endif
223 }
224 if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
225 }
226
227 if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
228 if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
229 new->st.st_blocks >>= 1;
230
231 if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
232 if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
233
234 return dirtree_notdotdot(new) & DIRTREE_SAVE;
235 }
236
237 // For column view, calculate horizontal position (for padding) and return
238 // index of next entry to display.
239
next_column(unsigned long ul,unsigned long dtlen,unsigned columns,unsigned * xpos)240 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
241 unsigned columns, unsigned *xpos)
242 {
243 unsigned long transition;
244 unsigned height, widecols;
245
246 // Horizontal sort is easy
247 if (!FLAG(C)) {
248 *xpos = ul % columns;
249 return ul;
250 }
251
252 // vertical sort
253
254 // For -x, calculate height of display, rounded up
255 height = (dtlen+columns-1)/columns;
256
257 // Sanity check: does wrapping render this column count impossible
258 // due to the right edge wrapping eating a whole row?
259 if (height*columns - dtlen >= height) {
260 *xpos = columns;
261 return 0;
262 }
263
264 // Uneven rounding goes along right edge
265 widecols = dtlen % height;
266 if (!widecols) widecols = height;
267 transition = widecols * columns;
268 if (ul < transition) {
269 *xpos = ul % columns;
270 return (*xpos*height) + (ul/columns);
271 }
272
273 ul -= transition;
274 *xpos = ul % (columns-1);
275
276 return (*xpos*height) + widecols + (ul/(columns-1));
277 }
278
color_from_mode(mode_t mode)279 static int color_from_mode(mode_t mode)
280 {
281 int color = 0;
282
283 if (S_ISDIR(mode)) color = 256+34;
284 else if (S_ISLNK(mode)) color = 256+36;
285 else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
286 else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
287 else if (S_ISFIFO(mode)) color = 33;
288 else if (S_ISSOCK(mode)) color = 256+35;
289
290 return color;
291 }
292
zprint(int zap,char * pat,int len,unsigned long arg)293 static void zprint(int zap, char *pat, int len, unsigned long arg)
294 {
295 char tmp[32];
296
297 sprintf(tmp, "%%*%s", zap ? "s" : pat);
298 if (zap && pat[strlen(pat)-1]==' ') strcat(tmp, " ");
299 printf(tmp, len, zap ? (unsigned long)"?" : arg);
300 }
301
302 // Display a list of dirtree entries, according to current format
303 // Output types -1, -l, -C, or stream
304
listfiles(int dirfd,struct dirtree * indir)305 static void listfiles(int dirfd, struct dirtree *indir)
306 {
307 struct dirtree *dt, **sort;
308 unsigned long dtlen, ul = 0;
309 unsigned width, flags = toys.optflags, totals[8], len[8], totpad = 0,
310 *colsizes = (unsigned *)toybuf, columns = sizeof(toybuf)/4;
311 char tmp[64];
312
313 if (-1 == dirfd) {
314 perror_msg_raw(indir->name);
315
316 return;
317 }
318
319 memset(totals, 0, sizeof(totals));
320 if (CFG_TOYBOX_DEBUG) memset(len, 0, sizeof(len));
321
322 // Top level directory was already populated by main()
323 if (!indir->parent) {
324 // Silently descend into single directory listed by itself on command line.
325 // In this case only show dirname/total header when given -R.
326 dt = indir->child;
327 if (dt && S_ISDIR(dt->st.st_mode) && !dt->next && !(flags&(FLAG_d|FLAG_R)))
328 {
329 listfiles(open(dt->name, 0), TT.singledir = dt);
330
331 return;
332 }
333
334 // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
335 for (;dt; dt = dt->next) filter(dt);
336 if (flags == (FLAG_1|FLAG_f)) return;
337 // Read directory contents. We dup() the fd because this will close it.
338 // This reads/saves contents to display later, except for in "ls -1f" mode.
339 } else dirtree_recurse(indir, filter, dup(dirfd),
340 DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
341
342 // Copy linked list to array and sort it. Directories go in array because
343 // we visit them in sorted order too. (The nested loops let us measure and
344 // fill with the same inner loop.)
345 for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
346 for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
347 if (sort) sort[dtlen] = dt;
348 if (sort || !dtlen) break;
349 }
350
351 // Label directory if not top of tree, or if -R
352 if (indir->parent && (TT.singledir!=indir || (flags&FLAG_R)))
353 {
354 char *path = dirtree_path(indir, 0);
355
356 if (TT.nl_title++) xputc('\n');
357 xprintf("%s:\n", path);
358 free(path);
359 }
360
361 // Measure each entry to work out whitespace padding and total blocks
362 if (!(flags & FLAG_f)) {
363 unsigned long long blocks = 0;
364
365 qsort(sort, dtlen, sizeof(void *), (void *)compare);
366 for (ul = 0; ul<dtlen; ul++) {
367 entrylen(sort[ul], len);
368 for (width = 0; width<8; width++)
369 if (len[width]>totals[width]) totals[width] = len[width];
370 blocks += sort[ul]->st.st_blocks;
371 }
372 totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
373 if ((flags&(FLAG_h|FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent) {
374 print_with_h(tmp, blocks, 512);
375 xprintf("total %s\n", tmp);
376 }
377 }
378
379 // Find largest entry in each field for display alignment
380 if (flags & (FLAG_C|FLAG_x)) {
381
382 // columns can't be more than toybuf can hold, or more than files,
383 // or > 1/2 screen width (one char filename, one space).
384 if (columns > TT.screen_width/2) columns = TT.screen_width/2;
385 if (columns > dtlen) columns = dtlen;
386
387 // Try to fit as many columns as we can, dropping down by one each time
388 for (;columns > 1; columns--) {
389 unsigned c, totlen = columns;
390
391 memset(colsizes, 0, columns*sizeof(unsigned));
392 for (ul=0; ul<dtlen; ul++) {
393 entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
394 // Add `2` to `totpad` to ensure two spaces between filenames
395 *len += totpad+2;
396 if (c == columns) break;
397 // Expand this column if necessary, break if that puts us over budget
398 if (*len > colsizes[c]) {
399 totlen += (*len)-colsizes[c];
400 colsizes[c] = *len;
401 if (totlen > TT.screen_width) break;
402 }
403 }
404 // If everything fit, stop here
405 if (ul == dtlen) break;
406 }
407 }
408
409 // Loop through again to produce output.
410 width = 0;
411 for (ul = 0; ul<dtlen; ul++) {
412 int ii, zap;
413 unsigned curcol, color = 0;
414 unsigned long next = next_column(ul, dtlen, columns, &curcol);
415 struct stat *st = &(sort[next]->st);
416 mode_t mode = st->st_mode;
417 char et = endtype(st), *ss;
418
419 // If we couldn't stat, output ? for most fields
420 zap = !st->st_blksize && !st->st_dev && !st->st_ino;
421
422 // Skip directories at the top of the tree when -d isn't set
423 if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
424 TT.nl_title=1;
425
426 // Handle padding and wrapping for display purposes
427 entrylen(sort[next], len);
428 if (ul) {
429 int mm = !!(flags & FLAG_m);
430
431 if (mm) xputc(',');
432 if (flags & (FLAG_C|FLAG_x)) {
433 if (!curcol) xputc('\n');
434 } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
435 xputc('\n');
436 width = 0;
437 } else {
438 printf(" "+mm, 0); // shut up the stupid compiler
439 width += 2-mm;
440 }
441 }
442 width += *len;
443
444 if (flags & FLAG_i) zprint(zap, "lu ", totals[1], st->st_ino);
445
446 if (flags & FLAG_s) {
447 print_with_h(tmp, st->st_blocks, 512);
448 zprint(zap, "s ", totals[6], (unsigned long)tmp);
449 }
450
451 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
452
453 // (long) is to coerce the st types into something we know we can print.
454 mode_to_string(mode, tmp);
455 if (zap) memset(tmp+1, '?', 9);
456 printf("%s", tmp);
457 zprint(zap, "ld", totals[2]+1, st->st_nlink);
458
459 // print user
460 if (!(flags&FLAG_g)) {
461 putchar(' ');
462 ii = -totals[3];
463 if (zap || (flags&FLAG_n)) zprint(zap, "lu", ii, st->st_uid);
464 else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
465 crunch_qb);
466 }
467
468 // print group
469 if (!(flags&FLAG_o)) {
470 putchar(' ');
471 ii = -totals[4];
472 if (zap || (flags&FLAG_n)) zprint(zap, "lu", ii, st->st_gid);
473 else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
474 crunch_qb);
475 }
476 }
477 if (FLAG(Z))
478 printf(" %-*s "+!FLAG(l), -(int)totals[7], (char *)sort[next]->extra);
479
480 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
481 struct tm *tm;
482
483 // print major/minor, or size
484 if (!zap && (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)))
485 printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
486 dev_minor(st->st_rdev));
487 else {
488 print_with_h(tmp, st->st_size, 1);
489 zprint(zap, "s", totals[5]+1, (unsigned long)tmp);
490 }
491
492 // print time, always in --time-style=long-iso
493 tm = localtime(&(st->st_mtime));
494 strftime(tmp, sizeof(tmp), " %F %H:%M", tm);
495 if (TT.l>1) {
496 char *s = tmp+strlen(tmp);
497
498 s += sprintf(s, ":%02d.%09d ", tm->tm_sec, (int)st->st_mtim.tv_nsec);
499 strftime(s, sizeof(tmp)-(s-tmp), "%z", tm);
500 }
501 zprint(zap, "s ", 17+(TT.l>1)*13, (unsigned long)tmp);
502 }
503
504 if (flags & FLAG_color) {
505 color = color_from_mode(st->st_mode);
506 if (color) printf("\033[%d;%dm", color>>8, color&255);
507 }
508
509 ss = sort[next]->name;
510 crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
511 if (color) printf("\033[0m");
512
513 if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
514 printf(" -> ");
515 if (!zap && (flags & FLAG_color)) {
516 struct stat st2;
517
518 if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
519 else color = color_from_mode(st2.st_mode);
520
521 if (color) printf("\033[%d;%dm", color>>8, color&255);
522 }
523
524 zprint(zap, "s", 0, (unsigned long)sort[next]->symlink);
525 if (!zap && color) printf("\033[0m");
526 }
527
528 if (et) xputc(et);
529
530 // Pad columns
531 if (flags & (FLAG_C|FLAG_x)) {
532 curcol = colsizes[curcol]-(*len)-totpad;
533 if (curcol < 255) printf("%*c", curcol, ' ');
534 }
535 }
536
537 if (width) xputc('\n');
538
539 // Free directory entries, recursing first if necessary.
540
541 for (ul = 0; ul<dtlen; free(sort[ul++])) {
542 if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
543
544 // Recurse into dirs if at top of the tree or given -R
545 if (!indir->parent || ((flags&FLAG_R) && dirtree_notdotdot(sort[ul])))
546 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
547 free((void *)sort[ul]->extra);
548 }
549 free(sort);
550 if (dirfd != AT_FDCWD) close(dirfd);
551 }
552
ls_main(void)553 void ls_main(void)
554 {
555 char **s, *noargs[] = {".", 0};
556 struct dirtree *dt;
557
558 if (FLAG(full_time)) {
559 toys.optflags |= FLAG_l;
560 TT.l = 2;
561 }
562
563 // Do we have an implied -1
564 if (isatty(1)) {
565 if (!FLAG(show_control_chars)) toys.optflags |= FLAG_b;
566 if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g)) toys.optflags |= FLAG_1;
567 else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
568 } else {
569 if (!FLAG(m)) toys.optflags |= FLAG_1;
570 if (TT.color) toys.optflags ^= FLAG_color;
571 }
572
573 TT.screen_width = 80;
574 terminal_size(&TT.screen_width, NULL);
575 if (TT.screen_width<2) TT.screen_width = 2;
576 if (FLAG(b)) TT.escmore = " \\";
577
578 // The optflags parsing infrastructure should really do this for us,
579 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
580 // behave differently
581 if (FLAG(d)) toys.optflags &= ~FLAG_R;
582
583 // Iterate through command line arguments, collecting directories and files.
584 // Non-absolute paths are relative to current directory. Top of tree is
585 // a dummy node to collect command line arguments into pseudo-directory.
586 TT.files = dirtree_add_node(0, 0, 0);
587 TT.files->dirfd = AT_FDCWD;
588 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
589 int sym = !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F))
590 || (toys.optflags&(FLAG_L|FLAG_H));
591
592 dt = dirtree_add_node(0, *s, DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*sym);
593
594 // note: double_list->prev temporarily goes in dirtree->parent
595 if (dt) {
596 if (dt->again&2) {
597 perror_msg_raw(*s);
598 free(dt);
599 } else dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
600 } else toys.exitval = 1;
601 }
602
603 // Convert double_list into dirtree.
604 dlist_terminate(TT.files->child);
605 for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
606
607 // Display the files we collected
608 listfiles(AT_FDCWD, TT.files);
609
610 if (CFG_TOYBOX_FREE) free(TT.files);
611 }
612