ls.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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. const 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. if (age < 3600L * 24 * 365 / 2 && age > -15 * 60) {
  540. /* less than 6 months old */
  541. /* "mmm dd hh:mm " */
  542. printf("%.12s ", filetime + 4);
  543. } else {
  544. /* "mmm dd yyyy " */
  545. /* "mmm dd yyyyy " after year 9999 :) */
  546. strchr(filetime + 20, '\n')[0] = ' ';
  547. printf("%.7s%6s", filetime + 4, filetime + 20);
  548. }
  549. column += 13;
  550. }
  551. }
  552. #endif
  553. #if ENABLE_SELINUX
  554. if (G.all_fmt & LIST_CONTEXT) {
  555. column += printf("%-32s ", dn->sid ? dn->sid : "unknown");
  556. freecon(dn->sid);
  557. }
  558. #endif
  559. #if ENABLE_FEATURE_LS_COLOR
  560. if (G_show_color) {
  561. mode_t mode = dn->dn_mode_lstat;
  562. if (!mode)
  563. if (lstat(dn->fullname, &statbuf) == 0)
  564. mode = statbuf.st_mode;
  565. printf("\033[%u;%um", bold(mode), fgcolor(mode));
  566. }
  567. #endif
  568. column += print_name(dn->name);
  569. if (G_show_color) {
  570. printf("\033[0m");
  571. }
  572. if (lpath) {
  573. printf(" -> ");
  574. #if ENABLE_FEATURE_LS_FILETYPES || ENABLE_FEATURE_LS_COLOR
  575. if ((G.all_fmt & LIST_FILETYPE) || G_show_color) {
  576. mode_t mode = dn->dn_mode_stat;
  577. if (!mode)
  578. if (stat(dn->fullname, &statbuf) == 0)
  579. mode = statbuf.st_mode;
  580. # if ENABLE_FEATURE_LS_FILETYPES
  581. append = append_char(mode);
  582. # endif
  583. # if ENABLE_FEATURE_LS_COLOR
  584. if (G_show_color) {
  585. printf("\033[%u;%um", bold(mode), fgcolor(mode));
  586. }
  587. # endif
  588. }
  589. #endif
  590. column += print_name(lpath) + 4;
  591. free(lpath);
  592. if (G_show_color) {
  593. printf("\033[0m");
  594. }
  595. }
  596. #if ENABLE_FEATURE_LS_FILETYPES
  597. if (G.all_fmt & LIST_FILETYPE) {
  598. if (append) {
  599. putchar(append);
  600. column++;
  601. }
  602. }
  603. #endif
  604. return column;
  605. }
  606. static void display_files(struct dnode **dn, unsigned nfiles)
  607. {
  608. unsigned i, ncols, nrows, row, nc;
  609. unsigned column;
  610. unsigned nexttab;
  611. unsigned column_width = 0; /* used only by STYLE_COLUMNAR */
  612. if (G.all_fmt & STYLE_LONG) { /* STYLE_LONG or STYLE_SINGLE */
  613. ncols = 1;
  614. } else {
  615. /* find the longest file name, use that as the column width */
  616. for (i = 0; dn[i]; i++) {
  617. int len = calc_name_len(dn[i]->name);
  618. if (column_width < len)
  619. column_width = len;
  620. }
  621. column_width += 2 +
  622. IF_SELINUX( ((G.all_fmt & LIST_CONTEXT) ? 33 : 0) + )
  623. ((G.all_fmt & LIST_INO) ? 8 : 0) +
  624. ((G.all_fmt & LIST_BLOCKS) ? 5 : 0);
  625. ncols = (unsigned)G_terminal_width / column_width;
  626. }
  627. if (ncols > 1) {
  628. nrows = nfiles / ncols;
  629. if (nrows * ncols < nfiles)
  630. nrows++; /* round up fractionals */
  631. } else {
  632. nrows = nfiles;
  633. ncols = 1;
  634. }
  635. column = 0;
  636. nexttab = 0;
  637. for (row = 0; row < nrows; row++) {
  638. for (nc = 0; nc < ncols; nc++) {
  639. /* reach into the array based on the column and row */
  640. if (G.all_fmt & DISP_ROWS)
  641. i = (row * ncols) + nc; /* display across row */
  642. else
  643. i = (nc * nrows) + row; /* display by column */
  644. if (i < nfiles) {
  645. if (column > 0) {
  646. nexttab -= column;
  647. printf("%*s", nexttab, "");
  648. column += nexttab;
  649. }
  650. nexttab = column + column_width;
  651. column += display_single(dn[i]);
  652. }
  653. }
  654. putchar('\n');
  655. column = 0;
  656. }
  657. }
  658. /*** Dir scanning code ***/
  659. static struct dnode *my_stat(const char *fullname, const char *name, int force_follow)
  660. {
  661. struct stat statbuf;
  662. struct dnode *cur;
  663. cur = xzalloc(sizeof(*cur));
  664. cur->fullname = fullname;
  665. cur->name = name;
  666. if ((option_mask32 & OPT_L) || force_follow) {
  667. #if ENABLE_SELINUX
  668. if (is_selinux_enabled()) {
  669. getfilecon(fullname, &cur->sid);
  670. }
  671. #endif
  672. if (stat(fullname, &statbuf)) {
  673. bb_simple_perror_msg(fullname);
  674. G.exit_code = EXIT_FAILURE;
  675. free(cur);
  676. return NULL;
  677. }
  678. cur->dn_mode_stat = statbuf.st_mode;
  679. } else {
  680. #if ENABLE_SELINUX
  681. if (is_selinux_enabled()) {
  682. lgetfilecon(fullname, &cur->sid);
  683. }
  684. #endif
  685. if (lstat(fullname, &statbuf)) {
  686. bb_simple_perror_msg(fullname);
  687. G.exit_code = EXIT_FAILURE;
  688. free(cur);
  689. return NULL;
  690. }
  691. cur->dn_mode_lstat = statbuf.st_mode;
  692. }
  693. /* cur->dstat = statbuf: */
  694. cur->dn_mode = statbuf.st_mode ;
  695. cur->dn_size = statbuf.st_size ;
  696. #if ENABLE_FEATURE_LS_TIMESTAMPS || ENABLE_FEATURE_LS_SORTFILES
  697. cur->dn_atime = statbuf.st_atime ;
  698. cur->dn_mtime = statbuf.st_mtime ;
  699. cur->dn_ctime = statbuf.st_ctime ;
  700. #endif
  701. cur->dn_ino = statbuf.st_ino ;
  702. cur->dn_blocks = statbuf.st_blocks;
  703. cur->dn_nlink = statbuf.st_nlink ;
  704. cur->dn_uid = statbuf.st_uid ;
  705. cur->dn_gid = statbuf.st_gid ;
  706. cur->dn_rdev_maj = major(statbuf.st_rdev);
  707. cur->dn_rdev_min = minor(statbuf.st_rdev);
  708. return cur;
  709. }
  710. static unsigned count_dirs(struct dnode **dn, int which)
  711. {
  712. unsigned dirs, all;
  713. if (!dn)
  714. return 0;
  715. dirs = all = 0;
  716. for (; *dn; dn++) {
  717. const char *name;
  718. all++;
  719. if (!S_ISDIR((*dn)->dn_mode))
  720. continue;
  721. name = (*dn)->name;
  722. if (which != SPLIT_SUBDIR /* if not requested to skip . / .. */
  723. /* or if it's not . or .. */
  724. || name[0] != '.'
  725. || (name[1] && (name[1] != '.' || name[2]))
  726. ) {
  727. dirs++;
  728. }
  729. }
  730. return which != SPLIT_FILE ? dirs : all - dirs;
  731. }
  732. /* get memory to hold an array of pointers */
  733. static struct dnode **dnalloc(unsigned num)
  734. {
  735. if (num < 1)
  736. return NULL;
  737. num++; /* so that we have terminating NULL */
  738. return xzalloc(num * sizeof(struct dnode *));
  739. }
  740. #if ENABLE_FEATURE_LS_RECURSIVE
  741. static void dfree(struct dnode **dnp)
  742. {
  743. unsigned i;
  744. if (dnp == NULL)
  745. return;
  746. for (i = 0; dnp[i]; i++) {
  747. struct dnode *cur = dnp[i];
  748. if (cur->fname_allocated)
  749. free((char*)cur->fullname);
  750. free(cur);
  751. }
  752. free(dnp);
  753. }
  754. #else
  755. #define dfree(...) ((void)0)
  756. #endif
  757. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  758. static struct dnode **splitdnarray(struct dnode **dn, int which)
  759. {
  760. unsigned dncnt, d;
  761. struct dnode **dnp;
  762. if (dn == NULL)
  763. return NULL;
  764. /* count how many dirs or files there are */
  765. dncnt = count_dirs(dn, which);
  766. /* allocate a file array and a dir array */
  767. dnp = dnalloc(dncnt);
  768. /* copy the entrys into the file or dir array */
  769. for (d = 0; *dn; dn++) {
  770. if (S_ISDIR((*dn)->dn_mode)) {
  771. const char *name;
  772. if (which == SPLIT_FILE)
  773. continue;
  774. name = (*dn)->name;
  775. if ((which & SPLIT_DIR) /* any dir... */
  776. /* ... or not . or .. */
  777. || name[0] != '.'
  778. || (name[1] && (name[1] != '.' || name[2]))
  779. ) {
  780. dnp[d++] = *dn;
  781. }
  782. } else
  783. if (which == SPLIT_FILE) {
  784. dnp[d++] = *dn;
  785. }
  786. }
  787. return dnp;
  788. }
  789. #if ENABLE_FEATURE_LS_SORTFILES
  790. static int sortcmp(const void *a, const void *b)
  791. {
  792. struct dnode *d1 = *(struct dnode **)a;
  793. struct dnode *d2 = *(struct dnode **)b;
  794. unsigned sort_opts = G.all_fmt & SORT_MASK;
  795. off_t dif;
  796. dif = 0; /* assume SORT_NAME */
  797. // TODO: use pre-initialized function pointer
  798. // instead of branch forest
  799. if (sort_opts == SORT_SIZE) {
  800. dif = (d2->dn_size - d1->dn_size);
  801. } else
  802. if (sort_opts == SORT_ATIME) {
  803. dif = (d2->dn_atime - d1->dn_atime);
  804. } else
  805. if (sort_opts == SORT_CTIME) {
  806. dif = (d2->dn_ctime - d1->dn_ctime);
  807. } else
  808. if (sort_opts == SORT_MTIME) {
  809. dif = (d2->dn_mtime - d1->dn_mtime);
  810. } else
  811. if (sort_opts == SORT_DIR) {
  812. dif = S_ISDIR(d2->dn_mode) - S_ISDIR(d1->dn_mode);
  813. } else
  814. #if defined(HAVE_STRVERSCMP) && HAVE_STRVERSCMP == 1
  815. if (sort_opts == SORT_VERSION) {
  816. dif = strverscmp(d1->name, d2->name);
  817. } else
  818. #endif
  819. if (sort_opts == SORT_EXT) {
  820. dif = strcmp(strchrnul(d1->name, '.'), strchrnul(d2->name, '.'));
  821. }
  822. if (dif == 0) {
  823. /* sort by name, use as tie breaker for other sorts */
  824. if (ENABLE_LOCALE_SUPPORT)
  825. dif = strcoll(d1->name, d2->name);
  826. else
  827. dif = strcmp(d1->name, d2->name);
  828. }
  829. /* Make dif fit into an int */
  830. if (sizeof(dif) > sizeof(int)) {
  831. enum { BITS_TO_SHIFT = 8 * (sizeof(dif) - sizeof(int)) };
  832. /* shift leaving only "int" worth of bits */
  833. if (dif != 0) {
  834. dif = 1 | (int)((uoff_t)dif >> BITS_TO_SHIFT);
  835. }
  836. }
  837. return (G.all_fmt & SORT_REVERSE) ? -(int)dif : (int)dif;
  838. }
  839. static void dnsort(struct dnode **dn, int size)
  840. {
  841. qsort(dn, size, sizeof(*dn), sortcmp);
  842. }
  843. static void sort_and_display_files(struct dnode **dn, unsigned nfiles)
  844. {
  845. dnsort(dn, nfiles);
  846. display_files(dn, nfiles);
  847. }
  848. #else
  849. # define dnsort(dn, size) ((void)0)
  850. # define sort_and_display_files(dn, nfiles) display_files(dn, nfiles)
  851. #endif
  852. /* Returns NULL-terminated malloced vector of pointers (or NULL) */
  853. static struct dnode **scan_one_dir(const char *path, unsigned *nfiles_p)
  854. {
  855. struct dnode *dn, *cur, **dnp;
  856. struct dirent *entry;
  857. DIR *dir;
  858. unsigned i, nfiles;
  859. *nfiles_p = 0;
  860. dir = warn_opendir(path);
  861. if (dir == NULL) {
  862. G.exit_code = EXIT_FAILURE;
  863. return NULL; /* could not open the dir */
  864. }
  865. dn = NULL;
  866. nfiles = 0;
  867. while ((entry = readdir(dir)) != NULL) {
  868. char *fullname;
  869. /* are we going to list the file- it may be . or .. or a hidden file */
  870. if (entry->d_name[0] == '.') {
  871. if ((!entry->d_name[1] || (entry->d_name[1] == '.' && !entry->d_name[2]))
  872. && !(G.all_fmt & DISP_DOT)
  873. ) {
  874. continue;
  875. }
  876. if (!(G.all_fmt & DISP_HIDDEN))
  877. continue;
  878. }
  879. fullname = concat_path_file(path, entry->d_name);
  880. cur = my_stat(fullname, bb_basename(fullname), 0);
  881. if (!cur) {
  882. free(fullname);
  883. continue;
  884. }
  885. cur->fname_allocated = 1;
  886. cur->dn_next = dn;
  887. dn = cur;
  888. nfiles++;
  889. }
  890. closedir(dir);
  891. if (dn == NULL)
  892. return NULL;
  893. /* now that we know how many files there are
  894. * allocate memory for an array to hold dnode pointers
  895. */
  896. *nfiles_p = nfiles;
  897. dnp = dnalloc(nfiles);
  898. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  899. dnp[i] = dn; /* save pointer to node in array */
  900. dn = dn->dn_next;
  901. if (!dn)
  902. break;
  903. }
  904. return dnp;
  905. }
  906. #if ENABLE_DESKTOP
  907. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/ls.html
  908. * If any of the -l, -n, -s options is specified, each list
  909. * of files within the directory shall be preceded by a
  910. * status line indicating the number of file system blocks
  911. * occupied by files in the directory in 512-byte units if
  912. * the -k option is not specified, or 1024-byte units if the
  913. * -k option is specified, rounded up to the next integral
  914. * number of units.
  915. */
  916. /* by Jorgen Overgaard (jorgen AT antistaten.se) */
  917. static off_t calculate_blocks(struct dnode **dn)
  918. {
  919. uoff_t blocks = 1;
  920. if (dn) {
  921. while (*dn) {
  922. /* st_blocks is in 512 byte blocks */
  923. blocks += (*dn)->dn_blocks;
  924. dn++;
  925. }
  926. }
  927. /* Even though standard says use 512 byte blocks, coreutils use 1k */
  928. /* Actually, we round up by calculating (blocks + 1) / 2,
  929. * "+ 1" was done when we initialized blocks to 1 */
  930. return blocks >> 1;
  931. }
  932. #endif
  933. static void scan_and_display_dirs_recur(struct dnode **dn, int first)
  934. {
  935. unsigned nfiles;
  936. struct dnode **subdnp;
  937. for (; *dn; dn++) {
  938. if (G.all_fmt & (DISP_DIRNAME | DISP_RECURSIVE)) {
  939. if (!first)
  940. bb_putchar('\n');
  941. first = 0;
  942. printf("%s:\n", (*dn)->fullname);
  943. }
  944. subdnp = scan_one_dir((*dn)->fullname, &nfiles);
  945. #if ENABLE_DESKTOP
  946. if ((G.all_fmt & STYLE_MASK) == STYLE_LONG || (G.all_fmt & LIST_BLOCKS))
  947. printf("total %"OFF_FMT"u\n", calculate_blocks(subdnp));
  948. #endif
  949. if (nfiles > 0) {
  950. /* list all files at this level */
  951. sort_and_display_files(subdnp, nfiles);
  952. if (ENABLE_FEATURE_LS_RECURSIVE
  953. && (G.all_fmt & DISP_RECURSIVE)
  954. ) {
  955. struct dnode **dnd;
  956. unsigned dndirs;
  957. /* recursive - list the sub-dirs */
  958. dnd = splitdnarray(subdnp, SPLIT_SUBDIR);
  959. dndirs = count_dirs(subdnp, SPLIT_SUBDIR);
  960. if (dndirs > 0) {
  961. dnsort(dnd, dndirs);
  962. scan_and_display_dirs_recur(dnd, 0);
  963. /* free the array of dnode pointers to the dirs */
  964. free(dnd);
  965. }
  966. }
  967. /* free the dnodes and the fullname mem */
  968. dfree(subdnp);
  969. }
  970. }
  971. }
  972. int ls_main(int argc UNUSED_PARAM, char **argv)
  973. {
  974. struct dnode **dnd;
  975. struct dnode **dnf;
  976. struct dnode **dnp;
  977. struct dnode *dn;
  978. struct dnode *cur;
  979. unsigned opt;
  980. unsigned nfiles;
  981. unsigned dnfiles;
  982. unsigned dndirs;
  983. unsigned i;
  984. #if ENABLE_FEATURE_LS_COLOR
  985. /* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
  986. /* coreutils 6.10:
  987. * # ls --color=BOGUS
  988. * ls: invalid argument 'BOGUS' for '--color'
  989. * Valid arguments are:
  990. * 'always', 'yes', 'force'
  991. * 'never', 'no', 'none'
  992. * 'auto', 'tty', 'if-tty'
  993. * (and substrings: "--color=alwa" work too)
  994. */
  995. static const char ls_longopts[] ALIGN1 =
  996. "color\0" Optional_argument "\xff"; /* no short equivalent */
  997. static const char color_str[] ALIGN1 =
  998. "always\0""yes\0""force\0"
  999. "auto\0""tty\0""if-tty\0";
  1000. /* need to initialize since --color has _an optional_ argument */
  1001. const char *color_opt = color_str; /* "always" */
  1002. #endif
  1003. INIT_G();
  1004. init_unicode();
  1005. if (ENABLE_FEATURE_LS_SORTFILES)
  1006. G.all_fmt = SORT_NAME;
  1007. #if ENABLE_FEATURE_AUTOWIDTH
  1008. /* obtain the terminal width */
  1009. G_terminal_width = get_terminal_width(STDIN_FILENO);
  1010. /* go one less... */
  1011. G_terminal_width--;
  1012. #endif
  1013. /* process options */
  1014. IF_FEATURE_LS_COLOR(applet_long_options = ls_longopts;)
  1015. opt_complementary =
  1016. /* -e implies -l */
  1017. IF_FEATURE_LS_TIMESTAMPS("el")
  1018. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html:
  1019. * in some pairs of opts, only last one takes effect:
  1020. */
  1021. IF_FEATURE_LS_TIMESTAMPS(IF_FEATURE_LS_SORTFILES(":t-S:S-t")) /* time/size */
  1022. // ":m-l:l-m" - we don't have -m
  1023. IF_FEATURE_LS_FOLLOWLINKS(":H-L:L-H")
  1024. ":C-xl:x-Cl:l-xC" /* bycols/bylines/long */
  1025. ":C-1:1-C" /* bycols/oneline */
  1026. ":x-1:1-x" /* bylines/oneline (not in SuS, but in GNU coreutils 8.4) */
  1027. IF_FEATURE_LS_TIMESTAMPS(":c-u:u-c") /* mtime/atime */
  1028. /* -w NUM: */
  1029. IF_FEATURE_AUTOWIDTH(":w+");
  1030. opt = getopt32(argv, ls_options
  1031. IF_FEATURE_AUTOWIDTH(, NULL, &G_terminal_width)
  1032. IF_FEATURE_LS_COLOR(, &color_opt)
  1033. );
  1034. for (i = 0; opt_flags[i] != (1U << 31); i++) {
  1035. if (opt & (1 << i)) {
  1036. uint32_t flags = opt_flags[i];
  1037. if (flags & STYLE_MASK)
  1038. G.all_fmt &= ~STYLE_MASK;
  1039. if (flags & SORT_MASK)
  1040. G.all_fmt &= ~SORT_MASK;
  1041. if (flags & TIME_MASK)
  1042. G.all_fmt &= ~TIME_MASK;
  1043. G.all_fmt |= flags;
  1044. }
  1045. }
  1046. #if ENABLE_FEATURE_LS_COLOR
  1047. /* set G_show_color = 1/0 */
  1048. if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
  1049. char *p = getenv("LS_COLORS");
  1050. /* LS_COLORS is unset, or (not empty && not "none") ? */
  1051. if (!p || (p[0] && strcmp(p, "none") != 0))
  1052. G_show_color = 1;
  1053. }
  1054. if (opt & OPT_color) {
  1055. if (color_opt[0] == 'n')
  1056. G_show_color = 0;
  1057. else switch (index_in_substrings(color_str, color_opt)) {
  1058. case 3:
  1059. case 4:
  1060. case 5:
  1061. if (isatty(STDOUT_FILENO)) {
  1062. case 0:
  1063. case 1:
  1064. case 2:
  1065. G_show_color = 1;
  1066. }
  1067. }
  1068. }
  1069. #endif
  1070. /* sort out which command line options take precedence */
  1071. if (ENABLE_FEATURE_LS_RECURSIVE && (G.all_fmt & DISP_NOLIST))
  1072. G.all_fmt &= ~DISP_RECURSIVE; /* no recurse if listing only dir */
  1073. if (ENABLE_FEATURE_LS_TIMESTAMPS && ENABLE_FEATURE_LS_SORTFILES) {
  1074. if (G.all_fmt & TIME_CHANGE)
  1075. G.all_fmt = (G.all_fmt & ~SORT_MASK) | SORT_CTIME;
  1076. if (G.all_fmt & TIME_ACCESS)
  1077. G.all_fmt = (G.all_fmt & ~SORT_MASK) | SORT_ATIME;
  1078. }
  1079. if ((G.all_fmt & STYLE_MASK) != STYLE_LONG) /* not -l? */
  1080. G.all_fmt &= ~(LIST_ID_NUMERIC|LIST_ID_NAME|LIST_FULLTIME);
  1081. /* choose a display format if one was not already specified by an option */
  1082. if (!(G.all_fmt & STYLE_MASK))
  1083. G.all_fmt |= (isatty(STDOUT_FILENO) ? STYLE_COLUMNAR : STYLE_SINGLE);
  1084. argv += optind;
  1085. if (!argv[0])
  1086. *--argv = (char*)".";
  1087. if (argv[1])
  1088. G.all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
  1089. /* stuff the command line file names into a dnode array */
  1090. dn = NULL;
  1091. nfiles = 0;
  1092. do {
  1093. cur = my_stat(*argv, *argv,
  1094. /* follow links on command line unless -l, -s or -F: */
  1095. !((G.all_fmt & STYLE_MASK) == STYLE_LONG
  1096. || (G.all_fmt & LIST_BLOCKS)
  1097. || (option_mask32 & OPT_F)
  1098. )
  1099. /* ... or if -H: */
  1100. || (option_mask32 & OPT_H)
  1101. /* ... or if -L, but my_stat always follows links if -L */
  1102. );
  1103. argv++;
  1104. if (!cur)
  1105. continue;
  1106. /*cur->fname_allocated = 0; - already is */
  1107. cur->dn_next = dn;
  1108. dn = cur;
  1109. nfiles++;
  1110. } while (*argv);
  1111. /* nfiles _may_ be 0 here - try "ls doesnt_exist" */
  1112. if (nfiles == 0)
  1113. return G.exit_code;
  1114. /* now that we know how many files there are
  1115. * allocate memory for an array to hold dnode pointers
  1116. */
  1117. dnp = dnalloc(nfiles);
  1118. for (i = 0; /* i < nfiles - detected via !dn below */; i++) {
  1119. dnp[i] = dn; /* save pointer to node in array */
  1120. dn = dn->dn_next;
  1121. if (!dn)
  1122. break;
  1123. }
  1124. if (G.all_fmt & DISP_NOLIST) {
  1125. sort_and_display_files(dnp, nfiles);
  1126. } else {
  1127. dnd = splitdnarray(dnp, SPLIT_DIR);
  1128. dnf = splitdnarray(dnp, SPLIT_FILE);
  1129. dndirs = count_dirs(dnp, SPLIT_DIR);
  1130. dnfiles = nfiles - dndirs;
  1131. if (dnfiles > 0) {
  1132. sort_and_display_files(dnf, dnfiles);
  1133. if (ENABLE_FEATURE_CLEAN_UP)
  1134. free(dnf);
  1135. }
  1136. if (dndirs > 0) {
  1137. dnsort(dnd, dndirs);
  1138. scan_and_display_dirs_recur(dnd, dnfiles == 0);
  1139. if (ENABLE_FEATURE_CLEAN_UP)
  1140. free(dnd);
  1141. }
  1142. }
  1143. if (ENABLE_FEATURE_CLEAN_UP)
  1144. dfree(dnp);
  1145. return G.exit_code;
  1146. }