3 * $Id: exec.c,v 1.4 2001/02/03 20:30:03 mdw Exp $
5 * Source and target for executable programs
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of the `fw' port forwarder.
14 * `fw' is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * `fw' is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with `fw'; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Revision history --------------------------------------------------*
32 * Revision 1.4 2001/02/03 20:30:03 mdw
33 * Support re-reading config files on SIGHUP.
35 * Revision 1.3 2000/07/01 11:28:52 mdw
36 * Use new mLib selbuf features.
38 * Revision 1.2 1999/10/22 22:46:17 mdw
39 * When a non-file endpoint is attached to a file, keep the file endpoint
40 * open until the nonfile is done. This stops socket sources from
41 * resetting their connection limits too early.
43 * Revision 1.1 1999/07/26 23:33:32 mdw
44 * New sources and targets.
48 /*----- Header files ------------------------------------------------------*/
61 #include <sys/types.h>
68 # include <sys/resource.h>
72 extern char **environ;
80 #include <mLib/alloc.h>
81 #include <mLib/dstr.h>
83 #include <mLib/fdflags.h>
84 #include <mLib/report.h>
86 #include <mLib/selbuf.h>
101 /*----- Data structures ---------------------------------------------------*/
103 /* --- Resource usage --- */
105 #ifdef HAVE_SETRLIMIT
107 typedef struct xlimit {
108 #define R(r, n) struct rlimit n;
114 /* --- Environment variable modifications --- */
116 typedef struct xenv {
126 /* --- Program options --- */
128 typedef struct xopts {
137 #ifdef HAVE_SETRLIMIT
144 /* --- Executable program arguments --- */
146 typedef struct xargs {
152 #define XARGS_SZ(n) (sizeof(xargs) + sizeof(char *) * (n))
154 /* --- Executable endpoints --- */
156 typedef struct xept {
158 struct xept *next, *prev;
168 #define XEF_CLOSE 16u
171 /* --- Executable program data --- */
173 typedef struct xdata {
178 /* --- Executable source block --- */
180 typedef struct xsource {
185 /* --- Executable target block --- */
187 typedef struct xtarget {
192 /*----- Static variables --------------------------------------------------*/
194 static xopts exec_opts = { 1, 0, 0, 0, -1, -1, 0, &exec_opts.env };
195 static xept *xept_list;
197 static sym_table env;
199 /*----- Fiddling about with resource limits -------------------------------*/
201 #ifdef HAVE_SETRLIMIT
203 /* --- Table mapping user-level names to OS interface bits --- */
205 typedef struct rlimit_ent {
212 static rlimit_ent rlimits[] = {
213 #define R(r, n) { #n, #r, r, offsetof(xlimit, n) },
218 #define RLIMIT(xl, o) ((struct rlimit *)((char *)(xl) + (o)))
220 /* --- @rlimit_get@ --- *
222 * Arguments: @xlimit *xl@ = pointer to limit structure
226 * Use: Initializes a limit structure from the current limits.
229 static void rlimit_get(xlimit *xl)
233 for (r = rlimits; r->name; r++) {
234 if (getrlimit(r->r, RLIMIT(xl, r->off))) {
235 moan("couldn't read %s: %s", r->rname, strerror(errno));
241 /* --- @rlimit_set@ --- *
243 * Arguments: @xlimit *xl@ = pointer to limit structure
247 * Use: Sets resource limits from the supplied limits structure.
250 static void rlimit_set(xlimit *xl)
254 for (r = rlimits; r->name; r++) {
255 if (setrlimit(r->r, RLIMIT(xl, r->off))) {
256 moan("couldn't set %s: %s", r->rname, strerror(errno));
262 /* --- @rlimit_option@ --- */
264 static int rlimit_option(xlimit *xl, scanner *sc)
266 CONF_BEGIN(sc, "rlimit", "resource limit")
267 enum { w_soft, w_hard, w_both } which = w_both;
272 /* --- Find out which resource is being fiddled --- */
278 for (r = rlimits; r->name; r++) {
279 if (strncmp(sc->d.buf, r->name, sc->d.len) == 0) {
280 if (r->name[sc->d.len] == 0) {
284 error(sc, "ambiguous resource limit name `%s'", sc->d.buf);
292 rl = RLIMIT(xl, chosen->off);
295 /* --- Look for hard or soft restrictions --- */
301 if (sc->t == CTOK_WORD) {
302 if ((i = conf_enum(sc, "soft,hard",
303 ENUM_ABBREV | ENUM_NONE, "limit type")) != -1)
308 /* --- Now read the new value --- */
312 if (sc->t != CTOK_WORD)
313 error(sc, "parse error, expected limit value");
315 if (conf_enum(sc, "unlimited,infinity",
316 ENUM_ABBREV | ENUM_NONE, "limit value") > -1)
321 v = strtol(sc->d.buf, &p, 0);
323 error(sc, "parse error, invalid limit value `%s'", sc->d.buf);
324 switch (tolower((unsigned char)*p)) {
326 case 'b': v *= 512; break;
329 case 'k': v *= 1024; break;
330 default: error(sc, "parse error, invalid limit scale `%c'", *p);
335 /* --- Store the limit value away --- */
343 if (v > rl->rlim_max)
344 error(sc, "soft limit %l exceeds hard limit %l for %s",
345 v, rl->rlim_max, chosen->rname);
350 if (rl->rlim_cur > v)
361 /*----- Environment fiddling ----------------------------------------------*/
363 /* --- @xenv_option@ --- *
365 * Arguments: @xopts *xo@ = pointer to options block
366 * @scanner *sc@ = pointer to scanner
368 * Returns: Nonzero if claimed
370 * Use: Parses environment variable assignments.
373 static int xenv_option(xopts *xo, scanner *sc)
375 CONF_BEGIN(sc, "env", "environment")
378 /* --- Unset a variable --- */
380 if (strcmp(sc->d.buf, "unset") == 0) {
382 if (sc->t != CTOK_WORD)
383 error(sc, "parse error, expected environment variable name");
385 xe->name = xstrdup(sc->d.buf);
392 /* --- Clear the entire environment --- */
394 if (strcmp(sc->d.buf, "clear") == 0) {
401 /* --- Allow `set' to be omitted if there's a prefix --- */
403 if (strcmp(sc->d.buf, "set") == 0)
408 /* --- Set a variable --- */
410 if (sc->t != CTOK_WORD)
411 error(sc, "parse error, expected environment variable name");
413 xe->name = xstrdup(sc->d.buf);
417 if (sc->t != CTOK_WORD)
418 error(sc, "parse error, expected environment variable value");
419 xe->value = xstrdup(sc->d.buf);
427 xo->etail = &xe->next;
430 /* --- Nothing else to try --- */
435 /* --- @xenv_apply@ --- *
437 * Arguments: @xenv *xe@ = pointer to a variable change list
441 * Use: Modifies the environment (in @env@) according to the list.
444 static void xenv_apply(xenv *xe)
449 env_put(&env, xe->name, xe->value);
460 /* --- @xenv_destroy@ --- *
462 * Arguments: @xenv *xe@ = pointer to a variable change list
466 * Use: Frees the memory used by an environment variable change list.
469 static void xenv_destroy(xenv *xe)
481 /*----- Miscellaneous good things -----------------------------------------*/
483 /* --- @x_tidy@ --- *
485 * Arguments: @xargs *xa@ = pointer to an arguments block
486 * @xopts *xo@ = pointer to an options block
490 * Use: Releases a reference to argument and options blocks.
493 static void x_tidy(xargs *xa, xopts *xo)
501 xenv_destroy(xo->env);
506 /*----- Executable endpoints ----------------------------------------------*/
508 /* --- @attach@ --- */
510 static void xept_error(char */*p*/, void */*v*/);
512 static void xept_attach(endpt *e, reffd *in, reffd *out)
514 xept *xe = (xept *)e;
518 /* --- Make a pipe for standard error --- */
521 fw_log(-1, "[%s] couldn't create pipe: %s", xe->desc, strerror(errno));
524 fdflags(fd[0], O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
526 /* --- Fork a child, and handle an error if there was one --- */
528 if ((kid = fork()) == -1) {
529 fw_log(-1, "[%s] couldn't fork: %s", xe->desc, strerror(errno));
535 /* --- Do the child thing --- */
540 /* --- Fiddle with the file descriptors --- *
542 * Attach the other endpoint's descriptors to standard input and output.
543 * Attach my pipe to standard error. Mark everything as blocking and
544 * not-to-be-closed-on-exec at this end.
548 if (dup2(in->fd, STDIN_FILENO) < 0 ||
549 dup2(out->fd, STDOUT_FILENO) < 0 ||
550 dup2(fd[1], STDERR_FILENO) < 0) {
551 moan("couldn't manipulate file descriptors: %s", strerror(errno));
560 fdflags(STDIN_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
561 fdflags(STDOUT_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
562 fdflags(STDERR_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
564 /* --- First of all set the @chroot@ prison --- */
566 if (xo->root && chroot(xo->root)) {
567 moan("couldn't set `%s' as filesystem root: %s",
568 xo->root, strerror(errno));
572 /* --- Now set the current directory --- */
574 if (xo->dir ? chdir(xo->dir) : xo->root ? chdir("/") : 0) {
575 moan("couldn't set `%s' as current directory: %s",
576 xo->dir ? xo->dir : "/", strerror(errno));
580 /* --- Set the resource limits --- */
582 #ifdef HAVE_SETRLIMIT
586 /* --- Set group id --- */
589 if (setgid(xo->gid)) {
590 moan("couldn't set gid %i: %s", xo->gid, strerror(errno));
593 #ifdef HAVE_SETGROUPS
594 if (setgroups(1, &xo->gid))
595 moan("warning: couldn't set group list to %i: %s", xo->gid,
600 /* --- Set uid --- */
603 if (setuid(xo->uid)) {
604 moan("couldn't set uid %i: %s", xo->uid, strerror(errno));
609 /* --- Play with signal dispositions --- */
611 signal(SIGPIPE, SIG_DFL);
613 /* --- Fiddle with the environment --- */
615 xenv_apply(exec_opts.env);
616 xenv_apply(xe->xo->env);
617 environ = env_export(&env);
619 /* --- Run the program --- */
621 execvp(xe->xa->file, xe->xa->argv);
622 moan("couldn't execute `%s': %s", xe->xa->file, strerror(errno));
626 /* --- The child's done; see to the parent --- */
629 selbuf_init(&xe->err, sel, fd[0], xept_error, xe);
631 xe->next = xept_list;
634 xept_list->prev = xe;
636 if (!(xe->xo->f & XF_NOLOG))
637 fw_log(-1, "[%s] started with pid %i", xe->desc, kid);
642 /* --- @xept_file@ --- */
644 static void xept_file(endpt *e, endpt *f)
646 xept *xe = (xept *)e;
650 /* --- @xept_close@ --- */
652 static void xept_close(endpt *e)
654 xept *xe = (xept *)e;
657 xe->f->ops->close(xe->f);
658 x_tidy(xe->xa, xe->xo);
664 /* --- @xept_destroy@ --- */
666 static void xept_destroy(xept *xe)
668 /* --- First emit the news about the process --- */
670 if (xe->xo->f & XF_NOLOG)
672 else if (WIFEXITED(xe->st)) {
673 if (WEXITSTATUS(xe->st) == 0)
674 fw_log(-1, "[%s] pid %i exited successfully", xe->desc, xe->kid);
676 fw_log(-1, "[%s] pid %i failed: status %i",
677 xe->desc, xe->kid, WEXITSTATUS(xe->st));
679 } else if (WIFSIGNALED(xe->st)) {
681 #ifdef HAVE_STRSIGNAL
682 s = strsignal(WTERMSIG(xe->st));
683 #elif HAVE__SYS_SIGLIST
684 s = _sys_siglist[WTERMSIG(xe->st)];
687 sprintf(buf, "signal %i", WTERMSIG(xe->st));
690 fw_log(-1, "[%s] pid %i failed: %s", xe->desc, xe->kid, s);
692 fw_log(-1, "[%s] pid %i failed: unrecognized status", xe->desc, xe->kid);
694 /* --- Free up the parent-side resources --- */
697 xe->next->prev = xe->prev;
699 xe->prev->next = xe->next;
701 xept_list = xe->next;
705 xe->f->ops->close(xe->f);
706 x_tidy(xe->xa, xe->xo);
711 /* --- @xept_chld@ --- *
713 * Arguments: @int n@ = signal number
714 * @void *p@ = uninteresting pointer
718 * Use: Deals with child death situations.
721 static void xept_chld(int n, void *p)
726 while ((kid = waitpid(-1, &st, WNOHANG)) > 0) {
727 xept *xe = xept_list;
731 if (kid == xxe->kid) {
733 xxe->e.f |= XEF_EXIT;
734 if (xxe->e.f & XEF_CLOSE)
742 /* --- @xept_error@ --- *
744 * Arguments: @char *p@ = pointer to string read from stderr
745 * @void *v@ = pointer to by endpoint
749 * Use: Handles error reports from a child process.
752 static void xept_error(char *p, void *v)
756 fw_log(-1, "[%s] pid %i: %s", xe->desc, xe->kid, p);
758 close(xe->err.reader.fd);
759 selbuf_destroy(&xe->err);
760 xe->e.f |= XEF_CLOSE;
761 if (xe->e.f & XEF_EXIT)
766 /* --- Endpoint operations --- */
768 static endpt_ops xept_ops = { xept_attach, xept_file, 0, xept_close };
770 /*----- General operations on sources and targets -------------------------*/
772 /* --- @exec_init@ --- *
778 * Use: Initializes the executable problem source and target.
783 rlimit_get(&exec_opts.xl);
784 sig_add(&xept_sig, SIGCHLD, xept_chld, 0);
786 env_import(&env, environ);
789 /* --- @exec_option@ --- */
791 static int exec_option(xdata *x, scanner *sc)
793 xopts *xo = x ? x->xo : &exec_opts;
795 CONF_BEGIN(sc, "exec", "executable");
797 /* --- Logging settings --- */
799 if (strcmp(sc->d.buf, "logging") == 0 ||
800 strcmp(sc->d.buf, "log") == 0) {
804 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
811 /* --- Current directory setting --- *
813 * Lots of possibilities to guard against possible brainoes.
816 if (strcmp(sc->d.buf, "dir") == 0 ||
817 strcmp(sc->d.buf, "cd") == 0 ||
818 strcmp(sc->d.buf, "chdir") == 0 ||
819 strcmp(sc->d.buf, "cwd") == 0) {
824 conf_name(sc, '/', &d);
825 xo->dir = xstrdup(d.buf);
830 /* --- Set a chroot prison --- */
832 if (strcmp(sc->d.buf, "root") == 0 ||
833 strcmp(sc->d.buf, "chroot") == 0) {
838 conf_name(sc, '/', &d);
839 xo->root = xstrdup(d.buf);
844 /* --- Set the target user id --- */
846 if (strcmp(sc->d.buf, "uid") == 0 ||
847 strcmp(sc->d.buf, "user") == 0) {
851 if (sc->t != CTOK_WORD)
852 error(sc, "parse error, expected user name or uid");
853 if (isdigit((unsigned char)*sc->d.buf))
854 xo->uid = atoi(sc->d.buf);
856 struct passwd *pw = getpwnam(sc->d.buf);
858 error(sc, "unknown user name `%s'", sc->d.buf);
859 xo->uid = pw->pw_uid;
865 /* --- Set the target group id --- */
867 if (strcmp(sc->d.buf, "gid") == 0 ||
868 strcmp(sc->d.buf, "group") == 0) {
872 if (sc->t != CTOK_WORD)
873 error(sc, "parse error, expected group name or gid");
874 if (isdigit((unsigned char)*sc->d.buf))
875 xo->gid = atoi(sc->d.buf);
877 struct group *gr = getgrnam(sc->d.buf);
879 error(sc, "unknown user name `%s'", sc->d.buf);
880 xo->gid = gr->gr_gid;
886 /* --- Now try resource limit settings --- */
888 if (rlimit_option(&xo->xl, sc))
891 /* --- And then environment settings --- */
893 if (xenv_option(xo, sc))
896 /* --- Nothing found --- */
901 /* --- @exec_desc@ --- */
903 static void exec_desc(xdata *x, dstr *d)
907 dstr_puts(d, "exec ");
908 if (strcmp(x->xa->file, x->xa->argv[0]) != 0) {
909 dstr_puts(d, x->xa->file);
912 for (p = x->xa->argv; *p; p++) {
921 /* --- @exec_read@ --- */
923 static void exec_read(xdata *x, scanner *sc)
929 /* --- Read the first word --- *
931 * This is either a shell command or the actual program to run.
934 if (sc->t == CTOK_WORD) {
935 dstr_putd(&d, &sc->d); d.len++;
940 /* --- See if there's a list of arguments --- *
942 * If not, then the thing I saw was a shell command, so build the proper
943 * arguments for that.
949 error(sc, "parse error, expected shell command or argument list");
950 xa = xmalloc(XARGS_SZ(3) + 8 + 3 + d.len);
951 p = (char *)(xa->argv + 4);
954 xa->argv[0] = p; memcpy(p, "/bin/sh", 8); p += 8;
955 xa->argv[1] = p; memcpy(p, "-c", 3); p += 3;
956 xa->argv[2] = p; memcpy(p, d.buf, d.len); p += d.len;
960 /* --- Snarf in a list of arguments --- */
967 /* --- Strip off the leading `[' --- */
971 /* --- Read a sequence of arguments --- */
973 while (sc->t == CTOK_WORD) {
974 dstr_putd(&d, &sc->d); d.len++;
979 /* --- Expect the closing `]' --- */
982 error(sc, "parse error, missing `]'");
985 /* --- If there are no arguments, whinge --- */
988 error(sc, "must specify at least one argument");
990 /* --- Allocate a lump of memory for the array --- */
992 xa = xmalloc(XARGS_SZ(argc) + d.len);
995 p = (char *)(v + argc + 1);
996 memcpy(p, d.buf, d.len);
1001 /* --- Start dumping addresses into the @argv@ array --- */
1005 while (*p++ && p < q)
1013 /* --- Do some other setting up --- */
1017 x->xo = CREATE(xopts);
1023 /* --- @exec_endpt@ --- */
1025 static endpt *exec_endpt(xdata *x, const char *desc)
1027 xept *xe = CREATE(xept);
1028 xe->e.ops = &xept_ops;
1032 xe->xa = x->xa; xe->xa->ref++;
1033 xe->xo = x->xo; xe->xo->ref++;
1036 xe->desc = xstrdup(desc);
1040 /* --- @exec_destroy@ --- */
1042 static void exec_destroy(xdata *x)
1044 x_tidy(x->xa, x->xo);
1047 /*----- Source definition -------------------------------------------------*/
1049 /* --- @option@ --- */
1051 static int xsource_option(source *s, scanner *sc)
1053 xsource *xs = (xsource *)s;
1054 return (exec_option(xs ? &xs->x : 0, sc));
1057 /* --- @read@ --- */
1059 static source *xsource_read(scanner *sc)
1063 if (!conf_prefix(sc, "exec"))
1065 xs = CREATE(xsource);
1066 xs->s.ops = &xsource_ops;
1068 exec_read(&xs->x, sc);
1072 /* --- @attach@ --- */
1074 static void xsource_destroy(source */*s*/);
1076 static void xsource_attach(source *s, scanner *sc, target *t)
1078 xsource *xs = (xsource *)s;
1081 /* --- Set up the source description string --- */
1085 exec_desc(&xs->x, &d);
1086 dstr_puts(&d, " -> ");
1087 dstr_puts(&d, t->desc);
1088 xs->s.desc = xstrdup(d.buf);
1092 /* --- Create the endpoints --- */
1094 if ((ee = t->ops->create(t, xs->s.desc)) == 0)
1096 if ((e = exec_endpt(&xs->x, xs->s.desc)) == 0) {
1102 /* --- Dispose of source and target --- */
1106 xsource_destroy(&xs->s);
1109 /* --- @destroy@ --- */
1111 static void xsource_destroy(source *s)
1113 xsource *xs = (xsource *)s;
1115 exec_destroy(&xs->x);
1119 /* --- Executable source operations --- */
1121 source_ops xsource_ops = {
1123 xsource_option, xsource_read, xsource_attach, xsource_destroy
1126 /*----- Exec target description -------------------------------------------*/
1128 /* --- @option@ --- */
1130 static int xtarget_option(target *t, scanner *sc)
1132 xtarget *xt = (xtarget *)t;
1133 return (exec_option(xt ? &xt->x : 0, sc));
1136 /* --- @read@ --- */
1138 static target *xtarget_read(scanner *sc)
1143 if (!conf_prefix(sc, "exec"))
1145 xt = CREATE(xtarget);
1146 xt->t.ops = &xtarget_ops;
1147 exec_read(&xt->x, sc);
1148 exec_desc(&xt->x, &d);
1149 xt->t.desc = xstrdup(d.buf);
1154 /* --- @create@ --- */
1156 static endpt *xtarget_create(target *t, const char *desc)
1158 xtarget *xt = (xtarget *)t;
1159 endpt *e = exec_endpt(&xt->x, desc);
1163 /* --- @destroy@ --- */
1165 static void xtarget_destroy(target *t)
1167 xtarget *xt = (xtarget *)t;
1169 exec_destroy(&xt->x);
1173 /* --- Exec target operations --- */
1175 target_ops xtarget_ops = {
1177 xtarget_option, xtarget_read, xtarget_create, xtarget_destroy
1180 /*----- That's all, folks -------------------------------------------------*/