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
c_test(wp)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 				/* Historically, -t by itself test if fd 1
159 				 * is a file descriptor, but POSIX says its
160 				 * a string test...
161 				 */
162 				if (!Flag(FPOSIX) && strcmp(opnd1, "-t") == 0)
163 				    break;
164 				res = (*te.eval)(&te, TO_STNZE, opnd1,
165 						(char *) 0, 1);
166 				if (invert & 1)
167 					res = !res;
168 				return !res;
169 			}
170 			if ((*te.isa)(&te, TM_NOT)) {
171 				invert++;
172 			} else
173 				break;
174 		}
175 		te.pos.wp = owp + 1;
176 	}
177 
178 	return test_parse(&te);
179 }
180 
181 /*
182  * Generic test routines.
183  */
184 
185 Test_op
test_isop(te,meta,s)186 test_isop(te, meta, s)
187 	Test_env *te;
188 	Test_meta meta;
189 	const char *s;
190 {
191 	char sc1;
192 	const struct t_op *otab;
193 
194 	otab = meta == TM_UNOP ? u_ops : b_ops;
195 	if (*s) {
196 		sc1 = s[1];
197 		for (; otab->op_text[0]; otab++)
198 			if (sc1 == otab->op_text[1]
199 			    && strcmp(s, otab->op_text) == 0
200 			    && ((te->flags & TEF_DBRACKET)
201 				|| (otab->op_num != TO_STLT
202 				    && otab->op_num != TO_STGT)))
203 				return otab->op_num;
204 	}
205 	return TO_NONOP;
206 }
207 
208 int
test_eval(te,op,opnd1,opnd2,do_eval)209 test_eval(te, op, opnd1, opnd2, do_eval)
210 	Test_env *te;
211 	Test_op op;
212 	const char *opnd1;
213 	const char *opnd2;
214 	int do_eval;
215 {
216 	int res;
217 	int not;
218 	struct stat b1, b2;
219 
220 	if (!do_eval)
221 		return 0;
222 
223 	switch ((int) op) {
224 	/*
225 	 * Unary Operators
226 	 */
227 	  case TO_STNZE: /* -n */
228 		return *opnd1 != '\0';
229 	  case TO_STZER: /* -z */
230 		return *opnd1 == '\0';
231 	  case TO_OPTION: /* -o */
232 		if ((not = *opnd1 == '!'))
233 			opnd1++;
234 		if ((res = option(opnd1)) < 0)
235 			res = 0;
236 		else {
237 			res = Flag(res);
238 			if (not)
239 				res = !res;
240 		}
241 		return res;
242 	  case TO_FILRD: /* -r */
243 		return test_eaccess(opnd1, R_OK) == 0;
244 	  case TO_FILWR: /* -w */
245 		return test_eaccess(opnd1, W_OK) == 0;
246 	  case TO_FILEX: /* -x */
247 		return test_eaccess(opnd1, X_OK) == 0;
248 	  case TO_FILAXST: /* -a */
249 		return test_stat(opnd1, &b1) == 0;
250 	  case TO_FILEXST: /* -e */
251 		/* at&t ksh does not appear to do the /dev/fd/ thing for
252 		 * this (unless the os itself handles it)
253 		 */
254 		return stat(opnd1, &b1) == 0;
255 	  case TO_FILREG: /* -r */
256 		return test_stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode);
257 	  case TO_FILID: /* -d */
258 		return test_stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode);
259 	  case TO_FILCDEV: /* -c */
260 #ifdef S_ISCHR
261 		return test_stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode);
262 #else
263 		return 0;
264 #endif
265 	  case TO_FILBDEV: /* -b */
266 #ifdef S_ISBLK
267 		return test_stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode);
268 #else
269 		return 0;
270 #endif
271 	  case TO_FILFIFO: /* -p */
272 #ifdef S_ISFIFO
273 		return test_stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode);
274 #else
275 		return 0;
276 #endif
277 	  case TO_FILSYM: /* -h -L */
278 #ifdef S_ISLNK
279 		return lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode);
280 #else
281 		return 0;
282 #endif
283 	  case TO_FILSOCK: /* -S */
284 #ifdef S_ISSOCK
285 		return test_stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode);
286 #else
287 		return 0;
288 #endif
289 	  case TO_FILCDF:/* -H HP context dependent files (directories) */
290 #ifdef S_ISCDF
291 	  {
292 		/* Append a + to filename and check to see if result is a
293 		 * setuid directory.  CDF stuff in general is hookey, since
294 		 * it breaks for the following sequence: echo hi > foo+;
295 		 * mkdir foo; echo bye > foo/default; chmod u+s foo
296 		 * (foo+ refers to the file with hi in it, there is no way
297 		 * to get at the file with bye in it - please correct me if
298 		 * I'm wrong about this).
299 		 */
300 		int len = strlen(opnd1);
301 		char *p = str_nsave(opnd1, len + 1, ATEMP);
302 
303 		p[len++] = '+';
304 		p[len] = '\0';
305 		return stat(p, &b1) == 0 && S_ISCDF(b1.st_mode);
306 	  }
307 #else
308 		return 0;
309 #endif
310 	  case TO_FILSETU: /* -u */
311 #ifdef S_ISUID
312 		return test_stat(opnd1, &b1) == 0
313 			&& (b1.st_mode & S_ISUID) == S_ISUID;
314 #else
315 		return 0;
316 #endif
317 	  case TO_FILSETG: /* -g */
318 #ifdef S_ISGID
319 		return test_stat(opnd1, &b1) == 0
320 			&& (b1.st_mode & S_ISGID) == S_ISGID;
321 #else
322 		return 0;
323 #endif
324 	  case TO_FILSTCK: /* -k */
325 		return test_stat(opnd1, &b1) == 0
326 			&& (b1.st_mode & S_ISVTX) == S_ISVTX;
327 	  case TO_FILGZ: /* -s */
328 		return test_stat(opnd1, &b1) == 0 && b1.st_size > 0L;
329 	  case TO_FILTT: /* -t */
330 		if (opnd1 && !bi_getn(opnd1, &res)) {
331 			te->flags |= TEF_ERROR;
332 			res = 0;
333 		} else {
334 			/* generate error if in FPOSIX mode? */
335 			res = isatty(opnd1 ? res : 0);
336 		}
337 		return res;
338 	  case TO_FILUID: /* -O */
339 		return test_stat(opnd1, &b1) == 0 && b1.st_uid == ksheuid;
340 	  case TO_FILGID: /* -G */
341 		return test_stat(opnd1, &b1) == 0 && b1.st_gid == getegid();
342 	/*
343 	 * Binary Operators
344 	 */
345 	  case TO_STEQL: /* = */
346 		if (te->flags & TEF_DBRACKET)
347 			return gmatch(opnd1, opnd2, FALSE);
348 		return strcmp(opnd1, opnd2) == 0;
349 	  case TO_STNEQ: /* != */
350 		if (te->flags & TEF_DBRACKET)
351 			return !gmatch(opnd1, opnd2, FALSE);
352 		return strcmp(opnd1, opnd2) != 0;
353 	  case TO_STLT: /* < */
354 		return strcmp(opnd1, opnd2) < 0;
355 	  case TO_STGT: /* > */
356 		return strcmp(opnd1, opnd2) > 0;
357 	  case TO_INTEQ: /* -eq */
358 	  case TO_INTNE: /* -ne */
359 	  case TO_INTGE: /* -ge */
360 	  case TO_INTGT: /* -gt */
361 	  case TO_INTLE: /* -le */
362 	  case TO_INTLT: /* -lt */
363 		{
364 			long v1, v2;
365 
366 			if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR)
367 			    || !evaluate(opnd2, &v2, KSH_RETURN_ERROR))
368 			{
369 				/* error already printed.. */
370 				te->flags |= TEF_ERROR;
371 				return 1;
372 			}
373 			switch ((int) op) {
374 			  case TO_INTEQ:
375 				return v1 == v2;
376 			  case TO_INTNE:
377 				return v1 != v2;
378 			  case TO_INTGE:
379 				return v1 >= v2;
380 			  case TO_INTGT:
381 				return v1 > v2;
382 			  case TO_INTLE:
383 				return v1 <= v2;
384 			  case TO_INTLT:
385 				return v1 < v2;
386 			}
387 		}
388 	  case TO_FILNT: /* -nt */
389 		{
390 			int s2;
391 			/* ksh88/ksh93 succeed if file2 can't be stated
392 			 * (subtly different from `does not exist').
393 			 */
394 			return stat(opnd1, &b1) == 0
395 				&& (((s2 = stat(opnd2, &b2)) == 0
396 				      && b1.st_mtime > b2.st_mtime) || s2 < 0);
397 		}
398 	  case TO_FILOT: /* -ot */
399 		{
400 			int s1;
401 			/* ksh88/ksh93 succeed if file1 can't be stated
402 			 * (subtly different from `does not exist').
403 			 */
404 			return stat(opnd2, &b2) == 0
405 				&& (((s1 = stat(opnd1, &b1)) == 0
406 				      && b1.st_mtime < b2.st_mtime) || s1 < 0);
407 		}
408 	  case TO_FILEQ: /* -ef */
409 		return stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0
410 		       && b1.st_dev == b2.st_dev
411 		       && b1.st_ino == b2.st_ino;
412 	}
413 	(*te->error)(te, 0, "internal error: unknown op");
414 	return 1;
415 }
416 
417 /* Nasty kludge to handle Korn's bizarre /dev/fd hack */
418 static int
test_stat(path,statb)419 test_stat(path, statb)
420 	const char *path;
421 	struct stat *statb;
422 {
423 #if !defined(HAVE_DEV_FD)
424 	int fd;
425 
426 	if (strncmp(path, "/dev/fd/", 8) == 0 && getn(path + 8, &fd))
427 		return fstat(fd, statb);
428 #endif /* !HAVE_DEV_FD */
429 
430 	return stat(path, statb);
431 }
432 
433 /* Routine to handle Korn's /dev/fd hack, and to deal with X_OK on
434  * non-directories when running as root.
435  */
436 static int
test_eaccess(path,mode)437 test_eaccess(path, mode)
438 	const char *path;
439 	int mode;
440 {
441 	int res;
442 
443 #if !defined(HAVE_DEV_FD)
444 	int fd;
445 
446 	/* Note: doesn't handle //dev/fd, etc.. (this is ok) */
447 	if (strncmp(path, "/dev/fd/", 8) == 0 && getn(path + 8, &fd)) {
448 		int flags;
449 
450 		if ((flags = fcntl(fd, F_GETFL, 0)) < 0
451 		    || (mode & X_OK)
452 		    || ((mode & W_OK) && (flags & O_ACCMODE) == O_RDONLY)
453 		    || ((mode & R_OK) && (flags & O_ACCMODE) == O_WRONLY))
454 			return -1;
455 		return 0;
456 	}
457 #endif /* !HAVE_DEV_FD */
458 
459 	/* On most (all?) unixes, access() says everything is executable for
460 	 * root - avoid this on files by using stat().
461 	 */
462 	if ((mode & X_OK) && ksheuid == 0) {
463 		struct stat statb;
464 
465 		if (stat(path, &statb) < 0)
466 			res = -1;
467 		else if (S_ISDIR(statb.st_mode))
468 			res = 0;
469 		else
470 			res = (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
471 				? 0 : -1;
472 		/* Need to check other permissions?  If so, use access() as
473 		 * this will deal with root on NFS.
474 		 */
475 		if (res == 0 && (mode & (R_OK|W_OK)))
476 			res = eaccess(path, mode);
477 	} else
478 		res = eaccess(path, mode);
479 
480 	return res;
481 }
482 
483 int
test_parse(te)484 test_parse(te)
485 	Test_env *te;
486 {
487 	int res;
488 
489 	res = test_oexpr(te, 1);
490 
491 	if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
492 		(*te->error)(te, 0, "unexpected operator/operand");
493 
494 	return (te->flags & TEF_ERROR) ? T_ERR_EXIT : !res;
495 }
496 
497 static int
test_oexpr(te,do_eval)498 test_oexpr(te, do_eval)
499 	Test_env *te;
500 	int do_eval;
501 {
502 	int res;
503 
504 	res = test_aexpr(te, do_eval);
505 	if (res)
506 		do_eval = 0;
507 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
508 		return test_oexpr(te, do_eval) || res;
509 	return res;
510 }
511 
512 static int
test_aexpr(te,do_eval)513 test_aexpr(te, do_eval)
514 	Test_env *te;
515 	int do_eval;
516 {
517 	int res;
518 
519 	res = test_nexpr(te, do_eval);
520 	if (!res)
521 		do_eval = 0;
522 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
523 		return test_aexpr(te, do_eval) && res;
524 	return res;
525 }
526 
527 static int
test_nexpr(te,do_eval)528 test_nexpr(te, do_eval)
529 	Test_env *te;
530 	int do_eval;
531 {
532 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
533 		return !test_nexpr(te, do_eval);
534 	return test_primary(te, do_eval);
535 }
536 
537 static int
test_primary(te,do_eval)538 test_primary(te, do_eval)
539 	Test_env *te;
540 	int do_eval;
541 {
542 	const char *opnd1, *opnd2;
543 	int res;
544 	Test_op op;
545 
546 	if (te->flags & TEF_ERROR)
547 		return 0;
548 	if ((*te->isa)(te, TM_OPAREN)) {
549 		res = test_oexpr(te, do_eval);
550 		if (te->flags & TEF_ERROR)
551 			return 0;
552 		if (!(*te->isa)(te, TM_CPAREN)) {
553 			(*te->error)(te, 0, "missing closing paren");
554 			return 0;
555 		}
556 		return res;
557 	}
558 	if ((op = (Test_op) (*te->isa)(te, TM_UNOP))) {
559 		/* unary expression */
560 		opnd1 = (*te->getopnd)(te, op, do_eval);
561 		if (!opnd1) {
562 			(*te->error)(te, -1, "missing argument");
563 			return 0;
564 		}
565 
566 		return (*te->eval)(te, op, opnd1, (const char *) 0, do_eval);
567 	}
568 	opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
569 	if (!opnd1) {
570 		(*te->error)(te, 0, "expression expected");
571 		return 0;
572 	}
573 	if ((op = (Test_op) (*te->isa)(te, TM_BINOP))) {
574 		/* binary expression */
575 		opnd2 = (*te->getopnd)(te, op, do_eval);
576 		if (!opnd2) {
577 			(*te->error)(te, -1, "missing second argument");
578 			return 0;
579 		}
580 
581 		return (*te->eval)(te, op, opnd1, opnd2, do_eval);
582 	}
583 	if (te->flags & TEF_DBRACKET) {
584 		(*te->error)(te, -1, "missing expression operator");
585 		return 0;
586 	}
587 	return (*te->eval)(te, TO_STNZE, opnd1, (const char *) 0, do_eval);
588 }
589 
590 /*
591  * Plain test (test and [ .. ]) specific routines.
592  */
593 
594 /* Test if the current token is a whatever.  Accepts the current token if
595  * it is.  Returns 0 if it is not, non-zero if it is (in the case of
596  * TM_UNOP and TM_BINOP, the returned value is a Test_op).
597  */
598 static int
ptest_isa(te,meta)599 ptest_isa(te, meta)
600 	Test_env *te;
601 	Test_meta meta;
602 {
603 	/* Order important - indexed by Test_meta values */
604 	static const char *const tokens[] = {
605 				"-o", "-a", "!", "(", ")"
606 			};
607 	int ret;
608 
609 	if (te->pos.wp >= te->wp_end)
610 		return meta == TM_END;
611 
612 	if (meta == TM_UNOP || meta == TM_BINOP)
613 		ret = (int) test_isop(te, meta, *te->pos.wp);
614 	else if (meta == TM_END)
615 		ret = 0;
616 	else
617 		ret = strcmp(*te->pos.wp, tokens[(int) meta]) == 0;
618 
619 	/* Accept the token? */
620 	if (ret)
621 		te->pos.wp++;
622 
623 	return ret;
624 }
625 
626 static const char *
ptest_getopnd(te,op,do_eval)627 ptest_getopnd(te, op, do_eval)
628 	Test_env *te;
629 	Test_op op;
630 	int do_eval;
631 {
632 	if (te->pos.wp >= te->wp_end)
633 		return op == TO_FILTT ? "1" : (const char *) 0;
634 	return *te->pos.wp++;
635 }
636 
637 static int
ptest_eval(te,op,opnd1,opnd2,do_eval)638 ptest_eval(te, op, opnd1, opnd2, do_eval)
639 	Test_env *te;
640 	Test_op op;
641 	const char *opnd1;
642 	const char *opnd2;
643 	int do_eval;
644 {
645 	return test_eval(te, op, opnd1, opnd2, do_eval);
646 }
647 
648 static void
ptest_error(te,offset,msg)649 ptest_error(te, offset, msg)
650 	Test_env *te;
651 	int offset;
652 	const char *msg;
653 {
654 	const char *op = te->pos.wp + offset >= te->wp_end ?
655 				(const char *) 0 : te->pos.wp[offset];
656 
657 	te->flags |= TEF_ERROR;
658 	if (op)
659 		bi_errorf("%s: %s", op, msg);
660 	else
661 		bi_errorf("%s", msg);
662 }
663