OSDN Git Service

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