1 /* vi: set sw=4 ts=4: */
3 * test implementation for busybox
5 * Copyright (c) by a whole pile of folks:
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
15 * modified by Bernhard Reutner-Fischer to be useable (i.e. a bit less bloaty).
17 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
19 * Original copyright notice states:
20 * "This program is in the Public Domain."
25 /* This is a NOFORK applet. Be very careful! */
27 /* test_main() is called from shells, and we need to be extra careful here.
28 * This is true regardless of PREFER_APPLETS and STANDALONE_SHELL
31 /* test(1) accepts the following grammar:
32 oexpr ::= aexpr | aexpr "-o" oexpr ;
33 aexpr ::= nexpr | nexpr "-a" aexpr ;
34 nexpr ::= primary | "!" primary
35 primary ::= unary-operator operand
36 | operand binary-operator operand
40 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
41 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
43 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
45 operand ::= <any legal UNIX file name>
48 /* TODO: handle [[ expr ]] bashism bash-compatibly.
49 * [[ ]] is meant to be a "better [ ]", with less weird syntax
50 * and without the risk of variables and quoted strings misinterpreted
52 * This will require support from shells - we need to know quote status
53 * of each parameter (see below).
55 * Word splitting and pathname expansion should NOT be performed:
56 * # a="a b"; [[ $a = "a b" ]] && echo YES
58 * # [[ /bin/m* ]] && echo YES
61 * =~ should do regexp match
62 * = and == should do pattern match against right side:
63 * # [[ *a* == bab ]] && echo YES
64 * # [[ bab == *a* ]] && echo YES
66 * != does the negated == (i.e., also with pattern matching).
67 * Pattern matching is quotation-sensitive:
68 * # [[ bab == "b"a* ]] && echo YES
70 * # [[ bab == b"a*" ]] && echo YES
72 * Conditional operators such as -f must be unquoted literals to be recognized:
73 * # [[ -e /bin ]] && echo YES
75 * # [[ '-e' /bin ]] && echo YES
76 * bash: conditional binary operator expected...
77 * # A='-e'; [[ $A /bin ]] && echo YES
78 * bash: conditional binary operator expected...
80 * || and && should work as -o and -a work in [ ]
81 * -a and -o aren't recognized (&& and || are to be used instead)
82 * ( and ) do not need to be quoted unlike in [ ]:
83 * # [[ ( abc ) && '' ]] && echo YES
84 * # [[ ( abc ) || '' ]] && echo YES
86 * # [[ ( abc ) -o '' ]] && echo YES
87 * bash: syntax error in conditional expression...
89 * Apart from the above, [[ expr ]] should work as [ expr ]
97 FILRD, /* file access */
103 FILREG, /* file type */
114 FILSUID, /* file bit */
118 FILNT, /* file ops */
146 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
147 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
148 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
149 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
150 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
151 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
155 #define nest_msg(...) do { \
157 fprintf(stderr, "%*s", depth*2, ""); \
158 fprintf(stderr, __VA_ARGS__); \
160 #define unnest_msg(...) do { \
161 fprintf(stderr, "%*s", depth*2, ""); \
162 fprintf(stderr, __VA_ARGS__); \
165 #define dbg_msg(...) do { \
166 fprintf(stderr, "%*s", depth*2, ""); \
167 fprintf(stderr, __VA_ARGS__); \
169 #define unnest_msg_and_return(expr, ...) do { \
170 number_t __res = (expr); \
171 fprintf(stderr, "%*s", depth*2, ""); \
172 fprintf(stderr, __VA_ARGS__, res); \
176 static const char *const TOKSTR[] = {
219 #define nest_msg(...) ((void)0)
220 #define unnest_msg(...) ((void)0)
221 #define dbg_msg(...) ((void)0)
222 #define unnest_msg_and_return(expr, ...) return expr
234 unsigned char op_num, op_type;
237 static const struct operator_t ops_table[] = {
238 { /* "-r" */ FILRD , UNOP },
239 { /* "-w" */ FILWR , UNOP },
240 { /* "-x" */ FILEX , UNOP },
241 { /* "-e" */ FILEXIST, UNOP },
242 { /* "-f" */ FILREG , UNOP },
243 { /* "-d" */ FILDIR , UNOP },
244 { /* "-c" */ FILCDEV , UNOP },
245 { /* "-b" */ FILBDEV , UNOP },
246 { /* "-p" */ FILFIFO , UNOP },
247 { /* "-u" */ FILSUID , UNOP },
248 { /* "-g" */ FILSGID , UNOP },
249 { /* "-k" */ FILSTCK , UNOP },
250 { /* "-s" */ FILGZ , UNOP },
251 { /* "-t" */ FILTT , UNOP },
252 { /* "-z" */ STREZ , UNOP },
253 { /* "-n" */ STRNZ , UNOP },
254 { /* "-h" */ FILSYM , UNOP }, /* for backwards compat */
256 { /* "-O" */ FILUID , UNOP },
257 { /* "-G" */ FILGID , UNOP },
258 { /* "-L" */ FILSYM , UNOP },
259 { /* "-S" */ FILSOCK , UNOP },
260 { /* "=" */ STREQ , BINOP },
261 { /* "==" */ STREQ , BINOP },
262 { /* "!=" */ STRNE , BINOP },
263 { /* "<" */ STRLT , BINOP },
264 { /* ">" */ STRGT , BINOP },
265 { /* "-eq"*/ INTEQ , BINOP },
266 { /* "-ne"*/ INTNE , BINOP },
267 { /* "-ge"*/ INTGE , BINOP },
268 { /* "-gt"*/ INTGT , BINOP },
269 { /* "-le"*/ INTLE , BINOP },
270 { /* "-lt"*/ INTLT , BINOP },
271 { /* "-nt"*/ FILNT , BINOP },
272 { /* "-ot"*/ FILOT , BINOP },
273 { /* "-ef"*/ FILEQ , BINOP },
274 { /* "!" */ UNOT , BUNOP },
275 { /* "-a" */ BAND , BBINOP },
276 { /* "-o" */ BOR , BBINOP },
277 { /* "(" */ LPAREN , PAREN },
278 { /* ")" */ RPAREN , PAREN },
280 /* Please keep these two tables in sync */
281 static const char ops_texts[] ALIGN1 =
326 #if ENABLE_FEATURE_TEST_64
327 typedef int64_t number_t;
329 typedef int number_t;
333 /* We try to minimize both static and stack usage. */
334 struct test_statics {
336 /* set only by check_operator(), either to bogus struct
337 * or points to matching operator_t struct. Never NULL. */
338 const struct operator_t *last_operator;
344 /* See test_ptr_hack.c */
345 extern struct test_statics *const test_ptr_to_statics;
347 #define S (*test_ptr_to_statics)
348 #define args (S.args )
349 #define last_operator (S.last_operator)
350 #define group_array (S.group_array )
351 #define ngroups (S.ngroups )
352 #define leaving (S.leaving )
354 #define INIT_S() do { \
355 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
358 #define DEINIT_S() do { \
359 free(test_ptr_to_statics); \
362 static number_t primary(enum token n);
364 static void syntax(const char *op, const char *msg) NORETURN;
365 static void syntax(const char *op, const char *msg)
368 bb_error_msg("%s: %s", op, msg);
370 bb_error_msg("%s: %s"+4, msg);
375 /* atoi with error detection */
376 //XXX: FIXME: duplicate of existing libbb function?
377 static number_t getn(const char *s)
380 #if ENABLE_FEATURE_TEST_64
387 #if ENABLE_FEATURE_TEST_64
388 r = strtoll(s, &p, 10);
390 r = strtol(s, &p, 10);
394 syntax(s, "out of range");
396 if (*(skip_whitespace(p)))
397 syntax(s, "bad number");
403 static int newerf(const char *f1, const char *f2)
407 return (stat(f1, &b1) == 0 &&
408 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
411 static int olderf(const char *f1, const char *f2)
415 return (stat(f1, &b1) == 0 &&
416 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
419 static int equalf(const char *f1, const char *f2)
423 return (stat(f1, &b1) == 0 &&
424 stat(f2, &b2) == 0 &&
425 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
430 static enum token check_operator(const char *s)
432 static const struct operator_t no_op = {
438 last_operator = &no_op;
441 n = index_in_strings(ops_texts, s);
444 last_operator = &ops_table[n];
445 return ops_table[n].op_num;
449 static int binop(void)
451 const char *opnd1, *opnd2;
452 const struct operator_t *op;
456 check_operator(*++args);
461 syntax(args[-1], "argument expected");
463 if (is_int_op(op->op_num)) {
466 if (op->op_num == INTEQ)
468 if (op->op_num == INTNE)
470 if (op->op_num == INTGE)
472 if (op->op_num == INTGT)
474 if (op->op_num == INTLE)
476 /*if (op->op_num == INTLT)*/
479 if (is_str_op(op->op_num)) {
480 val1 = strcmp(opnd1, opnd2);
481 if (op->op_num == STREQ)
483 if (op->op_num == STRNE)
485 if (op->op_num == STRLT)
487 /*if (op->op_num == STRGT)*/
490 /* We are sure that these three are by now the only binops we didn't check
491 * yet, so we do not check if the class is correct:
493 /* if (is_file_op(op->op_num)) */
497 if (stat(opnd1, &b1) || stat(opnd2, &b2))
498 return 0; /* false, since at least one stat failed */
499 if (op->op_num == FILNT)
500 return b1.st_mtime > b2.st_mtime;
501 if (op->op_num == FILOT)
502 return b1.st_mtime < b2.st_mtime;
503 /*if (op->op_num == FILEQ)*/
504 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
506 /*return 1; - NOTREACHED */
510 static void initialize_group_array(void)
514 /* getgroups may be expensive, try to use it only once */
517 /* FIXME: ash tries so hard to not die on OOM,
518 * and we spoil it with just one xrealloc here */
519 /* We realloc, because test_main can be entered repeatedly by shell.
520 * Testcase (ash): 'while true; do test -x some_file; done'
521 * and watch top. (some_file must have owner != you) */
523 group_array = xrealloc(group_array, n * sizeof(gid_t));
524 ngroups = getgroups(n, group_array);
525 } while (ngroups > n);
529 /* Return non-zero if GID is one that we have in our groups list. */
530 //XXX: FIXME: duplicate of existing libbb function?
531 // see toplevel TODO file:
532 // possible code duplication ingroup() and is_a_group_member()
533 static int is_a_group_member(gid_t gid)
537 /* Short-circuit if possible, maybe saving a call to getgroups(). */
538 if (gid == getgid() || gid == getegid())
542 initialize_group_array();
544 /* Search through the list looking for GID. */
545 for (i = 0; i < ngroups; i++)
546 if (gid == group_array[i])
553 /* Do the same thing access(2) does, but use the effective uid and gid,
554 and don't make the mistake of telling root that any file is
556 static int test_eaccess(char *path, int mode)
559 unsigned int euid = geteuid();
561 if (stat(path, &st) < 0)
565 /* Root can read or write any file. */
569 /* Root can execute any file that has any one of the execute
571 if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
575 if (st.st_uid == euid) /* owner */
577 else if (is_a_group_member(st.st_gid))
580 if (st.st_mode & mode)
587 static int filstat(char *nm, enum token mode)
590 unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
592 if (mode == FILSYM) {
594 if (lstat(nm, &s) == 0) {
602 if (stat(nm, &s) != 0)
604 if (mode == FILEXIST)
606 if (is_file_access(mode)) {
613 return test_eaccess(nm, i) == 0;
615 if (is_file_type(mode)) {
624 if (mode == FILFIFO) {
631 if (mode == FILSOCK) {
639 return ((s.st_mode & S_IFMT) == i);
641 if (is_file_bit(mode)) {
648 return ((s.st_mode & i) != 0);
651 return s.st_size > 0L;
653 return s.st_uid == geteuid();
655 return s.st_gid == getegid();
656 return 1; /* NOTREACHED */
660 static number_t nexpr(enum token n)
664 nest_msg(">nexpr(%s)\n", TOKSTR[n]);
666 n = check_operator(*++args);
668 /* special case: [ ! ], [ a -a ! ] are valid */
669 /* IOW, "! ARG" may miss ARG */
670 unnest_msg("<nexpr:1 (!EOI)\n");
674 unnest_msg("<nexpr:%lld\n", res);
678 unnest_msg("<nexpr:%lld\n", res);
683 static number_t aexpr(enum token n)
687 nest_msg(">aexpr(%s)\n", TOKSTR[n]);
689 dbg_msg("aexpr: nexpr:%lld, next args:%s\n", res, args[1]);
690 if (check_operator(*++args) == BAND) {
691 dbg_msg("aexpr: arg is AND, next args:%s\n", args[1]);
692 res = aexpr(check_operator(*++args)) && res;
693 unnest_msg("<aexpr:%lld\n", res);
697 unnest_msg("<aexpr:%lld, args:%s\n", res, args[0]);
702 static number_t oexpr(enum token n)
706 nest_msg(">oexpr(%s)\n", TOKSTR[n]);
708 dbg_msg("oexpr: aexpr:%lld, next args:%s\n", res, args[1]);
709 if (check_operator(*++args) == BOR) {
710 dbg_msg("oexpr: next arg is OR, next args:%s\n", args[1]);
711 res = oexpr(check_operator(*++args)) || res;
712 unnest_msg("<oexpr:%lld\n", res);
716 unnest_msg("<oexpr:%lld, args:%s\n", res, args[0]);
721 static number_t primary(enum token n)
724 number_t res = res; /* for compiler */
728 const struct operator_t *args0_op;
730 nest_msg(">primary(%s)\n", TOKSTR[n]);
732 syntax(NULL, "argument expected");
735 res = oexpr(check_operator(*++args));
736 if (check_operator(*++args) != RPAREN)
737 syntax(NULL, "closing paren expected");
738 unnest_msg("<primary:%lld\n", res);
742 /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
744 args0_op = last_operator;
745 /* last_operator = operator at args[1] */
746 if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
748 // coreutils also does this:
749 // if (args[3] && args[0]="-l" && args[2] is BINOP)
750 // return binop(1 /* prepended by -l */);
751 if (last_operator->op_type == BINOP)
752 unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
755 /* check "is args[0] unop?" second */
756 if (args0_op->op_type == UNOP) {
757 /* unary expression */
759 // syntax(args0_op->op_text, "argument expected");
760 goto check_emptiness;
763 unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
765 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
767 unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
768 unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
771 /*check_operator(args[1]); - already done */
772 if (last_operator->op_type == BINOP) {
773 /* args[2] is known to be NULL, isn't it bound to fail? */
774 unnest_msg_and_return(binop(), "<primary:%lld\n");
777 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
781 int test_main(int argc, char **argv)
787 arg0 = bb_basename(argv[0]);
788 if (arg0[0] == '[') {
790 if (!arg0[1]) { /* "[" ? */
791 if (NOT_LONE_CHAR(argv[argc], ']')) {
792 bb_error_msg("missing ]");
795 } else { /* assuming "[[" */
796 if (strcmp(argv[argc], "]]") != 0) {
797 bb_error_msg("missing ]]");
804 /* We must do DEINIT_S() prior to returning */
807 res = setjmp(leaving);
811 /* resetting ngroups is probably unnecessary. it will
812 * force a new call to getgroups(), which prevents using
813 * group data fetched during a previous call. but the
814 * only way the group data could be stale is if there's
815 * been an intervening call to setgroups(), and this
816 * isn't likely in the case of a shell. paranoia
819 /*ngroups = 0; - done by INIT_S() */
824 /* Implement special cases from POSIX.2, section 4.62.4 */
825 if (!argv[0]) { /* "test" */
830 // Now it's fixed in the parser and should not be needed
831 if (LONE_CHAR(argv[0], '!') && argv[1]) {
836 if (!argv[1]) { /* "test [!] arg" */
837 res = (*argv[0] == '\0');
840 if (argv[2] && !argv[3]) {
841 check_operator(argv[1]);
842 if (last_operator->op_type == BINOP) {
843 /* "test [!] arg1 <binary_op> arg2" */
845 res = (binop() == 0);
850 /* Some complex expression. Undo '!' removal */
858 res = !oexpr(check_operator(*args));
860 if (*args != NULL && *++args != NULL) {
861 /* TODO: example when this happens? */
862 bb_error_msg("%s: unknown operand", *args);
867 // return negate ? !res : res;