3796e2cd2b7f55039b7f877ec83eac0d4b8aa05b
[oweals/busybox.git] / coreutils / test.c
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 Fischer to be useable (i.e. a bit less bloaty).
16  *
17  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
18  *
19  * Original copyright notice states:
20  *     "This program is in the Public Domain."
21  */
22
23 #include "libbb.h"
24 #include <setjmp.h>
25
26 /* This is a NOEXEC applet. Be very careful! */
27
28
29 /* test(1) accepts the following grammar:
30         oexpr   ::= aexpr | aexpr "-o" oexpr ;
31         aexpr   ::= nexpr | nexpr "-a" aexpr ;
32         nexpr   ::= primary | "!" primary
33         primary ::= unary-operator operand
34                 | operand binary-operator operand
35                 | operand
36                 | "(" oexpr ")"
37                 ;
38         unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
39                 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
40
41         binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
42                         "-nt"|"-ot"|"-ef";
43         operand ::= <any legal UNIX file name>
44 */
45
46 enum token {
47         EOI,
48         FILRD,
49         FILWR,
50         FILEX,
51         FILEXIST,
52         FILREG,
53         FILDIR,
54         FILCDEV,
55         FILBDEV,
56         FILFIFO,
57         FILSOCK,
58         FILSYM,
59         FILGZ,
60         FILTT,
61         FILSUID,
62         FILSGID,
63         FILSTCK,
64         FILNT,
65         FILOT,
66         FILEQ,
67         FILUID,
68         FILGID,
69         STREZ,
70         STRNZ,
71         STREQ,
72         STRNE,
73         STRLT,
74         STRGT,
75         INTEQ,
76         INTNE,
77         INTGE,
78         INTGT,
79         INTLE,
80         INTLT,
81         UNOT,
82         BAND,
83         BOR,
84         LPAREN,
85         RPAREN,
86         OPERAND
87 };
88 #define is_int_op(a) (((unsigned char)((a) - INTEQ)) <= 5)
89 #define is_str_op(a) (((unsigned char)((a) - STREZ)) <= 5)
90 #define is_file_op(a) (((unsigned char)((a) - FILNT)) <= 2)
91 #define is_file_access(a) (((unsigned char)((a) - FILRD)) <= 2)
92 #define is_file_type(a) (((unsigned char)((a) - FILREG)) <= 5)
93 #define is_file_bit(a) (((unsigned char)((a) - FILSUID)) <= 2)
94 enum token_types {
95         UNOP,
96         BINOP,
97         BUNOP,
98         BBINOP,
99         PAREN
100 };
101
102 static const struct t_op {
103         char op_text[4];
104         unsigned char op_num, op_type;
105 } ops[] = {
106         { "-r", FILRD   , UNOP   },
107         { "-w", FILWR   , UNOP   },
108         { "-x", FILEX   , UNOP   },
109         { "-e", FILEXIST, UNOP   },
110         { "-f", FILREG  , UNOP   },
111         { "-d", FILDIR  , UNOP   },
112         { "-c", FILCDEV , UNOP   },
113         { "-b", FILBDEV , UNOP   },
114         { "-p", FILFIFO , UNOP   },
115         { "-u", FILSUID , UNOP   },
116         { "-g", FILSGID , UNOP   },
117         { "-k", FILSTCK , UNOP   },
118         { "-s", FILGZ   , UNOP   },
119         { "-t", FILTT   , UNOP   },
120         { "-z", STREZ   , UNOP   },
121         { "-n", STRNZ   , UNOP   },
122         { "-h", FILSYM  , UNOP   },    /* for backwards compat */
123
124         { "-O" , FILUID , UNOP   },
125         { "-G" , FILGID , UNOP   },
126         { "-L" , FILSYM , UNOP   },
127         { "-S" , FILSOCK, UNOP   },
128         { "="  , STREQ  , BINOP  },
129         { "==" , STREQ  , BINOP  },
130         { "!=" , STRNE  , BINOP  },
131         { "<"  , STRLT  , BINOP  },
132         { ">"  , STRGT  , BINOP  },
133         { "-eq", INTEQ  , BINOP  },
134         { "-ne", INTNE  , BINOP  },
135         { "-ge", INTGE  , BINOP  },
136         { "-gt", INTGT  , BINOP  },
137         { "-le", INTLE  , BINOP  },
138         { "-lt", INTLT  , BINOP  },
139         { "-nt", FILNT  , BINOP  },
140         { "-ot", FILOT  , BINOP  },
141         { "-ef", FILEQ  , BINOP  },
142         { "!"  , UNOT   , BUNOP  },
143         { "-a" , BAND   , BBINOP },
144         { "-o" , BOR    , BBINOP },
145         { "("  , LPAREN , PAREN  },
146         { ")"  , RPAREN , PAREN  },
147 };
148
149 enum { NUM_OPS = sizeof(ops) / sizeof(ops[0]) };
150
151 #if ENABLE_FEATURE_TEST_64
152 typedef int64_t arith_t;
153 #else
154 typedef int arith_t;
155 #endif
156
157 /* Cannot eliminate these static data (do the G trick)
158  * because of bb_test usage from other applets */
159 static char **t_wp;
160 static struct t_op const *t_wp_op;
161 static gid_t *group_array;
162 static int ngroups;
163 static jmp_buf leaving;
164
165 static enum token t_lex(char *s);
166 static arith_t oexpr(enum token n);
167 static arith_t aexpr(enum token n);
168 static arith_t nexpr(enum token n);
169 static int binop(void);
170 static arith_t primary(enum token n);
171 static int filstat(char *nm, enum token mode);
172 static arith_t getn(const char *s);
173 /* UNUSED
174 static int newerf(const char *f1, const char *f2);
175 static int olderf(const char *f1, const char *f2);
176 static int equalf(const char *f1, const char *f2);
177 */
178 static int test_eaccess(char *path, int mode);
179 static int is_a_group_member(gid_t gid);
180 static void initialize_group_array(void);
181
182 int bb_test(int argc, char **argv)
183 {
184         int res;
185         char *arg0;
186         bool _off;
187
188         arg0 = strrchr(argv[0], '/');
189         if (!arg0++) arg0 = argv[0];
190         if (arg0[0] == '[') {
191                 if (!arg0[1]) { /* "[" ? */
192                         --argc;
193                         if (NOT_LONE_CHAR(argv[argc], ']')) {
194                                 bb_error_msg("missing ]");
195                                 return 2;
196                         }
197                         argv[argc] = NULL;
198                 } else if (LONE_CHAR(arg0+1, '[') == 0) { /* "[[" ? */
199                         --argc;
200                         if (strcmp(argv[argc], "]]") != 0) {
201                                 bb_error_msg("missing ]]");
202                                 return 2;
203                         }
204                         argv[argc] = NULL;
205                 }
206         }
207
208         res = setjmp(leaving);
209         if (res)
210                 return res;
211
212         /* resetting ngroups is probably unnecessary.  it will
213          * force a new call to getgroups(), which prevents using
214          * group data fetched during a previous call.  but the
215          * only way the group data could be stale is if there's
216          * been an intervening call to setgroups(), and this
217          * isn't likely in the case of a shell.  paranoia
218          * prevails...
219          */
220         ngroups = 0;
221
222         /* Implement special cases from POSIX.2, section 4.62.4 */
223         if (argc == 1)
224                 return 1;
225         if (argc == 2)
226                 return *argv[1] == '\0';
227 //assert(argc);
228         /* remember if we saw argc==4 which wants *no* '!' test */
229         _off = argc - 4;
230         if (_off ?
231                 (LONE_CHAR(argv[1], '!'))
232                 : (argv[1][0] != '!' || argv[1][1] != '\0'))
233         {
234                 if (argc == 3)
235                         return *argv[2] != '\0';
236
237                 t_lex(argv[2 + _off]);
238                 if (t_wp_op && t_wp_op->op_type == BINOP) {
239                         t_wp = &argv[1 + _off];
240                         return binop() == _off;
241                 }
242         }
243         t_wp = &argv[1];
244         res = !oexpr(t_lex(*t_wp));
245
246         if (*t_wp != NULL && *++t_wp != NULL) {
247                 bb_error_msg("%s: unknown operand", *t_wp);
248                 return 2;
249         }
250         return res;
251 }
252
253 static void syntax(const char *op, const char *msg) ATTRIBUTE_NORETURN;
254 static void syntax(const char *op, const char *msg)
255 {
256         if (op && *op) {
257                 bb_error_msg("%s: %s", op, msg);
258         } else {
259                 bb_error_msg("%s: %s"+4, msg);
260         }
261         longjmp(leaving, 2);
262 }
263
264 static arith_t oexpr(enum token n)
265 {
266         arith_t res;
267
268         res = aexpr(n);
269         if (t_lex(*++t_wp) == BOR) {
270                 return oexpr(t_lex(*++t_wp)) || res;
271         }
272         t_wp--;
273         return res;
274 }
275
276 static arith_t aexpr(enum token n)
277 {
278         arith_t res;
279
280         res = nexpr(n);
281         if (t_lex(*++t_wp) == BAND)
282                 return aexpr(t_lex(*++t_wp)) && res;
283         t_wp--;
284         return res;
285 }
286
287 static arith_t nexpr(enum token n)
288 {
289         if (n == UNOT)
290                 return !nexpr(t_lex(*++t_wp));
291         return primary(n);
292 }
293
294 static arith_t primary(enum token n)
295 {
296         arith_t res;
297
298         if (n == EOI) {
299                 syntax(NULL, "argument expected");
300         }
301         if (n == LPAREN) {
302                 res = oexpr(t_lex(*++t_wp));
303                 if (t_lex(*++t_wp) != RPAREN)
304                         syntax(NULL, "closing paren expected");
305                 return res;
306         }
307         if (t_wp_op && t_wp_op->op_type == UNOP) {
308                 /* unary expression */
309                 if (*++t_wp == NULL)
310                         syntax(t_wp_op->op_text, "argument expected");
311                 if (n == STREZ)
312                         return t_wp[0][0] == '\0';
313                 if (n == STRNZ)
314                         return t_wp[0][0] != '\0';
315                 if (n == FILTT)
316                         return isatty(getn(*t_wp));
317                 return filstat(*t_wp, n);
318         }
319
320         t_lex(t_wp[1]);
321         if (t_wp_op && t_wp_op->op_type == BINOP) {
322                 return binop();
323         }
324
325         return t_wp[0][0] != '\0';
326 }
327
328 static int binop(void)
329 {
330         const char *opnd1, *opnd2;
331         struct t_op const *op;
332         arith_t val1, val2;
333
334         opnd1 = *t_wp;
335         (void) t_lex(*++t_wp);
336         op = t_wp_op;
337
338         opnd2 = *++t_wp;
339         if (opnd2 == NULL)
340                 syntax(op->op_text, "argument expected");
341
342         if (is_int_op(op->op_num)) {
343                 val1 = getn(opnd1);
344                 val2 = getn(opnd2);
345                 if (op->op_num == INTEQ)
346                         return val1 == val2;
347                 if (op->op_num == INTNE)
348                         return val1 != val2;
349                 if (op->op_num == INTGE)
350                         return val1 >= val2;
351                 if (op->op_num == INTGT)
352                         return val1 >  val2;
353                 if (op->op_num == INTLE)
354                         return val1 <= val2;
355                 if (op->op_num == INTLT)
356                         return val1 <  val2;
357         }
358         if (is_str_op(op->op_num)) {
359                 val1 = strcmp(opnd1, opnd2);
360                 if (op->op_num == STREQ)
361                         return val1 == 0;
362                 if (op->op_num == STRNE)
363                         return val1 != 0;
364                 if (op->op_num == STRLT)
365                         return val1 < 0;
366                 if (op->op_num == STRGT)
367                         return val1 > 0;
368         }
369         /* We are sure that these three are by now the only binops we didn't check
370          * yet, so we do not check if the class is correct:
371          */
372 /*      if (is_file_op(op->op_num)) */
373         {
374                 struct stat b1, b2;
375
376                 if (stat(opnd1, &b1) || stat(opnd2, &b2))
377                         return 0; /* false, since at least one stat failed */
378                 if (op->op_num == FILNT)
379                         return b1.st_mtime > b2.st_mtime;
380                 if (op->op_num == FILOT)
381                         return b1.st_mtime < b2.st_mtime;
382                 if (op->op_num == FILEQ)
383                         return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
384         }
385         return 1; /* NOTREACHED */
386 }
387
388 static int filstat(char *nm, enum token mode)
389 {
390         struct stat s;
391         int i;
392
393         if (mode == FILSYM) {
394 #ifdef S_IFLNK
395                 if (lstat(nm, &s) == 0) {
396                         i = S_IFLNK;
397                         goto filetype;
398                 }
399 #endif
400                 return 0;
401         }
402
403         if (stat(nm, &s) != 0)
404                 return 0;
405         if (mode == FILEXIST)
406                 return 1;
407         if (is_file_access(mode)) {
408                 if (mode == FILRD)
409                         i = R_OK;
410                 if (mode == FILWR)
411                         i = W_OK;
412                 if (mode == FILEX)
413                         i = X_OK;
414                 return test_eaccess(nm, i) == 0;
415         }
416         if (is_file_type(mode)) {
417                 if (mode == FILREG)
418                         i = S_IFREG;
419                 if (mode == FILDIR)
420                         i = S_IFDIR;
421                 if (mode == FILCDEV)
422                         i = S_IFCHR;
423                 if (mode == FILBDEV)
424                         i = S_IFBLK;
425                 if (mode == FILFIFO) {
426 #ifdef S_IFIFO
427                         i = S_IFIFO;
428 #else
429                         return 0;
430 #endif
431                 }
432                 if (mode == FILSOCK) {
433 #ifdef S_IFSOCK
434                         i = S_IFSOCK;
435 #else
436                         return 0;
437 #endif
438                 }
439  filetype:
440                 return ((s.st_mode & S_IFMT) == i);
441         }
442         if (is_file_bit(mode)) {
443                 if (mode == FILSUID)
444                         i = S_ISUID;
445                 if (mode == FILSGID)
446                         i = S_ISGID;
447                 if (mode == FILSTCK)
448                         i = S_ISVTX;
449                 return ((s.st_mode & i) != 0);
450         }
451         if (mode == FILGZ)
452                 return s.st_size > 0L;
453         if (mode == FILUID)
454                 return s.st_uid == geteuid();
455         if (mode == FILGID)
456                 return s.st_gid == getegid();
457         return 1; /* NOTREACHED */
458 }
459
460 static enum token t_lex(char *s)
461 {
462         const struct t_op *op;
463
464         t_wp_op = NULL;
465         if (s == NULL) {
466                 return EOI;
467         }
468
469         op = ops;
470         do {
471                 if (strcmp(s, op->op_text) == 0) {
472                         t_wp_op = op;
473                         return op->op_num;
474                 }
475                 op++;
476         } while (op < ops + NUM_OPS);
477
478         return OPERAND;
479 }
480
481 /* atoi with error detection */
482 //XXX: FIXME: duplicate of existing libbb function?
483 static arith_t getn(const char *s)
484 {
485         char *p;
486 #if ENABLE_FEATURE_TEST_64
487         long long r;
488 #else
489         long r;
490 #endif
491
492         errno = 0;
493 #if ENABLE_FEATURE_TEST_64
494         r = strtoll(s, &p, 10);
495 #else
496         r = strtol(s, &p, 10);
497 #endif
498
499         if (errno != 0)
500                 syntax(s, "out of range");
501
502         if (*(skip_whitespace(p)))
503                 syntax(s, "bad number");
504
505         return r;
506 }
507
508 /* UNUSED
509 static int newerf(const char *f1, const char *f2)
510 {
511         struct stat b1, b2;
512
513         return (stat(f1, &b1) == 0 &&
514                         stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
515 }
516
517 static int olderf(const char *f1, const char *f2)
518 {
519         struct stat b1, b2;
520
521         return (stat(f1, &b1) == 0 &&
522                         stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
523 }
524
525 static int equalf(const char *f1, const char *f2)
526 {
527         struct stat b1, b2;
528
529         return (stat(f1, &b1) == 0 &&
530                         stat(f2, &b2) == 0 &&
531                         b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
532 }
533 */
534
535 /* Do the same thing access(2) does, but use the effective uid and gid,
536    and don't make the mistake of telling root that any file is
537    executable. */
538 static int test_eaccess(char *path, int mode)
539 {
540         struct stat st;
541         unsigned int euid = geteuid();
542
543         if (stat(path, &st) < 0)
544                 return -1;
545
546         if (euid == 0) {
547                 /* Root can read or write any file. */
548                 if (mode != X_OK)
549                         return 0;
550
551                 /* Root can execute any file that has any one of the execute
552                    bits set. */
553                 if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
554                         return 0;
555         }
556
557         if (st.st_uid == euid)  /* owner */
558                 mode <<= 6;
559         else if (is_a_group_member(st.st_gid))
560                 mode <<= 3;
561
562         if (st.st_mode & mode)
563                 return 0;
564
565         return -1;
566 }
567
568 static void initialize_group_array(void)
569 {
570         ngroups = getgroups(0, NULL);
571         if (ngroups > 0) {
572                 /* FIXME: ash tries so hard to not die on OOM,
573                  * and we spoil it with just one xrealloc here */
574                 /* We realloc, because bb_test can be entered repeatedly by shell.
575                  * Testcase (ash): 'while true; do test -x some_file; done'
576                  * and watch top. (some_file must have owner != you) */
577                 group_array = xrealloc(group_array, ngroups * sizeof(gid_t));
578                 getgroups(ngroups, group_array);
579         }
580 }
581
582 /* Return non-zero if GID is one that we have in our groups list. */
583 //XXX: FIXME: duplicate of existing libbb function?
584 // see toplevel TODO file:
585 // possible code duplication ingroup() and is_a_group_member()
586 static int is_a_group_member(gid_t gid)
587 {
588         int i;
589
590         /* Short-circuit if possible, maybe saving a call to getgroups(). */
591         if (gid == getgid() || gid == getegid())
592                 return 1;
593
594         if (ngroups == 0)
595                 initialize_group_array();
596
597         /* Search through the list looking for GID. */
598         for (i = 0; i < ngroups; i++)
599                 if (gid == group_array[i])
600                         return 1;
601
602         return 0;
603 }
604
605
606 /* applet entry point */
607
608 int test_main(int argc, char **argv);
609 int test_main(int argc, char **argv)
610 {
611         return bb_test(argc, argv);
612 }