xref: /openbsd-src/bin/csh/sem.c (revision b05220827cf0816361ac08bbd1ba47907bab4f49)
1 /*	$OpenBSD: sem.c,v 1.25 2024/08/20 23:40:39 guenther Exp $	*/
2 /*	$NetBSD: sem.c,v 1.9 1995/09/27 00:38:50 jtc Exp $	*/
3 
4 /*-
5  * Copyright (c) 1980, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <limits.h>
41 #include <stdarg.h>
42 
43 #include "csh.h"
44 #include "proc.h"
45 #include "extern.h"
46 
47 static void	 vffree(int);
48 static Char	*splicepipe(struct command *t, Char *);
49 static void	 doio(struct command *t, int *, int *);
50 static void	 chkclob(char *);
51 
52 void
53 execute(struct command *t, int wanttty, int *pipein, int *pipeout)
54 {
55     bool    forked = 0;
56     struct biltins *bifunc;
57     int     pid = 0;
58     int     pv[2];
59     sigset_t sigset;
60 
61     static sigset_t csigset;
62 
63     static sigset_t ocsigset;
64     static int onosigchld = 0;
65     static int nosigchld = 0;
66 
67     UNREGISTER(forked);
68     UNREGISTER(bifunc);
69     UNREGISTER(wanttty);
70 
71     if (t == 0)
72 	return;
73 
74     if (t->t_dflg & F_AMPERSAND)
75 	wanttty = 0;
76     switch (t->t_dtyp) {
77 
78     case NODE_COMMAND:
79 	if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE)
80 	    (void) memmove(t->t_dcom[0], t->t_dcom[0] + 1,
81 		(Strlen(t->t_dcom[0] + 1) + 1) * sizeof(Char));
82 	if ((t->t_dflg & F_REPEAT) == 0)
83 	    Dfix(t);		/* $ " ' \ */
84 	if (t->t_dcom[0] == 0)
85 	    return;
86 	/* fall into... */
87 
88     case NODE_PAREN:
89 	if (t->t_dflg & F_PIPEOUT)
90 	    mypipe(pipeout);
91 	/*
92 	 * Must do << early so parent will know where input pointer should be.
93 	 * If noexec then this is all we do.
94 	 */
95 	if (t->t_dflg & F_READ) {
96 	    (void) close(0);
97 	    heredoc(t->t_dlef);
98 	    if (noexec)
99 		(void) close(0);
100 	}
101 
102 	set(STRstatus, Strsave(STR0));
103 
104 	/*
105 	 * This mess is the necessary kludge to handle the prefix builtins:
106 	 * nice, nohup, time.  These commands can also be used by themselves,
107 	 * and this is not handled here. This will also work when loops are
108 	 * parsed.
109 	 */
110 	while (t->t_dtyp == NODE_COMMAND)
111 	    if (eq(t->t_dcom[0], STRnice))
112 		if (t->t_dcom[1])
113 		    if (strchr("+-", t->t_dcom[1][0]))
114 			if (t->t_dcom[2]) {
115 			    setname("nice");
116 			    t->t_nice =
117 				getn(t->t_dcom[1]);
118 			    lshift(t->t_dcom, 2);
119 			    t->t_dflg |= F_NICE;
120 			}
121 			else
122 			    break;
123 		    else {
124 			t->t_nice = 4;
125 			lshift(t->t_dcom, 1);
126 			t->t_dflg |= F_NICE;
127 		    }
128 		else
129 		    break;
130 	    else if (eq(t->t_dcom[0], STRnohup))
131 		if (t->t_dcom[1]) {
132 		    t->t_dflg |= F_NOHUP;
133 		    lshift(t->t_dcom, 1);
134 		}
135 		else
136 		    break;
137 	    else if (eq(t->t_dcom[0], STRtime))
138 		if (t->t_dcom[1]) {
139 		    t->t_dflg |= F_TIME;
140 		    lshift(t->t_dcom, 1);
141 		}
142 		else
143 		    break;
144 	    else
145 		break;
146 
147 	/* is it a command */
148 	if (t->t_dtyp == NODE_COMMAND) {
149 	    /*
150 	     * Check if we have a builtin function and remember which one.
151 	     */
152 	    bifunc = isbfunc(t);
153 	    if (noexec) {
154 		/*
155 		 * Continue for builtins that are part of the scripting language
156 		 */
157 		if (bifunc &&
158 		    bifunc->bfunct != dobreak   && bifunc->bfunct != docontin &&
159 		    bifunc->bfunct != doelse    && bifunc->bfunct != doend    &&
160 		    bifunc->bfunct != doforeach && bifunc->bfunct != dogoto   &&
161 		    bifunc->bfunct != doif      && bifunc->bfunct != dorepeat &&
162 		    bifunc->bfunct != doswbrk   && bifunc->bfunct != doswitch &&
163 		    bifunc->bfunct != dowhile   && bifunc->bfunct != dozip)
164 		    break;
165 	    }
166 	}
167 	else {			/* not a command */
168 	    bifunc = NULL;
169 	    if (noexec)
170 		break;
171 	}
172 
173 	/*
174 	 * We fork only if we are timed, or are not the end of a parenthesized
175 	 * list and not a simple builtin function. Simple meaning one that is
176 	 * not pipedout, niced, nohupped, or &'d. It would be nice(?) to not
177 	 * fork in some of these cases.
178 	 */
179 	/*
180 	 * Prevent forking cd, pushd, popd, chdir cause this will cause the
181 	 * shell not to change dir!
182 	 */
183 	if (bifunc && (bifunc->bfunct == dochngd ||
184 		       bifunc->bfunct == dopushd ||
185 		       bifunc->bfunct == dopopd))
186 	    t->t_dflg &= ~(F_NICE);
187 	if (((t->t_dflg & F_TIME) || ((t->t_dflg & F_NOFORK) == 0 &&
188 	     (!bifunc || t->t_dflg &
189 	      (F_PIPEOUT | F_AMPERSAND | F_NICE | F_NOHUP)))) ||
190 	/*
191 	 * We have to fork for eval too.
192 	 */
193 	    (bifunc && (t->t_dflg & (F_PIPEIN | F_PIPEOUT)) != 0 &&
194 	     bifunc->bfunct == doeval)) {
195 	    if (t->t_dtyp == NODE_PAREN ||
196 		t->t_dflg & (F_REPEAT | F_AMPERSAND) || bifunc) {
197 		forked++;
198 		/*
199 		 * We need to block SIGCHLD/SIGHUP here, so that if the process does
200 		 * not die before we can set the process group
201 		 */
202 		if (wanttty >= 0 && !nosigchld) {
203 		    sigemptyset(&sigset);
204 		    sigaddset(&sigset, SIGCHLD);
205 		    sigaddset(&sigset, SIGHUP);
206 		    sigprocmask(SIG_BLOCK, &sigset, &csigset);
207 		    nosigchld = 1;
208 		}
209 
210 		pid = pfork(t, wanttty);
211 		if (pid == 0 && nosigchld) {
212 		    sigprocmask(SIG_SETMASK, &csigset, NULL);
213 		    nosigchld = 0;
214 		}
215 		else if (pid != 0 && (t->t_dflg & F_AMPERSAND))
216 		    backpid = pid;
217 
218 	    }
219 	    else {
220 		int     ochild, osetintr, ohaderr, odidfds;
221 		int     oSHIN, oSHOUT, oSHERR, oOLDSTD, otpgrp;
222 		sigset_t osigset;
223 
224 		/*
225 		 * Prepare for the vfork by saving everything that the child
226 		 * corrupts before it exec's. Note that in some signal
227 		 * implementations which keep the signal info in user space
228 		 * (e.g. Sun's) it will also be necessary to save and restore
229 		 * the current sigaction's for the signals the child touches
230 		 * before it exec's.
231 		 */
232 		if (wanttty >= 0 && !nosigchld && !noexec) {
233 		    sigemptyset(&sigset);
234 		    sigaddset(&sigset, SIGCHLD);
235 		    sigaddset(&sigset, SIGHUP);
236 		    sigprocmask(SIG_BLOCK, &sigset, &csigset);
237 		    nosigchld = 1;
238 		}
239 		sigemptyset(&sigset);
240 		sigaddset(&sigset, SIGCHLD);
241 		sigaddset(&sigset, SIGHUP);
242 		sigaddset(&sigset, SIGINT);
243 		sigprocmask(SIG_BLOCK, &sigset, &osigset);
244 		ochild = child;
245 		osetintr = setintr;
246 		ohaderr = haderr;
247 		odidfds = didfds;
248 		oSHIN = SHIN;
249 		oSHOUT = SHOUT;
250 		oSHERR = SHERR;
251 		oOLDSTD = OLDSTD;
252 		otpgrp = tpgrp;
253 		ocsigset = csigset;
254 		onosigchld = nosigchld;
255 		Vsav = Vdp = NULL;
256 		Vexpath = 0;
257 		Vt = 0;
258 		pid = vfork();
259 
260 		if (pid == -1) {
261 		    sigprocmask(SIG_SETMASK, &osigset, NULL);
262 		    stderror(ERR_NOPROC);
263 		}
264 		forked++;
265 		if (pid) {	/* parent */
266 		    child = ochild;
267 		    setintr = osetintr;
268 		    haderr = ohaderr;
269 		    didfds = odidfds;
270 		    SHIN = oSHIN;
271 		    SHOUT = oSHOUT;
272 		    SHERR = oSHERR;
273 		    OLDSTD = oOLDSTD;
274 		    tpgrp = otpgrp;
275 		    csigset = ocsigset;
276 		    nosigchld = onosigchld;
277 
278 		    free(Vsav);
279 		    Vsav = NULL;
280 		    free(Vdp);
281 		    Vdp = NULL;
282 		    free(Vexpath);
283 		    Vexpath = NULL;
284 		    blkfree((Char **) Vt);
285 		    Vt = NULL;
286 		    /* this is from pfork() */
287 		    palloc(pid, t);
288 		    sigprocmask(SIG_SETMASK, &osigset, NULL);
289 		}
290 		else {		/* child */
291 		    /* this is from pfork() */
292 		    int     pgrp;
293 		    bool    ignint = 0;
294 
295 		    if (nosigchld) {
296 			sigprocmask(SIG_SETMASK, &csigset, NULL);
297 			nosigchld = 0;
298 		    }
299 
300 		    if (setintr)
301 			ignint =
302 			    (tpgrp == -1 &&
303 			     (t->t_dflg & F_NOINTERRUPT))
304 			    || (gointr && eq(gointr, STRminus));
305 		    pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
306 		    child++;
307 		    if (setintr) {
308 			setintr = 0;
309 			if (ignint) {
310 			    (void) signal(SIGINT, SIG_IGN);
311 			    (void) signal(SIGQUIT, SIG_IGN);
312 			}
313 			else {
314 			    (void) signal(SIGINT, vffree);
315 			    (void) signal(SIGQUIT, SIG_DFL);
316 			}
317 
318 			if (wanttty >= 0) {
319 			    (void) signal(SIGTSTP, SIG_DFL);
320 			    (void) signal(SIGTTIN, SIG_DFL);
321 			    (void) signal(SIGTTOU, SIG_DFL);
322 			}
323 
324 			(void) signal(SIGTERM, parterm);
325 		    }
326 		    else if (tpgrp == -1 &&
327 			     (t->t_dflg & F_NOINTERRUPT)) {
328 			(void) signal(SIGINT, SIG_IGN);
329 			(void) signal(SIGQUIT, SIG_IGN);
330 		    }
331 
332 		    pgetty(wanttty, pgrp);
333 		    if (t->t_dflg & F_NOHUP)
334 			(void) signal(SIGHUP, SIG_IGN);
335 		    if (t->t_dflg & F_NICE)
336 			(void) setpriority(PRIO_PROCESS, 0, t->t_nice);
337 		}
338 
339 	    }
340 	}
341 	if (pid != 0) {
342 	    /*
343 	     * It would be better if we could wait for the whole job when we
344 	     * knew the last process had been started.  Pwait, in fact, does
345 	     * wait for the whole job anyway, but this test doesn't really
346 	     * express our intentions.
347 	     */
348 	    if (didfds == 0 && t->t_dflg & F_PIPEIN) {
349 		(void) close(pipein[0]);
350 		(void) close(pipein[1]);
351 	    }
352 	    if ((t->t_dflg & F_PIPEOUT) == 0) {
353 		if (nosigchld) {
354 		    sigprocmask(SIG_SETMASK, &csigset, NULL);
355 		    nosigchld = 0;
356 		}
357 		if ((t->t_dflg & F_AMPERSAND) == 0)
358 		    pwait();
359 	    }
360 	    break;
361 	}
362 	doio(t, pipein, pipeout);
363 	if (t->t_dflg & F_PIPEOUT) {
364 	    (void) close(pipeout[0]);
365 	    (void) close(pipeout[1]);
366 	}
367 	/*
368 	 * Perform a builtin function. If we are not forked, arrange for
369 	 * possible stopping
370 	 */
371 	if (bifunc) {
372 	    func(t, bifunc);
373 	    if (forked)
374 		exitstat();
375 	    break;
376 	}
377 	if (t->t_dtyp != NODE_PAREN) {
378 	    doexec(NULL, t);
379 	    /* NOTREACHED */
380 	}
381 	/*
382 	 * For () commands must put new 0,1,2 in FSH* and recurse
383 	 */
384 	OLDSTD = dcopy(0, FOLDSTD);
385 	SHOUT = dcopy(1, FSHOUT);
386 	SHERR = dcopy(2, FSHERR);
387 	(void) close(SHIN);
388 	SHIN = -1;
389 	didfds = 0;
390 	wanttty = -1;
391 	t->t_dspr->t_dflg |= t->t_dflg & F_NOINTERRUPT;
392 	execute(t->t_dspr, wanttty, NULL, NULL);
393 	exitstat();
394 
395     case NODE_PIPE:
396 	t->t_dcar->t_dflg |= F_PIPEOUT |
397 	    (t->t_dflg & (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT));
398 	execute(t->t_dcar, wanttty, pipein, pv);
399 	t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg &
400 			(F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT));
401 	if (wanttty > 0)
402 	    wanttty = 0;	/* got tty already */
403 	execute(t->t_dcdr, wanttty, pv, pipeout);
404 	break;
405 
406     case NODE_LIST:
407 	if (t->t_dcar) {
408 	    t->t_dcar->t_dflg |= t->t_dflg & F_NOINTERRUPT;
409 	    execute(t->t_dcar, wanttty, NULL, NULL);
410 	    /*
411 	     * In strange case of A&B make a new job after A
412 	     */
413 	    if (t->t_dcar->t_dflg & F_AMPERSAND && t->t_dcdr &&
414 		(t->t_dcdr->t_dflg & F_AMPERSAND) == 0)
415 		pendjob();
416 	}
417 	if (t->t_dcdr) {
418 	    t->t_dcdr->t_dflg |= t->t_dflg &
419 		(F_NOFORK | F_NOINTERRUPT);
420 	    execute(t->t_dcdr, wanttty, NULL, NULL);
421 	}
422 	break;
423 
424     case NODE_OR:
425     case NODE_AND:
426 	if (t->t_dcar) {
427 	    t->t_dcar->t_dflg |= t->t_dflg & F_NOINTERRUPT;
428 	    execute(t->t_dcar, wanttty, NULL, NULL);
429 	    if ((getn(value(STRstatus)) == 0) !=
430 		(t->t_dtyp == NODE_AND))
431 		return;
432 	}
433 	if (t->t_dcdr) {
434 	    t->t_dcdr->t_dflg |= t->t_dflg &
435 		(F_NOFORK | F_NOINTERRUPT);
436 	    execute(t->t_dcdr, wanttty, NULL, NULL);
437 	}
438 	break;
439     }
440     /*
441      * Fall through for all breaks from switch
442      *
443      * If there will be no more executions of this command, flush all file
444      * descriptors. Places that turn on the F_REPEAT bit are responsible for
445      * doing donefds after the last re-execution
446      */
447     if (didfds && !(t->t_dflg & F_REPEAT))
448 	donefds();
449 }
450 
451 static void
452 vffree(int i)
453 {
454     _exit(i);
455 }
456 
457 /*
458  * Expand and glob the words after an i/o redirection.
459  * If more than one word is generated, then update the command vector.
460  *
461  * This is done differently in all the shells:
462  * 1. in the bourne shell and ksh globbing is not performed
463  * 2. Bash/csh say ambiguous
464  * 3. zsh does i/o to/from all the files
465  * 4. itcsh concatenates the words.
466  *
467  * I don't know what is best to do. I think that Ambiguous is better
468  * than restructuring the command vector, because the user can get
469  * unexpected results. In any case, the command vector restructuring
470  * code is present and the user can choose it by setting noambiguous
471  */
472 static Char *
473 splicepipe(struct command *t, Char *cp) /* word after < or > */
474 {
475     Char *blk[2];
476 
477     if (adrof(STRnoambiguous)) {
478 	Char **pv;
479 
480 	blk[0] = Dfix1(cp); /* expand $ */
481 	blk[1] = NULL;
482 
483 	gflag = 0, tglob(blk);
484 	if (gflag) {
485 	    pv = globall(blk);
486 	    if (pv == NULL) {
487 		setname(vis_str(blk[0]));
488 		free(blk[0]);
489 		stderror(ERR_NAME | ERR_NOMATCH);
490 	    }
491 	    gargv = NULL;
492 	    if (pv[1] != NULL) { /* we need to fix the command vector */
493 		Char **av = blkspl(t->t_dcom, &pv[1]);
494 		free(t->t_dcom);
495 		t->t_dcom = av;
496 	    }
497 	    free(blk[0]);
498 	    blk[0] = pv[0];
499 	    free(pv);
500 	}
501     }
502     else {
503 	blk[0] = globone(blk[1] = Dfix1(cp), G_ERROR);
504 	free(blk[1]);
505     }
506     return(blk[0]);
507 }
508 
509 /*
510  * Perform io redirection.
511  * We may or maynot be forked here.
512  */
513 static void
514 doio(struct command *t, int *pipein, int *pipeout)
515 {
516     int fd;
517     Char *cp;
518     int flags = t->t_dflg;
519 
520     if (didfds || (flags & F_REPEAT))
521 	return;
522     if ((flags & F_READ) == 0) {/* F_READ already done */
523 	if (t->t_dlef) {
524 	    char    tmp[PATH_MAX];
525 
526 	    /*
527 	     * so < /dev/std{in,out,err} work
528 	     */
529 	    (void) dcopy(SHIN, 0);
530 	    (void) dcopy(SHOUT, 1);
531 	    (void) dcopy(SHERR, 2);
532 	    cp = splicepipe(t, t->t_dlef);
533 	    strlcpy(tmp, short2str(cp), sizeof tmp);
534 	    free(cp);
535 	    if ((fd = open(tmp, O_RDONLY)) == -1)
536 		stderror(ERR_SYSTEM, tmp, strerror(errno));
537 	    (void) dmove(fd, 0);
538 	}
539 	else if (flags & F_PIPEIN) {
540 	    (void) dup2(pipein[0], 0);
541 	    (void) close(pipein[0]);
542 	    (void) close(pipein[1]);
543 	}
544 	else if ((flags & F_NOINTERRUPT) && tpgrp == -1) {
545 	    (void) close(0);
546 	    (void) open(_PATH_DEVNULL, O_RDONLY);
547 	}
548 	else {
549 	    (void) dup2(OLDSTD, 0);
550 	}
551     }
552     if (t->t_drit) {
553 	char    tmp[PATH_MAX];
554 
555 	cp = splicepipe(t, t->t_drit);
556 	strlcpy(tmp, short2str(cp), sizeof tmp);
557 	free(cp);
558 	/*
559 	 * so > /dev/std{out,err} work
560 	 */
561 	(void) dcopy(SHOUT, 1);
562 	(void) dcopy(SHERR, 2);
563 	if ((flags & F_APPEND) &&
564 	    (fd = open(tmp, O_WRONLY | O_APPEND)) >= 0);
565 	else {
566 	    if (!(flags & F_OVERWRITE) && adrof(STRnoclobber)) {
567 		if (flags & F_APPEND)
568 		    stderror(ERR_SYSTEM, tmp, strerror(errno));
569 		chkclob(tmp);
570 	    }
571 	    if ((fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)
572 		stderror(ERR_SYSTEM, tmp, strerror(errno));
573 	}
574 	(void) dmove(fd, 1);
575     }
576     else if (flags & F_PIPEOUT) {
577 	(void) dup2(pipeout[1], 1);
578     }
579     else {
580 	(void) dup2(SHOUT, 1);
581     }
582 
583     if (flags & F_STDERR) {
584 	(void) dup2(1, 2);
585     }
586     else {
587 	(void) dup2(SHERR, 2);
588     }
589     didfds = 1;
590 }
591 
592 void
593 mypipe(int *pv)
594 {
595 
596     if (pipe(pv) == -1)
597 	goto oops;
598     pv[0] = dmove(pv[0], -1);
599     pv[1] = dmove(pv[1], -1);
600     if (pv[0] >= 0 && pv[1] >= 0)
601 	return;
602 oops:
603     stderror(ERR_PIPE);
604 }
605 
606 static void
607 chkclob(char *cp)
608 {
609     struct stat stb;
610 
611     if (stat(cp, &stb) == -1)
612 	return;
613     if (S_ISCHR(stb.st_mode))
614 	return;
615     stderror(ERR_EXISTS, cp);
616 }
617