3 * $Id: exec.c,v 1.6 2002/02/22 23:43:32 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.6 2002/02/22 23:43:32 mdw
33 * Call @xfree@ rather than @free@.
35 * Revision 1.5 2002/01/13 14:49:03 mdw
36 * Track @lbuf@ changes in mLib.
38 * Revision 1.4 2001/02/03 20:30:03 mdw
39 * Support re-reading config files on SIGHUP.
41 * Revision 1.3 2000/07/01 11:28:52 mdw
42 * Use new mLib selbuf features.
44 * Revision 1.2 1999/10/22 22:46:17 mdw
45 * When a non-file endpoint is attached to a file, keep the file endpoint
46 * open until the nonfile is done. This stops socket sources from
47 * resetting their connection limits too early.
49 * Revision 1.1 1999/07/26 23:33:32 mdw
50 * New sources and targets.
54 /*----- Header files ------------------------------------------------------*/
67 #include <sys/types.h>
74 # include <sys/resource.h>
78 extern char **environ;
86 #include <mLib/alloc.h>
87 #include <mLib/dstr.h>
89 #include <mLib/fdflags.h>
90 #include <mLib/report.h>
92 #include <mLib/selbuf.h>
107 /*----- Data structures ---------------------------------------------------*/
109 /* --- Resource usage --- */
111 #ifdef HAVE_SETRLIMIT
113 typedef struct xlimit {
114 #define R(r, n) struct rlimit n;
120 /* --- Environment variable modifications --- */
122 typedef struct xenv {
132 /* --- Program options --- */
134 typedef struct xopts {
143 #ifdef HAVE_SETRLIMIT
150 /* --- Executable program arguments --- */
152 typedef struct xargs {
158 #define XARGS_SZ(n) (sizeof(xargs) + sizeof(char *) * (n))
160 /* --- Executable endpoints --- */
162 typedef struct xept {
164 struct xept *next, *prev;
174 #define XEF_CLOSE 16u
177 /* --- Executable program data --- */
179 typedef struct xdata {
184 /* --- Executable source block --- */
186 typedef struct xsource {
191 /* --- Executable target block --- */
193 typedef struct xtarget {
198 /*----- Static variables --------------------------------------------------*/
200 static xopts exec_opts = { 1, 0, 0, 0, -1, -1, 0, &exec_opts.env };
201 static xept *xept_list;
203 static sym_table env;
205 /*----- Fiddling about with resource limits -------------------------------*/
207 #ifdef HAVE_SETRLIMIT
209 /* --- Table mapping user-level names to OS interface bits --- */
211 typedef struct rlimit_ent {
218 static rlimit_ent rlimits[] = {
219 #define R(r, n) { #n, #r, r, offsetof(xlimit, n) },
224 #define RLIMIT(xl, o) ((struct rlimit *)((char *)(xl) + (o)))
226 /* --- @rlimit_get@ --- *
228 * Arguments: @xlimit *xl@ = pointer to limit structure
232 * Use: Initializes a limit structure from the current limits.
235 static void rlimit_get(xlimit *xl)
239 for (r = rlimits; r->name; r++) {
240 if (getrlimit(r->r, RLIMIT(xl, r->off))) {
241 moan("couldn't read %s: %s", r->rname, strerror(errno));
247 /* --- @rlimit_set@ --- *
249 * Arguments: @xlimit *xl@ = pointer to limit structure
253 * Use: Sets resource limits from the supplied limits structure.
256 static void rlimit_set(xlimit *xl)
260 for (r = rlimits; r->name; r++) {
261 if (setrlimit(r->r, RLIMIT(xl, r->off))) {
262 moan("couldn't set %s: %s", r->rname, strerror(errno));
268 /* --- @rlimit_option@ --- */
270 static int rlimit_option(xlimit *xl, scanner *sc)
272 CONF_BEGIN(sc, "rlimit", "resource limit")
273 enum { w_soft, w_hard, w_both } which = w_both;
278 /* --- Find out which resource is being fiddled --- */
284 for (r = rlimits; r->name; r++) {
285 if (strncmp(sc->d.buf, r->name, sc->d.len) == 0) {
286 if (r->name[sc->d.len] == 0) {
290 error(sc, "ambiguous resource limit name `%s'", sc->d.buf);
298 rl = RLIMIT(xl, chosen->off);
301 /* --- Look for hard or soft restrictions --- */
307 if (sc->t == CTOK_WORD) {
308 if ((i = conf_enum(sc, "soft,hard",
309 ENUM_ABBREV | ENUM_NONE, "limit type")) != -1)
314 /* --- Now read the new value --- */
318 if (sc->t != CTOK_WORD)
319 error(sc, "parse error, expected limit value");
321 if (conf_enum(sc, "unlimited,infinity",
322 ENUM_ABBREV | ENUM_NONE, "limit value") > -1)
327 v = strtol(sc->d.buf, &p, 0);
329 error(sc, "parse error, invalid limit value `%s'", sc->d.buf);
330 switch (tolower((unsigned char)*p)) {
332 case 'b': v *= 512; break;
335 case 'k': v *= 1024; break;
336 default: error(sc, "parse error, invalid limit scale `%c'", *p);
341 /* --- Store the limit value away --- */
349 if (v > rl->rlim_max)
350 error(sc, "soft limit %l exceeds hard limit %l for %s",
351 v, rl->rlim_max, chosen->rname);
356 if (rl->rlim_cur > v)
367 /*----- Environment fiddling ----------------------------------------------*/
369 /* --- @xenv_option@ --- *
371 * Arguments: @xopts *xo@ = pointer to options block
372 * @scanner *sc@ = pointer to scanner
374 * Returns: Nonzero if claimed
376 * Use: Parses environment variable assignments.
379 static int xenv_option(xopts *xo, scanner *sc)
381 CONF_BEGIN(sc, "env", "environment")
384 /* --- Unset a variable --- */
386 if (strcmp(sc->d.buf, "unset") == 0) {
388 if (sc->t != CTOK_WORD)
389 error(sc, "parse error, expected environment variable name");
391 xe->name = xstrdup(sc->d.buf);
398 /* --- Clear the entire environment --- */
400 if (strcmp(sc->d.buf, "clear") == 0) {
407 /* --- Allow `set' to be omitted if there's a prefix --- */
409 if (strcmp(sc->d.buf, "set") == 0)
414 /* --- Set a variable --- */
416 if (sc->t != CTOK_WORD)
417 error(sc, "parse error, expected environment variable name");
419 xe->name = xstrdup(sc->d.buf);
423 if (sc->t != CTOK_WORD)
424 error(sc, "parse error, expected environment variable value");
425 xe->value = xstrdup(sc->d.buf);
433 xo->etail = &xe->next;
436 /* --- Nothing else to try --- */
441 /* --- @xenv_apply@ --- *
443 * Arguments: @xenv *xe@ = pointer to a variable change list
447 * Use: Modifies the environment (in @env@) according to the list.
450 static void xenv_apply(xenv *xe)
455 env_put(&env, xe->name, xe->value);
466 /* --- @xenv_destroy@ --- *
468 * Arguments: @xenv *xe@ = pointer to a variable change list
472 * Use: Frees the memory used by an environment variable change list.
475 static void xenv_destroy(xenv *xe)
487 /*----- Miscellaneous good things -----------------------------------------*/
489 /* --- @x_tidy@ --- *
491 * Arguments: @xargs *xa@ = pointer to an arguments block
492 * @xopts *xo@ = pointer to an options block
496 * Use: Releases a reference to argument and options blocks.
499 static void x_tidy(xargs *xa, xopts *xo)
507 xenv_destroy(xo->env);
512 /*----- Executable endpoints ----------------------------------------------*/
514 /* --- @attach@ --- */
516 static void xept_error(char */*p*/, size_t /*len*/, void */*v*/);
518 static void xept_attach(endpt *e, reffd *in, reffd *out)
520 xept *xe = (xept *)e;
524 /* --- Make a pipe for standard error --- */
527 fw_log(-1, "[%s] couldn't create pipe: %s", xe->desc, strerror(errno));
530 fdflags(fd[0], O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
532 /* --- Fork a child, and handle an error if there was one --- */
534 if ((kid = fork()) == -1) {
535 fw_log(-1, "[%s] couldn't fork: %s", xe->desc, strerror(errno));
541 /* --- Do the child thing --- */
546 /* --- Fiddle with the file descriptors --- *
548 * Attach the other endpoint's descriptors to standard input and output.
549 * Attach my pipe to standard error. Mark everything as blocking and
550 * not-to-be-closed-on-exec at this end.
554 if (dup2(in->fd, STDIN_FILENO) < 0 ||
555 dup2(out->fd, STDOUT_FILENO) < 0 ||
556 dup2(fd[1], STDERR_FILENO) < 0) {
557 moan("couldn't manipulate file descriptors: %s", strerror(errno));
566 fdflags(STDIN_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
567 fdflags(STDOUT_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
568 fdflags(STDERR_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
570 /* --- First of all set the @chroot@ prison --- */
572 if (xo->root && chroot(xo->root)) {
573 moan("couldn't set `%s' as filesystem root: %s",
574 xo->root, strerror(errno));
578 /* --- Now set the current directory --- */
580 if (xo->dir ? chdir(xo->dir) : xo->root ? chdir("/") : 0) {
581 moan("couldn't set `%s' as current directory: %s",
582 xo->dir ? xo->dir : "/", strerror(errno));
586 /* --- Set the resource limits --- */
588 #ifdef HAVE_SETRLIMIT
592 /* --- Set group id --- */
595 if (setgid(xo->gid)) {
596 moan("couldn't set gid %i: %s", xo->gid, strerror(errno));
599 #ifdef HAVE_SETGROUPS
600 if (setgroups(1, &xo->gid))
601 moan("warning: couldn't set group list to %i: %s", xo->gid,
606 /* --- Set uid --- */
609 if (setuid(xo->uid)) {
610 moan("couldn't set uid %i: %s", xo->uid, strerror(errno));
615 /* --- Play with signal dispositions --- */
617 signal(SIGPIPE, SIG_DFL);
619 /* --- Fiddle with the environment --- */
621 xenv_apply(exec_opts.env);
622 xenv_apply(xe->xo->env);
623 environ = env_export(&env);
625 /* --- Run the program --- */
627 execvp(xe->xa->file, xe->xa->argv);
628 moan("couldn't execute `%s': %s", xe->xa->file, strerror(errno));
632 /* --- The child's done; see to the parent --- */
635 selbuf_init(&xe->err, sel, fd[0], xept_error, xe);
637 xe->next = xept_list;
640 xept_list->prev = xe;
642 if (!(xe->xo->f & XF_NOLOG))
643 fw_log(-1, "[%s] started with pid %i", xe->desc, kid);
648 /* --- @xept_file@ --- */
650 static void xept_file(endpt *e, endpt *f)
652 xept *xe = (xept *)e;
656 /* --- @xept_close@ --- */
658 static void xept_close(endpt *e)
660 xept *xe = (xept *)e;
663 xe->f->ops->close(xe->f);
664 x_tidy(xe->xa, xe->xo);
670 /* --- @xept_destroy@ --- */
672 static void xept_destroy(xept *xe)
674 /* --- First emit the news about the process --- */
676 if (xe->xo->f & XF_NOLOG)
678 else if (WIFEXITED(xe->st)) {
679 if (WEXITSTATUS(xe->st) == 0)
680 fw_log(-1, "[%s] pid %i exited successfully", xe->desc, xe->kid);
682 fw_log(-1, "[%s] pid %i failed: status %i",
683 xe->desc, xe->kid, WEXITSTATUS(xe->st));
685 } else if (WIFSIGNALED(xe->st)) {
687 #ifdef HAVE_STRSIGNAL
688 s = strsignal(WTERMSIG(xe->st));
689 #elif HAVE__SYS_SIGLIST
690 s = _sys_siglist[WTERMSIG(xe->st)];
693 sprintf(buf, "signal %i", WTERMSIG(xe->st));
696 fw_log(-1, "[%s] pid %i failed: %s", xe->desc, xe->kid, s);
698 fw_log(-1, "[%s] pid %i failed: unrecognized status", xe->desc, xe->kid);
700 /* --- Free up the parent-side resources --- */
703 xe->next->prev = xe->prev;
705 xe->prev->next = xe->next;
707 xept_list = xe->next;
711 xe->f->ops->close(xe->f);
712 x_tidy(xe->xa, xe->xo);
717 /* --- @xept_chld@ --- *
719 * Arguments: @int n@ = signal number
720 * @void *p@ = uninteresting pointer
724 * Use: Deals with child death situations.
727 static void xept_chld(int n, void *p)
732 while ((kid = waitpid(-1, &st, WNOHANG)) > 0) {
733 xept *xe = xept_list;
737 if (kid == xxe->kid) {
739 xxe->e.f |= XEF_EXIT;
740 if (xxe->e.f & XEF_CLOSE)
748 /* --- @xept_error@ --- *
750 * Arguments: @char *p@ = pointer to string read from stderr
751 * @size_t len@ = length of the string
752 * @void *v@ = pointer to by endpoint
756 * Use: Handles error reports from a child process.
759 static void xept_error(char *p, size_t len, void *v)
763 fw_log(-1, "[%s] pid %i: %s", xe->desc, xe->kid, p);
765 close(xe->err.reader.fd);
766 selbuf_destroy(&xe->err);
767 xe->e.f |= XEF_CLOSE;
768 if (xe->e.f & XEF_EXIT)
773 /* --- Endpoint operations --- */
775 static endpt_ops xept_ops = { xept_attach, xept_file, 0, xept_close };
777 /*----- General operations on sources and targets -------------------------*/
779 /* --- @exec_init@ --- *
785 * Use: Initializes the executable problem source and target.
790 rlimit_get(&exec_opts.xl);
791 sig_add(&xept_sig, SIGCHLD, xept_chld, 0);
793 env_import(&env, environ);
796 /* --- @exec_option@ --- */
798 static int exec_option(xdata *x, scanner *sc)
800 xopts *xo = x ? x->xo : &exec_opts;
802 CONF_BEGIN(sc, "exec", "executable");
804 /* --- Logging settings --- */
806 if (strcmp(sc->d.buf, "logging") == 0 ||
807 strcmp(sc->d.buf, "log") == 0) {
811 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
818 /* --- Current directory setting --- *
820 * Lots of possibilities to guard against possible brainoes.
823 if (strcmp(sc->d.buf, "dir") == 0 ||
824 strcmp(sc->d.buf, "cd") == 0 ||
825 strcmp(sc->d.buf, "chdir") == 0 ||
826 strcmp(sc->d.buf, "cwd") == 0) {
831 conf_name(sc, '/', &d);
832 xo->dir = xstrdup(d.buf);
837 /* --- Set a chroot prison --- */
839 if (strcmp(sc->d.buf, "root") == 0 ||
840 strcmp(sc->d.buf, "chroot") == 0) {
845 conf_name(sc, '/', &d);
846 xo->root = xstrdup(d.buf);
851 /* --- Set the target user id --- */
853 if (strcmp(sc->d.buf, "uid") == 0 ||
854 strcmp(sc->d.buf, "user") == 0) {
858 if (sc->t != CTOK_WORD)
859 error(sc, "parse error, expected user name or uid");
860 if (isdigit((unsigned char)*sc->d.buf))
861 xo->uid = atoi(sc->d.buf);
863 struct passwd *pw = getpwnam(sc->d.buf);
865 error(sc, "unknown user name `%s'", sc->d.buf);
866 xo->uid = pw->pw_uid;
872 /* --- Set the target group id --- */
874 if (strcmp(sc->d.buf, "gid") == 0 ||
875 strcmp(sc->d.buf, "group") == 0) {
879 if (sc->t != CTOK_WORD)
880 error(sc, "parse error, expected group name or gid");
881 if (isdigit((unsigned char)*sc->d.buf))
882 xo->gid = atoi(sc->d.buf);
884 struct group *gr = getgrnam(sc->d.buf);
886 error(sc, "unknown user name `%s'", sc->d.buf);
887 xo->gid = gr->gr_gid;
893 /* --- Now try resource limit settings --- */
895 if (rlimit_option(&xo->xl, sc))
898 /* --- And then environment settings --- */
900 if (xenv_option(xo, sc))
903 /* --- Nothing found --- */
908 /* --- @exec_desc@ --- */
910 static void exec_desc(xdata *x, dstr *d)
914 dstr_puts(d, "exec ");
915 if (strcmp(x->xa->file, x->xa->argv[0]) != 0) {
916 dstr_puts(d, x->xa->file);
919 for (p = x->xa->argv; *p; p++) {
928 /* --- @exec_read@ --- */
930 static void exec_read(xdata *x, scanner *sc)
936 /* --- Read the first word --- *
938 * This is either a shell command or the actual program to run.
941 if (sc->t == CTOK_WORD) {
942 dstr_putd(&d, &sc->d); d.len++;
947 /* --- See if there's a list of arguments --- *
949 * If not, then the thing I saw was a shell command, so build the proper
950 * arguments for that.
956 error(sc, "parse error, expected shell command or argument list");
957 xa = xmalloc(XARGS_SZ(3) + 8 + 3 + d.len);
958 p = (char *)(xa->argv + 4);
961 xa->argv[0] = p; memcpy(p, "/bin/sh", 8); p += 8;
962 xa->argv[1] = p; memcpy(p, "-c", 3); p += 3;
963 xa->argv[2] = p; memcpy(p, d.buf, d.len); p += d.len;
967 /* --- Snarf in a list of arguments --- */
974 /* --- Strip off the leading `[' --- */
978 /* --- Read a sequence of arguments --- */
980 while (sc->t == CTOK_WORD) {
981 dstr_putd(&d, &sc->d); d.len++;
986 /* --- Expect the closing `]' --- */
989 error(sc, "parse error, missing `]'");
992 /* --- If there are no arguments, whinge --- */
995 error(sc, "must specify at least one argument");
997 /* --- Allocate a lump of memory for the array --- */
999 xa = xmalloc(XARGS_SZ(argc) + d.len);
1002 p = (char *)(v + argc + 1);
1003 memcpy(p, d.buf, d.len);
1008 /* --- Start dumping addresses into the @argv@ array --- */
1012 while (*p++ && p < q)
1020 /* --- Do some other setting up --- */
1024 x->xo = CREATE(xopts);
1030 /* --- @exec_endpt@ --- */
1032 static endpt *exec_endpt(xdata *x, const char *desc)
1034 xept *xe = CREATE(xept);
1035 xe->e.ops = &xept_ops;
1039 xe->xa = x->xa; xe->xa->ref++;
1040 xe->xo = x->xo; xe->xo->ref++;
1043 xe->desc = xstrdup(desc);
1047 /* --- @exec_destroy@ --- */
1049 static void exec_destroy(xdata *x)
1051 x_tidy(x->xa, x->xo);
1054 /*----- Source definition -------------------------------------------------*/
1056 /* --- @option@ --- */
1058 static int xsource_option(source *s, scanner *sc)
1060 xsource *xs = (xsource *)s;
1061 return (exec_option(xs ? &xs->x : 0, sc));
1064 /* --- @read@ --- */
1066 static source *xsource_read(scanner *sc)
1070 if (!conf_prefix(sc, "exec"))
1072 xs = CREATE(xsource);
1073 xs->s.ops = &xsource_ops;
1075 exec_read(&xs->x, sc);
1079 /* --- @attach@ --- */
1081 static void xsource_destroy(source */*s*/);
1083 static void xsource_attach(source *s, scanner *sc, target *t)
1085 xsource *xs = (xsource *)s;
1088 /* --- Set up the source description string --- */
1092 exec_desc(&xs->x, &d);
1093 dstr_puts(&d, " -> ");
1094 dstr_puts(&d, t->desc);
1095 xs->s.desc = xstrdup(d.buf);
1099 /* --- Create the endpoints --- */
1101 if ((ee = t->ops->create(t, xs->s.desc)) == 0)
1103 if ((e = exec_endpt(&xs->x, xs->s.desc)) == 0) {
1109 /* --- Dispose of source and target --- */
1113 xsource_destroy(&xs->s);
1116 /* --- @destroy@ --- */
1118 static void xsource_destroy(source *s)
1120 xsource *xs = (xsource *)s;
1122 exec_destroy(&xs->x);
1126 /* --- Executable source operations --- */
1128 source_ops xsource_ops = {
1130 xsource_option, xsource_read, xsource_attach, xsource_destroy
1133 /*----- Exec target description -------------------------------------------*/
1135 /* --- @option@ --- */
1137 static int xtarget_option(target *t, scanner *sc)
1139 xtarget *xt = (xtarget *)t;
1140 return (exec_option(xt ? &xt->x : 0, sc));
1143 /* --- @read@ --- */
1145 static target *xtarget_read(scanner *sc)
1150 if (!conf_prefix(sc, "exec"))
1152 xt = CREATE(xtarget);
1153 xt->t.ops = &xtarget_ops;
1154 exec_read(&xt->x, sc);
1155 exec_desc(&xt->x, &d);
1156 xt->t.desc = xstrdup(d.buf);
1161 /* --- @create@ --- */
1163 static endpt *xtarget_create(target *t, const char *desc)
1165 xtarget *xt = (xtarget *)t;
1166 endpt *e = exec_endpt(&xt->x, desc);
1170 /* --- @destroy@ --- */
1172 static void xtarget_destroy(target *t)
1174 xtarget *xt = (xtarget *)t;
1176 exec_destroy(&xt->x);
1180 /* --- Exec target operations --- */
1182 target_ops xtarget_ops = {
1184 xtarget_option, xtarget_read, xtarget_create, xtarget_destroy
1187 /*----- That's all, folks -------------------------------------------------*/