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