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
235 unsigned char op_num, op_type;
238 static const struct operator_t ops[] = {
239 { "-r", FILRD , UNOP },
240 { "-w", FILWR , UNOP },
241 { "-x", FILEX , UNOP },
242 { "-e", FILEXIST, UNOP },
243 { "-f", FILREG , UNOP },
244 { "-d", FILDIR , UNOP },
245 { "-c", FILCDEV , UNOP },
246 { "-b", FILBDEV , UNOP },
247 { "-p", FILFIFO , UNOP },
248 { "-u", FILSUID , UNOP },
249 { "-g", FILSGID , UNOP },
250 { "-k", FILSTCK , UNOP },
251 { "-s", FILGZ , UNOP },
252 { "-t", FILTT , UNOP },
253 { "-z", STREZ , UNOP },
254 { "-n", STRNZ , UNOP },
255 { "-h", FILSYM , UNOP }, /* for backwards compat */
257 { "-O" , FILUID , UNOP },
258 { "-G" , FILGID , UNOP },
259 { "-L" , FILSYM , UNOP },
260 { "-S" , FILSOCK, UNOP },
261 { "=" , STREQ , BINOP },
262 { "==" , STREQ , BINOP },
263 { "!=" , STRNE , BINOP },
264 { "<" , STRLT , BINOP },
265 { ">" , STRGT , BINOP },
266 { "-eq", INTEQ , BINOP },
267 { "-ne", INTNE , BINOP },
268 { "-ge", INTGE , BINOP },
269 { "-gt", INTGT , BINOP },
270 { "-le", INTLE , BINOP },
271 { "-lt", INTLT , BINOP },
272 { "-nt", FILNT , BINOP },
273 { "-ot", FILOT , BINOP },
274 { "-ef", FILEQ , BINOP },
275 { "!" , UNOT , BUNOP },
276 { "-a" , BAND , BBINOP },
277 { "-o" , BOR , BBINOP },
278 { "(" , LPAREN , PAREN },
279 { ")" , RPAREN , PAREN },
283 #if ENABLE_FEATURE_TEST_64
284 typedef int64_t number_t;
286 typedef int number_t;
290 /* We try to minimize both static and stack usage. */
291 struct test_statics {
293 /* set only by check_operator(), either to bogus struct
294 * or points to matching operator_t struct. Never NULL. */
295 const struct operator_t *last_operator;
301 /* See test_ptr_hack.c */
302 extern struct test_statics *const test_ptr_to_statics;
304 #define S (*test_ptr_to_statics)
305 #define args (S.args )
306 #define last_operator (S.last_operator)
307 #define group_array (S.group_array )
308 #define ngroups (S.ngroups )
309 #define leaving (S.leaving )
311 #define INIT_S() do { \
312 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
315 #define DEINIT_S() do { \
316 free(test_ptr_to_statics); \
319 static number_t primary(enum token n);
321 static void syntax(const char *op, const char *msg) NORETURN;
322 static void syntax(const char *op, const char *msg)
325 bb_error_msg("%s: %s", op, msg);
327 bb_error_msg("%s: %s"+4, msg);
332 /* atoi with error detection */
333 //XXX: FIXME: duplicate of existing libbb function?
334 static number_t getn(const char *s)
337 #if ENABLE_FEATURE_TEST_64
344 #if ENABLE_FEATURE_TEST_64
345 r = strtoll(s, &p, 10);
347 r = strtol(s, &p, 10);
351 syntax(s, "out of range");
353 if (*(skip_whitespace(p)))
354 syntax(s, "bad number");
360 static int newerf(const char *f1, const char *f2)
364 return (stat(f1, &b1) == 0 &&
365 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
368 static int olderf(const char *f1, const char *f2)
372 return (stat(f1, &b1) == 0 &&
373 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
376 static int equalf(const char *f1, const char *f2)
380 return (stat(f1, &b1) == 0 &&
381 stat(f2, &b2) == 0 &&
382 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
387 static enum token check_operator(char *s)
389 static const struct operator_t no_op = {
393 const struct operator_t *op;
395 last_operator = &no_op;
402 if (strcmp(s, op->op_text) == 0) {
407 } while (op < ops + ARRAY_SIZE(ops));
413 static int binop(void)
415 const char *opnd1, *opnd2;
416 const struct operator_t *op;
420 check_operator(*++args);
425 syntax(op->op_text, "argument expected");
427 if (is_int_op(op->op_num)) {
430 if (op->op_num == INTEQ)
432 if (op->op_num == INTNE)
434 if (op->op_num == INTGE)
436 if (op->op_num == INTGT)
438 if (op->op_num == INTLE)
440 /*if (op->op_num == INTLT)*/
443 if (is_str_op(op->op_num)) {
444 val1 = strcmp(opnd1, opnd2);
445 if (op->op_num == STREQ)
447 if (op->op_num == STRNE)
449 if (op->op_num == STRLT)
451 /*if (op->op_num == STRGT)*/
454 /* We are sure that these three are by now the only binops we didn't check
455 * yet, so we do not check if the class is correct:
457 /* if (is_file_op(op->op_num)) */
461 if (stat(opnd1, &b1) || stat(opnd2, &b2))
462 return 0; /* false, since at least one stat failed */
463 if (op->op_num == FILNT)
464 return b1.st_mtime > b2.st_mtime;
465 if (op->op_num == FILOT)
466 return b1.st_mtime < b2.st_mtime;
467 /*if (op->op_num == FILEQ)*/
468 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
470 /*return 1; - NOTREACHED */
474 static void initialize_group_array(void)
478 /* getgroups may be expensive, try to use it only once */
481 /* FIXME: ash tries so hard to not die on OOM,
482 * and we spoil it with just one xrealloc here */
483 /* We realloc, because test_main can be entered repeatedly by shell.
484 * Testcase (ash): 'while true; do test -x some_file; done'
485 * and watch top. (some_file must have owner != you) */
487 group_array = xrealloc(group_array, n * sizeof(gid_t));
488 ngroups = getgroups(n, group_array);
489 } while (ngroups > n);
493 /* Return non-zero if GID is one that we have in our groups list. */
494 //XXX: FIXME: duplicate of existing libbb function?
495 // see toplevel TODO file:
496 // possible code duplication ingroup() and is_a_group_member()
497 static int is_a_group_member(gid_t gid)
501 /* Short-circuit if possible, maybe saving a call to getgroups(). */
502 if (gid == getgid() || gid == getegid())
506 initialize_group_array();
508 /* Search through the list looking for GID. */
509 for (i = 0; i < ngroups; i++)
510 if (gid == group_array[i])
517 /* Do the same thing access(2) does, but use the effective uid and gid,
518 and don't make the mistake of telling root that any file is
520 static int test_eaccess(char *path, int mode)
523 unsigned int euid = geteuid();
525 if (stat(path, &st) < 0)
529 /* Root can read or write any file. */
533 /* Root can execute any file that has any one of the execute
535 if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
539 if (st.st_uid == euid) /* owner */
541 else if (is_a_group_member(st.st_gid))
544 if (st.st_mode & mode)
551 static int filstat(char *nm, enum token mode)
554 unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
556 if (mode == FILSYM) {
558 if (lstat(nm, &s) == 0) {
566 if (stat(nm, &s) != 0)
568 if (mode == FILEXIST)
570 if (is_file_access(mode)) {
577 return test_eaccess(nm, i) == 0;
579 if (is_file_type(mode)) {
588 if (mode == FILFIFO) {
595 if (mode == FILSOCK) {
603 return ((s.st_mode & S_IFMT) == i);
605 if (is_file_bit(mode)) {
612 return ((s.st_mode & i) != 0);
615 return s.st_size > 0L;
617 return s.st_uid == geteuid();
619 return s.st_gid == getegid();
620 return 1; /* NOTREACHED */
624 static number_t nexpr(enum token n)
628 nest_msg(">nexpr(%s)\n", TOKSTR[n]);
630 n = check_operator(*++args);
632 /* special case: [ ! ], [ a -a ! ] are valid */
633 /* IOW, "! ARG" may miss ARG */
634 unnest_msg("<nexpr:1 (!EOI)\n");
638 unnest_msg("<nexpr:%lld\n", res);
642 unnest_msg("<nexpr:%lld\n", res);
647 static number_t aexpr(enum token n)
651 nest_msg(">aexpr(%s)\n", TOKSTR[n]);
653 dbg_msg("aexpr: nexpr:%lld, next args:%s\n", res, args[1]);
654 if (check_operator(*++args) == BAND) {
655 dbg_msg("aexpr: arg is AND, next args:%s\n", args[1]);
656 res = aexpr(check_operator(*++args)) && res;
657 unnest_msg("<aexpr:%lld\n", res);
661 unnest_msg("<aexpr:%lld, args:%s\n", res, args[0]);
666 static number_t oexpr(enum token n)
670 nest_msg(">oexpr(%s)\n", TOKSTR[n]);
672 dbg_msg("oexpr: aexpr:%lld, next args:%s\n", res, args[1]);
673 if (check_operator(*++args) == BOR) {
674 dbg_msg("oexpr: next arg is OR, next args:%s\n", args[1]);
675 res = oexpr(check_operator(*++args)) || res;
676 unnest_msg("<oexpr:%lld\n", res);
680 unnest_msg("<oexpr:%lld, args:%s\n", res, args[0]);
685 static number_t primary(enum token n)
688 number_t res = res; /* for compiler */
692 const struct operator_t *args0_op;
694 nest_msg(">primary(%s)\n", TOKSTR[n]);
696 syntax(NULL, "argument expected");
699 res = oexpr(check_operator(*++args));
700 if (check_operator(*++args) != RPAREN)
701 syntax(NULL, "closing paren expected");
702 unnest_msg("<primary:%lld\n", res);
706 /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
708 args0_op = last_operator;
709 /* last_operator = operator at args[1] */
710 if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
712 // coreutils also does this:
713 // if (args[3] && args[0]="-l" && args[2] is BINOP)
714 // return binop(1 /* prepended by -l */);
715 if (last_operator->op_type == BINOP)
716 unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
719 /* check "is args[0] unop?" second */
720 if (args0_op->op_type == UNOP) {
721 /* unary expression */
723 // syntax(args0_op->op_text, "argument expected");
724 goto check_emptiness;
727 unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
729 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
731 unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
732 unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
735 /*check_operator(args[1]); - already done */
736 if (last_operator->op_type == BINOP) {
737 /* args[2] is known to be NULL, isn't it bound to fail? */
738 unnest_msg_and_return(binop(), "<primary:%lld\n");
741 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
745 int test_main(int argc, char **argv)
751 arg0 = bb_basename(argv[0]);
752 if (arg0[0] == '[') {
754 if (!arg0[1]) { /* "[" ? */
755 if (NOT_LONE_CHAR(argv[argc], ']')) {
756 bb_error_msg("missing ]");
759 } else { /* assuming "[[" */
760 if (strcmp(argv[argc], "]]") != 0) {
761 bb_error_msg("missing ]]");
768 /* We must do DEINIT_S() prior to returning */
771 res = setjmp(leaving);
775 /* resetting ngroups is probably unnecessary. it will
776 * force a new call to getgroups(), which prevents using
777 * group data fetched during a previous call. but the
778 * only way the group data could be stale is if there's
779 * been an intervening call to setgroups(), and this
780 * isn't likely in the case of a shell. paranoia
783 /*ngroups = 0; - done by INIT_S() */
788 /* Implement special cases from POSIX.2, section 4.62.4 */
789 if (!argv[0]) { /* "test" */
794 // Now it's fixed in the parser and should not be needed
795 if (LONE_CHAR(argv[0], '!') && argv[1]) {
800 if (!argv[1]) { /* "test [!] arg" */
801 res = (*argv[0] == '\0');
804 if (argv[2] && !argv[3]) {
805 check_operator(argv[1]);
806 if (last_operator->op_type == BINOP) {
807 /* "test [!] arg1 <binary_op> arg2" */
809 res = (binop() == 0);
814 /* Some complex expression. Undo '!' removal */
822 res = !oexpr(check_operator(*args));
824 if (*args != NULL && *++args != NULL) {
825 /* TODO: example when this happens? */
826 bb_error_msg("%s: unknown operand", *args);
831 // return negate ? !res : res;