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