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."
26 /* This is a NOFORK applet. Be very careful! */
28 /* test_main() is called from shells, and we need to be extra careful here.
29 * This is true regardless of PREFER_APPLETS and STANDALONE_SHELL
33 /* test(1) accepts the following grammar:
34 oexpr ::= aexpr | aexpr "-o" oexpr ;
35 aexpr ::= nexpr | nexpr "-a" aexpr ;
36 nexpr ::= primary | "!" primary
37 primary ::= unary-operator operand
38 | operand binary-operator operand
42 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
43 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
45 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
47 operand ::= <any legal UNIX file name>
55 FILRD, /* file access */
61 FILREG, /* file type */
72 FILSUID, /* file bit */
104 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
105 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
106 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
107 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
108 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
109 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
113 #define nest_msg(...) do { \
115 fprintf(stderr, "%*s", depth*2, ""); \
116 fprintf(stderr, __VA_ARGS__); \
118 #define unnest_msg(...) do { \
119 fprintf(stderr, "%*s", depth*2, ""); \
120 fprintf(stderr, __VA_ARGS__); \
123 #define dbg_msg(...) do { \
124 fprintf(stderr, "%*s", depth*2, ""); \
125 fprintf(stderr, __VA_ARGS__); \
127 #define unnest_msg_and_return(expr, ...) do { \
128 number_t __res = (expr); \
129 fprintf(stderr, "%*s", depth*2, ""); \
130 fprintf(stderr, __VA_ARGS__, res); \
134 static const char *const TOKSTR[] = {
177 #define nest_msg(...) ((void)0)
178 #define unnest_msg(...) ((void)0)
179 #define dbg_msg(...) ((void)0)
180 #define unnest_msg_and_return(expr, ...) return expr
193 unsigned char op_num, op_type;
196 static const struct operator_t ops[] = {
197 { "-r", FILRD , UNOP },
198 { "-w", FILWR , UNOP },
199 { "-x", FILEX , UNOP },
200 { "-e", FILEXIST, UNOP },
201 { "-f", FILREG , UNOP },
202 { "-d", FILDIR , UNOP },
203 { "-c", FILCDEV , UNOP },
204 { "-b", FILBDEV , UNOP },
205 { "-p", FILFIFO , UNOP },
206 { "-u", FILSUID , UNOP },
207 { "-g", FILSGID , UNOP },
208 { "-k", FILSTCK , UNOP },
209 { "-s", FILGZ , UNOP },
210 { "-t", FILTT , UNOP },
211 { "-z", STREZ , UNOP },
212 { "-n", STRNZ , UNOP },
213 { "-h", FILSYM , UNOP }, /* for backwards compat */
215 { "-O" , FILUID , UNOP },
216 { "-G" , FILGID , UNOP },
217 { "-L" , FILSYM , UNOP },
218 { "-S" , FILSOCK, UNOP },
219 { "=" , STREQ , BINOP },
220 { "==" , STREQ , BINOP },
221 { "!=" , STRNE , BINOP },
222 { "<" , STRLT , BINOP },
223 { ">" , STRGT , BINOP },
224 { "-eq", INTEQ , BINOP },
225 { "-ne", INTNE , BINOP },
226 { "-ge", INTGE , BINOP },
227 { "-gt", INTGT , BINOP },
228 { "-le", INTLE , BINOP },
229 { "-lt", INTLT , BINOP },
230 { "-nt", FILNT , BINOP },
231 { "-ot", FILOT , BINOP },
232 { "-ef", FILEQ , BINOP },
233 { "!" , UNOT , BUNOP },
234 { "-a" , BAND , BBINOP },
235 { "-o" , BOR , BBINOP },
236 { "(" , LPAREN , PAREN },
237 { ")" , RPAREN , PAREN },
241 #if ENABLE_FEATURE_TEST_64
242 typedef int64_t number_t;
244 typedef int number_t;
248 /* We try to minimize both static and stack usage. */
249 struct test_statics {
251 /* set only by check_operator(), either to bogus struct
252 * or points to matching operator_t struct. Never NULL. */
253 const struct operator_t *last_operator;
259 /* See test_ptr_hack.c */
260 extern struct test_statics *const test_ptr_to_statics;
262 #define S (*test_ptr_to_statics)
263 #define args (S.args )
264 #define last_operator (S.last_operator)
265 #define group_array (S.group_array )
266 #define ngroups (S.ngroups )
267 #define leaving (S.leaving )
269 #define INIT_S() do { \
270 (*(struct test_statics**)&test_ptr_to_statics) = xzalloc(sizeof(S)); \
273 #define DEINIT_S() do { \
274 free(test_ptr_to_statics); \
277 static number_t primary(enum token n);
279 static void syntax(const char *op, const char *msg) NORETURN;
280 static void syntax(const char *op, const char *msg)
283 bb_error_msg("%s: %s", op, msg);
285 bb_error_msg("%s: %s"+4, msg);
290 /* atoi with error detection */
291 //XXX: FIXME: duplicate of existing libbb function?
292 static number_t getn(const char *s)
295 #if ENABLE_FEATURE_TEST_64
302 #if ENABLE_FEATURE_TEST_64
303 r = strtoll(s, &p, 10);
305 r = strtol(s, &p, 10);
309 syntax(s, "out of range");
311 if (*(skip_whitespace(p)))
312 syntax(s, "bad number");
318 static int newerf(const char *f1, const char *f2)
322 return (stat(f1, &b1) == 0 &&
323 stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
326 static int olderf(const char *f1, const char *f2)
330 return (stat(f1, &b1) == 0 &&
331 stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
334 static int equalf(const char *f1, const char *f2)
338 return (stat(f1, &b1) == 0 &&
339 stat(f2, &b2) == 0 &&
340 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
345 static enum token check_operator(char *s)
347 static const struct operator_t no_op = {
351 const struct operator_t *op;
353 last_operator = &no_op;
360 if (strcmp(s, op->op_text) == 0) {
365 } while (op < ops + ARRAY_SIZE(ops));
371 static int binop(void)
373 const char *opnd1, *opnd2;
374 const struct operator_t *op;
378 check_operator(*++args);
383 syntax(op->op_text, "argument expected");
385 if (is_int_op(op->op_num)) {
388 if (op->op_num == INTEQ)
390 if (op->op_num == INTNE)
392 if (op->op_num == INTGE)
394 if (op->op_num == INTGT)
396 if (op->op_num == INTLE)
398 /*if (op->op_num == INTLT)*/
401 if (is_str_op(op->op_num)) {
402 val1 = strcmp(opnd1, opnd2);
403 if (op->op_num == STREQ)
405 if (op->op_num == STRNE)
407 if (op->op_num == STRLT)
409 /*if (op->op_num == STRGT)*/
412 /* We are sure that these three are by now the only binops we didn't check
413 * yet, so we do not check if the class is correct:
415 /* if (is_file_op(op->op_num)) */
419 if (stat(opnd1, &b1) || stat(opnd2, &b2))
420 return 0; /* false, since at least one stat failed */
421 if (op->op_num == FILNT)
422 return b1.st_mtime > b2.st_mtime;
423 if (op->op_num == FILOT)
424 return b1.st_mtime < b2.st_mtime;
425 /*if (op->op_num == FILEQ)*/
426 return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
428 /*return 1; - NOTREACHED */
432 static void initialize_group_array(void)
436 /* getgroups may be expensive, try to use it only once */
439 /* FIXME: ash tries so hard to not die on OOM,
440 * and we spoil it with just one xrealloc here */
441 /* We realloc, because test_main can be entered repeatedly by shell.
442 * Testcase (ash): 'while true; do test -x some_file; done'
443 * and watch top. (some_file must have owner != you) */
445 group_array = xrealloc(group_array, n * sizeof(gid_t));
446 ngroups = getgroups(n, group_array);
447 } while (ngroups > n);
451 /* Return non-zero if GID is one that we have in our groups list. */
452 //XXX: FIXME: duplicate of existing libbb function?
453 // see toplevel TODO file:
454 // possible code duplication ingroup() and is_a_group_member()
455 static int is_a_group_member(gid_t gid)
459 /* Short-circuit if possible, maybe saving a call to getgroups(). */
460 if (gid == getgid() || gid == getegid())
464 initialize_group_array();
466 /* Search through the list looking for GID. */
467 for (i = 0; i < ngroups; i++)
468 if (gid == group_array[i])
475 /* Do the same thing access(2) does, but use the effective uid and gid,
476 and don't make the mistake of telling root that any file is
478 static int test_eaccess(char *path, int mode)
481 unsigned int euid = geteuid();
483 if (stat(path, &st) < 0)
487 /* Root can read or write any file. */
491 /* Root can execute any file that has any one of the execute
493 if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
497 if (st.st_uid == euid) /* owner */
499 else if (is_a_group_member(st.st_gid))
502 if (st.st_mode & mode)
509 static int filstat(char *nm, enum token mode)
512 unsigned i = i; /* gcc 3.x thinks it can be used uninitialized */
514 if (mode == FILSYM) {
516 if (lstat(nm, &s) == 0) {
524 if (stat(nm, &s) != 0)
526 if (mode == FILEXIST)
528 if (is_file_access(mode)) {
535 return test_eaccess(nm, i) == 0;
537 if (is_file_type(mode)) {
546 if (mode == FILFIFO) {
553 if (mode == FILSOCK) {
561 return ((s.st_mode & S_IFMT) == i);
563 if (is_file_bit(mode)) {
570 return ((s.st_mode & i) != 0);
573 return s.st_size > 0L;
575 return s.st_uid == geteuid();
577 return s.st_gid == getegid();
578 return 1; /* NOTREACHED */
582 static number_t nexpr(enum token n)
586 nest_msg(">nexpr(%s)\n", TOKSTR[n]);
588 res = !nexpr(check_operator(*++args));
589 unnest_msg("<nexpr:%lld\n", res);
593 unnest_msg("<nexpr:%lld\n", res);
598 static number_t aexpr(enum token n)
602 nest_msg(">aexpr(%s)\n", TOKSTR[n]);
604 dbg_msg("aexpr: nexpr:%lld, next args:%s\n", res, args[1]);
605 if (check_operator(*++args) == BAND) {
606 dbg_msg("aexpr: arg is AND, next args:%s\n", args[1]);
607 res = aexpr(check_operator(*++args)) && res;
608 unnest_msg("<aexpr:%lld\n", res);
612 unnest_msg("<aexpr:%lld, args:%s\n", res, args[0]);
617 static number_t oexpr(enum token n)
621 nest_msg(">oexpr(%s)\n", TOKSTR[n]);
623 dbg_msg("oexpr: aexpr:%lld, next args:%s\n", res, args[1]);
624 if (check_operator(*++args) == BOR) {
625 dbg_msg("oexpr: next arg is OR, next args:%s\n", args[1]);
626 res = oexpr(check_operator(*++args)) || res;
627 unnest_msg("<oexpr:%lld\n", res);
631 unnest_msg("<oexpr:%lld, args:%s\n", res, args[0]);
636 static number_t primary(enum token n)
639 number_t res = res; /* for compiler */
643 const struct operator_t *args0_op;
645 nest_msg(">primary(%s)\n", TOKSTR[n]);
647 syntax(NULL, "argument expected");
650 res = oexpr(check_operator(*++args));
651 if (check_operator(*++args) != RPAREN)
652 syntax(NULL, "closing paren expected");
653 unnest_msg("<primary:%lld\n", res);
657 /* coreutils 6.9 checks "is args[1] binop and args[2] exist?" first,
659 args0_op = last_operator;
660 /* last_operator = operator at args[1] */
661 if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
663 // coreutils also does this:
664 // if (args[3] && args[0]="-l" && args[2] is BINOP)
665 // return binop(1 /* prepended by -l */);
666 if (last_operator->op_type == BINOP)
667 unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
670 /* check "is args[0] unop?" second */
671 if (args0_op->op_type == UNOP) {
672 /* unary expression */
674 // syntax(args0_op->op_text, "argument expected");
675 goto check_emptiness;
678 unnest_msg_and_return(args[0][0] == '\0', "<primary:%lld\n");
680 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
682 unnest_msg_and_return(isatty(getn(*args)), "<primary: isatty(%s)%lld\n", *args);
683 unnest_msg_and_return(filstat(*args, n), "<primary: filstat(%s):%lld\n", *args);
686 /*check_operator(args[1]); - already done */
687 if (last_operator->op_type == BINOP) {
688 /* args[2] is known to be NULL, isn't it bound to fail? */
689 unnest_msg_and_return(binop(), "<primary:%lld\n");
692 unnest_msg_and_return(args[0][0] != '\0', "<primary:%lld\n");
696 int test_main(int argc, char **argv)
702 arg0 = bb_basename(argv[0]);
703 if (arg0[0] == '[') {
705 if (!arg0[1]) { /* "[" ? */
706 if (NOT_LONE_CHAR(argv[argc], ']')) {
707 bb_error_msg("missing ]");
710 } else { /* assuming "[[" */
711 if (strcmp(argv[argc], "]]") != 0) {
712 bb_error_msg("missing ]]");
719 /* We must do DEINIT_S() prior to returning */
722 res = setjmp(leaving);
726 /* resetting ngroups is probably unnecessary. it will
727 * force a new call to getgroups(), which prevents using
728 * group data fetched during a previous call. but the
729 * only way the group data could be stale is if there's
730 * been an intervening call to setgroups(), and this
731 * isn't likely in the case of a shell. paranoia
734 /*ngroups = 0; - done by INIT_S() */
739 /* Implement special cases from POSIX.2, section 4.62.4 */
740 if (!argv[0]) { /* "test" */
745 // Now it's fixed in the parser and should not be needed
746 if (LONE_CHAR(argv[0], '!') && argv[1]) {
751 if (!argv[1]) { /* "test [!] arg" */
752 res = (*argv[0] == '\0');
755 if (argv[2] && !argv[3]) {
756 check_operator(argv[1]);
757 if (last_operator->op_type == BINOP) {
758 /* "test [!] arg1 <binary_op> arg2" */
760 res = (binop() == 0);
765 /* Some complex expression. Undo '!' removal */
773 res = !oexpr(check_operator(*args));
775 if (*args != NULL && *++args != NULL) {
776 /* TODO: example when this happens? */
777 bb_error_msg("%s: unknown operand", *args);
782 // return negate ? !res : res;