find.c 43 KB

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