3 * $Id: exec.c,v 1.2 1999/10/22 22:46:17 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.2 1999/10/22 22:46:17 mdw
33 * When a non-file endpoint is attached to a file, keep the file endpoint
34 * open until the nonfile is done. This stops socket sources from
35 * resetting their connection limits too early.
37 * Revision 1.1 1999/07/26 23:33:32 mdw
38 * New sources and targets.
42 /*----- Header files ------------------------------------------------------*/
55 #include <sys/types.h>
62 # include <sys/resource.h>
66 extern char **environ;
74 #include <mLib/alloc.h>
75 #include <mLib/dstr.h>
77 #include <mLib/fdflags.h>
78 #include <mLib/report.h>
80 #include <mLib/selbuf.h>
95 /*----- Data structures ---------------------------------------------------*/
97 /* --- Resource usage --- */
101 typedef struct xlimit {
102 #define R(r, n) struct rlimit n;
108 /* --- Environment variable modifications --- */
110 typedef struct xenv {
120 /* --- Program options --- */
122 typedef struct xopts {
131 #ifdef HAVE_SETRLIMIT
138 /* --- Executable program arguments --- */
140 typedef struct xargs {
146 #define XARGS_SZ(n) (sizeof(xargs) + sizeof(char *) * (n))
148 /* --- Executable endpoints --- */
150 typedef struct xept {
152 struct xept *next, *prev;
162 #define XEF_CLOSE 16u
165 /* --- Executable program data --- */
167 typedef struct xdata {
172 /* --- Executable source block --- */
174 typedef struct xsource {
179 /* --- Executable target block --- */
181 typedef struct xtarget {
186 /*----- Static variables --------------------------------------------------*/
188 static xopts exec_opts = { 1, 0, 0, 0, -1, -1, 0, &exec_opts.env };
189 static xept *xept_list;
191 static sym_table env;
193 /*----- Fiddling about with resource limits -------------------------------*/
195 #ifdef HAVE_SETRLIMIT
197 /* --- Table mapping user-level names to OS interface bits --- */
199 typedef struct rlimit_ent {
206 static rlimit_ent rlimits[] = {
207 #define R(r, n) { #n, #r, r, offsetof(xlimit, n) },
212 #define RLIMIT(xl, o) ((struct rlimit *)((char *)(xl) + (o)))
214 /* --- @rlimit_get@ --- *
216 * Arguments: @xlimit *xl@ = pointer to limit structure
220 * Use: Initializes a limit structure from the current limits.
223 static void rlimit_get(xlimit *xl)
227 for (r = rlimits; r->name; r++) {
228 if (getrlimit(r->r, RLIMIT(xl, r->off))) {
229 moan("couldn't read %s: %s", r->rname, strerror(errno));
235 /* --- @rlimit_set@ --- *
237 * Arguments: @xlimit *xl@ = pointer to limit structure
241 * Use: Sets resource limits from the supplied limits structure.
244 static void rlimit_set(xlimit *xl)
248 for (r = rlimits; r->name; r++) {
249 if (setrlimit(r->r, RLIMIT(xl, r->off))) {
250 moan("couldn't set %s: %s", r->rname, strerror(errno));
256 /* --- @rlimit_option@ --- */
258 static int rlimit_option(xlimit *xl, scanner *sc)
260 CONF_BEGIN(sc, "rlimit", "resource limit")
261 enum { w_soft, w_hard, w_both } which = w_both;
266 /* --- Find out which resource is being fiddled --- */
272 for (r = rlimits; r->name; r++) {
273 if (strncmp(sc->d.buf, r->name, sc->d.len) == 0) {
274 if (r->name[sc->d.len] == 0) {
278 error(sc, "ambiguous resource limit name `%s'", sc->d.buf);
286 rl = RLIMIT(xl, chosen->off);
289 /* --- Look for hard or soft restrictions --- */
295 if (sc->t == CTOK_WORD) {
296 if ((i = conf_enum(sc, "soft,hard",
297 ENUM_ABBREV | ENUM_NONE, "limit type")) != -1)
302 /* --- Now read the new value --- */
306 if (sc->t != CTOK_WORD)
307 error(sc, "parse error, expected limit value");
309 if (conf_enum(sc, "unlimited,infinity",
310 ENUM_ABBREV | ENUM_NONE, "limit value") > -1)
315 v = strtol(sc->d.buf, &p, 0);
317 error(sc, "parse error, invalid limit value `%s'", sc->d.buf);
318 switch (tolower((unsigned char)*p)) {
320 case 'b': v *= 512; break;
323 case 'k': v *= 1024; break;
324 default: error(sc, "parse error, invalid limit scale `%c'", *p);
329 /* --- Store the limit value away --- */
337 if (v > rl->rlim_max)
338 error(sc, "soft limit %l exceeds hard limit %l for %s",
339 v, rl->rlim_max, chosen->rname);
344 if (rl->rlim_cur > v)
355 /*----- Environment fiddling ----------------------------------------------*/
357 /* --- @xenv_option@ --- *
359 * Arguments: @xopts *xo@ = pointer to options block
360 * @scanner *sc@ = pointer to scanner
362 * Returns: Nonzero if claimed
364 * Use: Parses environment variable assignments.
367 static int xenv_option(xopts *xo, scanner *sc)
369 CONF_BEGIN(sc, "env", "environment")
372 /* --- Unset a variable --- */
374 if (strcmp(sc->d.buf, "unset") == 0) {
376 if (sc->t != CTOK_WORD)
377 error(sc, "parse error, expected environment variable name");
379 xe->name = xstrdup(sc->d.buf);
386 /* --- Clear the entire environment --- */
388 if (strcmp(sc->d.buf, "clear") == 0) {
395 /* --- Allow `set' to be omitted if there's a prefix --- */
397 if (strcmp(sc->d.buf, "set") == 0)
402 /* --- Set a variable --- */
404 if (sc->t != CTOK_WORD)
405 error(sc, "parse error, expected environment variable name");
407 xe->name = xstrdup(sc->d.buf);
411 if (sc->t != CTOK_WORD)
412 error(sc, "parse error, expected environment variable value");
413 xe->value = xstrdup(sc->d.buf);
421 xo->etail = &xe->next;
424 /* --- Nothing else to try --- */
429 /* --- @xenv_apply@ --- *
431 * Arguments: @xenv *xe@ = pointer to a variable change list
435 * Use: Modifies the environment (in @env@) according to the list.
438 static void xenv_apply(xenv *xe)
443 env_put(&env, xe->name, xe->value);
454 /* --- @xenv_destroy@ --- *
456 * Arguments: @xenv *xe@ = pointer to a variable change list
460 * Use: Frees the memory used by an environment variable change list.
463 static void xenv_destroy(xenv *xe)
475 /*----- Miscellaneous good things -----------------------------------------*/
477 /* --- @x_tidy@ --- *
479 * Arguments: @xargs *xa@ = pointer to an arguments block
480 * @xopts *xo@ = pointer to an options block
484 * Use: Releases a reference to argument and options blocks.
487 static void x_tidy(xargs *xa, xopts *xo)
495 xenv_destroy(xo->env);
500 /*----- Executable endpoints ----------------------------------------------*/
502 /* --- @attach@ --- */
504 static void xept_error(char */*p*/, void */*v*/);
506 static void xept_attach(endpt *e, reffd *in, reffd *out)
508 xept *xe = (xept *)e;
512 /* --- Make a pipe for standard error --- */
515 fw_log(-1, "[%s] couldn't create pipe: %s", xe->desc, strerror(errno));
518 fdflags(fd[0], O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
520 /* --- Fork a child, and handle an error if there was one --- */
522 if ((kid = fork()) == -1) {
523 fw_log(-1, "[%s] couldn't fork: %s", xe->desc, strerror(errno));
529 /* --- Do the child thing --- */
534 /* --- Fiddle with the file descriptors --- *
536 * Attach the other endpoint's descriptors to standard input and output.
537 * Attach my pipe to standard error. Mark everything as blocking and
538 * not-to-be-closed-on-exec at this end.
542 if (dup2(in->fd, STDIN_FILENO) < 0 ||
543 dup2(out->fd, STDOUT_FILENO) < 0 ||
544 dup2(fd[1], STDERR_FILENO) < 0) {
545 moan("couldn't manipulate file descriptors: %s", strerror(errno));
554 fdflags(STDIN_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
555 fdflags(STDOUT_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
556 fdflags(STDERR_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
558 /* --- First of all set the @chroot@ prison --- */
560 if (xo->root && chroot(xo->root)) {
561 moan("couldn't set `%s' as filesystem root: %s",
562 xo->root, strerror(errno));
566 /* --- Now set the current directory --- */
568 if (xo->dir ? chdir(xo->dir) : xo->root ? chdir("/") : 0) {
569 moan("couldn't set `%s' as current directory: %s",
570 xo->dir ? xo->dir : "/", strerror(errno));
574 /* --- Set the resource limits --- */
576 #ifdef HAVE_SETRLIMIT
580 /* --- Set group id --- */
583 if (setgid(xo->gid)) {
584 moan("couldn't set gid %i: %s", xo->gid, strerror(errno));
587 #ifdef HAVE_SETGROUPS
588 if (setgroups(1, &xo->gid))
589 moan("warning: couldn't set group list to %i: %s", xo->gid,
594 /* --- Set uid --- */
597 if (setuid(xo->uid)) {
598 moan("couldn't set uid %i: %s", xo->uid, strerror(errno));
603 /* --- Play with signal dispositions --- */
605 signal(SIGPIPE, SIG_DFL);
607 /* --- Fiddle with the environment --- */
609 xenv_apply(exec_opts.env);
610 xenv_apply(xe->xo->env);
611 environ = env_export(&env);
613 /* --- Run the program --- */
615 execvp(xe->xa->file, xe->xa->argv);
616 moan("couldn't execute `%s': %s", xe->xa->file, strerror(errno));
620 /* --- The child's done; see to the parent --- */
623 selbuf_init(&xe->err, sel, fd[0], xept_error, xe);
625 xe->next = xept_list;
628 xept_list->prev = xe;
630 if (!(xe->xo->f & XF_NOLOG))
631 fw_log(-1, "[%s] started with pid %i", xe->desc, kid);
636 /* --- @xept_file@ --- */
638 static void xept_file(endpt *e, endpt *f)
640 xept *xe = (xept *)e;
644 /* --- @xept_close@ --- */
646 static void xept_close(endpt *e)
648 xept *xe = (xept *)e;
651 xe->f->ops->close(xe->f);
652 x_tidy(xe->xa, xe->xo);
658 /* --- @xept_destroy@ --- */
660 static void xept_destroy(xept *xe)
662 /* --- First emit the news about the process --- */
664 if (xe->xo->f & XF_NOLOG)
666 else if (WIFEXITED(xe->st)) {
667 if (WEXITSTATUS(xe->st) == 0)
668 fw_log(-1, "[%s] pid %i exited successfully", xe->desc, xe->kid);
670 fw_log(-1, "[%s] pid %i failed: status %i",
671 xe->desc, xe->kid, WEXITSTATUS(xe->st));
673 } else if (WIFSIGNALED(xe->st)) {
675 #ifdef HAVE_STRSIGNAL
676 s = strsignal(WTERMSIG(xe->st));
677 #elif HAVE__SYS_SIGLIST
678 s = _sys_siglist[WTERMSIG(xe->st)];
681 sprintf(buf, "signal %i", WTERMSIG(xe->st));
684 fw_log(-1, "[%s] pid %i failed: %s", xe->desc, xe->kid, s);
686 fw_log(-1, "[%s] pid %i failed: unrecognized status", xe->desc, xe->kid);
688 /* --- Free up the parent-side resources --- */
691 xe->next->prev = xe->prev;
693 xe->prev->next = xe->next;
695 xept_list = xe->next;
698 xe->f->ops->close(xe->f);
699 x_tidy(xe->xa, xe->xo);
704 /* --- @xept_chld@ --- *
706 * Arguments: @int n@ = signal number
707 * @void *p@ = uninteresting pointer
711 * Use: Deals with child death situations.
714 static void xept_chld(int n, void *p)
719 while ((kid = waitpid(-1, &st, WNOHANG)) > 0) {
720 xept *xe = xept_list;
724 if (kid == xxe->kid) {
726 xxe->e.f |= XEF_EXIT;
727 if (xxe->e.f & XEF_CLOSE)
735 /* --- @xept_error@ --- *
737 * Arguments: @char *p@ = pointer to string read from stderr
738 * @void *v@ = pointer to by endpoint
742 * Use: Handles error reports from a child process.
745 static void xept_error(char *p, void *v)
749 fw_log(-1, "[%s] pid %i: %s", xe->desc, xe->kid, p);
751 selbuf_disable(&xe->err);
752 close(xe->err.reader.fd);
753 xe->e.f |= XEF_CLOSE;
754 if (xe->e.f & XEF_EXIT)
759 /* --- Endpoint operations --- */
761 static endpt_ops xept_ops = { xept_attach, xept_file, 0, xept_close };
763 /*----- General operations on sources and targets -------------------------*/
765 /* --- @exec_init@ --- *
771 * Use: Initializes the executable problem source and target.
776 rlimit_get(&exec_opts.xl);
777 sig_add(&xept_sig, SIGCHLD, xept_chld, 0);
779 env_import(&env, environ);
782 /* --- @exec_option@ --- */
784 static int exec_option(xdata *x, scanner *sc)
786 xopts *xo = x ? x->xo : &exec_opts;
788 CONF_BEGIN(sc, "exec", "executable");
790 /* --- Logging settings --- */
792 if (strcmp(sc->d.buf, "logging") == 0 ||
793 strcmp(sc->d.buf, "log") == 0) {
797 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
804 /* --- Current directory setting --- *
806 * Lots of possibilities to guard against possible brainoes.
809 if (strcmp(sc->d.buf, "dir") == 0 ||
810 strcmp(sc->d.buf, "cd") == 0 ||
811 strcmp(sc->d.buf, "chdir") == 0 ||
812 strcmp(sc->d.buf, "cwd") == 0) {
817 conf_name(sc, '/', &d);
818 xo->dir = xstrdup(d.buf);
823 /* --- Set a chroot prison --- */
825 if (strcmp(sc->d.buf, "root") == 0 ||
826 strcmp(sc->d.buf, "chroot") == 0) {
831 conf_name(sc, '/', &d);
832 xo->root = xstrdup(d.buf);
837 /* --- Set the target user id --- */
839 if (strcmp(sc->d.buf, "uid") == 0 ||
840 strcmp(sc->d.buf, "user") == 0) {
844 if (sc->t != CTOK_WORD)
845 error(sc, "parse error, expected user name or uid");
846 if (isdigit((unsigned char)*sc->d.buf))
847 xo->uid = atoi(sc->d.buf);
849 struct passwd *pw = getpwnam(sc->d.buf);
851 error(sc, "unknown user name `%s'", sc->d.buf);
852 xo->uid = pw->pw_uid;
858 /* --- Set the target group id --- */
860 if (strcmp(sc->d.buf, "gid") == 0 ||
861 strcmp(sc->d.buf, "group") == 0) {
865 if (sc->t != CTOK_WORD)
866 error(sc, "parse error, expected group name or gid");
867 if (isdigit((unsigned char)*sc->d.buf))
868 xo->gid = atoi(sc->d.buf);
870 struct group *gr = getgrnam(sc->d.buf);
872 error(sc, "unknown user name `%s'", sc->d.buf);
873 xo->gid = gr->gr_gid;
879 /* --- Now try resource limit settings --- */
881 if (rlimit_option(&xo->xl, sc))
884 /* --- And then environment settings --- */
886 if (xenv_option(xo, sc))
889 /* --- Nothing found --- */
894 /* --- @exec_desc@ --- */
896 static void exec_desc(xdata *x, dstr *d)
900 dstr_puts(d, "exec ");
901 if (strcmp(x->xa->file, x->xa->argv[0]) != 0) {
902 dstr_puts(d, x->xa->file);
905 for (p = x->xa->argv; *p; p++) {
914 /* --- @exec_read@ --- */
916 static void exec_read(xdata *x, scanner *sc)
922 /* --- Read the first word --- *
924 * This is either a shell command or the actual program to run.
927 if (sc->t == CTOK_WORD) {
928 dstr_putd(&d, &sc->d); d.len++;
933 /* --- See if there's a list of arguments --- *
935 * If not, then the thing I saw was a shell command, so build the proper
936 * arguments for that.
942 error(sc, "parse error, expected shell command or argument list");
943 xa = xmalloc(XARGS_SZ(3) + 8 + 3 + d.len);
944 p = (char *)(xa->argv + 4);
947 xa->argv[0] = p; memcpy(p, "/bin/sh", 8); p += 8;
948 xa->argv[1] = p; memcpy(p, "-c", 3); p += 3;
949 xa->argv[2] = p; memcpy(p, d.buf, d.len); p += d.len;
953 /* --- Snarf in a list of arguments --- */
960 /* --- Strip off the leading `[' --- */
964 /* --- Read a sequence of arguments --- */
966 while (sc->t == CTOK_WORD) {
967 dstr_putd(&d, &sc->d); d.len++;
972 /* --- Expect the closing `]' --- */
975 error(sc, "parse error, missing `]'");
978 /* --- If there are no arguments, whinge --- */
981 error(sc, "must specify at least one argument");
983 /* --- Allocate a lump of memory for the array --- */
985 xa = xmalloc(XARGS_SZ(argc) + d.len);
988 p = (char *)(v + argc + 1);
989 memcpy(p, d.buf, d.len);
994 /* --- Start dumping addresses into the @argv@ array --- */
998 while (*p++ && p < q)
1006 /* --- Do some other setting up --- */
1010 x->xo = CREATE(xopts);
1016 /* --- @exec_endpt@ --- */
1018 static endpt *exec_endpt(xdata *x, const char *desc)
1020 xept *xe = CREATE(xept);
1021 xe->e.ops = &xept_ops;
1025 xe->xa = x->xa; xe->xa->ref++;
1026 xe->xo = x->xo; xe->xo->ref++;
1033 /* --- @exec_destroy@ --- */
1035 static void exec_destroy(xdata *x)
1037 x_tidy(x->xa, x->xo);
1040 /*----- Source definition -------------------------------------------------*/
1042 /* --- @option@ --- */
1044 static int xsource_option(source *s, scanner *sc)
1046 xsource *xs = (xsource *)s;
1047 return (exec_option(xs ? &xs->x : 0, sc));
1050 /* --- @read@ --- */
1052 static source *xsource_read(scanner *sc)
1056 if (!conf_prefix(sc, "exec"))
1058 xs = CREATE(xsource);
1059 xs->s.ops = &xsource_ops;
1061 exec_read(&xs->x, sc);
1065 /* --- @attach@ --- */
1067 static void xsource_destroy(source */*s*/);
1069 static void xsource_attach(source *s, scanner *sc, target *t)
1071 xsource *xs = (xsource *)s;
1074 /* --- Set up the source description string --- */
1078 exec_desc(&xs->x, &d);
1079 dstr_puts(&d, " -> ");
1080 dstr_puts(&d, t->desc);
1081 xs->s.desc = xstrdup(d.buf);
1085 /* --- Create the endpoints --- */
1087 if ((ee = t->ops->create(t, xs->s.desc)) == 0)
1089 if ((e = exec_endpt(&xs->x, xs->s.desc)) == 0) {
1095 /* --- Dispose of source and target --- */
1099 xsource_destroy(&xs->s);
1102 /* --- @destroy@ --- */
1104 static void xsource_destroy(source *s)
1106 xsource *xs = (xsource *)s;
1107 exec_destroy(&xs->x);
1111 /* --- Executable source operations --- */
1113 source_ops xsource_ops = {
1115 xsource_option, xsource_read, xsource_attach, xsource_destroy
1118 /*----- Exec target description -------------------------------------------*/
1120 /* --- @option@ --- */
1122 static int xtarget_option(target *t, scanner *sc)
1124 xtarget *xt = (xtarget *)t;
1125 return (exec_option(xt ? &xt->x : 0, sc));
1128 /* --- @read@ --- */
1130 static target *xtarget_read(scanner *sc)
1135 if (!conf_prefix(sc, "exec"))
1137 xt = CREATE(xtarget);
1138 xt->t.ops = &xtarget_ops;
1139 exec_read(&xt->x, sc);
1140 exec_desc(&xt->x, &d);
1141 xt->t.desc = xstrdup(d.buf);
1146 /* --- @create@ --- */
1148 static endpt *xtarget_create(target *t, const char *desc)
1150 xtarget *xt = (xtarget *)t;
1151 endpt *e = exec_endpt(&xt->x, desc);
1155 /* --- @destroy@ --- */
1157 static void xtarget_destroy(target *t)
1159 xtarget *xt = (xtarget *)t;
1160 exec_destroy(&xt->x);
1164 /* --- Exec target operations --- */
1166 target_ops xtarget_ops = {
1168 xtarget_option, xtarget_read, xtarget_create, xtarget_destroy
1171 /*----- That's all, folks -------------------------------------------------*/