test.c 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * test implementation for busybox
  4. *
  5. * Copyright (c) by a whole pile of folks:
  6. *
  7. * test(1); version 7-like -- author Erik Baalbergen
  8. * modified by Eric Gisin to be used as built-in.
  9. * modified by Arnold Robbins to add SVR3 compatibility
  10. * (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket).
  11. * modified by J.T. Conklin for NetBSD.
  12. * modified by Herbert Xu to be used as built-in in ash.
  13. * modified by Erik Andersen <andersen@codepoet.org> to be used
  14. * in busybox.
  15. * modified by Bernhard Reutner-Fischer to be useable (i.e. a bit less bloaty).
  16. *
  17. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  18. *
  19. * Original copyright notice states:
  20. * "This program is in the Public Domain."
  21. */
  22. //config:config TEST
  23. //config: bool "test (4.1 kb)"
  24. //config: default y
  25. //config: help
  26. //config: test is used to check file types and compare values,
  27. //config: returning an appropriate exit code. The bash shell
  28. //config: has test built in, ash can build it in optionally.
  29. //config:
  30. //config:config TEST1
  31. //config: bool "test as ["
  32. //config: default y
  33. //config: help
  34. //config: Provide test command in the "[ EXPR ]" form
  35. //config:
  36. //config:config TEST2
  37. //config: bool "test as [["
  38. //config: default y
  39. //config: help
  40. //config: Provide test command in the "[[ EXPR ]]" form
  41. //config:
  42. //config:config FEATURE_TEST_64
  43. //config: bool "Extend test to 64 bit"
  44. //config: default y
  45. //config: depends on TEST || TEST1 || TEST2 || ASH_TEST || HUSH_TEST
  46. //config: help
  47. //config: Enable 64-bit support in test.
  48. //applet:IF_TEST(APPLET_NOFORK(test, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
  49. //applet:IF_TEST1(APPLET_NOFORK([, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
  50. //applet:IF_TEST2(APPLET_NOFORK([[, test, BB_DIR_USR_BIN, BB_SUID_DROP, test))
  51. //kbuild:lib-$(CONFIG_TEST) += test.o test_ptr_hack.o
  52. //kbuild:lib-$(CONFIG_TEST1) += test.o test_ptr_hack.o
  53. //kbuild:lib-$(CONFIG_TEST2) += test.o test_ptr_hack.o
  54. //kbuild:lib-$(CONFIG_ASH_TEST) += test.o test_ptr_hack.o
  55. //kbuild:lib-$(CONFIG_HUSH_TEST) += test.o test_ptr_hack.o
  56. /* "test --help" is special-cased to ignore --help */
  57. //usage:#define test_trivial_usage NOUSAGE_STR
  58. //usage:#define test_full_usage ""
  59. //usage:
  60. //usage:#define test_example_usage
  61. //usage: "$ test 1 -eq 2\n"
  62. //usage: "$ echo $?\n"
  63. //usage: "1\n"
  64. //usage: "$ test 1 -eq 1\n"
  65. //usage: "$ echo $?\n"
  66. //usage: "0\n"
  67. //usage: "$ [ -d /etc ]\n"
  68. //usage: "$ echo $?\n"
  69. //usage: "0\n"
  70. //usage: "$ [ -d /junk ]\n"
  71. //usage: "$ echo $?\n"
  72. //usage: "1\n"
  73. #include "libbb.h"
  74. #include <regex.h>
  75. #include <fnmatch.h>
  76. /* This is a NOFORK applet. Be very careful! */
  77. /* test_main() is called from shells, and we need to be extra careful here.
  78. * This is true regardless of PREFER_APPLETS and SH_STANDALONE
  79. * state. */
  80. /* test(1) accepts the following grammar:
  81. oexpr ::= aexpr | aexpr "-o" oexpr ;
  82. aexpr ::= nexpr | nexpr "-a" aexpr ;
  83. nexpr ::= primary | "!" primary
  84. primary ::= unary-operator operand
  85. | operand binary-operator operand
  86. | operand
  87. | "(" oexpr ")"
  88. ;
  89. unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
  90. "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
  91. binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
  92. "-nt"|"-ot"|"-ef";
  93. operand ::= <any legal UNIX file name>
  94. */
  95. /* TODO: handle [[ expr ]] bashism bash-compatibly.
  96. * [[ ]] is meant to be a "better [ ]", with less weird syntax
  97. * and without the risk of variables and quoted strings misinterpreted
  98. * as operators.
  99. * This will require support from shells - we need to know quote status
  100. * of each parameter (see below).
  101. *
  102. * Word splitting and pathname expansion should NOT be performed:
  103. * # a="a b"; [[ $a = "a b" ]] && echo YES
  104. * YES
  105. * # [[ /bin/m* ]] && echo YES
  106. * YES
  107. *
  108. * =~ should do regexp match
  109. * = and == should do pattern match against right side:
  110. * # [[ *a* == bab ]] && echo YES
  111. * # [[ bab == *a* ]] && echo YES
  112. * YES
  113. * != does the negated == (i.e., also with pattern matching).
  114. * Pattern matching is quotation-sensitive:
  115. * # [[ bab == "b"a* ]] && echo YES
  116. * YES
  117. * # [[ bab == b"a*" ]] && echo YES
  118. *
  119. * Conditional operators such as -f must be unquoted literals to be recognized:
  120. * # [[ -e /bin ]] && echo YES
  121. * YES
  122. * # [[ '-e' /bin ]] && echo YES
  123. * bash: conditional binary operator expected...
  124. * # A='-e'; [[ $A /bin ]] && echo YES
  125. * bash: conditional binary operator expected...
  126. *
  127. * || and && should work as -o and -a work in [ ]
  128. * -a and -o aren't recognized (&& and || are to be used instead)
  129. * ( and ) do not need to be quoted unlike in [ ]:
  130. * # [[ ( abc ) && '' ]] && echo YES
  131. * # [[ ( abc ) || '' ]] && echo YES
  132. * YES
  133. * # [[ ( abc ) -o '' ]] && echo YES
  134. * bash: syntax error in conditional expression...
  135. *
  136. * Apart from the above, [[ expr ]] should work as [ expr ]
  137. */
  138. #define TEST_DEBUG 0
  139. #if ENABLE_TEST2 \
  140. || (ENABLE_ASH_BASH_COMPAT && ENABLE_ASH_TEST) \
  141. || (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  142. # define BASH_TEST2 1
  143. #else
  144. # define BASH_TEST2 0
  145. #endif
  146. enum token {
  147. EOI,
  148. FILRD, /* file access */
  149. FILWR,
  150. FILEX,
  151. FILEXIST,
  152. FILREG, /* file type */
  153. FILDIR,
  154. FILCDEV,
  155. FILBDEV,
  156. FILFIFO,
  157. FILSOCK,
  158. FILSYM,
  159. FILGZ,
  160. FILTT,
  161. FILSUID, /* file bit */
  162. FILSGID,
  163. FILSTCK,
  164. FILNT, /* file ops */
  165. FILOT,
  166. FILEQ,
  167. FILUID,
  168. FILGID,
  169. STREZ, /* str ops */
  170. STRNZ,
  171. STREQ,
  172. STRNE,
  173. STRLT,
  174. STRGT,
  175. #if BASH_TEST2
  176. REGEX,
  177. #endif
  178. INTEQ, /* int ops */
  179. INTNE,
  180. INTGE,
  181. INTGT,
  182. INTLE,
  183. INTLT,
  184. UNOT,
  185. BAND,
  186. BOR,
  187. LPAREN,
  188. RPAREN,
  189. OPERAND
  190. };
  191. #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
  192. #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
  193. #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
  194. #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
  195. #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
  196. #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
  197. #if TEST_DEBUG
  198. int depth;
  199. #define nest_msg(...) do { \
  200. depth++; \
  201. fprintf(stderr, "%*s", depth*2, ""); \
  202. fprintf(stderr, __VA_ARGS__); \
  203. } while (0)
  204. #define unnest_msg(...) do { \
  205. fprintf(stderr, "%*s", depth*2, ""); \
  206. fprintf(stderr, __VA_ARGS__); \
  207. depth--; \
  208. } while (0)
  209. #define dbg_msg(...) do { \
  210. fprintf(stderr, "%*s", depth*2, ""); \
  211. fprintf(stderr, __VA_ARGS__); \
  212. } while (0)
  213. #define unnest_msg_and_return(expr, ...) do { \
  214. number_t __res = (expr); \
  215. fprintf(stderr, "%*s", depth*2, ""); \
  216. fprintf(stderr, __VA_ARGS__, res); \
  217. depth--; \
  218. return __res; \
  219. } while (0)
  220. static const char *const TOKSTR[] ALIGN_PTR = {
  221. "EOI",
  222. "FILRD",
  223. "FILWR",
  224. "FILEX",
  225. "FILEXIST",
  226. "FILREG",
  227. "FILDIR",
  228. "FILCDEV",
  229. "FILBDEV",
  230. "FILFIFO",
  231. "FILSOCK",
  232. "FILSYM",
  233. "FILGZ",
  234. "FILTT",
  235. "FILSUID",
  236. "FILSGID",
  237. "FILSTCK",
  238. "FILNT",
  239. "FILOT",
  240. "FILEQ",
  241. "FILUID",
  242. "FILGID",
  243. "STREZ",
  244. "STRNZ",
  245. "STREQ",
  246. "STRNE",
  247. "STRLT",
  248. "STRGT",
  249. #if BASH_TEST2
  250. "REGEX",
  251. #endif
  252. "INTEQ",
  253. "INTNE",
  254. "INTGE",
  255. "INTGT",
  256. "INTLE",
  257. "INTLT",
  258. "UNOT",
  259. "BAND",
  260. "BOR",
  261. "LPAREN",
  262. "RPAREN",
  263. "OPERAND"
  264. };
  265. #else
  266. #define nest_msg(...) ((void)0)
  267. #define unnest_msg(...) ((void)0)
  268. #define dbg_msg(...) ((void)0)
  269. #define unnest_msg_and_return(expr, ...) return expr
  270. #endif
  271. enum {
  272. UNOP,
  273. BINOP,
  274. BUNOP,
  275. BBINOP,
  276. PAREN
  277. };
  278. struct operator_t {
  279. unsigned char op_num, op_type;
  280. };
  281. static const struct operator_t ops_table[] ALIGN2 = {
  282. { /* "-r" */ FILRD , UNOP },
  283. { /* "-w" */ FILWR , UNOP },
  284. { /* "-x" */ FILEX , UNOP },
  285. { /* "-e" */ FILEXIST, UNOP },
  286. { /* "-f" */ FILREG , UNOP },
  287. { /* "-d" */ FILDIR , UNOP },
  288. { /* "-c" */ FILCDEV , UNOP },
  289. { /* "-b" */ FILBDEV , UNOP },
  290. { /* "-p" */ FILFIFO , UNOP },
  291. { /* "-u" */ FILSUID , UNOP },
  292. { /* "-g" */ FILSGID , UNOP },
  293. { /* "-k" */ FILSTCK , UNOP },
  294. { /* "-s" */ FILGZ , UNOP },
  295. { /* "-t" */ FILTT , UNOP },
  296. { /* "-z" */ STREZ , UNOP },
  297. { /* "-n" */ STRNZ , UNOP },
  298. { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
  299. { /* "-O" */ FILUID , UNOP },
  300. { /* "-G" */ FILGID , UNOP },
  301. { /* "-L" */ FILSYM , UNOP },
  302. { /* "-S" */ FILSOCK , UNOP },
  303. { /* "=" */ STREQ , BINOP },
  304. /* "==" is bashism, http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
  305. * lists only "=" as comparison operator.
  306. */
  307. { /* "==" */ STREQ , BINOP },
  308. { /* "!=" */ STRNE , BINOP },
  309. { /* "<" */ STRLT , BINOP },
  310. { /* ">" */ STRGT , BINOP },
  311. #if BASH_TEST2
  312. { /* "=~" */ REGEX , BINOP },
  313. #endif
  314. { /* "-eq"*/ INTEQ , BINOP },
  315. { /* "-ne"*/ INTNE , BINOP },
  316. { /* "-ge"*/ INTGE , BINOP },
  317. { /* "-gt"*/ INTGT , BINOP },
  318. { /* "-le"*/ INTLE , BINOP },
  319. { /* "-lt"*/ INTLT , BINOP },
  320. { /* "-nt"*/ FILNT , BINOP },
  321. { /* "-ot"*/ FILOT , BINOP },
  322. { /* "-ef"*/ FILEQ , BINOP },
  323. { /* "!" */ UNOT , BUNOP },
  324. { /* "-a" */ BAND , BBINOP },
  325. { /* "-o" */ BOR , BBINOP },
  326. #if BASH_TEST2
  327. { /* "&&" */ BAND , BBINOP },
  328. { /* "||" */ BOR , BBINOP },
  329. #endif
  330. { /* "(" */ LPAREN , PAREN },
  331. { /* ")" */ RPAREN , PAREN },
  332. };
  333. /* Please keep these two tables in sync */
  334. static const char ops_texts[] ALIGN1 =
  335. "-r" "\0"
  336. "-w" "\0"
  337. "-x" "\0"
  338. "-e" "\0"
  339. "-f" "\0"
  340. "-d" "\0"
  341. "-c" "\0"
  342. "-b" "\0"
  343. "-p" "\0"
  344. "-u" "\0"
  345. "-g" "\0"
  346. "-k" "\0"
  347. "-s" "\0"
  348. "-t" "\0"
  349. "-z" "\0"
  350. "-n" "\0"
  351. "-h" "\0"
  352. "-O" "\0"
  353. "-G" "\0"
  354. "-L" "\0"
  355. "-S" "\0"
  356. "=" "\0"
  357. /* "==" is bashism */
  358. "==" "\0"
  359. "!=" "\0"
  360. "<" "\0"
  361. ">" "\0"
  362. #if BASH_TEST2
  363. "=~" "\0"
  364. #endif
  365. "-eq" "\0"
  366. "-ne" "\0"
  367. "-ge" "\0"
  368. "-gt" "\0"
  369. "-le" "\0"
  370. "-lt" "\0"
  371. "-nt" "\0"
  372. "-ot" "\0"
  373. "-ef" "\0"
  374. "!" "\0"
  375. "-a" "\0"
  376. "-o" "\0"
  377. #if BASH_TEST2
  378. "&&" "\0"
  379. "||" "\0"
  380. #endif
  381. "(" "\0"
  382. ")" "\0"
  383. ;
  384. #if ENABLE_FEATURE_TEST_64
  385. typedef int64_t number_t;
  386. #else
  387. typedef int number_t;
  388. #endif
  389. /* We try to minimize both static and stack usage. */
  390. struct test_statics {
  391. char **args;
  392. /* set only by check_operator(), either to bogus struct
  393. * or points to matching operator_t struct. Never NULL. */
  394. const struct operator_t *last_operator;
  395. gid_t *group_array;
  396. int ngroups;
  397. #if BASH_TEST2
  398. bool bash_test2;
  399. #endif
  400. jmp_buf leaving;
  401. };
  402. /* See test_ptr_hack.c */
  403. extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
  404. #define S (*test_ptr_to_statics)
  405. #define args (S.args )
  406. #define last_operator (S.last_operator)
  407. #define group_array (S.group_array )
  408. #define ngroups (S.ngroups )
  409. #define bash_test2 (S.bash_test2 )
  410. #define leaving (S.leaving )
  411. #define INIT_S() do { \
  412. XZALLOC_CONST_PTR(&test_ptr_to_statics, sizeof(S)); \
  413. } while (0)
  414. #define DEINIT_S() do { \
  415. free(group_array); \
  416. free(test_ptr_to_statics); \
  417. } while (0)
  418. static number_t primary(enum token n);
  419. static void syntax(const char *op, const char *msg) NORETURN;
  420. static void syntax(const char *op, const char *msg)
  421. {
  422. if (op && *op) {
  423. bb_error_msg("%s: %s", op, msg);
  424. } else {
  425. bb_error_msg("%s: %s"+4, msg);
  426. }
  427. longjmp(leaving, 2);
  428. }
  429. /* atoi with error detection */
  430. //XXX: FIXME: duplicate of existing libbb function?
  431. static number_t getn(const char *s)
  432. {
  433. char *p;
  434. #if ENABLE_FEATURE_TEST_64
  435. long long r;
  436. #else
  437. long r;
  438. #endif
  439. errno = 0;
  440. #if ENABLE_FEATURE_TEST_64
  441. r = strtoll(s, &p, 10);
  442. #else
  443. r = strtol(s, &p, 10);
  444. #endif
  445. if (errno != 0)
  446. syntax(s, "out of range");
  447. if (p == s || *(skip_whitespace(p)) != '\0')
  448. syntax(s, "bad number");
  449. return r;
  450. }
  451. /* UNUSED
  452. static int newerf(const char *f1, const char *f2)
  453. {
  454. struct stat b1, b2;
  455. return (stat(f1, &b1) == 0 &&
  456. stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
  457. }
  458. static int olderf(const char *f1, const char *f2)
  459. {
  460. struct stat b1, b2;
  461. return (stat(f1, &b1) == 0 &&
  462. stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
  463. }
  464. static int equalf(const char *f1, const char *f2)
  465. {
  466. struct stat b1, b2;
  467. return (stat(f1, &b1) == 0 &&
  468. stat(f2, &b2) == 0 &&
  469. b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
  470. }
  471. */
  472. static enum token check_operator(const char *s)
  473. {
  474. static const struct operator_t no_op = {
  475. .op_num = -1,
  476. .op_type = -1
  477. };
  478. int n;
  479. last_operator = &no_op;
  480. if (s == NULL)
  481. return EOI;
  482. n = index_in_strings(ops_texts, s);
  483. if (n < 0)
  484. return OPERAND;
  485. #if BASH_TEST2
  486. if (ops_table[n].op_num == REGEX && !bash_test2) {
  487. /* =~ is only for [[ ]] */
  488. return OPERAND;
  489. }
  490. if (ops_table[n].op_num == BAND || ops_table[n].op_num == BOR) {
  491. /* [ ] accepts -a and -o but not && and || */
  492. /* [[ ]] accepts && and || but not -a and -o */
  493. if (bash_test2 == (s[0] == '-'))
  494. return OPERAND;
  495. }
  496. #endif
  497. last_operator = &ops_table[n];
  498. return ops_table[n].op_num;
  499. }
  500. static int binop(void)
  501. {
  502. const char *opnd1, *opnd2;
  503. const struct operator_t *op;
  504. number_t val1, val2;
  505. opnd1 = *args;
  506. check_operator(*++args);
  507. op = last_operator;
  508. opnd2 = *++args;
  509. if (opnd2 == NULL)
  510. syntax(args[-1], "argument expected");
  511. if (is_int_op(op->op_num)) {
  512. val1 = getn(opnd1);
  513. val2 = getn(opnd2);
  514. if (op->op_num == INTEQ)
  515. return val1 == val2;
  516. if (op->op_num == INTNE)
  517. return val1 != val2;
  518. if (op->op_num == INTGE)
  519. return val1 >= val2;
  520. if (op->op_num == INTGT)
  521. return val1 > val2;
  522. if (op->op_num == INTLE)
  523. return val1 <= val2;
  524. /*if (op->op_num == INTLT)*/
  525. return val1 < val2;
  526. }
  527. #if BASH_TEST2
  528. if (bash_test2) {
  529. if (op->op_num == STREQ) {
  530. val1 = fnmatch(opnd2, opnd1, 0);
  531. return val1 == 0;
  532. }
  533. if (op->op_num == STRNE) {
  534. val1 = fnmatch(opnd2, opnd1, 0);
  535. return val1 != 0;
  536. }
  537. if (op->op_num == REGEX) {
  538. regex_t re_buffer;
  539. memset(&re_buffer, 0, sizeof(re_buffer));
  540. if (regcomp(&re_buffer, opnd2, REG_EXTENDED)) { // REG_NEWLINE?
  541. /* Bad regex */
  542. longjmp(leaving, 2); /* [[ a =~ * ]]; echo $? - prints 2 (silently, no error msg) */
  543. }
  544. val1 = regexec(&re_buffer, opnd1, 0, NULL, 0);
  545. regfree(&re_buffer);
  546. return val1 == 0;
  547. }
  548. }
  549. #endif
  550. if (is_str_op(op->op_num)) {
  551. val1 = strcmp(opnd1, opnd2);
  552. if (op->op_num == STREQ)
  553. return val1 == 0;
  554. if (op->op_num == STRNE)
  555. return val1 != 0;
  556. if (op->op_num == STRLT)
  557. return val1 < 0;
  558. /*if (op->op_num == STRGT)*/
  559. return val1 > 0;
  560. }
  561. /* We are sure that these three are by now the only binops we didn't check
  562. * yet, so we do not check if the class is correct:
  563. */
  564. /* if (is_file_op(op->op_num)) */
  565. {
  566. struct stat b1, b2;
  567. if (stat(opnd1, &b1) || stat(opnd2, &b2))
  568. return 0; /* false, since at least one stat failed */
  569. if (op->op_num == FILNT)
  570. return b1.st_mtime > b2.st_mtime;
  571. if (op->op_num == FILOT)
  572. return b1.st_mtime < b2.st_mtime;
  573. /*if (op->op_num == FILEQ)*/
  574. return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
  575. }
  576. /*return 1; - NOTREACHED */
  577. }
  578. static void initialize_group_array(void)
  579. {
  580. group_array = bb_getgroups(&ngroups, NULL);
  581. }
  582. /* Return non-zero if GID is one that we have in our groups list. */
  583. //XXX: FIXME: duplicate of existing libbb function?
  584. // see toplevel TODO file:
  585. // possible code duplication ingroup() and is_a_group_member()
  586. static int is_a_group_member(gid_t gid)
  587. {
  588. int i;
  589. /* Short-circuit if possible, maybe saving a call to getgroups(). */
  590. if (gid == getgid() || gid == getegid())
  591. return 1;
  592. if (ngroups == 0)
  593. initialize_group_array();
  594. /* Search through the list looking for GID. */
  595. for (i = 0; i < ngroups; i++)
  596. if (gid == group_array[i])
  597. return 1;
  598. return 0;
  599. }
  600. /* Do the same thing access(2) does, but use the effective uid and gid,
  601. and don't make the mistake of telling root that any file is
  602. executable. */
  603. static int test_eaccess(struct stat *st, int mode)
  604. {
  605. unsigned int euid = geteuid();
  606. if (euid == 0) {
  607. /* Root can read or write any file. */
  608. if (mode != X_OK)
  609. return 0;
  610. /* Root can execute any file that has any one of the execute
  611. * bits set. */
  612. if (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
  613. return 0;
  614. }
  615. if (st->st_uid == euid) /* owner */
  616. mode <<= 6;
  617. else if (is_a_group_member(st->st_gid))
  618. mode <<= 3;
  619. if (st->st_mode & mode)
  620. return 0;
  621. return -1;
  622. }
  623. static int filstat(char *nm, enum token mode)
  624. {
  625. struct stat s;
  626. unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
  627. if (mode == FILSYM) {
  628. #ifdef S_IFLNK
  629. if (lstat(nm, &s) == 0) {
  630. i = S_IFLNK;
  631. goto filetype;
  632. }
  633. #endif
  634. return 0;
  635. }
  636. if (stat(nm, &s) != 0)
  637. return 0;
  638. if (mode == FILEXIST)
  639. return 1;
  640. if (is_file_access(mode)) {
  641. if (mode == FILRD)
  642. i = R_OK;
  643. if (mode == FILWR)
  644. i = W_OK;
  645. if (mode == FILEX)
  646. i = X_OK;
  647. return test_eaccess(&s, i) == 0;
  648. }
  649. if (is_file_type(mode)) {
  650. if (mode == FILREG)
  651. i = S_IFREG;
  652. if (mode == FILDIR)
  653. i = S_IFDIR;
  654. if (mode == FILCDEV)
  655. i = S_IFCHR;
  656. if (mode == FILBDEV)
  657. i = S_IFBLK;
  658. if (mode == FILFIFO) {
  659. #ifdef S_IFIFO
  660. i = S_IFIFO;
  661. #else
  662. return 0;
  663. #endif
  664. }
  665. if (mode == FILSOCK) {
  666. #ifdef S_IFSOCK
  667. i = S_IFSOCK;
  668. #else
  669. return 0;
  670. #endif
  671. }
  672. filetype:
  673. return ((s.st_mode & S_IFMT) == i);
  674. }
  675. if (is_file_bit(mode)) {
  676. if (mode == FILSUID)
  677. i = S_ISUID;
  678. if (mode == FILSGID)
  679. i = S_ISGID;
  680. if (mode == FILSTCK)
  681. i = S_ISVTX;
  682. return ((s.st_mode & i) != 0);
  683. }
  684. if (mode == FILGZ)
  685. return s.st_size > 0L;
  686. if (mode == FILUID)
  687. return s.st_uid == geteuid();
  688. if (mode == FILGID)
  689. return s.st_gid == getegid();
  690. return 1; /* NOTREACHED */
  691. }
  692. static number_t nexpr(enum token n)
  693. {
  694. number_t res;
  695. nest_msg(">nexpr(%s)\n", TOKSTR[n]);
  696. if (n == UNOT) {
  697. n = check_operator(*++args);
  698. if (n == EOI) {
  699. /* special case: [ ! ], [ a -a ! ] are valid */
  700. /* IOW, "! ARG" may miss ARG */
  701. args--;
  702. unnest_msg("<nexpr:1 (!EOI), args:%s(%p)\n", args[0], &args[0]);
  703. return 1;
  704. }
  705. res = !nexpr(n);
  706. unnest_msg("<nexpr:%lld\n", res);
  707. return res;
  708. }
  709. res = primary(n);
  710. unnest_msg("<nexpr:%lld\n", res);
  711. return res;
  712. }
  713. static number_t aexpr(enum token n)
  714. {
  715. number_t res;
  716. nest_msg(">aexpr(%s)\n", TOKSTR[n]);
  717. res = nexpr(n);
  718. dbg_msg("aexpr: nexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
  719. if (check_operator(*++args) == BAND) {
  720. dbg_msg("aexpr: arg is AND, next args:%s(%p)\n", args[1], &args[1]);
  721. res = aexpr(check_operator(*++args)) && res;
  722. unnest_msg("<aexpr:%lld\n", res);
  723. return res;
  724. }
  725. args--;
  726. unnest_msg("<aexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
  727. return res;
  728. }
  729. static number_t oexpr(enum token n)
  730. {
  731. number_t res;
  732. nest_msg(">oexpr(%s)\n", TOKSTR[n]);
  733. res = aexpr(n);
  734. dbg_msg("oexpr: aexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
  735. if (check_operator(*++args) == BOR) {
  736. dbg_msg("oexpr: next arg is OR, next args:%s(%p)\n", args[1], &args[1]);
  737. res = oexpr(check_operator(*++args)) || res;
  738. unnest_msg("<oexpr:%lld\n", res);
  739. return res;
  740. }
  741. args--;
  742. unnest_msg("<oexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
  743. return res;
  744. }
  745. static number_t primary(enum token n)
  746. {
  747. #if TEST_DEBUG
  748. number_t res = res; /* for compiler */
  749. #else
  750. number_t res;
  751. #endif
  752. const struct operator_t *args0_op;
  753. nest_msg(">primary(%s)\n", TOKSTR[n]);
  754. if (n == EOI) {
  755. syntax(NULL, "argument expected");
  756. }
  757. if (n == LPAREN) {
  758. res = oexpr(check_operator(*++args));
  759. if (check_operator(*++args) != RPAREN)
  760. syntax(NULL, "closing paren expected");
  761. unnest_msg("<primary:%lld\n", res);
  762. return res;
  763. }
  764. /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
  765. * do the same */
  766. args0_op = last_operator;
  767. /* last_operator = operator at args[1] */
  768. if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
  769. if (args[2]) {
  770. // coreutils also does this:
  771. // if (args[3] && args[0] = "-l" && args[2] is BINOP)
  772. // return binop(1 /* prepended by -l */);
  773. if (last_operator->op_type == BINOP)
  774. unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
  775. }
  776. }
  777. /* check "is args[0] unop?" second */
  778. if (args0_op->op_type == UNOP) {
  779. /* unary expression */
  780. if (args[1] == NULL)
  781. // syntax(args0_op->op_text, "argument expected");
  782. goto check_emptiness;
  783. args++;
  784. if (n == STREZ)
  785. unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
  786. if (n == STRNZ)
  787. unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
  788. if (n == FILTT)
  789. unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
  790. unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
  791. }
  792. /*check_operator(args[1]); - already done */
  793. if (last_operator->op_type == BINOP) {
  794. /* args[2] is known to be NULL, isn't it bound to fail? */
  795. unnest_msg_and_return(binop(), "<primary:%lld\n");
  796. }
  797. check_emptiness:
  798. unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
  799. }
  800. int test_main(int argc, char **argv)
  801. {
  802. int res;
  803. const char *arg0;
  804. #if BASH_TEST2
  805. bool bt2 = 0;
  806. #endif
  807. arg0 = bb_basename(argv[0]);
  808. if ((ENABLE_TEST1 || ENABLE_TEST2 || ENABLE_ASH_TEST || ENABLE_HUSH_TEST)
  809. && (arg0[0] == '[')
  810. ) {
  811. --argc;
  812. if (!arg0[1]) { /* "[" ? */
  813. if (NOT_LONE_CHAR(argv[argc], ']')) {
  814. bb_simple_error_msg("missing ]");
  815. return 2;
  816. }
  817. } else { /* assuming "[[" */
  818. if (strcmp(argv[argc], "]]") != 0) {
  819. bb_simple_error_msg("missing ]]");
  820. return 2;
  821. }
  822. #if BASH_TEST2
  823. bt2 = 1;
  824. #endif
  825. }
  826. argv[argc] = NULL;
  827. }
  828. /* argc is unused after this point */
  829. /* We must do DEINIT_S() prior to returning */
  830. INIT_S();
  831. #if BASH_TEST2
  832. bash_test2 = bt2;
  833. #endif
  834. res = setjmp(leaving);
  835. if (res)
  836. goto ret;
  837. /* resetting ngroups is probably unnecessary. it will
  838. * force a new call to getgroups(), which prevents using
  839. * group data fetched during a previous call. but the
  840. * only way the group data could be stale is if there's
  841. * been an intervening call to setgroups(), and this
  842. * isn't likely in the case of a shell. paranoia
  843. * prevails...
  844. */
  845. /*ngroups = 0; - done by INIT_S() */
  846. argv++;
  847. args = argv;
  848. /* Implement special cases from POSIX.2, section 4.62.4.
  849. * Testcase: "test '(' = '('"
  850. * The general parser would misinterpret '(' as group start.
  851. */
  852. if (1) {
  853. int negate = 0;
  854. again:
  855. if (!argv[0]) {
  856. /* "test" */
  857. res = 1;
  858. goto ret_special;
  859. }
  860. if (!argv[1]) {
  861. /* "test [!] arg" */
  862. res = (argv[0][0] == '\0');
  863. goto ret_special;
  864. }
  865. if (argv[2]) {
  866. if (!argv[3]) {
  867. /*
  868. * http://pubs.opengroup.org/onlinepubs/009695399/utilities/test.html
  869. * """ 3 arguments:
  870. * If $2 is a binary primary, perform the binary test of $1 and $3.
  871. * """
  872. */
  873. check_operator(argv[1]);
  874. if (last_operator->op_type == BINOP) {
  875. /* "test [!] arg1 <binary_op> arg2" */
  876. args = argv;
  877. res = (binop() == 0);
  878. ret_special:
  879. /* If there was leading "!" op... */
  880. res ^= negate;
  881. goto ret;
  882. }
  883. /* """If $1 is '(' and $3 is ')', perform the unary test of $2."""
  884. * Looks like this works without additional coding.
  885. */
  886. goto check_negate;
  887. }
  888. /* argv[3] exists (at least 4 args), is it exactly 4 args? */
  889. if (!argv[4]) {
  890. /*
  891. * """ 4 arguments:
  892. * If $1 is '!', negate the three-argument test of $2, $3, and $4.
  893. * If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3.
  894. * """
  895. * Example why code below is necessary: test '(' ! -e ')'
  896. */
  897. if (LONE_CHAR(argv[0], '(')
  898. && LONE_CHAR(argv[3], ')')
  899. ) {
  900. /* "test [!] ( x y )" */
  901. argv[3] = NULL;
  902. argv++;
  903. }
  904. }
  905. }
  906. check_negate:
  907. if (LONE_CHAR(argv[0], '!')) {
  908. argv++;
  909. negate ^= 1;
  910. goto again;
  911. }
  912. }
  913. res = !oexpr(check_operator(*args));
  914. if (*args != NULL && *++args != NULL) {
  915. /* Examples:
  916. * test 3 -lt 5 6
  917. * test -t 1 2
  918. */
  919. bb_error_msg("%s: unknown operand", *args);
  920. res = 2;
  921. }
  922. ret:
  923. DEINIT_S();
  924. return res;
  925. }