ls.c 35 KB

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