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 (as default instead of -q: -b is unambiguous without collisions)
10 * add -Z -ll --color
11 * Posix says the -l date format should vary based on how recent it is
12 * and we do --time-style=long-iso instead
13 * ignore -k because we default to 1024 byte blocks
14 * Deviations from gnu: -N switches off -q (no --show-control-chars)
15 * No --quoting-style=shell-escape, mostly because no short or long opt for it
16
17 USE_LS(NEWTOY(ls, "(sort):(color):;(full-time)(block-size)#=1024<1(show-control-chars)\241(group-directories-first)\376ZgoACFHLNRSUXabcdfhikl@mnpqrstuw#=80<0x1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL][-Nqb]", TOYFLAG_BIN|TOYFLAG_LOCALE))
18
19 config LS
20 bool "ls"
21 default y
22 help
23 usage: ls [-1ACFHLNRSUXZabcdfghilmnopqrstuwx] [--color[=auto]] [FILE...]
24
25 List files
26
27 what to show:
28 -A all files except . and .. -a all files including .hidden
29 -b escape nongraphic chars -d directory, not contents
30 -F append /dir *exe @sym |FIFO -f files (no sort/filter/format)
31 -H follow command line symlinks -i inode number
32 -L follow symlinks -N no escaping, even on tty
33 -p put '/' after dir names -q unprintable chars as '?'
34 -R recursively list in subdirs -s storage used (in --block-size)
35 -Z security context
36
37 output formats:
38 -1 list one file per line -C columns (sorted vertically)
39 -g like -l but no owner -h human readable sizes
40 -l long (show full details) -ll long with nanoseconds (--full-time)
41 -m comma separated -n long with numeric uid/gid
42 -o long without group column -r reverse order
43 -w set column width -x columns (horizontal sort)
44
45 sort by: (also --sort=longname,longname... ends with alphabetical)
46 -c ctime -r reverse -S size -t time -u atime -U none
47 -X extension -! dirfirst -~ nocase
48
49 --block-size N block size (default 1024)
50 --color =always (default) =auto (when stdout is tty) =never
51 exe=green suid=red suidfile=redback stickydir=greenback
52 device=yellow symlink=turquoise/red dir=blue socket=purple
53
54 Long output uses -cu for display, use -ltc/-ltu to also sort by ctime/atime.
55 */
56
57 #define FOR_ls
58 #include "toys.h"
59
60 // test sst output (suid/sticky in ls flaglist)
61
62 // ls -lR starts .: then ./subdir:
63
64 GLOBALS(
65 long w, l, block_size;
66 char *color, *sort;
67
68 struct dirtree *files, *singledir;
69 unsigned screen_width;
70 int nl_title;
71 char *escmore;
72 )
73
74 // Callback from crunch_str to represent unprintable chars
crunch_qb(FILE * out,int cols,int wc)75 static int crunch_qb(FILE *out, int cols, int wc)
76 {
77 int len = 1;
78 char buf[32];
79
80 if (FLAG(q)) *buf = '?';
81 else {
82 if (wc<256) *buf = wc;
83 // scrute the inscrutable, eff the ineffable, print the unprintable
84 else if ((len = wcrtomb(buf, wc, 0) ) == -1) len = 1;
85 if (FLAG(b)) {
86 char *to = buf, *from = buf+24;
87 int i, j;
88
89 memcpy(from, to, 8);
90 for (i = 0; i<len; i++) {
91 *to++ = '\\';
92 if (strchr(TT.escmore, from[i])) *to++ = from[i];
93 else if (-1 != (j = stridx("\\\a\b\e\f\n\r\t\v", from[i])))
94 *to++ = "\\abefnrtv"[j];
95 else to += sprintf(to, "%03o", from[i]);
96 }
97 len = to-buf;
98 }
99 }
100
101 if (cols<len) len = cols;
102 if (out) fwrite(buf, len, 1, out);
103
104 return len;
105 }
106
107 // Returns wcwidth(utf8) version of strlen with -qb escapes
strwidth(char * s)108 static int strwidth(char *s)
109 {
110 return crunch_str(&s, INT_MAX, 0, TT.escmore, crunch_qb);
111 }
112
endtype(struct stat * st)113 static char endtype(struct stat *st)
114 {
115 mode_t mode = st->st_mode;
116 if ((FLAG(F)||FLAG(p)) && S_ISDIR(mode)) return '/';
117 if (FLAG(F)) {
118 if (S_ISLNK(mode)) return '@';
119 if (S_ISREG(mode) && (mode&0111)) return '*';
120 if (S_ISFIFO(mode)) return '|';
121 if (S_ISSOCK(mode)) return '=';
122 }
123 return 0;
124 }
125
numlen(long long ll)126 static int numlen(long long ll)
127 {
128 return snprintf(0, 0, "%llu", ll);
129 }
130
print_with_h(char * s,long long value,int blocks)131 static int print_with_h(char *s, long long value, int blocks)
132 {
133 if (blocks) value = (value * 1024) / TT.block_size;
134 if (FLAG(h)) return human_readable(s, value, 0);
135 else return sprintf(s, "%lld", value);
136 }
137
138 // Figure out size of printable entry fields for display indent/wrap
139
entrylen(struct dirtree * dt,unsigned * len)140 static void entrylen(struct dirtree *dt, unsigned *len)
141 {
142 struct stat *st = &(dt->st);
143 char tmp[64];
144
145 *len = strwidth(dt->name);
146 if (endtype(st)) ++*len;
147 if (FLAG(m)) ++*len;
148
149 len[1] = FLAG(i) ? numlen(st->st_ino) : 0;
150 if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) {
151 len[2] = numlen(st->st_nlink);
152 len[3] = FLAG(n) ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
153 len[4] = FLAG(n) ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
154 if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
155 // cheating slightly here: assuming minor is always 3 digits to avoid
156 // tracking another column
157 len[5] = numlen(dev_major(st->st_rdev))+5;
158 } else len[5] = print_with_h(tmp, st->st_size, 0);
159 }
160
161 len[6] = FLAG(s) ? print_with_h(tmp, st->st_blocks, 1) : 0;
162 len[7] = FLAG(Z) ? strwidth((char *)dt->extra) : 0;
163 }
164
165 // Perform one or more comparisons on a pair of files.
166 // Reused FLAG_a to mean "alphabetical"
do_compare(struct dirtree * a,struct dirtree * b,long long flags)167 static int do_compare(struct dirtree *a, struct dirtree *b, long long flags)
168 {
169 struct timespec *ts1 = 0, *ts2;
170 char *s1, *s2;
171 int ret;
172
173 // TODO -? nocase -! dirfirst
174
175 if (flags&FLAG_S) {
176 if (a->st.st_size > b->st.st_size) return -1;
177 else if (a->st.st_size < b->st.st_size) return 1;
178 }
179 if (flags&FLAG_t) ts1 = &a->st.st_mtim, ts2 = &b->st.st_mtim;
180 if (flags&FLAG_u) ts1 = &a->st.st_atim, ts2 = &b->st.st_atim;
181 if (flags&FLAG_c) ts1 = &a->st.st_ctim, ts2 = &b->st.st_ctim;
182 if (ts1) {
183 // Newest is first by default, so return values are backwards
184 if (ts1->tv_sec > ts2->tv_sec) return -1;
185 else if (ts1->tv_sec < ts2->tv_sec) return 1;
186 else if (ts1->tv_nsec > ts2->tv_nsec) return -1;
187 else if (ts1->tv_nsec < ts2->tv_nsec) return 1;
188 }
189 if (flags&FLAG_X21) // dirfirst
190 if (S_ISDIR(a->st.st_mode)!=S_ISDIR(b->st.st_mode))
191 return S_ISDIR(a->st.st_mode) ? -1 : 1;
192
193 // -X is a form of alphabetical sort, without -~ do case sensitive comparison
194 s1 = 0;
195 if (flags&FLAG_X) {
196 s1 = strrchr(a->name, '.');
197 s2 = strrchr(b->name, '.');
198 if (s2 && !s1) return -1;
199 if (s1 && !s2) return 1;
200 if (!(flags&FLAG_X7E)) flags |= FLAG_a;
201 }
202 if (!s1) {
203 s1 = a->name;
204 s2 = b->name;
205 }
206
207 // case insensitive sort falls back to case sensitive sort when equal
208 ret = (flags&FLAG_X7E) ? strcasecmp(s1, s2) : 0;
209 if (!ret && (flags&FLAG_a)) ret = strcmp(s1, s2);
210
211 return ret;
212 }
213
comma_start(char ** aa,char * b)214 int comma_start(char **aa, char *b)
215 {
216 return strstart(aa, b) && (!**aa || **aa==',');
217 }
218
219 // callback for qsort
compare(void * a,void * b)220 static int compare(void *a, void *b)
221 {
222 struct dirtree *dta = *(struct dirtree **)a;
223 struct dirtree *dtb = *(struct dirtree **)b;
224 char *ss = TT.sort;
225 long long ll = 0;
226 int ret = 0;
227 // TODO: test --sort=reverse with fallback alphabetical
228
229 if (ss) for (;;) {
230 while (*ss==',') ss++;
231 if (!*ss) break;
232 if (comma_start(&ss, "reverse")) toys.optflags |= FLAG_r;
233 else if (comma_start(&ss, "none")) goto skip;
234 else if (comma_start(&ss, "ctime")) ll = FLAG_c;
235 else if (comma_start(&ss, "size")) ll = FLAG_S;
236 else if (comma_start(&ss, "time")) ll = FLAG_t;
237 else if (comma_start(&ss, "atime")) ll = FLAG_u;
238 else if (comma_start(&ss, "nocase")) ll = FLAG_X7E;
239 else if (comma_start(&ss, "extension")) ll = FLAG_X;
240 else if (comma_start(&ss, "dirfirst")) ll = FLAG_X21;
241 else error_exit("bad --sort %s", ss);
242
243 if (!ret) ret = do_compare(dta, dtb, ll);
244 }
245
246 // Alpha fallback sort, and handle short opts
247 if (!ret) {
248 ll = toys.optflags|FLAG_a;
249 // historical nonsense: -lc displays -c but doesn't sort, -ltc sorts.
250 if (FLAG(o)|FLAG(l)) {
251 if (!FLAG(t)) ll &= ~(FLAG_c|FLAG_u);
252 else if (FLAG(c)||FLAG(u)) ll &= ~FLAG_t;
253 }
254 ret = do_compare(dta, dtb, ll);
255 }
256 skip:
257 if (FLAG(r)) ret *= -1;
258
259 return ret;
260 }
261
262 #ifdef TOYBOX_OH_ADAPT
263 // callback for qsort but file first
compare_file_first(void * a,void * b)264 static int compare_file_first(void *a, void *b)
265 {
266 struct dirtree *dta = *(struct dirtree **)a;
267 struct dirtree *dtb = *(struct dirtree **)b;
268
269 int ret = S_ISDIR(dta->st.st_mode) - S_ISDIR(dtb->st.st_mode);
270 return ret ? ret : compare(a, b);
271 }
272
273 // move dir to back of list, and return file count
move_dir_back(struct dirtree ** sort,unsigned long dtlen)274 static int move_dir_back(struct dirtree **sort, unsigned long dtlen)
275 {
276 struct dirtree **dir_list = xmalloc(dtlen*sizeof(void *));
277 unsigned long dir_list_len = 0;
278 if (dir_list == NULL) {
279 return dtlen;
280 }
281
282 int file_count = 0;
283 for (int i = 0; i < dtlen; i++) {
284 if (S_ISDIR(sort[i]->st.st_mode)) {
285 // move dir to dir_list
286 dir_list[dir_list_len++] = sort[i];
287 sort[i] = NULL;
288 } else {
289 // move files to front
290 if (file_count < i) {
291 sort[file_count] = sort[i];
292 sort[i] = NULL;
293 }
294 file_count++;
295 }
296 }
297
298 // restore dir at the back
299 for (int i = file_count, j = 0; i < dtlen && j < dir_list_len; i++, j++) {
300 sort[i] = dir_list[j];
301 }
302
303 free(dir_list);
304 return file_count;
305 }
306 #endif
307
308 #ifdef TOYBOX_OH_ADAPT
309 #define ENABLE_HIDDEN_STR "1"
310 #define ENABLE_HIDDEN_STR_LEN 1
311 #define ATTR_VALUE_LEN 8
is_file_hidden(const char * path)312 int is_file_hidden(const char *path) {
313 char value[ATTR_VALUE_LEN];
314 ssize_t ret = xattr_get(path, "user.filemanager.hidden", &value, sizeof(value) - 1);
315 if (ret >= 0 && ret < ATTR_VALUE_LEN) {
316 value[ret] = '\0';
317 } else {
318 value[0] = '\0';
319 }
320 return (ret == ENABLE_HIDDEN_STR_LEN) && !strncmp(ENABLE_HIDDEN_STR, value, sizeof(value));
321 }
322 #endif
323
324 // callback from dirtree_recurse() determining how to handle this entry.
325
filter(struct dirtree * new)326 static int filter(struct dirtree *new)
327 {
328 // Special case to handle enormous dirs without running out of memory.
329 if (toys.optflags == (FLAG_1|FLAG_f)) {
330 xprintf("%s\n", new->name);
331 return 0;
332 }
333
334 if (FLAG(Z)) {
335 if (!CFG_TOYBOX_LSM_NONE) {
336 // Linux doesn't support fgetxattr(2) on O_PATH file descriptors (though
337 // bionic works around that), and there are no *xattrat(2) calls, so we
338 // just use lgetxattr(2).
339 char *path = dirtree_path(new, 0);
340
341 (FLAG(L) ? lsm_get_context : lsm_lget_context)(path,(char **)&new->extra);
342 free(path);
343 }
344 if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
345 }
346
347 if (FLAG(u)) new->st.st_mtime = new->st.st_atime;
348 if (FLAG(c)) new->st.st_mtime = new->st.st_ctime;
349 new->st.st_blocks >>= 1; // Use 1KiB blocks rather than 512B blocks.
350
351 if (FLAG(a)||FLAG(f)) return DIRTREE_SAVE;
352 if (!FLAG(A) && *new->name=='.') return 0;
353 #ifdef TOYBOX_OH_ADAPT
354 if (!FLAG(A)) {
355 char *path = dirtree_path(new, 0);
356 if (path) {
357 int is_hidden = is_file_hidden(path);
358 free(path);
359 path = NULL;
360 if (is_hidden) {
361 return 0;
362 }
363 }
364 }
365 #endif
366
367 return dirtree_notdotdot(new) & DIRTREE_SAVE;
368 }
369
370 // For column view, calculate horizontal position (for padding) and return
371 // index of next entry to display.
372
next_column(unsigned long ul,unsigned long dtlen,unsigned columns,unsigned * xpos)373 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
374 unsigned columns, unsigned *xpos)
375 {
376 unsigned height, extra;
377
378 // Horizontal sort is easy
379 if (!FLAG(C)) {
380 *xpos = ul % columns;
381 return ul;
382 }
383
384 // vertical sort (-x), uneven rounding goes along right edge
385 height = (dtlen+columns-1)/columns; // round up
386 extra = dtlen%height; // how many rows are wider?
387 if (extra && ul >= extra*columns) ul -= extra*columns--;
388 else extra = 0;
389
390 return (*xpos = ul % columns)*height + extra + ul/columns;
391 }
392
color_from_mode(mode_t mode)393 static int color_from_mode(mode_t mode)
394 {
395 int color = 0;
396
397 if (S_ISDIR(mode)) color = 256+34;
398 else if (S_ISLNK(mode)) color = 256+36;
399 else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
400 else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
401 else if (S_ISFIFO(mode)) color = 33;
402 else if (S_ISSOCK(mode)) color = 256+35;
403
404 return color;
405 }
406
zprint(int zap,char * pat,int len,unsigned long arg)407 static void zprint(int zap, char *pat, int len, unsigned long arg)
408 {
409 char tmp[32];
410
411 sprintf(tmp, "%%*%s", zap ? "s" : pat);
412 if (zap && pat[strlen(pat)-1]==' ') strcat(tmp, " ");
413 printf(tmp, len, zap ? (unsigned long)"?" : arg);
414 }
415
416 // Display a list of dirtree entries, according to current format
417 // Output types -1, -l, -C, or stream
418
listfiles(int dirfd,struct dirtree * indir)419 static void listfiles(int dirfd, struct dirtree *indir)
420 {
421 struct dirtree *dt, **sort;
422 unsigned long dtlen, ul = 0;
423 unsigned width, totals[8], len[8], totpad = 0,
424 *colsizes = (unsigned *)toybuf, columns = sizeof(toybuf)/4;
425 char tmp[64];
426 #ifdef TOYBOX_OH_ADAPT
427 unsigned long dtlen_old;
428 int skip_dir = !indir->parent && !FLAG(d);
429 #endif
430
431 if (-1 == dirfd) {
432 perror_msg_raw(indir->name);
433
434 return;
435 }
436
437 memset(totals, 0, sizeof(totals));
438 memset(len, 0, sizeof(len));
439
440 // Top level directory was already populated by main()
441 if (!indir->parent) {
442 // Silently descend into single directory listed by itself on command line.
443 // In this case only show dirname/total header when given -R.
444 dt = indir->child;
445 if (dt && S_ISDIR(dt->st.st_mode) && !dt->next && !(FLAG(d)||FLAG(R))) {
446 listfiles(open(dt->name, 0), TT.singledir = dt);
447
448 return;
449 }
450
451 // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
452 for (;dt; dt = dt->next) filter(dt);
453 if (toys.optflags == (FLAG_1|FLAG_f)) return;
454 // Read directory contents. We dup() the fd because this will close it.
455 // This reads/saves contents to display later, except for in "ls -1f" mode.
456 } else dirtree_recurse(indir, filter, dirfd,
457 DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*FLAG(L));
458
459 // Copy linked list to array and sort it. Directories go in array because
460 // we visit them in sorted order too. (The nested loops let us measure and
461 // fill with the same inner loop.)
462 for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
463 for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
464 if (sort) sort[dtlen] = dt;
465 if (sort || !dtlen) break;
466 }
467
468 #ifdef TOYBOX_OH_ADAPT
469 dtlen_old = dtlen;
470 if (FLAG(f) || FLAG(U)) {
471 // no sort, so fix it here
472 if (skip_dir) {
473 dtlen = move_dir_back(sort, dtlen_old);
474 }
475 }
476 #endif
477
478 // Label directory if not top of tree, or if -R
479 if (indir->parent && (TT.singledir!=indir || FLAG(R))) {
480 char *path = dirtree_path(indir, 0);
481
482 if (TT.nl_title++) xputc('\n');
483 xprintf("%s:\n", path);
484 free(path);
485 }
486
487 // Measure each entry to work out whitespace padding and total blocks
488 if (!FLAG(f)) {
489 unsigned long long blocks = 0;
490
491 if (!FLAG(U)) {
492 #ifdef TOYBOX_OH_ADAPT
493 if (skip_dir) {
494 // compare with file first
495 qsort(sort, dtlen, sizeof(void *), (void *)compare_file_first);
496 // modify dtlen to skip all dirs
497 for (ul = 0; ul < dtlen; ul++) {
498 if (S_ISDIR(sort[ul]->st.st_mode)) {
499 dtlen = ul;
500 break;
501 }
502 }
503 } else {
504 #endif
505 qsort(sort, dtlen, sizeof(void *), (void *)compare);
506 #ifdef TOYBOX_OH_ADAPT
507 }
508 #endif
509 }
510 for (ul = 0; ul<dtlen; ul++) {
511 entrylen(sort[ul], len);
512 for (width = 0; width<8; width++)
513 if (len[width]>totals[width]) totals[width] = len[width];
514 blocks += sort[ul]->st.st_blocks;
515 }
516 totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
517 if ((FLAG(h)||FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)||FLAG(s)) && indir->parent)
518 {
519 #ifdef TOYBOX_OH_ADAPT
520 print_with_h(tmp, blocks * 1024, 0);
521 #else
522 print_with_h(tmp, blocks, 1);
523 #endif
524 xprintf("total %s\n", tmp);
525 }
526 }
527
528 // Find largest entry in each field for display alignment
529 if (FLAG(C)||FLAG(x)) {
530
531 // columns can't be more than toybuf can hold, or more than files,
532 // or > 1/2 screen width (one char filename, one space).
533 if (columns > TT.screen_width/2) columns = TT.screen_width/2;
534 if (columns > dtlen) columns = dtlen;
535
536 // Try to fit as many columns as we can, dropping down by one each time
537 for (;columns > 1; columns--) {
538 unsigned c, cc, totlen = columns;
539
540 memset(colsizes, 0, columns*sizeof(unsigned));
541 for (ul = 0; ul<dtlen; ul++) {
542 cc = next_column(ul, dtlen, columns, &c);
543 if (cc>=dtlen) break; // tilt: remainder bigger than height
544 entrylen(sort[cc], len);
545 if (c<columns-1) *len += totpad+2; // 2 spaces between filenames
546 // Expand this column if necessary, break if that puts us over budget
547 if (*len > colsizes[c]) {
548 totlen += (*len)-colsizes[c];
549 colsizes[c] = *len;
550 if (totlen > TT.screen_width) break;
551 }
552 }
553 // If everything fit, stop here
554 if (ul == dtlen) break;
555 }
556 }
557
558 // Loop through again to produce output.
559 width = 0;
560 for (ul = 0; ul<dtlen; ul++) {
561 int ii, zap;
562 unsigned curcol, lastlen = *len, color = 0;
563 struct stat *st = &((dt = sort[next_column(ul,dtlen,columns,&curcol)])->st);
564 mode_t mode = st->st_mode;
565 char et = endtype(st), *ss;
566
567 // If we couldn't stat, output ? for most fields
568 zap = !st->st_blksize && !st->st_dev && !st->st_ino;
569
570 #ifndef TOYBOX_OH_ADAPT
571 // Skip directories at the top of the tree when -d isn't set
572 if (S_ISDIR(mode) && !indir->parent && !FLAG(d)) continue;
573 #endif
574 TT.nl_title=1;
575
576 // Handle padding and wrapping for display purposes
577 entrylen(dt, len);
578 if (ul) {
579 if (FLAG(m)) xputc(',');
580 if (FLAG(C)||FLAG(x)) {
581 if (!curcol) xputc('\n');
582 else {
583 if (ul) next_column(ul-1, dtlen, columns, &curcol);
584 printf("%*c", colsizes[ul ? curcol : 0]-lastlen-totpad, ' ');
585 }
586 } else if (FLAG(1) || width+1+*len > TT.screen_width) {
587 xputc('\n');
588 width = 0;
589 } else {
590 xputsn(" "+FLAG(m));
591 width += 2-FLAG(m);
592 }
593 }
594 width += *len;
595
596 if (FLAG(i)) zprint(zap, "lu ", totals[1], st->st_ino);
597
598 if (FLAG(s)) {
599 print_with_h(tmp, st->st_blocks, 1);
600 zprint(zap, "s ", totals[6], (unsigned long)tmp);
601 }
602
603 if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) {
604 mode_to_string(mode, tmp);
605 if (zap) memset(tmp+1, '?', 9);
606 printf("%s", tmp);
607 zprint(zap, "ld", totals[2]+1, st->st_nlink);
608
609 // print user
610 if (!FLAG(g)) {
611 putchar(' ');
612 ii = -totals[3];
613 if (zap || FLAG(n)) zprint(zap, "lu", ii, st->st_uid);
614 else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
615 crunch_qb);
616 }
617
618 // print group
619 if (!FLAG(o)) {
620 putchar(' ');
621 ii = -totals[4];
622 if (zap || FLAG(n)) zprint(zap, "lu", ii, st->st_gid);
623 else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
624 crunch_qb);
625 }
626 }
627 if (FLAG(Z)) printf(" %-*s "+!FLAG(l), -(int)totals[7], (char *)dt->extra);
628
629 if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) {
630 struct tm *tm;
631
632 // print major/minor, or size
633 if (!zap && (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)))
634 printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
635 dev_minor(st->st_rdev));
636 else {
637 print_with_h(tmp, st->st_size, 0);
638 zprint(zap, "s", totals[5]+1, (unsigned long)tmp);
639 }
640
641 // print time, always in --time-style=long-iso
642 tm = localtime(&(st->st_mtime));
643 strftime(tmp, sizeof(tmp), " %F %H:%M", tm);
644 if (TT.l>1) {
645 char *s = tmp+strlen(tmp);
646
647 s += sprintf(s, ":%02d.%09d ", tm->tm_sec, (int)st->st_mtim.tv_nsec);
648 strftime(s, sizeof(tmp)-(s-tmp), "%z", tm);
649 }
650 zprint(zap, "s ", 17+(TT.l>1)*13, (unsigned long)tmp);
651 }
652
653 if (FLAG(color)) {
654 color = color_from_mode(st->st_mode);
655 if (color) printf("\e[%d;%dm", color>>8, color&255);
656 }
657
658 ss = dt->name;
659 crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
660 if (color) printf("\e[0m");
661
662 if ((FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) && S_ISLNK(mode)) {
663 printf(" -> ");
664 if (!zap && FLAG(color)) {
665 struct stat st2;
666
667 if (fstatat(dirfd, dt->symlink, &st2, 0)) color = 256+31;
668 else color = color_from_mode(st2.st_mode);
669
670 if (color) printf("\e[%d;%dm", color>>8, color&255);
671 }
672
673 zprint(zap, "s", 0, (unsigned long)dt->symlink);
674 if (!zap && color) printf("\e[0m");
675 }
676
677 if (et) xputc(et);
678 }
679
680 if (width) xputc('\n');
681
682 // Free directory entries, recursing first if necessary.
683 #ifdef TOYBOX_OH_ADAPT
684 for (ul = 0; ul<dtlen_old; free(sort[ul++])) {
685 #else
686 for (ul = 0; ul<dtlen; free(sort[ul++])) {
687 #endif
688 if (FLAG(d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
689
690 // Recurse into dirs if at top of the tree or given -R
691 if (!indir->parent || (FLAG(R) && dirtree_notdotdot(sort[ul])))
692 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
693 free((void *)sort[ul]->extra);
694 }
695 free(sort);
696 if (dirfd != AT_FDCWD) close(dirfd);
697 }
698
699 void ls_main(void)
700 {
701 char **s, *noargs[] = {".", 0};
702 struct dirtree *dt;
703
704 if (FLAG(full_time)) {
705 toys.optflags |= FLAG_l;
706 TT.l = 2;
707 }
708
709 // Do we have an implied -1
710 if (isatty(1)) {
711 if (!FLAG(show_control_chars)) toys.optflags |= FLAG_b;
712 if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) toys.optflags |= FLAG_1;
713 else if (!(FLAG(1)||FLAG(x)||FLAG(m))) toys.optflags |= FLAG_C;
714 } else {
715 if (!FLAG(m)) toys.optflags |= FLAG_1;
716 if (TT.color) toys.optflags ^= FLAG_color;
717 }
718
719 // -N *doesn't* disable -q; you need --show-control-chars for that.
720 if (FLAG(N)) toys.optflags &= ~FLAG_b;
721
722 TT.screen_width = 80;
723 if (FLAG(w)) TT.screen_width = TT.w+2;
724 else terminal_size(&TT.screen_width, NULL);
725 if (TT.screen_width<2) TT.screen_width = 2;
726 if (FLAG(b)) TT.escmore = " \\";
727
728 // The optflags parsing infrastructure should really do this for us,
729 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
730 // behave differently
731 if (FLAG(d)) toys.optflags &= ~FLAG_R;
732
733 // Iterate through command line arguments, collecting directories and files.
734 // Non-absolute paths are relative to current directory. Top of tree is
735 // a dummy node to collect command line arguments into pseudo-directory.
736 TT.files = dirtree_add_node(0, 0, 0);
737 TT.files->dirfd = AT_FDCWD;
738 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
739 int sym = !(FLAG(l)||FLAG(d)||FLAG(F)) || FLAG(L) || FLAG(H);
740
741 dt = dirtree_add_node(0, *s, DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*sym);
742
743 // note: double_list->prev temporarily goes in dirtree->parent
744 if (dt) {
745 if (dt->again&DIRTREE_STATLESS) {
746 perror_msg_raw(*s);
747 free(dt);
748 } else dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
749 } else toys.exitval = 1;
750 }
751
752 // Convert double_list into dirtree.
753 dlist_terminate(TT.files->child);
754 for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
755
756 // Display the files we collected
757 listfiles(AT_FDCWD, TT.files);
758
759 if (CFG_TOYBOX_FREE) free(TT.files);
760 }
761