Merge branch 'topic/notsupp'
[s-mailx.git] / popen.c
blobb672c19acabdc2b554a61cda3a76b91336b714f3
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_MAILDIR = 1<<4,
62 FP_HOOK = 1<<5,
63 FP_MASK = (1<<6) - 1,
64 /* TODO FP_UNLINK: should be in a separated process so that unlinking
65 * TODO the temporary "garbage" is "safe"(r than it is like that) */
66 FP_UNLINK = 1<<6
67 } flags;
70 struct child {
71 int pid;
72 char done;
73 char free;
74 int status;
75 struct child *link;
78 static struct fp *fp_head;
79 static struct child *_popen_child;
81 /* TODO Rather temporary: deal with job control with FD_PASS */
82 static struct termios a_popen_tios;
83 static sighandler_type a_popen_otstp, a_popen_ottin, a_popen_ottou;
84 static volatile int a_popen_hadsig;
86 static int scan_mode(char const *mode, int *omode);
87 static void register_file(FILE *fp, int omode, int ispipe, int pid,
88 int flags, char const *realfile, long offset,
89 char const *save_cmd);
90 static enum okay _file_save(struct fp *fpp);
91 static int _file_load(int flags, int infd, int outfd,
92 char const *load_cmd);
93 static enum okay unregister_file(FILE *fp);
94 static int file_pid(FILE *fp);
96 /* TODO Rather temporary: deal with job control with FD_PASS */
97 static void a_popen_jobsigs_up(void);
98 static void a_popen_jobsigs_down(void);
99 static void a_popen_jobsig(int sig);
101 /* Handle SIGCHLD */
102 static void _sigchld(int signo);
104 static struct child *_findchild(int pid, bool_t create);
105 static void _delchild(struct child *cp);
107 static int
108 scan_mode(char const *mode, int *omode)
110 static struct {
111 char const mode[4];
112 int omode;
113 } const maps[] = {
114 {"r", O_RDONLY},
115 {"w", O_WRONLY | O_CREAT | O_TRUNC},
116 {"wx", O_WRONLY | O_CREAT | O_EXCL},
117 {"a", O_WRONLY | O_APPEND | O_CREAT},
118 {"a+", O_RDWR | O_APPEND},
119 {"r+", O_RDWR},
120 {"w+", O_RDWR | O_CREAT | O_EXCL}
123 int i;
124 NYD2_ENTER;
126 for (i = 0; UICMP(z, i, <, NELEM(maps)); ++i)
127 if (!strcmp(maps[i].mode, mode)) {
128 *omode = maps[i].omode;
129 i = 0;
130 goto jleave;
133 n_alert(_("Internal error: bad stdio open mode %s"), mode);
134 errno = EINVAL;
135 *omode = 0; /* (silence CC) */
136 i = -1;
137 jleave:
138 NYD2_LEAVE;
139 return i;
142 static void
143 register_file(FILE *fp, int omode, int ispipe, int pid, int flags,
144 char const *realfile, long offset, char const *save_cmd)
146 struct fp *fpp;
147 NYD_ENTER;
149 assert(!(flags & FP_UNLINK) || realfile != NULL);
151 fpp = smalloc(sizeof *fpp);
152 fpp->fp = fp;
153 fpp->omode = omode;
154 fpp->pipe = ispipe;
155 fpp->pid = pid;
156 fpp->link = fp_head;
157 fpp->flags = flags;
158 fpp->realfile = (realfile != NULL) ? sstrdup(realfile) : NULL;
159 fpp->save_cmd = (save_cmd != NULL) ? sstrdup(save_cmd) : NULL;
160 fpp->offset = offset;
161 fp_head = fpp;
162 NYD_LEAVE;
165 static enum okay
166 _file_save(struct fp *fpp)
168 char const *cmd[3];
169 int outfd, infd;
170 enum okay rv;
171 NYD_ENTER;
173 if (fpp->omode == O_RDONLY) {
174 rv = OKAY;
175 goto jleave;
177 rv = STOP;
179 fflush(fpp->fp);
180 clearerr(fpp->fp);
182 if ((fpp->flags & FP_MASK) == FP_MAILDIR) {
183 if (fseek(fpp->fp, fpp->offset, SEEK_SET) == -1) {
184 outfd = errno;
185 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
186 fpp->realfile, strerror(outfd));
187 goto jleave;
189 rv = maildir_append(fpp->realfile, fpp->fp, fpp->offset);
190 goto jleave;
193 /* Ensure the I/O library doesn't optimize the fseek(3) away! */
194 if(lseek(infd = fileno(fpp->fp), fpp->offset, SEEK_SET) == -1){
195 outfd = errno;
196 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
197 fpp->realfile, strerror(outfd));
198 goto jleave;
201 outfd = open(fpp->realfile,
202 ((fpp->omode | O_CREAT | (fpp->omode & O_APPEND ? 0 : O_TRUNC))
203 & ~O_EXCL), 0666);
204 if (outfd == -1) {
205 outfd = errno;
206 n_err(_("Fatal: cannot create %s: %s\n"),
207 fpp->realfile, strerror(outfd));
208 goto jleave;
211 cmd[2] = NULL;
212 switch (fpp->flags & FP_MASK) {
213 case FP_GZIP:
214 cmd[0] = "gzip"; cmd[1] = "-c"; break;
215 case FP_BZIP2:
216 cmd[0] = "bzip2"; cmd[1] = "-c"; break;
217 case FP_XZ:
218 cmd[0] = "xz"; cmd[1] = "-c"; break;
219 default:
220 cmd[0] = "cat"; cmd[1] = NULL; break;
221 case FP_HOOK:
222 if ((cmd[0] = ok_vlook(SHELL)) == NULL)
223 cmd[0] = XSHELL;
224 cmd[1] = "-c";
225 cmd[2] = fpp->save_cmd;
227 if (run_command(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL) >= 0)
228 rv = OKAY;
230 close(outfd);
231 jleave:
232 NYD_LEAVE;
233 return rv;
236 static int
237 _file_load(int flags, int infd, int outfd, char const *load_cmd)
239 char const *cmd[3];
240 int rv;
241 NYD_ENTER;
243 cmd[2] = NULL;
244 switch (flags & FP_MASK) {
245 case FP_GZIP: cmd[0] = "gzip"; cmd[1] = "-cd"; break;
246 case FP_BZIP2: cmd[0] = "bzip2"; cmd[1] = "-cd"; break;
247 case FP_XZ: cmd[0] = "xz"; cmd[1] = "-cd"; break;
248 default: cmd[0] = "cat"; cmd[1] = NULL; break;
249 case FP_HOOK:
250 if ((cmd[0] = ok_vlook(SHELL)) == NULL)
251 cmd[0] = XSHELL;
252 cmd[1] = "-c";
253 cmd[2] = load_cmd;
254 break;
255 case FP_MAILDIR:
256 rv = 0;
257 goto jleave;
260 rv = run_command(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL);
261 jleave:
262 NYD_LEAVE;
263 return rv;
266 static enum okay
267 unregister_file(FILE *fp)
269 struct fp **pp, *p;
270 enum okay rv = OKAY;
271 NYD_ENTER;
273 for (pp = &fp_head; (p = *pp) != NULL; pp = &p->link)
274 if (p->fp == fp) {
275 if ((p->flags & FP_MASK) != FP_RAW) /* TODO ;} */
276 rv = _file_save(p);
277 if (p->flags & FP_UNLINK && unlink(p->realfile))
278 rv = STOP;
279 *pp = p->link;
280 if (p->save_cmd != NULL)
281 free(p->save_cmd);
282 if (p->realfile != NULL)
283 free(p->realfile);
284 free(p);
285 goto jleave;
287 DBGOR(n_panic, n_alert)(_("Invalid file pointer"));
288 rv = STOP;
289 jleave:
290 NYD_LEAVE;
291 return rv;
294 static int
295 file_pid(FILE *fp)
297 int rv;
298 struct fp *p;
299 NYD2_ENTER;
301 rv = -1;
302 for (p = fp_head; p; p = p->link)
303 if (p->fp == fp) {
304 rv = p->pid;
305 break;
307 NYD2_LEAVE;
308 return rv;
311 static void
312 a_popen_jobsigs_up(void){
313 sigset_t nset, oset;
314 NYD2_ENTER;
316 sigfillset(&nset);
318 sigprocmask(SIG_BLOCK, &nset, &oset);
319 a_popen_otstp = safe_signal(SIGTSTP, &a_popen_jobsig);
320 a_popen_ottin = safe_signal(SIGTTIN, &a_popen_jobsig);
321 a_popen_ottou = safe_signal(SIGTTOU, &a_popen_jobsig);
323 /* This assumes oset contains nothing but SIGCHLD, so to say */
324 sigdelset(&oset, SIGTSTP);
325 sigdelset(&oset, SIGTTIN);
326 sigdelset(&oset, SIGTTOU);
327 sigprocmask(SIG_SETMASK, &oset, NULL);
328 NYD2_LEAVE;
331 static void
332 a_popen_jobsigs_down(void){
333 sigset_t nset, oset;
334 NYD2_ENTER;
336 sigfillset(&nset);
338 sigprocmask(SIG_BLOCK, &nset, &oset);
339 safe_signal(SIGTSTP, a_popen_otstp);
340 safe_signal(SIGTTIN, a_popen_ottin);
341 safe_signal(SIGTTOU, a_popen_ottou);
343 sigaddset(&oset, SIGTSTP);
344 sigaddset(&oset, SIGTTIN);
345 sigaddset(&oset, SIGTTOU);
346 sigprocmask(SIG_SETMASK, &oset, NULL);
347 NYD2_LEAVE;
350 static void
351 a_popen_jobsig(int sig){
352 sighandler_type oldact;
353 sigset_t nset;
354 bool_t hadsig;
355 NYD_X; /* Signal handler */
357 hadsig = (a_popen_hadsig != 0);
358 a_popen_hadsig = 1;
360 oldact = safe_signal(sig, SIG_DFL);
362 sigemptyset(&nset);
363 sigaddset(&nset, sig);
364 sigprocmask(SIG_UNBLOCK, &nset, NULL);
365 n_raise(sig);
366 sigprocmask(SIG_BLOCK, &nset, NULL);
368 safe_signal(sig, oldact);
371 static void
372 _sigchld(int signo)
374 pid_t pid;
375 int status;
376 struct child *cp;
377 NYD_X; /* Signal handler */
378 UNUSED(signo);
380 for (;;) {
381 pid = waitpid(-1, &status, WNOHANG);
382 if (pid <= 0) {
383 if (pid == -1 && errno == EINTR)
384 continue;
385 break;
388 if ((cp = _findchild(pid, FAL0)) != NULL) {
389 if (cp->free)
390 cp->pid = -1; /* XXX Was _delchild(cp);# */
391 else {
392 cp->done = 1;
393 cp->status = status;
399 static struct child *
400 _findchild(int pid, bool_t create)
402 struct child **cpp;
403 NYD_ENTER;
405 for (cpp = &_popen_child; *cpp != NULL && (*cpp)->pid != pid;
406 cpp = &(*cpp)->link)
409 if (*cpp == NULL && create) {
410 *cpp = smalloc(sizeof **cpp);
411 (*cpp)->pid = pid;
412 (*cpp)->done = (*cpp)->free = 0;
413 (*cpp)->link = NULL;
415 NYD_LEAVE;
416 return *cpp;
419 static void
420 _delchild(struct child *cp)
422 struct child **cpp;
423 NYD_ENTER;
425 cpp = &_popen_child;
426 for (;;) {
427 if (*cpp == cp) {
428 *cpp = cp->link;
429 free(cp);
430 break;
432 if (*(cpp = &(*cpp)->link) == NULL) {
433 DBG( n_err("! popen.c:_delchild(): implementation error\n"); )
434 break;
437 NYD_LEAVE;
440 FL void
441 command_manager_start(void)
443 struct sigaction nact, oact;
444 NYD_ENTER;
446 nact.sa_handler = &_sigchld;
447 sigemptyset(&nact.sa_mask);
448 nact.sa_flags = 0
449 #ifdef SA_RESTART
450 | SA_RESTART
451 #endif
452 #ifdef SA_NOCLDSTOP
453 | SA_NOCLDSTOP
454 #endif
456 if (sigaction(SIGCHLD, &nact, &oact) != 0)
457 n_panic(_("Cannot install signal handler for child process management"));
458 NYD_LEAVE;
461 FL FILE *
462 safe_fopen(char const *file, char const *oflags, int *xflags)
464 int osflags, fd;
465 FILE *fp = NULL;
466 NYD2_ENTER; /* (only for Fopen() and once in lex.c) */
468 if (scan_mode(oflags, &osflags) < 0)
469 goto jleave;
470 osflags |= _O_CLOEXEC;
471 if (xflags != NULL)
472 *xflags = osflags;
474 if ((fd = open(file, osflags, 0666)) == -1)
475 goto jleave;
476 _CLOEXEC_SET(fd);
478 fp = fdopen(fd, oflags);
479 jleave:
480 NYD2_LEAVE;
481 return fp;
484 FL FILE *
485 Fopen(char const *file, char const *oflags)
487 FILE *fp;
488 int osflags;
489 NYD_ENTER;
491 if ((fp = safe_fopen(file, oflags, &osflags)) != NULL)
492 register_file(fp, osflags, 0, 0, FP_RAW, NULL, 0L, NULL);
493 NYD_LEAVE;
494 return fp;
497 FL FILE *
498 Fdopen(int fd, char const *oflags, bool_t nocloexec)
500 FILE *fp;
501 int osflags;
502 NYD_ENTER;
504 scan_mode(oflags, &osflags);
505 if (!nocloexec)
506 osflags |= _O_CLOEXEC; /* Ensured to be set by caller as documented! */
508 if ((fp = fdopen(fd, oflags)) != NULL)
509 register_file(fp, osflags, 0, 0, FP_RAW, NULL, 0L, NULL);
510 NYD_LEAVE;
511 return fp;
514 FL int
515 Fclose(FILE *fp)
517 int i = 0;
518 NYD_ENTER;
520 if (unregister_file(fp) == OKAY)
521 i |= 1;
522 if (fclose(fp) == 0)
523 i |= 2;
524 NYD_LEAVE;
525 return (i == 3 ? 0 : EOF);
528 FL FILE *
529 Zopen(char const *file, char const *oflags) /* FIXME MESS! */
531 FILE *rv = NULL;
532 char const *cload = NULL, *csave = NULL;
533 int flags, osflags, mode, infd;
534 enum oflags rof;
535 long offset;
536 enum protocol p;
537 NYD_ENTER;
539 if (scan_mode(oflags, &osflags) < 0)
540 goto jleave;
542 flags = 0;
543 rof = OF_RDWR | OF_UNLINK;
544 if (osflags & O_APPEND)
545 rof |= OF_APPEND;
546 mode = (osflags == O_RDONLY) ? R_OK : R_OK | W_OK;
548 if ((osflags & O_APPEND) && ((p = which_protocol(file)) == PROTO_MAILDIR)) {
549 flags |= FP_MAILDIR;
550 osflags = O_RDWR | O_APPEND | O_CREAT;
551 infd = -1;
552 } else {
553 char const *ext;
555 if ((ext = strrchr(file, '.')) != NULL) {
556 if (!asccasecmp(ext, ".gz"))
557 flags |= FP_GZIP;
558 else if (!asccasecmp(ext, ".xz")) {
559 flags |= FP_XZ;
560 osflags &= ~O_APPEND;
561 rof &= ~OF_APPEND;
562 } else if (!asccasecmp(ext, ".bz2")) {
563 flags |= FP_BZIP2;
564 osflags &= ~O_APPEND;
565 rof &= ~OF_APPEND;
566 } else {
567 #undef _X1
568 #define _X1 "file-hook-load-"
569 #undef _X2
570 #define _X2 "file-hook-save-"
571 size_t l = strlen(++ext);
572 char *vbuf = ac_alloc(l + MAX(sizeof(_X1), sizeof(_X2)));
574 memcpy(vbuf, _X1, sizeof(_X1) -1);
575 memcpy(vbuf + sizeof(_X1) -1, ext, l);
576 vbuf[sizeof(_X1) -1 + l] = '\0';
577 cload = vok_vlook(vbuf);
578 memcpy(vbuf, _X2, sizeof(_X2) -1);
579 memcpy(vbuf + sizeof(_X2) -1, ext, l);
580 vbuf[sizeof(_X2) -1 + l] = '\0';
581 csave = vok_vlook(vbuf);
582 #undef _X2
583 #undef _X1
584 ac_free(vbuf);
586 if ((csave != NULL) && (cload != NULL)) {
587 flags |= FP_HOOK;
588 osflags &= ~O_APPEND;
589 rof &= ~OF_APPEND;
590 } else if ((csave != NULL) | (cload != NULL)) {
591 n_alert(_("Only one of *mailbox-(load|save)-%s* is set! "
592 "Treating as plain text!"), ext);
593 goto jraw;
594 } else
595 goto jraw;
597 } else {
598 jraw:
599 /*flags |= FP_RAW;*/
600 rv = Fopen(file, oflags);
601 goto jleave;
604 if ((infd = open(file, (mode & W_OK) ? O_RDWR : O_RDONLY)) == -1 &&
605 (!(osflags & O_CREAT) || errno != ENOENT))
606 goto jleave;
609 /* Note rv is not yet register_file()d, fclose() it in error path! */
610 if ((rv = Ftmp(NULL, "zopen", rof)) == NULL) {
611 n_perr(_("tmpfile"), 0);
612 goto jerr;
615 if (flags & FP_MAILDIR)
617 else if (infd >= 0) {
618 if (_file_load(flags, infd, fileno(rv), cload) < 0) {
619 jerr:
620 if (rv != NULL)
621 fclose(rv);
622 rv = NULL;
623 if (infd >= 0)
624 close(infd);
625 goto jleave;
627 } else {
628 if ((infd = creat(file, 0666)) == -1) {
629 fclose(rv);
630 rv = NULL;
631 goto jleave;
635 if (infd >= 0)
636 close(infd);
637 fflush(rv);
639 if (!(osflags & O_APPEND))
640 rewind(rv);
641 if ((offset = ftell(rv)) == -1) {
642 Fclose(rv);
643 rv = NULL;
644 goto jleave;
647 register_file(rv, osflags, 0, 0, flags, file, offset, csave);
648 jleave:
649 NYD_LEAVE;
650 return rv;
653 FL FILE *
654 Ftmp(char **fn, char const *namehint, enum oflags oflags)
656 /* The 8 is arbitrary but leaves room for a six character suffix (the
657 * POSIX minimum path length is 14, though we don't check that XXX).
658 * 8 should be more than sufficient given that we use base64url encoding
659 * for our random string */
660 enum {_RANDCHARS = 8};
662 size_t maxname, xlen, i;
663 char *cp_base, *cp;
664 int osoflags, fd, e;
665 bool_t relesigs;
666 FILE *fp;
667 NYD_ENTER;
669 assert(namehint != NULL);
670 assert((oflags & OF_WRONLY) || (oflags & OF_RDWR));
671 assert(!(oflags & OF_RDONLY));
672 assert(!(oflags & OF_REGISTER_UNLINK) || (oflags & OF_REGISTER));
674 fp = NULL;
675 relesigs = FAL0;
676 e = 0;
677 maxname = NAME_MAX;
678 #ifdef HAVE_PATHCONF
679 { long pc;
681 if ((pc = pathconf(tempdir, _PC_NAME_MAX)) != -1)
682 maxname = (size_t)pc;
684 #endif
686 if ((oflags & OF_SUFFIX) && *namehint != '\0') {
687 if ((xlen = strlen(namehint)) > maxname - _RANDCHARS) {
688 errno = ENAMETOOLONG;
689 goto jleave;
691 } else
692 xlen = 0;
694 /* Prepare the template string once, then iterate over the random range */
695 cp_base =
696 cp = smalloc(strlen(tempdir) + 1 + maxname +1);
697 cp = sstpcpy(cp, tempdir);
698 *cp++ = '/';
700 char *x = sstpcpy(cp, UAGENT);
701 *x++ = '-';
702 if (!(oflags & OF_SUFFIX))
703 x = sstpcpy(x, namehint);
705 i = PTR2SIZE(x - cp);
706 if (i > maxname - xlen - _RANDCHARS) {
707 size_t j = maxname - xlen - _RANDCHARS;
708 x -= i - j;
709 i = j;
712 if ((oflags & OF_SUFFIX) && xlen > 0)
713 memcpy(x + _RANDCHARS, namehint, xlen);
715 x[xlen + _RANDCHARS] = '\0';
716 cp = x;
719 osoflags = O_CREAT | O_EXCL | _O_CLOEXEC;
720 osoflags |= (oflags & OF_WRONLY) ? O_WRONLY : O_RDWR;
721 if (oflags & OF_APPEND)
722 osoflags |= O_APPEND;
724 for (i = 0;; ++i) {
725 memcpy(cp, getrandstring(_RANDCHARS), _RANDCHARS);
727 hold_all_sigs();
728 relesigs = TRU1;
730 if ((fd = open(cp_base, osoflags, 0600)) != -1) {
731 _CLOEXEC_SET(fd);
732 break;
734 if (i >= FTMP_OPEN_TRIES) {
735 e = errno;
736 goto jfree;
738 relesigs = FAL0;
739 rele_all_sigs();
742 if (oflags & OF_REGISTER) {
743 char const *osflags = (oflags & OF_RDWR ? "w+" : "w");
744 int osflagbits;
746 scan_mode(osflags, &osflagbits); /* TODO osoflags&xy ?!!? */
747 if ((fp = fdopen(fd, osflags)) != NULL)
748 register_file(fp, osflagbits | _O_CLOEXEC, 0, 0,
749 (FP_RAW | (oflags & OF_REGISTER_UNLINK ? FP_UNLINK : 0)),
750 cp_base, 0L, NULL);
751 } else
752 fp = fdopen(fd, (oflags & OF_RDWR ? "w+" : "w"));
754 if (fp == NULL || (oflags & OF_UNLINK)) {
755 e = errno;
756 unlink(cp_base);
757 goto jfree;
760 if (fn != NULL)
761 *fn = cp_base;
762 else
763 free(cp_base);
764 jleave:
765 if (relesigs && (fp == NULL || !(oflags & OF_HOLDSIGS)))
766 rele_all_sigs();
767 if (fp == NULL)
768 errno = e;
769 NYD_LEAVE;
770 return fp;
771 jfree:
772 if ((cp = cp_base) != NULL)
773 free(cp);
774 goto jleave;
777 FL void
778 Ftmp_release(char **fn)
780 char *cp;
781 NYD_ENTER;
783 cp = *fn;
784 *fn = NULL;
785 if (cp != NULL) {
786 unlink(cp);
787 rele_all_sigs();
788 free(cp);
790 NYD_LEAVE;
793 FL void
794 Ftmp_free(char **fn) /* TODO DROP: OF_REGISTER_FREEPATH! */
796 char *cp;
797 NYD_ENTER;
799 cp = *fn;
800 *fn = NULL;
801 if (cp != NULL)
802 free(cp);
803 NYD_LEAVE;
806 FL bool_t
807 pipe_cloexec(int fd[2])
809 bool_t rv = FAL0;
810 NYD_ENTER;
812 #ifdef HAVE_PIPE2
813 if (pipe2(fd, O_CLOEXEC) == -1)
814 goto jleave;
815 #else
816 if (pipe(fd) == -1)
817 goto jleave;
818 (void)fcntl(fd[0], F_SETFD, FD_CLOEXEC);
819 (void)fcntl(fd[1], F_SETFD, FD_CLOEXEC);
820 #endif
821 rv = TRU1;
822 jleave:
823 NYD_LEAVE;
824 return rv;
827 FL FILE *
828 Popen(char const *cmd, char const *mode, char const *sh,
829 char const **env_addon, int newfd1)
831 int p[2], myside, hisside, fd0, fd1, pid;
832 char mod[2] = {'0', '\0'};
833 sigset_t nset;
834 FILE *rv = NULL;
835 NYD_ENTER;
837 /* First clean up child structures */
838 { sigset_t oset;
839 struct child **cpp, *cp;
841 sigfillset(&nset);
842 sigprocmask(SIG_BLOCK, &nset, &oset);
844 for (cpp = &_popen_child; *cpp != NULL;) {
845 if ((*cpp)->pid == -1) {
846 cp = *cpp;
847 *cpp = cp->link;
848 free(cp);
849 } else
850 cpp = &(*cpp)->link;
853 sigprocmask(SIG_SETMASK, &oset, NULL);
856 if (!pipe_cloexec(p))
857 goto jleave;
859 if (*mode == 'r') {
860 myside = p[READ];
861 fd0 = -1;
862 hisside = fd1 = p[WRITE];
863 mod[0] = *mode;
864 } else if (*mode == 'W') {
865 myside = p[WRITE];
866 hisside = fd0 = p[READ];
867 fd1 = newfd1;
868 mod[0] = 'w';
869 } else {
870 myside = p[WRITE];
871 hisside = fd0 = p[READ];
872 fd1 = -1;
873 mod[0] = 'w';
876 sigemptyset(&nset);
878 if (cmd == (char*)-1) {
879 if ((pid = fork_child()) == -1)
880 n_perr(_("fork"), 0);
881 else if (pid == 0) {
882 union {char const *ccp; int (*ptf)(void); int es;} u;
883 prepare_child(&nset, fd0, fd1);
884 close(p[READ]);
885 close(p[WRITE]);
886 u.ccp = sh;
887 u.es = (*u.ptf)();
888 _exit(u.es);
890 } else if (sh == NULL) {
891 pid = start_command(cmd, &nset, fd0, fd1, NULL, NULL, NULL, env_addon);
892 } else {
893 pid = start_command(sh, &nset, fd0, fd1, "-c", cmd, NULL, env_addon);
895 if (pid < 0) {
896 close(p[READ]);
897 close(p[WRITE]);
898 goto jleave;
900 close(hisside);
901 if ((rv = fdopen(myside, mod)) != NULL)
902 register_file(rv, 0, 1, pid, FP_RAW, NULL, 0L, NULL);
903 else
904 close(myside);
905 jleave:
906 NYD_LEAVE;
907 return rv;
910 FL bool_t
911 Pclose(FILE *ptr, bool_t dowait)
913 sigset_t nset, oset;
914 int pid;
915 bool_t rv = FAL0;
916 NYD_ENTER;
918 pid = file_pid(ptr);
919 if (pid < 0)
920 goto jleave;
921 unregister_file(ptr);
922 fclose(ptr);
923 if (dowait) {
924 sigemptyset(&nset);
925 sigaddset(&nset, SIGINT);
926 sigaddset(&nset, SIGHUP);
927 sigprocmask(SIG_BLOCK, &nset, &oset);
928 rv = wait_child(pid, NULL);
929 sigprocmask(SIG_SETMASK, &oset, NULL);
930 } else {
931 free_child(pid);
932 rv = TRU1;
934 jleave:
935 NYD_LEAVE;
936 return rv;
939 FL void
940 close_all_files(void)
942 NYD_ENTER;
943 while (fp_head != NULL)
944 if (fp_head->pipe)
945 Pclose(fp_head->fp, TRU1);
946 else
947 Fclose(fp_head->fp);
948 NYD_LEAVE;
951 FL int
952 fork_child(void)
954 struct child *cp;
955 int pid;
956 NYD_ENTER;
958 cp = _findchild(0, TRU1);
960 if ((cp->pid = pid = fork()) == -1) {
961 _delchild(cp);
962 n_perr(_("fork"), 0);
964 NYD_LEAVE;
965 return pid;
968 FL int
969 run_command(char const *cmd, sigset_t *mask, int infd, int outfd,
970 char const *a0, char const *a1, char const *a2, char const **env_addon)
972 sigset_t nset, oset;
973 bool_t tio_set;
974 int rv;
975 NYD_ENTER;
977 /* TODO Of course this is a joke given that during a "p*" the PAGER may
978 * TODO be up and running while we play around like this... but i guess
979 * TODO this can't be helped at all unless we perform complete and true
980 * TODO process group separation and ensure we don't deadlock us out
981 * TODO via TTY jobcontrol signal storms (could this really happen?).
982 * TODO Or have a builtin pager. Or query any necessity BEFORE we start
983 * TODO any action, and shall we find we need to run programs dump it
984 * TODO all into a temporary file which is then passed through to the
985 * TODO PAGER. Ugh. That still won't help for "needsterminal" anyway */
986 if ((tio_set = ((options & OPT_INTERACTIVE) &&
987 (infd == COMMAND_FD_PASS || outfd == COMMAND_FD_PASS)))) {
988 tcgetattr((options & OPT_TTYIN ? STDIN_FILENO : STDOUT_FILENO), &a_popen_tios);
989 sigfillset(&nset);
990 sigdelset(&nset, SIGCHLD);
991 /* sigdelset(&nset, SIGPIPE); TODO would need a handler */
992 sigprocmask(SIG_BLOCK, &nset, &oset);
993 a_popen_hadsig = 0;
994 a_popen_jobsigs_up();
997 if ((rv = start_command(cmd, mask, infd, outfd, a0, a1, a2, env_addon)) < 0)
998 rv = -1;
999 else {
1000 if (wait_child(rv, NULL))
1001 rv = 0;
1002 else {
1003 if (ok_blook(bsdcompat) || ok_blook(bsdmsgs))
1004 n_err(_("Fatal error in process\n"));
1005 rv = -1;
1009 if (tio_set) {
1010 a_popen_jobsigs_down();
1011 tio_set = ((options & OPT_TTYIN) != 0);
1012 tcsetattr((tio_set ? STDIN_FILENO : STDOUT_FILENO),
1013 (tio_set ? TCSAFLUSH : TCSADRAIN), &a_popen_tios);
1014 sigprocmask(SIG_SETMASK, &oset, NULL);
1016 NYD_LEAVE;
1017 return rv;
1020 FL int
1021 start_command(char const *cmd, sigset_t *mask, int infd, int outfd,
1022 char const *a0, char const *a1, char const *a2,
1023 char const **env_addon)
1025 int rv;
1026 NYD_ENTER;
1028 if ((rv = fork_child()) == -1) {
1029 n_perr(_("fork"), 0);
1030 rv = -1;
1031 } else if (rv == 0) {
1032 char *argv[128];
1033 int i;
1035 if (env_addon != NULL) { /* TODO env_addon; should have struct child */
1036 extern char **environ;
1037 size_t ei, ei_orig, ai, ai_orig;
1038 char **env;
1040 /* TODO note we don't check the POSIX limit:
1041 * the total space used to store the environment and the arguments to
1042 * the process is limited to {ARG_MAX} bytes */
1043 for (ei = 0; environ[ei] != NULL; ++ei)
1045 ei_orig = ei;
1046 for (ai = 0; env_addon[ai] != NULL; ++ai)
1048 ai_orig = ai;
1049 env = ac_alloc(sizeof(*env) * (ei + ai +1));
1050 memcpy(env, environ, sizeof(*env) * ei);
1052 /* Replace all those keys that yet exist */
1053 while (ai-- > 0) {
1054 char const *ee, *kvs;
1055 size_t kl;
1057 ee = env_addon[ai];
1058 kvs = strchr(ee, '=');
1059 assert(kvs != NULL);
1060 kl = PTR2SIZE(kvs - ee);
1061 assert(kl > 0);
1062 for (ei = ei_orig; ei-- > 0;) {
1063 char const *ekvs = strchr(env[ei], '=');
1064 if (ekvs != NULL && kl == PTR2SIZE(ekvs - env[ei]) &&
1065 !memcmp(ee, env[ei], kl)) {
1066 env[ei] = UNCONST(ee);
1067 env_addon[ai] = NULL;
1068 break;
1073 /* And append the rest */
1074 for (ei = ei_orig, ai = ai_orig; ai-- > 0;)
1075 if (env_addon[ai] != NULL)
1076 env[ei++] = UNCONST(env_addon[ai]);
1078 env[ei] = NULL;
1079 environ = env;
1082 i = getrawlist(cmd, strlen(cmd), argv, NELEM(argv), 0);
1084 if ((argv[i++] = UNCONST(a0)) != NULL &&
1085 (argv[i++] = UNCONST(a1)) != NULL &&
1086 (argv[i++] = UNCONST(a2)) != NULL)
1087 argv[i] = NULL;
1088 prepare_child(mask, infd, outfd);
1089 execvp(argv[0], argv);
1090 perror(argv[0]);
1091 _exit(EXIT_ERR);
1093 NYD_LEAVE;
1094 return rv;
1097 FL void
1098 prepare_child(sigset_t *nset, int infd, int outfd)
1100 int i;
1101 sigset_t fset;
1102 NYD_ENTER;
1104 /* All file descriptors other than 0, 1, and 2 are supposed to be cloexec */
1105 /* TODO WHAT IS WITH STDERR_FILENO DAMN? */
1106 if ((i = (infd == COMMAND_FD_NULL)))
1107 infd = open("/dev/null", O_RDONLY);
1108 if (infd >= 0) {
1109 dup2(infd, STDIN_FILENO);
1110 if (i)
1111 close(infd);
1114 if ((i = (outfd == COMMAND_FD_NULL)))
1115 outfd = open("/dev/null", O_WRONLY);
1116 if (outfd >= 0) {
1117 dup2(outfd, STDOUT_FILENO);
1118 if (i)
1119 close(outfd);
1122 if (nset) {
1123 for (i = 1; i < NSIG; ++i)
1124 if (sigismember(nset, i))
1125 safe_signal(i, SIG_IGN);
1126 if (!sigismember(nset, SIGINT))
1127 safe_signal(SIGINT, SIG_DFL);
1130 sigemptyset(&fset);
1131 sigprocmask(SIG_SETMASK, &fset, NULL);
1132 NYD_LEAVE;
1135 FL void
1136 free_child(int pid)
1138 sigset_t nset, oset;
1139 struct child *cp;
1140 NYD_ENTER;
1142 sigemptyset(&nset);
1143 sigaddset(&nset, SIGCHLD);
1144 sigprocmask(SIG_BLOCK, &nset, &oset);
1146 if ((cp = _findchild(pid, FAL0)) != NULL) {
1147 if (cp->done)
1148 _delchild(cp);
1149 else
1150 cp->free = 1;
1153 sigprocmask(SIG_SETMASK, &oset, NULL);
1154 NYD_LEAVE;
1157 FL bool_t
1158 wait_child(int pid, int *wait_status)
1160 sigset_t nset, oset;
1161 struct child *cp;
1162 int ws;
1163 bool_t rv;
1164 NYD_ENTER;
1166 sigemptyset(&nset);
1167 sigaddset(&nset, SIGCHLD);
1168 sigprocmask(SIG_BLOCK, &nset, &oset);
1170 cp = _findchild(pid, FAL0);
1171 if (cp != NULL) {
1172 while (!cp->done)
1173 sigsuspend(&oset);
1174 ws = cp->status;
1175 _delchild(cp);
1176 } else
1177 ws = 0;
1179 sigprocmask(SIG_SETMASK, &oset, NULL);
1181 if (wait_status != NULL)
1182 *wait_status = ws;
1183 rv = (WIFEXITED(ws) && WEXITSTATUS(ws) == 0);
1184 NYD_LEAVE;
1185 return rv;
1188 /* s-it-mode */