test.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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[] = {
  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 *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. (*(struct test_statics**)not_const_pp(&test_ptr_to_statics)) = xzalloc(sizeof(S)); \
  413. barrier(); \
  414. } while (0)
  415. #define DEINIT_S() do { \
  416. free(group_array); \
  417. free(test_ptr_to_statics); \
  418. } while (0)
  419. static number_t primary(enum token n);
  420. static void syntax(const char *op, const char *msg) NORETURN;
  421. static void syntax(const char *op, const char *msg)
  422. {
  423. if (op && *op) {
  424. bb_error_msg("%s: %s", op, msg);
  425. } else {
  426. bb_error_msg("%s: %s"+4, msg);
  427. }
  428. longjmp(leaving, 2);
  429. }
  430. /* atoi with error detection */
  431. //XXX: FIXME: duplicate of existing libbb function?
  432. static number_t getn(const char *s)
  433. {
  434. char *p;
  435. #if ENABLE_FEATURE_TEST_64
  436. long long r;
  437. #else
  438. long r;
  439. #endif
  440. errno = 0;
  441. #if ENABLE_FEATURE_TEST_64
  442. r = strtoll(s, &p, 10);
  443. #else
  444. r = strtol(s, &p, 10);
  445. #endif
  446. if (errno != 0)
  447. syntax(s, "out of range");
  448. if (p == s || *(skip_whitespace(p)) != '\0')
  449. syntax(s, "bad number");
  450. return r;
  451. }
  452. /* UNUSED
  453. static int newerf(const char *f1, const char *f2)
  454. {
  455. struct stat b1, b2;
  456. return (stat(f1, &b1) == 0 &&
  457. stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
  458. }
  459. static int olderf(const char *f1, const char *f2)
  460. {
  461. struct stat b1, b2;
  462. return (stat(f1, &b1) == 0 &&
  463. stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
  464. }
  465. static int equalf(const char *f1, const char *f2)
  466. {
  467. struct stat b1, b2;
  468. return (stat(f1, &b1) == 0 &&
  469. stat(f2, &b2) == 0 &&
  470. b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
  471. }
  472. */
  473. static enum token check_operator(const char *s)
  474. {
  475. static const struct operator_t no_op = {
  476. .op_num = -1,
  477. .op_type = -1
  478. };
  479. int n;
  480. last_operator = &no_op;
  481. if (s == NULL)
  482. return EOI;
  483. n = index_in_strings(ops_texts, s);
  484. if (n < 0)
  485. return OPERAND;
  486. #if BASH_TEST2
  487. if (ops_table[n].op_num == REGEX && !bash_test2) {
  488. /* =~ is only for [[ ]] */
  489. return OPERAND;
  490. }
  491. if (ops_table[n].op_num == BAND || ops_table[n].op_num == BOR) {
  492. /* [ ] accepts -a and -o but not && and || */
  493. /* [[ ]] accepts && and || but not -a and -o */
  494. if (bash_test2 == (s[0] == '-'))
  495. return OPERAND;
  496. }
  497. #endif
  498. last_operator = &ops_table[n];
  499. return ops_table[n].op_num;
  500. }
  501. static int binop(void)
  502. {
  503. const char *opnd1, *opnd2;
  504. const struct operator_t *op;
  505. number_t val1, val2;
  506. opnd1 = *args;
  507. check_operator(*++args);
  508. op = last_operator;
  509. opnd2 = *++args;
  510. if (opnd2 == NULL)
  511. syntax(args[-1], "argument expected");
  512. if (is_int_op(op->op_num)) {
  513. val1 = getn(opnd1);
  514. val2 = getn(opnd2);
  515. if (op->op_num == INTEQ)
  516. return val1 == val2;
  517. if (op->op_num == INTNE)
  518. return val1 != val2;
  519. if (op->op_num == INTGE)
  520. return val1 >= val2;
  521. if (op->op_num == INTGT)
  522. return val1 > val2;
  523. if (op->op_num == INTLE)
  524. return val1 <= val2;
  525. /*if (op->op_num == INTLT)*/
  526. return val1 < val2;
  527. }
  528. #if BASH_TEST2
  529. if (bash_test2) {
  530. if (op->op_num == STREQ) {
  531. val1 = fnmatch(opnd2, opnd1, 0);
  532. return val1 == 0;
  533. }
  534. if (op->op_num == STRNE) {
  535. val1 = fnmatch(opnd2, opnd1, 0);
  536. return val1 != 0;
  537. }
  538. if (op->op_num == REGEX) {
  539. regex_t re_buffer;
  540. memset(&re_buffer, 0, sizeof(re_buffer));
  541. if (regcomp(&re_buffer, opnd2, REG_EXTENDED)) { // REG_NEWLINE?
  542. /* Bad regex */
  543. longjmp(leaving, 2); /* [[ a =~ * ]]; echo $? - prints 2 (silently, no error msg) */
  544. }
  545. val1 = regexec(&re_buffer, opnd1, 0, NULL, 0);
  546. regfree(&re_buffer);
  547. return val1 == 0;
  548. }
  549. }
  550. #endif
  551. if (is_str_op(op->op_num)) {
  552. val1 = strcmp(opnd1, opnd2);
  553. if (op->op_num == STREQ)
  554. return val1 == 0;
  555. if (op->op_num == STRNE)
  556. return val1 != 0;
  557. if (op->op_num == STRLT)
  558. return val1 < 0;
  559. /*if (op->op_num == STRGT)*/
  560. return val1 > 0;
  561. }
  562. /* We are sure that these three are by now the only binops we didn't check
  563. * yet, so we do not check if the class is correct:
  564. */
  565. /* if (is_file_op(op->op_num)) */
  566. {
  567. struct stat b1, b2;
  568. if (stat(opnd1, &b1) || stat(opnd2, &b2))
  569. return 0; /* false, since at least one stat failed */
  570. if (op->op_num == FILNT)
  571. return b1.st_mtime > b2.st_mtime;
  572. if (op->op_num == FILOT)
  573. return b1.st_mtime < b2.st_mtime;
  574. /*if (op->op_num == FILEQ)*/
  575. return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
  576. }
  577. /*return 1; - NOTREACHED */
  578. }
  579. static void initialize_group_array(void)
  580. {
  581. group_array = bb_getgroups(&ngroups, NULL);
  582. }
  583. /* Return non-zero if GID is one that we have in our groups list. */
  584. //XXX: FIXME: duplicate of existing libbb function?
  585. // see toplevel TODO file:
  586. // possible code duplication ingroup() and is_a_group_member()
  587. static int is_a_group_member(gid_t gid)
  588. {
  589. int i;
  590. /* Short-circuit if possible, maybe saving a call to getgroups(). */
  591. if (gid == getgid() || gid == getegid())
  592. return 1;
  593. if (ngroups == 0)
  594. initialize_group_array();
  595. /* Search through the list looking for GID. */
  596. for (i = 0; i < ngroups; i++)
  597. if (gid == group_array[i])
  598. return 1;
  599. return 0;
  600. }
  601. /* Do the same thing access(2) does, but use the effective uid and gid,
  602. and don't make the mistake of telling root that any file is
  603. executable. */
  604. static int test_eaccess(struct stat *st, int mode)
  605. {
  606. unsigned int euid = geteuid();
  607. if (euid == 0) {
  608. /* Root can read or write any file. */
  609. if (mode != X_OK)
  610. return 0;
  611. /* Root can execute any file that has any one of the execute
  612. * bits set. */
  613. if (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
  614. return 0;
  615. }
  616. if (st->st_uid == euid) /* owner */
  617. mode <<= 6;
  618. else if (is_a_group_member(st->st_gid))
  619. mode <<= 3;
  620. if (st->st_mode & mode)
  621. return 0;
  622. return -1;
  623. }
  624. static int filstat(char *nm, enum token mode)
  625. {
  626. struct stat s;
  627. unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
  628. if (mode == FILSYM) {
  629. #ifdef S_IFLNK
  630. if (lstat(nm, &s) == 0) {
  631. i = S_IFLNK;
  632. goto filetype;
  633. }
  634. #endif
  635. return 0;
  636. }
  637. if (stat(nm, &s) != 0)
  638. return 0;
  639. if (mode == FILEXIST)
  640. return 1;
  641. if (is_file_access(mode)) {
  642. if (mode == FILRD)
  643. i = R_OK;
  644. if (mode == FILWR)
  645. i = W_OK;
  646. if (mode == FILEX)
  647. i = X_OK;
  648. return test_eaccess(&s, i) == 0;
  649. }
  650. if (is_file_type(mode)) {
  651. if (mode == FILREG)
  652. i = S_IFREG;
  653. if (mode == FILDIR)
  654. i = S_IFDIR;
  655. if (mode == FILCDEV)
  656. i = S_IFCHR;
  657. if (mode == FILBDEV)
  658. i = S_IFBLK;
  659. if (mode == FILFIFO) {
  660. #ifdef S_IFIFO
  661. i = S_IFIFO;
  662. #else
  663. return 0;
  664. #endif
  665. }
  666. if (mode == FILSOCK) {
  667. #ifdef S_IFSOCK
  668. i = S_IFSOCK;
  669. #else
  670. return 0;
  671. #endif
  672. }
  673. filetype:
  674. return ((s.st_mode & S_IFMT) == i);
  675. }
  676. if (is_file_bit(mode)) {
  677. if (mode == FILSUID)
  678. i = S_ISUID;
  679. if (mode == FILSGID)
  680. i = S_ISGID;
  681. if (mode == FILSTCK)
  682. i = S_ISVTX;
  683. return ((s.st_mode & i) != 0);
  684. }
  685. if (mode == FILGZ)
  686. return s.st_size > 0L;
  687. if (mode == FILUID)
  688. return s.st_uid == geteuid();
  689. if (mode == FILGID)
  690. return s.st_gid == getegid();
  691. return 1; /* NOTREACHED */
  692. }
  693. static number_t nexpr(enum token n)
  694. {
  695. number_t res;
  696. nest_msg(">nexpr(%s)\n", TOKSTR[n]);
  697. if (n == UNOT) {
  698. n = check_operator(*++args);
  699. if (n == EOI) {
  700. /* special case: [ ! ], [ a -a ! ] are valid */
  701. /* IOW, "! ARG" may miss ARG */
  702. args--;
  703. unnest_msg("<nexpr:1 (!EOI), args:%s(%p)\n", args[0], &args[0]);
  704. return 1;
  705. }
  706. res = !nexpr(n);
  707. unnest_msg("<nexpr:%lld\n", res);
  708. return res;
  709. }
  710. res = primary(n);
  711. unnest_msg("<nexpr:%lld\n", res);
  712. return res;
  713. }
  714. static number_t aexpr(enum token n)
  715. {
  716. number_t res;
  717. nest_msg(">aexpr(%s)\n", TOKSTR[n]);
  718. res = nexpr(n);
  719. dbg_msg("aexpr: nexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
  720. if (check_operator(*++args) == BAND) {
  721. dbg_msg("aexpr: arg is AND, next args:%s(%p)\n", args[1], &args[1]);
  722. res = aexpr(check_operator(*++args)) && res;
  723. unnest_msg("<aexpr:%lld\n", res);
  724. return res;
  725. }
  726. args--;
  727. unnest_msg("<aexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
  728. return res;
  729. }
  730. static number_t oexpr(enum token n)
  731. {
  732. number_t res;
  733. nest_msg(">oexpr(%s)\n", TOKSTR[n]);
  734. res = aexpr(n);
  735. dbg_msg("oexpr: aexpr:%lld, next args:%s(%p)\n", res, args[1], &args[1]);
  736. if (check_operator(*++args) == BOR) {
  737. dbg_msg("oexpr: next arg is OR, next args:%s(%p)\n", args[1], &args[1]);
  738. res = oexpr(check_operator(*++args)) || res;
  739. unnest_msg("<oexpr:%lld\n", res);
  740. return res;
  741. }
  742. args--;
  743. unnest_msg("<oexpr:%lld, args:%s(%p)\n", res, args[0], &args[0]);
  744. return res;
  745. }
  746. static number_t primary(enum token n)
  747. {
  748. #if TEST_DEBUG
  749. number_t res = res; /* for compiler */
  750. #else
  751. number_t res;
  752. #endif
  753. const struct operator_t *args0_op;
  754. nest_msg(">primary(%s)\n", TOKSTR[n]);
  755. if (n == EOI) {
  756. syntax(NULL, "argument expected");
  757. }
  758. if (n == LPAREN) {
  759. res = oexpr(check_operator(*++args));
  760. if (check_operator(*++args) != RPAREN)
  761. syntax(NULL, "closing paren expected");
  762. unnest_msg("<primary:%lld\n", res);
  763. return res;
  764. }
  765. /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
  766. * do the same */
  767. args0_op = last_operator;
  768. /* last_operator = operator at args[1] */
  769. if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
  770. if (args[2]) {
  771. // coreutils also does this:
  772. // if (args[3] && args[0]="-l" && args[2] is BINOP)
  773. // return binop(1 /* prepended by -l */);
  774. if (last_operator->op_type == BINOP)
  775. unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
  776. }
  777. }
  778. /* check "is args[0] unop?" second */
  779. if (args0_op->op_type == UNOP) {
  780. /* unary expression */
  781. if (args[1] == NULL)
  782. // syntax(args0_op->op_text, "argument expected");
  783. goto check_emptiness;
  784. args++;
  785. if (n == STREZ)
  786. unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
  787. if (n == STRNZ)
  788. unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
  789. if (n == FILTT)
  790. unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
  791. unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
  792. }
  793. /*check_operator(args[1]); - already done */
  794. if (last_operator->op_type == BINOP) {
  795. /* args[2] is known to be NULL, isn't it bound to fail? */
  796. unnest_msg_and_return(binop(), "<primary:%lld\n");
  797. }
  798. check_emptiness:
  799. unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
  800. }
  801. int test_main(int argc, char **argv)
  802. {
  803. int res;
  804. const char *arg0;
  805. #if BASH_TEST2
  806. bool bt2 = 0;
  807. #endif
  808. arg0 = bb_basename(argv[0]);
  809. if ((ENABLE_TEST1 || ENABLE_TEST2 || ENABLE_ASH_TEST || ENABLE_HUSH_TEST)
  810. && (arg0[0] == '[')
  811. ) {
  812. --argc;
  813. if (!arg0[1]) { /* "[" ? */
  814. if (NOT_LONE_CHAR(argv[argc], ']')) {
  815. bb_simple_error_msg("missing ]");
  816. return 2;
  817. }
  818. } else { /* assuming "[[" */
  819. if (strcmp(argv[argc], "]]") != 0) {
  820. bb_simple_error_msg("missing ]]");
  821. return 2;
  822. }
  823. #if BASH_TEST2
  824. bt2 = 1;
  825. #endif
  826. }
  827. argv[argc] = NULL;
  828. }
  829. /* argc is unused after this point */
  830. /* We must do DEINIT_S() prior to returning */
  831. INIT_S();
  832. #if BASH_TEST2
  833. bash_test2 = bt2;
  834. #endif
  835. res = setjmp(leaving);
  836. if (res)
  837. goto ret;
  838. /* resetting ngroups is probably unnecessary. it will
  839. * force a new call to getgroups(), which prevents using
  840. * group data fetched during a previous call. but the
  841. * only way the group data could be stale is if there's
  842. * been an intervening call to setgroups(), and this
  843. * isn't likely in the case of a shell. paranoia
  844. * prevails...
  845. */
  846. /*ngroups = 0; - done by INIT_S() */
  847. argv++;
  848. args = argv;
  849. /* Implement special cases from POSIX.2, section 4.62.4.
  850. * Testcase: "test '(' = '('"
  851. * The general parser would misinterpret '(' as group start.
  852. */
  853. if (1) {
  854. int negate = 0;
  855. again:
  856. if (!argv[0]) {
  857. /* "test" */
  858. res = 1;
  859. goto ret_special;
  860. }
  861. if (!argv[1]) {
  862. /* "test [!] arg" */
  863. res = (argv[0][0] == '\0');
  864. goto ret_special;
  865. }
  866. if (argv[2]) {
  867. if (!argv[3]) {
  868. /*
  869. * http://pubs.opengroup.org/onlinepubs/009695399/utilities/test.html
  870. * """ 3 arguments:
  871. * If $2 is a binary primary, perform the binary test of $1 and $3.
  872. * """
  873. */
  874. check_operator(argv[1]);
  875. if (last_operator->op_type == BINOP) {
  876. /* "test [!] arg1 <binary_op> arg2" */
  877. args = argv;
  878. res = (binop() == 0);
  879. ret_special:
  880. /* If there was leading "!" op... */
  881. res ^= negate;
  882. goto ret;
  883. }
  884. /* """If $1 is '(' and $3 is ')', perform the unary test of $2."""
  885. * Looks like this works without additional coding.
  886. */
  887. goto check_negate;
  888. }
  889. /* argv[3] exists (at least 4 args), is it exactly 4 args? */
  890. if (!argv[4]) {
  891. /*
  892. * """ 4 arguments:
  893. * If $1 is '!', negate the three-argument test of $2, $3, and $4.
  894. * If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3.
  895. * """
  896. * Example why code below is necessary: test '(' ! -e ')'
  897. */
  898. if (LONE_CHAR(argv[0], '(')
  899. && LONE_CHAR(argv[3], ')')
  900. ) {
  901. /* "test [!] ( x y )" */
  902. argv[3] = NULL;
  903. argv++;
  904. }
  905. }
  906. }
  907. check_negate:
  908. if (LONE_CHAR(argv[0], '!')) {
  909. argv++;
  910. negate ^= 1;
  911. goto again;
  912. }
  913. }
  914. res = !oexpr(check_operator(*args));
  915. if (*args != NULL && *++args != NULL) {
  916. /* Examples:
  917. * test 3 -lt 5 6
  918. * test -t 1 2
  919. */
  920. bb_error_msg("%s: unknown operand", *args);
  921. res = 2;
  922. }
  923. ret:
  924. DEINIT_S();
  925. return res;
  926. }