ls.c revision 31db579265fa9e0acea036faa486be26f508e67a
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
8USE_LS(NEWTOY(ls, USE_LS_COLOR("(color):;")"goACFHLRSacdfiklmnpqrstux1[-1Cglmnox][-cu][-ftS][-HL]", TOYFLAG_BIN|TOYFLAG_LOCALE))
9
10config 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
35config 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
54GLOBALS(
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// Does two things: 1) Returns wcwidth(utf8) version of strlen,
65// 2) replaces unprintable characters input string with '?' wildcard char.
66int strwidth(char *s)
67{
68  int total = 0, width, len;
69  wchar_t c;
70
71  if (!CFG_TOYBOX_I18N) {
72    total = strlen(s);
73    if (toys.optflags & FLAG_q) for (; *s; s++) if (!isprint(*s)) *s = '?';
74  } else while (*s) {
75    len = mbrtowc(&c, s, MB_CUR_MAX, 0);
76    if (len < 1 || (width = wcwidth(c)) < 0) {
77      total++;
78      if (toys.optflags & FLAG_q) *s = '?';
79      s++;
80    } else {
81      s += len;
82      total += width;
83    }
84  }
85
86  return total;
87}
88
89void dlist_to_dirtree(struct dirtree *parent)
90{
91  // Turn double_list into dirtree
92  struct dirtree *dt = parent->child;
93  if (dt) {
94    dt->parent->next = NULL;
95    while (dt) {
96      dt->parent = parent;
97      dt = dt->next;
98    }
99  }
100}
101
102static char endtype(struct stat *st)
103{
104  mode_t mode = st->st_mode;
105  if ((toys.optflags&(FLAG_F|FLAG_p)) && S_ISDIR(mode)) return '/';
106  if (toys.optflags & FLAG_F) {
107    if (S_ISLNK(mode)) return '@';
108    if (S_ISREG(mode) && (mode&0111)) return '*';
109    if (S_ISFIFO(mode)) return '|';
110    if (S_ISSOCK(mode)) return '=';
111  }
112  return 0;
113}
114
115static char *getusername(uid_t uid)
116{
117  struct passwd *pw = getpwuid(uid);
118
119  sprintf(TT.uid_buf, "%u", (unsigned)uid);
120  return pw ? pw->pw_name : TT.uid_buf;
121}
122
123static char *getgroupname(gid_t gid)
124{
125  struct group *gr = getgrgid(gid);
126
127  sprintf(TT.gid_buf, "%u", (unsigned)gid);
128  return gr ? gr->gr_name : TT.gid_buf;
129}
130
131// Figure out size of printable entry fields for display indent/wrap
132
133static void entrylen(struct dirtree *dt, unsigned *len)
134{
135  struct stat *st = &(dt->st);
136  unsigned flags = toys.optflags;
137
138  *len = strwidth(dt->name);
139  if (endtype(st)) ++*len;
140  if (flags & FLAG_m) ++*len;
141
142  if (flags & FLAG_i) *len += (len[1] = numlen(st->st_ino));
143  if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
144    unsigned fn = flags & FLAG_n;
145    len[2] = numlen(st->st_nlink);
146    len[3] = fn ? snprintf(0, 0, "%u", (unsigned)st->st_uid)
147                : strwidth(getusername(st->st_uid));
148    len[4] = fn ? snprintf(0, 0, "%u", (unsigned)st->st_gid)
149                : strwidth(getgroupname(st->st_gid));
150    if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
151      // cheating slightly here: assuming minor is always 3 digits to avoid
152      // tracking another column
153      len[5] = numlen(major(st->st_rdev))+5;
154    } else len[5] = numlen(st->st_size);
155  }
156  if (flags & FLAG_s) *len += (len[6] = numlen(st->st_blocks));
157}
158
159static 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
179static 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
202static 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
241int color_from_mode(mode_t mode)
242{
243  int color = 0;
244
245  if (S_ISDIR(mode)) color = 256+34;
246  else if (S_ISLNK(mode)) color = 256+36;
247  else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
248  else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
249  else if (S_ISFIFO(mode)) color = 33;
250  else if (S_ISSOCK(mode)) color = 256+35;
251
252  return color;
253}
254
255// Display a list of dirtree entries, according to current format
256// Output types -1, -l, -C, or stream
257
258static void listfiles(int dirfd, struct dirtree *indir)
259{
260  struct dirtree *dt, **sort = 0;
261  unsigned long dtlen = 0, ul = 0;
262  unsigned width, flags = toys.optflags, totals[7], len[7],
263    *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
264
265  memset(totals, 0, sizeof(totals));
266
267  // Silently descend into single directory listed by itself on command line.
268  // In this case only show dirname/total header when given -R.
269  if (!indir->parent) {
270    if (!(dt = indir->child)) return;
271    if (S_ISDIR(dt->st.st_mode) && !dt->next && !(flags & FLAG_d)) {
272      dt->extra = 1;
273      listfiles(open(dt->name, 0), dt);
274      return;
275    }
276  } else {
277    // Read directory contents. We dup() the fd because this will close it.
278    indir->data = dup(dirfd);
279    dirtree_recurse(indir, filter, (flags&FLAG_L));
280  }
281
282  // Copy linked list to array and sort it. Directories go in array because
283  // we visit them in sorted order.
284
285  for (;;) {
286    for (dt = indir->child; dt; dt = dt->next) {
287      if (sort) sort[dtlen] = dt;
288      dtlen++;
289    }
290    if (sort) break;
291    sort = xmalloc(dtlen * sizeof(void *));
292    dtlen = 0;
293    continue;
294  }
295
296  // Label directory if not top of tree, or if -R
297  if (indir->parent && (!indir->extra || (flags & FLAG_R)))
298  {
299    char *path = dirtree_path(indir, 0);
300
301    if (TT.nl_title++) xputc('\n');
302    xprintf("%s:\n", path);
303    free(path);
304  }
305
306  if (!(flags & FLAG_f)) qsort(sort, dtlen, sizeof(void *), (void *)compare);
307
308  // Find largest entry in each field for display alignment
309  if (flags & (FLAG_C|FLAG_x)) {
310
311    // columns can't be more than toybuf can hold, or more than files,
312    // or > 1/2 screen width (one char filename, one space).
313    if (columns > TT.screen_width/2) columns = TT.screen_width/2;
314    if (columns > dtlen) columns = dtlen;
315
316    // Try to fit as many columns as we can, dropping down by one each time
317    for (;columns > 1; columns--) {
318      unsigned c, totlen = columns;
319
320      memset(colsizes, 0, columns*sizeof(unsigned));
321      for (ul=0; ul<dtlen; ul++) {
322        entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
323        if (c == columns) break;
324        // Does this put us over budget?
325        if (*len > colsizes[c]) {
326          totlen += *len-colsizes[c];
327          colsizes[c] = *len;
328          if (totlen > TT.screen_width) break;
329        }
330      }
331      // If it fit, stop here
332      if (ul == dtlen) break;
333    }
334  } else if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) {
335    unsigned long blocks = 0;
336
337    for (ul = 0; ul<dtlen; ul++)
338    {
339      entrylen(sort[ul], len);
340      for (width=0; width<6; width++)
341        if (len[width] > totals[width]) totals[width] = len[width];
342      blocks += sort[ul]->st.st_blocks;
343    }
344
345    if (indir->parent) xprintf("total %lu\n", blocks);
346  }
347
348  // Loop through again to produce output.
349  memset(toybuf, ' ', 256);
350  width = 0;
351  for (ul = 0; ul<dtlen; ul++) {
352    unsigned curcol, color = 0;
353    unsigned long next = next_column(ul, dtlen, columns, &curcol);
354    struct stat *st = &(sort[next]->st);
355    mode_t mode = st->st_mode;
356    char et = endtype(st);
357
358    // Skip directories at the top of the tree when -d isn't set
359    if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
360    TT.nl_title=1;
361
362    // Handle padding and wrapping for display purposes
363    entrylen(sort[next], len);
364    if (ul) {
365      if (flags & FLAG_m) xputc(',');
366      if (flags & (FLAG_C|FLAG_x)) {
367        if (!curcol) xputc('\n');
368      } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
369        xputc('\n');
370        width = 0;
371      } else {
372        xputc(' ');
373        width++;
374      }
375    }
376    width += *len;
377
378    if (flags & FLAG_i) xprintf("% *lu ", len[1], (unsigned long)st->st_ino);
379    if (flags & FLAG_s) xprintf("% *lu ", len[6], (unsigned long)st->st_blocks);
380
381    if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
382      struct tm *tm;
383      char perm[11], thyme[64], *usr, *upad, *grp, *grpad;
384
385      mode_to_string(mode, perm);
386
387      if (flags&FLAG_o) grp = grpad = toybuf+256;
388      else {
389        if (flags&FLAG_n) sprintf(grp = thyme, "%u", (unsigned)st->st_gid);
390        else strwidth(grp = getgroupname(st->st_gid));
391        grpad = toybuf+256-(totals[4]-len[4]);
392      }
393
394      if (flags&FLAG_g) usr = upad = toybuf+256;
395      else {
396        upad = toybuf+255-(totals[3]-len[3]);
397        if (flags&FLAG_n) sprintf(usr = TT.uid_buf, "%u", (unsigned)st->st_uid);
398        else strwidth(usr = getusername(st->st_uid));
399      }
400
401      // Coerce the st types into something we know we can print.
402      printf("%s% *ld %s%s%s%s", perm, totals[2]+1, (long)st->st_nlink,
403             usr, upad, grp, grpad);
404
405      if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
406        printf("% *d,% 4d", totals[5]-4, major(st->st_rdev),minor(st->st_rdev));
407      else printf("% *"PRId64, totals[5]+1, (int64_t)st->st_size);
408
409      tm = localtime(&(st->st_mtime));
410      strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
411      xprintf(" %s ", thyme);
412    }
413
414    if (flags & FLAG_color) {
415      color = color_from_mode(st->st_mode);
416      if (color) printf("\033[%d;%dm", color>>8, color&255);
417    }
418
419    if (flags & FLAG_q) {
420      char *p;
421      for (p=sort[next]->name; *p; p++) fputc(isprint(*p) ? *p : '?', stdout);
422    } else xprintf("%s", sort[next]->name);
423    if (color) xprintf("\033[0m");
424
425    if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
426      printf(" -> ");
427      if (flags & FLAG_color) {
428        struct stat st2;
429
430        if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
431        else color = color_from_mode(st2.st_mode);
432
433        if (color) printf("\033[%d;%dm", color>>8, color&255);
434      }
435
436      printf("%s", sort[next]->symlink);
437      if (color) printf("\033[0m");
438    }
439
440    if (et) xputc(et);
441
442    // Pad columns
443    if (flags & (FLAG_C|FLAG_x)) {
444      curcol = colsizes[curcol] - *len;
445      if (curcol < 255) xprintf("%s", toybuf+255-curcol);
446    }
447  }
448
449  if (width) xputc('\n');
450
451  // Free directory entries, recursing first if necessary.
452
453  for (ul = 0; ul<dtlen; free(sort[ul++])) {
454    if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)
455      || !dirtree_notdotdot(sort[ul])) continue;
456
457    // Recurse into dirs if at top of the tree or given -R
458    if (!indir->parent || (flags & FLAG_R))
459      listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
460  }
461  free(sort);
462  if (dirfd != AT_FDCWD) close(dirfd);
463}
464
465void ls_main(void)
466{
467  char **s, *noargs[] = {".", 0};
468  struct dirtree *dt;
469
470  TT.screen_width = 80;
471  terminal_size(&TT.screen_width, NULL);
472  if (TT.screen_width<2) TT.screen_width = 2;
473
474  // Do we have an implied -1
475  if (!isatty(1)) {
476    toys.optflags |= FLAG_1;
477    if (TT.color) toys.optflags ^= FLAG_color;
478  } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
479    toys.optflags |= FLAG_1;
480  else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
481  // The optflags parsing infrastructure should really do this for us,
482  // but currently it has "switch off when this is set", so "-dR" and "-Rd"
483  // behave differently
484  if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
485
486  // Iterate through command line arguments, collecting directories and files.
487  // Non-absolute paths are relative to current directory.
488  TT.files = dirtree_add_node(0, 0, 0);
489  for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
490    dt = dirtree_add_node(0, *s,
491      (toys.optflags & (FLAG_L|FLAG_H|FLAG_l))^FLAG_l);
492
493    if (!dt) {
494      toys.exitval = 1;
495      continue;
496    }
497
498    // Typecast means double_list->prev temporarirly goes in dirtree->parent
499    dlist_add_nomalloc((void *)&TT.files->child, (struct double_list *)dt);
500  }
501
502  // Turn double_list into dirtree
503  dlist_to_dirtree(TT.files);
504
505  // Display the files we collected
506  listfiles(AT_FDCWD, TT.files);
507
508  if (CFG_TOYBOX_FREE) free(TT.files);
509}
510