ls.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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_string(&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_string(&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. printf("total %"OFF_FMT"u\n", calculate_blocks(subdnp));
  935. }
  936. #endif
  937. if (nfiles > 0) {
  938. /* list all files at this level */
  939. sort_and_display_files(subdnp, nfiles);
  940. if (ENABLE_FEATURE_LS_RECURSIVE
  941. && (option_mask32 & OPT_R)
  942. ) {
  943. struct dnode **dnd;
  944. unsigned dndirs;
  945. /* recursive - list the sub-dirs */
  946. dnd = splitdnarray(subdnp, SPLIT_SUBDIR);
  947. dndirs = count_dirs(subdnp, SPLIT_SUBDIR);
  948. if (dndirs > 0) {
  949. dnsort(dnd, dndirs);
  950. scan_and_display_dirs_recur(dnd, 0);
  951. /* free the array of dnode pointers to the dirs */
  952. free(dnd);
  953. }
  954. }
  955. /* free the dnodes and the fullname mem */
  956. dfree(subdnp);
  957. }
  958. }
  959. }
  960. int ls_main(int argc UNUSED_PARAM, char **argv)
  961. { /* ^^^^^^^^^^^^^^^^^ note: if FTPD, argc can be wrong, see ftpd.c */
  962. struct dnode **dnd;
  963. struct dnode **dnf;
  964. struct dnode **dnp;
  965. struct dnode *dn;
  966. struct dnode *cur;
  967. unsigned opt;
  968. unsigned nfiles;
  969. unsigned dnfiles;
  970. unsigned dndirs;
  971. unsigned i;
  972. #if ENABLE_FEATURE_LS_COLOR
  973. /* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
  974. /* coreutils 6.10:
  975. * # ls --color=BOGUS
  976. * ls: invalid argument 'BOGUS' for '--color'
  977. * Valid arguments are:
  978. * 'always', 'yes', 'force'
  979. * 'never', 'no', 'none'
  980. * 'auto', 'tty', 'if-tty'
  981. * (and substrings: "--color=alwa" work too)
  982. */
  983. static const char color_str[] ALIGN1 =
  984. "always\0""yes\0""force\0"
  985. "auto\0""tty\0""if-tty\0";
  986. /* need to initialize since --color has _an optional_ argument */
  987. const char *color_opt = color_str; /* "always" */
  988. #endif
  989. #if ENABLE_LONG_OPTS
  990. static const char ls_longopts[] ALIGN1 =
  991. "full-time\0" No_argument "\xff"
  992. "group-directories-first\0" No_argument "\xfe"
  993. "color\0" Optional_argument "\xfd"
  994. ;
  995. #endif
  996. INIT_G();
  997. init_unicode();
  998. #if ENABLE_FEATURE_LS_WIDTH
  999. /* obtain the terminal width */
  1000. G_terminal_width = get_terminal_width(STDIN_FILENO);
  1001. /* go one less... */
  1002. G_terminal_width--;
  1003. #endif
  1004. /* process options */
  1005. opt = getopt32long(argv, "^"
  1006. ls_options
  1007. "\0"
  1008. /* -n and -g imply -l */
  1009. "nl:gl"
  1010. /* --full-time implies -l */
  1011. IF_FEATURE_LS_TIMESTAMPS(IF_LONG_OPTS(":\xff""l"))
  1012. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html:
  1013. * in some pairs of opts, only last one takes effect:
  1014. */
  1015. IF_FEATURE_LS_TIMESTAMPS(IF_FEATURE_LS_SORTFILES(":t-S:S-t")) /* time/size */
  1016. // ":m-l:l-m" - we don't have -m
  1017. IF_FEATURE_LS_FOLLOWLINKS(":H-L:L-H")
  1018. ":C-xl:x-Cl:l-xC" /* bycols/bylines/long */
  1019. ":C-1:1-C" /* bycols/oneline */
  1020. ":x-1:1-x" /* bylines/oneline (not in SuS, but in GNU coreutils 8.4) */
  1021. IF_FEATURE_LS_TIMESTAMPS(":c-u:u-c") /* mtime/atime */
  1022. /* -w NUM: */
  1023. IF_FEATURE_LS_WIDTH(":w+")
  1024. , ls_longopts
  1025. IF_FEATURE_LS_WIDTH(, /*-T*/ NULL, /*-w*/ &G_terminal_width)
  1026. IF_FEATURE_LS_COLOR(, &color_opt)
  1027. );
  1028. #if 0 /* option bits debug */
  1029. bb_error_msg("opt:0x%08x l:%x H:%x color:%x dirs:%x", opt, OPT_l, OPT_H, OPT_color, OPT_dirs_first);
  1030. if (opt & OPT_c ) bb_error_msg("-c");
  1031. if (opt & OPT_l ) bb_error_msg("-l");
  1032. if (opt & OPT_H ) bb_error_msg("-H");
  1033. if (opt & OPT_color ) bb_error_msg("--color");
  1034. if (opt & OPT_dirs_first) bb_error_msg("--group-directories-first");
  1035. if (opt & OPT_full_time ) bb_error_msg("--full-time");
  1036. exit(0);
  1037. #endif
  1038. #if ENABLE_SELINUX
  1039. if (opt & OPT_Z) {
  1040. if (!is_selinux_enabled())
  1041. option_mask32 &= ~OPT_Z;
  1042. }
  1043. #endif
  1044. #if ENABLE_FEATURE_LS_COLOR
  1045. /* set G_show_color = 1/0 */
  1046. if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
  1047. char *p = getenv("LS_COLORS");
  1048. /* LS_COLORS is unset, or (not empty && not "none") ? */
  1049. if (!p || (p[0] && strcmp(p, "none") != 0))
  1050. G_show_color = 1;
  1051. }
  1052. if (opt & OPT_color) {
  1053. if (color_opt[0] == 'n')
  1054. G_show_color = 0;
  1055. else switch (index_in_substrings(color_str, color_opt)) {
  1056. case 3:
  1057. case 4:
  1058. case 5:
  1059. if (isatty(STDOUT_FILENO)) {
  1060. case 0:
  1061. case 1:
  1062. case 2:
  1063. G_show_color = 1;
  1064. }
  1065. }
  1066. }
  1067. #endif
  1068. /* sort out which command line options take precedence */
  1069. if (ENABLE_FEATURE_LS_RECURSIVE && (opt & OPT_d))
  1070. option_mask32 &= ~OPT_R; /* no recurse if listing only dir */
  1071. if (!(opt & OPT_l)) { /* not -l? */
  1072. if (ENABLE_FEATURE_LS_TIMESTAMPS && ENABLE_FEATURE_LS_SORTFILES) {
  1073. /* when to sort by time? -t[cu] sorts by time even with -l */
  1074. /* (this is achieved by opt_flags[] element for -t) */
  1075. /* without -l, bare -c or -u enable sort too */
  1076. /* (with -l, bare -c or -u just select which time to show) */
  1077. if (opt & (OPT_c|OPT_u)) {
  1078. option_mask32 |= OPT_t;
  1079. }
  1080. }
  1081. }
  1082. /* choose a display format if one was not already specified by an option */
  1083. if (!(option_mask32 & (OPT_l|OPT_1|OPT_x|OPT_C)))
  1084. option_mask32 |= (isatty(STDOUT_FILENO) ? OPT_C : OPT_1);
  1085. if (ENABLE_FTPD && applet_name[0] == 'f') {
  1086. /* ftpd secret backdoor. dirs first are much nicer */
  1087. option_mask32 |= OPT_dirs_first;
  1088. }
  1089. argv += optind;
  1090. if (!argv[0])
  1091. *--argv = (char*)".";
  1092. if (argv[1])
  1093. G.show_dirname = 1; /* 2 or more items? label directories */
  1094. /* stuff the command line file names into a dnode array */
  1095. dn = NULL;
  1096. nfiles = 0;
  1097. do {
  1098. cur = my_stat(*argv, *argv,
  1099. /* follow links on command line unless -l, -s or -F: */
  1100. !(option_mask32 & (OPT_l|OPT_s|OPT_F))
  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 (option_mask32 & OPT_d) {
  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. }