exec.c revision 1.16 1 /* $NetBSD: exec.c,v 1.16 2001/09/14 14:04:00 wiz Exp $ */
2
3 /*-
4 * Copyright (c) 1980, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)exec.c 8.3 (Berkeley) 5/23/95";
40 #else
41 __RCSID("$NetBSD: exec.c,v 1.16 2001/09/14 14:04:00 wiz Exp $");
42 #endif
43 #endif /* not lint */
44
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48
49 #include <dirent.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55
56 #if __STDC__
57 # include <stdarg.h>
58 #else
59 # include <varargs.h>
60 #endif
61
62 #include "csh.h"
63 #include "extern.h"
64
65 /*
66 * System level search and execute of a command. We look in each directory
67 * for the specified command name. If the name contains a '/' then we
68 * execute only the full path name. If there is no search path then we
69 * execute only full path names.
70 */
71 extern char **environ;
72
73 /*
74 * As we search for the command we note the first non-trivial error
75 * message for presentation to the user. This allows us often
76 * to show that a file has the wrong mode/no access when the file
77 * is not in the last component of the search path, so we must
78 * go on after first detecting the error.
79 */
80 static const char *exerr; /* Execution error message */
81 static Char *expath; /* Path for exerr */
82
83 /*
84 * Xhash is an array of HSHSIZ bits (HSHSIZ / 8 chars), which are used
85 * to hash execs. If it is allocated (havhash true), then to tell
86 * whether ``name'' is (possibly) present in the i'th component
87 * of the variable path, you look at the bit in xhash indexed by
88 * hash(hashname("name"), i). This is setup automatically
89 * after .login is executed, and recomputed whenever ``path'' is
90 * changed.
91 * The two part hash function is designed to let texec() call the
92 * more expensive hashname() only once and the simple hash() several
93 * times (once for each path component checked).
94 * Byte size is assumed to be 8.
95 */
96 #define HSHSIZ 8192 /* 1k bytes */
97 #define HSHMASK (HSHSIZ - 1)
98 #define HSHMUL 243
99 static char xhash[HSHSIZ / 8];
100
101 #define hash(a, b) (((a) * HSHMUL + (b)) & HSHMASK)
102 #define bit(h, b) ((h)[(b) >> 3] & 1 << ((b) & 7)) /* bit test */
103 #define bis(h, b) ((h)[(b) >> 3] |= 1 << ((b) & 7)) /* bit set */
104 static int hits, misses;
105
106 /* Dummy search path for just absolute search when no path */
107 static Char *justabs[] = {STRNULL, 0};
108
109 static void pexerr __P((void)) __attribute__((noreturn));
110 static void texec(Char *, Char **);
111 static int hashname(Char *);
112 static int tellmewhat(struct wordent *, Char *);
113 static int executable(Char *, Char *, bool);
114 static int iscommand(Char *);
115
116 void
117 /*ARGSUSED*/
118 doexec(Char **v, struct command *t)
119 {
120 struct varent *pathv;
121 Char *blk[2], **av, *dp, **pv, *sav;
122 int i, hashval, hashval1;
123 sigset_t sigset;
124 bool slash;
125
126 hashval = 0;
127 /*
128 * Glob the command name. We will search $path even if this does something,
129 * as in sh but not in csh. One special case: if there is no PATH, then we
130 * execute only commands which start with '/'.
131 */
132 blk[0] = t->t_dcom[0];
133 blk[1] = 0;
134 gflag = 0, tglob(blk);
135 if (gflag) {
136 pv = globall(blk);
137 if (pv == 0) {
138 setname(vis_str(blk[0]));
139 stderror(ERR_NAME | ERR_NOMATCH);
140 }
141 gargv = 0;
142 }
143 else
144 pv = saveblk(blk);
145
146 trim(pv);
147
148 exerr = 0;
149 expath = Strsave(pv[0]);
150 Vexpath = expath;
151
152 pathv = adrof(STRpath);
153 if (pathv == 0 && expath[0] != '/') {
154 blkfree(pv);
155 pexerr();
156 }
157 slash = any(short2str(expath), '/');
158
159 /*
160 * Glob the argument list, if necessary. Otherwise trim off the quote bits.
161 */
162 gflag = 0;
163 av = &t->t_dcom[1];
164 tglob(av);
165 if (gflag) {
166 av = globall(av);
167 if (av == 0) {
168 blkfree(pv);
169 setname(vis_str(expath));
170 stderror(ERR_NAME | ERR_NOMATCH);
171 }
172 gargv = 0;
173 }
174 else
175 av = saveblk(av);
176
177 blkfree(t->t_dcom);
178 t->t_dcom = blkspl(pv, av);
179 xfree((ptr_t) pv);
180 xfree((ptr_t) av);
181 av = t->t_dcom;
182 trim(av);
183
184 if (*av == NULL || **av == '\0')
185 pexerr();
186
187 xechoit(av); /* Echo command if -x */
188 /*
189 * Since all internal file descriptors are set to close on exec, we don't
190 * need to close them explicitly here. Just reorient ourselves for error
191 * messages.
192 */
193 SHIN = 0;
194 SHOUT = 1;
195 SHERR = 2;
196 OLDSTD = 0;
197 /*
198 * We must do this AFTER any possible forking (like `foo` in glob) so that
199 * this shell can still do subprocesses.
200 */
201 sigemptyset(&sigset);
202 (void)sigprocmask(SIG_SETMASK, &sigset, NULL);
203 /*
204 * If no path, no words in path, or a / in the filename then restrict the
205 * command search.
206 */
207 if (pathv == 0 || pathv->vec[0] == 0 || slash)
208 pv = justabs;
209 else
210 pv = pathv->vec;
211 sav = Strspl(STRslash, *av); /* / command name for postpending */
212 Vsav = sav;
213 if (havhash)
214 hashval = hashname(*av);
215 i = 0;
216 hits++;
217 do {
218 /*
219 * Try to save time by looking at the hash table for where this command
220 * could be. If we are doing delayed hashing, then we put the names in
221 * one at a time, as the user enters them. This is kinda like Korn
222 * Shell's "tracked aliases".
223 */
224 if (!slash && pv[0][0] == '/' && havhash) {
225 hashval1 = hash(hashval, i);
226 if (!bit(xhash, hashval1))
227 goto cont;
228 }
229 if (pv[0][0] == 0 || eq(pv[0], STRdot)) /* don't make ./xxx */
230 texec(*av, av);
231 else {
232 dp = Strspl(*pv, sav);
233 Vdp = dp;
234 texec(dp, av);
235 Vdp = 0;
236 xfree((ptr_t)dp);
237 }
238 misses++;
239 cont:
240 pv++;
241 i++;
242 } while (*pv);
243 hits--;
244 Vsav = 0;
245 xfree((ptr_t)sav);
246 pexerr();
247 /* NOTREACHED */
248 }
249
250 static void
251 pexerr(void)
252 {
253 /* Couldn't find the damn thing */
254 if (expath) {
255 setname(vis_str(expath));
256 Vexpath = 0;
257 xfree((ptr_t)expath);
258 expath = 0;
259 }
260 else
261 setname("");
262 if (exerr)
263 stderror(ERR_NAME | ERR_STRING, exerr);
264 else
265 stderror(ERR_NAME | ERR_COMMAND);
266 /* NOTREACHED */
267 }
268
269 /*
270 * Execute command f, arg list t.
271 * Record error message if not found.
272 * Also do shell scripts here.
273 */
274 static void
275 texec(Char *sf, Char **st)
276 {
277 struct varent *v;
278 Char *lastsh[2], **vp, *st0, **ost;
279 char *f, **t;
280 int fd;
281 unsigned char c;
282
283 /* The order for the conversions is significant */
284 t = short2blk(st);
285 f = short2str(sf);
286 Vt = t;
287 errno = 0; /* don't use a previous error */
288 (void)execve(f, t, environ);
289 Vt = 0;
290 blkfree((Char **)t);
291 switch (errno) {
292
293 case ENOEXEC:
294 /*
295 * From: casper (at) fwi.uva.nl (Casper H.S. Dik) If we could not execute
296 * it, don't feed it to the shell if it looks like a binary!
297 */
298 if ((fd = open(f, O_RDONLY)) != -1) {
299 if (read(fd, (char *)&c, 1) == 1) {
300 if (!Isprint(c) && (c != '\n' && c != '\t')) {
301 (void)close(fd);
302 /*
303 * We *know* what ENOEXEC means.
304 */
305 stderror(ERR_ARCH, f, strerror(errno));
306 }
307 }
308 #ifdef _PATH_BSHELL
309 else
310 c = '#';
311 #endif
312 (void)close(fd);
313 }
314 /*
315 * If there is an alias for shell, then put the words of the alias in
316 * front of the argument list replacing the command name. Note no
317 * interpretation of the words at this point.
318 */
319 v = adrof1(STRshell, &aliases);
320 if (v == 0) {
321 vp = lastsh;
322 vp[0] = adrof(STRshell) ? value(STRshell) : STR_SHELLPATH;
323 vp[1] = NULL;
324 #ifdef _PATH_BSHELL
325 if (fd != -1 && c != '#')
326 vp[0] = STR_BSHELL;
327 #endif
328 }
329 else
330 vp = v->vec;
331 st0 = st[0];
332 st[0] = sf;
333 ost = st;
334 st = blkspl(vp, st); /* Splice up the new arglst */
335 ost[0] = st0;
336 sf = *st;
337 /* The order for the conversions is significant */
338 t = short2blk(st);
339 f = short2str(sf);
340 xfree((ptr_t) st);
341 Vt = t;
342 (void)execve(f, t, environ);
343 Vt = 0;
344 blkfree((Char **) t);
345 /* FALLTHROUGH */
346
347 case ENOMEM:
348 stderror(ERR_SYSTEM, f, strerror(errno));
349 /* NOTREACHED */
350
351 case ENOENT:
352 break;
353
354 default:
355 if (exerr == 0) {
356 exerr = strerror(errno);
357 if (expath)
358 xfree((ptr_t) expath);
359 expath = Strsave(sf);
360 Vexpath = expath;
361 }
362 }
363 }
364
365 /*ARGSUSED*/
366 void
367 execash(Char **t, struct command *kp)
368 {
369 jmp_buf osetexit;
370 sig_t osigint, osigquit, osigterm;
371 int my_reenter, odidfds, oOLDSTD, oSHERR, oSHIN, oSHOUT;
372 int saveDIAG, saveIN, saveOUT, saveSTD;
373
374 if (chkstop == 0 && setintr)
375 panystop(0);
376 /*
377 * Hmm, we don't really want to do that now because we might
378 * fail, but what is the choice
379 */
380 rechist();
381
382 osigint = signal(SIGINT, parintr);
383 osigquit = signal(SIGQUIT, parintr);
384 osigterm = signal(SIGTERM, parterm);
385
386 odidfds = didfds;
387 oSHIN = SHIN;
388 oSHOUT = SHOUT;
389 oSHERR = SHERR;
390 oOLDSTD = OLDSTD;
391
392 saveIN = dcopy(SHIN, -1);
393 saveOUT = dcopy(SHOUT, -1);
394 saveDIAG = dcopy(SHERR, -1);
395 saveSTD = dcopy(OLDSTD, -1);
396
397 lshift(kp->t_dcom, 1);
398
399 getexit(osetexit);
400
401 if ((my_reenter = setexit()) == 0) {
402 SHIN = dcopy(0, -1);
403 SHOUT = dcopy(1, -1);
404 SHERR = dcopy(2, -1);
405 didfds = 0;
406 doexec(t, kp);
407 }
408
409 (void)signal(SIGINT, osigint);
410 (void)signal(SIGQUIT, osigquit);
411 (void)signal(SIGTERM, osigterm);
412
413 doneinp = 0;
414 didfds = odidfds;
415 (void)close(SHIN);
416 (void)close(SHOUT);
417 (void)close(SHERR);
418 (void)close(OLDSTD);
419 SHIN = dmove(saveIN, oSHIN);
420 SHOUT = dmove(saveOUT, oSHOUT);
421 SHERR = dmove(saveDIAG, oSHERR);
422 OLDSTD = dmove(saveSTD, oOLDSTD);
423
424 resexit(osetexit);
425 if (my_reenter)
426 stderror(ERR_SILENT);
427 }
428
429 void
430 xechoit(Char **t)
431 {
432 if (adrof(STRecho)) {
433 (void)fflush(csherr);
434 blkpr(csherr, t);
435 (void)fputc('\n', csherr);
436 }
437 }
438
439 void
440 /*ARGSUSED*/
441 dohash(Char **v, struct command *t)
442 {
443 struct dirent *dp;
444 struct varent *pathv;
445 DIR *dirp;
446 Char **pv;
447 int cnt, hashval, i;
448
449 i = 0;
450 havhash = 1;
451 pathv = adrof(STRpath);
452
453 for (cnt = 0; cnt < sizeof xhash; cnt++)
454 xhash[cnt] = 0;
455 if (pathv == 0)
456 return;
457 for (pv = pathv->vec; *pv; pv++, i++) {
458 if (pv[0][0] != '/')
459 continue;
460 dirp = opendir(short2str(*pv));
461 if (dirp == NULL)
462 continue;
463 while ((dp = readdir(dirp)) != NULL) {
464 if (dp->d_ino == 0)
465 continue;
466 if (dp->d_name[0] == '.' &&
467 (dp->d_name[1] == '\0' ||
468 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
469 continue;
470 hashval = hash(hashname(str2short(dp->d_name)), i);
471 bis(xhash, hashval);
472 /* tw_add_comm_name (dp->d_name); */
473 }
474 (void) closedir(dirp);
475 }
476 }
477
478 void
479 /*ARGSUSED*/
480 dounhash(Char **v, struct command *t)
481 {
482 havhash = 0;
483 }
484
485 void
486 /*ARGSUSED*/
487 hashstat(Char **v, struct command *t)
488 {
489 if (hits + misses)
490 (void)fprintf(cshout, "%d hits, %d misses, %d%%\n",
491 hits, misses, 100 * hits / (hits + misses));
492 }
493
494 /*
495 * Hash a command name.
496 */
497 static int
498 hashname(Char *cp)
499 {
500 long h = 0;
501
502 while (*cp)
503 h = hash(h, *cp++);
504 return ((int) h);
505 }
506
507 static int
508 iscommand(Char *name)
509 {
510 struct varent *v;
511 Char **pv, *sav;
512 int hashval, hashval1, i;
513 bool slash;
514
515 hashval = 0;
516 slash = any(short2str(name), '/');
517 v = adrof(STRpath);
518
519 if (v == 0 || v->vec[0] == 0 || slash)
520 pv = justabs;
521 else
522 pv = v->vec;
523 sav = Strspl(STRslash, name); /* / command name for postpending */
524 if (havhash)
525 hashval = hashname(name);
526 i = 0;
527 do {
528 if (!slash && pv[0][0] == '/' && havhash) {
529 hashval1 = hash(hashval, i);
530 if (!bit(xhash, hashval1))
531 goto cont;
532 }
533 if (pv[0][0] == 0 || eq(pv[0], STRdot)) { /* don't make ./xxx */
534 if (executable(NULL, name, 0)) {
535 xfree((ptr_t) sav);
536 return i + 1;
537 }
538 }
539 else {
540 if (executable(*pv, sav, 0)) {
541 xfree((ptr_t) sav);
542 return i + 1;
543 }
544 }
545 cont:
546 pv++;
547 i++;
548 } while (*pv);
549 xfree((ptr_t) sav);
550 return 0;
551 }
552
553 /* Also by:
554 * Andreas Luik <luik (at) isaak.isa.de>
555 * I S A GmbH - Informationssysteme fuer computerintegrierte Automatisierung
556 * Azenberstr. 35
557 * D-7000 Stuttgart 1
558 * West-Germany
559 * is the executable() routine below and changes to iscommand().
560 * Thanks again!!
561 */
562
563 /*
564 * executable() examines the pathname obtained by concatenating dir and name
565 * (dir may be NULL), and returns 1 either if it is executable by us, or
566 * if dir_ok is set and the pathname refers to a directory.
567 * This is a bit kludgy, but in the name of optimization...
568 */
569 static int
570 executable(Char *dir, Char *name, bool dir_ok)
571 {
572 struct stat stbuf;
573 Char path[MAXPATHLEN + 1], *dp, *sp;
574 char *strname;
575
576 if (dir && *dir) {
577 for (dp = path, sp = dir; *sp; *dp++ = *sp++)
578 if (dp == &path[MAXPATHLEN + 1]) {
579 *--dp = '\0';
580 break;
581 }
582 for (sp = name; *sp; *dp++ = *sp++)
583 if (dp == &path[MAXPATHLEN + 1]) {
584 *--dp = '\0';
585 break;
586 }
587 *dp = '\0';
588 strname = short2str(path);
589 }
590 else
591 strname = short2str(name);
592 return (stat(strname, &stbuf) != -1 && ((S_ISREG(stbuf.st_mode) &&
593 /* save time by not calling access() in the hopeless case */
594 (stbuf.st_mode & (S_IXOTH | S_IXGRP | S_IXUSR)) &&
595 access(strname, X_OK) == 0) || (dir_ok && S_ISDIR(stbuf.st_mode))));
596 }
597
598 /* The dowhich() is by:
599 * Andreas Luik <luik (at) isaak.isa.de>
600 * I S A GmbH - Informationssysteme fuer computerintegrierte Automatisierung
601 * Azenberstr. 35
602 * D-7000 Stuttgart 1
603 * West-Germany
604 * Thanks!!
605 */
606 /*ARGSUSED*/
607 void
608 dowhich(Char **v, struct command *c)
609 {
610 struct wordent lex[3];
611 struct varent *vp;
612
613 lex[0].next = &lex[1];
614 lex[1].next = &lex[2];
615 lex[2].next = &lex[0];
616
617 lex[0].prev = &lex[2];
618 lex[1].prev = &lex[0];
619 lex[2].prev = &lex[1];
620
621 lex[0].word = STRNULL;
622 lex[2].word = STRret;
623
624 while (*++v) {
625 if ((vp = adrof1(*v, &aliases)) != NULL) {
626 (void)fprintf(cshout, "%s: \t aliased to ", vis_str(*v));
627 blkpr(cshout, vp->vec);
628 (void)fputc('\n', cshout);
629 set(STRstatus, Strsave(STR0));
630 }
631 else {
632 lex[1].word = *v;
633 set(STRstatus, Strsave(tellmewhat(lex, NULL) ? STR0 : STR1));
634 }
635 }
636 }
637
638 static int
639 tellmewhat(struct wordent *lexp, Char *str)
640 {
641 struct biltins *bptr;
642 struct wordent *sp;
643 Char *cmd, *s0, *s1, *s2;
644 int i;
645 bool aliased, found;
646 Char qc;
647
648 aliased = 0;
649 sp = lexp->next;
650
651 if (adrof1(sp->word, &aliases)) {
652 alias(lexp);
653 sp = lexp->next;
654 aliased = 1;
655 }
656
657 s0 = sp->word; /* to get the memory freeing right... */
658
659 /* handle quoted alias hack */
660 if ((*(sp->word) & (QUOTE | TRIM)) == QUOTE)
661 (sp->word)++;
662
663 /* do quoting, if it hasn't been done */
664 s1 = s2 = sp->word;
665 while (*s2)
666 switch (*s2) {
667 case '\'':
668 case '"':
669 qc = *s2++;
670 while (*s2 && *s2 != qc)
671 *s1++ = *s2++ | QUOTE;
672 if (*s2)
673 s2++;
674 break;
675 case '\\':
676 if (*++s2)
677 *s1++ = *s2++ | QUOTE;
678 break;
679 default:
680 *s1++ = *s2++;
681 }
682 *s1 = '\0';
683
684 for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) {
685 if (eq(sp->word, str2short(bptr->bname))) {
686 if (str == NULL) {
687 if (aliased)
688 prlex(cshout, lexp);
689 (void)fprintf(cshout, "%s: shell built-in command.\n",
690 vis_str(sp->word));
691 }
692 else
693 (void)Strcpy(str, sp->word);
694 sp->word = s0; /* we save and then restore this */
695 return 1;
696 }
697 }
698
699 sp->word = cmd = globone(sp->word, G_IGNORE);
700
701 if ((i = iscommand(sp->word)) != 0) {
702 Char **pv;
703 struct varent *v;
704 bool slash = any(short2str(sp->word), '/');
705
706 v = adrof(STRpath);
707 if (v == 0 || v->vec[0] == 0 || slash)
708 pv = justabs;
709 else
710 pv = v->vec;
711
712 while (--i)
713 pv++;
714 if (pv[0][0] == 0 || eq(pv[0], STRdot)) {
715 if (!slash) {
716 sp->word = Strspl(STRdotsl, sp->word);
717 prlex(cshout, lexp);
718 xfree((ptr_t) sp->word);
719 }
720 else
721 prlex(cshout, lexp);
722 }
723 else {
724 s1 = Strspl(*pv, STRslash);
725 sp->word = Strspl(s1, sp->word);
726 xfree((ptr_t) s1);
727 if (str == NULL)
728 prlex(cshout, lexp);
729 else
730 (void)Strcpy(str, sp->word);
731 xfree((ptr_t) sp->word);
732 }
733 found = 1;
734 }
735 else {
736 if (str == NULL) {
737 if (aliased)
738 prlex(cshout, lexp);
739 (void)fprintf(csherr,
740 "%s: Command not found.\n", vis_str(sp->word));
741 }
742 else
743 (void)Strcpy(str, sp->word);
744 found = 0;
745 }
746 sp->word = s0; /* we save and then restore this */
747 xfree((ptr_t) cmd);
748 return found;
749 }
750