• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  * Deviations from posix:
9  *   add -b (and default to it instead of -q for an unambiguous representation
10  *   that doesn't cause collisions)
11  *   add -Z -ll --color
12  *   Posix says the -l date format should vary based on how recent it is
13  *   and we do --time-style=long-iso instead
14 
15 USE_LS(NEWTOY(ls, "(color):;(full-time)(show-control-chars)ZgoACFHLRSabcdfhikl@mnpqrstux1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL][!qb]", TOYFLAG_BIN|TOYFLAG_LOCALE))
16 
17 config LS
18   bool "ls"
19   default y
20   help
21     usage: ls [-ACFHLSZacdfhiklmnpqrstux1] [--color[=auto]] [directory...]
22 
23     List files.
24 
25     what to show:
26     -a  all files including .hidden    -b  escape nongraphic chars
27     -c  use ctime for timestamps       -d  directory, not contents
28     -i  inode number                   -p  put a '/' after dir names
29     -q  unprintable chars as '?'       -s  storage used (1024 byte units)
30     -u  use access time for timestamps -A  list all files but . and ..
31     -H  follow command line symlinks   -L  follow symlinks
32     -Z  security context
33 
34     output formats:
35     -1  list one file per line         -C  columns (sorted vertically)
36     -g  like -l but no owner           -h  human readable sizes
37     -l  long (show full details)       -m  comma separated
38     -n  like -l but numeric uid/gid    -o  like -l but no group
39     -x  columns (horizontal sort)      -ll long with nanoseconds (--full-time)
40     --color  device=yellow  symlink=turquoise/red  dir=blue  socket=purple
41              files: exe=green  suid=red  suidfile=redback  stickydir=greenback
42              =auto means detect if output is a tty.
43 
44     sorting (default is alphabetical):
45     -f  unsorted    -r  reverse    -t  timestamp    -S  size
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   long l;
57   char *color;
58 
59   struct dirtree *files, *singledir;
60   unsigned screen_width;
61   int nl_title;
62   char *escmore;
63 )
64 
65 // Callback from crunch_str to represent unprintable chars
crunch_qb(FILE * out,int cols,int wc)66 static int crunch_qb(FILE *out, int cols, int wc)
67 {
68   int len = 1;
69   char buf[32];
70 
71   if (FLAG(q)) *buf = '?';
72   else {
73     if (wc<256) *buf = wc;
74     // scrute the inscrutable, eff the ineffable, print the unprintable
75     else if ((len = wcrtomb(buf, wc, 0) ) == -1) len = 1;
76     if (FLAG(b)) {
77       char *to = buf, *from = buf+24;
78       int i, j;
79 
80       memcpy(from, to, 8);
81       for (i = 0; i<len; i++) {
82         *to++ = '\\';
83         if (strchr(TT.escmore, from[i])) *to++ = from[i];
84         else if (-1 != (j = stridx("\\\a\b\033\f\n\r\t\v", from[i])))
85           *to++ = "\\abefnrtv"[j];
86         else to += sprintf(to, "%03o", from[i]);
87       }
88       len = to-buf;
89     }
90   }
91 
92   if (cols<len) len = cols;
93   if (out) fwrite(buf, len, 1, out);
94 
95   return len;
96 }
97 
98 // Returns wcwidth(utf8) version of strlen with -qb escapes
strwidth(char * s)99 static int strwidth(char *s)
100 {
101   return crunch_str(&s, INT_MAX, 0, TT.escmore, crunch_qb);
102 }
103 
endtype(struct stat * st)104 static char endtype(struct stat *st)
105 {
106   mode_t mode = st->st_mode;
107   if ((FLAG(F)||FLAG(p)) && S_ISDIR(mode)) return '/';
108   if (FLAG(F)) {
109     if (S_ISLNK(mode)) return '@';
110     if (S_ISREG(mode) && (mode&0111)) return '*';
111     if (S_ISFIFO(mode)) return '|';
112     if (S_ISSOCK(mode)) return '=';
113   }
114   return 0;
115 }
116 
numlen(long long ll)117 static int numlen(long long ll)
118 {
119   return snprintf(0, 0, "%llu", ll);
120 }
121 
print_with_h(char * s,long long value,int units)122 static int print_with_h(char *s, long long value, int units)
123 {
124   if (FLAG(h)) return human_readable(s, value*units, 0);
125   else return sprintf(s, "%lld", value);
126 }
127 
128 // Figure out size of printable entry fields for display indent/wrap
129 
entrylen(struct dirtree * dt,unsigned * len)130 static void entrylen(struct dirtree *dt, unsigned *len)
131 {
132   struct stat *st = &(dt->st);
133   unsigned flags = toys.optflags;
134   char tmp[64];
135 
136   *len = strwidth(dt->name);
137   if (endtype(st)) ++*len;
138   if (flags & FLAG_m) ++*len;
139 
140   len[1] = (flags & FLAG_i) ? numlen(st->st_ino) : 0;
141   if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
142     unsigned fn = flags & FLAG_n;
143 
144     len[2] = numlen(st->st_nlink);
145     len[3] = fn ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
146     len[4] = fn ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
147     if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
148       // cheating slightly here: assuming minor is always 3 digits to avoid
149       // tracking another column
150       len[5] = numlen(dev_major(st->st_rdev))+5;
151     } else len[5] = print_with_h(tmp, st->st_size, 1);
152   }
153 
154   len[6] = (flags & FLAG_s) ? print_with_h(tmp, st->st_blocks, 512) : 0;
155   len[7] = (flags & FLAG_Z) ? strwidth((char *)dt->extra) : 0;
156 }
157 
compare(void * a,void * b)158 static int compare(void *a, void *b)
159 {
160   struct dirtree *dta = *(struct dirtree **)a;
161   struct dirtree *dtb = *(struct dirtree **)b;
162   int ret = 0, reverse = FLAG(r) ? -1 : 1;
163 
164   if (FLAG(S)) {
165     if (dta->st.st_size > dtb->st.st_size) ret = -1;
166     else if (dta->st.st_size < dtb->st.st_size) ret = 1;
167   }
168   if (FLAG(t)) {
169     if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
170     else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
171     else if (dta->st.st_mtim.tv_nsec > dtb->st.st_mtim.tv_nsec) ret = -1;
172     else if (dta->st.st_mtim.tv_nsec < dtb->st.st_mtim.tv_nsec) ret = 1;
173   }
174   if (!ret) ret = strcmp(dta->name, dtb->name);
175   return ret * reverse;
176 }
177 
178 // callback from dirtree_recurse() determining how to handle this entry.
179 
filter(struct dirtree * new)180 static int filter(struct dirtree *new)
181 {
182   int flags = toys.optflags;
183 
184   // Special case to handle enormous dirs without running out of memory.
185   if (flags == (FLAG_1|FLAG_f)) {
186     xprintf("%s\n", new->name);
187     return 0;
188   }
189 
190   if (flags & FLAG_Z) {
191     if (!CFG_TOYBOX_LSM_NONE) {
192 
193       // (Wouldn't it be nice if the lsm functions worked like openat(),
194       // fchmodat(), mknodat(), readlinkat() so we could do this without
195       // even O_PATH? But no, this is 1990's tech.)
196       int fd = openat(dirtree_parentfd(new), new->name,
197         O_PATH|(O_NOFOLLOW*!FLAG(L)));
198 
199       if (fd != -1) {
200         if (-1 == lsm_fget_context(fd, (char **)&new->extra) && errno == EBADF)
201         {
202           char hack[32];
203 
204           // Work around kernel bug that won't let us read this "metadata" from
205           // the filehandle unless we have permission to read the data. (We can
206           // query the same data in by path, but can't do it through an O_PATH
207           // filehandle, because reasons. But for some reason, THIS is ok? If
208           // they ever fix the kernel, this should stop triggering.)
209 
210           sprintf(hack, "/proc/self/fd/%d", fd);
211           lsm_lget_context(hack, (char **)&new->extra);
212         }
213         close(fd);
214       }
215     }
216     if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
217   }
218 
219   if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
220   if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
221   new->st.st_blocks >>= 1;
222 
223   if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
224   if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
225 
226   return dirtree_notdotdot(new) & DIRTREE_SAVE;
227 }
228 
229 // For column view, calculate horizontal position (for padding) and return
230 // index of next entry to display.
231 
next_column(unsigned long ul,unsigned long dtlen,unsigned columns,unsigned * xpos)232 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
233   unsigned columns, unsigned *xpos)
234 {
235   unsigned long transition;
236   unsigned height, widecols;
237 
238   // Horizontal sort is easy
239   if (!FLAG(C)) {
240     *xpos = ul % columns;
241     return ul;
242   }
243 
244   // vertical sort
245 
246   // For -x, calculate height of display, rounded up
247   height = (dtlen+columns-1)/columns;
248 
249   // Sanity check: does wrapping render this column count impossible
250   // due to the right edge wrapping eating a whole row?
251   if (height*columns - dtlen >= height) {
252     *xpos = columns;
253     return 0;
254   }
255 
256   // Uneven rounding goes along right edge
257   widecols = dtlen % height;
258   if (!widecols) widecols = height;
259   transition = widecols * columns;
260   if (ul < transition) {
261     *xpos =  ul % columns;
262     return (*xpos*height) + (ul/columns);
263   }
264 
265   ul -= transition;
266   *xpos = ul % (columns-1);
267 
268   return (*xpos*height) + widecols + (ul/(columns-1));
269 }
270 
color_from_mode(mode_t mode)271 static int color_from_mode(mode_t mode)
272 {
273   int color = 0;
274 
275   if (S_ISDIR(mode)) color = 256+34;
276   else if (S_ISLNK(mode)) color = 256+36;
277   else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
278   else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
279   else if (S_ISFIFO(mode)) color = 33;
280   else if (S_ISSOCK(mode)) color = 256+35;
281 
282   return color;
283 }
284 
zprint(int zap,char * pat,int len,unsigned long arg)285 static void zprint(int zap, char *pat, int len, unsigned long arg)
286 {
287   char tmp[32];
288 
289   sprintf(tmp, "%%*%s", zap ? "s" : pat);
290   if (zap && pat[strlen(pat)-1]==' ') strcat(tmp, " ");
291   printf(tmp, len, zap ? (unsigned long)"?" : arg);
292 }
293 
294 // Display a list of dirtree entries, according to current format
295 // Output types -1, -l, -C, or stream
296 
listfiles(int dirfd,struct dirtree * indir)297 static void listfiles(int dirfd, struct dirtree *indir)
298 {
299   struct dirtree *dt, **sort;
300   unsigned long dtlen, ul = 0;
301   unsigned width, flags = toys.optflags, totals[8], len[8], totpad = 0,
302     *colsizes = (unsigned *)toybuf, columns = sizeof(toybuf)/4;
303   char tmp[64];
304 
305   if (-1 == dirfd) {
306     perror_msg_raw(indir->name);
307 
308     return;
309   }
310 
311   memset(totals, 0, sizeof(totals));
312   if (CFG_TOYBOX_DEBUG) memset(len, 0, sizeof(len));
313 
314   // Top level directory was already populated by main()
315   if (!indir->parent) {
316     // Silently descend into single directory listed by itself on command line.
317     // In this case only show dirname/total header when given -R.
318     dt = indir->child;
319     if (dt && S_ISDIR(dt->st.st_mode) && !dt->next && !(flags&(FLAG_d|FLAG_R)))
320     {
321       listfiles(open(dt->name, O_DIRECTORY), TT.singledir = dt);
322       return;
323     }
324 
325     // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
326     for (;dt; dt = dt->next) filter(dt);
327     if (flags == (FLAG_1|FLAG_f)) return;
328   // Read directory contents. We dup() the fd because this will close it.
329   // This reads/saves contents to display later, except for in "ls -1f" mode.
330   } else dirtree_recurse(indir, filter, dup(dirfd),
331       DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
332 
333   // Copy linked list to array and sort it. Directories go in array because
334   // we visit them in sorted order too. (The nested loops let us measure and
335   // fill with the same inner loop.)
336   for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
337     for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
338       if (sort) sort[dtlen] = dt;
339     if (sort || !dtlen) break;
340   }
341 
342   // Label directory if not top of tree, or if -R
343   if (indir->parent && (TT.singledir!=indir || (flags&FLAG_R)))
344   {
345     char *path = dirtree_path(indir, 0);
346 
347     if (TT.nl_title++) xputc('\n');
348     xprintf("%s:\n", path);
349     free(path);
350   }
351 
352   // Measure each entry to work out whitespace padding and total blocks
353   if (!(flags & FLAG_f)) {
354     unsigned long long blocks = 0;
355 
356     qsort(sort, dtlen, sizeof(void *), (void *)compare);
357     for (ul = 0; ul<dtlen; ul++) {
358       entrylen(sort[ul], len);
359       for (width = 0; width<8; width++)
360         if (len[width]>totals[width]) totals[width] = len[width];
361       blocks += sort[ul]->st.st_blocks;
362     }
363     totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
364     if ((flags&(FLAG_h|FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent) {
365       print_with_h(tmp, blocks, 512);
366       xprintf("total %s\n", tmp);
367     }
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         // Add `2` to `totpad` to ensure two spaces between filenames
386         *len += totpad+2;
387         if (c == columns) break;
388         // Expand this column if necessary, break if that puts us over budget
389         if (*len > colsizes[c]) {
390           totlen += (*len)-colsizes[c];
391           colsizes[c] = *len;
392           if (totlen > TT.screen_width) break;
393         }
394       }
395       // If everything fit, stop here
396       if (ul == dtlen) break;
397     }
398   }
399 
400   // Loop through again to produce output.
401   width = 0;
402   for (ul = 0; ul<dtlen; ul++) {
403     int ii, zap;
404     unsigned curcol, color = 0;
405     unsigned long next = next_column(ul, dtlen, columns, &curcol);
406     struct stat *st = &(sort[next]->st);
407     mode_t mode = st->st_mode;
408     char et = endtype(st), *ss;
409 
410     // If we couldn't stat, output ? for most fields
411     zap = 0;
412     // Skip directories at the top of the tree when -d isn't set
413     if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
414     TT.nl_title=1;
415 
416     // Handle padding and wrapping for display purposes
417     entrylen(sort[next], len);
418     if (ul) {
419       int mm = !!(flags & FLAG_m);
420 
421       if (mm) xputc(',');
422       if (flags & (FLAG_C|FLAG_x)) {
423         if (!curcol) xputc('\n');
424       } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
425         xputc('\n');
426         width = 0;
427       } else {
428         printf("  "+mm, 0); // shut up the stupid compiler
429         width += 2-mm;
430       }
431     }
432     width += *len;
433 
434     if (flags & FLAG_i) zprint(zap, "lu ", totals[1], st->st_ino);
435 
436     if (flags & FLAG_s) {
437       print_with_h(tmp, st->st_blocks, 512);
438       zprint(zap, "s ", totals[6], (unsigned long)tmp);
439     }
440 
441     if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
442 
443       // (long) is to coerce the st types into something we know we can print.
444       mode_to_string(mode, tmp);
445       if (zap) memset(tmp+1, '?', 9);
446       printf("%s", tmp);
447       zprint(zap, "ld", totals[2]+1, st->st_nlink);
448 
449       // print user
450       if (!(flags&FLAG_g)) {
451         putchar(' ');
452         ii = -totals[3];
453         if (zap || (flags&FLAG_n)) zprint(zap, "lu", ii, st->st_uid);
454         else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
455                            crunch_qb);
456       }
457 
458       // print group
459       if (!(flags&FLAG_o)) {
460         putchar(' ');
461         ii = -totals[4];
462         if (zap || (flags&FLAG_n)) zprint(zap, "lu", ii, st->st_gid);
463         else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
464                            crunch_qb);
465       }
466     }
467     if (FLAG(Z))
468       printf(" %-*s "+!FLAG(l), -(int)totals[7], (char *)sort[next]->extra);
469 
470     if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
471       struct tm *tm;
472 
473       // print major/minor, or size
474       if (!zap && (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)))
475         printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
476           dev_minor(st->st_rdev));
477       else {
478         print_with_h(tmp, st->st_size, 1);
479         zprint(zap, "s", totals[5]+1, (unsigned long)tmp);
480       }
481 
482       // print time, always in --time-style=long-iso
483       tm = localtime(&(st->st_mtime));
484       strftime(tmp, sizeof(tmp), " %F %H:%M", tm);
485       if (TT.l>1) {
486         char *s = tmp+strlen(tmp);
487 
488         s += sprintf(s, ":%02d.%09d ", tm->tm_sec, (int)st->st_mtim.tv_nsec);
489         strftime(s, sizeof(tmp)-(s-tmp), "%z", tm);
490       }
491       zprint(zap, "s ", 17+(TT.l>1)*13, (unsigned long)tmp);
492     }
493 
494     if (flags & FLAG_color) {
495       color = color_from_mode(st->st_mode);
496       if (color) printf("\033[%d;%dm", color>>8, color&255);
497     }
498 
499     ss = sort[next]->name;
500     crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
501     if (color) printf("\033[0m");
502 
503     if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
504       printf(" -> ");
505       if (!zap && (flags & FLAG_color)) {
506         struct stat st2;
507 
508         if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
509         else color = color_from_mode(st2.st_mode);
510 
511         if (color) printf("\033[%d;%dm", color>>8, color&255);
512       }
513 
514       zprint(zap, "s", 0, (unsigned long)sort[next]->symlink);
515       if (!zap && color) printf("\033[0m");
516     }
517 
518     if (et) xputc(et);
519 
520     // Pad columns
521     if (flags & (FLAG_C|FLAG_x)) {
522       curcol = colsizes[curcol]-(*len)-totpad;
523       if (curcol < 255) printf("%*c", curcol, ' ');
524     }
525   }
526 
527   if (width) xputc('\n');
528 
529   // Free directory entries, recursing first if necessary.
530 
531   for (ul = 0; ul<dtlen; free(sort[ul++])) {
532     if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
533 
534     // Recurse into dirs if at top of the tree or given -R
535     if (!indir->parent || ((flags&FLAG_R) && dirtree_notdotdot(sort[ul])))
536       listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
537     free((void *)sort[ul]->extra);
538   }
539   free(sort);
540   if (dirfd != AT_FDCWD) close(dirfd);
541 }
542 
ls_main(void)543 void ls_main(void)
544 {
545   char **s, *noargs[] = {".", 0};
546   struct dirtree *dt;
547 
548   if (FLAG(full_time)) {
549     toys.optflags |= FLAG_l;
550     TT.l = 2;
551   }
552 
553   // Do we have an implied -1
554   if (isatty(1)) {
555     if (!FLAG(show_control_chars)) toys.optflags |= FLAG_b;
556     if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g)) toys.optflags |= FLAG_1;
557     else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
558   } else {
559     if (!FLAG(m)) toys.optflags |= FLAG_1;
560     if (TT.color) toys.optflags ^= FLAG_color;
561   }
562 
563   TT.screen_width = 80;
564   terminal_size(&TT.screen_width, NULL);
565   if (TT.screen_width<2) TT.screen_width = 2;
566   if (FLAG(b)) TT.escmore = " \\";
567 
568   // The optflags parsing infrastructure should really do this for us,
569   // but currently it has "switch off when this is set", so "-dR" and "-Rd"
570   // behave differently
571   if (FLAG(d)) toys.optflags &= ~FLAG_R;
572 
573   // Iterate through command line arguments, collecting directories and files.
574   // Non-absolute paths are relative to current directory. Top of tree is
575   // a dummy node to collect command line arguments into pseudo-directory.
576   TT.files = dirtree_add_node(0, 0, 0);
577   TT.files->dirfd = AT_FDCWD;
578   for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
579     int sym = !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F))
580       || (toys.optflags&(FLAG_L|FLAG_H));
581 
582     dt = dirtree_add_node(0, *s, DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*sym);
583 
584     // note: double_list->prev temporarily goes in dirtree->parent
585     if (dt) {
586       if (dt->again&2) {
587         perror_msg_raw(*s);
588         free(dt);
589       } else dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
590     } else toys.exitval = 1;
591   }
592 
593   // Convert double_list into dirtree.
594   dlist_terminate(TT.files->child);
595   for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
596 
597   // Display the files we collected
598   listfiles(AT_FDCWD, TT.files);
599 
600   if (CFG_TOYBOX_FREE) free(TT.files);
601 }
602