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):;")"ZgoACFHLRSacdfiklmnpqrstux1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL]", TOYFLAG_BIN|TOYFLAG_LOCALE))
14 usage: ls [-ACFHLRSZacdfiklmnpqrstux1] [directory...]
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
28 -1 list one file per line -C columns (sorted vertically)
29 -g like -l but no owner -l long (show full details)
30 -m comma separated -n like -l but numeric uid/gid
31 -o like -l but no group -x columns (horizontal sort)
33 sorting (default is alphabetical):
34 -f unsorted -r reverse -t timestamp -S size
41 usage: ls --color[=auto]
43 --color device=yellow symlink=turquoise/red dir=blue socket=purple
44 files: exe=green suid=red suidfile=redback stickydir=greenback
45 =auto means detect if output is a tty.
52 // test sst output (suid/sticky in ls flaglist)
54 // ls -lR starts .: then ./subdir:
59 struct dirtree *files, *singledir;
61 unsigned screen_width;
63 char uid_buf[12], gid_buf[12];
66 // Does two things: 1) Returns wcwidth(utf8) version of strlen,
67 // 2) replaces unprintable characters input string with '?' wildcard char.
70 int total = 0, width, len;
73 if (!CFG_TOYBOX_I18N) {
75 if (toys.optflags & FLAG_q) for (; *s; s++) if (!isprint(*s)) *s = '?';
77 len = mbrtowc(&c, s, MB_CUR_MAX, 0);
78 if (len < 1 || (width = wcwidth(c)) < 0) {
80 if (toys.optflags & FLAG_q) *s = '?';
91 static char endtype(struct stat *st)
93 mode_t mode = st->st_mode;
94 if ((toys.optflags&(FLAG_F|FLAG_p)) && S_ISDIR(mode)) return '/';
95 if (toys.optflags & FLAG_F) {
96 if (S_ISLNK(mode)) return '@';
97 if (S_ISREG(mode) && (mode&0111)) return '*';
98 if (S_ISFIFO(mode)) return '|';
99 if (S_ISSOCK(mode)) return '=';
104 static char *getusername(uid_t uid)
106 struct passwd *pw = getpwuid(uid);
108 sprintf(TT.uid_buf, "%u", (unsigned)uid);
109 return pw ? pw->pw_name : TT.uid_buf;
112 static char *getgroupname(gid_t gid)
114 struct group *gr = getgrgid(gid);
116 sprintf(TT.gid_buf, "%u", (unsigned)gid);
117 return gr ? gr->gr_name : TT.gid_buf;
120 static int numlen(long long ll)
122 return snprintf(0, 0, "%llu", ll);
125 // Figure out size of printable entry fields for display indent/wrap
127 static void entrylen(struct dirtree *dt, unsigned *len)
129 struct stat *st = &(dt->st);
130 unsigned flags = toys.optflags;
132 *len = strwidth(dt->name);
133 if (endtype(st)) ++*len;
134 if (flags & FLAG_m) ++*len;
136 len[1] = (flags & FLAG_i) ? numlen(st->st_ino) : 0;
137 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
138 unsigned fn = flags & FLAG_n;
139 len[2] = numlen(st->st_nlink);
140 len[3] = fn ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
141 len[4] = fn ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
142 if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
143 // cheating slightly here: assuming minor is always 3 digits to avoid
144 // tracking another column
145 len[5] = numlen(major(st->st_rdev))+5;
146 } else len[5] = numlen(st->st_size);
149 len[6] = (flags & FLAG_s) ? numlen(st->st_blocks) : 0;
150 len[7] = (flags & FLAG_Z) ? strwidth((char *)dt->extra) : 0;
153 static int compare(void *a, void *b)
155 struct dirtree *dta = *(struct dirtree **)a;
156 struct dirtree *dtb = *(struct dirtree **)b;
157 int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
159 if (toys.optflags & FLAG_S) {
160 if (dta->st.st_size > dtb->st.st_size) ret = -1;
161 else if (dta->st.st_size < dtb->st.st_size) ret = 1;
163 if (toys.optflags & FLAG_t) {
164 if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
165 else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
167 if (!ret) ret = strcmp(dta->name, dtb->name);
168 return ret * reverse;
171 // callback from dirtree_recurse() determining how to handle this entry.
173 static int filter(struct dirtree *new)
175 int flags = toys.optflags;
177 // Special case to handle enormous dirs without running out of memory.
178 if (flags == (FLAG_1|FLAG_f)) {
179 xprintf("%s\n", new->name);
183 if (flags & FLAG_Z) {
184 if (!CFG_TOYBOX_LSM_NONE) {
185 // In theory we can just openat(O_PATH|O_NOFOLLOW) and getcontext() on
186 // that filehandle, but the kernel won't let us read this "metadata"
187 // unless we have permission to read the data, so we do these elaborate
188 // bug workarounds instead.
189 if (S_ISLNK(new->st.st_mode) && !(toys.optflags & FLAG_L)) {
192 // Wouldn't it be nice if the lsm functions worked like openat(),
193 // fchmodat(), mknodat(), readlinkat()... but no, this is 1990's tech.
194 path = dirtree_path(new, 0);
195 lsm_lget_context(path, (char **)&new->extra);
198 // Why O_NONBLOCK? No idea. Why not O_PATH|O_NOFOLLOW? Kernel's broken.
199 int fd = openat(dirtree_parentfd(new), new->name,
200 O_RDONLY|O_NONBLOCK|O_NOATIME);
202 if (fd != -1) lsm_fget_context(fd, (char **)&new->extra);
206 if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
209 if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
210 if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
211 if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
213 if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
214 if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
216 return dirtree_notdotdot(new) & DIRTREE_SAVE;
219 // For column view, calculate horizontal position (for padding) and return
220 // index of next entry to display.
222 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
223 unsigned columns, unsigned *xpos)
225 unsigned long transition;
226 unsigned height, widecols;
228 // Horizontal sort is easy
229 if (!(toys.optflags & FLAG_C)) {
230 *xpos = ul % columns;
236 // For -x, calculate height of display, rounded up
237 height = (dtlen+columns-1)/columns;
239 // Sanity check: does wrapping render this column count impossible
240 // due to the right edge wrapping eating a whole row?
241 if (height*columns - dtlen >= height) {
246 // Uneven rounding goes along right edge
247 widecols = dtlen % height;
248 if (!widecols) widecols = height;
249 transition = widecols * columns;
250 if (ul < transition) {
251 *xpos = ul % columns;
252 return (*xpos*height) + (ul/columns);
256 *xpos = ul % (columns-1);
258 return (*xpos*height) + widecols + (ul/(columns-1));
261 int color_from_mode(mode_t mode)
265 if (S_ISDIR(mode)) color = 256+34;
266 else if (S_ISLNK(mode)) color = 256+36;
267 else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
268 else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
269 else if (S_ISFIFO(mode)) color = 33;
270 else if (S_ISSOCK(mode)) color = 256+35;
275 // Display a list of dirtree entries, according to current format
276 // Output types -1, -l, -C, or stream
278 static void listfiles(int dirfd, struct dirtree *indir)
280 struct dirtree *dt, **sort;
281 unsigned long dtlen, ul = 0;
282 unsigned width, flags = toys.optflags, totals[8], len[8], totpad = 0,
283 *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
285 memset(totals, 0, sizeof(totals));
287 // Top level directory was already populated by main()
288 if (!indir->parent) {
289 // Silently descend into single directory listed by itself on command line.
290 // In this case only show dirname/total header when given -R.
292 if (S_ISDIR(dt->st.st_mode) && !dt->next && !(flags&(FLAG_d|FLAG_R))) {
293 listfiles(open(dt->name, 0), TT.singledir = dt);
298 // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
299 for (;dt; dt = dt->next) filter(dt);
300 if (flags == (FLAG_1|FLAG_f)) return;
302 // Read directory contents. We dup() the fd because this will close it.
303 // This reads/saves contents to display later, except for in "ls -1f" mode.
304 indir->data = dup(dirfd);
305 dirtree_recurse(indir, filter, DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
308 // Copy linked list to array and sort it. Directories go in array because
309 // we visit them in sorted order too. (The nested loops let us measure and
310 // fill with the same inner loop.)
311 for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
312 for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
313 if (sort) sort[dtlen] = dt;
317 // Label directory if not top of tree, or if -R
318 if (indir->parent && (TT.singledir!=indir || (flags&FLAG_R)))
320 char *path = dirtree_path(indir, 0);
322 if (TT.nl_title++) xputc('\n');
323 xprintf("%s:\n", path);
327 // Measure each entry to work out whitespace padding and total blocks
328 if (!(flags & FLAG_f)) {
329 unsigned long long blocks = 0;
331 qsort(sort, dtlen, sizeof(void *), (void *)compare);
332 for (ul = 0; ul<dtlen; ul++) {
333 entrylen(sort[ul], len);
334 for (width = 0; width<8; width++)
335 if (len[width]>totals[width]) totals[width] = len[width];
336 blocks += sort[ul]->st.st_blocks;
338 totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
339 if ((flags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent)
340 xprintf("total %llu\n", blocks);
343 // Find largest entry in each field for display alignment
344 if (flags & (FLAG_C|FLAG_x)) {
346 // columns can't be more than toybuf can hold, or more than files,
347 // or > 1/2 screen width (one char filename, one space).
348 if (columns > TT.screen_width/2) columns = TT.screen_width/2;
349 if (columns > dtlen) columns = dtlen;
351 // Try to fit as many columns as we can, dropping down by one each time
352 for (;columns > 1; columns--) {
353 unsigned c, totlen = columns;
355 memset(colsizes, 0, columns*sizeof(unsigned));
356 for (ul=0; ul<dtlen; ul++) {
357 entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
359 if (c == columns) break;
360 // Expand this column if necessary, break if that puts us over budget
361 if (*len > colsizes[c]) {
362 totlen += (*len)-colsizes[c];
364 if (totlen > TT.screen_width) break;
367 // If everything fit, stop here
368 if (ul == dtlen) break;
372 // Loop through again to produce output.
373 memset(toybuf, ' ', 256);
375 for (ul = 0; ul<dtlen; ul++) {
376 unsigned curcol, color = 0;
377 unsigned long next = next_column(ul, dtlen, columns, &curcol);
378 struct stat *st = &(sort[next]->st);
379 mode_t mode = st->st_mode;
380 char et = endtype(st);
382 // Skip directories at the top of the tree when -d isn't set
383 if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
386 // Handle padding and wrapping for display purposes
387 entrylen(sort[next], len);
389 if (flags & FLAG_m) xputc(',');
390 if (flags & (FLAG_C|FLAG_x)) {
391 if (!curcol) xputc('\n');
392 } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
403 xprintf("%*lu ", totals[1], (unsigned long)st->st_ino);
405 xprintf("%*lu ", totals[6], (unsigned long)st->st_blocks);
407 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
409 char perm[11], thyme[64], *usr, *upad, *grp, *grpad;
411 mode_to_string(mode, perm);
413 if (flags&FLAG_o) grp = grpad = toybuf+256;
415 if (flags&FLAG_n) sprintf(grp = thyme, "%u", (unsigned)st->st_gid);
416 else strwidth(grp = getgroupname(st->st_gid));
417 grpad = toybuf+256-(totals[4]-len[4]);
420 if (flags&FLAG_g) usr = upad = toybuf+256;
422 upad = toybuf+255-(totals[3]-len[3]);
423 if (flags&FLAG_n) sprintf(usr = TT.uid_buf, "%u", (unsigned)st->st_uid);
424 else strwidth(usr = getusername(st->st_uid));
427 // Coerce the st types into something we know we can print.
428 printf("%s% *ld %s%s%s%s", perm, totals[2]+1, (long)st->st_nlink,
429 usr, upad, grp, grpad);
432 printf("%*s ", -(int)totals[7], (char *)sort[next]->extra);
434 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
435 printf("% *d,% 4d", totals[5]-4, major(st->st_rdev),minor(st->st_rdev));
436 else printf("% *lld", totals[5]+1, (long long)st->st_size);
438 tm = localtime(&(st->st_mtime));
439 strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
440 xprintf(" %s ", thyme);
441 } else if (flags & FLAG_Z)
442 printf("%*s ", (int)totals[7], (char *)sort[next]->extra);
444 if (flags & FLAG_color) {
445 color = color_from_mode(st->st_mode);
446 if (color) printf("\033[%d;%dm", color>>8, color&255);
449 if (flags & FLAG_q) {
451 for (p=sort[next]->name; *p; p++) fputc(isprint(*p) ? *p : '?', stdout);
452 } else xprintf("%s", sort[next]->name);
453 if (color) xprintf("\033[0m");
455 if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
457 if (flags & FLAG_color) {
460 if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
461 else color = color_from_mode(st2.st_mode);
463 if (color) printf("\033[%d;%dm", color>>8, color&255);
466 printf("%s", sort[next]->symlink);
467 if (color) printf("\033[0m");
473 if (flags & (FLAG_C|FLAG_x)) {
474 curcol = colsizes[curcol]-(*len)-totpad;
475 if (curcol < 255) xprintf("%s", toybuf+255-curcol);
479 if (width) xputc('\n');
481 // Free directory entries, recursing first if necessary.
483 for (ul = 0; ul<dtlen; free(sort[ul++])) {
484 if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
486 // Recurse into dirs if at top of the tree or given -R
487 if (!indir->parent || ((flags&FLAG_R) && dirtree_notdotdot(sort[ul])))
488 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
489 free((void *)sort[ul]->extra);
492 if (dirfd != AT_FDCWD) close(dirfd);
497 char **s, *noargs[] = {".", 0};
500 TT.screen_width = 80;
501 terminal_size(&TT.screen_width, NULL);
502 if (TT.screen_width<2) TT.screen_width = 2;
504 // Do we have an implied -1
506 toys.optflags |= FLAG_1;
507 if (TT.color) toys.optflags ^= FLAG_color;
508 } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
509 toys.optflags |= FLAG_1;
510 else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
511 // The optflags parsing infrastructure should really do this for us,
512 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
513 // behave differently
514 if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
516 // Iterate through command line arguments, collecting directories and files.
517 // Non-absolute paths are relative to current directory.
518 TT.files = dirtree_start(0, 0);
519 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
520 dt = dirtree_start(*s, !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F)) ||
521 (toys.optflags&(FLAG_L|FLAG_H)));
523 // note: double_list->prev temporarirly goes in dirtree->parent
524 if (dt) dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
525 else toys.exitval = 1;
528 // Convert double_list into dirtree.
529 dlist_terminate(TT.files->child);
530 for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
532 // Display the files we collected
533 listfiles(AT_FDCWD, TT.files);
535 if (CFG_TOYBOX_FREE) free(TT.files);