ls.c 35 KB

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