OSDN Git Service

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