3
0

ls.c 35 KB

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