OSDN Git Service

Add ls -b and make ls -q work with utf8.
[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                   -k  block sizes in kilobytes
22     -p  put a '/' after dir names      -q  unprintable chars as '?'
23     -s  size (in blocks)               -u  use access time for timestamps
24     -A  list all files but . and ..    -H  follow command line symlinks
25     -L  follow symlinks                -R  recursively list files in subdirs
26     -F  append /dir *exe @sym |FIFO    -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 uid_buf[12], gid_buf[12], *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 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 // Figure out size of printable entry fields for display indent/wrap
146
147 static void entrylen(struct dirtree *dt, unsigned *len)
148 {
149   struct stat *st = &(dt->st);
150   unsigned flags = toys.optflags;
151   char tmp[64];
152
153   *len = strwidth(dt->name);
154   if (endtype(st)) ++*len;
155   if (flags & FLAG_m) ++*len;
156
157   len[1] = (flags & FLAG_i) ? numlen(st->st_ino) : 0;
158   if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
159     unsigned fn = flags & FLAG_n;
160     len[2] = numlen(st->st_nlink);
161     len[3] = fn ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
162     len[4] = fn ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
163     if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
164       // cheating slightly here: assuming minor is always 3 digits to avoid
165       // tracking another column
166       len[5] = numlen(dev_major(st->st_rdev))+5;
167     } else if (flags & FLAG_h) {
168         human_readable(tmp, st->st_size, 0);
169         len[5] = strwidth(tmp);
170     } else len[5] = numlen(st->st_size);
171   }
172
173   len[6] = (flags & FLAG_s) ? numlen(st->st_blocks) : 0;
174   len[7] = (flags & FLAG_Z) ? strwidth((char *)dt->extra) : 0;
175 }
176
177 static int compare(void *a, void *b)
178 {
179   struct dirtree *dta = *(struct dirtree **)a;
180   struct dirtree *dtb = *(struct dirtree **)b;
181   int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
182
183   if (toys.optflags & FLAG_S) {
184     if (dta->st.st_size > dtb->st.st_size) ret = -1;
185     else if (dta->st.st_size < dtb->st.st_size) ret = 1;
186   }
187   if (toys.optflags & FLAG_t) {
188     if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
189     else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
190   }
191   if (!ret) ret = strcmp(dta->name, dtb->name);
192   return ret * reverse;
193 }
194
195 // callback from dirtree_recurse() determining how to handle this entry.
196
197 static int filter(struct dirtree *new)
198 {
199   int flags = toys.optflags;
200
201   // Special case to handle enormous dirs without running out of memory.
202   if (flags == (FLAG_1|FLAG_f)) {
203     xprintf("%s\n", new->name);
204     return 0;
205   }
206
207   if (flags & FLAG_Z) {
208     if (!CFG_TOYBOX_LSM_NONE) {
209
210       // (Wouldn't it be nice if the lsm functions worked like openat(),
211       // fchmodat(), mknodat(), readlinkat() so we could do this without
212       // even O_PATH? But no, this is 1990's tech.)
213       int fd = openat(dirtree_parentfd(new), new->name,
214         O_PATH|(O_NOFOLLOW*!(toys.optflags&FLAG_L)));
215
216       if (fd != -1) {
217         if (-1 == lsm_fget_context(fd, (char **)&new->extra) && errno == EBADF)
218         {
219           char hack[32];
220
221           // Work around kernel bug that won't let us read this "metadata" from
222           // the filehandle unless we have permission to read the data. (We can
223           // query the same data in by path, but can't do it through an O_PATH
224           // filehandle, because reasons. But for some reason, THIS is ok? If
225           // they ever fix the kernel, this should stop triggering.)
226
227           sprintf(hack, "/proc/self/fd/%d", fd);
228           lsm_lget_context(hack, (char **)&new->extra);
229         }
230         close(fd);
231       }
232     }
233     if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
234   }
235
236   if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
237   if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
238   if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
239
240   if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
241   if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
242
243   return dirtree_notdotdot(new) & DIRTREE_SAVE;
244 }
245
246 // For column view, calculate horizontal position (for padding) and return
247 // index of next entry to display.
248
249 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
250   unsigned columns, unsigned *xpos)
251 {
252   unsigned long transition;
253   unsigned height, widecols;
254
255   // Horizontal sort is easy
256   if (!(toys.optflags & FLAG_C)) {
257     *xpos = ul % columns;
258     return ul;
259   }
260
261   // vertical sort
262
263   // For -x, calculate height of display, rounded up
264   height = (dtlen+columns-1)/columns;
265
266   // Sanity check: does wrapping render this column count impossible
267   // due to the right edge wrapping eating a whole row?
268   if (height*columns - dtlen >= height) {
269     *xpos = columns;
270     return 0;
271   }
272
273   // Uneven rounding goes along right edge
274   widecols = dtlen % height;
275   if (!widecols) widecols = height;
276   transition = widecols * columns;
277   if (ul < transition) {
278     *xpos =  ul % columns;
279     return (*xpos*height) + (ul/columns);
280   }
281
282   ul -= transition;
283   *xpos = ul % (columns-1);
284
285   return (*xpos*height) + widecols + (ul/(columns-1));
286 }
287
288 int color_from_mode(mode_t mode)
289 {
290   int color = 0;
291
292   if (S_ISDIR(mode)) color = 256+34;
293   else if (S_ISLNK(mode)) color = 256+36;
294   else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
295   else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
296   else if (S_ISFIFO(mode)) color = 33;
297   else if (S_ISSOCK(mode)) color = 256+35;
298
299   return color;
300 }
301
302 // Display a list of dirtree entries, according to current format
303 // Output types -1, -l, -C, or stream
304
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+260), columns = (sizeof(toybuf)-260)/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   } else {
338     // Read directory contents. We dup() the fd because this will close it.
339     // This reads/saves contents to display later, except for in "ls -1f" mode.
340     indir->dirfd = dup(dirfd);
341     dirtree_recurse(indir, filter, DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
342   }
343
344   // Copy linked list to array and sort it. Directories go in array because
345   // we visit them in sorted order too. (The nested loops let us measure and
346   // fill with the same inner loop.)
347   for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
348     for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
349       if (sort) sort[dtlen] = dt;
350     if (sort || !dtlen) break;
351   }
352
353   // Label directory if not top of tree, or if -R
354   if (indir->parent && (TT.singledir!=indir || (flags&FLAG_R)))
355   {
356     char *path = dirtree_path(indir, 0);
357
358     if (TT.nl_title++) xputc('\n');
359     xprintf("%s:\n", path);
360     free(path);
361   }
362
363   // Measure each entry to work out whitespace padding and total blocks
364   if (!(flags & FLAG_f)) {
365     unsigned long long blocks = 0;
366
367     qsort(sort, dtlen, sizeof(void *), (void *)compare);
368     for (ul = 0; ul<dtlen; ul++) {
369       entrylen(sort[ul], len);
370       for (width = 0; width<8; width++)
371         if (len[width]>totals[width]) totals[width] = len[width];
372       blocks += sort[ul]->st.st_blocks;
373     }
374     totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
375     if ((flags&(FLAG_h|FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent) {
376       if (flags&FLAG_h) {
377         human_readable(tmp, blocks*512, 0);
378         xprintf("total %s\n", tmp);
379       } else xprintf("total %llu\n", blocks);
380     }
381   }
382
383   // Find largest entry in each field for display alignment
384   if (flags & (FLAG_C|FLAG_x)) {
385
386     // columns can't be more than toybuf can hold, or more than files,
387     // or > 1/2 screen width (one char filename, one space).
388     if (columns > TT.screen_width/2) columns = TT.screen_width/2;
389     if (columns > dtlen) columns = dtlen;
390
391     // Try to fit as many columns as we can, dropping down by one each time
392     for (;columns > 1; columns--) {
393       unsigned c, totlen = columns;
394
395       memset(colsizes, 0, columns*sizeof(unsigned));
396       for (ul=0; ul<dtlen; ul++) {
397         entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
398         *len += totpad;
399         if (c == columns) break;
400         // Expand this column if necessary, break if that puts us over budget
401         if (*len > colsizes[c]) {
402           totlen += (*len)-colsizes[c];
403           colsizes[c] = *len;
404           if (totlen > TT.screen_width) break;
405         }
406       }
407       // If everything fit, stop here
408       if (ul == dtlen) break;
409     }
410   }
411
412   // Loop through again to produce output.
413   memset(toybuf, ' ', 256);
414   width = 0;
415   for (ul = 0; ul<dtlen; ul++) {
416     int ii;
417     unsigned curcol, color = 0;
418     unsigned long next = next_column(ul, dtlen, columns, &curcol);
419     struct stat *st = &(sort[next]->st);
420     mode_t mode = st->st_mode;
421     char et = endtype(st), *ss;
422
423     // Skip directories at the top of the tree when -d isn't set
424     if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
425     TT.nl_title=1;
426
427     // Handle padding and wrapping for display purposes
428     entrylen(sort[next], len);
429     if (ul) {
430       if (flags & FLAG_m) xputc(',');
431       if (flags & (FLAG_C|FLAG_x)) {
432         if (!curcol) xputc('\n');
433       } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
434         xputc('\n');
435         width = 0;
436       } else {
437         xputc(' ');
438         width++;
439       }
440     }
441     width += *len;
442
443     if (flags & FLAG_i)
444       xprintf("%*lu ", totals[1], (unsigned long)st->st_ino);
445     if (flags & FLAG_s)
446       xprintf("%*lu ", totals[6], (unsigned long)st->st_blocks);
447
448     if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
449       struct tm *tm;
450
451       // (long) is to coerce the st types into something we know we can print.
452       mode_to_string(mode, tmp);
453       printf("%s% *ld", tmp, totals[2]+1, (long)st->st_nlink);
454
455       // print user
456       if (!(flags&FLAG_g)) {
457         putchar(' ');
458         ii = -totals[3];
459         if (flags&FLAG_n) printf("%*u", ii, (unsigned)st->st_uid);
460         else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
461                            crunch_qb);
462       }
463
464       // print group
465       if (!(flags&FLAG_o)) {
466         putchar(' ');
467         ii = -totals[4];
468         if (flags&FLAG_n) printf("%*u", ii, (unsigned)st->st_gid);
469         else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
470                            crunch_qb);
471       }
472
473       if (flags & FLAG_Z)
474         printf(" %-*s", -(int)totals[7], (char *)sort[next]->extra);
475
476       // print major/minor, or size
477       if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
478         printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
479           dev_minor(st->st_rdev));
480       else if (flags&FLAG_h) {
481         human_readable(tmp, st->st_size, 0);
482         xprintf("%*s", totals[5]+1, tmp);
483       } else printf("% *lld", totals[5]+1, (long long)st->st_size);
484
485       // print time, always in --time-style=long-iso
486       tm = localtime(&(st->st_mtime));
487       strftime(tmp, sizeof(tmp), "%F %H:%M", tm);
488       xprintf(" %s ", tmp);
489     } else if (flags & FLAG_Z)
490       printf("%-*s ", (int)totals[7], (char *)sort[next]->extra);
491
492     if (flags & FLAG_color) {
493       color = color_from_mode(st->st_mode);
494       if (color) printf("\033[%d;%dm", color>>8, color&255);
495     }
496
497     ss = sort[next]->name;
498     crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
499     if (color) xprintf("\033[0m");
500
501     if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
502       printf(" -> ");
503       if (flags & FLAG_color) {
504         struct stat st2;
505
506         if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
507         else color = color_from_mode(st2.st_mode);
508
509         if (color) printf("\033[%d;%dm", color>>8, color&255);
510       }
511
512       printf("%s", sort[next]->symlink);
513       if (color) printf("\033[0m");
514     }
515
516     if (et) xputc(et);
517
518     // Pad columns
519     if (flags & (FLAG_C|FLAG_x)) {
520       curcol = colsizes[curcol]-(*len)-totpad;
521       if (curcol < 255) xprintf("%s", toybuf+255-curcol);
522     }
523   }
524
525   if (width) xputc('\n');
526
527   // Free directory entries, recursing first if necessary.
528
529   for (ul = 0; ul<dtlen; free(sort[ul++])) {
530     if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
531
532     // Recurse into dirs if at top of the tree or given -R
533     if (!indir->parent || ((flags&FLAG_R) && dirtree_notdotdot(sort[ul])))
534       listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
535     free((void *)sort[ul]->extra);
536   }
537   free(sort);
538   if (dirfd != AT_FDCWD) close(dirfd);
539 }
540
541 void ls_main(void)
542 {
543   char **s, *noargs[] = {".", 0};
544   struct dirtree *dt;
545
546   TT.screen_width = 80;
547   terminal_size(&TT.screen_width, NULL);
548   if (TT.screen_width<2) TT.screen_width = 2;
549   if (toys.optflags&FLAG_b) TT.escmore = " \\";
550
551   // Do we have an implied -1
552   if (!isatty(1)) {
553     if (!(toys.optflags & FLAG_m)) toys.optflags |= FLAG_1;
554     if (TT.color) toys.optflags ^= FLAG_color;
555   } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
556     toys.optflags |= FLAG_1;
557   else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
558   // The optflags parsing infrastructure should really do this for us,
559   // but currently it has "switch off when this is set", so "-dR" and "-Rd"
560   // behave differently
561   if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
562
563   // Iterate through command line arguments, collecting directories and files.
564   // Non-absolute paths are relative to current directory. Top of tree is
565   // a dummy node to collect command line arguments into pseudo-directory.
566   TT.files = dirtree_add_node(0, 0, 0);
567   TT.files->dirfd = AT_FDCWD;
568   for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
569     int sym = !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F))
570       || (toys.optflags&(FLAG_L|FLAG_H));
571
572     dt = dirtree_add_node(0, *s, DIRTREE_SYMFOLLOW*sym);
573
574     // note: double_list->prev temporarirly goes in dirtree->parent
575     if (dt) dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
576     else toys.exitval = 1;
577   }
578
579   // Convert double_list into dirtree.
580   dlist_terminate(TT.files->child);
581   for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
582
583   // Display the files we collected
584   listfiles(AT_FDCWD, TT.files);
585
586   if (CFG_TOYBOX_FREE) free(TT.files);
587 }