OSDN Git Service

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