OSDN Git Service

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