Add COMMAND_FD_{NULL,PASS}, deal with termios(4)..
[s-mailx.git] / popen.c
blobf7ddd8e204d8124b1655fe190f8b13a3a8a9f5ef
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Handling of pipes, child processes, temporary files, file enwrapping.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. 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.
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.
35 #undef n_FILE
36 #define n_FILE popen
38 #ifndef HAVE_AMALGAMATION
39 # include "nail.h"
40 #endif
42 #include <sys/wait.h>
44 #define READ 0
45 #define WRITE 1
47 struct fp {
48 FILE *fp;
49 struct fp *link;
50 char *realfile;
51 char *save_cmd;
52 long offset;
53 int omode;
54 int pipe;
55 int pid;
56 enum {
57 FP_RAW = 0,
58 FP_GZIP = 1<<0,
59 FP_XZ = 1<<1,
60 FP_BZIP2 = 1<<2,
61 FP_IMAP = 1<<3,
62 FP_MAILDIR = 1<<4,
63 FP_HOOK = 1<<5,
64 FP_MASK = (1<<6) - 1,
65 /* TODO FP_UNLINK: should be in a separated process so that unlinking
66 * TODO the temporary "garbage" is "safe"(r than it is like that) */
67 FP_UNLINK = 1<<6
68 } flags;
71 struct child {
72 int pid;
73 char done;
74 char free;
75 int status;
76 struct child *link;
79 static struct fp *fp_head;
80 static struct child *_popen_child;
82 /* TODO Rather temporary: deal with job control with FD_PASS */
83 static struct termios a_popen_tios;
84 static sighandler_type a_popen_otstp, a_popen_ottin, a_popen_ottou;
85 static volatile int a_popen_hadsig;
87 static int scan_mode(char const *mode, int *omode);
88 static void register_file(FILE *fp, int omode, int ispipe, int pid,
89 int flags, char const *realfile, long offset,
90 char const *save_cmd);
91 static enum okay _file_save(struct fp *fpp);
92 static int _file_load(int flags, int infd, int outfd,
93 char const *load_cmd);
94 static enum okay unregister_file(FILE *fp);
95 static int file_pid(FILE *fp);
97 /* TODO Rather temporary: deal with job control with FD_PASS */
98 static void a_popen_jobsigs_up(void);
99 static void a_popen_jobsigs_down(void);
100 static void a_popen_jobsig(int sig);
102 /* Handle SIGCHLD */
103 static void _sigchld(int signo);
105 static struct child *_findchild(int pid, bool_t create);
106 static void _delchild(struct child *cp);
108 static int
109 scan_mode(char const *mode, int *omode)
111 static struct {
112 char const mode[4];
113 int omode;
114 } const maps[] = {
115 {"r", O_RDONLY},
116 {"w", O_WRONLY | O_CREAT | O_TRUNC},
117 {"wx", O_WRONLY | O_CREAT | O_EXCL},
118 {"a", O_WRONLY | O_APPEND | O_CREAT},
119 {"a+", O_RDWR | O_APPEND},
120 {"r+", O_RDWR},
121 {"w+", O_RDWR | O_CREAT | O_EXCL}
124 int i;
125 NYD2_ENTER;
127 for (i = 0; UICMP(z, i, <, NELEM(maps)); ++i)
128 if (!strcmp(maps[i].mode, mode)) {
129 *omode = maps[i].omode;
130 i = 0;
131 goto jleave;
134 n_alert(_("Internal error: bad stdio open mode %s"), mode);
135 errno = EINVAL;
136 *omode = 0; /* (silence CC) */
137 i = -1;
138 jleave:
139 NYD2_LEAVE;
140 return i;
143 static void
144 register_file(FILE *fp, int omode, int ispipe, int pid, int flags,
145 char const *realfile, long offset, char const *save_cmd)
147 struct fp *fpp;
148 NYD_ENTER;
150 assert(!(flags & FP_UNLINK) || realfile != NULL);
152 fpp = smalloc(sizeof *fpp);
153 fpp->fp = fp;
154 fpp->omode = omode;
155 fpp->pipe = ispipe;
156 fpp->pid = pid;
157 fpp->link = fp_head;
158 fpp->flags = flags;
159 fpp->realfile = (realfile != NULL) ? sstrdup(realfile) : NULL;
160 fpp->save_cmd = (save_cmd != NULL) ? sstrdup(save_cmd) : NULL;
161 fpp->offset = offset;
162 fp_head = fpp;
163 NYD_LEAVE;
166 static enum okay
167 _file_save(struct fp *fpp)
169 char const *cmd[3];
170 int outfd, infd;
171 enum okay rv;
172 NYD_ENTER;
174 if (fpp->omode == O_RDONLY) {
175 rv = OKAY;
176 goto jleave;
178 rv = STOP;
180 fflush(fpp->fp);
181 clearerr(fpp->fp);
183 #ifdef HAVE_IMAP
184 if ((fpp->flags & FP_MASK) == FP_IMAP) {
185 rv = imap_append(fpp->realfile, fpp->fp);
186 goto jleave;
188 #endif
189 if ((fpp->flags & FP_MASK) == FP_MAILDIR) {
190 if (fseek(fpp->fp, fpp->offset, SEEK_SET) == -1) {
191 outfd = errno;
192 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
193 fpp->realfile, strerror(outfd));
194 goto jleave;
196 rv = maildir_append(fpp->realfile, fpp->fp, fpp->offset);
197 goto jleave;
200 /* Ensure the I/O library doesn't optimize the fseek(3) away! */
201 if(lseek(infd = fileno(fpp->fp), fpp->offset, SEEK_SET) == -1){
202 outfd = errno;
203 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
204 fpp->realfile, strerror(outfd));
205 goto jleave;
208 outfd = open(fpp->realfile,
209 ((fpp->omode | O_CREAT | (fpp->omode & O_APPEND ? 0 : O_TRUNC))
210 & ~O_EXCL), 0666);
211 if (outfd == -1) {
212 outfd = errno;
213 n_err(_("Fatal: cannot create %s: %s\n"),
214 fpp->realfile, strerror(outfd));
215 goto jleave;
218 cmd[2] = NULL;
219 switch (fpp->flags & FP_MASK) {
220 case FP_GZIP:
221 cmd[0] = "gzip"; cmd[1] = "-c"; break;
222 case FP_BZIP2:
223 cmd[0] = "bzip2"; cmd[1] = "-c"; break;
224 case FP_XZ:
225 cmd[0] = "xz"; cmd[1] = "-c"; break;
226 default:
227 cmd[0] = "cat"; cmd[1] = NULL; break;
228 case FP_HOOK:
229 if ((cmd[0] = ok_vlook(SHELL)) == NULL)
230 cmd[0] = XSHELL;
231 cmd[1] = "-c";
232 cmd[2] = fpp->save_cmd;
234 if (run_command(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL) >= 0)
235 rv = OKAY;
237 close(outfd);
238 jleave:
239 NYD_LEAVE;
240 return rv;
243 static int
244 _file_load(int flags, int infd, int outfd, char const *load_cmd)
246 char const *cmd[3];
247 int rv;
248 NYD_ENTER;
250 cmd[2] = NULL;
251 switch (flags & FP_MASK) {
252 case FP_GZIP: cmd[0] = "gzip"; cmd[1] = "-cd"; break;
253 case FP_BZIP2: cmd[0] = "bzip2"; cmd[1] = "-cd"; break;
254 case FP_XZ: cmd[0] = "xz"; cmd[1] = "-cd"; break;
255 default: cmd[0] = "cat"; cmd[1] = NULL; break;
256 case FP_HOOK:
257 if ((cmd[0] = ok_vlook(SHELL)) == NULL)
258 cmd[0] = XSHELL;
259 cmd[1] = "-c";
260 cmd[2] = load_cmd;
261 break;
262 case FP_MAILDIR:
263 case FP_IMAP:
264 rv = 0;
265 goto jleave;
268 rv = run_command(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL);
269 jleave:
270 NYD_LEAVE;
271 return rv;
274 static enum okay
275 unregister_file(FILE *fp)
277 struct fp **pp, *p;
278 enum okay rv = OKAY;
279 NYD_ENTER;
281 for (pp = &fp_head; (p = *pp) != NULL; pp = &p->link)
282 if (p->fp == fp) {
283 if ((p->flags & FP_MASK) != FP_RAW) /* TODO ;} */
284 rv = _file_save(p);
285 if (p->flags & FP_UNLINK && unlink(p->realfile))
286 rv = STOP;
287 *pp = p->link;
288 if (p->save_cmd != NULL)
289 free(p->save_cmd);
290 if (p->realfile != NULL)
291 free(p->realfile);
292 free(p);
293 goto jleave;
295 DBGOR(n_panic, n_alert)(_("Invalid file pointer"));
296 rv = STOP;
297 jleave:
298 NYD_LEAVE;
299 return rv;
302 static int
303 file_pid(FILE *fp)
305 int rv;
306 struct fp *p;
307 NYD2_ENTER;
309 rv = -1;
310 for (p = fp_head; p; p = p->link)
311 if (p->fp == fp) {
312 rv = p->pid;
313 break;
315 NYD2_LEAVE;
316 return rv;
319 static void
320 a_popen_jobsigs_up(void){
321 sigset_t nset, oset;
322 NYD2_ENTER;
324 sigfillset(&nset);
326 sigprocmask(SIG_BLOCK, &nset, &oset);
327 a_popen_otstp = safe_signal(SIGTSTP, &a_popen_jobsig);
328 a_popen_ottin = safe_signal(SIGTTIN, &a_popen_jobsig);
329 a_popen_ottou = safe_signal(SIGTTOU, &a_popen_jobsig);
331 /* This assumes oset contains nothing but SIGCHLD, so to say */
332 sigdelset(&oset, SIGTSTP);
333 sigdelset(&oset, SIGTTIN);
334 sigdelset(&oset, SIGTTOU);
335 sigprocmask(SIG_SETMASK, &oset, NULL);
336 NYD2_LEAVE;
339 static void
340 a_popen_jobsigs_down(void){
341 sigset_t nset, oset;
342 NYD2_ENTER;
344 sigfillset(&nset);
346 sigprocmask(SIG_BLOCK, &nset, &oset);
347 safe_signal(SIGTSTP, a_popen_otstp);
348 safe_signal(SIGTTIN, a_popen_ottin);
349 safe_signal(SIGTTOU, a_popen_ottou);
351 sigaddset(&oset, SIGTSTP);
352 sigaddset(&oset, SIGTTIN);
353 sigaddset(&oset, SIGTTOU);
354 sigprocmask(SIG_SETMASK, &oset, NULL);
355 NYD2_LEAVE;
358 static void
359 a_popen_jobsig(int sig){
360 sighandler_type oldact;
361 sigset_t nset;
362 bool_t hadsig;
363 NYD_X; /* Signal handler */
365 hadsig = (a_popen_hadsig != 0);
366 a_popen_hadsig = 1;
368 oldact = safe_signal(sig, SIG_DFL);
370 sigemptyset(&nset);
371 sigaddset(&nset, sig);
372 sigprocmask(SIG_UNBLOCK, &nset, NULL);
373 n_raise(sig);
374 sigprocmask(SIG_BLOCK, &nset, NULL);
376 safe_signal(sig, oldact);
379 static void
380 _sigchld(int signo)
382 pid_t pid;
383 int status;
384 struct child *cp;
385 NYD_X; /* Signal handler */
386 UNUSED(signo);
388 for (;;) {
389 pid = waitpid(-1, &status, WNOHANG);
390 if (pid <= 0) {
391 if (pid == -1 && errno == EINTR)
392 continue;
393 break;
396 if ((cp = _findchild(pid, FAL0)) != NULL) {
397 if (cp->free)
398 cp->pid = -1; /* XXX Was _delchild(cp);# */
399 else {
400 cp->done = 1;
401 cp->status = status;
407 static struct child *
408 _findchild(int pid, bool_t create)
410 struct child **cpp;
411 NYD_ENTER;
413 for (cpp = &_popen_child; *cpp != NULL && (*cpp)->pid != pid;
414 cpp = &(*cpp)->link)
417 if (*cpp == NULL && create) {
418 *cpp = smalloc(sizeof **cpp);
419 (*cpp)->pid = pid;
420 (*cpp)->done = (*cpp)->free = 0;
421 (*cpp)->link = NULL;
423 NYD_LEAVE;
424 return *cpp;
427 static void
428 _delchild(struct child *cp)
430 struct child **cpp;
431 NYD_ENTER;
433 cpp = &_popen_child;
434 for (;;) {
435 if (*cpp == cp) {
436 *cpp = cp->link;
437 free(cp);
438 break;
440 if (*(cpp = &(*cpp)->link) == NULL) {
441 DBG( n_err("! popen.c:_delchild(): implementation error\n"); )
442 break;
445 NYD_LEAVE;
448 FL void
449 command_manager_start(void)
451 struct sigaction nact, oact;
452 NYD_ENTER;
454 nact.sa_handler = &_sigchld;
455 sigemptyset(&nact.sa_mask);
456 nact.sa_flags = 0
457 #ifdef SA_RESTART
458 | SA_RESTART
459 #endif
460 #ifdef SA_NOCLDSTOP
461 | SA_NOCLDSTOP
462 #endif
464 if (sigaction(SIGCHLD, &nact, &oact) != 0)
465 n_panic(_("Cannot install signal handler for child process management"));
466 NYD_LEAVE;
469 FL FILE *
470 safe_fopen(char const *file, char const *oflags, int *xflags)
472 int osflags, fd;
473 FILE *fp = NULL;
474 NYD2_ENTER; /* (only for Fopen() and once in lex.c) */
476 if (scan_mode(oflags, &osflags) < 0)
477 goto jleave;
478 osflags |= _O_CLOEXEC;
479 if (xflags != NULL)
480 *xflags = osflags;
482 if ((fd = open(file, osflags, 0666)) == -1)
483 goto jleave;
484 _CLOEXEC_SET(fd);
486 fp = fdopen(fd, oflags);
487 jleave:
488 NYD2_LEAVE;
489 return fp;
492 FL FILE *
493 Fopen(char const *file, char const *oflags)
495 FILE *fp;
496 int osflags;
497 NYD_ENTER;
499 if ((fp = safe_fopen(file, oflags, &osflags)) != NULL)
500 register_file(fp, osflags, 0, 0, FP_RAW, NULL, 0L, NULL);
501 NYD_LEAVE;
502 return fp;
505 FL FILE *
506 Fdopen(int fd, char const *oflags, bool_t nocloexec)
508 FILE *fp;
509 int osflags;
510 NYD_ENTER;
512 scan_mode(oflags, &osflags);
513 if (!nocloexec)
514 osflags |= _O_CLOEXEC; /* Ensured to be set by caller as documented! */
516 if ((fp = fdopen(fd, oflags)) != NULL)
517 register_file(fp, osflags, 0, 0, FP_RAW, NULL, 0L, NULL);
518 NYD_LEAVE;
519 return fp;
522 FL int
523 Fclose(FILE *fp)
525 int i = 0;
526 NYD_ENTER;
528 if (unregister_file(fp) == OKAY)
529 i |= 1;
530 if (fclose(fp) == 0)
531 i |= 2;
532 NYD_LEAVE;
533 return (i == 3 ? 0 : EOF);
536 FL FILE *
537 Zopen(char const *file, char const *oflags) /* FIXME MESS! */
539 FILE *rv = NULL;
540 char const *cload = NULL, *csave = NULL;
541 int flags, osflags, mode, infd;
542 enum oflags rof;
543 long offset;
544 enum protocol p;
545 NYD_ENTER;
547 if (scan_mode(oflags, &osflags) < 0)
548 goto jleave;
550 flags = 0;
551 rof = OF_RDWR | OF_UNLINK;
552 if (osflags & O_APPEND)
553 rof |= OF_APPEND;
554 mode = (osflags == O_RDONLY) ? R_OK : R_OK | W_OK;
556 if ((osflags & O_APPEND) && ((p = which_protocol(file)) == PROTO_IMAP ||
557 p == PROTO_MAILDIR)) {
558 flags |= (p == PROTO_IMAP) ? FP_IMAP : FP_MAILDIR;
559 osflags = O_RDWR | O_APPEND | O_CREAT;
560 infd = -1;
561 } else {
562 char const *ext;
564 if ((ext = strrchr(file, '.')) != NULL) {
565 if (!asccasecmp(ext, ".gz"))
566 flags |= FP_GZIP;
567 else if (!asccasecmp(ext, ".xz")) {
568 flags |= FP_XZ;
569 osflags &= ~O_APPEND;
570 rof &= ~OF_APPEND;
571 } else if (!asccasecmp(ext, ".bz2")) {
572 flags |= FP_BZIP2;
573 osflags &= ~O_APPEND;
574 rof &= ~OF_APPEND;
575 } else {
576 #undef _X1
577 #define _X1 "file-hook-load-"
578 #undef _X2
579 #define _X2 "file-hook-save-"
580 size_t l = strlen(++ext);
581 char *vbuf = ac_alloc(l + MAX(sizeof(_X1), sizeof(_X2)));
583 memcpy(vbuf, _X1, sizeof(_X1) -1);
584 memcpy(vbuf + sizeof(_X1) -1, ext, l);
585 vbuf[sizeof(_X1) -1 + l] = '\0';
586 cload = vok_vlook(vbuf);
587 memcpy(vbuf, _X2, sizeof(_X2) -1);
588 memcpy(vbuf + sizeof(_X2) -1, ext, l);
589 vbuf[sizeof(_X2) -1 + l] = '\0';
590 csave = vok_vlook(vbuf);
591 #undef _X2
592 #undef _X1
593 ac_free(vbuf);
595 if ((csave != NULL) && (cload != NULL)) {
596 flags |= FP_HOOK;
597 osflags &= ~O_APPEND;
598 rof &= ~OF_APPEND;
599 } else if ((csave != NULL) | (cload != NULL)) {
600 n_alert(_("Only one of *mailbox-(load|save)-%s* is set! "
601 "Treating as plain text!"), ext);
602 goto jraw;
603 } else
604 goto jraw;
606 } else {
607 jraw:
608 /*flags |= FP_RAW;*/
609 rv = Fopen(file, oflags);
610 goto jleave;
613 if ((infd = open(file, (mode & W_OK) ? O_RDWR : O_RDONLY)) == -1 &&
614 (!(osflags & O_CREAT) || errno != ENOENT))
615 goto jleave;
618 /* Note rv is not yet register_file()d, fclose() it in error path! */
619 if ((rv = Ftmp(NULL, "zopen", rof, 0600)) == NULL) {
620 n_perr(_("tmpfile"), 0);
621 goto jerr;
624 if (flags & (FP_IMAP | FP_MAILDIR))
626 else if (infd >= 0) {
627 if (_file_load(flags, infd, fileno(rv), cload) < 0) {
628 jerr:
629 if (rv != NULL)
630 fclose(rv);
631 rv = NULL;
632 if (infd >= 0)
633 close(infd);
634 goto jleave;
636 } else {
637 if ((infd = creat(file, 0666)) == -1) {
638 fclose(rv);
639 rv = NULL;
640 goto jleave;
644 if (infd >= 0)
645 close(infd);
646 fflush(rv);
648 if (!(osflags & O_APPEND))
649 rewind(rv);
650 if ((offset = ftell(rv)) == -1) {
651 Fclose(rv);
652 rv = NULL;
653 goto jleave;
656 register_file(rv, osflags, 0, 0, flags, file, offset, csave);
657 jleave:
658 NYD_LEAVE;
659 return rv;
662 FL FILE *
663 Ftmp(char **fn, char const *prefix, enum oflags oflags, int mode)
665 FILE *fp = NULL;
666 size_t maxname, tries;
667 char *cp_base, *cp;
668 int osoflags, fd, e;
669 NYD_ENTER;
671 assert((oflags & OF_WRONLY) || (oflags & OF_RDWR));
672 assert(!(oflags & OF_RDONLY));
673 assert(!(oflags & OF_REGISTER_UNLINK) || (oflags & OF_REGISTER));
675 e = 0;
676 maxname = NAME_MAX;
677 #ifdef HAVE_PATHCONF
678 { long pc;
680 if ((pc = pathconf(tempdir, _PC_NAME_MAX)) != -1)
681 maxname = (size_t)pc;
683 #endif
685 cp_base =
686 cp = smalloc(strlen(tempdir) + 1 + maxname +1);
687 cp = sstpcpy(cp, tempdir);
688 *cp++ = '/';
690 osoflags = O_CREAT | O_EXCL | _O_CLOEXEC;
691 osoflags |= (oflags & OF_WRONLY) ? O_WRONLY : O_RDWR;
692 if (oflags & OF_APPEND)
693 osoflags |= O_APPEND;
695 for (tries = 0;; ++tries) {
696 size_t i;
697 char *x;
699 x = sstpcpy(cp, UAGENT);
700 *x++ = '-';
701 if (*prefix != '\0') {
702 x = sstpcpy(x, prefix);
703 *x++ = '-';
706 /* Calculate length of a random string addon */
707 i = PTR2SIZE(x - cp);
708 if (i >= maxname >> 1) {
709 x = cp;
710 i = maxname -1;
711 } else
712 i = maxname >> 1;
713 /* But don't be too fatalistic */
714 if (i > 8 && tries < FTMP_OPEN_TRIES / 2)
715 i = 8;
716 memcpy(x, getrandstring(i), i +1);
718 hold_all_sigs();
719 if ((fd = open(cp_base, osoflags, mode)) != -1) {
720 _CLOEXEC_SET(fd);
721 break;
723 if (tries >= FTMP_OPEN_TRIES) {
724 e = errno;
725 goto jfree;
727 rele_all_sigs();
730 if (oflags & OF_REGISTER) {
731 char const *osflags = (oflags & OF_RDWR ? "w+" : "w");
732 int osflagbits;
734 scan_mode(osflags, &osflagbits); /* TODO osoflags&xy ?!!? */
735 if ((fp = fdopen(fd, osflags)) != NULL)
736 register_file(fp, osflagbits | _O_CLOEXEC, 0, 0,
737 (FP_RAW | (oflags & OF_REGISTER_UNLINK ? FP_UNLINK : 0)),
738 cp_base, 0L, NULL);
739 } else
740 fp = fdopen(fd, (oflags & OF_RDWR ? "w+" : "w"));
742 if (fp == NULL || (oflags & OF_UNLINK)) {
743 e = errno;
744 unlink(cp_base);
745 goto jfree;
748 if (fn != NULL)
749 *fn = cp_base;
750 else
751 free(cp_base);
752 jleave:
753 if (fp == NULL || !(oflags & OF_HOLDSIGS))
754 rele_all_sigs();
755 if (fp == NULL)
756 errno = e;
757 NYD_LEAVE;
758 return fp;
759 jfree:
760 if ((cp = cp_base) != NULL)
761 free(cp);
762 goto jleave;
765 FL void
766 Ftmp_release(char **fn)
768 char *cp;
769 NYD_ENTER;
771 cp = *fn;
772 *fn = NULL;
773 if (cp != NULL) {
774 unlink(cp);
775 rele_all_sigs();
776 free(cp);
778 NYD_LEAVE;
781 FL void
782 Ftmp_free(char **fn)
784 char *cp;
785 NYD_ENTER;
787 cp = *fn;
788 *fn = NULL;
789 if (cp != NULL)
790 free(cp);
791 NYD_LEAVE;
794 FL bool_t
795 pipe_cloexec(int fd[2])
797 bool_t rv = FAL0;
798 NYD_ENTER;
800 #ifdef HAVE_PIPE2
801 if (pipe2(fd, O_CLOEXEC) == -1)
802 goto jleave;
803 #else
804 if (pipe(fd) == -1)
805 goto jleave;
806 (void)fcntl(fd[0], F_SETFD, FD_CLOEXEC);
807 (void)fcntl(fd[1], F_SETFD, FD_CLOEXEC);
808 #endif
809 rv = TRU1;
810 jleave:
811 NYD_LEAVE;
812 return rv;
815 FL FILE *
816 Popen(char const *cmd, char const *mode, char const *sh,
817 char const **env_addon, int newfd1)
819 int p[2], myside, hisside, fd0, fd1, pid;
820 char mod[2] = {'0', '\0'};
821 sigset_t nset;
822 FILE *rv = NULL;
823 NYD_ENTER;
825 /* First clean up child structures */
826 { sigset_t oset;
827 struct child **cpp, *cp;
829 sigfillset(&nset);
830 sigprocmask(SIG_BLOCK, &nset, &oset);
832 for (cpp = &_popen_child; *cpp != NULL;) {
833 if ((*cpp)->pid == -1) {
834 cp = *cpp;
835 *cpp = cp->link;
836 free(cp);
837 } else
838 cpp = &(*cpp)->link;
841 sigprocmask(SIG_SETMASK, &oset, NULL);
844 if (!pipe_cloexec(p))
845 goto jleave;
847 if (*mode == 'r') {
848 myside = p[READ];
849 fd0 = -1;
850 hisside = fd1 = p[WRITE];
851 mod[0] = *mode;
852 } else if (*mode == 'W') {
853 myside = p[WRITE];
854 hisside = fd0 = p[READ];
855 fd1 = newfd1;
856 mod[0] = 'w';
857 } else {
858 myside = p[WRITE];
859 hisside = fd0 = p[READ];
860 fd1 = -1;
861 mod[0] = 'w';
864 sigemptyset(&nset);
866 if (cmd == (char*)-1) {
867 if ((pid = fork_child()) == -1)
868 n_perr(_("fork"), 0);
869 else if (pid == 0) {
870 union {char const *ccp; int (*ptf)(void); int es;} u;
871 prepare_child(&nset, fd0, fd1);
872 close(p[READ]);
873 close(p[WRITE]);
874 u.ccp = sh;
875 u.es = (*u.ptf)();
876 _exit(u.es);
878 } else if (sh == NULL) {
879 pid = start_command(cmd, &nset, fd0, fd1, NULL, NULL, NULL, env_addon);
880 } else {
881 pid = start_command(sh, &nset, fd0, fd1, "-c", cmd, NULL, env_addon);
883 if (pid < 0) {
884 close(p[READ]);
885 close(p[WRITE]);
886 goto jleave;
888 close(hisside);
889 if ((rv = fdopen(myside, mod)) != NULL)
890 register_file(rv, 0, 1, pid, FP_RAW, NULL, 0L, NULL);
891 else
892 close(myside);
893 jleave:
894 NYD_LEAVE;
895 return rv;
898 FL bool_t
899 Pclose(FILE *ptr, bool_t dowait)
901 sigset_t nset, oset;
902 int pid;
903 bool_t rv = FAL0;
904 NYD_ENTER;
906 pid = file_pid(ptr);
907 if (pid < 0)
908 goto jleave;
909 unregister_file(ptr);
910 fclose(ptr);
911 if (dowait) {
912 sigemptyset(&nset);
913 sigaddset(&nset, SIGINT);
914 sigaddset(&nset, SIGHUP);
915 sigprocmask(SIG_BLOCK, &nset, &oset);
916 rv = wait_child(pid, NULL);
917 sigprocmask(SIG_SETMASK, &oset, NULL);
918 } else {
919 free_child(pid);
920 rv = TRU1;
922 jleave:
923 NYD_LEAVE;
924 return rv;
927 FL void
928 close_all_files(void)
930 NYD_ENTER;
931 while (fp_head != NULL)
932 if (fp_head->pipe)
933 Pclose(fp_head->fp, TRU1);
934 else
935 Fclose(fp_head->fp);
936 NYD_LEAVE;
939 FL int
940 fork_child(void)
942 struct child *cp;
943 int pid;
944 NYD_ENTER;
946 cp = _findchild(0, TRU1);
948 if ((cp->pid = pid = fork()) == -1) {
949 _delchild(cp);
950 n_perr(_("fork"), 0);
952 NYD_LEAVE;
953 return pid;
956 FL int
957 run_command(char const *cmd, sigset_t *mask, int infd, int outfd,
958 char const *a0, char const *a1, char const *a2, char const **env_addon)
960 sigset_t nset, oset;
961 bool_t tio_set;
962 int rv;
963 NYD_ENTER;
965 /* TODO Of course this is a joke given that during a "p*" the PAGER may
966 * TODO be up and running while we play around like this... but i guess
967 * TODO this can't be helped at all unless we perform complete and true
968 * TODO process group separation and ensure we don't deadlock us out
969 * TODO via TTY jobcontrol signal storms (could this really happen?).
970 * TODO Or have a builtin pager. Or query any necessity BEFORE we start
971 * TODO any action, and shall we find we need to run programs dump it
972 * TODO all into a temporary file which is then passed through to the
973 * TODO PAGER. Ugh. That still won't help for "needsterminal" anyway */
974 if ((tio_set = ((options & OPT_INTERACTIVE) &&
975 (infd == COMMAND_FD_PASS || outfd == COMMAND_FD_PASS)))) {
976 tcgetattr((options & OPT_TTYIN ? STDIN_FILENO : STDOUT_FILENO), &a_popen_tios);
977 sigfillset(&nset);
978 sigdelset(&nset, SIGCHLD);
979 /* sigdelset(&nset, SIGPIPE); TODO would need a handler */
980 sigprocmask(SIG_BLOCK, &nset, &oset);
981 a_popen_hadsig = 0;
982 a_popen_jobsigs_up();
985 if ((rv = start_command(cmd, mask, infd, outfd, a0, a1, a2, env_addon)) < 0)
986 rv = -1;
987 else {
988 if (wait_child(rv, NULL))
989 rv = 0;
990 else {
991 if (ok_blook(bsdcompat) || ok_blook(bsdmsgs))
992 n_err(_("Fatal error in process\n"));
993 rv = -1;
997 if (tio_set) {
998 a_popen_jobsigs_down();
999 tio_set = ((options & OPT_TTYIN) != 0);
1000 tcsetattr((tio_set ? STDIN_FILENO : STDOUT_FILENO),
1001 (tio_set ? TCSAFLUSH : TCSADRAIN), &a_popen_tios);
1002 sigprocmask(SIG_SETMASK, &oset, NULL);
1004 NYD_LEAVE;
1005 return rv;
1008 FL int
1009 start_command(char const *cmd, sigset_t *mask, int infd, int outfd,
1010 char const *a0, char const *a1, char const *a2,
1011 char const **env_addon)
1013 int rv;
1014 NYD_ENTER;
1016 if ((rv = fork_child()) == -1) {
1017 n_perr(_("fork"), 0);
1018 rv = -1;
1019 } else if (rv == 0) {
1020 char *argv[128];
1021 int i;
1023 if (env_addon != NULL) { /* TODO env_addon; should have struct child */
1024 extern char **environ;
1025 size_t ei, ei_orig, ai, ai_orig;
1026 char **env;
1028 /* TODO note we don't check the POSIX limit:
1029 * the total space used to store the environment and the arguments to
1030 * the process is limited to {ARG_MAX} bytes */
1031 for (ei = 0; environ[ei] != NULL; ++ei)
1033 ei_orig = ei;
1034 for (ai = 0; env_addon[ai] != NULL; ++ai)
1036 ai_orig = ai;
1037 env = ac_alloc(sizeof(*env) * (ei + ai +1));
1038 memcpy(env, environ, sizeof(*env) * ei);
1040 /* Replace all those keys that yet exist */
1041 while (ai-- > 0) {
1042 char const *ee, *kvs;
1043 size_t kl;
1045 ee = env_addon[ai];
1046 kvs = strchr(ee, '=');
1047 assert(kvs != NULL);
1048 kl = PTR2SIZE(kvs - ee);
1049 assert(kl > 0);
1050 for (ei = ei_orig; ei-- > 0;) {
1051 char const *ekvs = strchr(env[ei], '=');
1052 if (ekvs != NULL && kl == PTR2SIZE(ekvs - env[ei]) &&
1053 !memcmp(ee, env[ei], kl)) {
1054 env[ei] = UNCONST(ee);
1055 env_addon[ai] = NULL;
1056 break;
1061 /* And append the rest */
1062 for (ei = ei_orig, ai = ai_orig; ai-- > 0;)
1063 if (env_addon[ai] != NULL)
1064 env[ei++] = UNCONST(env_addon[ai]);
1066 env[ei] = NULL;
1067 environ = env;
1070 i = getrawlist(cmd, strlen(cmd), argv, NELEM(argv), 0);
1072 if ((argv[i++] = UNCONST(a0)) != NULL &&
1073 (argv[i++] = UNCONST(a1)) != NULL &&
1074 (argv[i++] = UNCONST(a2)) != NULL)
1075 argv[i] = NULL;
1076 prepare_child(mask, infd, outfd);
1077 execvp(argv[0], argv);
1078 perror(argv[0]);
1079 _exit(EXIT_ERR);
1081 NYD_LEAVE;
1082 return rv;
1085 FL void
1086 prepare_child(sigset_t *nset, int infd, int outfd)
1088 int i;
1089 sigset_t fset;
1090 NYD_ENTER;
1092 /* All file descriptors other than 0, 1, and 2 are supposed to be cloexec */
1093 /* TODO WHAT IS WITH STDERR_FILENO DAMN? */
1094 if ((i = (infd == COMMAND_FD_NULL)))
1095 infd = open("/dev/null", O_RDONLY);
1096 if (infd >= 0) {
1097 dup2(infd, STDIN_FILENO);
1098 if (i)
1099 close(infd);
1102 if ((i = (outfd == COMMAND_FD_NULL)))
1103 outfd = open("/dev/null", O_WRONLY);
1104 if (outfd >= 0) {
1105 dup2(outfd, STDOUT_FILENO);
1106 if (i)
1107 close(outfd);
1110 if (nset) {
1111 for (i = 1; i < NSIG; ++i)
1112 if (sigismember(nset, i))
1113 safe_signal(i, SIG_IGN);
1114 if (!sigismember(nset, SIGINT))
1115 safe_signal(SIGINT, SIG_DFL);
1118 sigemptyset(&fset);
1119 sigprocmask(SIG_SETMASK, &fset, NULL);
1120 NYD_LEAVE;
1123 FL void
1124 free_child(int pid)
1126 sigset_t nset, oset;
1127 struct child *cp;
1128 NYD_ENTER;
1130 sigemptyset(&nset);
1131 sigaddset(&nset, SIGCHLD);
1132 sigprocmask(SIG_BLOCK, &nset, &oset);
1134 if ((cp = _findchild(pid, FAL0)) != NULL) {
1135 if (cp->done)
1136 _delchild(cp);
1137 else
1138 cp->free = 1;
1141 sigprocmask(SIG_SETMASK, &oset, NULL);
1142 NYD_LEAVE;
1145 FL bool_t
1146 wait_child(int pid, int *wait_status)
1148 sigset_t nset, oset;
1149 struct child *cp;
1150 int ws;
1151 bool_t rv;
1152 NYD_ENTER;
1154 sigemptyset(&nset);
1155 sigaddset(&nset, SIGCHLD);
1156 sigprocmask(SIG_BLOCK, &nset, &oset);
1158 cp = _findchild(pid, FAL0);
1159 if (cp != NULL) {
1160 while (!cp->done)
1161 sigsuspend(&oset);
1162 ws = cp->status;
1163 _delchild(cp);
1164 } else
1165 ws = 0;
1167 sigprocmask(SIG_SETMASK, &oset, NULL);
1169 if (wait_status != NULL)
1170 *wait_status = ws;
1171 rv = (WIFEXITED(ws) && WEXITSTATUS(ws) == 0);
1172 NYD_LEAVE;
1173 return rv;
1176 /* s-it-mode */