test.c 22 KB

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