3 * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
4 * Copyright 2012 Rob Landley <rob@landley.net>
6 * See http://opengroup.org/onlinepubs/9699919799/utilities/ls.html
8 USE_LS(NEWTOY(ls, USE_LS_COLOR("(color):;")"ZgoACFHLRSabcdfhiklmnpqrstux1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL][!qb]", TOYFLAG_BIN|TOYFLAG_LOCALE))
14 usage: ls [-ACFHLRSZacdfhiklmnpqrstux1] [directory...]
19 -a all files including .hidden -b escape nongraphic chars
20 -c use ctime for timestamps -d directory, not contents
21 -i inode number -k block sizes in kilobytes
22 -p put a '/' after dir names -q unprintable chars as '?'
23 -s size (in blocks) -u use access time for timestamps
24 -A list all files but . and .. -H follow command line symlinks
25 -L follow symlinks -R recursively list files in subdirs
26 -F append /dir *exe @sym |FIFO -Z security context
29 -1 list one file per line -C columns (sorted vertically)
30 -g like -l but no owner -h human readable sizes
31 -l long (show full details) -m comma separated
32 -n like -l but numeric uid/gid -o like -l but no group
33 -x columns (horizontal sort)
35 sorting (default is alphabetical):
36 -f unsorted -r reverse -t timestamp -S size
43 usage: ls --color[=auto]
45 --color device=yellow symlink=turquoise/red dir=blue socket=purple
46 files: exe=green suid=red suidfile=redback stickydir=greenback
47 =auto means detect if output is a tty.
53 // test sst output (suid/sticky in ls flaglist)
55 // ls -lR starts .: then ./subdir:
60 struct dirtree *files, *singledir;
62 unsigned screen_width;
67 // Callback from crunch_str to represent unprintable chars
68 int crunch_qb(FILE *out, int cols, int wc)
73 if (toys.optflags&FLAG_q) *buf = '?';
75 if (wc<256) *buf = wc;
76 // scrute the inscrutable, eff the ineffable, print the unprintable
77 else len = wcrtomb(buf, wc, 0);
78 if (toys.optflags&FLAG_b) {
79 char *to = buf, *from = buf+24;
83 for (i = 0; i<len; i++) {
85 if (strchr(TT.escmore, from[i])) *to++ = from[i];
86 else if (-1 != (j = stridx("\\\a\b\033\f\n\r\t\v", from[i])))
87 *to++ = "\\abefnrtv"[j];
88 else to += sprintf(to, "%03o", from[i]);
94 if (cols<len) len = cols;
95 if (out) fwrite(buf, len, 1, out);
100 // Returns wcwidth(utf8) version of strlen with -qb escapes
101 int strwidth(char *s)
103 return crunch_str(&s, INT_MAX, 0, TT.escmore, crunch_qb);
106 void qbstr(char *s, int width)
108 draw_trim_esc(s, width, abs(width), TT.escmore, crunch_qb);
111 static char endtype(struct stat *st)
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 '=';
124 static int numlen(long long ll)
126 return snprintf(0, 0, "%llu", ll);
129 // Figure out size of printable entry fields for display indent/wrap
131 static void entrylen(struct dirtree *dt, unsigned *len)
133 struct stat *st = &(dt->st);
134 unsigned flags = toys.optflags;
137 *len = strwidth(dt->name);
138 if (endtype(st)) ++*len;
139 if (flags & FLAG_m) ++*len;
141 len[1] = (flags & FLAG_i) ? numlen(st->st_ino) : 0;
142 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
143 unsigned fn = flags & FLAG_n;
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 if (flags & FLAG_h) {
152 human_readable(tmp, st->st_size, 0);
153 len[5] = strwidth(tmp);
154 } else len[5] = numlen(st->st_size);
157 if (flags & FLAG_s) {
158 if (flags & FLAG_h) {
159 human_readable(tmp, st->st_blocks*512, 0);
160 len[6] = strwidth(tmp);
161 } else len[6] = numlen(st->st_blocks);
163 len[7] = (flags & FLAG_Z) ? strwidth((char *)dt->extra) : 0;
166 static int compare(void *a, void *b)
168 struct dirtree *dta = *(struct dirtree **)a;
169 struct dirtree *dtb = *(struct dirtree **)b;
170 int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
172 if (toys.optflags & FLAG_S) {
173 if (dta->st.st_size > dtb->st.st_size) ret = -1;
174 else if (dta->st.st_size < dtb->st.st_size) ret = 1;
176 if (toys.optflags & FLAG_t) {
177 if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
178 else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
180 if (!ret) ret = strcmp(dta->name, dtb->name);
181 return ret * reverse;
184 // callback from dirtree_recurse() determining how to handle this entry.
186 static int filter(struct dirtree *new)
188 int flags = toys.optflags;
190 // Special case to handle enormous dirs without running out of memory.
191 if (flags == (FLAG_1|FLAG_f)) {
192 xprintf("%s\n", new->name);
196 if (flags & FLAG_Z) {
197 if (!CFG_TOYBOX_LSM_NONE) {
199 // (Wouldn't it be nice if the lsm functions worked like openat(),
200 // fchmodat(), mknodat(), readlinkat() so we could do this without
201 // even O_PATH? But no, this is 1990's tech.)
202 int fd = openat(dirtree_parentfd(new), new->name,
203 O_PATH|(O_NOFOLLOW*!(toys.optflags&FLAG_L)));
206 if (-1 == lsm_fget_context(fd, (char **)&new->extra) && errno == EBADF)
210 // Work around kernel bug that won't let us read this "metadata" from
211 // the filehandle unless we have permission to read the data. (We can
212 // query the same data in by path, but can't do it through an O_PATH
213 // filehandle, because reasons. But for some reason, THIS is ok? If
214 // they ever fix the kernel, this should stop triggering.)
216 sprintf(hack, "/proc/self/fd/%d", fd);
217 lsm_lget_context(hack, (char **)&new->extra);
222 if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
225 if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
226 if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
227 if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
229 if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
230 if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
232 return dirtree_notdotdot(new) & DIRTREE_SAVE;
235 // For column view, calculate horizontal position (for padding) and return
236 // index of next entry to display.
238 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
239 unsigned columns, unsigned *xpos)
241 unsigned long transition;
242 unsigned height, widecols;
244 // Horizontal sort is easy
245 if (!(toys.optflags & FLAG_C)) {
246 *xpos = ul % columns;
252 // For -x, calculate height of display, rounded up
253 height = (dtlen+columns-1)/columns;
255 // Sanity check: does wrapping render this column count impossible
256 // due to the right edge wrapping eating a whole row?
257 if (height*columns - dtlen >= height) {
262 // Uneven rounding goes along right edge
263 widecols = dtlen % height;
264 if (!widecols) widecols = height;
265 transition = widecols * columns;
266 if (ul < transition) {
267 *xpos = ul % columns;
268 return (*xpos*height) + (ul/columns);
272 *xpos = ul % (columns-1);
274 return (*xpos*height) + widecols + (ul/(columns-1));
277 int color_from_mode(mode_t mode)
281 if (S_ISDIR(mode)) color = 256+34;
282 else if (S_ISLNK(mode)) color = 256+36;
283 else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
284 else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
285 else if (S_ISFIFO(mode)) color = 33;
286 else if (S_ISSOCK(mode)) color = 256+35;
291 // Display a list of dirtree entries, according to current format
292 // Output types -1, -l, -C, or stream
294 static void listfiles(int dirfd, struct dirtree *indir)
296 struct dirtree *dt, **sort;
297 unsigned long dtlen, ul = 0;
298 unsigned width, flags = toys.optflags, totals[8], len[8], totpad = 0,
299 *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
303 perror_msg_raw(indir->name);
308 memset(totals, 0, sizeof(totals));
309 if (CFG_TOYBOX_DEBUG) memset(len, 0, sizeof(len));
311 // Top level directory was already populated by main()
312 if (!indir->parent) {
313 // Silently descend into single directory listed by itself on command line.
314 // In this case only show dirname/total header when given -R.
316 if (dt && S_ISDIR(dt->st.st_mode) && !dt->next && !(flags&(FLAG_d|FLAG_R)))
318 listfiles(open(dt->name, 0), TT.singledir = dt);
323 // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
324 for (;dt; dt = dt->next) filter(dt);
325 if (flags == (FLAG_1|FLAG_f)) return;
326 // Read directory contents. We dup() the fd because this will close it.
327 // This reads/saves contents to display later, except for in "ls -1f" mode.
328 } else dirtree_recurse(indir, filter, dup(dirfd),
329 DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
331 // Copy linked list to array and sort it. Directories go in array because
332 // we visit them in sorted order too. (The nested loops let us measure and
333 // fill with the same inner loop.)
334 for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
335 for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
336 if (sort) sort[dtlen] = dt;
337 if (sort || !dtlen) break;
340 // Label directory if not top of tree, or if -R
341 if (indir->parent && (TT.singledir!=indir || (flags&FLAG_R)))
343 char *path = dirtree_path(indir, 0);
345 if (TT.nl_title++) xputc('\n');
346 xprintf("%s:\n", path);
350 // Measure each entry to work out whitespace padding and total blocks
351 if (!(flags & FLAG_f)) {
352 unsigned long long blocks = 0;
354 qsort(sort, dtlen, sizeof(void *), (void *)compare);
355 for (ul = 0; ul<dtlen; ul++) {
356 entrylen(sort[ul], len);
357 for (width = 0; width<8; width++)
358 if (len[width]>totals[width]) totals[width] = len[width];
359 blocks += sort[ul]->st.st_blocks;
361 totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
362 if ((flags&(FLAG_h|FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent) {
364 human_readable(tmp, blocks*512, 0);
365 xprintf("total %s\n", tmp);
366 } else xprintf("total %llu\n", blocks);
370 // Find largest entry in each field for display alignment
371 if (flags & (FLAG_C|FLAG_x)) {
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;
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;
382 memset(colsizes, 0, columns*sizeof(unsigned));
383 for (ul=0; ul<dtlen; ul++) {
384 entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
386 if (c == columns) break;
387 // Expand this column if necessary, break if that puts us over budget
388 if (*len > colsizes[c]) {
389 totlen += (*len)-colsizes[c];
391 if (totlen > TT.screen_width) break;
394 // If everything fit, stop here
395 if (ul == dtlen) break;
399 // Loop through again to produce output.
400 memset(toybuf, ' ', 256);
402 for (ul = 0; ul<dtlen; ul++) {
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;
410 // Skip directories at the top of the tree when -d isn't set
411 if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
414 // Handle padding and wrapping for display purposes
415 entrylen(sort[next], len);
417 if (flags & FLAG_m) xputc(',');
418 if (flags & (FLAG_C|FLAG_x)) {
419 if (!curcol) xputc('\n');
420 } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
431 xprintf("%*lu ", totals[1], (unsigned long)st->st_ino);
433 if (flags & FLAG_s) {
434 if (flags & FLAG_h) {
435 human_readable(tmp, st->st_blocks*512, 0);
436 xprintf("%*s ", totals[6], tmp);
437 } else xprintf("%*lu ", totals[6], (unsigned long)st->st_blocks);
440 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
443 // (long) is to coerce the st types into something we know we can print.
444 mode_to_string(mode, tmp);
445 printf("%s% *ld", tmp, totals[2]+1, (long)st->st_nlink);
448 if (!(flags&FLAG_g)) {
451 if (flags&FLAG_n) printf("%*u", ii, (unsigned)st->st_uid);
452 else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
457 if (!(flags&FLAG_o)) {
460 if (flags&FLAG_n) printf("%*u", ii, (unsigned)st->st_gid);
461 else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
466 printf(" %-*s", -(int)totals[7], (char *)sort[next]->extra);
468 // print major/minor, or size
469 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
470 printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
471 dev_minor(st->st_rdev));
472 else if (flags&FLAG_h) {
473 human_readable(tmp, st->st_size, 0);
474 xprintf("%*s", totals[5]+1, tmp);
475 } else printf("% *lld", totals[5]+1, (long long)st->st_size);
477 // print time, always in --time-style=long-iso
478 tm = localtime(&(st->st_mtime));
479 strftime(tmp, sizeof(tmp), "%F %H:%M", tm);
480 xprintf(" %s ", tmp);
481 } else if (flags & FLAG_Z)
482 printf("%-*s ", (int)totals[7], (char *)sort[next]->extra);
484 if (flags & FLAG_color) {
485 color = color_from_mode(st->st_mode);
486 if (color) printf("\033[%d;%dm", color>>8, color&255);
489 ss = sort[next]->name;
490 crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
491 if (color) xprintf("\033[0m");
493 if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
495 if (flags & FLAG_color) {
498 if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
499 else color = color_from_mode(st2.st_mode);
501 if (color) printf("\033[%d;%dm", color>>8, color&255);
504 printf("%s", sort[next]->symlink);
505 if (color) printf("\033[0m");
511 if (flags & (FLAG_C|FLAG_x)) {
512 curcol = colsizes[curcol]-(*len)-totpad;
513 if (curcol < 255) xprintf("%s", toybuf+255-curcol);
517 if (width) xputc('\n');
519 // Free directory entries, recursing first if necessary.
521 for (ul = 0; ul<dtlen; free(sort[ul++])) {
522 if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
524 // Recurse into dirs if at top of the tree or given -R
525 if (!indir->parent || ((flags&FLAG_R) && dirtree_notdotdot(sort[ul])))
526 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
527 free((void *)sort[ul]->extra);
530 if (dirfd != AT_FDCWD) close(dirfd);
535 char **s, *noargs[] = {".", 0};
538 TT.screen_width = 80;
539 terminal_size(&TT.screen_width, NULL);
540 if (TT.screen_width<2) TT.screen_width = 2;
541 if (toys.optflags&FLAG_b) TT.escmore = " \\";
543 // Do we have an implied -1
545 if (!(toys.optflags & FLAG_m)) toys.optflags |= FLAG_1;
546 if (TT.color) toys.optflags ^= FLAG_color;
547 } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
548 toys.optflags |= FLAG_1;
549 else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
550 // The optflags parsing infrastructure should really do this for us,
551 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
552 // behave differently
553 if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
555 // Iterate through command line arguments, collecting directories and files.
556 // Non-absolute paths are relative to current directory. Top of tree is
557 // a dummy node to collect command line arguments into pseudo-directory.
558 TT.files = dirtree_add_node(0, 0, 0);
559 TT.files->dirfd = AT_FDCWD;
560 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
561 int sym = !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F))
562 || (toys.optflags&(FLAG_L|FLAG_H));
564 dt = dirtree_add_node(0, *s, DIRTREE_SYMFOLLOW*sym);
566 // note: double_list->prev temporarirly goes in dirtree->parent
567 if (dt) dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
568 else toys.exitval = 1;
571 // Convert double_list into dirtree.
572 dlist_terminate(TT.files->child);
573 for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
575 // Display the files we collected
576 listfiles(AT_FDCWD, TT.files);
578 if (CFG_TOYBOX_FREE) free(TT.files);