find.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini find implementation for busybox
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Reworked by David Douthitt <n9ubh@callsign.net> and
  8. * Matt Kraai <kraai@alumni.carnegiemellon.edu>.
  9. *
  10. * Licensed under GPLv2, see file LICENSE in this source tree.
  11. */
  12. /* findutils-4.1.20:
  13. *
  14. * # find file.txt -exec 'echo {}' '{} {}' ';'
  15. * find: echo file.txt: No such file or directory
  16. * # find file.txt -exec 'echo' '{} {}' '; '
  17. * find: missing argument to '-exec'
  18. * # find file.txt -exec 'echo {}' '{} {}' ';' junk
  19. * find: paths must precede expression
  20. * # find file.txt -exec 'echo {}' '{} {}' ';' junk ';'
  21. * find: paths must precede expression
  22. * # find file.txt -exec 'echo' '{} {}' ';'
  23. * file.txt file.txt
  24. * (strace: execve("/bin/echo", ["echo", "file.txt file.txt"], [ 30 vars ]))
  25. * # find file.txt -exec 'echo' '{} {}' ';' -print -exec pwd ';'
  26. * file.txt file.txt
  27. * file.txt
  28. * /tmp
  29. * # find -name '*.c' -o -name '*.h'
  30. * [shows files, *.c and *.h intermixed]
  31. * # find file.txt -name '*f*' -o -name '*t*'
  32. * file.txt
  33. * # find file.txt -name '*z*' -o -name '*t*'
  34. * file.txt
  35. * # find file.txt -name '*f*' -o -name '*z*'
  36. * file.txt
  37. *
  38. * # find t z -name '*t*' -print -o -name '*z*'
  39. * t
  40. * # find t z t z -name '*t*' -o -name '*z*' -print
  41. * z
  42. * z
  43. * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
  44. * (no output)
  45. */
  46. /* Testing script
  47. * ./busybox find "$@" | tee /tmp/bb_find
  48. * echo ==================
  49. * /path/to/gnu/find "$@" | tee /tmp/std_find
  50. * echo ==================
  51. * diff -u /tmp/std_find /tmp/bb_find && echo Identical
  52. */
  53. //config:config FIND
  54. //config: bool "find (14 kb)"
  55. //config: default y
  56. //config: help
  57. //config: find is used to search your system to find specified files.
  58. //config:
  59. //config:config FEATURE_FIND_PRINT0
  60. //config: bool "Enable -print0: NUL-terminated output"
  61. //config: default y
  62. //config: depends on FIND
  63. //config: help
  64. //config: Causes output names to be separated by a NUL character
  65. //config: rather than a newline. This allows names that contain
  66. //config: newlines and other whitespace to be more easily
  67. //config: interpreted by other programs.
  68. //config:
  69. //config:config FEATURE_FIND_MTIME
  70. //config: bool "Enable -mtime: modified time matching"
  71. //config: default y
  72. //config: depends on FIND
  73. //config: help
  74. //config: Allow searching based on the modification time of
  75. //config: files, in days.
  76. //config:
  77. //config:config FEATURE_FIND_MMIN
  78. //config: bool "Enable -mmin: modified time matching by minutes"
  79. //config: default y
  80. //config: depends on FIND
  81. //config: help
  82. //config: Allow searching based on the modification time of
  83. //config: files, in minutes.
  84. //config:
  85. //config:config FEATURE_FIND_PERM
  86. //config: bool "Enable -perm: permissions matching"
  87. //config: default y
  88. //config: depends on FIND
  89. //config:
  90. //config:config FEATURE_FIND_TYPE
  91. //config: bool "Enable -type: file type matching (file/dir/link/...)"
  92. //config: default y
  93. //config: depends on FIND
  94. //config: help
  95. //config: Enable searching based on file type (file,
  96. //config: directory, socket, device, etc.).
  97. //config:
  98. //config:config FEATURE_FIND_EXECUTABLE
  99. //config: bool "Enable -executable: file is executable"
  100. //config: default y
  101. //config: depends on FIND
  102. //config:
  103. //config:config FEATURE_FIND_XDEV
  104. //config: bool "Enable -xdev: 'stay in filesystem'"
  105. //config: default y
  106. //config: depends on FIND
  107. //config:
  108. //config:config FEATURE_FIND_MAXDEPTH
  109. //config: bool "Enable -mindepth N and -maxdepth N"
  110. //config: default y
  111. //config: depends on FIND
  112. //config:
  113. //config:config FEATURE_FIND_NEWER
  114. //config: bool "Enable -newer: compare file modification times"
  115. //config: default y
  116. //config: depends on FIND
  117. //config: help
  118. //config: Support the 'find -newer' option for finding any files which have
  119. //config: modification time that is more recent than the specified FILE.
  120. //config:
  121. //config:config FEATURE_FIND_INUM
  122. //config: bool "Enable -inum: inode number matching"
  123. //config: default y
  124. //config: depends on FIND
  125. //config:
  126. //config:config FEATURE_FIND_EXEC
  127. //config: bool "Enable -exec: execute commands"
  128. //config: default y
  129. //config: depends on FIND
  130. //config: help
  131. //config: Support the 'find -exec' option for executing commands based upon
  132. //config: the files matched.
  133. //config:
  134. //config:config FEATURE_FIND_EXEC_PLUS
  135. //config: bool "Enable -exec ... {} +"
  136. //config: default y
  137. //config: depends on FEATURE_FIND_EXEC
  138. //config: help
  139. //config: Support the 'find -exec ... {} +' option for executing commands
  140. //config: for all matched files at once.
  141. //config: Without this option, -exec + is a synonym for -exec ;
  142. //config: (IOW: it works correctly, but without expected speedup)
  143. //config:
  144. //config:config FEATURE_FIND_USER
  145. //config: bool "Enable -user: username/uid matching"
  146. //config: default y
  147. //config: depends on FIND
  148. //config:
  149. //config:config FEATURE_FIND_GROUP
  150. //config: bool "Enable -group: group/gid matching"
  151. //config: default y
  152. //config: depends on FIND
  153. //config:
  154. //config:config FEATURE_FIND_NOT
  155. //config: bool "Enable the 'not' (!) operator"
  156. //config: default y
  157. //config: depends on FIND
  158. //config: help
  159. //config: Support the '!' operator to invert the test results.
  160. //config: If 'Enable full-blown desktop' is enabled, then will also support
  161. //config: the non-POSIX notation '-not'.
  162. //config:
  163. //config:config FEATURE_FIND_DEPTH
  164. //config: bool "Enable -depth"
  165. //config: default y
  166. //config: depends on FIND
  167. //config: help
  168. //config: Process each directory's contents before the directory itself.
  169. //config:
  170. //config:config FEATURE_FIND_PAREN
  171. //config: bool "Enable parens in options"
  172. //config: default y
  173. //config: depends on FIND
  174. //config: help
  175. //config: Enable usage of parens '(' to specify logical order of arguments.
  176. //config:
  177. //config:config FEATURE_FIND_SIZE
  178. //config: bool "Enable -size: file size matching"
  179. //config: default y
  180. //config: depends on FIND
  181. //config:
  182. //config:config FEATURE_FIND_PRUNE
  183. //config: bool "Enable -prune: exclude subdirectories"
  184. //config: default y
  185. //config: depends on FIND
  186. //config: help
  187. //config: If the file is a directory, don't descend into it. Useful for
  188. //config: exclusion .svn and CVS directories.
  189. //config:
  190. //config:config FEATURE_FIND_QUIT
  191. //config: bool "Enable -quit: exit"
  192. //config: default y
  193. //config: depends on FIND
  194. //config: help
  195. //config: If this action is reached, 'find' exits.
  196. //config:
  197. //config:config FEATURE_FIND_DELETE
  198. //config: bool "Enable -delete: delete files/dirs"
  199. //config: default y
  200. //config: depends on FIND && FEATURE_FIND_DEPTH
  201. //config: help
  202. //config: Support the 'find -delete' option for deleting files and directories.
  203. //config: WARNING: This option can do much harm if used wrong. Busybox will not
  204. //config: try to protect the user from doing stupid things. Use with care.
  205. //config:
  206. //config:config FEATURE_FIND_EMPTY
  207. //config: bool "Enable -empty: match empty files or directories"
  208. //config: default y
  209. //config: depends on FIND
  210. //config: help
  211. //config: Support the 'find -empty' option to find empty regular files
  212. //config: or directories.
  213. //config:
  214. //config:config FEATURE_FIND_PATH
  215. //config: bool "Enable -path: match pathname with shell pattern"
  216. //config: default y
  217. //config: depends on FIND
  218. //config: help
  219. //config: The -path option matches whole pathname instead of just filename.
  220. //config:
  221. //config:config FEATURE_FIND_REGEX
  222. //config: bool "Enable -regex: match pathname with regex"
  223. //config: default y
  224. //config: depends on FIND
  225. //config: help
  226. //config: The -regex option matches whole pathname against regular expression.
  227. //config:
  228. //config:config FEATURE_FIND_CONTEXT
  229. //config: bool "Enable -context: security context matching"
  230. //config: default n
  231. //config: depends on FIND && SELINUX
  232. //config: help
  233. //config: Support the 'find -context' option for matching security context.
  234. //config:
  235. //config:config FEATURE_FIND_LINKS
  236. //config: bool "Enable -links: link count matching"
  237. //config: default y
  238. //config: depends on FIND
  239. //config: help
  240. //config: Support the 'find -links' option for matching number of links.
  241. //applet:IF_FIND(APPLET_NOEXEC(find, find, BB_DIR_USR_BIN, BB_SUID_DROP, find))
  242. //kbuild:lib-$(CONFIG_FIND) += find.o
  243. //usage:#define find_trivial_usage
  244. //usage: "[-HL] [PATH]... [OPTIONS] [ACTIONS]"
  245. //usage:#define find_full_usage "\n\n"
  246. //usage: "Search for files and perform actions on them.\n"
  247. //usage: "First failed action stops processing of current file.\n"
  248. //usage: "Defaults: PATH is current directory, action is '-print'\n"
  249. //usage: "\n -L,-follow Follow symlinks"
  250. //usage: "\n -H ...on command line only"
  251. //usage: IF_FEATURE_FIND_XDEV(
  252. //usage: "\n -xdev Don't descend directories on other filesystems"
  253. //usage: )
  254. //usage: IF_FEATURE_FIND_MAXDEPTH(
  255. //usage: "\n -maxdepth N Descend at most N levels. -maxdepth 0 applies"
  256. //usage: "\n actions to command line arguments only"
  257. //usage: "\n -mindepth N Don't act on first N levels"
  258. //usage: )
  259. //usage: IF_FEATURE_FIND_DEPTH(
  260. //usage: "\n -depth Act on directory *after* traversing it"
  261. //usage: )
  262. //usage: "\n"
  263. //usage: "\nActions:"
  264. //usage: IF_FEATURE_FIND_PAREN(
  265. //usage: "\n ( ACTIONS ) Group actions for -o / -a"
  266. //usage: )
  267. //usage: IF_FEATURE_FIND_NOT(
  268. //usage: "\n ! ACT Invert ACT's success/failure"
  269. //usage: )
  270. //usage: "\n ACT1 [-a] ACT2 If ACT1 fails, stop, else do ACT2"
  271. //usage: "\n ACT1 -o ACT2 If ACT1 succeeds, stop, else do ACT2"
  272. //usage: "\n Note: -a has higher priority than -o"
  273. //usage: "\n -name PATTERN Match file name (w/o directory name) to PATTERN"
  274. //usage: "\n -iname PATTERN Case insensitive -name"
  275. //usage: IF_FEATURE_FIND_PATH(
  276. //usage: "\n -path PATTERN Match path to PATTERN"
  277. //usage: "\n -ipath PATTERN Case insensitive -path"
  278. //usage: )
  279. //usage: IF_FEATURE_FIND_REGEX(
  280. //usage: "\n -regex PATTERN Match path to regex PATTERN"
  281. //usage: )
  282. //usage: IF_FEATURE_FIND_TYPE(
  283. //usage: "\n -type X File type is X (one of: f,d,l,b,c,s,p)"
  284. //usage: )
  285. //usage: IF_FEATURE_FIND_EXECUTABLE(
  286. //usage: "\n -executable File is executable"
  287. //usage: )
  288. //usage: IF_FEATURE_FIND_PERM(
  289. //usage: "\n -perm MASK At least one mask bit (+MASK), all bits (-MASK),"
  290. //usage: "\n or exactly MASK bits are set in file's mode"
  291. //usage: )
  292. //usage: IF_FEATURE_FIND_MTIME(
  293. //usage: "\n -mtime DAYS mtime is greater than (+N), less than (-N),"
  294. //usage: "\n or exactly N days in the past"
  295. //usage: )
  296. //usage: IF_FEATURE_FIND_MMIN(
  297. //usage: "\n -mmin MINS mtime is greater than (+N), less than (-N),"
  298. //usage: "\n or exactly N minutes in the past"
  299. //usage: )
  300. //usage: IF_FEATURE_FIND_NEWER(
  301. //usage: "\n -newer FILE mtime is more recent than FILE's"
  302. //usage: )
  303. //usage: IF_FEATURE_FIND_INUM(
  304. //usage: "\n -inum N File has inode number N"
  305. //usage: )
  306. //usage: IF_FEATURE_FIND_USER(
  307. //usage: "\n -user NAME/ID File is owned by given user"
  308. //usage: )
  309. //usage: IF_FEATURE_FIND_GROUP(
  310. //usage: "\n -group NAME/ID File is owned by given group"
  311. //usage: )
  312. //usage: IF_FEATURE_FIND_SIZE(
  313. //usage: "\n -size N[bck] File size is N (c:bytes,k:kbytes,b:512 bytes(def.))"
  314. //usage: "\n +/-N: file size is bigger/smaller than N"
  315. //usage: )
  316. //usage: IF_FEATURE_FIND_LINKS(
  317. //usage: "\n -links N Number of links is greater than (+N), less than (-N),"
  318. //usage: "\n or exactly N"
  319. //usage: )
  320. //usage: IF_FEATURE_FIND_CONTEXT(
  321. //usage: "\n -context CTX File has specified security context"
  322. //usage: )
  323. //usage: IF_FEATURE_FIND_EMPTY(
  324. //usage: "\n -empty Match empty file/directory"
  325. //usage: )
  326. //usage: IF_FEATURE_FIND_PRUNE(
  327. //usage: "\n -prune If current file is directory, don't descend into it"
  328. //usage: )
  329. //usage: "\nIf none of the following actions is specified, -print is assumed"
  330. //usage: "\n -print Print file name"
  331. //usage: IF_FEATURE_FIND_PRINT0(
  332. //usage: "\n -print0 Print file name, NUL terminated"
  333. //usage: )
  334. //usage: IF_FEATURE_FIND_EXEC(
  335. //usage: "\n -exec CMD ARG ; Run CMD with all instances of {} replaced by"
  336. //usage: "\n file name. Fails if CMD exits with nonzero"
  337. //usage: )
  338. //usage: IF_FEATURE_FIND_EXEC_PLUS(
  339. //usage: "\n -exec CMD ARG + Run CMD with {} replaced by list of file names"
  340. //usage: )
  341. //usage: IF_FEATURE_FIND_DELETE(
  342. //usage: "\n -delete Delete current file/directory. Turns on -depth option"
  343. //usage: )
  344. //usage: IF_FEATURE_FIND_QUIT(
  345. //usage: "\n -quit Exit"
  346. //usage: )
  347. //usage:
  348. //usage:#define find_example_usage
  349. //usage: "$ find / -name passwd\n"
  350. //usage: "/etc/passwd\n"
  351. #include <fnmatch.h>
  352. #include "libbb.h"
  353. #include "common_bufsiz.h"
  354. #if ENABLE_FEATURE_FIND_REGEX
  355. # include "xregex.h"
  356. #endif
  357. /* GNUism: */
  358. #ifndef FNM_CASEFOLD
  359. # define FNM_CASEFOLD 0
  360. #endif
  361. #if 1
  362. # define dbg(...) ((void)0)
  363. #else
  364. # define dbg(...) bb_error_msg(__VA_ARGS__)
  365. #endif
  366. /* This is a NOEXEC applet. Be very careful! */
  367. typedef int (*action_fp)(const char *fileName, const struct stat *statbuf, void *) FAST_FUNC;
  368. typedef struct {
  369. action_fp f;
  370. #if ENABLE_FEATURE_FIND_NOT
  371. bool invert;
  372. #endif
  373. } action;
  374. #define ACTS(name, ...) typedef struct { action a; __VA_ARGS__ } action_##name;
  375. #define ACTF(name) \
  376. static int FAST_FUNC func_##name(const char *fileName UNUSED_PARAM, \
  377. const struct stat *statbuf UNUSED_PARAM, \
  378. action_##name* ap UNUSED_PARAM)
  379. ACTS(print)
  380. ACTS(name, const char *pattern; bool iname;)
  381. IF_FEATURE_FIND_PATH( ACTS(path, const char *pattern; bool ipath;))
  382. IF_FEATURE_FIND_REGEX( ACTS(regex, regex_t compiled_pattern;))
  383. IF_FEATURE_FIND_PRINT0( ACTS(print0))
  384. IF_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
  385. IF_FEATURE_FIND_EXECUTABLE(ACTS(executable))
  386. IF_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
  387. IF_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
  388. IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
  389. IF_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
  390. IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
  391. IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
  392. IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
  393. IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
  394. IF_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
  395. IF_FEATURE_FIND_PRUNE( ACTS(prune))
  396. IF_FEATURE_FIND_QUIT( ACTS(quit))
  397. IF_FEATURE_FIND_DELETE( ACTS(delete))
  398. IF_FEATURE_FIND_EMPTY( ACTS(empty))
  399. IF_FEATURE_FIND_EXEC( ACTS(exec,
  400. char **exec_argv; /* -exec ARGS */
  401. unsigned *subst_count;
  402. int exec_argc; /* count of ARGS */
  403. IF_FEATURE_FIND_EXEC_PLUS(
  404. /*
  405. * filelist is NULL if "exec ;"
  406. * non-NULL if "exec +"
  407. */
  408. char **filelist;
  409. int filelist_idx;
  410. int file_len;
  411. )
  412. ))
  413. IF_FEATURE_FIND_GROUP( ACTS(group, gid_t gid;))
  414. IF_FEATURE_FIND_LINKS( ACTS(links, char links_char; int links_count;))
  415. struct globals {
  416. IF_FEATURE_FIND_XDEV(dev_t *xdev_dev;)
  417. IF_FEATURE_FIND_XDEV(int xdev_count;)
  418. #if ENABLE_FEATURE_FIND_MAXDEPTH
  419. int minmaxdepth[2];
  420. #endif
  421. action ***actions;
  422. smallint need_print;
  423. smallint xdev_on;
  424. smalluint exitstatus;
  425. recurse_flags_t recurse_flags;
  426. IF_FEATURE_FIND_EXEC_PLUS(unsigned max_argv_len;)
  427. } FIX_ALIASING;
  428. #define G (*(struct globals*)bb_common_bufsiz1)
  429. #define INIT_G() do { \
  430. setup_common_bufsiz(); \
  431. BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
  432. /* we have to zero it out because of NOEXEC */ \
  433. memset(&G, 0, sizeof(G)); \
  434. IF_FEATURE_FIND_MAXDEPTH(G.minmaxdepth[1] = INT_MAX;) \
  435. IF_FEATURE_FIND_EXEC_PLUS(G.max_argv_len = bb_arg_max() - 2048;) \
  436. G.need_print = 1; \
  437. G.recurse_flags = ACTION_RECURSE; \
  438. } while (0)
  439. /* Return values of ACTFs ('action functions') are a bit mask:
  440. * bit 1=1: prune (use SKIP constant for setting it)
  441. * bit 0=1: matched successfully (TRUE)
  442. */
  443. static int exec_actions(action ***appp, const char *fileName, const struct stat *statbuf)
  444. {
  445. int cur_group;
  446. int cur_action;
  447. int rc = 0;
  448. action **app, *ap;
  449. /* "action group" is a set of actions ANDed together.
  450. * groups are ORed together.
  451. * We simply evaluate each group until we find one in which all actions
  452. * succeed. */
  453. /* -prune is special: if it is encountered, then we won't
  454. * descend into current directory. It doesn't matter whether
  455. * action group (in which -prune sits) will succeed or not:
  456. * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
  457. * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
  458. * not starting with 'f' */
  459. /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
  460. * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
  461. * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
  462. * On return, bit is restored. */
  463. cur_group = -1;
  464. while ((app = appp[++cur_group]) != NULL) {
  465. rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
  466. cur_action = -1;
  467. while (1) {
  468. ap = app[++cur_action];
  469. if (!ap) /* all actions in group were successful */
  470. return rc ^ TRUE; /* restore TRUE bit */
  471. rc |= TRUE ^ ap->f(fileName, statbuf, ap);
  472. #if ENABLE_FEATURE_FIND_NOT
  473. if (ap->invert) rc ^= TRUE;
  474. #endif
  475. dbg("grp %d action %d rc:0x%x", cur_group, cur_action, rc);
  476. if (rc & TRUE) /* current group failed, try next */
  477. break;
  478. }
  479. }
  480. dbg("returning:0x%x", rc ^ TRUE);
  481. return rc ^ TRUE; /* restore TRUE bit */
  482. }
  483. #if !FNM_CASEFOLD
  484. static char *strcpy_upcase(char *dst, const char *src)
  485. {
  486. char *d = dst;
  487. while (1) {
  488. unsigned char ch = *src++;
  489. if (ch >= 'a' && ch <= 'z')
  490. ch -= ('a' - 'A');
  491. *d++ = ch;
  492. if (ch == '\0')
  493. break;
  494. }
  495. return dst;
  496. }
  497. #endif
  498. ACTF(name)
  499. {
  500. int r;
  501. const char *tmp = bb_basename(fileName);
  502. /* GNU findutils: find DIR/ -name DIR
  503. * prints "DIR/" (DIR// prints "DIR//" etc).
  504. * Need to strip trailing "/".
  505. * Such names can come only from top-level names, but
  506. * we can't do this before recursive_action() call,
  507. * since then "find FILE/ -name FILE"
  508. * would also work (on non-directories), which is wrong.
  509. */
  510. char *trunc_slash = NULL;
  511. if (*tmp == '\0') {
  512. /* "foo/bar/[//...]" */
  513. while (tmp != fileName && tmp[-1] == '/')
  514. tmp--;
  515. if (tmp == fileName) { /* entire fileName is "//.."? */
  516. /* yes, convert "//..." to "/"
  517. * Testcases:
  518. * find / -maxdepth 1 -name /: prints /
  519. * find // -maxdepth 1 -name /: prints //
  520. * find / -maxdepth 1 -name //: prints nothing
  521. * find // -maxdepth 1 -name //: prints nothing
  522. */
  523. if (tmp[1])
  524. trunc_slash = (char*)tmp + 1;
  525. } else {
  526. /* no, it's "foo/bar/[//...]", go back to 'b' */
  527. trunc_slash = (char*)tmp;
  528. while (tmp != fileName && tmp[-1] != '/')
  529. tmp--;
  530. }
  531. }
  532. /* Was using FNM_PERIOD flag too,
  533. * but somewhere between 4.1.20 and 4.4.0 GNU find stopped using it.
  534. * find -name '*foo' should match .foo too:
  535. */
  536. if (trunc_slash) *trunc_slash = '\0';
  537. #if FNM_CASEFOLD
  538. r = fnmatch(ap->pattern, tmp, (ap->iname ? FNM_CASEFOLD : 0));
  539. #else
  540. if (ap->iname)
  541. tmp = strcpy_upcase(alloca(strlen(tmp) + 1), tmp);
  542. r = fnmatch(ap->pattern, tmp, 0);
  543. #endif
  544. if (trunc_slash) *trunc_slash = '/';
  545. return r == 0;
  546. }
  547. #if ENABLE_FEATURE_FIND_PATH
  548. ACTF(path)
  549. {
  550. # if FNM_CASEFOLD
  551. return fnmatch(ap->pattern, fileName, (ap->ipath ? FNM_CASEFOLD : 0)) == 0;
  552. # else
  553. if (ap->ipath)
  554. fileName = strcpy_upcase(alloca(strlen(fileName) + 1), fileName);
  555. return fnmatch(ap->pattern, fileName, 0) == 0;
  556. # endif
  557. }
  558. #endif
  559. #if ENABLE_FEATURE_FIND_REGEX
  560. ACTF(regex)
  561. {
  562. regmatch_t match;
  563. if (regexec(&ap->compiled_pattern, fileName, 1, &match, 0 /*eflags*/))
  564. return 0; /* no match */
  565. if (match.rm_so)
  566. return 0; /* match doesn't start at pos 0 */
  567. if (fileName[match.rm_eo])
  568. return 0; /* match doesn't end exactly at end of pathname */
  569. return 1;
  570. }
  571. #endif
  572. #if ENABLE_FEATURE_FIND_TYPE
  573. ACTF(type)
  574. {
  575. return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
  576. }
  577. #endif
  578. #if ENABLE_FEATURE_FIND_EXECUTABLE
  579. ACTF(executable)
  580. {
  581. return access(fileName, X_OK) == 0;
  582. }
  583. #endif
  584. #if ENABLE_FEATURE_FIND_PERM
  585. ACTF(perm)
  586. {
  587. /* -perm [+/]mode: at least one of perm_mask bits are set */
  588. if (ap->perm_char == '+' || ap->perm_char == '/')
  589. return (statbuf->st_mode & ap->perm_mask) != 0;
  590. /* -perm -mode: all of perm_mask are set */
  591. if (ap->perm_char == '-')
  592. return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
  593. /* -perm mode: file mode must match perm_mask */
  594. return (statbuf->st_mode & 07777) == ap->perm_mask;
  595. }
  596. #endif
  597. #if ENABLE_FEATURE_FIND_MTIME
  598. ACTF(mtime)
  599. {
  600. time_t file_age = time(NULL) - statbuf->st_mtime;
  601. time_t mtime_secs = ap->mtime_days * 24*60*60;
  602. if (ap->mtime_char == '+')
  603. return file_age >= mtime_secs + 24*60*60;
  604. if (ap->mtime_char == '-')
  605. return file_age < mtime_secs;
  606. /* just numeric mtime */
  607. return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
  608. }
  609. #endif
  610. #if ENABLE_FEATURE_FIND_MMIN
  611. ACTF(mmin)
  612. {
  613. time_t file_age = time(NULL) - statbuf->st_mtime;
  614. time_t mmin_secs = ap->mmin_mins * 60;
  615. if (ap->mmin_char == '+')
  616. return file_age >= mmin_secs + 60;
  617. if (ap->mmin_char == '-')
  618. return file_age < mmin_secs;
  619. /* just numeric mmin */
  620. return file_age >= mmin_secs && file_age < (mmin_secs + 60);
  621. }
  622. #endif
  623. #if ENABLE_FEATURE_FIND_NEWER
  624. ACTF(newer)
  625. {
  626. return (ap->newer_mtime < statbuf->st_mtime);
  627. }
  628. #endif
  629. #if ENABLE_FEATURE_FIND_INUM
  630. ACTF(inum)
  631. {
  632. return (statbuf->st_ino == ap->inode_num);
  633. }
  634. #endif
  635. #if ENABLE_FEATURE_FIND_EXEC
  636. static int do_exec(action_exec *ap, const char *fileName)
  637. {
  638. int i, rc;
  639. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  640. int size = ap->exec_argc + ap->filelist_idx + 1;
  641. # else
  642. int size = ap->exec_argc + 1;
  643. # endif
  644. # if ENABLE_USE_PORTABLE_CODE
  645. char **argv = alloca(sizeof(char*) * size);
  646. # else /* gcc 4.3.1 generates smaller code: */
  647. char *argv[size];
  648. # endif
  649. char **pp = argv;
  650. for (i = 0; i < ap->exec_argc; i++) {
  651. const char *arg = ap->exec_argv[i];
  652. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  653. if (ap->filelist) {
  654. /* Handling "-exec +"
  655. * Only one exec_argv[i] has substitution in it.
  656. * Expand that one exec_argv[i] into file list.
  657. */
  658. if (ap->subst_count[i] == 0) {
  659. *pp++ = xstrdup(arg);
  660. } else {
  661. int j = 0;
  662. while (ap->filelist[j]) {
  663. /* 2nd arg here should be ap->subst_count[i], but it is always 1: */
  664. *pp++ = xmalloc_substitute_string(arg, 1, "{}", ap->filelist[j]);
  665. free(ap->filelist[j]);
  666. j++;
  667. }
  668. }
  669. } else
  670. # endif
  671. {
  672. /* Handling "-exec ;" */
  673. *pp++ = xmalloc_substitute_string(arg, ap->subst_count[i], "{}", fileName);
  674. }
  675. }
  676. *pp = NULL; /* terminate the list */
  677. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  678. if (ap->filelist) {
  679. ap->filelist[0] = NULL;
  680. ap->filelist_idx = 0;
  681. ap->file_len = 0;
  682. }
  683. # endif
  684. rc = spawn_and_wait(argv);
  685. if (rc < 0)
  686. bb_simple_perror_msg(argv[0]);
  687. i = 0;
  688. while (argv[i])
  689. free(argv[i++]);
  690. return rc == 0; /* return 1 if exitcode 0 */
  691. }
  692. ACTF(exec)
  693. {
  694. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  695. if (ap->filelist) {
  696. int rc;
  697. ap->filelist = xrealloc_vector(ap->filelist, 8, ap->filelist_idx);
  698. ap->filelist[ap->filelist_idx++] = xstrdup(fileName);
  699. ap->file_len += strlen(fileName) + sizeof(char*) + 1;
  700. /* If we have lots of files already, exec the command */
  701. rc = 1;
  702. if (ap->file_len >= G.max_argv_len)
  703. rc = do_exec(ap, NULL);
  704. return rc;
  705. }
  706. # endif
  707. return do_exec(ap, fileName);
  708. }
  709. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  710. static int flush_exec_plus(void)
  711. {
  712. action *ap;
  713. action **app;
  714. action ***appp = G.actions;
  715. while ((app = *appp++) != NULL) {
  716. while ((ap = *app++) != NULL) {
  717. if (ap->f == (action_fp)func_exec) {
  718. action_exec *ae = (void*)ap;
  719. if (ae->filelist_idx != 0) {
  720. int rc = do_exec(ae, NULL);
  721. # if ENABLE_FEATURE_FIND_NOT
  722. if (ap->invert) rc = !rc;
  723. # endif
  724. if (rc == 0)
  725. return 1;
  726. }
  727. }
  728. }
  729. }
  730. return 0;
  731. }
  732. # endif
  733. #endif
  734. #if ENABLE_FEATURE_FIND_USER
  735. ACTF(user)
  736. {
  737. return (statbuf->st_uid == ap->uid);
  738. }
  739. #endif
  740. #if ENABLE_FEATURE_FIND_GROUP
  741. ACTF(group)
  742. {
  743. return (statbuf->st_gid == ap->gid);
  744. }
  745. #endif
  746. #if ENABLE_FEATURE_FIND_PRINT0
  747. ACTF(print0)
  748. {
  749. printf("%s%c", fileName, '\0');
  750. return TRUE;
  751. }
  752. #endif
  753. ACTF(print)
  754. {
  755. puts(fileName);
  756. return TRUE;
  757. }
  758. #if ENABLE_FEATURE_FIND_PAREN
  759. ACTF(paren)
  760. {
  761. return exec_actions(ap->subexpr, fileName, statbuf);
  762. }
  763. #endif
  764. #if ENABLE_FEATURE_FIND_SIZE
  765. ACTF(size)
  766. {
  767. if (ap->size_char == '+')
  768. return statbuf->st_size > ap->size;
  769. if (ap->size_char == '-')
  770. return statbuf->st_size < ap->size;
  771. return statbuf->st_size == ap->size;
  772. }
  773. #endif
  774. #if ENABLE_FEATURE_FIND_PRUNE
  775. /*
  776. * -prune: if -depth is not given, return true and do not descend
  777. * current dir; if -depth is given, return false with no effect.
  778. * Example:
  779. * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
  780. */
  781. ACTF(prune)
  782. {
  783. return SKIP + TRUE;
  784. }
  785. #endif
  786. #if ENABLE_FEATURE_FIND_QUIT
  787. ACTF(quit)
  788. {
  789. exit(G.exitstatus);
  790. }
  791. #endif
  792. #if ENABLE_FEATURE_FIND_DELETE
  793. ACTF(delete)
  794. {
  795. int rc;
  796. if (S_ISDIR(statbuf->st_mode)) {
  797. /* "find . -delete" skips rmdir(".") */
  798. rc = 0;
  799. if (NOT_LONE_CHAR(fileName, '.'))
  800. rc = rmdir(fileName);
  801. } else {
  802. rc = unlink(fileName);
  803. }
  804. if (rc < 0)
  805. bb_simple_perror_msg(fileName);
  806. return TRUE;
  807. }
  808. #endif
  809. #if ENABLE_FEATURE_FIND_EMPTY
  810. ACTF(empty)
  811. {
  812. if (S_ISDIR(statbuf->st_mode)) {
  813. DIR *dir;
  814. struct dirent *dent;
  815. dir = opendir(fileName);
  816. if (!dir) {
  817. bb_simple_perror_msg(fileName);
  818. return FALSE;
  819. }
  820. while ((dent = readdir(dir)) != NULL
  821. && DOT_OR_DOTDOT(dent->d_name)
  822. ) {
  823. continue;
  824. }
  825. closedir(dir);
  826. return dent == NULL;
  827. }
  828. return S_ISREG(statbuf->st_mode) && statbuf->st_size == 0;
  829. }
  830. #endif
  831. #if ENABLE_FEATURE_FIND_CONTEXT
  832. ACTF(context)
  833. {
  834. security_context_t con;
  835. int rc;
  836. if (G.recurse_flags & ACTION_FOLLOWLINKS) {
  837. rc = getfilecon(fileName, &con);
  838. } else {
  839. rc = lgetfilecon(fileName, &con);
  840. }
  841. if (rc < 0)
  842. return FALSE;
  843. rc = strcmp(ap->context, con);
  844. freecon(con);
  845. return rc == 0;
  846. }
  847. #endif
  848. #if ENABLE_FEATURE_FIND_LINKS
  849. ACTF(links)
  850. {
  851. switch(ap->links_char) {
  852. case '-' : return (statbuf->st_nlink < ap->links_count);
  853. case '+' : return (statbuf->st_nlink > ap->links_count);
  854. default: return (statbuf->st_nlink == ap->links_count);
  855. }
  856. }
  857. #endif
  858. static int FAST_FUNC fileAction(
  859. struct recursive_state *state IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM),
  860. const char *fileName,
  861. struct stat *statbuf)
  862. {
  863. int r;
  864. int same_fs = 1;
  865. #if ENABLE_FEATURE_FIND_XDEV
  866. if (S_ISDIR(statbuf->st_mode) && G.xdev_count) {
  867. int i;
  868. for (i = 0; i < G.xdev_count; i++) {
  869. if (G.xdev_dev[i] == statbuf->st_dev)
  870. goto found;
  871. }
  872. //bb_error_msg("'%s': not same fs", fileName);
  873. same_fs = 0;
  874. found: ;
  875. }
  876. #endif
  877. #if ENABLE_FEATURE_FIND_MAXDEPTH
  878. if (state->depth < G.minmaxdepth[0]) {
  879. if (same_fs)
  880. return TRUE; /* skip this, continue recursing */
  881. return SKIP; /* stop recursing */
  882. }
  883. if (state->depth > G.minmaxdepth[1])
  884. return SKIP; /* stop recursing */
  885. #endif
  886. r = exec_actions(G.actions, fileName, statbuf);
  887. /* Had no explicit -print[0] or -exec? then print */
  888. if ((r & TRUE) && G.need_print)
  889. puts(fileName);
  890. #if ENABLE_FEATURE_FIND_MAXDEPTH
  891. if (S_ISDIR(statbuf->st_mode)) {
  892. if (state->depth == G.minmaxdepth[1])
  893. return SKIP;
  894. }
  895. #endif
  896. /* -xdev stops on mountpoints, but AFTER mountpoit itself
  897. * is processed as usual */
  898. if (!same_fs) {
  899. return SKIP;
  900. }
  901. /* Cannot return 0: our caller, recursive_action(),
  902. * will perror() and skip dirs (if called on dir) */
  903. return (r & SKIP) ? SKIP : TRUE;
  904. }
  905. #if ENABLE_FEATURE_FIND_TYPE
  906. static int find_type(const char *type)
  907. {
  908. int mask = 0;
  909. if (*type == 'b')
  910. mask = S_IFBLK;
  911. else if (*type == 'c')
  912. mask = S_IFCHR;
  913. else if (*type == 'd')
  914. mask = S_IFDIR;
  915. else if (*type == 'p')
  916. mask = S_IFIFO;
  917. else if (*type == 'f')
  918. mask = S_IFREG;
  919. else if (*type == 'l')
  920. mask = S_IFLNK;
  921. else if (*type == 's')
  922. mask = S_IFSOCK;
  923. if (mask == 0 || type[1] != '\0')
  924. bb_error_msg_and_die(bb_msg_invalid_arg_to, type, "-type");
  925. return mask;
  926. }
  927. #endif
  928. #if ENABLE_FEATURE_FIND_PERM \
  929. || ENABLE_FEATURE_FIND_MTIME || ENABLE_FEATURE_FIND_MMIN \
  930. || ENABLE_FEATURE_FIND_SIZE || ENABLE_FEATURE_FIND_LINKS
  931. static const char* plus_minus_num(const char* str)
  932. {
  933. if (*str == '-' || *str == '+')
  934. str++;
  935. return str;
  936. }
  937. #endif
  938. /* Say no to GCCism */
  939. #define USE_NESTED_FUNCTION 0
  940. #if !USE_NESTED_FUNCTION
  941. struct pp_locals {
  942. action*** appp;
  943. unsigned cur_group;
  944. unsigned cur_action;
  945. IF_FEATURE_FIND_NOT( bool invert_flag; )
  946. };
  947. static action* alloc_action(struct pp_locals *ppl, int sizeof_struct, action_fp f)
  948. {
  949. action *ap = xzalloc(sizeof_struct);
  950. action **app;
  951. action ***group = &ppl->appp[ppl->cur_group];
  952. *group = app = xrealloc(*group, (ppl->cur_action+2) * sizeof(ppl->appp[0][0]));
  953. app[ppl->cur_action++] = ap;
  954. app[ppl->cur_action] = NULL;
  955. ap->f = f;
  956. IF_FEATURE_FIND_NOT( ap->invert = ppl->invert_flag; )
  957. IF_FEATURE_FIND_NOT( ppl->invert_flag = 0; )
  958. return ap;
  959. }
  960. #endif
  961. static action*** parse_params(char **argv)
  962. {
  963. enum {
  964. OPT_FOLLOW ,
  965. IF_FEATURE_FIND_XDEV( OPT_XDEV ,)
  966. IF_FEATURE_FIND_DEPTH( OPT_DEPTH ,)
  967. PARM_a ,
  968. PARM_o ,
  969. IF_FEATURE_FIND_NOT( PARM_char_not ,)
  970. #if ENABLE_DESKTOP
  971. PARM_and ,
  972. PARM_or ,
  973. IF_FEATURE_FIND_NOT( PARM_not ,)
  974. #endif
  975. PARM_print ,
  976. IF_FEATURE_FIND_PRINT0( PARM_print0 ,)
  977. IF_FEATURE_FIND_PRUNE( PARM_prune ,)
  978. IF_FEATURE_FIND_QUIT( PARM_quit ,)
  979. IF_FEATURE_FIND_DELETE( PARM_delete ,)
  980. IF_FEATURE_FIND_EMPTY( PARM_empty ,)
  981. IF_FEATURE_FIND_EXEC( PARM_exec ,)
  982. IF_FEATURE_FIND_EXECUTABLE(PARM_executable,)
  983. IF_FEATURE_FIND_PAREN( PARM_char_brace,)
  984. /* All options/actions starting from here require argument */
  985. PARM_name ,
  986. PARM_iname ,
  987. IF_FEATURE_FIND_PATH( PARM_path ,)
  988. #if ENABLE_DESKTOP
  989. /* -wholename is a synonym for -path */
  990. /* We support it because Linux kernel's "make tags" uses it */
  991. IF_FEATURE_FIND_PATH( PARM_wholename ,)
  992. #endif
  993. IF_FEATURE_FIND_PATH( PARM_ipath ,)
  994. IF_FEATURE_FIND_REGEX( PARM_regex ,)
  995. IF_FEATURE_FIND_TYPE( PARM_type ,)
  996. IF_FEATURE_FIND_PERM( PARM_perm ,)
  997. IF_FEATURE_FIND_MTIME( PARM_mtime ,)
  998. IF_FEATURE_FIND_MMIN( PARM_mmin ,)
  999. IF_FEATURE_FIND_NEWER( PARM_newer ,)
  1000. IF_FEATURE_FIND_INUM( PARM_inum ,)
  1001. IF_FEATURE_FIND_USER( PARM_user ,)
  1002. IF_FEATURE_FIND_GROUP( PARM_group ,)
  1003. IF_FEATURE_FIND_SIZE( PARM_size ,)
  1004. IF_FEATURE_FIND_CONTEXT(PARM_context ,)
  1005. IF_FEATURE_FIND_LINKS( PARM_links ,)
  1006. IF_FEATURE_FIND_MAXDEPTH(OPT_MINDEPTH,OPT_MAXDEPTH,)
  1007. };
  1008. static const char params[] ALIGN1 =
  1009. "-follow\0"
  1010. IF_FEATURE_FIND_XDEV( "-xdev\0" )
  1011. IF_FEATURE_FIND_DEPTH( "-depth\0" )
  1012. "-a\0"
  1013. "-o\0"
  1014. IF_FEATURE_FIND_NOT( "!\0" )
  1015. #if ENABLE_DESKTOP
  1016. "-and\0"
  1017. "-or\0"
  1018. IF_FEATURE_FIND_NOT( "-not\0" )
  1019. #endif
  1020. "-print\0"
  1021. IF_FEATURE_FIND_PRINT0( "-print0\0" )
  1022. IF_FEATURE_FIND_PRUNE( "-prune\0" )
  1023. IF_FEATURE_FIND_QUIT( "-quit\0" )
  1024. IF_FEATURE_FIND_DELETE( "-delete\0" )
  1025. IF_FEATURE_FIND_EMPTY( "-empty\0" )
  1026. IF_FEATURE_FIND_EXEC( "-exec\0" )
  1027. IF_FEATURE_FIND_EXECUTABLE("-executable\0")
  1028. IF_FEATURE_FIND_PAREN( "(\0" )
  1029. /* All options/actions starting from here require argument */
  1030. "-name\0"
  1031. "-iname\0"
  1032. IF_FEATURE_FIND_PATH( "-path\0" )
  1033. #if ENABLE_DESKTOP
  1034. IF_FEATURE_FIND_PATH( "-wholename\0")
  1035. #endif
  1036. IF_FEATURE_FIND_PATH( "-ipath\0" )
  1037. IF_FEATURE_FIND_REGEX( "-regex\0" )
  1038. IF_FEATURE_FIND_TYPE( "-type\0" )
  1039. IF_FEATURE_FIND_PERM( "-perm\0" )
  1040. IF_FEATURE_FIND_MTIME( "-mtime\0" )
  1041. IF_FEATURE_FIND_MMIN( "-mmin\0" )
  1042. IF_FEATURE_FIND_NEWER( "-newer\0" )
  1043. IF_FEATURE_FIND_INUM( "-inum\0" )
  1044. IF_FEATURE_FIND_USER( "-user\0" )
  1045. IF_FEATURE_FIND_GROUP( "-group\0" )
  1046. IF_FEATURE_FIND_SIZE( "-size\0" )
  1047. IF_FEATURE_FIND_CONTEXT("-context\0")
  1048. IF_FEATURE_FIND_LINKS( "-links\0" )
  1049. IF_FEATURE_FIND_MAXDEPTH("-mindepth\0""-maxdepth\0")
  1050. ;
  1051. #if !USE_NESTED_FUNCTION
  1052. struct pp_locals ppl;
  1053. #define appp (ppl.appp )
  1054. #define cur_group (ppl.cur_group )
  1055. #define cur_action (ppl.cur_action )
  1056. #define invert_flag (ppl.invert_flag)
  1057. #define ALLOC_ACTION(name) (action_##name*)alloc_action(&ppl, sizeof(action_##name), (action_fp) func_##name)
  1058. #else
  1059. action*** appp;
  1060. unsigned cur_group;
  1061. unsigned cur_action;
  1062. IF_FEATURE_FIND_NOT( bool invert_flag; )
  1063. /* This is the only place in busybox where we use nested function.
  1064. * So far more standard alternatives were bigger. */
  1065. /* Auto decl suppresses "func without a prototype" warning: */
  1066. auto action* alloc_action(int sizeof_struct, action_fp f);
  1067. action* alloc_action(int sizeof_struct, action_fp f)
  1068. {
  1069. action *ap;
  1070. appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(appp[0][0]));
  1071. appp[cur_group][cur_action++] = ap = xzalloc(sizeof_struct);
  1072. appp[cur_group][cur_action] = NULL;
  1073. ap->f = f;
  1074. IF_FEATURE_FIND_NOT( ap->invert = invert_flag; )
  1075. IF_FEATURE_FIND_NOT( invert_flag = 0; )
  1076. return ap;
  1077. }
  1078. #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
  1079. #endif
  1080. cur_group = 0;
  1081. cur_action = 0;
  1082. IF_FEATURE_FIND_NOT( invert_flag = 0; )
  1083. appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
  1084. while (*argv) {
  1085. const char *arg = argv[0];
  1086. int parm = index_in_strings(params, arg);
  1087. const char *arg1 = argv[1];
  1088. dbg("arg:'%s' arg1:'%s' parm:%d PARM_type:%d", arg, arg1, parm, PARM_type);
  1089. if (parm >= PARM_name) {
  1090. /* All options/actions starting from -name require argument */
  1091. if (!arg1)
  1092. bb_error_msg_and_die(bb_msg_requires_arg, arg);
  1093. argv++;
  1094. }
  1095. /* We can use big switch() here, but on i386
  1096. * it doesn't give smaller code. Other arches? */
  1097. /* Options always return true. They always take effect
  1098. * rather than being processed only when their place in the
  1099. * expression is reached.
  1100. */
  1101. /* Options */
  1102. if (parm == OPT_FOLLOW) {
  1103. dbg("follow enabled: %d", __LINE__);
  1104. G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
  1105. }
  1106. #if ENABLE_FEATURE_FIND_XDEV
  1107. else if (parm == OPT_XDEV) {
  1108. dbg("%d", __LINE__);
  1109. G.xdev_on = 1;
  1110. }
  1111. #endif
  1112. #if ENABLE_FEATURE_FIND_MAXDEPTH
  1113. else if (parm == OPT_MINDEPTH || parm == OPT_MINDEPTH + 1) {
  1114. dbg("%d", __LINE__);
  1115. G.minmaxdepth[parm - OPT_MINDEPTH] = xatoi_positive(arg1);
  1116. }
  1117. #endif
  1118. #if ENABLE_FEATURE_FIND_DEPTH
  1119. else if (parm == OPT_DEPTH) {
  1120. dbg("%d", __LINE__);
  1121. G.recurse_flags |= ACTION_DEPTHFIRST;
  1122. }
  1123. #endif
  1124. /* Actions are grouped by operators
  1125. * ( expr ) Force precedence
  1126. * ! expr True if expr is false
  1127. * -not expr Same as ! expr
  1128. * expr1 [-a[nd]] expr2 And; expr2 is not evaluated if expr1 is false
  1129. * expr1 -o[r] expr2 Or; expr2 is not evaluated if expr1 is true
  1130. * expr1 , expr2 List; both expr1 and expr2 are always evaluated
  1131. * We implement: (), -a, -o
  1132. */
  1133. /* Operators */
  1134. else if (parm == PARM_a IF_DESKTOP(|| parm == PARM_and)) {
  1135. dbg("%d", __LINE__);
  1136. /* no further special handling required */
  1137. }
  1138. else if (parm == PARM_o IF_DESKTOP(|| parm == PARM_or)) {
  1139. dbg("%d", __LINE__);
  1140. /* start new OR group */
  1141. cur_group++;
  1142. appp = xrealloc(appp, (cur_group+2) * sizeof(appp[0]));
  1143. /*appp[cur_group] = NULL; - already NULL */
  1144. appp[cur_group+1] = NULL;
  1145. cur_action = 0;
  1146. }
  1147. #if ENABLE_FEATURE_FIND_NOT
  1148. else if (parm == PARM_char_not IF_DESKTOP(|| parm == PARM_not)) {
  1149. /* also handles "find ! ! -name 'foo*'" */
  1150. invert_flag ^= 1;
  1151. dbg("invert_flag:%d", invert_flag);
  1152. }
  1153. #endif
  1154. /* Actions */
  1155. else if (parm == PARM_print) {
  1156. dbg("%d", __LINE__);
  1157. G.need_print = 0;
  1158. (void) ALLOC_ACTION(print);
  1159. }
  1160. #if ENABLE_FEATURE_FIND_PRINT0
  1161. else if (parm == PARM_print0) {
  1162. dbg("%d", __LINE__);
  1163. G.need_print = 0;
  1164. (void) ALLOC_ACTION(print0);
  1165. }
  1166. #endif
  1167. #if ENABLE_FEATURE_FIND_PRUNE
  1168. else if (parm == PARM_prune) {
  1169. dbg("%d", __LINE__);
  1170. (void) ALLOC_ACTION(prune);
  1171. }
  1172. #endif
  1173. #if ENABLE_FEATURE_FIND_QUIT
  1174. else if (parm == PARM_quit) {
  1175. dbg("%d", __LINE__);
  1176. (void) ALLOC_ACTION(quit);
  1177. }
  1178. #endif
  1179. #if ENABLE_FEATURE_FIND_DELETE
  1180. else if (parm == PARM_delete) {
  1181. dbg("%d", __LINE__);
  1182. G.need_print = 0;
  1183. G.recurse_flags |= ACTION_DEPTHFIRST;
  1184. (void) ALLOC_ACTION(delete);
  1185. }
  1186. #endif
  1187. #if ENABLE_FEATURE_FIND_EMPTY
  1188. else if (parm == PARM_empty) {
  1189. dbg("%d", __LINE__);
  1190. (void) ALLOC_ACTION(empty);
  1191. }
  1192. #endif
  1193. #if ENABLE_FEATURE_FIND_EXEC
  1194. else if (parm == PARM_exec) {
  1195. int i;
  1196. action_exec *ap;
  1197. IF_FEATURE_FIND_EXEC_PLUS(int all_subst = 0;)
  1198. dbg("%d", __LINE__);
  1199. G.need_print = 0;
  1200. ap = ALLOC_ACTION(exec);
  1201. ap->exec_argv = ++argv; /* first arg after -exec */
  1202. /*ap->exec_argc = 0; - ALLOC_ACTION did it */
  1203. while (1) {
  1204. if (!*argv) /* did not see ';' or '+' until end */
  1205. bb_error_msg_and_die(bb_msg_requires_arg, "-exec");
  1206. // find -exec echo Foo ">{}<" ";"
  1207. // executes "echo Foo >FILENAME<",
  1208. // find -exec echo Foo ">{}<" "+"
  1209. // executes "echo Foo FILENAME1 FILENAME2 FILENAME3...".
  1210. if ((argv[0][0] == ';' || argv[0][0] == '+')
  1211. && argv[0][1] == '\0'
  1212. ) {
  1213. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  1214. if (argv[0][0] == '+')
  1215. ap->filelist = xzalloc(sizeof(ap->filelist[0]));
  1216. # endif
  1217. break;
  1218. }
  1219. argv++;
  1220. ap->exec_argc++;
  1221. }
  1222. if (ap->exec_argc == 0)
  1223. bb_error_msg_and_die(bb_msg_requires_arg, arg);
  1224. ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
  1225. i = ap->exec_argc;
  1226. while (i--) {
  1227. ap->subst_count[i] = count_strstr(ap->exec_argv[i], "{}");
  1228. IF_FEATURE_FIND_EXEC_PLUS(all_subst += ap->subst_count[i];)
  1229. }
  1230. # if ENABLE_FEATURE_FIND_EXEC_PLUS
  1231. /*
  1232. * coreutils expects {} to appear only once in "-exec +"
  1233. */
  1234. if (all_subst != 1 && ap->filelist)
  1235. bb_simple_error_msg_and_die("only one '{}' allowed for -exec +");
  1236. # endif
  1237. }
  1238. #endif
  1239. #if ENABLE_FEATURE_FIND_PAREN
  1240. else if (parm == PARM_char_brace) {
  1241. action_paren *ap;
  1242. char **endarg;
  1243. unsigned nested = 1;
  1244. dbg("%d", __LINE__);
  1245. endarg = argv;
  1246. while (1) {
  1247. if (!*++endarg)
  1248. bb_simple_error_msg_and_die("unpaired '('");
  1249. if (LONE_CHAR(*endarg, '('))
  1250. nested++;
  1251. else if (LONE_CHAR(*endarg, ')') && !--nested) {
  1252. *endarg = NULL;
  1253. break;
  1254. }
  1255. }
  1256. ap = ALLOC_ACTION(paren);
  1257. ap->subexpr = parse_params(argv + 1);
  1258. *endarg = (char*) ")"; /* restore NULLed parameter */
  1259. argv = endarg;
  1260. }
  1261. #endif
  1262. else if (parm == PARM_name || parm == PARM_iname) {
  1263. action_name *ap;
  1264. dbg("%d", __LINE__);
  1265. ap = ALLOC_ACTION(name);
  1266. ap->pattern = arg1;
  1267. ap->iname = (parm == PARM_iname);
  1268. }
  1269. #if ENABLE_FEATURE_FIND_PATH
  1270. else if (parm == PARM_path IF_DESKTOP(|| parm == PARM_wholename) || parm == PARM_ipath) {
  1271. action_path *ap;
  1272. dbg("%d", __LINE__);
  1273. ap = ALLOC_ACTION(path);
  1274. ap->pattern = arg1;
  1275. ap->ipath = (parm == PARM_ipath);
  1276. }
  1277. #endif
  1278. #if ENABLE_FEATURE_FIND_REGEX
  1279. else if (parm == PARM_regex) {
  1280. action_regex *ap;
  1281. dbg("%d", __LINE__);
  1282. ap = ALLOC_ACTION(regex);
  1283. xregcomp(&ap->compiled_pattern, arg1, 0 /*cflags*/);
  1284. }
  1285. #endif
  1286. #if ENABLE_FEATURE_FIND_TYPE
  1287. else if (parm == PARM_type) {
  1288. action_type *ap;
  1289. ap = ALLOC_ACTION(type);
  1290. ap->type_mask = find_type(arg1);
  1291. dbg("created:type mask:%x", ap->type_mask);
  1292. }
  1293. #endif
  1294. #if ENABLE_FEATURE_FIND_EXECUTABLE
  1295. else if (parm == PARM_executable) {
  1296. (void) ALLOC_ACTION(executable);
  1297. }
  1298. #endif
  1299. #if ENABLE_FEATURE_FIND_PERM
  1300. /* -perm BITS File's mode bits are exactly BITS (octal or symbolic).
  1301. * Symbolic modes use mode 0 as a point of departure.
  1302. * -perm -BITS All of the BITS are set in file's mode.
  1303. * -perm [+/]BITS At least one of the BITS is set in file's mode.
  1304. */
  1305. else if (parm == PARM_perm) {
  1306. action_perm *ap;
  1307. dbg("%d", __LINE__);
  1308. ap = ALLOC_ACTION(perm);
  1309. ap->perm_char = arg1[0];
  1310. arg1 = (arg1[0] == '/' ? arg1+1 : plus_minus_num(arg1));
  1311. /*ap->perm_mask = 0; - ALLOC_ACTION did it */
  1312. ap->perm_mask = bb_parse_mode(arg1, ap->perm_mask);
  1313. if (ap->perm_mask == (mode_t)-1)
  1314. bb_error_msg_and_die("invalid mode '%s'", arg1);
  1315. }
  1316. #endif
  1317. #if ENABLE_FEATURE_FIND_MTIME
  1318. else if (parm == PARM_mtime) {
  1319. action_mtime *ap;
  1320. dbg("%d", __LINE__);
  1321. ap = ALLOC_ACTION(mtime);
  1322. ap->mtime_char = arg1[0];
  1323. ap->mtime_days = xatoul(plus_minus_num(arg1));
  1324. }
  1325. #endif
  1326. #if ENABLE_FEATURE_FIND_MMIN
  1327. else if (parm == PARM_mmin) {
  1328. action_mmin *ap;
  1329. dbg("%d", __LINE__);
  1330. ap = ALLOC_ACTION(mmin);
  1331. ap->mmin_char = arg1[0];
  1332. ap->mmin_mins = xatoul(plus_minus_num(arg1));
  1333. }
  1334. #endif
  1335. #if ENABLE_FEATURE_FIND_NEWER
  1336. else if (parm == PARM_newer) {
  1337. struct stat stat_newer;
  1338. action_newer *ap;
  1339. dbg("%d", __LINE__);
  1340. ap = ALLOC_ACTION(newer);
  1341. xstat(arg1, &stat_newer);
  1342. ap->newer_mtime = stat_newer.st_mtime;
  1343. }
  1344. #endif
  1345. #if ENABLE_FEATURE_FIND_INUM
  1346. else if (parm == PARM_inum) {
  1347. action_inum *ap;
  1348. dbg("%d", __LINE__);
  1349. ap = ALLOC_ACTION(inum);
  1350. ap->inode_num = xatoul(arg1);
  1351. }
  1352. #endif
  1353. #if ENABLE_FEATURE_FIND_USER
  1354. else if (parm == PARM_user) {
  1355. action_user *ap;
  1356. dbg("%d", __LINE__);
  1357. ap = ALLOC_ACTION(user);
  1358. ap->uid = bb_strtou(arg1, NULL, 10);
  1359. if (errno)
  1360. ap->uid = xuname2uid(arg1);
  1361. }
  1362. #endif
  1363. #if ENABLE_FEATURE_FIND_GROUP
  1364. else if (parm == PARM_group) {
  1365. action_group *ap;
  1366. dbg("%d", __LINE__);
  1367. ap = ALLOC_ACTION(group);
  1368. ap->gid = bb_strtou(arg1, NULL, 10);
  1369. if (errno)
  1370. ap->gid = xgroup2gid(arg1);
  1371. }
  1372. #endif
  1373. #if ENABLE_FEATURE_FIND_SIZE
  1374. else if (parm == PARM_size) {
  1375. /* -size n[bckw]: file uses n units of space
  1376. * b (default): units are 512-byte blocks
  1377. * c: 1 byte
  1378. * k: kilobytes
  1379. * w: 2-byte words
  1380. */
  1381. #if ENABLE_LFS
  1382. #define XATOU_SFX xatoull_sfx
  1383. #else
  1384. #define XATOU_SFX xatoul_sfx
  1385. #endif
  1386. static const struct suffix_mult find_suffixes[] ALIGN_SUFFIX = {
  1387. { "c", 1 },
  1388. { "w", 2 },
  1389. { "", 512 },
  1390. { "b", 512 },
  1391. { "k", 1024 },
  1392. { "", 0 }
  1393. };
  1394. action_size *ap;
  1395. dbg("%d", __LINE__);
  1396. ap = ALLOC_ACTION(size);
  1397. ap->size_char = arg1[0];
  1398. ap->size = XATOU_SFX(plus_minus_num(arg1), find_suffixes);
  1399. }
  1400. #endif
  1401. #if ENABLE_FEATURE_FIND_CONTEXT
  1402. else if (parm == PARM_context) {
  1403. action_context *ap;
  1404. dbg("%d", __LINE__);
  1405. ap = ALLOC_ACTION(context);
  1406. /*ap->context = NULL; - ALLOC_ACTION did it */
  1407. /* SELinux headers erroneously declare non-const parameter */
  1408. if (selinux_raw_to_trans_context((char*)arg1, &ap->context))
  1409. bb_simple_perror_msg(arg1);
  1410. }
  1411. #endif
  1412. #if ENABLE_FEATURE_FIND_LINKS
  1413. else if (parm == PARM_links) {
  1414. action_links *ap;
  1415. dbg("%d", __LINE__);
  1416. ap = ALLOC_ACTION(links);
  1417. ap->links_char = arg1[0];
  1418. ap->links_count = xatoul(plus_minus_num(arg1));
  1419. }
  1420. #endif
  1421. else {
  1422. bb_error_msg("unrecognized: %s", arg);
  1423. bb_show_usage();
  1424. }
  1425. argv++;
  1426. }
  1427. dbg("exiting %s", __func__);
  1428. return appp;
  1429. #undef ALLOC_ACTION
  1430. #undef appp
  1431. #undef cur_action
  1432. #undef invert_flag
  1433. }
  1434. int find_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1435. int find_main(int argc UNUSED_PARAM, char **argv)
  1436. {
  1437. int i, firstopt;
  1438. char **past_HLP, *saved;
  1439. INIT_G();
  1440. /* "find -type f" + getopt("+HLP") => disaster.
  1441. * Need to avoid getopt running into a non-HLP option.
  1442. * Do this by temporarily storing NULL there:
  1443. */
  1444. past_HLP = argv;
  1445. for (;;) {
  1446. saved = *++past_HLP;
  1447. if (!saved)
  1448. break;
  1449. if (saved[0] != '-')
  1450. break;
  1451. if (!saved[1])
  1452. break; /* it is "-" */
  1453. if (saved[1] == '-' && !saved[2]) {
  1454. /* it is "--" */
  1455. /* Try: find -- /dev/null */
  1456. saved = *++past_HLP;
  1457. break;
  1458. }
  1459. if ((saved+1)[strspn(saved+1, "HLP")] != '\0')
  1460. break;
  1461. }
  1462. *past_HLP = NULL;
  1463. /* "+": stop on first non-option */
  1464. i = getopt32(argv, "+""HLP");
  1465. if (i & (1<<0))
  1466. G.recurse_flags |= ACTION_FOLLOWLINKS_L0 | ACTION_DANGLING_OK;
  1467. if (i & (1<<1))
  1468. G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
  1469. /* -P is default and is ignored */
  1470. argv = past_HLP; /* same result as "argv += optind;" */
  1471. *past_HLP = saved;
  1472. for (firstopt = 0; argv[firstopt]; firstopt++) {
  1473. if (argv[firstopt][0] == '-')
  1474. break;
  1475. if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
  1476. break;
  1477. if (ENABLE_FEATURE_FIND_PAREN && LONE_CHAR(argv[firstopt], '('))
  1478. break;
  1479. }
  1480. if (firstopt == 0) {
  1481. *--argv = (char*)".";
  1482. firstopt++;
  1483. }
  1484. G.actions = parse_params(&argv[firstopt]);
  1485. argv[firstopt] = NULL;
  1486. #if ENABLE_FEATURE_FIND_XDEV
  1487. if (G.xdev_on) {
  1488. struct stat stbuf;
  1489. G.xdev_count = firstopt;
  1490. G.xdev_dev = xzalloc(G.xdev_count * sizeof(G.xdev_dev[0]));
  1491. for (i = 0; argv[i]; i++) {
  1492. /* not xstat(): shouldn't bomb out on
  1493. * "find not_exist exist -xdev" */
  1494. if (stat(argv[i], &stbuf) == 0)
  1495. G.xdev_dev[i] = stbuf.st_dev;
  1496. /* else G.xdev_dev[i] stays 0 and
  1497. * won't match any real device dev_t
  1498. */
  1499. }
  1500. }
  1501. #endif
  1502. for (i = 0; argv[i]; i++) {
  1503. if (!recursive_action(argv[i],
  1504. G.recurse_flags,/* flags */
  1505. fileAction, /* file action */
  1506. fileAction, /* dir action */
  1507. NULL) /* user data */
  1508. ) {
  1509. G.exitstatus |= EXIT_FAILURE;
  1510. }
  1511. }
  1512. IF_FEATURE_FIND_EXEC_PLUS(G.exitstatus |= flush_exec_plus();)
  1513. return G.exitstatus;
  1514. }