`list': include argument-type etc. if *verbose*
[s-mailx.git] / popen.c
blob8fb154c30cf859fdb5e1bddabe3e60a553dfe696
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 struct termios *fp_tios;
53 long offset;
54 int omode;
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_PIPE = 1<<6,
64 FP_MASK = (1<<7) - 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<<9,
68 FP_TERMIOS = 1<<10
69 } flags;
72 struct child {
73 int pid;
74 char done;
75 char free;
76 int status;
77 struct child *link;
80 static struct fp *fp_head;
81 static struct child *_popen_child;
83 /* TODO Rather temporary: deal with job control with FD_PASS */
84 static struct termios a_popen_tios;
85 static sighandler_type a_popen_otstp, a_popen_ottin, a_popen_ottou;
86 static volatile int a_popen_hadsig;
88 static int scan_mode(char const *mode, int *omode);
89 static void register_file(FILE *fp, int omode, int pid,
90 int flags, char const *realfile, long offset,
91 char const *save_cmd, struct termios *tiosp);
92 static enum okay _file_save(struct fp *fpp);
93 static int _file_load(int flags, int infd, int outfd,
94 char const *load_cmd);
95 static enum okay unregister_file(FILE *fp, struct termios **tiosp);
96 static int file_pid(FILE *fp);
98 /* TODO Rather temporary: deal with job control with FD_PASS */
99 static void a_popen_jobsigs_up(void);
100 static void a_popen_jobsigs_down(void);
101 static void a_popen_jobsig(int sig);
103 /* Handle SIGCHLD */
104 static void _sigchld(int signo);
106 static struct child *_findchild(int pid, bool_t create);
107 static void _delchild(struct child *cp);
109 static int
110 scan_mode(char const *mode, int *omode)
112 static struct {
113 char const mode[4];
114 int omode;
115 } const maps[] = {
116 {"r", O_RDONLY},
117 {"w", O_WRONLY | O_CREAT | O_TRUNC},
118 {"wx", O_WRONLY | O_CREAT | O_EXCL},
119 {"a", O_WRONLY | O_APPEND | O_CREAT},
120 {"a+", O_RDWR | O_APPEND},
121 {"r+", O_RDWR},
122 {"w+", O_RDWR | O_CREAT | O_EXCL}
125 int i;
126 NYD2_ENTER;
128 for (i = 0; UICMP(z, i, <, NELEM(maps)); ++i)
129 if (!strcmp(maps[i].mode, mode)) {
130 *omode = maps[i].omode;
131 i = 0;
132 goto jleave;
135 n_alert(_("Internal error: bad stdio open mode %s"), mode);
136 errno = EINVAL;
137 *omode = 0; /* (silence CC) */
138 i = -1;
139 jleave:
140 NYD2_LEAVE;
141 return i;
144 static void
145 register_file(FILE *fp, int omode, int pid, int flags,
146 char const *realfile, long offset, char const *save_cmd,
147 struct termios *tiosp)
149 struct fp *fpp;
150 NYD_ENTER;
152 assert(!(flags & FP_UNLINK) || realfile != NULL);
153 assert(!(flags & FP_TERMIOS) || tiosp != NULL);
155 fpp = smalloc(sizeof *fpp);
156 fpp->fp = fp;
157 fpp->omode = omode;
158 fpp->pid = pid;
159 fpp->link = fp_head;
160 fpp->flags = flags;
161 fpp->realfile = (realfile != NULL) ? sstrdup(realfile) : NULL;
162 fpp->save_cmd = (save_cmd != NULL) ? sstrdup(save_cmd) : NULL;
163 fpp->fp_tios = tiosp;
164 fpp->offset = offset;
165 fp_head = fpp;
166 NYD_LEAVE;
169 static enum okay
170 _file_save(struct fp *fpp)
172 char const *cmd[3];
173 int outfd, infd;
174 enum okay rv;
175 NYD_ENTER;
177 if (fpp->omode == O_RDONLY) {
178 rv = OKAY;
179 goto jleave;
181 rv = STOP;
183 fflush(fpp->fp);
184 clearerr(fpp->fp);
186 if ((fpp->flags & FP_MASK) == FP_MAILDIR) {
187 if (fseek(fpp->fp, fpp->offset, SEEK_SET) == -1) {
188 outfd = errno;
189 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
190 n_shell_quote_cp(fpp->realfile, FAL0), strerror(outfd));
191 goto jleave;
193 rv = maildir_append(fpp->realfile, fpp->fp, fpp->offset);
194 goto jleave;
197 /* Ensure the I/O library doesn't optimize the fseek(3) away! */
198 if(lseek(infd = fileno(fpp->fp), fpp->offset, SEEK_SET) == -1){
199 outfd = errno;
200 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
201 n_shell_quote_cp(fpp->realfile, FAL0), strerror(outfd));
202 goto jleave;
205 outfd = open(fpp->realfile,
206 ((fpp->omode | O_CREAT | (fpp->omode & O_APPEND ? 0 : O_TRUNC))
207 & ~O_EXCL), 0666);
208 if (outfd == -1) {
209 outfd = errno;
210 n_err(_("Fatal: cannot create %s: %s\n"),
211 n_shell_quote_cp(fpp->realfile, FAL0), strerror(outfd));
212 goto jleave;
215 cmd[2] = NULL;
216 switch (fpp->flags & FP_MASK) {
217 case FP_GZIP:
218 cmd[0] = "gzip"; cmd[1] = "-c"; break;
219 case FP_BZIP2:
220 cmd[0] = "bzip2"; cmd[1] = "-c"; break;
221 case FP_XZ:
222 cmd[0] = "xz"; cmd[1] = "-c"; break;
223 default:
224 cmd[0] = "cat"; cmd[1] = NULL; break;
225 case FP_HOOK:
226 cmd[0] = ok_vlook(SHELL);
227 cmd[1] = "-c";
228 cmd[2] = fpp->save_cmd;
230 if (run_command(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL) >= 0)
231 rv = OKAY;
233 close(outfd);
234 jleave:
235 NYD_LEAVE;
236 return rv;
239 static int
240 _file_load(int flags, int infd, int outfd, char const *load_cmd)
242 char const *cmd[3];
243 int rv;
244 NYD_ENTER;
246 cmd[2] = NULL;
247 switch (flags & FP_MASK) {
248 case FP_GZIP: cmd[0] = "gzip"; cmd[1] = "-cd"; break;
249 case FP_BZIP2: cmd[0] = "bzip2"; cmd[1] = "-cd"; break;
250 case FP_XZ: cmd[0] = "xz"; cmd[1] = "-cd"; break;
251 default: cmd[0] = "cat"; cmd[1] = NULL; break;
252 case FP_HOOK:
253 cmd[0] = ok_vlook(SHELL);
254 cmd[1] = "-c";
255 cmd[2] = load_cmd;
256 break;
257 case FP_MAILDIR:
258 rv = 0;
259 goto jleave;
262 rv = run_command(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL);
263 jleave:
264 NYD_LEAVE;
265 return rv;
268 static enum okay
269 unregister_file(FILE *fp, struct termios **tiosp)
271 struct fp **pp, *p;
272 enum okay rv = OKAY;
273 NYD_ENTER;
275 if (tiosp)
276 *tiosp = NULL;
278 for (pp = &fp_head; (p = *pp) != NULL; pp = &p->link)
279 if (p->fp == fp) {
280 switch (p->flags & FP_MASK) {
281 case FP_RAW:
282 case FP_PIPE:
283 break;
284 default:
285 rv = _file_save(p);
286 break;
288 if ((p->flags & FP_UNLINK) && unlink(p->realfile))
289 rv = STOP;
291 *pp = p->link;
292 if (p->save_cmd != NULL)
293 free(p->save_cmd);
294 if (p->realfile != NULL)
295 free(p->realfile);
296 if (p->flags & FP_TERMIOS) {
297 if (tiosp != NULL)
298 *tiosp = p->fp_tios;
299 else
300 free(p->fp_tios);
302 free(p);
303 goto jleave;
305 DBGOR(n_panic, n_alert)(_("Invalid file pointer"));
306 rv = STOP;
307 jleave:
308 NYD_LEAVE;
309 return rv;
312 static int
313 file_pid(FILE *fp)
315 int rv;
316 struct fp *p;
317 NYD2_ENTER;
319 rv = -1;
320 for (p = fp_head; p; p = p->link)
321 if (p->fp == fp) {
322 rv = p->pid;
323 break;
325 NYD2_LEAVE;
326 return rv;
329 static void
330 a_popen_jobsigs_up(void){
331 sigset_t nset, oset;
332 NYD2_ENTER;
334 sigfillset(&nset);
336 sigprocmask(SIG_BLOCK, &nset, &oset);
337 a_popen_otstp = safe_signal(SIGTSTP, &a_popen_jobsig);
338 a_popen_ottin = safe_signal(SIGTTIN, &a_popen_jobsig);
339 a_popen_ottou = safe_signal(SIGTTOU, &a_popen_jobsig);
341 /* This assumes oset contains nothing but SIGCHLD, so to say */
342 sigdelset(&oset, SIGTSTP);
343 sigdelset(&oset, SIGTTIN);
344 sigdelset(&oset, SIGTTOU);
345 sigprocmask(SIG_SETMASK, &oset, NULL);
346 NYD2_LEAVE;
349 static void
350 a_popen_jobsigs_down(void){
351 sigset_t nset, oset;
352 NYD2_ENTER;
354 sigfillset(&nset);
356 sigprocmask(SIG_BLOCK, &nset, &oset);
357 safe_signal(SIGTSTP, a_popen_otstp);
358 safe_signal(SIGTTIN, a_popen_ottin);
359 safe_signal(SIGTTOU, a_popen_ottou);
361 sigaddset(&oset, SIGTSTP);
362 sigaddset(&oset, SIGTTIN);
363 sigaddset(&oset, SIGTTOU);
364 sigprocmask(SIG_SETMASK, &oset, NULL);
365 NYD2_LEAVE;
368 static void
369 a_popen_jobsig(int sig){
370 sighandler_type oldact;
371 sigset_t nset;
372 bool_t hadsig;
373 NYD_X; /* Signal handler */
375 hadsig = (a_popen_hadsig != 0);
376 a_popen_hadsig = 1;
377 if(!hadsig)
378 n_TERMCAP_SUSPEND(TRU1);
380 oldact = safe_signal(sig, SIG_DFL);
382 sigemptyset(&nset);
383 sigaddset(&nset, sig);
384 sigprocmask(SIG_UNBLOCK, &nset, NULL);
385 n_raise(sig);
386 sigprocmask(SIG_BLOCK, &nset, NULL);
388 safe_signal(sig, oldact);
391 static void
392 _sigchld(int signo)
394 pid_t pid;
395 int status;
396 struct child *cp;
397 NYD_X; /* Signal handler */
398 UNUSED(signo);
400 for (;;) {
401 pid = waitpid(-1, &status, WNOHANG);
402 if (pid <= 0) {
403 if (pid == -1 && errno == EINTR)
404 continue;
405 break;
408 if ((cp = _findchild(pid, FAL0)) != NULL) {
409 if (cp->free)
410 cp->pid = -1; /* XXX Was _delchild(cp);# */
411 else {
412 cp->done = 1;
413 cp->status = status;
419 static struct child *
420 _findchild(int pid, bool_t create)
422 struct child **cpp;
423 NYD_ENTER;
425 for (cpp = &_popen_child; *cpp != NULL && (*cpp)->pid != pid;
426 cpp = &(*cpp)->link)
429 if (*cpp == NULL && create) {
430 *cpp = smalloc(sizeof **cpp);
431 (*cpp)->pid = pid;
432 (*cpp)->done = (*cpp)->free = 0;
433 (*cpp)->link = NULL;
435 NYD_LEAVE;
436 return *cpp;
439 static void
440 _delchild(struct child *cp)
442 struct child **cpp;
443 NYD_ENTER;
445 cpp = &_popen_child;
446 for (;;) {
447 if (*cpp == cp) {
448 *cpp = cp->link;
449 free(cp);
450 break;
452 if (*(cpp = &(*cpp)->link) == NULL) {
453 DBG( n_err("! popen.c:_delchild(): implementation error\n"); )
454 break;
457 NYD_LEAVE;
460 FL void
461 command_manager_start(void)
463 struct sigaction nact, oact;
464 NYD_ENTER;
466 nact.sa_handler = &_sigchld;
467 sigemptyset(&nact.sa_mask);
468 nact.sa_flags = SA_RESTART
469 #ifdef SA_NOCLDSTOP
470 | SA_NOCLDSTOP
471 #endif
473 if (sigaction(SIGCHLD, &nact, &oact) != 0)
474 n_panic(_("Cannot install signal handler for child process management"));
475 NYD_LEAVE;
478 FL FILE *
479 safe_fopen(char const *file, char const *oflags, int *xflags)
481 int osflags, fd;
482 FILE *fp = NULL;
483 NYD2_ENTER; /* (only for Fopen() and once in lex.c) */
485 if (scan_mode(oflags, &osflags) < 0)
486 goto jleave;
487 osflags |= _O_CLOEXEC;
488 if (xflags != NULL)
489 *xflags = osflags;
491 if ((fd = open(file, osflags, 0666)) == -1)
492 goto jleave;
493 _CLOEXEC_SET(fd);
495 fp = fdopen(fd, oflags);
496 jleave:
497 NYD2_LEAVE;
498 return fp;
501 FL FILE *
502 Fopen(char const *file, char const *oflags)
504 FILE *fp;
505 int osflags;
506 NYD_ENTER;
508 if ((fp = safe_fopen(file, oflags, &osflags)) != NULL)
509 register_file(fp, osflags, 0, FP_RAW, NULL, 0L, NULL, NULL);
510 NYD_LEAVE;
511 return fp;
514 FL FILE *
515 Fdopen(int fd, char const *oflags, bool_t nocloexec)
517 FILE *fp;
518 int osflags;
519 NYD_ENTER;
521 scan_mode(oflags, &osflags);
522 if (!nocloexec)
523 osflags |= _O_CLOEXEC; /* Ensured to be set by caller as documented! */
525 if ((fp = fdopen(fd, oflags)) != NULL)
526 register_file(fp, osflags, 0, FP_RAW, NULL, 0L, NULL, NULL);
527 NYD_LEAVE;
528 return fp;
531 FL int
532 Fclose(FILE *fp)
534 int i = 0;
535 NYD_ENTER;
537 if (unregister_file(fp, NULL) == OKAY)
538 i |= 1;
539 if (fclose(fp) == 0)
540 i |= 2;
541 NYD_LEAVE;
542 return (i == 3 ? 0 : EOF);
545 FL FILE *
546 Zopen(char const *file, char const *oflags) /* FIXME MESS! */
548 FILE *rv = NULL;
549 char const *cload = NULL, *csave = NULL;
550 int flags, osflags, mode, infd;
551 enum oflags rof;
552 long offset;
553 enum protocol p;
554 NYD_ENTER;
556 if (scan_mode(oflags, &osflags) < 0)
557 goto jleave;
559 flags = 0;
560 rof = OF_RDWR | OF_UNLINK;
561 if (osflags & O_APPEND)
562 rof |= OF_APPEND;
563 mode = (osflags == O_RDONLY) ? R_OK : R_OK | W_OK;
565 if ((osflags & O_APPEND) && ((p = which_protocol(file)) == PROTO_MAILDIR)) {
566 flags |= FP_MAILDIR;
567 osflags = O_RDWR | O_APPEND | O_CREAT;
568 infd = -1;
569 } else {
570 char const *ext;
572 if ((ext = strrchr(file, '.')) != NULL) {
573 if (!asccasecmp(ext, ".gz"))
574 flags |= FP_GZIP;
575 else if (!asccasecmp(ext, ".xz")) {
576 flags |= FP_XZ;
577 osflags &= ~O_APPEND;
578 rof &= ~OF_APPEND;
579 } else if (!asccasecmp(ext, ".bz2")) {
580 flags |= FP_BZIP2;
581 osflags &= ~O_APPEND;
582 rof &= ~OF_APPEND;
583 } else {
584 #undef _X1
585 #define _X1 "file-hook-load-"
586 #undef _X2
587 #define _X2 "file-hook-save-"
588 size_t l = strlen(++ext);
589 char *vbuf = ac_alloc(l + MAX(sizeof(_X1), sizeof(_X2)));
591 memcpy(vbuf, _X1, sizeof(_X1) -1);
592 memcpy(vbuf + sizeof(_X1) -1, ext, l);
593 vbuf[sizeof(_X1) -1 + l] = '\0';
594 cload = vok_vlook(vbuf);
595 memcpy(vbuf, _X2, sizeof(_X2) -1);
596 memcpy(vbuf + sizeof(_X2) -1, ext, l);
597 vbuf[sizeof(_X2) -1 + l] = '\0';
598 csave = vok_vlook(vbuf);
599 #undef _X2
600 #undef _X1
601 ac_free(vbuf);
603 if ((csave != NULL) && (cload != NULL)) {
604 flags |= FP_HOOK;
605 osflags &= ~O_APPEND;
606 rof &= ~OF_APPEND;
607 } else if ((csave != NULL) | (cload != NULL)) {
608 n_alert(_("Only one of *mailbox-(load|save)-%s* is set! "
609 "Treating as plain text!"), ext);
610 goto jraw;
611 } else
612 goto jraw;
614 } else {
615 jraw:
616 /*flags |= FP_RAW;*/
617 rv = Fopen(file, oflags);
618 goto jleave;
621 if ((infd = open(file, (mode & W_OK) ? O_RDWR : O_RDONLY)) == -1 &&
622 (!(osflags & O_CREAT) || errno != ENOENT))
623 goto jleave;
626 /* Note rv is not yet register_file()d, fclose() it in error path! */
627 if ((rv = Ftmp(NULL, "zopen", rof)) == NULL) {
628 n_perr(_("tmpfile"), 0);
629 goto jerr;
632 if (flags & FP_MAILDIR)
634 else if (infd >= 0) {
635 if (_file_load(flags, infd, fileno(rv), cload) < 0) {
636 jerr:
637 if (rv != NULL)
638 fclose(rv);
639 rv = NULL;
640 if (infd >= 0)
641 close(infd);
642 goto jleave;
644 } else {
645 if ((infd = creat(file, 0666)) == -1) {
646 fclose(rv);
647 rv = NULL;
648 goto jleave;
652 if (infd >= 0)
653 close(infd);
654 fflush(rv);
656 if (!(osflags & O_APPEND))
657 rewind(rv);
658 if ((offset = ftell(rv)) == -1) {
659 Fclose(rv);
660 rv = NULL;
661 goto jleave;
664 register_file(rv, osflags, 0, flags, file, offset, csave, NULL);
665 jleave:
666 NYD_LEAVE;
667 return rv;
670 FL FILE *
671 Ftmp(char **fn, char const *namehint, enum oflags oflags)
673 /* The 8 is arbitrary but leaves room for a six character suffix (the
674 * POSIX minimum path length is 14, though we don't check that XXX).
675 * 8 should be more than sufficient given that we use base64url encoding
676 * for our random string */
677 enum {_RANDCHARS = 8};
679 size_t maxname, xlen, i;
680 char *cp_base, *cp;
681 int osoflags, fd, e;
682 bool_t relesigs;
683 FILE *fp;
684 NYD_ENTER;
686 assert(namehint != NULL);
687 assert((oflags & OF_WRONLY) || (oflags & OF_RDWR));
688 assert(!(oflags & OF_RDONLY));
689 assert(!(oflags & OF_REGISTER_UNLINK) || (oflags & OF_REGISTER));
691 fp = NULL;
692 relesigs = FAL0;
693 e = 0;
694 maxname = NAME_MAX;
695 #ifdef HAVE_PATHCONF
696 { long pc;
698 if ((pc = pathconf(tempdir, _PC_NAME_MAX)) != -1)
699 maxname = (size_t)pc;
701 #endif
703 if ((oflags & OF_SUFFIX) && *namehint != '\0') {
704 if ((xlen = strlen(namehint)) > maxname - _RANDCHARS) {
705 errno = ENAMETOOLONG;
706 goto jleave;
708 } else
709 xlen = 0;
711 /* Prepare the template string once, then iterate over the random range */
712 cp_base =
713 cp = smalloc(strlen(tempdir) + 1 + maxname +1);
714 cp = sstpcpy(cp, tempdir);
715 *cp++ = '/';
717 char *x = sstpcpy(cp, UAGENT);
718 *x++ = '-';
719 if (!(oflags & OF_SUFFIX))
720 x = sstpcpy(x, namehint);
722 i = PTR2SIZE(x - cp);
723 if (i > maxname - xlen - _RANDCHARS) {
724 size_t j = maxname - xlen - _RANDCHARS;
725 x -= i - j;
726 i = j;
729 if ((oflags & OF_SUFFIX) && xlen > 0)
730 memcpy(x + _RANDCHARS, namehint, xlen);
732 x[xlen + _RANDCHARS] = '\0';
733 cp = x;
736 osoflags = O_CREAT | O_EXCL | _O_CLOEXEC;
737 osoflags |= (oflags & OF_WRONLY) ? O_WRONLY : O_RDWR;
738 if (oflags & OF_APPEND)
739 osoflags |= O_APPEND;
741 for (i = 0;; ++i) {
742 memcpy(cp, getrandstring(_RANDCHARS), _RANDCHARS);
744 hold_all_sigs();
745 relesigs = TRU1;
747 if ((fd = open(cp_base, osoflags, 0600)) != -1) {
748 _CLOEXEC_SET(fd);
749 break;
751 if (i >= FTMP_OPEN_TRIES) {
752 e = errno;
753 goto jfree;
755 relesigs = FAL0;
756 rele_all_sigs();
759 if (oflags & OF_REGISTER) {
760 char const *osflags = (oflags & OF_RDWR ? "w+" : "w");
761 int osflagbits;
763 scan_mode(osflags, &osflagbits); /* TODO osoflags&xy ?!!? */
764 if ((fp = fdopen(fd, osflags)) != NULL)
765 register_file(fp, osflagbits | _O_CLOEXEC, 0,
766 (FP_RAW | (oflags & OF_REGISTER_UNLINK ? FP_UNLINK : 0)),
767 cp_base, 0L, NULL, NULL);
768 } else
769 fp = fdopen(fd, (oflags & OF_RDWR ? "w+" : "w"));
771 if (fp == NULL || (oflags & OF_UNLINK)) {
772 e = errno;
773 unlink(cp_base);
774 goto jfree;
777 if (fn != NULL)
778 *fn = cp_base;
779 else
780 free(cp_base);
781 jleave:
782 if (relesigs && (fp == NULL || !(oflags & OF_HOLDSIGS)))
783 rele_all_sigs();
784 if (fp == NULL)
785 errno = e;
786 NYD_LEAVE;
787 return fp;
788 jfree:
789 if ((cp = cp_base) != NULL)
790 free(cp);
791 goto jleave;
794 FL void
795 Ftmp_release(char **fn)
797 char *cp;
798 NYD_ENTER;
800 cp = *fn;
801 *fn = NULL;
802 if (cp != NULL) {
803 unlink(cp);
804 rele_all_sigs();
805 free(cp);
807 NYD_LEAVE;
810 FL void
811 Ftmp_free(char **fn) /* TODO DROP: OF_REGISTER_FREEPATH! */
813 char *cp;
814 NYD_ENTER;
816 cp = *fn;
817 *fn = NULL;
818 if (cp != NULL)
819 free(cp);
820 NYD_LEAVE;
823 FL bool_t
824 pipe_cloexec(int fd[2])
826 bool_t rv = FAL0;
827 NYD_ENTER;
829 #ifdef HAVE_PIPE2
830 if (pipe2(fd, O_CLOEXEC) == -1)
831 goto jleave;
832 #else
833 if (pipe(fd) == -1)
834 goto jleave;
835 (void)fcntl(fd[0], F_SETFD, FD_CLOEXEC);
836 (void)fcntl(fd[1], F_SETFD, FD_CLOEXEC);
837 #endif
838 rv = TRU1;
839 jleave:
840 NYD_LEAVE;
841 return rv;
844 FL FILE *
845 Popen(char const *cmd, char const *mode, char const *sh,
846 char const **env_addon, int newfd1)
848 struct termios *tiosp;
849 int p[2], myside, hisside, fd0, fd1, pid;
850 char mod[2] = {'0', '\0'};
851 sigset_t nset;
852 FILE *rv = NULL;
853 NYD_ENTER;
855 /* First clean up child structures */
856 { sigset_t oset;
857 struct child **cpp, *cp;
859 sigfillset(&nset);
860 sigprocmask(SIG_BLOCK, &nset, &oset);
862 for (cpp = &_popen_child; *cpp != NULL;) {
863 if ((*cpp)->pid == -1) {
864 cp = *cpp;
865 *cpp = cp->link;
866 free(cp);
867 } else
868 cpp = &(*cpp)->link;
871 sigprocmask(SIG_SETMASK, &oset, NULL);
874 if (!pipe_cloexec(p))
875 goto jleave;
877 if (*mode == 'r') {
878 myside = p[READ];
879 fd0 = COMMAND_FD_PASS;
880 hisside = fd1 = p[WRITE];
881 mod[0] = *mode;
882 } else if (*mode == 'W') {
883 myside = p[WRITE];
884 hisside = fd0 = p[READ];
885 fd1 = newfd1;
886 mod[0] = 'w';
887 } else {
888 myside = p[WRITE];
889 hisside = fd0 = p[READ];
890 fd1 = COMMAND_FD_PASS;
891 mod[0] = 'w';
894 /* In interactive mode both STDIN and STDOUT point to the terminal. If we
895 * pass through the TTY restore terminal attributes after pipe returns.
896 * XXX It shouldn't matter which FD we actually use in this case */
897 if ((options & OPT_INTERACTIVE) && (fd0 == COMMAND_FD_PASS ||
898 fd1 == COMMAND_FD_PASS)) {
899 tiosp = smalloc(sizeof *tiosp);
900 tcgetattr(STDIN_FILENO, tiosp);
901 n_TERMCAP_SUSPEND(TRU1);
902 } else
903 tiosp = NULL;
905 sigemptyset(&nset);
907 if (cmd == (char*)-1) {
908 if ((pid = fork_child()) == -1)
909 n_perr(_("fork"), 0);
910 else if (pid == 0) {
911 union {char const *ccp; int (*ptf)(void); int es;} u;
912 prepare_child(&nset, fd0, fd1);
913 close(p[READ]);
914 close(p[WRITE]);
915 u.ccp = sh;
916 u.es = (*u.ptf)();
917 _exit(u.es);
919 } else if (sh == NULL) {
920 pid = start_command(cmd, &nset, fd0, fd1, NULL, NULL, NULL, env_addon);
921 } else {
922 pid = start_command(sh, &nset, fd0, fd1, "-c", cmd, NULL, env_addon);
924 if (pid < 0) {
925 close(p[READ]);
926 close(p[WRITE]);
927 goto jleave;
929 close(hisside);
930 if ((rv = fdopen(myside, mod)) != NULL)
931 register_file(rv, 0, pid,
932 (tiosp == NULL ? FP_PIPE : FP_PIPE | FP_TERMIOS),
933 NULL, 0L, NULL, tiosp);
934 else
935 close(myside);
936 jleave:
937 NYD_LEAVE;
938 return rv;
941 FL bool_t
942 Pclose(FILE *ptr, bool_t dowait)
944 struct termios *tiosp;
945 sigset_t nset, oset;
946 int pid;
947 bool_t rv = FAL0;
948 NYD_ENTER;
950 pid = file_pid(ptr);
951 if (pid < 0)
952 goto jleave;
954 unregister_file(ptr, &tiosp);
955 fclose(ptr);
957 if (dowait) {
958 sigemptyset(&nset);
959 sigaddset(&nset, SIGINT);
960 sigaddset(&nset, SIGHUP);
961 sigprocmask(SIG_BLOCK, &nset, &oset);
962 rv = wait_child(pid, NULL);
963 if (tiosp != NULL) {
964 n_TERMCAP_RESUME(TRU1);
965 tcsetattr(STDIN_FILENO, TCSAFLUSH, tiosp);
967 sigprocmask(SIG_SETMASK, &oset, NULL);
968 } else {
969 free_child(pid);
970 rv = TRU1;
972 if (tiosp != NULL)
973 free(tiosp);
974 jleave:
975 NYD_LEAVE;
976 return rv;
979 FL FILE *
980 n_pager_open(void)
982 char const *env_add[2], *pager;
983 FILE *rv;
984 NYD_ENTER;
986 assert(options & OPT_INTERACTIVE);
988 pager = n_pager_get(env_add + 0);
989 env_add[1] = NULL;
991 if ((rv = Popen(pager, "w", NULL, env_add, COMMAND_FD_PASS)) == NULL)
992 n_perr(pager, 0);
993 NYD_LEAVE;
994 return rv;
997 FL bool_t
998 n_pager_close(FILE *fp)
1000 sighandler_type sh;
1001 bool_t rv;
1002 NYD_ENTER;
1004 sh = safe_signal(SIGPIPE, SIG_IGN);
1005 rv = Pclose(fp, TRU1);
1006 safe_signal(SIGPIPE, sh);
1007 NYD_LEAVE;
1008 return rv;
1011 FL void
1012 close_all_files(void)
1014 NYD_ENTER;
1015 while (fp_head != NULL)
1016 if ((fp_head->flags & FP_MASK) == FP_PIPE)
1017 Pclose(fp_head->fp, TRU1);
1018 else
1019 Fclose(fp_head->fp);
1020 NYD_LEAVE;
1023 FL int
1024 fork_child(void)
1026 struct child *cp;
1027 int pid;
1028 NYD_ENTER;
1030 cp = _findchild(0, TRU1);
1032 if ((cp->pid = pid = fork()) == -1) {
1033 _delchild(cp);
1034 n_perr(_("fork"), 0);
1036 NYD_LEAVE;
1037 return pid;
1040 FL int
1041 run_command(char const *cmd, sigset_t *mask, int infd, int outfd,
1042 char const *a0, char const *a1, char const *a2, char const **env_addon)
1044 sigset_t nset, oset;
1045 bool_t tio_set;
1046 int rv;
1047 NYD_ENTER;
1049 /* TODO Of course this is a joke given that during a "p*" the PAGER may
1050 * TODO be up and running while we play around like this... but i guess
1051 * TODO this can't be helped at all unless we perform complete and true
1052 * TODO process group separation and ensure we don't deadlock us out
1053 * TODO via TTY jobcontrol signal storms (could this really happen?).
1054 * TODO Or have a builtin pager. Or query any necessity BEFORE we start
1055 * TODO any action, and shall we find we need to run programs dump it
1056 * TODO all into a temporary file which is then passed through to the
1057 * TODO PAGER. Ugh. That still won't help for "needsterminal" anyway */
1058 if ((tio_set = ((options & OPT_INTERACTIVE) &&
1059 (infd == COMMAND_FD_PASS || outfd == COMMAND_FD_PASS)))) {
1060 tcgetattr((options & OPT_TTYIN ? STDIN_FILENO : STDOUT_FILENO), &a_popen_tios);
1061 n_TERMCAP_SUSPEND(FAL0);
1062 sigfillset(&nset);
1063 sigdelset(&nset, SIGCHLD);
1064 /* sigdelset(&nset, SIGPIPE); TODO would need a handler */
1065 sigprocmask(SIG_BLOCK, &nset, &oset);
1066 a_popen_hadsig = 0;
1067 a_popen_jobsigs_up();
1070 if ((rv = start_command(cmd, mask, infd, outfd, a0, a1, a2, env_addon)) < 0)
1071 rv = -1;
1072 else {
1073 if (wait_child(rv, NULL))
1074 rv = 0;
1075 else {
1076 if (ok_blook(bsdcompat) || ok_blook(bsdmsgs))
1077 n_err(_("Fatal error in process\n"));
1078 rv = -1;
1082 if (tio_set) {
1083 a_popen_jobsigs_down();
1084 tio_set = ((options & OPT_TTYIN) != 0);
1085 n_TERMCAP_RESUME(a_popen_hadsig ? TRU1 : FAL0);
1086 tcsetattr((tio_set ? STDIN_FILENO : STDOUT_FILENO),
1087 (tio_set ? TCSAFLUSH : TCSADRAIN), &a_popen_tios);
1088 sigprocmask(SIG_SETMASK, &oset, NULL);
1090 NYD_LEAVE;
1091 return rv;
1094 FL int
1095 start_command(char const *cmd, sigset_t *mask, int infd, int outfd,
1096 char const *a0, char const *a1, char const *a2,
1097 char const **env_addon)
1099 int rv;
1100 NYD_ENTER;
1102 if ((rv = fork_child()) == -1) {
1103 n_perr(_("fork"), 0);
1104 rv = -1;
1105 } else if (rv == 0) {
1106 char *argv[128];
1107 int i;
1109 if (env_addon != NULL) { /* TODO env_addon; should have struct child */
1110 extern char **environ;
1111 size_t ei, ei_orig, ai, ai_orig;
1112 char **env;
1114 /* TODO note we don't check the POSIX limit:
1115 * the total space used to store the environment and the arguments to
1116 * the process is limited to {ARG_MAX} bytes */
1117 for (ei = 0; environ[ei] != NULL; ++ei)
1119 ei_orig = ei;
1120 for (ai = 0; env_addon[ai] != NULL; ++ai)
1122 ai_orig = ai;
1123 env = ac_alloc(sizeof(*env) * (ei + ai +1));
1124 memcpy(env, environ, sizeof(*env) * ei);
1126 /* Replace all those keys that yet exist */
1127 while (ai-- > 0) {
1128 char const *ee, *kvs;
1129 size_t kl;
1131 ee = env_addon[ai];
1132 kvs = strchr(ee, '=');
1133 assert(kvs != NULL);
1134 kl = PTR2SIZE(kvs - ee);
1135 assert(kl > 0);
1136 for (ei = ei_orig; ei-- > 0;) {
1137 char const *ekvs = strchr(env[ei], '=');
1138 if (ekvs != NULL && kl == PTR2SIZE(ekvs - env[ei]) &&
1139 !memcmp(ee, env[ei], kl)) {
1140 env[ei] = UNCONST(ee);
1141 env_addon[ai] = NULL;
1142 break;
1147 /* And append the rest */
1148 for (ei = ei_orig, ai = ai_orig; ai-- > 0;)
1149 if (env_addon[ai] != NULL)
1150 env[ei++] = UNCONST(env_addon[ai]);
1152 env[ei] = NULL;
1153 environ = env;
1156 i = (int)getrawlist(FAL0, argv, NELEM(argv), cmd, strlen(cmd));
1158 if ((argv[i++] = UNCONST(a0)) != NULL &&
1159 (argv[i++] = UNCONST(a1)) != NULL &&
1160 (argv[i++] = UNCONST(a2)) != NULL)
1161 argv[i] = NULL;
1162 prepare_child(mask, infd, outfd);
1163 execvp(argv[0], argv);
1164 perror(argv[0]);
1165 _exit(EXIT_ERR);
1167 NYD_LEAVE;
1168 return rv;
1171 FL void
1172 prepare_child(sigset_t *nset, int infd, int outfd)
1174 int i;
1175 sigset_t fset;
1176 NYD_ENTER;
1178 /* All file descriptors other than 0, 1, and 2 are supposed to be cloexec */
1179 /* TODO WHAT IS WITH STDERR_FILENO DAMN? */
1180 if ((i = (infd == COMMAND_FD_NULL)))
1181 infd = open("/dev/null", O_RDONLY);
1182 if (infd >= 0) {
1183 dup2(infd, STDIN_FILENO);
1184 if (i)
1185 close(infd);
1188 if ((i = (outfd == COMMAND_FD_NULL)))
1189 outfd = open("/dev/null", O_WRONLY);
1190 if (outfd >= 0) {
1191 dup2(outfd, STDOUT_FILENO);
1192 if (i)
1193 close(outfd);
1196 if (nset) {
1197 for (i = 1; i < NSIG; ++i)
1198 if (sigismember(nset, i))
1199 safe_signal(i, SIG_IGN);
1200 if (!sigismember(nset, SIGINT))
1201 safe_signal(SIGINT, SIG_DFL);
1204 sigemptyset(&fset);
1205 sigprocmask(SIG_SETMASK, &fset, NULL);
1206 NYD_LEAVE;
1209 FL void
1210 free_child(int pid)
1212 sigset_t nset, oset;
1213 struct child *cp;
1214 NYD_ENTER;
1216 sigemptyset(&nset);
1217 sigaddset(&nset, SIGCHLD);
1218 sigprocmask(SIG_BLOCK, &nset, &oset);
1220 if ((cp = _findchild(pid, FAL0)) != NULL) {
1221 if (cp->done)
1222 _delchild(cp);
1223 else
1224 cp->free = 1;
1227 sigprocmask(SIG_SETMASK, &oset, NULL);
1228 NYD_LEAVE;
1231 FL bool_t
1232 wait_child(int pid, int *wait_status)
1234 sigset_t nset, oset;
1235 struct child *cp;
1236 int ws;
1237 bool_t rv;
1238 NYD_ENTER;
1240 sigemptyset(&nset);
1241 sigaddset(&nset, SIGCHLD);
1242 sigprocmask(SIG_BLOCK, &nset, &oset);
1244 cp = _findchild(pid, FAL0);
1245 if (cp != NULL) {
1246 while (!cp->done)
1247 sigsuspend(&oset);
1248 ws = cp->status;
1249 _delchild(cp);
1250 } else
1251 ws = 0;
1253 sigprocmask(SIG_SETMASK, &oset, NULL);
1255 if (wait_status != NULL)
1256 *wait_status = ws;
1257 rv = (WIFEXITED(ws) && WEXITSTATUS(ws) == 0);
1258 NYD_LEAVE;
1259 return rv;
1262 /* s-it-mode */