Bump S-nail v14.9.6 ("Marsh tit abiding a snow storm"), 2017-12-05
[s-mailx.git] / popen.c
blob3e2b72a7694fe7de00a3b927945b960806164430
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 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
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 #define READ 0
43 #define WRITE 1
45 struct fp {
46 struct fp *link;
47 int omode;
48 int pid;
49 enum {
50 FP_RAW,
52 FP_IMAP = 1u<<3,
53 FP_MAILDIR = 1u<<4,
54 FP_HOOK = 1u<<5,
55 FP_PIPE = 1u<<6,
56 FP_MASK = (1u<<7) - 1,
57 /* TODO FP_UNLINK: should be in a separated process so that unlinking
58 * TODO the temporary "garbage" is "safe"(r than it is like that) */
59 FP_UNLINK = 1u<<9,
60 FP_TERMIOS = 1u<<10
61 } flags;
62 long offset;
63 FILE *fp;
64 char *realfile;
65 char *save_cmd;
66 struct termios *fp_tios;
67 n_sighdl_t fp_osigint; /* Only if FP_TERMIOS */
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 a_popen_scan_mode(char const *mode, int *omode);
87 static void register_file(FILE *fp, int omode, int pid,
88 int flags, char const *realfile, long offset,
89 char const *save_cmd, struct termios *tiosp,
90 n_sighdl_t osigint);
91 static enum okay _file_save(struct fp *fpp);
92 static int a_popen_file_load(int flags, int infd, int outfd,
93 char const *load_cmd);
94 static enum okay unregister_file(FILE *fp, struct termios **tiosp,
95 n_sighdl_t *osigint);
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 a_popen_sigchld(int signo);
106 static struct child *a_popen_child_find(int pid, bool_t create);
107 static void a_popen_child_del(struct child *cp);
109 static int
110 a_popen_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 | n_O_NOXY_BITS | O_TRUNC},
117 {"wx", O_WRONLY | O_CREAT | O_EXCL},
118 {"a", O_WRONLY | O_APPEND | O_CREAT | n_O_NOXY_BITS},
119 {"a+", O_RDWR | O_APPEND | O_CREAT | n_O_NOXY_BITS},
120 {"r+", O_RDWR},
121 {"w+", O_RDWR | O_CREAT | O_EXCL}
123 int i;
124 NYD2_ENTER;
126 for(i = 0; UICMP(z, i, <, n_NELEM(maps)); ++i)
127 if(!strcmp(maps[i].mode, mode)){
128 *omode = maps[i].omode;
129 i = 0;
130 goto jleave;
133 DBG( n_alert(_("Internal error: bad stdio open mode %s"), mode); )
134 n_err_no = n_ERR_INVAL;
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 pid, int flags,
144 char const *realfile, long offset, char const *save_cmd,
145 struct termios *tiosp, n_sighdl_t osigint)
147 struct fp *fpp;
148 NYD_ENTER;
150 assert(!(flags & FP_UNLINK) || realfile != NULL);
151 assert(!(flags & FP_TERMIOS) || tiosp != NULL);
153 fpp = smalloc(sizeof *fpp);
154 fpp->fp = fp;
155 fpp->omode = omode;
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->fp_tios = tiosp;
162 fpp->fp_osigint = osigint;
163 fpp->offset = offset;
164 fp_head = fpp;
165 NYD_LEAVE;
168 static enum okay
169 _file_save(struct fp *fpp)
171 char const *cmd[3];
172 int outfd;
173 enum okay rv;
174 NYD_ENTER;
176 if (fpp->omode == O_RDONLY) {
177 rv = OKAY;
178 goto jleave;
180 rv = STOP;
182 fflush(fpp->fp);
183 clearerr(fpp->fp);
185 /* Ensure the I/O library doesn't optimize the fseek(3) away! */
186 if(!n_real_seek(fpp->fp, fpp->offset, SEEK_SET)){
187 outfd = n_err_no;
188 n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
189 n_shexp_quote_cp(fpp->realfile, FAL0), n_err_to_doc(outfd));
190 goto jleave;
193 #ifdef HAVE_IMAP
194 if ((fpp->flags & FP_MASK) == FP_IMAP) {
195 rv = imap_append(fpp->realfile, fpp->fp, fpp->offset);
196 goto jleave;
198 #endif
200 if ((fpp->flags & FP_MASK) == FP_MAILDIR) {
201 rv = maildir_append(fpp->realfile, fpp->fp, fpp->offset);
202 goto jleave;
205 outfd = open(fpp->realfile,
206 ((fpp->omode | O_CREAT | (fpp->omode & O_APPEND ? 0 : O_TRUNC) |
207 n_O_NOXY_BITS) & ~O_EXCL), 0666);
208 if (outfd == -1) {
209 outfd = n_err_no;
210 n_err(_("Fatal: cannot create %s: %s\n"),
211 n_shexp_quote_cp(fpp->realfile, FAL0), n_err_to_doc(outfd));
212 goto jleave;
215 cmd[2] = NULL;
216 switch(fpp->flags & FP_MASK){
217 case FP_HOOK:
218 cmd[0] = ok_vlook(SHELL);
219 cmd[1] = "-c";
220 cmd[2] = fpp->save_cmd;
221 break;
222 default:
223 cmd[0] = "cat";
224 cmd[1] = NULL;
225 break;
227 if (n_child_run(cmd[0], 0, fileno(fpp->fp), outfd,
228 cmd[1], cmd[2], NULL, NULL, NULL) >= 0)
229 rv = OKAY;
231 close(outfd);
232 jleave:
233 NYD_LEAVE;
234 return rv;
237 static int
238 a_popen_file_load(int flags, int infd, int outfd, char const *load_cmd){
239 char const *cmd[3];
240 int rv;
241 NYD2_ENTER;
243 cmd[2] = NULL;
244 switch(flags & FP_MASK){
245 case FP_IMAP:
246 case FP_MAILDIR:
247 rv = 0;
248 goto jleave;
249 case FP_HOOK:
250 cmd[0] = ok_vlook(SHELL);
251 cmd[1] = "-c";
252 cmd[2] = load_cmd;
253 break;
254 default:
255 cmd[0] = "cat";
256 cmd[1] = NULL;
257 break;
260 rv = n_child_run(cmd[0], 0, infd, outfd, cmd[1], cmd[2], NULL, NULL, NULL);
261 jleave:
262 NYD2_LEAVE;
263 return rv;
266 static enum okay
267 unregister_file(FILE *fp, struct termios **tiosp, n_sighdl_t *osigint)
269 struct fp **pp, *p;
270 enum okay rv = OKAY;
271 NYD_ENTER;
273 if (tiosp)
274 *tiosp = NULL;
276 for (pp = &fp_head; (p = *pp) != NULL; pp = &p->link)
277 if (p->fp == fp) {
278 switch (p->flags & FP_MASK) {
279 case FP_RAW:
280 case FP_PIPE:
281 break;
282 default:
283 rv = _file_save(p);
284 break;
286 if ((p->flags & FP_UNLINK) && unlink(p->realfile))
287 rv = STOP;
289 *pp = p->link;
290 if (p->save_cmd != NULL)
291 free(p->save_cmd);
292 if (p->realfile != NULL)
293 free(p->realfile);
294 if (p->flags & FP_TERMIOS) {
295 if (tiosp != NULL) {
296 *tiosp = p->fp_tios;
297 *osigint = p->fp_osigint;
298 } else
299 free(p->fp_tios);
301 free(p);
302 goto jleave;
304 DBGOR(n_panic, n_alert)(_("Invalid file pointer"));
305 rv = STOP;
306 jleave:
307 NYD_LEAVE;
308 return rv;
311 static int
312 file_pid(FILE *fp)
314 int rv;
315 struct fp *p;
316 NYD2_ENTER;
318 rv = -1;
319 for (p = fp_head; p; p = p->link)
320 if (p->fp == fp) {
321 rv = p->pid;
322 break;
324 NYD2_LEAVE;
325 return rv;
328 static void
329 a_popen_jobsigs_up(void){
330 sigset_t nset, oset;
331 NYD2_ENTER;
333 sigfillset(&nset);
335 sigprocmask(SIG_BLOCK, &nset, &oset);
336 a_popen_otstp = safe_signal(SIGTSTP, &a_popen_jobsig);
337 a_popen_ottin = safe_signal(SIGTTIN, &a_popen_jobsig);
338 a_popen_ottou = safe_signal(SIGTTOU, &a_popen_jobsig);
340 /* This assumes oset contains nothing but SIGCHLD, so to say */
341 sigdelset(&oset, SIGTSTP);
342 sigdelset(&oset, SIGTTIN);
343 sigdelset(&oset, SIGTTOU);
344 sigprocmask(SIG_SETMASK, &oset, NULL);
345 NYD2_LEAVE;
348 static void
349 a_popen_jobsigs_down(void){
350 sigset_t nset, oset;
351 NYD2_ENTER;
353 sigfillset(&nset);
355 sigprocmask(SIG_BLOCK, &nset, &oset);
356 safe_signal(SIGTSTP, a_popen_otstp);
357 safe_signal(SIGTTIN, a_popen_ottin);
358 safe_signal(SIGTTOU, a_popen_ottou);
360 sigaddset(&oset, SIGTSTP);
361 sigaddset(&oset, SIGTTIN);
362 sigaddset(&oset, SIGTTOU);
363 sigprocmask(SIG_SETMASK, &oset, NULL);
364 NYD2_LEAVE;
367 static void
368 a_popen_jobsig(int sig){
369 sighandler_type oldact;
370 sigset_t nset;
371 bool_t hadsig;
372 NYD_X; /* Signal handler */
374 hadsig = (a_popen_hadsig != 0);
375 a_popen_hadsig = 1;
376 if(!hadsig)
377 n_TERMCAP_SUSPEND(TRU1);
379 oldact = safe_signal(sig, SIG_DFL);
381 sigemptyset(&nset);
382 sigaddset(&nset, sig);
383 sigprocmask(SIG_UNBLOCK, &nset, NULL);
384 n_raise(sig);
385 sigprocmask(SIG_BLOCK, &nset, NULL);
387 safe_signal(sig, oldact);
390 static void
391 a_popen_sigchld(int signo){
392 pid_t pid;
393 int status;
394 struct child *cp;
395 NYD_X; /* Signal handler */
396 n_UNUSED(signo);
398 for (;;) {
399 pid = waitpid(-1, &status, WNOHANG);
400 if (pid <= 0) {
401 if (pid == -1 && n_err_no == n_ERR_INTR)
402 continue;
403 break;
406 if ((cp = a_popen_child_find(pid, FAL0)) != NULL) {
407 cp->done = 1;
408 if (cp->free)
409 cp->pid = -1; /* XXX Was _delchild(cp);# */
410 else {
411 cp->status = status;
417 static struct child *
418 a_popen_child_find(int pid, bool_t create){
419 struct child **cpp, *cp;
420 NYD2_ENTER;
422 for(cpp = &_popen_child; (cp = *cpp) != NULL && cp->pid != pid;
423 cpp = &(*cpp)->link)
426 if(cp == NULL && create)
427 (*cpp = cp = scalloc(1, sizeof *cp))->pid = pid;
428 NYD2_LEAVE;
429 return cp;
432 static void
433 a_popen_child_del(struct child *cp){
434 struct child **cpp;
435 NYD2_ENTER;
437 cpp = &_popen_child;
439 for(;;){
440 if(*cpp == cp){
441 *cpp = cp->link;
442 free(cp);
443 break;
445 if(*(cpp = &(*cpp)->link) == NULL){
446 DBG( n_err("! a_popen_child_del(): implementation error\n"); )
447 break;
450 NYD2_LEAVE;
453 FL void
454 n_child_manager_start(void)
456 struct sigaction nact, oact;
457 NYD_ENTER;
459 nact.sa_handler = &a_popen_sigchld;
460 sigemptyset(&nact.sa_mask);
461 nact.sa_flags = SA_RESTART
462 #ifdef SA_NOCLDSTOP
463 | SA_NOCLDSTOP
464 #endif
466 if (sigaction(SIGCHLD, &nact, &oact) != 0)
467 n_panic(_("Cannot install signal handler for child process management"));
468 NYD_LEAVE;
471 FL FILE *
472 safe_fopen(char const *file, char const *oflags, int *xflags)
474 int osflags, fd;
475 FILE *fp = NULL;
476 NYD2_ENTER; /* (only for Fopen() and once in go.c) */
478 if (a_popen_scan_mode(oflags, &osflags) < 0)
479 goto jleave;
480 osflags |= _O_CLOEXEC;
481 if (xflags != NULL)
482 *xflags = osflags;
484 if ((fd = open(file, osflags, 0666)) == -1)
485 goto jleave;
486 _CLOEXEC_SET(fd);
488 fp = fdopen(fd, oflags);
489 jleave:
490 NYD2_LEAVE;
491 return fp;
494 FL FILE *
495 Fopen(char const *file, char const *oflags)
497 FILE *fp;
498 int osflags;
499 NYD_ENTER;
501 if ((fp = safe_fopen(file, oflags, &osflags)) != NULL)
502 register_file(fp, osflags, 0, FP_RAW, NULL, 0L, NULL, NULL,NULL);
503 NYD_LEAVE;
504 return fp;
507 FL FILE *
508 Fdopen(int fd, char const *oflags, bool_t nocloexec)
510 FILE *fp;
511 int osflags;
512 NYD_ENTER;
514 a_popen_scan_mode(oflags, &osflags);
515 if (!nocloexec)
516 osflags |= _O_CLOEXEC; /* Ensured to be set by caller as documented! */
518 if ((fp = fdopen(fd, oflags)) != NULL)
519 register_file(fp, osflags, 0, FP_RAW, NULL, 0L, NULL, NULL,NULL);
520 NYD_LEAVE;
521 return fp;
524 FL int
525 Fclose(FILE *fp)
527 int i = 0;
528 NYD_ENTER;
530 if (unregister_file(fp, NULL, NULL) == OKAY)
531 i |= 1;
532 if (fclose(fp) == 0)
533 i |= 2;
534 NYD_LEAVE;
535 return (i == 3 ? 0 : EOF);
538 FL FILE *
539 n_fopen_any(char const *file, char const *oflags, /* TODO should take flags */
540 enum n_fopen_state *fs_or_null){ /* TODO as bits, return state */
541 /* TODO Support file locking upon open time */
542 long offset;
543 enum protocol p;
544 enum oflags rof;
545 int osflags, flags, omode, infd;
546 char const *cload, *csave;
547 enum n_fopen_state fs;
548 FILE *rv;
549 NYD_ENTER;
551 rv = NULL;
552 fs = n_FOPEN_STATE_NONE;
553 cload = csave = NULL;
555 if(a_popen_scan_mode(oflags, &osflags) < 0)
556 goto jleave;
558 flags = 0;
559 rof = OF_RDWR | OF_UNLINK;
560 if(osflags & O_APPEND)
561 rof |= OF_APPEND;
562 omode = (osflags == O_RDONLY) ? R_OK : R_OK | W_OK;
564 /* We don't want to find mbox.bz2 when doing "copy * mbox", but only for
565 * "file mbox", so don't try hooks when writing */
566 p = which_protocol(csave = file, TRU1, ((omode & W_OK) == 0), &file);
567 fs = (enum n_fopen_state)p;
568 switch(p){
569 default:
570 goto jleave;
571 case n_PROTO_IMAP:
572 #ifdef HAVE_IMAP
573 file = csave;
574 flags |= FP_IMAP;
575 osflags = O_RDWR | O_APPEND | O_CREAT | n_O_NOXY_BITS;
576 infd = -1;
577 break;
578 #else
579 n_err_no = n_ERR_OPNOTSUPP;
580 goto jleave;
581 #endif
582 case n_PROTO_MAILDIR:
583 if(fs_or_null != NULL && !access(file, F_OK))
584 fs |= n_FOPEN_STATE_EXISTS;
585 flags |= FP_MAILDIR;
586 osflags = O_RDWR | O_APPEND | O_CREAT | n_O_NOXY_BITS;
587 infd = -1;
588 break;
589 case n_PROTO_FILE:{
590 struct n_file_type ft;
592 if(!(osflags & O_EXCL) && fs_or_null != NULL && !access(file, F_OK))
593 fs |= n_FOPEN_STATE_EXISTS;
595 if(n_filetype_exists(&ft, file)){
596 flags |= FP_HOOK;
597 cload = ft.ft_load_dat;
598 csave = ft.ft_save_dat;
599 /* Cause truncation for compressor/hook output files */
600 osflags &= ~O_APPEND;
601 rof &= ~OF_APPEND;
602 if((infd = open(file, (omode & W_OK ? O_RDWR : O_RDONLY))) == -1){
603 if(!(osflags & O_CREAT) || n_err_no != n_ERR_NOENT)
604 goto jleave;
606 fs |= n_FOPEN_STATE_EXISTS;
607 }else{
608 /*flags |= FP_RAW;*/
609 rv = Fopen(file, oflags);
610 if((osflags & O_EXCL) && rv == NULL)
611 fs |= n_FOPEN_STATE_EXISTS;
612 goto jleave;
614 }break;
617 /* Note rv is not yet register_file()d, fclose() it in error path! */
618 if((rv = Ftmp(NULL, "fopenany", rof)) == NULL){
619 n_perr(_("tmpfile"), 0);
620 goto jerr;
623 if(flags & (FP_IMAP | FP_MAILDIR))
625 else if(infd >= 0){
626 if(a_popen_file_load(flags, infd, fileno(rv), cload) < 0){
627 jerr:
628 if(rv != NULL)
629 fclose(rv);
630 rv = NULL;
631 if(infd >= 0)
632 close(infd);
633 goto jleave;
635 }else{
636 if((infd = creat(file, 0666)) == -1){
637 fclose(rv);
638 rv = NULL;
639 goto jleave;
643 if(infd >= 0)
644 close(infd);
645 fflush(rv);
647 if(!(osflags & O_APPEND))
648 rewind(rv);
649 if((offset = ftell(rv)) == -1){
650 Fclose(rv);
651 rv = NULL;
652 goto jleave;
655 register_file(rv, osflags, 0, flags, file, offset, csave, NULL,NULL);
656 jleave:
657 if(fs_or_null != NULL)
658 *fs_or_null = fs;
659 NYD_LEAVE;
660 return rv;
663 FL FILE *
664 Ftmp(char **fn, char const *namehint, enum oflags oflags)
666 /* The 8 is arbitrary but leaves room for a six character suffix (the
667 * POSIX minimum path length is 14, though we don't check that XXX).
668 * 8 should be more than sufficient given that we use base64url encoding
669 * for our random string */
670 enum {_RANDCHARS = 8u};
672 char *cp_base, *cp;
673 size_t maxname, xlen, i;
674 char const *tmpdir;
675 int osoflags, fd, e;
676 bool_t relesigs;
677 FILE *fp;
678 NYD_ENTER;
680 assert(namehint != NULL);
681 assert((oflags & OF_WRONLY) || (oflags & OF_RDWR));
682 assert(!(oflags & OF_RDONLY));
683 assert(!(oflags & OF_REGISTER_UNLINK) || (oflags & OF_REGISTER));
685 fp = NULL;
686 relesigs = FAL0;
687 e = 0;
688 tmpdir = ok_vlook(TMPDIR);
689 maxname = NAME_MAX;
690 #ifdef HAVE_PATHCONF
691 { long pc;
693 if ((pc = pathconf(tmpdir, _PC_NAME_MAX)) != -1)
694 maxname = (size_t)pc;
696 #endif
698 if ((oflags & OF_SUFFIX) && *namehint != '\0') {
699 if ((xlen = strlen(namehint)) > maxname - _RANDCHARS) {
700 n_err_no = n_ERR_NAMETOOLONG;
701 goto jleave;
703 } else
704 xlen = 0;
706 /* Prepare the template string once, then iterate over the random range */
707 cp_base =
708 cp = smalloc(strlen(tmpdir) + 1 + maxname +1);
709 cp = sstpcpy(cp, tmpdir);
710 *cp++ = '/';
712 char *x = sstpcpy(cp, VAL_UAGENT);
713 *x++ = '-';
714 if (!(oflags & OF_SUFFIX))
715 x = sstpcpy(x, namehint);
717 i = PTR2SIZE(x - cp);
718 if (i > maxname - xlen - _RANDCHARS) {
719 size_t j = maxname - xlen - _RANDCHARS;
720 x -= i - j;
723 if ((oflags & OF_SUFFIX) && xlen > 0)
724 memcpy(x + _RANDCHARS, namehint, xlen);
726 x[xlen + _RANDCHARS] = '\0';
727 cp = x;
730 osoflags = O_CREAT | O_EXCL | _O_CLOEXEC;
731 osoflags |= (oflags & OF_WRONLY) ? O_WRONLY : O_RDWR;
732 if (oflags & OF_APPEND)
733 osoflags |= O_APPEND;
735 for(relesigs = TRU1, i = 0;; ++i){
736 memcpy(cp, n_random_create_cp(_RANDCHARS, NULL), _RANDCHARS);
738 hold_all_sigs();
740 if((fd = open(cp_base, osoflags, 0600)) != -1){
741 _CLOEXEC_SET(fd);
742 break;
744 if(i >= FTMP_OPEN_TRIES){
745 e = n_err_no;
746 goto jfree;
748 rele_all_sigs();
751 if (oflags & OF_REGISTER) {
752 char const *osflags = (oflags & OF_RDWR ? "w+" : "w");
753 int osflagbits;
755 a_popen_scan_mode(osflags, &osflagbits); /* TODO osoflags&xy ?!!? */
756 if ((fp = fdopen(fd, osflags)) != NULL)
757 register_file(fp, osflagbits | _O_CLOEXEC, 0,
758 (FP_RAW | (oflags & OF_REGISTER_UNLINK ? FP_UNLINK : 0)),
759 cp_base, 0L, NULL, NULL,NULL);
760 } else
761 fp = fdopen(fd, (oflags & OF_RDWR ? "w+" : "w"));
763 if (fp == NULL || (oflags & OF_UNLINK)) {
764 e = n_err_no;
765 unlink(cp_base);
766 goto jfree;
769 if (fn != NULL)
770 *fn = cp_base;
771 else
772 free(cp_base);
773 jleave:
774 if (relesigs && (fp == NULL || !(oflags & OF_HOLDSIGS)))
775 rele_all_sigs();
776 if (fp == NULL)
777 n_err_no = e;
778 NYD_LEAVE;
779 return fp;
780 jfree:
781 if ((cp = cp_base) != NULL)
782 free(cp);
783 goto jleave;
786 FL void
787 Ftmp_release(char **fn)
789 char *cp;
790 NYD_ENTER;
792 cp = *fn;
793 *fn = NULL;
794 if (cp != NULL) {
795 unlink(cp);
796 rele_all_sigs();
797 free(cp);
799 NYD_LEAVE;
802 FL void
803 Ftmp_free(char **fn) /* TODO DROP: OF_REGISTER_FREEPATH! */
805 char *cp;
806 NYD_ENTER;
808 cp = *fn;
809 *fn = NULL;
810 if (cp != NULL)
811 free(cp);
812 NYD_LEAVE;
815 FL bool_t
816 pipe_cloexec(int fd[2]){
817 bool_t rv;
818 NYD_ENTER;
820 rv = FAL0;
822 #ifdef HAVE_PIPE2
823 if(pipe2(fd, O_CLOEXEC) != -1)
824 rv = TRU1;
825 #else
826 if(pipe(fd) != -1){
827 n_fd_cloexec_set(fd[0]);
828 n_fd_cloexec_set(fd[1]);
829 rv = TRU1;
831 #endif
832 NYD_LEAVE;
833 return rv;
836 FL FILE *
837 Popen(char const *cmd, char const *mode, char const *sh,
838 char const **env_addon, int newfd1)
840 int p[2], myside, hisside, fd0, fd1, pid;
841 sigset_t nset;
842 char mod[2];
843 n_sighdl_t osigint;
844 struct termios *tiosp;
845 FILE *rv;
846 NYD_ENTER;
848 /* First clean up child structures */
849 /* C99 */{
850 struct child **cpp, *cp;
852 hold_all_sigs();
853 for (cpp = &_popen_child; *cpp != NULL;) {
854 if ((*cpp)->pid == -1) {
855 cp = *cpp;
856 *cpp = cp->link;
857 free(cp);
858 } else
859 cpp = &(*cpp)->link;
861 rele_all_sigs();
864 rv = NULL;
865 tiosp = NULL;
866 n_UNINIT(osigint, SIG_ERR);
867 mod[0] = '0', mod[1] = '\0';
869 if (!pipe_cloexec(p))
870 goto jleave;
872 if (*mode == 'r') {
873 myside = p[READ];
874 fd0 = n_CHILD_FD_PASS;
875 hisside = fd1 = p[WRITE];
876 mod[0] = *mode;
877 } else if (*mode == 'W') {
878 myside = p[WRITE];
879 hisside = fd0 = p[READ];
880 fd1 = newfd1;
881 mod[0] = 'w';
882 } else {
883 myside = p[WRITE];
884 hisside = fd0 = p[READ];
885 fd1 = n_CHILD_FD_PASS;
886 mod[0] = 'w';
889 /* In interactive mode both STDIN and STDOUT point to the terminal. If we
890 * pass through the TTY restore terminal attributes after pipe returns.
891 * XXX It shouldn't matter which FD we actually use in this case */
892 if ((n_psonce & n_PSO_INTERACTIVE) && (fd0 == n_CHILD_FD_PASS ||
893 fd1 == n_CHILD_FD_PASS)) {
894 osigint = n_signal(SIGINT, SIG_IGN);
895 tiosp = smalloc(sizeof *tiosp);
896 tcgetattr(STDIN_FILENO, tiosp);
897 n_TERMCAP_SUSPEND(TRU1);
900 sigemptyset(&nset);
902 if (cmd == (char*)-1) {
903 if ((pid = n_child_fork()) == -1)
904 n_perr(_("fork"), 0);
905 else if (pid == 0) {
906 union {char const *ccp; int (*ptf)(void); int es;} u;
907 n_child_prepare(&nset, fd0, fd1);
908 close(p[READ]);
909 close(p[WRITE]);
910 /* TODO should close all other open FDs except stds and reset memory */
911 /* Standard I/O drives me insane! All we need is a sync operation
912 * that causes n_stdin to forget about any read buffer it may have.
913 * We cannot use fflush(3), this works with Musl and Solaris, but not
914 * with GlibC. (For at least pipes.) We cannot use fdreopen(),
915 * because this function does not exist! Luckily (!!!) we only use
916 * n_stdin not stdin in our child, otherwise all bets were off!
917 * TODO (Unless we would fiddle around with FILE* directly:
918 * TODO #ifdef __GLIBC__
919 * TODO n_stdin->_IO_read_ptr = n_stdin->_IO_read_end;
920 * TODO #elif *BSD*
921 * TODO n_stdin->_r = 0;
922 * TODO #elif n_OS_SOLARIS || n_OS_SUNOS
923 * TODO n_stdin->_cnt = 0;
924 * TODO #endif
925 * TODO ) which should have additional config test for sure! */
926 n_stdin = fdopen(STDIN_FILENO, "r");
927 /*n_stdout = fdopen(STDOUT_FILENO, "w");*/
928 /*n_stderr = fdopen(STDERR_FILENO, "w");*/
929 u.ccp = sh;
930 u.es = (*u.ptf)();
931 /*fflush(NULL);*/
932 _exit(u.es);
934 } else if (sh == NULL) {
935 pid = n_child_start(cmd, &nset, fd0, fd1, NULL, NULL, NULL, env_addon);
936 } else {
937 pid = n_child_start(sh, &nset, fd0, fd1, "-c", cmd, NULL, env_addon);
939 if (pid < 0) {
940 close(p[READ]);
941 close(p[WRITE]);
942 goto jleave;
944 close(hisside);
945 if ((rv = fdopen(myside, mod)) != NULL)
946 register_file(rv, 0, pid,
947 (tiosp == NULL ? FP_PIPE : FP_PIPE | FP_TERMIOS),
948 NULL, 0L, NULL, tiosp, osigint);
949 else
950 close(myside);
951 jleave:
952 if(rv == NULL && tiosp != NULL){
953 n_TERMCAP_RESUME(TRU1);
954 tcsetattr(STDIN_FILENO, TCSAFLUSH, tiosp);
955 n_free(tiosp);
956 n_signal(SIGINT, osigint);
958 NYD_LEAVE;
959 return rv;
962 FL bool_t
963 Pclose(FILE *ptr, bool_t dowait)
965 n_sighdl_t osigint;
966 struct termios *tiosp;
967 int pid;
968 bool_t rv = FAL0;
969 NYD_ENTER;
971 pid = file_pid(ptr);
972 if(pid < 0)
973 goto jleave;
975 unregister_file(ptr, &tiosp, &osigint);
976 fclose(ptr);
978 if(dowait){
979 hold_all_sigs();
980 rv = n_child_wait(pid, NULL);
981 if(tiosp != NULL){
982 n_TERMCAP_RESUME(TRU1);
983 tcsetattr(STDIN_FILENO, TCSAFLUSH, tiosp);
984 n_signal(SIGINT, osigint);
986 rele_all_sigs();
987 }else{
988 n_child_free(pid);
989 rv = TRU1;
992 if(tiosp != NULL)
993 free(tiosp);
994 jleave:
995 NYD_LEAVE;
996 return rv;
999 VL int
1000 n_psignal(FILE *fp, int sig){
1001 int rv;
1002 NYD2_ENTER;
1004 if((rv = file_pid(fp)) >= 0){
1005 struct child *cp;
1007 if((cp = a_popen_child_find(rv, FAL0)) != NULL){
1008 if((rv = kill(rv, sig)) != 0)
1009 rv = n_err_no;
1010 }else
1011 rv = -1;
1013 NYD2_LEAVE;
1014 return rv;
1017 FL FILE *
1018 n_pager_open(void)
1020 char const *env_add[2], *pager;
1021 FILE *rv;
1022 NYD_ENTER;
1024 assert(n_psonce & n_PSO_INTERACTIVE);
1026 pager = n_pager_get(env_add + 0);
1027 env_add[1] = NULL;
1029 if ((rv = Popen(pager, "w", NULL, env_add, n_CHILD_FD_PASS)) == NULL)
1030 n_perr(pager, 0);
1031 NYD_LEAVE;
1032 return rv;
1035 FL bool_t
1036 n_pager_close(FILE *fp)
1038 sighandler_type sh;
1039 bool_t rv;
1040 NYD_ENTER;
1042 sh = safe_signal(SIGPIPE, SIG_IGN);
1043 rv = Pclose(fp, TRU1);
1044 safe_signal(SIGPIPE, sh);
1045 NYD_LEAVE;
1046 return rv;
1049 FL void
1050 close_all_files(void)
1052 NYD_ENTER;
1053 while (fp_head != NULL)
1054 if ((fp_head->flags & FP_MASK) == FP_PIPE)
1055 Pclose(fp_head->fp, TRU1);
1056 else
1057 Fclose(fp_head->fp);
1058 NYD_LEAVE;
1061 /* TODO The entire n_child_ series should be replaced with an object, but
1062 * TODO at least have carrier arguments. We anyway need a command manager
1063 * TODO that keeps track and knows how to handle job control ++++! */
1065 FL int
1066 n_child_run(char const *cmd, sigset_t *mask_or_null, int infd, int outfd,
1067 char const *a0_or_null, char const *a1_or_null, char const *a2_or_null,
1068 char const **env_addon_or_null, int *wait_status_or_null)
1070 sigset_t nset, oset;
1071 sighandler_type soldint;
1072 int rv, e;
1073 enum {a_NONE = 0, a_INTIGN = 1<<0, a_TTY = 1<<1} f;
1074 NYD_ENTER;
1076 f = a_NONE;
1077 n_UNINIT(soldint, SIG_ERR);
1079 /* TODO Of course this is a joke given that during a "p*" the PAGER may
1080 * TODO be up and running while we play around like this... but i guess
1081 * TODO this can't be helped at all unless we perform complete and true
1082 * TODO process group separation and ensure we don't deadlock us out
1083 * TODO via TTY jobcontrol signal storms (could this really happen?).
1084 * TODO Or have a built-in pager. Or query any necessity BEFORE we start
1085 * TODO any action, and shall we find we need to run programs dump it
1086 * TODO all into a temporary file which is then passed through to the
1087 * TODO PAGER. Ugh. That still won't help for "needsterminal" anyway */
1088 if(infd == n_CHILD_FD_PASS || outfd == n_CHILD_FD_PASS){
1089 soldint = safe_signal(SIGINT, SIG_IGN);
1090 f = a_INTIGN;
1092 if(n_psonce & n_PSO_INTERACTIVE){
1093 f |= a_TTY;
1094 tcgetattr((n_psonce & n_PSO_TTYIN ? STDIN_FILENO : STDOUT_FILENO),
1095 &a_popen_tios);
1096 n_TERMCAP_SUSPEND(FAL0);
1097 sigfillset(&nset);
1098 sigdelset(&nset, SIGCHLD);
1099 sigdelset(&nset, SIGINT);
1100 /* sigdelset(&nset, SIGPIPE); TODO would need a handler */
1101 sigprocmask(SIG_BLOCK, &nset, &oset);
1102 a_popen_hadsig = 0;
1103 a_popen_jobsigs_up();
1107 if((rv = n_child_start(cmd, mask_or_null, infd, outfd, a0_or_null,
1108 a1_or_null, a2_or_null, env_addon_or_null)) < 0){
1109 e = n_err_no;
1110 rv = -1;
1111 }else{
1112 int ws;
1114 e = 0;
1115 if(n_child_wait(rv, &ws))
1116 rv = 0;
1117 else if(wait_status_or_null == NULL || !WIFEXITED(ws)){
1118 if(ok_blook(bsdcompat) || ok_blook(bsdmsgs))
1119 n_err(_("Fatal error in process\n"));
1120 e = n_ERR_CHILD;
1121 rv = -1;
1123 if(wait_status_or_null != NULL)
1124 *wait_status_or_null = ws;
1127 if(f & a_TTY){
1128 a_popen_jobsigs_down();
1129 n_TERMCAP_RESUME(a_popen_hadsig ? TRU1 : FAL0);
1130 tcsetattr(((n_psonce & n_PSO_TTYIN) ? STDIN_FILENO : STDOUT_FILENO),
1131 ((n_psonce & n_PSO_TTYIN) ? TCSAFLUSH : TCSADRAIN), &a_popen_tios);
1132 sigprocmask(SIG_SETMASK, &oset, NULL);
1134 if(f & a_INTIGN){
1135 if(soldint != SIG_IGN)
1136 safe_signal(SIGINT, soldint);
1139 if(e != 0)
1140 n_err_no = e;
1141 NYD_LEAVE;
1142 return rv;
1145 FL int
1146 n_child_start(char const *cmd, sigset_t *mask_or_null, int infd, int outfd,
1147 char const *a0_or_null, char const *a1_or_null, char const *a2_or_null,
1148 char const **env_addon_or_null)
1150 int rv, e;
1151 NYD_ENTER;
1153 if ((rv = n_child_fork()) == -1) {
1154 e = n_err_no;
1155 n_perr(_("fork"), 0);
1156 n_err_no = e;
1157 rv = -1;
1158 } else if (rv == 0) {
1159 char *argv[128];
1160 int i;
1162 if (env_addon_or_null != NULL) {
1163 extern char **environ;
1164 size_t ei, ei_orig, ai, ai_orig;
1165 char **env;
1167 /* TODO note we don't check the POSIX limit:
1168 * the total space used to store the environment and the arguments to
1169 * the process is limited to {ARG_MAX} bytes */
1170 for (ei = 0; environ[ei] != NULL; ++ei)
1172 ei_orig = ei;
1173 for (ai = 0; env_addon_or_null[ai] != NULL; ++ai)
1175 ai_orig = ai;
1176 env = ac_alloc(sizeof(*env) * (ei + ai +1));
1177 memcpy(env, environ, sizeof(*env) * ei);
1179 /* Replace all those keys that yet exist */
1180 while (ai-- > 0) {
1181 char const *ee, *kvs;
1182 size_t kl;
1184 ee = env_addon_or_null[ai];
1185 kvs = strchr(ee, '=');
1186 assert(kvs != NULL);
1187 kl = PTR2SIZE(kvs - ee);
1188 assert(kl > 0);
1189 for (ei = ei_orig; ei-- > 0;) {
1190 char const *ekvs = strchr(env[ei], '=');
1191 if (ekvs != NULL && kl == PTR2SIZE(ekvs - env[ei]) &&
1192 !memcmp(ee, env[ei], kl)) {
1193 env[ei] = n_UNCONST(ee);
1194 env_addon_or_null[ai] = NULL;
1195 break;
1200 /* And append the rest */
1201 for (ei = ei_orig, ai = ai_orig; ai-- > 0;)
1202 if (env_addon_or_null[ai] != NULL)
1203 env[ei++] = n_UNCONST(env_addon_or_null[ai]);
1205 env[ei] = NULL;
1206 environ = env;
1209 i = (int)getrawlist(TRU1, argv, n_NELEM(argv), cmd, strlen(cmd));
1211 if ((argv[i++] = n_UNCONST(a0_or_null)) != NULL &&
1212 (argv[i++] = n_UNCONST(a1_or_null)) != NULL &&
1213 (argv[i++] = n_UNCONST(a2_or_null)) != NULL)
1214 argv[i] = NULL;
1215 n_child_prepare(mask_or_null, infd, outfd);
1216 execvp(argv[0], argv);
1217 perror(argv[0]);
1218 _exit(n_EXIT_ERR);
1220 NYD_LEAVE;
1221 return rv;
1224 FL int
1225 n_child_fork(void){
1226 /* Strictly speaking we should do so in the waitpid(2) case too, but since
1227 * we explicitly waitpid(2) on the pid if just the structure exists, which
1228 * n_child_wait() does in the parent, all is fine */
1229 #if n_SIGSUSPEND_NOT_WAITPID
1230 sigset_t nset, oset;
1231 #endif
1232 struct child *cp;
1233 int pid;
1234 NYD2_ENTER;
1236 #if n_SIGSUSPEND_NOT_WAITPID
1237 sigfillset(&nset);
1238 sigprocmask(SIG_BLOCK, &nset, &oset);
1239 #endif
1241 cp = a_popen_child_find(0, TRU1);
1243 if((cp->pid = pid = fork()) == -1){
1244 a_popen_child_del(cp);
1245 n_perr(_("fork"), 0);
1248 #if n_SIGSUSPEND_NOT_WAITPID
1249 sigprocmask(SIG_SETMASK, &oset, NULL);
1250 #endif
1251 NYD2_LEAVE;
1252 return pid;
1255 FL void
1256 n_child_prepare(sigset_t *nset_or_null, int infd, int outfd)
1258 int i;
1259 sigset_t fset;
1260 NYD_ENTER;
1262 /* All file descriptors other than 0, 1, and 2 are supposed to be cloexec */
1263 /* TODO WHAT IS WITH STDERR_FILENO DAMN? */
1264 if ((i = (infd == n_CHILD_FD_NULL)))
1265 infd = open(n_path_devnull, O_RDONLY);
1266 if (infd >= 0) {
1267 dup2(infd, STDIN_FILENO);
1268 if (i)
1269 close(infd);
1272 if ((i = (outfd == n_CHILD_FD_NULL)))
1273 outfd = open(n_path_devnull, O_WRONLY);
1274 if (outfd >= 0) {
1275 dup2(outfd, STDOUT_FILENO);
1276 if (i)
1277 close(outfd);
1280 if (nset_or_null != NULL) {
1281 for (i = 1; i < NSIG; ++i)
1282 if (sigismember(nset_or_null, i))
1283 safe_signal(i, SIG_IGN);
1284 if (!sigismember(nset_or_null, SIGINT))
1285 safe_signal(SIGINT, SIG_DFL);
1288 sigemptyset(&fset);
1289 sigprocmask(SIG_SETMASK, &fset, NULL);
1290 NYD_LEAVE;
1293 FL void
1294 n_child_free(int pid){
1295 sigset_t nset, oset;
1296 struct child *cp;
1297 NYD2_ENTER;
1299 sigemptyset(&nset);
1300 sigaddset(&nset, SIGCHLD);
1301 sigprocmask(SIG_BLOCK, &nset, &oset);
1303 if((cp = a_popen_child_find(pid, FAL0)) != NULL){
1304 if(cp->done)
1305 a_popen_child_del(cp);
1306 else
1307 cp->free = TRU1;
1310 sigprocmask(SIG_SETMASK, &oset, NULL);
1311 NYD2_LEAVE;
1314 FL bool_t
1315 n_child_wait(int pid, int *wait_status_or_null){
1316 #if !n_SIGSUSPEND_NOT_WAITPID
1317 sigset_t oset;
1318 #endif
1319 sigset_t nset;
1320 struct child *cp;
1321 int ws;
1322 bool_t rv;
1323 NYD_ENTER;
1325 #if !n_SIGSUSPEND_NOT_WAITPID
1326 sigemptyset(&nset);
1327 sigaddset(&nset, SIGCHLD);
1328 sigprocmask(SIG_BLOCK, &nset, &oset);
1329 #endif
1331 if((cp = a_popen_child_find(pid, FAL0)) != NULL){
1332 #if n_SIGSUSPEND_NOT_WAITPID
1333 sigfillset(&nset);
1334 sigdelset(&nset, SIGCHLD);
1335 while(!cp->done)
1336 sigsuspend(&nset); /* TODO we should allow more than SIGCHLD!! */
1337 ws = cp->status;
1338 #else
1339 waitpid(pid, &ws, 0);
1340 #endif
1341 a_popen_child_del(cp);
1342 }else
1343 ws = 0;
1345 #if !n_SIGSUSPEND_NOT_WAITPID
1346 sigprocmask(SIG_SETMASK, &oset, NULL);
1347 #endif
1349 if(wait_status_or_null != NULL)
1350 *wait_status_or_null = ws;
1351 rv = (WIFEXITED(ws) && WEXITSTATUS(ws) == 0);
1352 NYD_LEAVE;
1353 return rv;
1356 /* s-it-mode */