xref: /netbsd/bin/ksh/c_test.c (revision 6550d01e)
1 /*	$NetBSD: c_test.c,v 1.6 2005/06/26 19:09:00 christos Exp $	*/
2 
3 /*
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 Michael Rendell to add Korn's [[ .. ]] expressions.
9  * modified by J.T. Conklin to add POSIX compatibility.
10  */
11 #include <sys/cdefs.h>
12 
13 #ifndef lint
14 __RCSID("$NetBSD: c_test.c,v 1.6 2005/06/26 19:09:00 christos Exp $");
15 #endif
16 
17 
18 #include "sh.h"
19 #include "ksh_stat.h"
20 #include "c_test.h"
21 
22 /* test(1) accepts the following grammar:
23 	oexpr	::= aexpr | aexpr "-o" oexpr ;
24 	aexpr	::= nexpr | nexpr "-a" aexpr ;
25 	nexpr	::= primary | "!" nexpr ;
26 	primary	::= unary-operator operand
27 		| operand binary-operator operand
28 		| operand
29 		| "(" oexpr ")"
30 		;
31 
32 	unary-operator ::= "-a"|"-r"|"-w"|"-x"|"-e"|"-f"|"-d"|"-c"|"-b"|"-p"|
33 			   "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|
34 			   "-L"|"-h"|"-S"|"-H";
35 
36 	binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
37 			    "-nt"|"-ot"|"-ef"|
38 			    "<"|">"	# rules used for [[ .. ]] expressions
39 			    ;
40 	operand ::= <any thing>
41 */
42 
43 #define T_ERR_EXIT	2	/* POSIX says > 1 for errors */
44 
45 struct t_op {
46 	char	op_text[4];
47 	Test_op	op_num;
48 };
49 static const struct t_op u_ops [] = {
50 	{"-a",	TO_FILAXST },
51 	{"-b",	TO_FILBDEV },
52 	{"-c",	TO_FILCDEV },
53 	{"-d",	TO_FILID },
54 	{"-e",	TO_FILEXST },
55 	{"-f",	TO_FILREG },
56 	{"-G",	TO_FILGID },
57 	{"-g",	TO_FILSETG },
58 	{"-h",	TO_FILSYM },
59 	{"-H",	TO_FILCDF },
60 	{"-k",	TO_FILSTCK },
61 	{"-L",	TO_FILSYM },
62 	{"-n",	TO_STNZE },
63 	{"-O",	TO_FILUID },
64 	{"-o",	TO_OPTION },
65 	{"-p",	TO_FILFIFO },
66 	{"-r",	TO_FILRD },
67 	{"-s",	TO_FILGZ },
68 	{"-S",	TO_FILSOCK },
69 	{"-t",	TO_FILTT },
70 	{"-u",	TO_FILSETU },
71 	{"-w",	TO_FILWR },
72 	{"-x",	TO_FILEX },
73 	{"-z",	TO_STZER },
74 	{"",	TO_NONOP }
75     };
76 static const struct t_op b_ops [] = {
77 	{"=",	TO_STEQL },
78 #ifdef KSH
79 	{"==",	TO_STEQL },
80 #endif /* KSH */
81 	{"!=",	TO_STNEQ },
82 	{"<",	TO_STLT },
83 	{">",	TO_STGT },
84 	{"-eq",	TO_INTEQ },
85 	{"-ne",	TO_INTNE },
86 	{"-gt",	TO_INTGT },
87 	{"-ge",	TO_INTGE },
88 	{"-lt",	TO_INTLT },
89 	{"-le",	TO_INTLE },
90 	{"-ef",	TO_FILEQ },
91 	{"-nt",	TO_FILNT },
92 	{"-ot",	TO_FILOT },
93 	{"",	TO_NONOP }
94     };
95 
96 static int	test_stat ARGS((const char *, struct stat *));
97 static int	test_eaccess ARGS((const char *, int));
98 static int	test_oexpr ARGS((Test_env *, int));
99 static int	test_aexpr ARGS((Test_env *, int));
100 static int	test_nexpr ARGS((Test_env *, int));
101 static int	test_primary ARGS((Test_env *, int));
102 static int	ptest_isa ARGS((Test_env *, Test_meta));
103 static const char *ptest_getopnd ARGS((Test_env *, Test_op, int));
104 static int	ptest_eval ARGS((Test_env *, Test_op, const char *,
105 				const char *, int));
106 static void	ptest_error ARGS((Test_env *, int, const char *));
107 
108 int
109 c_test(wp)
110 	char **wp;
111 {
112 	int argc;
113 	int res;
114 	Test_env te;
115 
116 	te.flags = 0;
117 	te.isa = ptest_isa;
118 	te.getopnd = ptest_getopnd;
119 	te.eval = ptest_eval;
120 	te.error = ptest_error;
121 
122 	for (argc = 0; wp[argc]; argc++)
123 		;
124 
125 	if (strcmp(wp[0], "[") == 0) {
126 		if (strcmp(wp[--argc], "]") != 0) {
127 			bi_errorf("missing ]");
128 			return T_ERR_EXIT;
129 		}
130 	}
131 
132 	te.pos.wp = wp + 1;
133 	te.wp_end = wp + argc;
134 
135 	/*
136 	 * Handle the special cases from POSIX.2, section 4.62.4.
137 	 * Implementation of all the rules isn't necessary since
138 	 * our parser does the right thing for the omitted steps.
139 	 */
140 	if (argc <= 5) {
141 		char **owp = wp;
142 		int invert = 0;
143 		Test_op	op;
144 		const char *opnd1, *opnd2;
145 
146 		while (--argc >= 0) {
147 			if ((*te.isa)(&te, TM_END))
148 				return !0;
149 			if (argc == 3) {
150 				opnd1 = (*te.getopnd)(&te, TO_NONOP, 1);
151 				if ((op = (Test_op) (*te.isa)(&te, TM_BINOP))) {
152 					opnd2 = (*te.getopnd)(&te, op, 1);
153 					res = (*te.eval)(&te, op, opnd1, opnd2,
154 							1);
155 					if (te.flags & TEF_ERROR)
156 						return T_ERR_EXIT;
157 					if (invert & 1)
158 						res = !res;
159 					return !res;
160 				}
161 				/* back up to opnd1 */
162 				te.pos.wp--;
163 			}
164 			if (argc == 1) {
165 				opnd1 = (*te.getopnd)(&te, TO_NONOP, 1);
166 				/* Historically, -t by itself test if fd 1
167 				 * is a file descriptor, but POSIX says its
168 				 * a string test...
169 				 */
170 				if (!Flag(FPOSIX) && strcmp(opnd1, "-t") == 0)
171 				    break;
172 				res = (*te.eval)(&te, TO_STNZE, opnd1,
173 						(char *) 0, 1);
174 				if (invert & 1)
175 					res = !res;
176 				return !res;
177 			}
178 			if ((*te.isa)(&te, TM_NOT)) {
179 				invert++;
180 			} else
181 				break;
182 		}
183 		te.pos.wp = owp + 1;
184 	}
185 
186 	return test_parse(&te);
187 }
188 
189 /*
190  * Generic test routines.
191  */
192 
193 Test_op
194 test_isop(te, meta, s)
195 	Test_env *te;
196 	Test_meta meta;
197 	const char *s;
198 {
199 	char sc1;
200 	const struct t_op *otab;
201 
202 	otab = meta == TM_UNOP ? u_ops : b_ops;
203 	if (*s) {
204 		sc1 = s[1];
205 		for (; otab->op_text[0]; otab++)
206 			if (sc1 == otab->op_text[1]
207 			    && strcmp(s, otab->op_text) == 0
208 			    && ((te->flags & TEF_DBRACKET)
209 				|| (otab->op_num != TO_STLT
210 				    && otab->op_num != TO_STGT)))
211 				return otab->op_num;
212 	}
213 	return TO_NONOP;
214 }
215 
216 int
217 test_eval(te, op, opnd1, opnd2, do_eval)
218 	Test_env *te;
219 	Test_op op;
220 	const char *opnd1;
221 	const char *opnd2;
222 	int do_eval;
223 {
224 	int res;
225 	int not;
226 	struct stat b1, b2;
227 
228 	if (!do_eval)
229 		return 0;
230 
231 	switch ((int) op) {
232 	/*
233 	 * Unary Operators
234 	 */
235 	  case TO_STNZE: /* -n */
236 		return *opnd1 != '\0';
237 	  case TO_STZER: /* -z */
238 		return *opnd1 == '\0';
239 	  case TO_OPTION: /* -o */
240 		if ((not = *opnd1 == '!'))
241 			opnd1++;
242 		if ((res = option(opnd1)) < 0)
243 			res = 0;
244 		else {
245 			res = Flag(res);
246 			if (not)
247 				res = !res;
248 		}
249 		return res;
250 	  case TO_FILRD: /* -r */
251 		return test_eaccess(opnd1, R_OK) == 0;
252 	  case TO_FILWR: /* -w */
253 		return test_eaccess(opnd1, W_OK) == 0;
254 	  case TO_FILEX: /* -x */
255 		return test_eaccess(opnd1, X_OK) == 0;
256 	  case TO_FILAXST: /* -a */
257 		return test_stat(opnd1, &b1) == 0;
258 	  case TO_FILEXST: /* -e */
259 		/* at&t ksh does not appear to do the /dev/fd/ thing for
260 		 * this (unless the os itself handles it)
261 		 */
262 		return stat(opnd1, &b1) == 0;
263 	  case TO_FILREG: /* -r */
264 		return test_stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode);
265 	  case TO_FILID: /* -d */
266 		return test_stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode);
267 	  case TO_FILCDEV: /* -c */
268 #ifdef S_ISCHR
269 		return test_stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode);
270 #else
271 		return 0;
272 #endif
273 	  case TO_FILBDEV: /* -b */
274 #ifdef S_ISBLK
275 		return test_stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode);
276 #else
277 		return 0;
278 #endif
279 	  case TO_FILFIFO: /* -p */
280 #ifdef S_ISFIFO
281 		return test_stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode);
282 #else
283 		return 0;
284 #endif
285 	  case TO_FILSYM: /* -h -L */
286 #ifdef S_ISLNK
287 		return lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode);
288 #else
289 		return 0;
290 #endif
291 	  case TO_FILSOCK: /* -S */
292 #ifdef S_ISSOCK
293 		return test_stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode);
294 #else
295 		return 0;
296 #endif
297 	  case TO_FILCDF:/* -H HP context dependent files (directories) */
298 #ifdef S_ISCDF
299 	  {
300 		/* Append a + to filename and check to see if result is a
301 		 * setuid directory.  CDF stuff in general is hookey, since
302 		 * it breaks for the following sequence: echo hi > foo+;
303 		 * mkdir foo; echo bye > foo/default; chmod u+s foo
304 		 * (foo+ refers to the file with hi in it, there is no way
305 		 * to get at the file with bye in it - please correct me if
306 		 * I'm wrong about this).
307 		 */
308 		int len = strlen(opnd1);
309 		char *p = str_nsave(opnd1, len + 1, ATEMP);
310 
311 		p[len++] = '+';
312 		p[len] = '\0';
313 		return stat(p, &b1) == 0 && S_ISCDF(b1.st_mode);
314 	  }
315 #else
316 		return 0;
317 #endif
318 	  case TO_FILSETU: /* -u */
319 #ifdef S_ISUID
320 		return test_stat(opnd1, &b1) == 0
321 			&& (b1.st_mode & S_ISUID) == S_ISUID;
322 #else
323 		return 0;
324 #endif
325 	  case TO_FILSETG: /* -g */
326 #ifdef S_ISGID
327 		return test_stat(opnd1, &b1) == 0
328 			&& (b1.st_mode & S_ISGID) == S_ISGID;
329 #else
330 		return 0;
331 #endif
332 	  case TO_FILSTCK: /* -k */
333 		return test_stat(opnd1, &b1) == 0
334 			&& (b1.st_mode & S_ISVTX) == S_ISVTX;
335 	  case TO_FILGZ: /* -s */
336 		return test_stat(opnd1, &b1) == 0 && b1.st_size > 0L;
337 	  case TO_FILTT: /* -t */
338 		if (opnd1 && !bi_getn(opnd1, &res)) {
339 			te->flags |= TEF_ERROR;
340 			res = 0;
341 		} else {
342 			/* generate error if in FPOSIX mode? */
343 			res = isatty(opnd1 ? res : 0);
344 		}
345 		return res;
346 	  case TO_FILUID: /* -O */
347 		return test_stat(opnd1, &b1) == 0 && b1.st_uid == ksheuid;
348 	  case TO_FILGID: /* -G */
349 		return test_stat(opnd1, &b1) == 0 && b1.st_gid == getegid();
350 	/*
351 	 * Binary Operators
352 	 */
353 	  case TO_STEQL: /* = */
354 		if (te->flags & TEF_DBRACKET)
355 			return gmatch(opnd1, opnd2, FALSE);
356 		return strcmp(opnd1, opnd2) == 0;
357 	  case TO_STNEQ: /* != */
358 		if (te->flags & TEF_DBRACKET)
359 			return !gmatch(opnd1, opnd2, FALSE);
360 		return strcmp(opnd1, opnd2) != 0;
361 	  case TO_STLT: /* < */
362 		return strcmp(opnd1, opnd2) < 0;
363 	  case TO_STGT: /* > */
364 		return strcmp(opnd1, opnd2) > 0;
365 	  case TO_INTEQ: /* -eq */
366 	  case TO_INTNE: /* -ne */
367 	  case TO_INTGE: /* -ge */
368 	  case TO_INTGT: /* -gt */
369 	  case TO_INTLE: /* -le */
370 	  case TO_INTLT: /* -lt */
371 		{
372 			long v1, v2;
373 
374 			if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR)
375 			    || !evaluate(opnd2, &v2, KSH_RETURN_ERROR))
376 			{
377 				/* error already printed.. */
378 				te->flags |= TEF_ERROR;
379 				return 1;
380 			}
381 			switch ((int) op) {
382 			  case TO_INTEQ:
383 				return v1 == v2;
384 			  case TO_INTNE:
385 				return v1 != v2;
386 			  case TO_INTGE:
387 				return v1 >= v2;
388 			  case TO_INTGT:
389 				return v1 > v2;
390 			  case TO_INTLE:
391 				return v1 <= v2;
392 			  case TO_INTLT:
393 				return v1 < v2;
394 			}
395 		}
396 	  case TO_FILNT: /* -nt */
397 		{
398 			int s2;
399 			/* ksh88/ksh93 succeed if file2 can't be stated
400 			 * (subtly different from `does not exist').
401 			 */
402 			return stat(opnd1, &b1) == 0
403 				&& (((s2 = stat(opnd2, &b2)) == 0
404 				      && b1.st_mtime > b2.st_mtime) || s2 < 0);
405 		}
406 	  case TO_FILOT: /* -ot */
407 		{
408 			int s1;
409 			/* ksh88/ksh93 succeed if file1 can't be stated
410 			 * (subtly different from `does not exist').
411 			 */
412 			return stat(opnd2, &b2) == 0
413 				&& (((s1 = stat(opnd1, &b1)) == 0
414 				      && b1.st_mtime < b2.st_mtime) || s1 < 0);
415 		}
416 	  case TO_FILEQ: /* -ef */
417 		return stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0
418 		       && b1.st_dev == b2.st_dev
419 		       && b1.st_ino == b2.st_ino;
420 	}
421 	(*te->error)(te, 0, "internal error: unknown op");
422 	return 1;
423 }
424 
425 /* Nasty kludge to handle Korn's bizarre /dev/fd hack */
426 static int
427 test_stat(pathx, statb)
428 	const char *pathx;
429 	struct stat *statb;
430 {
431 #if !defined(HAVE_DEV_FD)
432 	int fd;
433 
434 	if (strncmp(pathx, "/dev/fd/", 8) == 0 && getn(pathx + 8, &fd))
435 		return fstat(fd, statb);
436 #endif /* !HAVE_DEV_FD */
437 
438 	return stat(pathx, statb);
439 }
440 
441 /* Routine to handle Korn's /dev/fd hack, and to deal with X_OK on
442  * non-directories when running as root.
443  */
444 static int
445 test_eaccess(pathx, mode)
446 	const char *pathx;
447 	int mode;
448 {
449 	int res;
450 
451 #if !defined(HAVE_DEV_FD)
452 	int fd;
453 
454 	/* Note: doesn't handle //dev/fd, etc.. (this is ok) */
455 	if (strncmp(pathx, "/dev/fd/", 8) == 0 && getn(pathx + 8, &fd)) {
456 		int flags;
457 
458 		if ((flags = fcntl(fd, F_GETFL, 0)) < 0
459 		    || (mode & X_OK)
460 		    || ((mode & W_OK) && (flags & O_ACCMODE) == O_RDONLY)
461 		    || ((mode & R_OK) && (flags & O_ACCMODE) == O_WRONLY))
462 			return -1;
463 		return 0;
464 	}
465 #endif /* !HAVE_DEV_FD */
466 
467 	res = eaccess(pathx, mode);
468 	/*
469 	 * On most (all?) unixes, access() says everything is executable for
470 	 * root - avoid this on files by using stat().
471 	 */
472 	if (res == 0 && ksheuid == 0 && (mode & X_OK)) {
473 		struct stat statb;
474 
475 		if (stat(pathx, &statb) < 0)
476 			res = -1;
477 		else if (S_ISDIR(statb.st_mode))
478 			res = 0;
479 		else
480 			res = (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
481 				? 0 : -1;
482 	}
483 
484 	return res;
485 }
486 
487 int
488 test_parse(te)
489 	Test_env *te;
490 {
491 	int res;
492 
493 	res = test_oexpr(te, 1);
494 
495 	if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
496 		(*te->error)(te, 0, "unexpected operator/operand");
497 
498 	return (te->flags & TEF_ERROR) ? T_ERR_EXIT : !res;
499 }
500 
501 static int
502 test_oexpr(te, do_eval)
503 	Test_env *te;
504 	int do_eval;
505 {
506 	int res;
507 
508 	res = test_aexpr(te, do_eval);
509 	if (res)
510 		do_eval = 0;
511 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
512 		return test_oexpr(te, do_eval) || res;
513 	return res;
514 }
515 
516 static int
517 test_aexpr(te, do_eval)
518 	Test_env *te;
519 	int do_eval;
520 {
521 	int res;
522 
523 	res = test_nexpr(te, do_eval);
524 	if (!res)
525 		do_eval = 0;
526 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
527 		return test_aexpr(te, do_eval) && res;
528 	return res;
529 }
530 
531 static int
532 test_nexpr(te, do_eval)
533 	Test_env *te;
534 	int do_eval;
535 {
536 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
537 		return !test_nexpr(te, do_eval);
538 	return test_primary(te, do_eval);
539 }
540 
541 static int
542 test_primary(te, do_eval)
543 	Test_env *te;
544 	int do_eval;
545 {
546 	const char *opnd1, *opnd2;
547 	int res;
548 	Test_op op;
549 
550 	if (te->flags & TEF_ERROR)
551 		return 0;
552 	if ((*te->isa)(te, TM_OPAREN)) {
553 		res = test_oexpr(te, do_eval);
554 		if (te->flags & TEF_ERROR)
555 			return 0;
556 		if (!(*te->isa)(te, TM_CPAREN)) {
557 			(*te->error)(te, 0, "missing closing paren");
558 			return 0;
559 		}
560 		return res;
561 	}
562 	if ((op = (Test_op) (*te->isa)(te, TM_UNOP))) {
563 		/* unary expression */
564 		opnd1 = (*te->getopnd)(te, op, do_eval);
565 		if (!opnd1) {
566 			(*te->error)(te, -1, "missing argument");
567 			return 0;
568 		}
569 
570 		return (*te->eval)(te, op, opnd1, (const char *) 0, do_eval);
571 	}
572 	opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
573 	if (!opnd1) {
574 		(*te->error)(te, 0, "expression expected");
575 		return 0;
576 	}
577 	if ((op = (Test_op) (*te->isa)(te, TM_BINOP))) {
578 		/* binary expression */
579 		opnd2 = (*te->getopnd)(te, op, do_eval);
580 		if (!opnd2) {
581 			(*te->error)(te, -1, "missing second argument");
582 			return 0;
583 		}
584 
585 		return (*te->eval)(te, op, opnd1, opnd2, do_eval);
586 	}
587 	if (te->flags & TEF_DBRACKET) {
588 		(*te->error)(te, -1, "missing expression operator");
589 		return 0;
590 	}
591 	return (*te->eval)(te, TO_STNZE, opnd1, (const char *) 0, do_eval);
592 }
593 
594 /*
595  * Plain test (test and [ .. ]) specific routines.
596  */
597 
598 /* Test if the current token is a whatever.  Accepts the current token if
599  * it is.  Returns 0 if it is not, non-zero if it is (in the case of
600  * TM_UNOP and TM_BINOP, the returned value is a Test_op).
601  */
602 static int
603 ptest_isa(te, meta)
604 	Test_env *te;
605 	Test_meta meta;
606 {
607 	/* Order important - indexed by Test_meta values */
608 	static const char *const tokens[] = {
609 				"-o", "-a", "!", "(", ")"
610 			};
611 	int ret;
612 
613 	if (te->pos.wp >= te->wp_end)
614 		return meta == TM_END;
615 
616 	if (meta == TM_UNOP || meta == TM_BINOP)
617 		ret = (int) test_isop(te, meta, *te->pos.wp);
618 	else if (meta == TM_END)
619 		ret = 0;
620 	else
621 		ret = strcmp(*te->pos.wp, tokens[(int) meta]) == 0;
622 
623 	/* Accept the token? */
624 	if (ret)
625 		te->pos.wp++;
626 
627 	return ret;
628 }
629 
630 static const char *
631 ptest_getopnd(te, op, do_eval)
632 	Test_env *te;
633 	Test_op op;
634 	int do_eval;
635 {
636 	if (te->pos.wp >= te->wp_end)
637 		return op == TO_FILTT ? "1" : (const char *) 0;
638 	return *te->pos.wp++;
639 }
640 
641 static int
642 ptest_eval(te, op, opnd1, opnd2, do_eval)
643 	Test_env *te;
644 	Test_op op;
645 	const char *opnd1;
646 	const char *opnd2;
647 	int do_eval;
648 {
649 	return test_eval(te, op, opnd1, opnd2, do_eval);
650 }
651 
652 static void
653 ptest_error(te, offset, msg)
654 	Test_env *te;
655 	int offset;
656 	const char *msg;
657 {
658 	const char *op = te->pos.wp + offset >= te->wp_end ?
659 				(const char *) 0 : te->pos.wp[offset];
660 
661 	te->flags |= TEF_ERROR;
662 	if (op)
663 		bi_errorf("%s: %s", op, msg);
664 	else
665 		bi_errorf("%s", msg);
666 }
667