1 /* $NetBSD: test.c,v 1.36 2008/06/20 23:29:36 christos 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.36 2008/06/20 23:29:36 christos 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 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
;
176 extern void *ckmalloc(size_t);
178 static void error(const char *, ...) __dead
;
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
)
209 int main(int, char *[]);
212 main(int argc
, char *argv
[])
221 setprogname(argv
[0]);
222 (void)setlocale(LC_ALL
, "");
223 argv0
= getprogname();
225 if (strcmp(argv0
, "[") == 0) {
226 if (strcmp(argv
[--argc
], "]"))
235 res
= !oexpr(t_lex(*t_wp
));
237 if (*t_wp
!= NULL
&& *++t_wp
!= NULL
)
238 syntax(*t_wp
, "unexpected operator");
244 syntax(const char *op
, const char *msg
)
248 error("%s: %s", op
, msg
);
261 if (t_lex(*++t_wp
) == BOR
)
262 return oexpr(t_lex(*++t_wp
)) || res
;
275 if (t_lex(*++t_wp
) == BAND
)
276 return aexpr(t_lex(*++t_wp
)) && res
;
286 return !nexpr(t_lex(*++t_wp
));
291 primary(enum token n
)
297 return 0; /* missing expression */
299 if ((nn
= t_lex(*++t_wp
)) == RPAREN
)
300 return 0; /* missing expression */
302 if (t_lex(*++t_wp
) != RPAREN
)
303 syntax(NULL
, "closing paren expected");
306 if (t_wp_op
&& t_wp_op
->op_type
== UNOP
) {
307 /* unary expression */
309 syntax(t_wp_op
->op_text
, "argument expected");
312 return strlen(*t_wp
) == 0;
314 return strlen(*t_wp
) != 0;
316 return isatty((int)getn(*t_wp
));
318 return filstat(*t_wp
, n
);
322 if (t_lex(t_wp
[1]), t_wp_op
&& t_wp_op
->op_type
== BINOP
) {
326 return strlen(*t_wp
) > 0;
332 const char *opnd1
, *opnd2
;
333 struct t_op
const *op
;
336 (void) t_lex(*++t_wp
);
339 if ((opnd2
= *++t_wp
) == NULL
)
340 syntax(op
->op_text
, "argument expected");
342 switch (op
->op_num
) {
344 return strcmp(opnd1
, opnd2
) == 0;
346 return strcmp(opnd1
, opnd2
) != 0;
348 return strcmp(opnd1
, opnd2
) < 0;
350 return strcmp(opnd1
, opnd2
) > 0;
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 getn(opnd1
) < getn(opnd2
);
364 return newerf(opnd1
, opnd2
);
366 return olderf(opnd1
, opnd2
);
368 return equalf(opnd1
, opnd2
);
376 * The manual, and IEEE POSIX 1003.2, suggests this should check the mode bits,
379 * True shall indicate only that the write flag is on. The file is not
380 * writable on a read-only file system even if this test indicates true.
382 * Unfortunately IEEE POSIX 1003.1-2001, as quoted in SuSv3, says only:
384 * True shall indicate that permission to read from file will be granted,
385 * as defined in "File Read, Write, and Creation".
387 * and that section says:
389 * When a file is to be read or written, the file shall be opened with an
390 * access mode corresponding to the operation to be performed. If file
391 * access permissions deny access, the requested operation shall fail.
393 * and of course access permissions are described as one might expect:
395 * * If a process has the appropriate privilege:
397 * * If read, write, or directory search permission is requested,
398 * access shall be granted.
400 * * If execute permission is requested, access shall be granted if
401 * execute permission is granted to at least one user by the file
402 * permission bits or by an alternate access control mechanism;
403 * otherwise, access shall be denied.
407 * * The file permission bits of a file contain read, write, and
408 * execute/search permissions for the file owner class, file group
409 * class, and file other class.
411 * * Access shall be granted if an alternate access control mechanism
412 * is not enabled and the requested access permission bit is set for
413 * the class (file owner class, file group class, or file other class)
414 * to which the process belongs, or if an alternate access control
415 * mechanism is enabled and it allows the requested access; otherwise,
416 * access shall be denied.
418 * and when I first read this I thought: surely we can't go about using
419 * open(O_WRONLY) to try this test! However the POSIX 1003.1-2001 Rationale
420 * section for test does in fact say:
422 * On historical BSD systems, test -w directory always returned false
423 * because test tried to open the directory for writing, which always
426 * and indeed this is in fact true for Seventh Edition UNIX, UNIX 32V, and UNIX
427 * System III, and thus presumably also for BSD up to and including 4.3.
429 * Secondly I remembered why using open() and/or access() are bogus. They
430 * don't work right for detecting read and write permissions bits when called
433 * Interestingly the 'test' in 4.4BSD was closer to correct (as per
434 * 1003.2-1992) and it was implemented efficiently with stat() instead of
437 * This was apparently broken in NetBSD around about 1994/06/30 when the old
438 * 4.4BSD implementation was replaced with a (arguably much better coded)
439 * implementation derived from pdksh.
441 * Note that modern pdksh is yet different again, but still not correct, at
442 * least not w.r.t. 1003.2-1992.
444 * As I think more about it and read more of the related IEEE docs I don't like
445 * that wording about 'test -r' and 'test -w' in 1003.1-2001 at all. I very
446 * much prefer the original wording in 1003.2-1992. It is much more useful,
447 * and so that's what I've implemented.
449 * (Note that a strictly conforming implementation of 1003.1-2001 is in fact
450 * totally useless for the case in question since its 'test -w' and 'test -r'
451 * can never fail for root for any existing files, i.e. files for which 'test
454 * The rationale for 1003.1-2001 suggests that the wording was "clarified" in
455 * 1003.1-2001 to align with the 1003.2b draft. 1003.2b Draft 12 (July 1999),
456 * which is the latest copy I have, does carry the same suggested wording as is
457 * in 1003.1-2001, with its rationale saying:
459 * This change is a clarification and is the result of interpretation
460 * request PASC 1003.2-92 #23 submitted for IEEE Std 1003.2-1992.
462 * That interpretation can be found here:
464 * http://www.pasc.org/interps/unofficial/db/p1003.2/pasc-1003.2-23.html
466 * Not terribly helpful, unfortunately. I wonder who that fence sitter was.
468 * Worse, IMVNSHO, I think the authors of 1003.2b-D12 have mis-interpreted the
469 * PASC interpretation and appear to be gone against at least one widely used
470 * implementation (namely 4.4BSD). The problem is that for file access by root
471 * this means that if test '-r' and '-w' are to behave as if open() were called
472 * then there's no way for a shell script running as root to check if a file
473 * has certain access bits set other than by the grotty means of interpreting
474 * the output of 'ls -l'. This was widely considered to be a bug in V7's
475 * "test" and is, I believe, one of the reasons why direct use of access() was
476 * avoided in some more recent implementations!
478 * I have always interpreted '-r' to match '-w' and '-x' as per the original
479 * wording in 1003.2-1992, not the other way around. I think 1003.2b goes much
480 * too far the wrong way without any valid rationale and that it's best if we
481 * stick with 1003.2-1992 and test the flags, and not mimic the behaviour of
482 * open() since we already know very well how it will work -- existance of the
483 * file is all that matters to open() for root.
485 * Unfortunately the SVID is no help at all (which is, I guess, partly why
486 * we're in this mess in the first place :-).
488 * The SysV implementation (at least in the 'test' builtin in /bin/sh) does use
489 * access(name, 2) even though it also goes to much greater lengths for '-x'
490 * matching the 1003.2-1992 definition (which is no doubt where that definition
493 * The ksh93 implementation uses access() for '-r' and '-w' if
494 * (euid==uid&&egid==gid), but uses st_mode for '-x' iff running as root.
495 * i.e. it does strictly conform to 1003.1-2001 (and presumably 1003.2b).
498 test_access(struct stat
*sp
, mode_t stmode
)
506 * I suppose we could use access() if not running as root and if we are
507 * running with ((euid == uid) && (egid == gid)), but we've already
508 * done the stat() so we might as well just test the permissions
509 * directly instead of asking the kernel to do it....
512 if (euid
== 0) /* any bit is good enough */
513 stmode
= (stmode
<< 6) | (stmode
<< 3) | stmode
;
514 else if (sp
->st_uid
== euid
)
516 else if (sp
->st_gid
== getegid())
519 /* XXX stolen almost verbatim from ksh93.... */
520 /* on some systems you can be in several groups */
521 if ((maxgroups
= getgroups(0, NULL
)) <= 0)
522 maxgroups
= NGROUPS_MAX
; /* pre-POSIX system? */
523 groups
= ckmalloc((maxgroups
+ 1) * sizeof(gid_t
));
524 n
= getgroups(maxgroups
, groups
);
526 if (groups
[n
] == sp
->st_gid
) {
534 return sp
->st_mode
& stmode
;
538 filstat(char *nm
, enum token mode
)
542 if (mode
== FILSYM
? lstat(nm
, &s
) : stat(nm
, &s
))
547 return test_access(&s
, S_IROTH
);
549 return test_access(&s
, S_IWOTH
);
551 return test_access(&s
, S_IXOTH
);
553 return 1; /* the successful lstat()/stat() is good enough */
555 return S_ISREG(s
.st_mode
);
557 return S_ISDIR(s
.st_mode
);
559 return S_ISCHR(s
.st_mode
);
561 return S_ISBLK(s
.st_mode
);
563 return S_ISFIFO(s
.st_mode
);
565 return S_ISSOCK(s
.st_mode
);
567 return S_ISLNK(s
.st_mode
);
569 return (s
.st_mode
& S_ISUID
) != 0;
571 return (s
.st_mode
& S_ISGID
) != 0;
573 return (s
.st_mode
& S_ISVTX
) != 0;
575 return s
.st_size
> (off_t
)0;
577 return s
.st_uid
== geteuid();
579 return s
.st_gid
== getegid();
585 #define VTOC(x) (const unsigned char *)((const struct t_op *)x)->op_text
588 compare1(const void *va
, const void *vb
)
590 const unsigned char *a
= va
;
591 const unsigned char *b
= VTOC(vb
);
597 compare2(const void *va
, const void *vb
)
599 const unsigned char *a
= va
;
600 const unsigned char *b
= VTOC(vb
);
603 return z
? z
: (a
[1] - b
[1]);
606 static struct t_op
const *
607 findop(const char *s
)
613 return bsearch(s
+ 1, mop2
, __arraycount(mop2
),
614 sizeof(*mop2
), compare1
);
615 else if (s
[3] != '\0')
618 return bsearch(s
+ 1, mop3
, __arraycount(mop3
),
619 sizeof(*mop3
), compare2
);
622 return bsearch(s
, cop
, __arraycount(cop
), sizeof(*cop
),
624 else if (strcmp(s
, cop2
[0].op_text
) == 0)
634 struct t_op
const *op
;
641 if ((op
= findop(s
)) != NULL
) {
642 if (!((op
->op_type
== UNOP
&& isoperand()) ||
643 (op
->op_num
== LPAREN
&& *(t_wp
+1) == 0))) {
655 struct t_op
const *op
;
658 if ((s
= *(t_wp
+1)) == 0)
660 if ((t
= *(t_wp
+2)) == 0)
662 if ((op
= findop(s
)) != NULL
)
663 return op
->op_type
== BINOP
&& (t
[0] != ')' || t
[1] != '\0');
667 /* atoi with error detection */
675 r
= strtoll(s
, &p
, 10);
678 if (errno
== ERANGE
&& (r
== LLONG_MAX
|| r
== LLONG_MIN
))
679 error("%s: out of range", s
);
681 while (isspace((unsigned char)*p
))
685 error("%s: bad number", s
);
691 newerf(const char *f1
, const char *f2
)
695 return (stat(f1
, &b1
) == 0 &&
696 stat(f2
, &b2
) == 0 &&
697 b1
.st_mtime
> b2
.st_mtime
);
701 olderf(const char *f1
, const char *f2
)
705 return (stat(f1
, &b1
) == 0 &&
706 stat(f2
, &b2
) == 0 &&
707 b1
.st_mtime
< b2
.st_mtime
);
711 equalf(const char *f1
, const char *f2
)
715 return (stat(f1
, &b1
) == 0 &&
716 stat(f2
, &b2
) == 0 &&
717 b1
.st_dev
== b2
.st_dev
&&
718 b1
.st_ino
== b2
.st_ino
);