ls.c 34 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. //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 entries which start 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 entries instead of 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 dir entries"
  123. //usage: "\n -F Append indicator (one of */=@|) to entries"
  124. //usage: )
  125. //usage: "\n -l Long listing 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 and 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}] Control coloring"
  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 can 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(name, stdout);
  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. //TODO: -h should affect -s too:
  463. if (opt & OPT_s) /* show allocated blocks */
  464. column += printf("%6"OFF_FMT"u ", (off_t) (dn->dn_blocks >> 1));
  465. if (opt & OPT_l) {
  466. /* long listing: show mode */
  467. column += printf("%-10s ", (char *) bb_mode_string(dn->dn_mode));
  468. /* long listing: show number of links */
  469. column += printf("%4lu ", (long) dn->dn_nlink);
  470. /* long listing: show user/group */
  471. if (opt & OPT_n) {
  472. if (opt & OPT_g)
  473. column += printf("%-8u ", (int) dn->dn_gid);
  474. else
  475. column += printf("%-8u %-8u ",
  476. (int) dn->dn_uid,
  477. (int) dn->dn_gid);
  478. }
  479. #if ENABLE_FEATURE_LS_USERNAME
  480. else {
  481. if (opt & OPT_g) {
  482. column += printf("%-8.8s ",
  483. get_cached_groupname(dn->dn_gid));
  484. } else {
  485. column += printf("%-8.8s %-8.8s ",
  486. get_cached_username(dn->dn_uid),
  487. get_cached_groupname(dn->dn_gid));
  488. }
  489. }
  490. #endif
  491. #if ENABLE_SELINUX
  492. }
  493. if (opt & OPT_Z) {
  494. column += printf("%-32s ", dn->sid ? dn->sid : "?");
  495. freecon(dn->sid);
  496. }
  497. if (opt & OPT_l) {
  498. #endif
  499. /* long listing: show size */
  500. if (S_ISBLK(dn->dn_mode) || S_ISCHR(dn->dn_mode)) {
  501. column += printf("%4u, %3u ",
  502. dn->dn_rdev_maj,
  503. dn->dn_rdev_min);
  504. } else {
  505. if (opt & OPT_h) {
  506. column += printf("%"HUMAN_READABLE_MAX_WIDTH_STR"s ",
  507. /* print size, show one fractional, use suffixes */
  508. make_human_readable_str(dn->dn_size, 1, 0)
  509. );
  510. } else {
  511. column += printf("%9"OFF_FMT"u ", dn->dn_size);
  512. }
  513. }
  514. #if ENABLE_FEATURE_LS_TIMESTAMPS
  515. /* long listing: show {m,c,a}time */
  516. if (opt & OPT_full_time) { /* --full-time */
  517. /* coreutils 8.4 ls --full-time prints:
  518. * 2009-07-13 17:49:27.000000000 +0200
  519. * we don't show fractional seconds.
  520. */
  521. char buf[sizeof("YYYY-mm-dd HH:MM:SS TIMEZONE")];
  522. strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z",
  523. localtime(&dn->dn_time));
  524. column += printf("%s ", buf);
  525. } else { /* ordinary time format */
  526. /* G.current_time_t is ~== time(NULL) */
  527. char *filetime = ctime(&dn->dn_time);
  528. /* filetime's format: "Wed Jun 30 21:49:08 1993\n" */
  529. time_t age = G.current_time_t - dn->dn_time;
  530. if (age < 3600L * 24 * 365 / 2 && age > -15 * 60) {
  531. /* less than 6 months old */
  532. /* "mmm dd hh:mm " */
  533. printf("%.12s ", filetime + 4);
  534. } else {
  535. /* "mmm dd yyyy " */
  536. /* "mmm dd yyyyy " after year 9999 :) */
  537. strchr(filetime + 20, '\n')[0] = ' ';
  538. printf("%.7s%6s", filetime + 4, filetime + 20);
  539. }
  540. column += 13;
  541. }
  542. #endif
  543. }
  544. #if ENABLE_FEATURE_LS_COLOR
  545. if (G_show_color) {
  546. mode_t mode = dn->dn_mode_lstat;
  547. if (!mode)
  548. if (lstat(dn->fullname, &statbuf) == 0)
  549. mode = statbuf.st_mode;
  550. printf(ESC"[%u;%um", bold(mode), fgcolor(mode));
  551. }
  552. #endif
  553. column += print_name(dn->name);
  554. if (G_show_color) {
  555. printf(ESC"[m");
  556. }
  557. if (lpath) {
  558. printf(" -> ");
  559. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  560. if ((opt & (OPT_F|OPT_p))
  561. || G_show_color
  562. ) {
  563. mode_t mode = dn->dn_mode_stat;
  564. if (!mode)
  565. if (stat(dn->fullname, &statbuf) == 0)
  566. mode = statbuf.st_mode;
  567. # if ENABLE_FEATURE_LS_FILETYPES
  568. append = append_char(mode);
  569. # endif
  570. # if ENABLE_FEATURE_LS_COLOR
  571. if (G_show_color) {
  572. printf(ESC"[%u;%um", bold(mode), fgcolor(mode));
  573. }
  574. # endif
  575. }
  576. #endif
  577. column += print_name(lpath) + 4;
  578. free(lpath);
  579. if (G_show_color) {
  580. printf(ESC"[m");
  581. }
  582. }
  583. #if ENABLE_FEATURE_LS_FILETYPES
  584. if (opt & (OPT_F|OPT_p)) {
  585. if (append) {
  586. putchar(append);
  587. column++;
  588. }
  589. }
  590. #endif
  591. return column;
  592. }
  593. static void display_files(struct dnode **dn, unsigned nfiles)
  594. {
  595. unsigned i, ncols, nrows, row, nc;
  596. unsigned column;
  597. unsigned nexttab;
  598. unsigned column_width = 0; /* used only by coulmnal output */
  599. if (option_mask32 & (OPT_l|OPT_1)) {
  600. ncols = 1;
  601. } else {
  602. /* find the longest file name, use that as the column width */
  603. for (i = 0; dn[i]; i++) {
  604. int len = calc_name_len(dn[i]->name);
  605. if (column_width < len)
  606. column_width = len;
  607. }
  608. column_width += 2
  609. + ((option_mask32 & OPT_Z) ? 33 : 0) /* context width */
  610. + ((option_mask32 & OPT_i) ? 8 : 0) /* inode# width */
  611. + ((option_mask32 & OPT_s) ? 5 : 0) /* "alloc block" width */
  612. ;
  613. ncols = (unsigned)G_terminal_width / column_width;
  614. }
  615. if (ncols > 1) {
  616. nrows = nfiles / ncols;
  617. if (nrows * ncols < nfiles)
  618. nrows++; /* round up fractionals */
  619. } else {
  620. nrows = nfiles;
  621. ncols = 1;
  622. }
  623. column = 0;
  624. nexttab = 0;
  625. for (row = 0; row < nrows; row++) {
  626. for (nc = 0; nc < ncols; nc++) {
  627. /* reach into the array based on the column and row */
  628. if (option_mask32 & OPT_x)
  629. i = (row * ncols) + nc; /* display across row */
  630. else
  631. i = (nc * nrows) + row; /* display by column */
  632. if (i < nfiles) {
  633. if (column > 0) {
  634. nexttab -= column;
  635. printf("%*s", nexttab, "");
  636. column += nexttab;
  637. }
  638. nexttab = column + column_width;
  639. column += display_single(dn[i]);
  640. }
  641. }
  642. putchar('\n');
  643. column = 0;
  644. }
  645. }
  646. /*** Dir scanning code ***/
  647. static struct dnode *my_stat(const char *fullname, const char *name, int force_follow)
  648. {
  649. struct stat statbuf;
  650. struct dnode *cur;
  651. cur = xzalloc(sizeof(*cur));
  652. cur->fullname = fullname;
  653. cur->name = name;
  654. if ((option_mask32 & OPT_L) || force_follow) {
  655. #if ENABLE_SELINUX
  656. if (option_mask32 & OPT_Z) {
  657. getfilecon(fullname, &cur->sid);
  658. }
  659. #endif
  660. if (stat(fullname, &statbuf)) {
  661. bb_simple_perror_msg(fullname);
  662. G.exit_code = EXIT_FAILURE;
  663. free(cur);
  664. return NULL;
  665. }
  666. cur->dn_mode_stat = statbuf.st_mode;
  667. } else {
  668. #if ENABLE_SELINUX
  669. if (option_mask32 & OPT_Z) {
  670. lgetfilecon(fullname, &cur->sid);
  671. }
  672. #endif
  673. if (lstat(fullname, &statbuf)) {
  674. bb_simple_perror_msg(fullname);
  675. G.exit_code = EXIT_FAILURE;
  676. free(cur);
  677. return NULL;
  678. }
  679. cur->dn_mode_lstat = statbuf.st_mode;
  680. }
  681. /* cur->dstat = statbuf: */
  682. cur->dn_mode = statbuf.st_mode ;
  683. cur->dn_size = statbuf.st_size ;
  684. #if ENABLE_FEATURE_LS_TIMESTAMPS || ENABLE_FEATURE_LS_SORTFILES
  685. cur->dn_time = statbuf.st_mtime ;
  686. if (option_mask32 & OPT_u)
  687. cur->dn_time = statbuf.st_atime;
  688. if (option_mask32 & OPT_c)
  689. cur->dn_time = statbuf.st_ctime;
  690. #endif
  691. cur->dn_ino = statbuf.st_ino ;
  692. cur->dn_blocks = statbuf.st_blocks;
  693. cur->dn_nlink = statbuf.st_nlink ;
  694. cur->dn_uid = statbuf.st_uid ;
  695. cur->dn_gid = statbuf.st_gid ;
  696. cur->dn_rdev_maj = major(statbuf.st_rdev);
  697. cur->dn_rdev_min = minor(statbuf.st_rdev);
  698. return cur;
  699. }
  700. static unsigned count_dirs(struct dnode **dn, int which)
  701. {
  702. unsigned dirs, all;
  703. if (!dn)
  704. return 0;
  705. dirs = all = 0;
  706. for (; *dn; dn++) {
  707. const char *name;
  708. all++;
  709. if (!S_ISDIR((*dn)->dn_mode))
  710. continue;
  711. name = (*dn)->name;
  712. if (which != SPLIT_SUBDIR /* if not requested to skip . / .. */
  713. /* or if it's not . or .. */
  714. || name[0] != '.'
  715. || (name[1] && (name[1] != '.' || name[2]))
  716. ) {
  717. dirs++;
  718. }
  719. }
  720. return which != SPLIT_FILE ? dirs : all - dirs;
  721. }
  722. /* get memory to hold an array of pointers */
  723. static struct dnode **dnalloc(unsigned num)
  724. {
  725. if (num < 1)
  726. return NULL;
  727. num++; /* so that we have terminating NULL */
  728. return xzalloc(num * sizeof(struct dnode *));
  729. }
  730. #if ENABLE_FEATURE_LS_RECURSIVE
  731. static void dfree(struct dnode **dnp)
  732. {
  733. unsigned i;
  734. if (dnp == NULL)
  735. return;
  736. for (i = 0; dnp[i]; i++) {
  737. struct dnode *cur = dnp[i];
  738. if (cur->fname_allocated)
  739. free((char*)cur->fullname);
  740. free(cur);
  741. }
  742. free(dnp);
  743. }
  744. #else
  745. #define dfree(...) ((void)0)
  746. #endif
  747. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  748. static struct dnode **splitdnarray(struct dnode **dn, int which)
  749. {
  750. unsigned dncnt, d;
  751. struct dnode **dnp;
  752. if (dn == NULL)
  753. return NULL;
  754. /* count how many dirs or files there are */
  755. dncnt = count_dirs(dn, which);
  756. /* allocate a file array and a dir array */
  757. dnp = dnalloc(dncnt);
  758. /* copy the entrys into the file or dir array */
  759. for (d = 0; *dn; dn++) {
  760. if (S_ISDIR((*dn)->dn_mode)) {
  761. const char *name;
  762. if (which == SPLIT_FILE)
  763. continue;
  764. name = (*dn)->name;
  765. if ((which & SPLIT_DIR) /* any dir... */
  766. /* ... or not . or .. */
  767. || name[0] != '.'
  768. || (name[1] && (name[1] != '.' || name[2]))
  769. ) {
  770. dnp[d++] = *dn;
  771. }
  772. } else
  773. if (which == SPLIT_FILE) {
  774. dnp[d++] = *dn;
  775. }
  776. }
  777. return dnp;
  778. }
  779. #if ENABLE_FEATURE_LS_SORTFILES
  780. static int sortcmp(const void *a, const void *b)
  781. {
  782. struct dnode *d1 = *(struct dnode **)a;
  783. struct dnode *d2 = *(struct dnode **)b;
  784. unsigned opt = option_mask32;
  785. off_t dif;
  786. dif = 0; /* assume sort by name */
  787. // TODO: use pre-initialized function pointer
  788. // instead of branch forest
  789. if (opt & OPT_dirs_first) {
  790. dif = S_ISDIR(d2->dn_mode) - S_ISDIR(d1->dn_mode);
  791. if (dif != 0)
  792. goto maybe_invert_and_ret;
  793. }
  794. if (opt & OPT_S) { /* sort by size */
  795. dif = (d2->dn_size - d1->dn_size);
  796. } else
  797. if (opt & OPT_t) { /* sort by time */
  798. dif = (d2->dn_time - d1->dn_time);
  799. } else
  800. #if defined(HAVE_STRVERSCMP) && HAVE_STRVERSCMP == 1
  801. if (opt & OPT_v) { /* sort by version */
  802. dif = strverscmp(d1->name, d2->name);
  803. } else
  804. #endif
  805. if (opt & OPT_X) { /* sort by extension */
  806. dif = strcmp(strchrnul(d1->name, '.'), strchrnul(d2->name, '.'));
  807. }
  808. if (dif == 0) {
  809. /* sort by name, use as tie breaker for other sorts */
  810. if (ENABLE_LOCALE_SUPPORT)
  811. dif = strcoll(d1->name, d2->name);
  812. else
  813. dif = strcmp(d1->name, d2->name);
  814. } else {
  815. /* Make dif fit into an int */
  816. if (sizeof(dif) > sizeof(int)) {
  817. enum { BITS_TO_SHIFT = 8 * (sizeof(dif) - sizeof(int)) };
  818. /* shift leaving only "int" worth of bits */
  819. /* (this requires dif != 0, and here it is nonzero) */
  820. dif = 1 | (int)((uoff_t)dif >> BITS_TO_SHIFT);
  821. }
  822. }
  823. maybe_invert_and_ret:
  824. return (opt & OPT_r) ? -(int)dif : (int)dif;
  825. }
  826. static void dnsort(struct dnode **dn, int size)
  827. {
  828. qsort(dn, size, sizeof(*dn), sortcmp);
  829. }
  830. static void sort_and_display_files(struct dnode **dn, unsigned nfiles)
  831. {
  832. dnsort(dn, nfiles);
  833. display_files(dn, nfiles);
  834. }
  835. #else
  836. # define dnsort(dn, size) ((void)0)
  837. # define sort_and_display_files(dn, nfiles) display_files(dn, nfiles)
  838. #endif
  839. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  840. static struct dnode **scan_one_dir(const char *path, unsigned *nfiles_p)
  841. {
  842. struct dnode *dn, *cur, **dnp;
  843. struct dirent *entry;
  844. DIR *dir;
  845. unsigned i, nfiles;
  846. *nfiles_p = 0;
  847. dir = warn_opendir(path);
  848. if (dir == NULL) {
  849. G.exit_code = EXIT_FAILURE;
  850. return NULL; /* could not open the dir */
  851. }
  852. dn = NULL;
  853. nfiles = 0;
  854. while ((entry = readdir(dir)) != NULL) {
  855. char *fullname;
  856. /* are we going to list the file- it may be . or .. or a hidden file */
  857. if (entry->d_name[0] == '.') {
  858. if (!(option_mask32 & (OPT_a|OPT_A)))
  859. continue; /* skip all dotfiles if no -a/-A */
  860. if (!(option_mask32 & OPT_a)
  861. && (!entry->d_name[1] || (entry->d_name[1] == '.' && !entry->d_name[2]))
  862. ) {
  863. continue; /* if only -A, skip . and .. but show other dotfiles */
  864. }
  865. }
  866. fullname = concat_path_file(path, entry->d_name);
  867. cur = my_stat(fullname, bb_basename(fullname), 0);
  868. if (!cur) {
  869. free(fullname);
  870. continue;
  871. }
  872. cur->fname_allocated = 1;
  873. cur->dn_next = dn;
  874. dn = cur;
  875. nfiles++;
  876. }
  877. closedir(dir);
  878. if (dn == NULL)
  879. return NULL;
  880. /* now that we know how many files there are
  881. * allocate memory for an array to hold dnode pointers
  882. */
  883. *nfiles_p = nfiles;
  884. dnp = dnalloc(nfiles);
  885. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  886. dnp[i] = dn; /* save pointer to node in array */
  887. dn = dn->dn_next;
  888. if (!dn)
  889. break;
  890. }
  891. return dnp;
  892. }
  893. #if ENABLE_DESKTOP
  894. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/ls.html
  895. * If any of the -l, -n, -s options is specified, each list
  896. * of files within the directory shall be preceded by a
  897. * status line indicating the number of file system blocks
  898. * occupied by files in the directory in 512-byte units if
  899. * the -k option is not specified, or 1024-byte units if the
  900. * -k option is specified, rounded up to the next integral
  901. * number of units.
  902. */
  903. /* by Jorgen Overgaard (jorgen AT antistaten.se) */
  904. static off_t calculate_blocks(struct dnode **dn)
  905. {
  906. uoff_t blocks = 1;
  907. if (dn) {
  908. while (*dn) {
  909. /* st_blocks is in 512 byte blocks */
  910. blocks += (*dn)->dn_blocks;
  911. dn++;
  912. }
  913. }
  914. /* Even though standard says use 512 byte blocks, coreutils use 1k */
  915. /* Actually, we round up by calculating (blocks + 1) / 2,
  916. * "+ 1" was done when we initialized blocks to 1 */
  917. return blocks >> 1;
  918. }
  919. #endif
  920. static void scan_and_display_dirs_recur(struct dnode **dn, int first)
  921. {
  922. unsigned nfiles;
  923. struct dnode **subdnp;
  924. for (; *dn; dn++) {
  925. if (G.show_dirname || (option_mask32 & OPT_R)) {
  926. if (!first)
  927. bb_putchar('\n');
  928. first = 0;
  929. printf("%s:\n", (*dn)->fullname);
  930. }
  931. subdnp = scan_one_dir((*dn)->fullname, &nfiles);
  932. #if ENABLE_DESKTOP
  933. if (option_mask32 & (OPT_s|OPT_l)) {
  934. if (option_mask32 & OPT_h) {
  935. printf("total %-"HUMAN_READABLE_MAX_WIDTH_STR"s\n",
  936. /* print size, no fractions, use suffixes */
  937. make_human_readable_str(calculate_blocks(subdnp) * 1024,
  938. 0, 0)
  939. );
  940. } else {
  941. printf("total %"OFF_FMT"u\n", calculate_blocks(subdnp));
  942. }
  943. }
  944. #endif
  945. if (nfiles > 0) {
  946. /* list all files at this level */
  947. sort_and_display_files(subdnp, nfiles);
  948. if (ENABLE_FEATURE_LS_RECURSIVE
  949. && (option_mask32 & OPT_R)
  950. ) {
  951. struct dnode **dnd;
  952. unsigned dndirs;
  953. /* recursive - list the sub-dirs */
  954. dnd = splitdnarray(subdnp, SPLIT_SUBDIR);
  955. dndirs = count_dirs(subdnp, SPLIT_SUBDIR);
  956. if (dndirs > 0) {
  957. dnsort(dnd, dndirs);
  958. scan_and_display_dirs_recur(dnd, 0);
  959. /* free the array of dnode pointers to the dirs */
  960. free(dnd);
  961. }
  962. }
  963. /* free the dnodes and the fullname mem */
  964. dfree(subdnp);
  965. }
  966. }
  967. }
  968. int ls_main(int argc UNUSED_PARAM, char **argv)
  969. { /* ^^^^^^^^^^^^^^^^^ note: if FTPD, argc can be wrong, see ftpd.c */
  970. struct dnode **dnd;
  971. struct dnode **dnf;
  972. struct dnode **dnp;
  973. struct dnode *dn;
  974. struct dnode *cur;
  975. unsigned opt;
  976. unsigned nfiles;
  977. unsigned dnfiles;
  978. unsigned dndirs;
  979. unsigned i;
  980. #if ENABLE_FEATURE_LS_COLOR
  981. /* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
  982. /* coreutils 6.10:
  983. * # ls --color=BOGUS
  984. * ls: invalid argument 'BOGUS' for '--color'
  985. * Valid arguments are:
  986. * 'always', 'yes', 'force'
  987. * 'never', 'no', 'none'
  988. * 'auto', 'tty', 'if-tty'
  989. * (and substrings: "--color=alwa" work too)
  990. */
  991. static const char color_str[] ALIGN1 =
  992. "always\0""yes\0""force\0"
  993. "auto\0""tty\0""if-tty\0";
  994. /* need to initialize since --color has _an optional_ argument */
  995. const char *color_opt = color_str; /* "always" */
  996. #endif
  997. #if ENABLE_LONG_OPTS
  998. static const char ls_longopts[] ALIGN1 =
  999. "full-time\0" No_argument "\xff"
  1000. "group-directories-first\0" No_argument "\xfe"
  1001. "color\0" Optional_argument "\xfd"
  1002. ;
  1003. #endif
  1004. INIT_G();
  1005. init_unicode();
  1006. #if ENABLE_FEATURE_LS_WIDTH
  1007. /* obtain the terminal width */
  1008. G_terminal_width = get_terminal_width(STDIN_FILENO);
  1009. /* go one less... */
  1010. G_terminal_width--;
  1011. #endif
  1012. /* process options */
  1013. opt = getopt32long(argv, "^"
  1014. ls_options
  1015. "\0"
  1016. /* -n and -g imply -l */
  1017. "nl:gl"
  1018. /* --full-time implies -l */
  1019. IF_FEATURE_LS_TIMESTAMPS(IF_LONG_OPTS(":\xff""l"))
  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_LS_WIDTH(":w+")
  1032. , ls_longopts
  1033. IF_FEATURE_LS_WIDTH(, /*-T*/ NULL, /*-w*/ &G_terminal_width)
  1034. IF_FEATURE_LS_COLOR(, &color_opt)
  1035. );
  1036. #if 0 /* option bits debug */
  1037. bb_error_msg("opt:0x%08x l:%x H:%x color:%x dirs:%x", opt, OPT_l, OPT_H, OPT_color, OPT_dirs_first);
  1038. if (opt & OPT_c ) bb_error_msg("-c");
  1039. if (opt & OPT_l ) bb_error_msg("-l");
  1040. if (opt & OPT_H ) bb_error_msg("-H");
  1041. if (opt & OPT_color ) bb_error_msg("--color");
  1042. if (opt & OPT_dirs_first) bb_error_msg("--group-directories-first");
  1043. if (opt & OPT_full_time ) bb_error_msg("--full-time");
  1044. exit(0);
  1045. #endif
  1046. #if ENABLE_SELINUX
  1047. if (opt & OPT_Z) {
  1048. if (!is_selinux_enabled())
  1049. option_mask32 &= ~OPT_Z;
  1050. }
  1051. #endif
  1052. #if ENABLE_FEATURE_LS_COLOR
  1053. /* set G_show_color = 1/0 */
  1054. if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
  1055. char *p = getenv("LS_COLORS");
  1056. /* LS_COLORS is unset, or (not empty && not "none") ? */
  1057. if (!p || (p[0] && strcmp(p, "none") != 0))
  1058. G_show_color = 1;
  1059. }
  1060. if (opt & OPT_color) {
  1061. if (color_opt[0] == 'n')
  1062. G_show_color = 0;
  1063. else switch (index_in_substrings(color_str, color_opt)) {
  1064. case 3:
  1065. case 4:
  1066. case 5:
  1067. if (isatty(STDOUT_FILENO)) {
  1068. case 0:
  1069. case 1:
  1070. case 2:
  1071. G_show_color = 1;
  1072. }
  1073. }
  1074. }
  1075. #endif
  1076. /* sort out which command line options take precedence */
  1077. if (ENABLE_FEATURE_LS_RECURSIVE && (opt & OPT_d))
  1078. option_mask32 &= ~OPT_R; /* no recurse if listing only dir */
  1079. if (!(opt & OPT_l)) { /* not -l? */
  1080. if (ENABLE_FEATURE_LS_TIMESTAMPS && ENABLE_FEATURE_LS_SORTFILES) {
  1081. /* when to sort by time? -t[cu] sorts by time even with -l */
  1082. /* (this is achieved by opt_flags[] element for -t) */
  1083. /* without -l, bare -c or -u enable sort too */
  1084. /* (with -l, bare -c or -u just select which time to show) */
  1085. if (opt & (OPT_c|OPT_u)) {
  1086. option_mask32 |= OPT_t;
  1087. }
  1088. }
  1089. }
  1090. /* choose a display format if one was not already specified by an option */
  1091. if (!(option_mask32 & (OPT_l|OPT_1|OPT_x|OPT_C)))
  1092. option_mask32 |= (isatty(STDOUT_FILENO) ? OPT_C : OPT_1);
  1093. if (ENABLE_FTPD && applet_name[0] == 'f') {
  1094. /* ftpd secret backdoor. dirs first are much nicer */
  1095. option_mask32 |= OPT_dirs_first;
  1096. }
  1097. argv += optind;
  1098. if (!argv[0])
  1099. *--argv = (char*)".";
  1100. if (argv[1])
  1101. G.show_dirname = 1; /* 2 or more items? label directories */
  1102. /* stuff the command line file names into a dnode array */
  1103. dn = NULL;
  1104. nfiles = 0;
  1105. do {
  1106. cur = my_stat(*argv, *argv,
  1107. /* follow links on command line unless -l, -s or -F: */
  1108. !(option_mask32 & (OPT_l|OPT_s|OPT_F))
  1109. /* ... or if -H: */
  1110. || (option_mask32 & OPT_H)
  1111. /* ... or if -L, but my_stat always follows links if -L */
  1112. );
  1113. argv++;
  1114. if (!cur)
  1115. continue;
  1116. /*cur->fname_allocated = 0; - already is */
  1117. cur->dn_next = dn;
  1118. dn = cur;
  1119. nfiles++;
  1120. } while (*argv);
  1121. /* nfiles _may_ be 0 here - try "ls doesnt_exist" */
  1122. if (nfiles == 0)
  1123. return G.exit_code;
  1124. /* now that we know how many files there are
  1125. * allocate memory for an array to hold dnode pointers
  1126. */
  1127. dnp = dnalloc(nfiles);
  1128. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  1129. dnp[i] = dn; /* save pointer to node in array */
  1130. dn = dn->dn_next;
  1131. if (!dn)
  1132. break;
  1133. }
  1134. if (option_mask32 & OPT_d) {
  1135. sort_and_display_files(dnp, nfiles);
  1136. } else {
  1137. dnd = splitdnarray(dnp, SPLIT_DIR);
  1138. dnf = splitdnarray(dnp, SPLIT_FILE);
  1139. dndirs = count_dirs(dnp, SPLIT_DIR);
  1140. dnfiles = nfiles - dndirs;
  1141. if (dnfiles > 0) {
  1142. sort_and_display_files(dnf, dnfiles);
  1143. if (ENABLE_FEATURE_CLEAN_UP)
  1144. free(dnf);
  1145. }
  1146. if (dndirs > 0) {
  1147. dnsort(dnd, dndirs);
  1148. scan_and_display_dirs_recur(dnd, dnfiles == 0);
  1149. if (ENABLE_FEATURE_CLEAN_UP)
  1150. free(dnd);
  1151. }
  1152. }
  1153. if (ENABLE_FEATURE_CLEAN_UP)
  1154. dfree(dnp);
  1155. return G.exit_code;
  1156. }