ls.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * tiny-ls.c version 0.1.0: A minimalist 'ls'
  4. * Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. /* [date unknown. Perhaps before year 2000]
  9. * To achieve a small memory footprint, this version of 'ls' doesn't do any
  10. * file sorting, and only has the most essential command line switches
  11. * (i.e., the ones I couldn't live without :-) All features which involve
  12. * linking in substantial chunks of libc can be disabled.
  13. *
  14. * Although I don't really want to add new features to this program to
  15. * keep it small, I *am* interested to receive bug fixes and ways to make
  16. * it more portable.
  17. *
  18. * KNOWN BUGS:
  19. * 1. hidden files can make column width too large
  20. *
  21. * NON-OPTIMAL BEHAVIOUR:
  22. * 1. autowidth reads directories twice
  23. * 2. if you do a short directory listing without filetype characters
  24. * appended, there's no need to stat each one
  25. * PORTABILITY:
  26. * 1. requires lstat (BSD) - how do you do it without?
  27. *
  28. * [2009-03]
  29. * ls sorts listing now, and supports almost all options.
  30. */
  31. #include "libbb.h"
  32. #include "unicode.h"
  33. /* This is a NOEXEC applet. Be very careful! */
  34. #if ENABLE_FTPD
  35. /* ftpd uses ls, and without timestamps Mozilla won't understand
  36. * ftpd's LIST output.
  37. */
  38. # undef CONFIG_FEATURE_LS_TIMESTAMPS
  39. # undef ENABLE_FEATURE_LS_TIMESTAMPS
  40. # undef IF_FEATURE_LS_TIMESTAMPS
  41. # undef IF_NOT_FEATURE_LS_TIMESTAMPS
  42. # define CONFIG_FEATURE_LS_TIMESTAMPS 1
  43. # define ENABLE_FEATURE_LS_TIMESTAMPS 1
  44. # define IF_FEATURE_LS_TIMESTAMPS(...) __VA_ARGS__
  45. # define IF_NOT_FEATURE_LS_TIMESTAMPS(...)
  46. #endif
  47. enum {
  48. TERMINAL_WIDTH = 80, /* use 79 if terminal has linefold bug */
  49. COLUMN_GAP = 2, /* includes the file type char */
  50. /* what is the overall style of the listing */
  51. STYLE_COLUMNS = 1 << 21, /* fill columns */
  52. STYLE_LONG = 2 << 21, /* one record per line, extended info */
  53. STYLE_SINGLE = 3 << 21, /* one record per line */
  54. STYLE_MASK = STYLE_SINGLE,
  55. /* 51306 lrwxrwxrwx 1 root root 2 May 11 01:43 /bin/view -> vi* */
  56. /* what file information will be listed */
  57. LIST_INO = 1 << 0,
  58. LIST_BLOCKS = 1 << 1,
  59. LIST_MODEBITS = 1 << 2,
  60. LIST_NLINKS = 1 << 3,
  61. LIST_ID_NAME = 1 << 4,
  62. LIST_ID_NUMERIC = 1 << 5,
  63. LIST_CONTEXT = 1 << 6,
  64. LIST_SIZE = 1 << 7,
  65. //LIST_DEV = 1 << 8, - unused, synonym to LIST_SIZE
  66. LIST_DATE_TIME = 1 << 9,
  67. LIST_FULLTIME = 1 << 10,
  68. LIST_FILENAME = 1 << 11,
  69. LIST_SYMLINK = 1 << 12,
  70. LIST_FILETYPE = 1 << 13,
  71. LIST_EXEC = 1 << 14,
  72. LIST_MASK = (LIST_EXEC << 1) - 1,
  73. /* what files will be displayed */
  74. DISP_DIRNAME = 1 << 15, /* 2 or more items? label directories */
  75. DISP_HIDDEN = 1 << 16, /* show filenames starting with . */
  76. DISP_DOT = 1 << 17, /* show . and .. */
  77. DISP_NOLIST = 1 << 18, /* show directory as itself, not contents */
  78. DISP_RECURSIVE = 1 << 19, /* show directory and everything below it */
  79. DISP_ROWS = 1 << 20, /* print across rows */
  80. DISP_MASK = ((DISP_ROWS << 1) - 1) & ~(DISP_DIRNAME - 1),
  81. /* how will the files be sorted (CONFIG_FEATURE_LS_SORTFILES) */
  82. SORT_FORWARD = 0, /* sort in reverse order */
  83. SORT_REVERSE = 1 << 27, /* sort in reverse order */
  84. SORT_NAME = 0, /* sort by file name */
  85. SORT_SIZE = 1 << 28, /* sort by file size */
  86. SORT_ATIME = 2 << 28, /* sort by last access time */
  87. SORT_CTIME = 3 << 28, /* sort by last change time */
  88. SORT_MTIME = 4 << 28, /* sort by last modification time */
  89. SORT_VERSION = 5 << 28, /* sort by version */
  90. SORT_EXT = 6 << 28, /* sort by file name extension */
  91. SORT_DIR = 7 << 28, /* sort by file or directory */
  92. SORT_MASK = (7 << 28) * ENABLE_FEATURE_LS_SORTFILES,
  93. /* which of the three times will be used */
  94. TIME_CHANGE = (1 << 23) * ENABLE_FEATURE_LS_TIMESTAMPS,
  95. TIME_ACCESS = (1 << 24) * ENABLE_FEATURE_LS_TIMESTAMPS,
  96. TIME_MASK = (3 << 23) * ENABLE_FEATURE_LS_TIMESTAMPS,
  97. FOLLOW_LINKS = (1 << 25) * ENABLE_FEATURE_LS_FOLLOWLINKS,
  98. LS_DISP_HR = (1 << 26) * ENABLE_FEATURE_HUMAN_READABLE,
  99. LIST_SHORT = LIST_FILENAME,
  100. LIST_LONG = LIST_MODEBITS | LIST_NLINKS | LIST_ID_NAME | LIST_SIZE | \
  101. LIST_DATE_TIME | LIST_FILENAME | LIST_SYMLINK,
  102. SPLIT_DIR = 1,
  103. SPLIT_FILE = 0,
  104. SPLIT_SUBDIR = 2,
  105. };
  106. /* "[-]Cadil1", POSIX mandated options, busybox always supports */
  107. /* "[-]gnsx", POSIX non-mandated options, busybox always supports */
  108. /* "[-]Q" GNU option? busybox always supports */
  109. /* "[-]Ak" GNU options, busybox always supports */
  110. /* "[-]FLRctur", POSIX mandated options, busybox optionally supports */
  111. /* "[-]p", POSIX non-mandated options, busybox optionally supports */
  112. /* "[-]SXvThw", GNU options, busybox optionally supports */
  113. /* "[-]K", SELinux mandated options, busybox optionally supports */
  114. /* "[-]e", I think we made this one up */
  115. static const char ls_options[] ALIGN1 =
  116. "Cadil1gnsxQAk" /* 13 opts, total 13 */
  117. IF_FEATURE_LS_TIMESTAMPS("cetu") /* 4, 17 */
  118. IF_FEATURE_LS_SORTFILES("SXrv") /* 4, 21 */
  119. IF_FEATURE_LS_FILETYPES("Fp") /* 2, 23 */
  120. IF_FEATURE_LS_FOLLOWLINKS("L") /* 1, 24 */
  121. IF_FEATURE_LS_RECURSIVE("R") /* 1, 25 */
  122. IF_FEATURE_HUMAN_READABLE("h") /* 1, 26 */
  123. IF_SELINUX("KZ") /* 2, 28 */
  124. IF_FEATURE_AUTOWIDTH("T:w:") /* 2, 30 */
  125. ;
  126. enum {
  127. //OPT_C = (1 << 0),
  128. //OPT_a = (1 << 1),
  129. //OPT_d = (1 << 2),
  130. //OPT_i = (1 << 3),
  131. //OPT_l = (1 << 4),
  132. //OPT_1 = (1 << 5),
  133. OPT_g = (1 << 6),
  134. //OPT_n = (1 << 7),
  135. //OPT_s = (1 << 8),
  136. //OPT_x = (1 << 9),
  137. OPT_Q = (1 << 10),
  138. //OPT_A = (1 << 11),
  139. //OPT_k = (1 << 12),
  140. OPTBIT_color = 13
  141. + 4 * ENABLE_FEATURE_LS_TIMESTAMPS
  142. + 4 * ENABLE_FEATURE_LS_SORTFILES
  143. + 2 * ENABLE_FEATURE_LS_FILETYPES
  144. + 1 * ENABLE_FEATURE_LS_FOLLOWLINKS
  145. + 1 * ENABLE_FEATURE_LS_RECURSIVE
  146. + 1 * ENABLE_FEATURE_HUMAN_READABLE
  147. + 2 * ENABLE_SELINUX
  148. + 2 * ENABLE_FEATURE_AUTOWIDTH,
  149. OPT_color = 1 << OPTBIT_color,
  150. };
  151. enum {
  152. LIST_MASK_TRIGGER = 0,
  153. STYLE_MASK_TRIGGER = STYLE_MASK,
  154. DISP_MASK_TRIGGER = DISP_ROWS,
  155. SORT_MASK_TRIGGER = SORT_MASK,
  156. };
  157. /* TODO: simple toggles may be stored as OPT_xxx bits instead */
  158. static const unsigned opt_flags[] = {
  159. LIST_SHORT | STYLE_COLUMNS, /* C */
  160. DISP_HIDDEN | DISP_DOT, /* a */
  161. DISP_NOLIST, /* d */
  162. LIST_INO, /* i */
  163. LIST_LONG | STYLE_LONG, /* l - remember LS_DISP_HR in mask! */
  164. LIST_SHORT | STYLE_SINGLE, /* 1 */
  165. 0, /* g (don't show owner) - handled via OPT_g */
  166. LIST_ID_NUMERIC, /* n */
  167. LIST_BLOCKS, /* s */
  168. DISP_ROWS, /* x */
  169. 0, /* Q (quote filename) - handled via OPT_Q */
  170. DISP_HIDDEN, /* A */
  171. ENABLE_SELINUX * LIST_CONTEXT, /* k (ignored if !SELINUX) */
  172. #if ENABLE_FEATURE_LS_TIMESTAMPS
  173. TIME_CHANGE | (ENABLE_FEATURE_LS_SORTFILES * SORT_CTIME), /* c */
  174. LIST_FULLTIME, /* e */
  175. ENABLE_FEATURE_LS_SORTFILES * SORT_MTIME, /* t */
  176. TIME_ACCESS | (ENABLE_FEATURE_LS_SORTFILES * SORT_ATIME), /* u */
  177. #endif
  178. #if ENABLE_FEATURE_LS_SORTFILES
  179. SORT_SIZE, /* S */
  180. SORT_EXT, /* X */
  181. SORT_REVERSE, /* r */
  182. SORT_VERSION, /* v */
  183. #endif
  184. #if ENABLE_FEATURE_LS_FILETYPES
  185. LIST_FILETYPE | LIST_EXEC, /* F */
  186. LIST_FILETYPE, /* p */
  187. #endif
  188. #if ENABLE_FEATURE_LS_FOLLOWLINKS
  189. FOLLOW_LINKS, /* L */
  190. #endif
  191. #if ENABLE_FEATURE_LS_RECURSIVE
  192. DISP_RECURSIVE, /* R */
  193. #endif
  194. #if ENABLE_FEATURE_HUMAN_READABLE
  195. LS_DISP_HR, /* h */
  196. #endif
  197. #if ENABLE_SELINUX
  198. LIST_MODEBITS|LIST_NLINKS|LIST_CONTEXT|LIST_SIZE|LIST_DATE_TIME, /* K */
  199. #endif
  200. #if ENABLE_SELINUX
  201. LIST_MODEBITS|LIST_ID_NAME|LIST_CONTEXT, /* Z */
  202. #endif
  203. (1U<<31)
  204. /* options after Z are not processed through opt_flags:
  205. * T, w - ignored
  206. */
  207. };
  208. /*
  209. * a directory entry and its stat info are stored here
  210. */
  211. struct dnode {
  212. const char *name; /* the dir entry name */
  213. const char *fullname; /* the dir entry name */
  214. struct dnode *next; /* point at the next node */
  215. smallint fname_allocated;
  216. struct stat dstat; /* the file stat info */
  217. IF_SELINUX(security_context_t sid;)
  218. };
  219. struct globals {
  220. #if ENABLE_FEATURE_LS_COLOR
  221. smallint show_color;
  222. #endif
  223. smallint exit_code;
  224. unsigned all_fmt;
  225. #if ENABLE_FEATURE_AUTOWIDTH
  226. unsigned tabstops; // = COLUMN_GAP;
  227. unsigned terminal_width; // = TERMINAL_WIDTH;
  228. #endif
  229. #if ENABLE_FEATURE_LS_TIMESTAMPS
  230. /* Do time() just once. Saves one syscall per file for "ls -l" */
  231. time_t current_time_t;
  232. #endif
  233. } FIX_ALIASING;
  234. #define G (*(struct globals*)&bb_common_bufsiz1)
  235. #if ENABLE_FEATURE_LS_COLOR
  236. # define show_color (G.show_color )
  237. #else
  238. enum { show_color = 0 };
  239. #endif
  240. #define exit_code (G.exit_code )
  241. #define all_fmt (G.all_fmt )
  242. #if ENABLE_FEATURE_AUTOWIDTH
  243. # define tabstops (G.tabstops )
  244. # define terminal_width (G.terminal_width)
  245. #else
  246. enum {
  247. tabstops = COLUMN_GAP,
  248. terminal_width = TERMINAL_WIDTH,
  249. };
  250. #endif
  251. #define current_time_t (G.current_time_t)
  252. #define INIT_G() do { \
  253. /* we have to zero it out because of NOEXEC */ \
  254. memset(&G, 0, sizeof(G)); \
  255. IF_FEATURE_AUTOWIDTH(tabstops = COLUMN_GAP;) \
  256. IF_FEATURE_AUTOWIDTH(terminal_width = TERMINAL_WIDTH;) \
  257. IF_FEATURE_LS_TIMESTAMPS(time(&current_time_t);) \
  258. } while (0)
  259. static struct dnode *my_stat(const char *fullname, const char *name, int force_follow)
  260. {
  261. struct stat dstat;
  262. struct dnode *cur;
  263. IF_SELINUX(security_context_t sid = NULL;)
  264. if ((all_fmt & FOLLOW_LINKS) || force_follow) {
  265. #if ENABLE_SELINUX
  266. if (is_selinux_enabled()) {
  267. getfilecon(fullname, &sid);
  268. }
  269. #endif
  270. if (stat(fullname, &dstat)) {
  271. bb_simple_perror_msg(fullname);
  272. exit_code = EXIT_FAILURE;
  273. return 0;
  274. }
  275. } else {
  276. #if ENABLE_SELINUX
  277. if (is_selinux_enabled()) {
  278. lgetfilecon(fullname, &sid);
  279. }
  280. #endif
  281. if (lstat(fullname, &dstat)) {
  282. bb_simple_perror_msg(fullname);
  283. exit_code = EXIT_FAILURE;
  284. return 0;
  285. }
  286. }
  287. cur = xmalloc(sizeof(*cur));
  288. cur->fullname = fullname;
  289. cur->name = name;
  290. cur->dstat = dstat;
  291. IF_SELINUX(cur->sid = sid;)
  292. return cur;
  293. }
  294. /* FYI type values: 1:fifo 2:char 4:dir 6:blk 8:file 10:link 12:socket
  295. * (various wacky OSes: 13:Sun door 14:BSD whiteout 5:XENIX named file
  296. * 3/7:multiplexed char/block device)
  297. * and we use 0 for unknown and 15 for executables (see below) */
  298. #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
  299. #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
  300. #define APPCHAR(mode) ("\0|\0\0/\0\0\0\0\0@\0=\0\0\0" [TYPEINDEX(mode)])
  301. /* 036 black foreground 050 black background
  302. 037 red foreground 051 red background
  303. 040 green foreground 052 green background
  304. 041 brown foreground 053 brown background
  305. 042 blue foreground 054 blue background
  306. 043 magenta (purple) foreground 055 magenta background
  307. 044 cyan (light blue) foreground 056 cyan background
  308. 045 gray foreground 057 white background
  309. */
  310. #define COLOR(mode) ( \
  311. /*un fi chr dir blk file link sock exe */ \
  312. "\037\043\043\045\042\045\043\043\000\045\044\045\043\045\045\040" \
  313. [TYPEINDEX(mode)])
  314. /* Select normal (0) [actually "reset all"] or bold (1)
  315. * (other attributes are 2:dim 4:underline 5:blink 7:reverse,
  316. * let's use 7 for "impossible" types, just for fun)
  317. * Note: coreutils 6.9 uses inverted red for setuid binaries.
  318. */
  319. #define ATTR(mode) ( \
  320. /*un fi chr dir blk file link sock exe */ \
  321. "\01\00\01\07\01\07\01\07\00\07\01\07\01\07\07\01" \
  322. [TYPEINDEX(mode)])
  323. #if ENABLE_FEATURE_LS_COLOR
  324. /* mode of zero is interpreted as "unknown" (stat failed) */
  325. static char fgcolor(mode_t mode)
  326. {
  327. if (S_ISREG(mode) && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
  328. return COLOR(0xF000); /* File is executable ... */
  329. return COLOR(mode);
  330. }
  331. static char bold(mode_t mode)
  332. {
  333. if (S_ISREG(mode) && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
  334. return ATTR(0xF000); /* File is executable ... */
  335. return ATTR(mode);
  336. }
  337. #endif
  338. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  339. static char append_char(mode_t mode)
  340. {
  341. if (!(all_fmt & LIST_FILETYPE))
  342. return '\0';
  343. if (S_ISDIR(mode))
  344. return '/';
  345. if (!(all_fmt & LIST_EXEC))
  346. return '\0';
  347. if (S_ISREG(mode) && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
  348. return '*';
  349. return APPCHAR(mode);
  350. }
  351. #endif
  352. static unsigned count_dirs(struct dnode **dn, int which)
  353. {
  354. unsigned dirs, all;
  355. if (!dn)
  356. return 0;
  357. dirs = all = 0;
  358. for (; *dn; dn++) {
  359. const char *name;
  360. all++;
  361. if (!S_ISDIR((*dn)->dstat.st_mode))
  362. continue;
  363. name = (*dn)->name;
  364. if (which != SPLIT_SUBDIR /* if not requested to skip . / .. */
  365. /* or if it's not . or .. */
  366. || name[0] != '.' || (name[1] && (name[1] != '.' || name[2]))
  367. ) {
  368. dirs++;
  369. }
  370. }
  371. return which != SPLIT_FILE ? dirs : all - dirs;
  372. }
  373. /* get memory to hold an array of pointers */
  374. static struct dnode **dnalloc(unsigned num)
  375. {
  376. if (num < 1)
  377. return NULL;
  378. num++; /* so that we have terminating NULL */
  379. return xzalloc(num * sizeof(struct dnode *));
  380. }
  381. #if ENABLE_FEATURE_LS_RECURSIVE
  382. static void dfree(struct dnode **dnp)
  383. {
  384. unsigned i;
  385. if (dnp == NULL)
  386. return;
  387. for (i = 0; dnp[i]; i++) {
  388. struct dnode *cur = dnp[i];
  389. if (cur->fname_allocated)
  390. free((char*)cur->fullname);
  391. free(cur);
  392. }
  393. free(dnp);
  394. }
  395. #else
  396. #define dfree(...) ((void)0)
  397. #endif
  398. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  399. static struct dnode **splitdnarray(struct dnode **dn, int which)
  400. {
  401. unsigned dncnt, d;
  402. struct dnode **dnp;
  403. if (dn == NULL)
  404. return NULL;
  405. /* count how many dirs or files there are */
  406. dncnt = count_dirs(dn, which);
  407. /* allocate a file array and a dir array */
  408. dnp = dnalloc(dncnt);
  409. /* copy the entrys into the file or dir array */
  410. for (d = 0; *dn; dn++) {
  411. if (S_ISDIR((*dn)->dstat.st_mode)) {
  412. const char *name;
  413. if (!(which & (SPLIT_DIR|SPLIT_SUBDIR)))
  414. continue;
  415. name = (*dn)->name;
  416. if ((which & SPLIT_DIR)
  417. || name[0]!='.' || (name[1] && (name[1]!='.' || name[2]))
  418. ) {
  419. dnp[d++] = *dn;
  420. }
  421. } else if (!(which & (SPLIT_DIR|SPLIT_SUBDIR))) {
  422. dnp[d++] = *dn;
  423. }
  424. }
  425. return dnp;
  426. }
  427. #if ENABLE_FEATURE_LS_SORTFILES
  428. static int sortcmp(const void *a, const void *b)
  429. {
  430. struct dnode *d1 = *(struct dnode **)a;
  431. struct dnode *d2 = *(struct dnode **)b;
  432. unsigned sort_opts = all_fmt & SORT_MASK;
  433. off_t dif;
  434. dif = 0; /* assume SORT_NAME */
  435. // TODO: use pre-initialized function pointer
  436. // instead of branch forest
  437. if (sort_opts == SORT_SIZE) {
  438. dif = (d2->dstat.st_size - d1->dstat.st_size);
  439. } else if (sort_opts == SORT_ATIME) {
  440. dif = (d2->dstat.st_atime - d1->dstat.st_atime);
  441. } else if (sort_opts == SORT_CTIME) {
  442. dif = (d2->dstat.st_ctime - d1->dstat.st_ctime);
  443. } else if (sort_opts == SORT_MTIME) {
  444. dif = (d2->dstat.st_mtime - d1->dstat.st_mtime);
  445. } else if (sort_opts == SORT_DIR) {
  446. dif = S_ISDIR(d2->dstat.st_mode) - S_ISDIR(d1->dstat.st_mode);
  447. /* } else if (sort_opts == SORT_VERSION) { */
  448. /* } else if (sort_opts == SORT_EXT) { */
  449. }
  450. if (dif == 0) {
  451. /* sort by name, or tie_breaker for other sorts */
  452. if (ENABLE_LOCALE_SUPPORT)
  453. dif = strcoll(d1->name, d2->name);
  454. else
  455. dif = strcmp(d1->name, d2->name);
  456. }
  457. /* Make dif fit into an int */
  458. if (sizeof(dif) > sizeof(int)) {
  459. enum { BITS_TO_SHIFT = 8 * (sizeof(dif) - sizeof(int)) };
  460. /* shift leaving only "int" worth of bits */
  461. if (dif != 0) {
  462. dif = 1 | (int)((uoff_t)dif >> BITS_TO_SHIFT);
  463. }
  464. }
  465. return (all_fmt & SORT_REVERSE) ? -(int)dif : (int)dif;
  466. }
  467. static void dnsort(struct dnode **dn, int size)
  468. {
  469. qsort(dn, size, sizeof(*dn), sortcmp);
  470. }
  471. #else
  472. #define dnsort(dn, size) ((void)0)
  473. #endif
  474. static unsigned calc_name_len(const char *name)
  475. {
  476. unsigned len;
  477. uni_stat_t uni_stat;
  478. // TODO: quote tab as \t, etc, if -Q
  479. name = printable_string(&uni_stat, name);
  480. if (!(option_mask32 & OPT_Q)) {
  481. return uni_stat.unicode_width;
  482. }
  483. len = 2 + uni_stat.unicode_width;
  484. while (*name) {
  485. if (*name == '"' || *name == '\\') {
  486. len++;
  487. }
  488. name++;
  489. }
  490. return len;
  491. }
  492. /* Return the number of used columns.
  493. * Note that only STYLE_COLUMNS uses return value.
  494. * STYLE_SINGLE and STYLE_LONG don't care.
  495. * coreutils 7.2 also supports:
  496. * ls -b (--escape) = octal escapes (although it doesn't look like working)
  497. * ls -N (--literal) = not escape at all
  498. */
  499. static unsigned print_name(const char *name)
  500. {
  501. unsigned len;
  502. uni_stat_t uni_stat;
  503. // TODO: quote tab as \t, etc, if -Q
  504. name = printable_string(&uni_stat, name);
  505. if (!(option_mask32 & OPT_Q)) {
  506. fputs(name, stdout);
  507. return uni_stat.unicode_width;
  508. }
  509. len = 2 + uni_stat.unicode_width;
  510. putchar('"');
  511. while (*name) {
  512. if (*name == '"' || *name == '\\') {
  513. putchar('\\');
  514. len++;
  515. }
  516. putchar(*name);
  517. name++;
  518. }
  519. putchar('"');
  520. return len;
  521. }
  522. /* Return the number of used columns.
  523. * Note that only STYLE_COLUMNS uses return value,
  524. * STYLE_SINGLE and STYLE_LONG don't care.
  525. */
  526. static NOINLINE unsigned list_single(const struct dnode *dn)
  527. {
  528. unsigned column = 0;
  529. char *lpath = lpath; /* for compiler */
  530. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  531. struct stat info;
  532. char append;
  533. #endif
  534. /* Never happens:
  535. if (dn->fullname == NULL)
  536. return 0;
  537. */
  538. #if ENABLE_FEATURE_LS_FILETYPES
  539. append = append_char(dn->dstat.st_mode);
  540. #endif
  541. /* Do readlink early, so that if it fails, error message
  542. * does not appear *inside* the "ls -l" line */
  543. if (all_fmt & LIST_SYMLINK)
  544. if (S_ISLNK(dn->dstat.st_mode))
  545. lpath = xmalloc_readlink_or_warn(dn->fullname);
  546. if (all_fmt & LIST_INO)
  547. column += printf("%7llu ", (long long) dn->dstat.st_ino);
  548. if (all_fmt & LIST_BLOCKS)
  549. column += printf("%4"OFF_FMT"u ", (off_t) (dn->dstat.st_blocks >> 1));
  550. if (all_fmt & LIST_MODEBITS)
  551. column += printf("%-10s ", (char *) bb_mode_string(dn->dstat.st_mode));
  552. if (all_fmt & LIST_NLINKS)
  553. column += printf("%4lu ", (long) dn->dstat.st_nlink);
  554. #if ENABLE_FEATURE_LS_USERNAME
  555. if (all_fmt & LIST_ID_NAME) {
  556. if (option_mask32 & OPT_g) {
  557. column += printf("%-8.8s ",
  558. get_cached_groupname(dn->dstat.st_gid));
  559. } else {
  560. column += printf("%-8.8s %-8.8s ",
  561. get_cached_username(dn->dstat.st_uid),
  562. get_cached_groupname(dn->dstat.st_gid));
  563. }
  564. }
  565. #endif
  566. if (all_fmt & LIST_ID_NUMERIC) {
  567. if (option_mask32 & OPT_g)
  568. column += printf("%-8u ", (int) dn->dstat.st_gid);
  569. else
  570. column += printf("%-8u %-8u ",
  571. (int) dn->dstat.st_uid,
  572. (int) dn->dstat.st_gid);
  573. }
  574. if (all_fmt & (LIST_SIZE /*|LIST_DEV*/ )) {
  575. if (S_ISBLK(dn->dstat.st_mode) || S_ISCHR(dn->dstat.st_mode)) {
  576. column += printf("%4u, %3u ",
  577. (int) major(dn->dstat.st_rdev),
  578. (int) minor(dn->dstat.st_rdev));
  579. } else {
  580. if (all_fmt & LS_DISP_HR) {
  581. column += printf("%"HUMAN_READABLE_MAX_WIDTH_STR"s ",
  582. /* print st_size, show one fractional, use suffixes */
  583. make_human_readable_str(dn->dstat.st_size, 1, 0)
  584. );
  585. } else {
  586. column += printf("%9"OFF_FMT"u ", (off_t) dn->dstat.st_size);
  587. }
  588. }
  589. }
  590. #if ENABLE_FEATURE_LS_TIMESTAMPS
  591. if (all_fmt & (LIST_FULLTIME|LIST_DATE_TIME)) {
  592. char *filetime;
  593. time_t ttime = dn->dstat.st_mtime;
  594. if (all_fmt & TIME_ACCESS)
  595. ttime = dn->dstat.st_atime;
  596. if (all_fmt & TIME_CHANGE)
  597. ttime = dn->dstat.st_ctime;
  598. filetime = ctime(&ttime);
  599. /* filetime's format: "Wed Jun 30 21:49:08 1993\n" */
  600. if (all_fmt & LIST_FULLTIME)
  601. column += printf("%.24s ", filetime);
  602. else { /* LIST_DATE_TIME */
  603. /* current_time_t ~== time(NULL) */
  604. time_t age = current_time_t - ttime;
  605. printf("%.6s ", filetime + 4); /* "Jun 30" */
  606. if (age < 3600L * 24 * 365 / 2 && age > -15 * 60) {
  607. /* hh:mm if less than 6 months old */
  608. printf("%.5s ", filetime + 11);
  609. } else { /* year. buggy if year > 9999 ;) */
  610. printf(" %.4s ", filetime + 20);
  611. }
  612. column += 13;
  613. }
  614. }
  615. #endif
  616. #if ENABLE_SELINUX
  617. if (all_fmt & LIST_CONTEXT) {
  618. column += printf("%-32s ", dn->sid ? dn->sid : "unknown");
  619. freecon(dn->sid);
  620. }
  621. #endif
  622. if (all_fmt & LIST_FILENAME) {
  623. #if ENABLE_FEATURE_LS_COLOR
  624. if (show_color) {
  625. info.st_mode = 0; /* for fgcolor() */
  626. lstat(dn->fullname, &info);
  627. printf("\033[%u;%um", bold(info.st_mode),
  628. fgcolor(info.st_mode));
  629. }
  630. #endif
  631. column += print_name(dn->name);
  632. if (show_color) {
  633. printf("\033[0m");
  634. }
  635. }
  636. if (all_fmt & LIST_SYMLINK) {
  637. if (S_ISLNK(dn->dstat.st_mode) && lpath) {
  638. printf(" -> ");
  639. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  640. #if ENABLE_FEATURE_LS_COLOR
  641. info.st_mode = 0; /* for fgcolor() */
  642. #endif
  643. if (stat(dn->fullname, &info) == 0) {
  644. append = append_char(info.st_mode);
  645. }
  646. #endif
  647. #if ENABLE_FEATURE_LS_COLOR
  648. if (show_color) {
  649. printf("\033[%u;%um", bold(info.st_mode),
  650. fgcolor(info.st_mode));
  651. }
  652. #endif
  653. column += print_name(lpath) + 4;
  654. if (show_color) {
  655. printf("\033[0m");
  656. }
  657. free(lpath);
  658. }
  659. }
  660. #if ENABLE_FEATURE_LS_FILETYPES
  661. if (all_fmt & LIST_FILETYPE) {
  662. if (append) {
  663. putchar(append);
  664. column++;
  665. }
  666. }
  667. #endif
  668. return column;
  669. }
  670. static void showfiles(struct dnode **dn, unsigned nfiles)
  671. {
  672. unsigned i, ncols, nrows, row, nc;
  673. unsigned column = 0;
  674. unsigned nexttab = 0;
  675. unsigned column_width = 0; /* used only by STYLE_COLUMNS */
  676. if (all_fmt & STYLE_LONG) { /* STYLE_LONG or STYLE_SINGLE */
  677. ncols = 1;
  678. } else {
  679. /* find the longest file name, use that as the column width */
  680. for (i = 0; dn[i]; i++) {
  681. int len = calc_name_len(dn[i]->name);
  682. if (column_width < len)
  683. column_width = len;
  684. }
  685. column_width += tabstops +
  686. IF_SELINUX( ((all_fmt & LIST_CONTEXT) ? 33 : 0) + )
  687. ((all_fmt & LIST_INO) ? 8 : 0) +
  688. ((all_fmt & LIST_BLOCKS) ? 5 : 0);
  689. ncols = (int) (terminal_width / column_width);
  690. }
  691. if (ncols > 1) {
  692. nrows = nfiles / ncols;
  693. if (nrows * ncols < nfiles)
  694. nrows++; /* round up fractionals */
  695. } else {
  696. nrows = nfiles;
  697. ncols = 1;
  698. }
  699. for (row = 0; row < nrows; row++) {
  700. for (nc = 0; nc < ncols; nc++) {
  701. /* reach into the array based on the column and row */
  702. if (all_fmt & DISP_ROWS)
  703. i = (row * ncols) + nc; /* display across row */
  704. else
  705. i = (nc * nrows) + row; /* display by column */
  706. if (i < nfiles) {
  707. if (column > 0) {
  708. nexttab -= column;
  709. printf("%*s", nexttab, "");
  710. column += nexttab;
  711. }
  712. nexttab = column + column_width;
  713. column += list_single(dn[i]);
  714. }
  715. }
  716. putchar('\n');
  717. column = 0;
  718. }
  719. }
  720. #if ENABLE_DESKTOP
  721. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/ls.html
  722. * If any of the -l, -n, -s options is specified, each list
  723. * of files within the directory shall be preceded by a
  724. * status line indicating the number of file system blocks
  725. * occupied by files in the directory in 512-byte units if
  726. * the -k option is not specified, or 1024-byte units if the
  727. * -k option is specified, rounded up to the next integral
  728. * number of units.
  729. */
  730. /* by Jorgen Overgaard (jorgen AT antistaten.se) */
  731. static off_t calculate_blocks(struct dnode **dn)
  732. {
  733. uoff_t blocks = 1;
  734. if (dn) {
  735. while (*dn) {
  736. /* st_blocks is in 512 byte blocks */
  737. blocks += (*dn)->dstat.st_blocks;
  738. dn++;
  739. }
  740. }
  741. /* Even though standard says use 512 byte blocks, coreutils use 1k */
  742. /* Actually, we round up by calculating (blocks + 1) / 2,
  743. * "+ 1" was done when we initialized blocks to 1 */
  744. return blocks >> 1;
  745. }
  746. #endif
  747. static struct dnode **list_dir(const char *, unsigned *);
  748. static void showdirs(struct dnode **dn, int first)
  749. {
  750. unsigned nfiles;
  751. unsigned dndirs;
  752. struct dnode **subdnp;
  753. struct dnode **dnd;
  754. /* Never happens:
  755. if (dn == NULL || ndirs < 1) {
  756. return;
  757. }
  758. */
  759. for (; *dn; dn++) {
  760. if (all_fmt & (DISP_DIRNAME | DISP_RECURSIVE)) {
  761. if (!first)
  762. bb_putchar('\n');
  763. first = 0;
  764. printf("%s:\n", (*dn)->fullname);
  765. }
  766. subdnp = list_dir((*dn)->fullname, &nfiles);
  767. #if ENABLE_DESKTOP
  768. if ((all_fmt & STYLE_MASK) == STYLE_LONG)
  769. printf("total %"OFF_FMT"u\n", calculate_blocks(subdnp));
  770. #endif
  771. if (nfiles > 0) {
  772. /* list all files at this level */
  773. dnsort(subdnp, nfiles);
  774. showfiles(subdnp, nfiles);
  775. if (ENABLE_FEATURE_LS_RECURSIVE
  776. && (all_fmt & DISP_RECURSIVE)
  777. ) {
  778. /* recursive - list the sub-dirs */
  779. dnd = splitdnarray(subdnp, SPLIT_SUBDIR);
  780. dndirs = count_dirs(subdnp, SPLIT_SUBDIR);
  781. if (dndirs > 0) {
  782. dnsort(dnd, dndirs);
  783. showdirs(dnd, 0);
  784. /* free the array of dnode pointers to the dirs */
  785. free(dnd);
  786. }
  787. }
  788. /* free the dnodes and the fullname mem */
  789. dfree(subdnp);
  790. }
  791. }
  792. }
  793. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  794. static struct dnode **list_dir(const char *path, unsigned *nfiles_p)
  795. {
  796. struct dnode *dn, *cur, **dnp;
  797. struct dirent *entry;
  798. DIR *dir;
  799. unsigned i, nfiles;
  800. /* Never happens:
  801. if (path == NULL)
  802. return NULL;
  803. */
  804. *nfiles_p = 0;
  805. dir = warn_opendir(path);
  806. if (dir == NULL) {
  807. exit_code = EXIT_FAILURE;
  808. return NULL; /* could not open the dir */
  809. }
  810. dn = NULL;
  811. nfiles = 0;
  812. while ((entry = readdir(dir)) != NULL) {
  813. char *fullname;
  814. /* are we going to list the file- it may be . or .. or a hidden file */
  815. if (entry->d_name[0] == '.') {
  816. if ((!entry->d_name[1] || (entry->d_name[1] == '.' && !entry->d_name[2]))
  817. && !(all_fmt & DISP_DOT)
  818. ) {
  819. continue;
  820. }
  821. if (!(all_fmt & DISP_HIDDEN))
  822. continue;
  823. }
  824. fullname = concat_path_file(path, entry->d_name);
  825. cur = my_stat(fullname, bb_basename(fullname), 0);
  826. if (!cur) {
  827. free(fullname);
  828. continue;
  829. }
  830. cur->fname_allocated = 1;
  831. cur->next = dn;
  832. dn = cur;
  833. nfiles++;
  834. }
  835. closedir(dir);
  836. if (dn == NULL)
  837. return NULL;
  838. /* now that we know how many files there are
  839. * allocate memory for an array to hold dnode pointers
  840. */
  841. *nfiles_p = nfiles;
  842. dnp = dnalloc(nfiles);
  843. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  844. dnp[i] = dn; /* save pointer to node in array */
  845. dn = dn->next;
  846. if (!dn)
  847. break;
  848. }
  849. return dnp;
  850. }
  851. int ls_main(int argc UNUSED_PARAM, char **argv)
  852. {
  853. struct dnode **dnd;
  854. struct dnode **dnf;
  855. struct dnode **dnp;
  856. struct dnode *dn;
  857. struct dnode *cur;
  858. unsigned opt;
  859. unsigned nfiles;
  860. unsigned dnfiles;
  861. unsigned dndirs;
  862. unsigned i;
  863. #if ENABLE_FEATURE_LS_COLOR
  864. /* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
  865. /* coreutils 6.10:
  866. * # ls --color=BOGUS
  867. * ls: invalid argument 'BOGUS' for '--color'
  868. * Valid arguments are:
  869. * 'always', 'yes', 'force'
  870. * 'never', 'no', 'none'
  871. * 'auto', 'tty', 'if-tty'
  872. * (and substrings: "--color=alwa" work too)
  873. */
  874. static const char ls_longopts[] ALIGN1 =
  875. "color\0" Optional_argument "\xff"; /* no short equivalent */
  876. static const char color_str[] ALIGN1 =
  877. "always\0""yes\0""force\0"
  878. "auto\0""tty\0""if-tty\0";
  879. /* need to initialize since --color has _an optional_ argument */
  880. const char *color_opt = color_str; /* "always" */
  881. #endif
  882. INIT_G();
  883. init_unicode();
  884. all_fmt = LIST_SHORT |
  885. (ENABLE_FEATURE_LS_SORTFILES * (SORT_NAME | SORT_FORWARD));
  886. #if ENABLE_FEATURE_AUTOWIDTH
  887. /* obtain the terminal width */
  888. get_terminal_width_height(STDIN_FILENO, &terminal_width, NULL);
  889. /* go one less... */
  890. terminal_width--;
  891. #endif
  892. /* process options */
  893. IF_FEATURE_LS_COLOR(applet_long_options = ls_longopts;)
  894. #if ENABLE_FEATURE_AUTOWIDTH
  895. opt_complementary = "T+:w+"; /* -T N, -w N */
  896. opt = getopt32(argv, ls_options, &tabstops, &terminal_width
  897. IF_FEATURE_LS_COLOR(, &color_opt));
  898. #else
  899. opt = getopt32(argv, ls_options IF_FEATURE_LS_COLOR(, &color_opt));
  900. #endif
  901. for (i = 0; opt_flags[i] != (1U<<31); i++) {
  902. if (opt & (1 << i)) {
  903. unsigned flags = opt_flags[i];
  904. if (flags & LIST_MASK_TRIGGER)
  905. all_fmt &= ~LIST_MASK;
  906. if (flags & STYLE_MASK_TRIGGER)
  907. all_fmt &= ~STYLE_MASK;
  908. if (flags & SORT_MASK_TRIGGER)
  909. all_fmt &= ~SORT_MASK;
  910. if (flags & DISP_MASK_TRIGGER)
  911. all_fmt &= ~DISP_MASK;
  912. if (flags & TIME_MASK)
  913. all_fmt &= ~TIME_MASK;
  914. if (flags & LIST_CONTEXT)
  915. all_fmt |= STYLE_SINGLE;
  916. /* huh?? opt cannot be 'l' */
  917. //if (LS_DISP_HR && opt == 'l')
  918. // all_fmt &= ~LS_DISP_HR;
  919. all_fmt |= flags;
  920. }
  921. }
  922. #if ENABLE_FEATURE_LS_COLOR
  923. /* find color bit value - last position for short getopt */
  924. if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
  925. char *p = getenv("LS_COLORS");
  926. /* LS_COLORS is unset, or (not empty && not "none") ? */
  927. if (!p || (p[0] && strcmp(p, "none") != 0))
  928. show_color = 1;
  929. }
  930. if (opt & OPT_color) {
  931. if (color_opt[0] == 'n')
  932. show_color = 0;
  933. else switch (index_in_substrings(color_str, color_opt)) {
  934. case 3:
  935. case 4:
  936. case 5:
  937. if (isatty(STDOUT_FILENO)) {
  938. case 0:
  939. case 1:
  940. case 2:
  941. show_color = 1;
  942. }
  943. }
  944. }
  945. #endif
  946. /* sort out which command line options take precedence */
  947. if (ENABLE_FEATURE_LS_RECURSIVE && (all_fmt & DISP_NOLIST))
  948. all_fmt &= ~DISP_RECURSIVE; /* no recurse if listing only dir */
  949. if (ENABLE_FEATURE_LS_TIMESTAMPS && ENABLE_FEATURE_LS_SORTFILES) {
  950. if (all_fmt & TIME_CHANGE)
  951. all_fmt = (all_fmt & ~SORT_MASK) | SORT_CTIME;
  952. if (all_fmt & TIME_ACCESS)
  953. all_fmt = (all_fmt & ~SORT_MASK) | SORT_ATIME;
  954. }
  955. if ((all_fmt & STYLE_MASK) != STYLE_LONG) /* only for long list */
  956. all_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
  957. if (ENABLE_FEATURE_LS_USERNAME)
  958. if ((all_fmt & STYLE_MASK) == STYLE_LONG && (all_fmt & LIST_ID_NUMERIC))
  959. all_fmt &= ~LIST_ID_NAME; /* don't list names if numeric uid */
  960. /* choose a display format */
  961. if (!(all_fmt & STYLE_MASK))
  962. all_fmt |= (isatty(STDOUT_FILENO) ? STYLE_COLUMNS : STYLE_SINGLE);
  963. argv += optind;
  964. if (!argv[0])
  965. *--argv = (char*)".";
  966. if (argv[1])
  967. all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
  968. /* stuff the command line file names into a dnode array */
  969. dn = NULL;
  970. nfiles = 0;
  971. do {
  972. /* NB: follow links on command line unless -l or -s */
  973. cur = my_stat(*argv, *argv, !(all_fmt & (STYLE_LONG|LIST_BLOCKS)));
  974. argv++;
  975. if (!cur)
  976. continue;
  977. cur->fname_allocated = 0;
  978. cur->next = dn;
  979. dn = cur;
  980. nfiles++;
  981. } while (*argv);
  982. /* nfiles _may_ be 0 here - try "ls doesnt_exist" */
  983. if (nfiles == 0)
  984. return exit_code;
  985. /* now that we know how many files there are
  986. * allocate memory for an array to hold dnode pointers
  987. */
  988. dnp = dnalloc(nfiles);
  989. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  990. dnp[i] = dn; /* save pointer to node in array */
  991. dn = dn->next;
  992. if (!dn)
  993. break;
  994. }
  995. if (all_fmt & DISP_NOLIST) {
  996. dnsort(dnp, nfiles);
  997. showfiles(dnp, nfiles);
  998. } else {
  999. dnd = splitdnarray(dnp, SPLIT_DIR);
  1000. dnf = splitdnarray(dnp, SPLIT_FILE);
  1001. dndirs = count_dirs(dnp, SPLIT_DIR);
  1002. dnfiles = nfiles - dndirs;
  1003. if (dnfiles > 0) {
  1004. dnsort(dnf, dnfiles);
  1005. showfiles(dnf, dnfiles);
  1006. if (ENABLE_FEATURE_CLEAN_UP)
  1007. free(dnf);
  1008. }
  1009. if (dndirs > 0) {
  1010. dnsort(dnd, dndirs);
  1011. showdirs(dnd, dnfiles == 0);
  1012. if (ENABLE_FEATURE_CLEAN_UP)
  1013. free(dnd);
  1014. }
  1015. }
  1016. if (ENABLE_FEATURE_CLEAN_UP)
  1017. dfree(dnp);
  1018. return exit_code;
  1019. }