OSDN Git Service

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