- remove most of the forward declarations. No obj-code changes.
[platform/upstream/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
150 #if ENABLE_FEATURE_TEST_64
151 typedef int64_t arith_t;
152 #else
153 typedef int arith_t;
154 #endif
155
156 /* Cannot eliminate these static data (do the G trick)
157  * because of test_main usage from other applets */
158 static char **t_wp;
159 static const struct t_op *t_wp_op;
160 static gid_t *group_array;
161 static int ngroups;
162 static jmp_buf leaving;
163
164 static arith_t primary(enum token n);
165
166 static void syntax(const char *op, const char *msg) ATTRIBUTE_NORETURN;
167 static void syntax(const char *op, const char *msg)
168 {
169         if (op && *op) {
170                 bb_error_msg("%s: %s", op, msg);
171         } else {
172                 bb_error_msg("%s: %s"+4, msg);
173         }
174         longjmp(leaving, 2);
175 }
176
177 /* atoi with error detection */
178 //XXX: FIXME: duplicate of existing libbb function?
179 static arith_t getn(const char *s)
180 {
181         char *p;
182 #if ENABLE_FEATURE_TEST_64
183         long long r;
184 #else
185         long r;
186 #endif
187
188         errno = 0;
189 #if ENABLE_FEATURE_TEST_64
190         r = strtoll(s, &p, 10);
191 #else
192         r = strtol(s, &p, 10);
193 #endif
194
195         if (errno != 0)
196                 syntax(s, "out of range");
197
198         if (*(skip_whitespace(p)))
199                 syntax(s, "bad number");
200
201         return r;
202 }
203
204 /* UNUSED
205 static int newerf(const char *f1, const char *f2)
206 {
207         struct stat b1, b2;
208
209         return (stat(f1, &b1) == 0 &&
210                         stat(f2, &b2) == 0 && b1.st_mtime > b2.st_mtime);
211 }
212
213 static int olderf(const char *f1, const char *f2)
214 {
215         struct stat b1, b2;
216
217         return (stat(f1, &b1) == 0 &&
218                         stat(f2, &b2) == 0 && b1.st_mtime < b2.st_mtime);
219 }
220
221 static int equalf(const char *f1, const char *f2)
222 {
223         struct stat b1, b2;
224
225         return (stat(f1, &b1) == 0 &&
226                         stat(f2, &b2) == 0 &&
227                         b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
228 }
229 */
230
231
232 static enum token t_lex(char *s)
233 {
234         const struct t_op *op;
235
236         t_wp_op = NULL;
237         if (s == NULL) {
238                 return EOI;
239         }
240
241         op = ops;
242         do {
243                 if (strcmp(s, op->op_text) == 0) {
244                         t_wp_op = op;
245                         return op->op_num;
246                 }
247                 op++;
248         } while (op < ops + ARRAY_SIZE(ops));
249
250         return OPERAND;
251 }
252
253
254 static int binop(void)
255 {
256         const char *opnd1, *opnd2;
257         struct t_op const *op;
258         arith_t val1, val2;
259
260         opnd1 = *t_wp;
261         (void) t_lex(*++t_wp);
262         op = t_wp_op;
263
264         opnd2 = *++t_wp;
265         if (opnd2 == NULL)
266                 syntax(op->op_text, "argument expected");
267
268         if (is_int_op(op->op_num)) {
269                 val1 = getn(opnd1);
270                 val2 = getn(opnd2);
271                 if (op->op_num == INTEQ)
272                         return val1 == val2;
273                 if (op->op_num == INTNE)
274                         return val1 != val2;
275                 if (op->op_num == INTGE)
276                         return val1 >= val2;
277                 if (op->op_num == INTGT)
278                         return val1 >  val2;
279                 if (op->op_num == INTLE)
280                         return val1 <= val2;
281                 if (op->op_num == INTLT)
282                         return val1 <  val2;
283         }
284         if (is_str_op(op->op_num)) {
285                 val1 = strcmp(opnd1, opnd2);
286                 if (op->op_num == STREQ)
287                         return val1 == 0;
288                 if (op->op_num == STRNE)
289                         return val1 != 0;
290                 if (op->op_num == STRLT)
291                         return val1 < 0;
292                 if (op->op_num == STRGT)
293                         return val1 > 0;
294         }
295         /* We are sure that these three are by now the only binops we didn't check
296          * yet, so we do not check if the class is correct:
297          */
298 /*      if (is_file_op(op->op_num)) */
299         {
300                 struct stat b1, b2;
301
302                 if (stat(opnd1, &b1) || stat(opnd2, &b2))
303                         return 0; /* false, since at least one stat failed */
304                 if (op->op_num == FILNT)
305                         return b1.st_mtime > b2.st_mtime;
306                 if (op->op_num == FILOT)
307                         return b1.st_mtime < b2.st_mtime;
308                 if (op->op_num == FILEQ)
309                         return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
310         }
311         return 1; /* NOTREACHED */
312 }
313
314
315 static void initialize_group_array(void)
316 {
317         ngroups = getgroups(0, NULL);
318         if (ngroups > 0) {
319                 /* FIXME: ash tries so hard to not die on OOM,
320                  * and we spoil it with just one xrealloc here */
321                 /* We realloc, because test_main can be entered repeatedly by shell.
322                  * Testcase (ash): 'while true; do test -x some_file; done'
323                  * and watch top. (some_file must have owner != you) */
324                 group_array = xrealloc(group_array, ngroups * sizeof(gid_t));
325                 getgroups(ngroups, group_array);
326         }
327 }
328
329
330 /* Return non-zero if GID is one that we have in our groups list. */
331 //XXX: FIXME: duplicate of existing libbb function?
332 // see toplevel TODO file:
333 // possible code duplication ingroup() and is_a_group_member()
334 static int is_a_group_member(gid_t gid)
335 {
336         int i;
337
338         /* Short-circuit if possible, maybe saving a call to getgroups(). */
339         if (gid == getgid() || gid == getegid())
340                 return 1;
341
342         if (ngroups == 0)
343                 initialize_group_array();
344
345         /* Search through the list looking for GID. */
346         for (i = 0; i < ngroups; i++)
347                 if (gid == group_array[i])
348                         return 1;
349
350         return 0;
351 }
352
353
354 /* Do the same thing access(2) does, but use the effective uid and gid,
355    and don't make the mistake of telling root that any file is
356    executable. */
357 static int test_eaccess(char *path, int mode)
358 {
359         struct stat st;
360         unsigned int euid = geteuid();
361
362         if (stat(path, &st) < 0)
363                 return -1;
364
365         if (euid == 0) {
366                 /* Root can read or write any file. */
367                 if (mode != X_OK)
368                         return 0;
369
370                 /* Root can execute any file that has any one of the execute
371                    bits set. */
372                 if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
373                         return 0;
374         }
375
376         if (st.st_uid == euid)  /* owner */
377                 mode <<= 6;
378         else if (is_a_group_member(st.st_gid))
379                 mode <<= 3;
380
381         if (st.st_mode & mode)
382                 return 0;
383
384         return -1;
385 }
386
387
388 static int filstat(char *nm, enum token mode)
389 {
390         struct stat s;
391         int i = i; /* gcc 3.x thinks it can be used uninitialized */
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
461 static arith_t nexpr(enum token n)
462 {
463         if (n == UNOT)
464                 return !nexpr(t_lex(*++t_wp));
465         return primary(n);
466 }
467
468
469 static arith_t aexpr(enum token n)
470 {
471         arith_t res;
472
473         res = nexpr(n);
474         if (t_lex(*++t_wp) == BAND)
475                 return aexpr(t_lex(*++t_wp)) && res;
476         t_wp--;
477         return res;
478 }
479
480
481 static arith_t oexpr(enum token n)
482 {
483         arith_t res;
484
485         res = aexpr(n);
486         if (t_lex(*++t_wp) == BOR) {
487                 return oexpr(t_lex(*++t_wp)) || res;
488         }
489         t_wp--;
490         return res;
491 }
492
493
494
495 static arith_t primary(enum token n)
496 {
497         arith_t res;
498
499         if (n == EOI) {
500                 syntax(NULL, "argument expected");
501         }
502         if (n == LPAREN) {
503                 res = oexpr(t_lex(*++t_wp));
504                 if (t_lex(*++t_wp) != RPAREN)
505                         syntax(NULL, "closing paren expected");
506                 return res;
507         }
508         if (t_wp_op && t_wp_op->op_type == UNOP) {
509                 /* unary expression */
510                 if (*++t_wp == NULL)
511                         syntax(t_wp_op->op_text, "argument expected");
512                 if (n == STREZ)
513                         return t_wp[0][0] == '\0';
514                 if (n == STRNZ)
515                         return t_wp[0][0] != '\0';
516                 if (n == FILTT)
517                         return isatty(getn(*t_wp));
518                 return filstat(*t_wp, n);
519         }
520
521         t_lex(t_wp[1]);
522         if (t_wp_op && t_wp_op->op_type == BINOP) {
523                 return binop();
524         }
525
526         return t_wp[0][0] != '\0';
527 }
528
529
530 int test_main(int argc, char **argv)
531 {
532         int res;
533         const char *arg0;
534         bool _off;
535
536         arg0 = bb_basename(argv[0]);
537         if (arg0[0] == '[') {
538                 --argc;
539                 if (!arg0[1]) { /* "[" ? */
540                         if (NOT_LONE_CHAR(argv[argc], ']')) {
541                                 bb_error_msg("missing ]");
542                                 return 2;
543                         }
544                 } else { /* assuming "[[" */
545                         if (strcmp(argv[argc], "]]") != 0) {
546                                 bb_error_msg("missing ]]");
547                                 return 2;
548                         }
549                 }
550                 argv[argc] = NULL;
551         }
552
553         res = setjmp(leaving);
554         if (res)
555                 return res;
556
557         /* resetting ngroups is probably unnecessary.  it will
558          * force a new call to getgroups(), which prevents using
559          * group data fetched during a previous call.  but the
560          * only way the group data could be stale is if there's
561          * been an intervening call to setgroups(), and this
562          * isn't likely in the case of a shell.  paranoia
563          * prevails...
564          */
565         ngroups = 0;
566
567         /* Implement special cases from POSIX.2, section 4.62.4 */
568         if (argc == 1)
569                 return 1;
570         if (argc == 2)
571                 return *argv[1] == '\0';
572 //assert(argc);
573         /* remember if we saw argc==4 which wants *no* '!' test */
574         _off = argc - 4;
575         if (_off ?
576                 (LONE_CHAR(argv[1], '!'))
577                 : (argv[1][0] != '!' || argv[1][1] != '\0'))
578         {
579                 if (argc == 3)
580                         return *argv[2] != '\0';
581
582                 t_lex(argv[2 + _off]);
583                 if (t_wp_op && t_wp_op->op_type == BINOP) {
584                         t_wp = &argv[1 + _off];
585                         return binop() == _off;
586                 }
587         }
588         t_wp = &argv[1];
589         res = !oexpr(t_lex(*t_wp));
590
591         if (*t_wp != NULL && *++t_wp != NULL) {
592                 bb_error_msg("%s: unknown operand", *t_wp);
593                 return 2;
594         }
595         return res;
596 }