ls.c 28 KB

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