ls.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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 tarball for details.
  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 group) - 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. }
  518. putchar('"');
  519. return len;
  520. }
  521. /* Return the number of used columns.
  522. * Note that only STYLE_COLUMNS uses return value,
  523. * STYLE_SINGLE and STYLE_LONG don't care.
  524. */
  525. static NOINLINE unsigned list_single(const struct dnode *dn)
  526. {
  527. unsigned column = 0;
  528. char *lpath = lpath; /* for compiler */
  529. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  530. struct stat info;
  531. char append;
  532. #endif
  533. /* Never happens:
  534. if (dn->fullname == NULL)
  535. return 0;
  536. */
  537. #if ENABLE_FEATURE_LS_FILETYPES
  538. append = append_char(dn->dstat.st_mode);
  539. #endif
  540. /* Do readlink early, so that if it fails, error message
  541. * does not appear *inside* the "ls -l" line */
  542. if (all_fmt & LIST_SYMLINK)
  543. if (S_ISLNK(dn->dstat.st_mode))
  544. lpath = xmalloc_readlink_or_warn(dn->fullname);
  545. if (all_fmt & LIST_INO)
  546. column += printf("%7llu ", (long long) dn->dstat.st_ino);
  547. if (all_fmt & LIST_BLOCKS)
  548. column += printf("%4"OFF_FMT"u ", (off_t) (dn->dstat.st_blocks >> 1));
  549. if (all_fmt & LIST_MODEBITS)
  550. column += printf("%-10s ", (char *) bb_mode_string(dn->dstat.st_mode));
  551. if (all_fmt & LIST_NLINKS)
  552. column += printf("%4lu ", (long) dn->dstat.st_nlink);
  553. #if ENABLE_FEATURE_LS_USERNAME
  554. if (all_fmt & LIST_ID_NAME) {
  555. if (option_mask32 & OPT_g) {
  556. column += printf("%-8.8s ",
  557. get_cached_username(dn->dstat.st_uid));
  558. } else {
  559. column += printf("%-8.8s %-8.8s ",
  560. get_cached_username(dn->dstat.st_uid),
  561. get_cached_groupname(dn->dstat.st_gid));
  562. }
  563. }
  564. #endif
  565. if (all_fmt & LIST_ID_NUMERIC) {
  566. if (option_mask32 & OPT_g)
  567. column += printf("%-8u ", (int) dn->dstat.st_uid);
  568. else
  569. column += printf("%-8u %-8u ",
  570. (int) dn->dstat.st_uid,
  571. (int) dn->dstat.st_gid);
  572. }
  573. if (all_fmt & (LIST_SIZE /*|LIST_DEV*/ )) {
  574. if (S_ISBLK(dn->dstat.st_mode) || S_ISCHR(dn->dstat.st_mode)) {
  575. column += printf("%4u, %3u ",
  576. (int) major(dn->dstat.st_rdev),
  577. (int) minor(dn->dstat.st_rdev));
  578. } else {
  579. if (all_fmt & LS_DISP_HR) {
  580. column += printf("%"HUMAN_READABLE_MAX_WIDTH_STR"s ",
  581. /* print st_size, show one fractional, use suffixes */
  582. make_human_readable_str(dn->dstat.st_size, 1, 0)
  583. );
  584. } else {
  585. column += printf("%9"OFF_FMT"u ", (off_t) dn->dstat.st_size);
  586. }
  587. }
  588. }
  589. #if ENABLE_FEATURE_LS_TIMESTAMPS
  590. if (all_fmt & (LIST_FULLTIME|LIST_DATE_TIME)) {
  591. char *filetime;
  592. time_t ttime = dn->dstat.st_mtime;
  593. if (all_fmt & TIME_ACCESS)
  594. ttime = dn->dstat.st_atime;
  595. if (all_fmt & TIME_CHANGE)
  596. ttime = dn->dstat.st_ctime;
  597. filetime = ctime(&ttime);
  598. /* filetime's format: "Wed Jun 30 21:49:08 1993\n" */
  599. if (all_fmt & LIST_FULLTIME)
  600. column += printf("%.24s ", filetime);
  601. else { /* LIST_DATE_TIME */
  602. /* current_time_t ~== time(NULL) */
  603. time_t age = current_time_t - ttime;
  604. printf("%.6s ", filetime + 4); /* "Jun 30" */
  605. if (age < 3600L * 24 * 365 / 2 && age > -15 * 60) {
  606. /* hh:mm if less than 6 months old */
  607. printf("%.5s ", filetime + 11);
  608. } else { /* year. buggy if year > 9999 ;) */
  609. printf(" %.4s ", filetime + 20);
  610. }
  611. column += 13;
  612. }
  613. }
  614. #endif
  615. #if ENABLE_SELINUX
  616. if (all_fmt & LIST_CONTEXT) {
  617. column += printf("%-32s ", dn->sid ? dn->sid : "unknown");
  618. freecon(dn->sid);
  619. }
  620. #endif
  621. if (all_fmt & LIST_FILENAME) {
  622. #if ENABLE_FEATURE_LS_COLOR
  623. if (show_color) {
  624. info.st_mode = 0; /* for fgcolor() */
  625. lstat(dn->fullname, &info);
  626. printf("\033[%u;%um", bold(info.st_mode),
  627. fgcolor(info.st_mode));
  628. }
  629. #endif
  630. column += print_name(dn->name);
  631. if (show_color) {
  632. printf("\033[0m");
  633. }
  634. }
  635. if (all_fmt & LIST_SYMLINK) {
  636. if (S_ISLNK(dn->dstat.st_mode) && lpath) {
  637. printf(" -> ");
  638. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  639. #if ENABLE_FEATURE_LS_COLOR
  640. info.st_mode = 0; /* for fgcolor() */
  641. #endif
  642. if (stat(dn->fullname, &info) == 0) {
  643. append = append_char(info.st_mode);
  644. }
  645. #endif
  646. #if ENABLE_FEATURE_LS_COLOR
  647. if (show_color) {
  648. printf("\033[%u;%um", bold(info.st_mode),
  649. fgcolor(info.st_mode));
  650. }
  651. #endif
  652. column += print_name(lpath) + 4;
  653. if (show_color) {
  654. printf("\033[0m");
  655. }
  656. free(lpath);
  657. }
  658. }
  659. #if ENABLE_FEATURE_LS_FILETYPES
  660. if (all_fmt & LIST_FILETYPE) {
  661. if (append) {
  662. putchar(append);
  663. column++;
  664. }
  665. }
  666. #endif
  667. return column;
  668. }
  669. static void showfiles(struct dnode **dn, unsigned nfiles)
  670. {
  671. unsigned i, ncols, nrows, row, nc;
  672. unsigned column = 0;
  673. unsigned nexttab = 0;
  674. unsigned column_width = 0; /* used only by STYLE_COLUMNS */
  675. if (all_fmt & STYLE_LONG) { /* STYLE_LONG or STYLE_SINGLE */
  676. ncols = 1;
  677. } else {
  678. /* find the longest file name, use that as the column width */
  679. for (i = 0; dn[i]; i++) {
  680. int len = calc_name_len(dn[i]->name);
  681. if (column_width < len)
  682. column_width = len;
  683. }
  684. column_width += tabstops +
  685. IF_SELINUX( ((all_fmt & LIST_CONTEXT) ? 33 : 0) + )
  686. ((all_fmt & LIST_INO) ? 8 : 0) +
  687. ((all_fmt & LIST_BLOCKS) ? 5 : 0);
  688. ncols = (int) (terminal_width / column_width);
  689. }
  690. if (ncols > 1) {
  691. nrows = nfiles / ncols;
  692. if (nrows * ncols < nfiles)
  693. nrows++; /* round up fractionals */
  694. } else {
  695. nrows = nfiles;
  696. ncols = 1;
  697. }
  698. for (row = 0; row < nrows; row++) {
  699. for (nc = 0; nc < ncols; nc++) {
  700. /* reach into the array based on the column and row */
  701. if (all_fmt & DISP_ROWS)
  702. i = (row * ncols) + nc; /* display across row */
  703. else
  704. i = (nc * nrows) + row; /* display by column */
  705. if (i < nfiles) {
  706. if (column > 0) {
  707. nexttab -= column;
  708. printf("%*s", nexttab, "");
  709. column += nexttab;
  710. }
  711. nexttab = column + column_width;
  712. column += list_single(dn[i]);
  713. }
  714. }
  715. putchar('\n');
  716. column = 0;
  717. }
  718. }
  719. #if ENABLE_DESKTOP
  720. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/ls.html
  721. * If any of the -l, -n, -s options is specified, each list
  722. * of files within the directory shall be preceded by a
  723. * status line indicating the number of file system blocks
  724. * occupied by files in the directory in 512-byte units if
  725. * the -k option is not specified, or 1024-byte units if the
  726. * -k option is specified, rounded up to the next integral
  727. * number of units.
  728. */
  729. /* by Jorgen Overgaard (jorgen AT antistaten.se) */
  730. static off_t calculate_blocks(struct dnode **dn)
  731. {
  732. uoff_t blocks = 1;
  733. if (dn) {
  734. while (*dn) {
  735. /* st_blocks is in 512 byte blocks */
  736. blocks += (*dn)->dstat.st_blocks;
  737. dn++;
  738. }
  739. }
  740. /* Even though standard says use 512 byte blocks, coreutils use 1k */
  741. /* Actually, we round up by calculating (blocks + 1) / 2,
  742. * "+ 1" was done when we initialized blocks to 1 */
  743. return blocks >> 1;
  744. }
  745. #endif
  746. static struct dnode **list_dir(const char *, unsigned *);
  747. static void showdirs(struct dnode **dn, int first)
  748. {
  749. unsigned nfiles;
  750. unsigned dndirs;
  751. struct dnode **subdnp;
  752. struct dnode **dnd;
  753. /* Never happens:
  754. if (dn == NULL || ndirs < 1) {
  755. return;
  756. }
  757. */
  758. for (; *dn; dn++) {
  759. if (all_fmt & (DISP_DIRNAME | DISP_RECURSIVE)) {
  760. if (!first)
  761. bb_putchar('\n');
  762. first = 0;
  763. printf("%s:\n", (*dn)->fullname);
  764. }
  765. subdnp = list_dir((*dn)->fullname, &nfiles);
  766. #if ENABLE_DESKTOP
  767. if ((all_fmt & STYLE_MASK) == STYLE_LONG)
  768. printf("total %"OFF_FMT"u\n", calculate_blocks(subdnp));
  769. #endif
  770. if (nfiles > 0) {
  771. /* list all files at this level */
  772. dnsort(subdnp, nfiles);
  773. showfiles(subdnp, nfiles);
  774. if (ENABLE_FEATURE_LS_RECURSIVE
  775. && (all_fmt & DISP_RECURSIVE)
  776. ) {
  777. /* recursive - list the sub-dirs */
  778. dnd = splitdnarray(subdnp, SPLIT_SUBDIR);
  779. dndirs = count_dirs(subdnp, SPLIT_SUBDIR);
  780. if (dndirs > 0) {
  781. dnsort(dnd, dndirs);
  782. showdirs(dnd, 0);
  783. /* free the array of dnode pointers to the dirs */
  784. free(dnd);
  785. }
  786. }
  787. /* free the dnodes and the fullname mem */
  788. dfree(subdnp);
  789. }
  790. }
  791. }
  792. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  793. static struct dnode **list_dir(const char *path, unsigned *nfiles_p)
  794. {
  795. struct dnode *dn, *cur, **dnp;
  796. struct dirent *entry;
  797. DIR *dir;
  798. unsigned i, nfiles;
  799. /* Never happens:
  800. if (path == NULL)
  801. return NULL;
  802. */
  803. *nfiles_p = 0;
  804. dir = warn_opendir(path);
  805. if (dir == NULL) {
  806. exit_code = EXIT_FAILURE;
  807. return NULL; /* could not open the dir */
  808. }
  809. dn = NULL;
  810. nfiles = 0;
  811. while ((entry = readdir(dir)) != NULL) {
  812. char *fullname;
  813. /* are we going to list the file- it may be . or .. or a hidden file */
  814. if (entry->d_name[0] == '.') {
  815. if ((!entry->d_name[1] || (entry->d_name[1] == '.' && !entry->d_name[2]))
  816. && !(all_fmt & DISP_DOT)
  817. ) {
  818. continue;
  819. }
  820. if (!(all_fmt & DISP_HIDDEN))
  821. continue;
  822. }
  823. fullname = concat_path_file(path, entry->d_name);
  824. cur = my_stat(fullname, bb_basename(fullname), 0);
  825. if (!cur) {
  826. free(fullname);
  827. continue;
  828. }
  829. cur->fname_allocated = 1;
  830. cur->next = dn;
  831. dn = cur;
  832. nfiles++;
  833. }
  834. closedir(dir);
  835. if (dn == NULL)
  836. return NULL;
  837. /* now that we know how many files there are
  838. * allocate memory for an array to hold dnode pointers
  839. */
  840. *nfiles_p = nfiles;
  841. dnp = dnalloc(nfiles);
  842. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  843. dnp[i] = dn; /* save pointer to node in array */
  844. dn = dn->next;
  845. if (!dn)
  846. break;
  847. }
  848. return dnp;
  849. }
  850. int ls_main(int argc UNUSED_PARAM, char **argv)
  851. {
  852. struct dnode **dnd;
  853. struct dnode **dnf;
  854. struct dnode **dnp;
  855. struct dnode *dn;
  856. struct dnode *cur;
  857. unsigned opt;
  858. unsigned nfiles;
  859. unsigned dnfiles;
  860. unsigned dndirs;
  861. unsigned i;
  862. #if ENABLE_FEATURE_LS_COLOR
  863. /* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
  864. /* coreutils 6.10:
  865. * # ls --color=BOGUS
  866. * ls: invalid argument 'BOGUS' for '--color'
  867. * Valid arguments are:
  868. * 'always', 'yes', 'force'
  869. * 'never', 'no', 'none'
  870. * 'auto', 'tty', 'if-tty'
  871. * (and substrings: "--color=alwa" work too)
  872. */
  873. static const char ls_longopts[] ALIGN1 =
  874. "color\0" Optional_argument "\xff"; /* no short equivalent */
  875. static const char color_str[] ALIGN1 =
  876. "always\0""yes\0""force\0"
  877. "auto\0""tty\0""if-tty\0";
  878. /* need to initialize since --color has _an optional_ argument */
  879. const char *color_opt = color_str; /* "always" */
  880. #endif
  881. INIT_G();
  882. init_unicode();
  883. all_fmt = LIST_SHORT |
  884. (ENABLE_FEATURE_LS_SORTFILES * (SORT_NAME | SORT_FORWARD));
  885. #if ENABLE_FEATURE_AUTOWIDTH
  886. /* obtain the terminal width */
  887. get_terminal_width_height(STDIN_FILENO, &terminal_width, NULL);
  888. /* go one less... */
  889. terminal_width--;
  890. #endif
  891. /* process options */
  892. IF_FEATURE_LS_COLOR(applet_long_options = ls_longopts;)
  893. #if ENABLE_FEATURE_AUTOWIDTH
  894. opt_complementary = "T+:w+"; /* -T N, -w N */
  895. opt = getopt32(argv, ls_options, &tabstops, &terminal_width
  896. IF_FEATURE_LS_COLOR(, &color_opt));
  897. #else
  898. opt = getopt32(argv, ls_options IF_FEATURE_LS_COLOR(, &color_opt));
  899. #endif
  900. for (i = 0; opt_flags[i] != (1U<<31); i++) {
  901. if (opt & (1 << i)) {
  902. unsigned flags = opt_flags[i];
  903. if (flags & LIST_MASK_TRIGGER)
  904. all_fmt &= ~LIST_MASK;
  905. if (flags & STYLE_MASK_TRIGGER)
  906. all_fmt &= ~STYLE_MASK;
  907. if (flags & SORT_MASK_TRIGGER)
  908. all_fmt &= ~SORT_MASK;
  909. if (flags & DISP_MASK_TRIGGER)
  910. all_fmt &= ~DISP_MASK;
  911. if (flags & TIME_MASK)
  912. all_fmt &= ~TIME_MASK;
  913. if (flags & LIST_CONTEXT)
  914. all_fmt |= STYLE_SINGLE;
  915. /* huh?? opt cannot be 'l' */
  916. //if (LS_DISP_HR && opt == 'l')
  917. // all_fmt &= ~LS_DISP_HR;
  918. all_fmt |= flags;
  919. }
  920. }
  921. #if ENABLE_FEATURE_LS_COLOR
  922. /* find color bit value - last position for short getopt */
  923. if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
  924. char *p = getenv("LS_COLORS");
  925. /* LS_COLORS is unset, or (not empty && not "none") ? */
  926. if (!p || (p[0] && strcmp(p, "none") != 0))
  927. show_color = 1;
  928. }
  929. if (opt & OPT_color) {
  930. if (color_opt[0] == 'n')
  931. show_color = 0;
  932. else switch (index_in_substrings(color_str, color_opt)) {
  933. case 3:
  934. case 4:
  935. case 5:
  936. if (isatty(STDOUT_FILENO)) {
  937. case 0:
  938. case 1:
  939. case 2:
  940. show_color = 1;
  941. }
  942. }
  943. }
  944. #endif
  945. /* sort out which command line options take precedence */
  946. if (ENABLE_FEATURE_LS_RECURSIVE && (all_fmt & DISP_NOLIST))
  947. all_fmt &= ~DISP_RECURSIVE; /* no recurse if listing only dir */
  948. if (ENABLE_FEATURE_LS_TIMESTAMPS && ENABLE_FEATURE_LS_SORTFILES) {
  949. if (all_fmt & TIME_CHANGE)
  950. all_fmt = (all_fmt & ~SORT_MASK) | SORT_CTIME;
  951. if (all_fmt & TIME_ACCESS)
  952. all_fmt = (all_fmt & ~SORT_MASK) | SORT_ATIME;
  953. }
  954. if ((all_fmt & STYLE_MASK) != STYLE_LONG) /* only for long list */
  955. all_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
  956. if (ENABLE_FEATURE_LS_USERNAME)
  957. if ((all_fmt & STYLE_MASK) == STYLE_LONG && (all_fmt & LIST_ID_NUMERIC))
  958. all_fmt &= ~LIST_ID_NAME; /* don't list names if numeric uid */
  959. /* choose a display format */
  960. if (!(all_fmt & STYLE_MASK))
  961. all_fmt |= (isatty(STDOUT_FILENO) ? STYLE_COLUMNS : STYLE_SINGLE);
  962. argv += optind;
  963. if (!argv[0])
  964. *--argv = (char*)".";
  965. if (argv[1])
  966. all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
  967. /* stuff the command line file names into a dnode array */
  968. dn = NULL;
  969. nfiles = 0;
  970. do {
  971. /* NB: follow links on command line unless -l or -s */
  972. cur = my_stat(*argv, *argv, !(all_fmt & (STYLE_LONG|LIST_BLOCKS)));
  973. argv++;
  974. if (!cur)
  975. continue;
  976. cur->fname_allocated = 0;
  977. cur->next = dn;
  978. dn = cur;
  979. nfiles++;
  980. } while (*argv);
  981. /* nfiles _may_ be 0 here - try "ls doesnt_exist" */
  982. if (nfiles == 0)
  983. return exit_code;
  984. /* now that we know how many files there are
  985. * allocate memory for an array to hold dnode pointers
  986. */
  987. dnp = dnalloc(nfiles);
  988. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  989. dnp[i] = dn; /* save pointer to node in array */
  990. dn = dn->next;
  991. if (!dn)
  992. break;
  993. }
  994. if (all_fmt & DISP_NOLIST) {
  995. dnsort(dnp, nfiles);
  996. showfiles(dnp, nfiles);
  997. } else {
  998. dnd = splitdnarray(dnp, SPLIT_DIR);
  999. dnf = splitdnarray(dnp, SPLIT_FILE);
  1000. dndirs = count_dirs(dnp, SPLIT_DIR);
  1001. dnfiles = nfiles - dndirs;
  1002. if (dnfiles > 0) {
  1003. dnsort(dnf, dnfiles);
  1004. showfiles(dnf, dnfiles);
  1005. if (ENABLE_FEATURE_CLEAN_UP)
  1006. free(dnf);
  1007. }
  1008. if (dndirs > 0) {
  1009. dnsort(dnd, dndirs);
  1010. showdirs(dnd, dnfiles == 0);
  1011. if (ENABLE_FEATURE_CLEAN_UP)
  1012. free(dnd);
  1013. }
  1014. }
  1015. if (ENABLE_FEATURE_CLEAN_UP)
  1016. dfree(dnp);
  1017. return exit_code;
  1018. }