test.c 23 KB

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