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