OSDN Git Service

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