1 /* $NetBSD: test.c,v 1.41 2016/09/05 01:00:07 sevan Exp $ */
4 * test(1); version 7-like -- author Erik Baalbergen
5 * modified by Eric Gisin to be used as built-in.
6 * modified by Arnold Robbins to add SVR3 compatibility
7 * (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket).
8 * modified by J.T. Conklin for NetBSD.
10 * This program is in the Public Domain.
13 #include <sys/cdefs.h>
15 __RCSID("$NetBSD: test.c,v 1.41 2016/09/05 01:00:07 sevan Exp $");
19 #include <sys/types.h>
32 /* test(1) accepts the following grammar:
33 oexpr ::= aexpr | aexpr "-o" oexpr ;
34 aexpr ::= nexpr | nexpr "-a" aexpr ;
35 nexpr ::= primary | "!" primary
36 primary ::= unary-operator operand
37 | operand binary-operator operand
41 unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
42 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
44 binary-operator ::= "="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
46 operand ::= <any legal UNIX file name>
102 short op_num
, op_type
;
105 static const struct t_op cop
[] = {
107 {"(", LPAREN
, PAREN
},
108 {")", RPAREN
, PAREN
},
114 static const struct t_op cop2
[] = {
115 {"!=", STRNE
, BINOP
},
118 static const struct t_op mop3
[] = {
119 {"ef", FILEQ
, BINOP
},
120 {"eq", INTEQ
, BINOP
},
121 {"ge", INTGE
, BINOP
},
122 {"gt", INTGT
, BINOP
},
123 {"le", INTLE
, BINOP
},
124 {"lt", INTLT
, BINOP
},
125 {"ne", INTNE
, BINOP
},
126 {"nt", FILNT
, BINOP
},
127 {"ot", FILOT
, BINOP
},
130 static const struct t_op mop2
[] = {
139 {"e", FILEXIST
,UNOP
},
142 {"h", FILSYM
, UNOP
}, /* for backwards compat */
157 static struct t_op
const *t_wp_op
;
159 __dead
static void syntax(const char *, const char *);
160 static int oexpr(enum token
);
161 static int aexpr(enum token
);
162 static int nexpr(enum token
);
163 static int primary(enum token
);
164 static int binop(void);
165 static int test_access(struct stat
*, mode_t
);
166 static int filstat(char *, enum token
);
167 static enum token
t_lex(char *);
168 static int isoperand(void);
169 static long long getn(const char *);
170 static int newerf(const char *, const char *);
171 static int olderf(const char *, const char *);
172 static int equalf(const char *, const char *);
175 extern void error(const char *, ...) __dead
__printflike(1, 2);
176 extern void *ckmalloc(size_t);
178 static void error(const char *, ...) __dead
__printflike(1, 2);
181 error(const char *msg
, ...)
191 static void *ckmalloc(size_t);
193 ckmalloc(size_t nbytes
)
195 void *p
= malloc(nbytes
);
198 error("Not enough memory!");
204 int testcmd(int, char **);
207 testcmd(int argc
, char **argv
)
210 main(int argc
, char *argv
[])
219 setprogname(argv
[0]);
220 (void)setlocale(LC_ALL
, "");
221 argv0
= getprogname();
223 if (strcmp(argv0
, "[") == 0) {
224 if (strcmp(argv
[--argc
], "]"))
233 res
= !oexpr(t_lex(*t_wp
));
235 if (*t_wp
!= NULL
&& *++t_wp
!= NULL
)
236 syntax(*t_wp
, "unexpected operator");
242 syntax(const char *op
, const char *msg
)
246 error("%s: %s", op
, msg
);
259 if (t_lex(*++t_wp
) == BOR
)
260 return oexpr(t_lex(*++t_wp
)) || res
;
273 if (t_lex(*++t_wp
) == BAND
)
274 return aexpr(t_lex(*++t_wp
)) && res
;
284 return !nexpr(t_lex(*++t_wp
));
289 primary(enum token n
)
295 return 0; /* missing expression */
297 if ((nn
= t_lex(*++t_wp
)) == RPAREN
)
298 return 0; /* missing expression */
300 if (t_lex(*++t_wp
) != RPAREN
)
301 syntax(NULL
, "closing paren expected");
304 if (t_wp_op
&& t_wp_op
->op_type
== UNOP
) {
305 /* unary expression */
307 syntax(t_wp_op
->op_text
, "argument expected");
310 return strlen(*t_wp
) == 0;
312 return strlen(*t_wp
) != 0;
314 return isatty((int)getn(*t_wp
));
316 return filstat(*t_wp
, n
);
320 if (t_lex(t_wp
[1]), t_wp_op
&& t_wp_op
->op_type
== BINOP
) {
324 return strlen(*t_wp
) > 0;
330 const char *opnd1
, *opnd2
;
331 struct t_op
const *op
;
334 (void) t_lex(*++t_wp
);
337 if ((opnd2
= *++t_wp
) == NULL
)
338 syntax(op
->op_text
, "argument expected");
340 switch (op
->op_num
) {
342 return strcmp(opnd1
, opnd2
) == 0;
344 return strcmp(opnd1
, opnd2
) != 0;
346 return strcmp(opnd1
, opnd2
) < 0;
348 return strcmp(opnd1
, opnd2
) > 0;
350 return getn(opnd1
) == getn(opnd2
);
352 return getn(opnd1
) != getn(opnd2
);
354 return getn(opnd1
) >= getn(opnd2
);
356 return getn(opnd1
) > getn(opnd2
);
358 return getn(opnd1
) <= getn(opnd2
);
360 return getn(opnd1
) < getn(opnd2
);
362 return newerf(opnd1
, opnd2
);
364 return olderf(opnd1
, opnd2
);
366 return equalf(opnd1
, opnd2
);
374 * The manual, and IEEE POSIX 1003.2, suggests this should check the mode bits,
377 * True shall indicate only that the write flag is on. The file is not
378 * writable on a read-only file system even if this test indicates true.
380 * Unfortunately IEEE POSIX 1003.1-2001, as quoted in SuSv3, says only:
382 * True shall indicate that permission to read from file will be granted,
383 * as defined in "File Read, Write, and Creation".
385 * and that section says:
387 * When a file is to be read or written, the file shall be opened with an
388 * access mode corresponding to the operation to be performed. If file
389 * access permissions deny access, the requested operation shall fail.
391 * and of course access permissions are described as one might expect:
393 * * If a process has the appropriate privilege:
395 * * If read, write, or directory search permission is requested,
396 * access shall be granted.
398 * * If execute permission is requested, access shall be granted if
399 * execute permission is granted to at least one user by the file
400 * permission bits or by an alternate access control mechanism;
401 * otherwise, access shall be denied.
405 * * The file permission bits of a file contain read, write, and
406 * execute/search permissions for the file owner class, file group
407 * class, and file other class.
409 * * Access shall be granted if an alternate access control mechanism
410 * is not enabled and the requested access permission bit is set for
411 * the class (file owner class, file group class, or file other class)
412 * to which the process belongs, or if an alternate access control
413 * mechanism is enabled and it allows the requested access; otherwise,
414 * access shall be denied.
416 * and when I first read this I thought: surely we can't go about using
417 * open(O_WRONLY) to try this test! However the POSIX 1003.1-2001 Rationale
418 * section for test does in fact say:
420 * On historical BSD systems, test -w directory always returned false
421 * because test tried to open the directory for writing, which always
424 * and indeed this is in fact true for Seventh Edition UNIX, UNIX 32V, and UNIX
425 * System III, and thus presumably also for BSD up to and including 4.3.
427 * Secondly I remembered why using open() and/or access() are bogus. They
428 * don't work right for detecting read and write permissions bits when called
431 * Interestingly the 'test' in 4.4BSD was closer to correct (as per
432 * 1003.2-1992) and it was implemented efficiently with stat() instead of
435 * This was apparently broken in NetBSD around about 1994/06/30 when the old
436 * 4.4BSD implementation was replaced with a (arguably much better coded)
437 * implementation derived from pdksh.
439 * Note that modern pdksh is yet different again, but still not correct, at
440 * least not w.r.t. 1003.2-1992.
442 * As I think more about it and read more of the related IEEE docs I don't like
443 * that wording about 'test -r' and 'test -w' in 1003.1-2001 at all. I very
444 * much prefer the original wording in 1003.2-1992. It is much more useful,
445 * and so that's what I've implemented.
447 * (Note that a strictly conforming implementation of 1003.1-2001 is in fact
448 * totally useless for the case in question since its 'test -w' and 'test -r'
449 * can never fail for root for any existing files, i.e. files for which 'test
452 * The rationale for 1003.1-2001 suggests that the wording was "clarified" in
453 * 1003.1-2001 to align with the 1003.2b draft. 1003.2b Draft 12 (July 1999),
454 * which is the latest copy I have, does carry the same suggested wording as is
455 * in 1003.1-2001, with its rationale saying:
457 * This change is a clarification and is the result of interpretation
458 * request PASC 1003.2-92 #23 submitted for IEEE Std 1003.2-1992.
460 * That interpretation can be found here:
462 * http://www.pasc.org/interps/unofficial/db/p1003.2/pasc-1003.2-23.html
464 * Not terribly helpful, unfortunately. I wonder who that fence sitter was.
466 * Worse, IMVNSHO, I think the authors of 1003.2b-D12 have mis-interpreted the
467 * PASC interpretation and appear to be gone against at least one widely used
468 * implementation (namely 4.4BSD). The problem is that for file access by root
469 * this means that if test '-r' and '-w' are to behave as if open() were called
470 * then there's no way for a shell script running as root to check if a file
471 * has certain access bits set other than by the grotty means of interpreting
472 * the output of 'ls -l'. This was widely considered to be a bug in V7's
473 * "test" and is, I believe, one of the reasons why direct use of access() was
474 * avoided in some more recent implementations!
476 * I have always interpreted '-r' to match '-w' and '-x' as per the original
477 * wording in 1003.2-1992, not the other way around. I think 1003.2b goes much
478 * too far the wrong way without any valid rationale and that it's best if we
479 * stick with 1003.2-1992 and test the flags, and not mimic the behaviour of
480 * open() since we already know very well how it will work -- existance of the
481 * file is all that matters to open() for root.
483 * Unfortunately the SVID is no help at all (which is, I guess, partly why
484 * we're in this mess in the first place :-).
486 * The SysV implementation (at least in the 'test' builtin in /bin/sh) does use
487 * access(name, 2) even though it also goes to much greater lengths for '-x'
488 * matching the 1003.2-1992 definition (which is no doubt where that definition
491 * The ksh93 implementation uses access() for '-r' and '-w' if
492 * (euid==uid&&egid==gid), but uses st_mode for '-x' iff running as root.
493 * i.e. it does strictly conform to 1003.1-2001 (and presumably 1003.2b).
496 test_access(struct stat
*sp
, mode_t stmode
)
504 * I suppose we could use access() if not running as root and if we are
505 * running with ((euid == uid) && (egid == gid)), but we've already
506 * done the stat() so we might as well just test the permissions
507 * directly instead of asking the kernel to do it....
510 if (euid
== 0) /* any bit is good enough */
511 stmode
= (stmode
<< 6) | (stmode
<< 3) | stmode
;
512 else if (sp
->st_uid
== euid
)
514 else if (sp
->st_gid
== getegid())
517 /* XXX stolen almost verbatim from ksh93.... */
518 /* on some systems you can be in several groups */
519 if ((maxgroups
= getgroups(0, NULL
)) <= 0)
520 maxgroups
= NGROUPS_MAX
; /* pre-POSIX system? */
521 groups
= ckmalloc((maxgroups
+ 1) * sizeof(gid_t
));
522 n
= getgroups(maxgroups
, groups
);
524 if (groups
[n
] == sp
->st_gid
) {
532 return sp
->st_mode
& stmode
;
536 filstat(char *nm
, enum token mode
)
540 if (mode
== FILSYM
? lstat(nm
, &s
) : stat(nm
, &s
))
545 return test_access(&s
, S_IROTH
);
547 return test_access(&s
, S_IWOTH
);
549 return test_access(&s
, S_IXOTH
);
551 return 1; /* the successful lstat()/stat() is good enough */
553 return S_ISREG(s
.st_mode
);
555 return S_ISDIR(s
.st_mode
);
557 return S_ISCHR(s
.st_mode
);
559 return S_ISBLK(s
.st_mode
);
561 return S_ISFIFO(s
.st_mode
);
563 return S_ISSOCK(s
.st_mode
);
565 return S_ISLNK(s
.st_mode
);
567 return (s
.st_mode
& S_ISUID
) != 0;
569 return (s
.st_mode
& S_ISGID
) != 0;
571 return (s
.st_mode
& S_ISVTX
) != 0;
573 return s
.st_size
> (off_t
)0;
575 return s
.st_uid
== geteuid();
577 return s
.st_gid
== getegid();
583 #define VTOC(x) (const unsigned char *)((const struct t_op *)x)->op_text
586 compare1(const void *va
, const void *vb
)
588 const unsigned char *a
= va
;
589 const unsigned char *b
= VTOC(vb
);
595 compare2(const void *va
, const void *vb
)
597 const unsigned char *a
= va
;
598 const unsigned char *b
= VTOC(vb
);
601 return z
? z
: (a
[1] - b
[1]);
604 static struct t_op
const *
605 findop(const char *s
)
611 return bsearch(s
+ 1, mop2
, __arraycount(mop2
),
612 sizeof(*mop2
), compare1
);
613 else if (s
[3] != '\0')
616 return bsearch(s
+ 1, mop3
, __arraycount(mop3
),
617 sizeof(*mop3
), compare2
);
620 return bsearch(s
, cop
, __arraycount(cop
), sizeof(*cop
),
622 else if (strcmp(s
, cop2
[0].op_text
) == 0)
632 struct t_op
const *op
;
639 if ((op
= findop(s
)) != NULL
) {
640 if (!((op
->op_type
== UNOP
&& isoperand()) ||
641 (op
->op_num
== LPAREN
&& *(t_wp
+1) == 0))) {
653 struct t_op
const *op
;
656 if ((s
= *(t_wp
+1)) == 0)
658 if ((t
= *(t_wp
+2)) == 0)
660 if ((op
= findop(s
)) != NULL
)
661 return op
->op_type
== BINOP
&& (t
[0] != ')' || t
[1] != '\0');
665 /* atoi with error detection */
673 r
= strtoll(s
, &p
, 10);
676 if (errno
== ERANGE
&& (r
== LLONG_MAX
|| r
== LLONG_MIN
))
677 error("%s: out of range", s
);
679 while (isspace((unsigned char)*p
))
683 error("%s: bad number", s
);
689 newerf(const char *f1
, const char *f2
)
693 return (stat(f1
, &b1
) == 0 &&
694 stat(f2
, &b2
) == 0 &&
695 timespeccmp(&b1
.st_mtim
, &b2
.st_mtim
, >));
699 olderf(const char *f1
, const char *f2
)
703 return (stat(f1
, &b1
) == 0 &&
704 stat(f2
, &b2
) == 0 &&
705 timespeccmp(&b1
.st_mtim
, &b2
.st_mtim
, <));
709 equalf(const char *f1
, const char *f2
)
713 return (stat(f1
, &b1
) == 0 &&
714 stat(f2
, &b2
) == 0 &&
715 b1
.st_dev
== b2
.st_dev
&&
716 b1
.st_ino
== b2
.st_ino
);