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