3 * $Id: exec.c,v 1.7 2003/01/24 20:12:26 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.7 2003/01/24 20:12:26 mdw
33 * Correctly cast uid and gid sentinel values. Parse full filenames in
34 * exec arguments (can't do it for program, unfortunately, since the die is
37 * Revision 1.6 2002/02/22 23:43:32 mdw
38 * Call @xfree@ rather than @free@.
40 * Revision 1.5 2002/01/13 14:49:03 mdw
41 * Track @lbuf@ changes in mLib.
43 * Revision 1.4 2001/02/03 20:30:03 mdw
44 * Support re-reading config files on SIGHUP.
46 * Revision 1.3 2000/07/01 11:28:52 mdw
47 * Use new mLib selbuf features.
49 * Revision 1.2 1999/10/22 22:46:17 mdw
50 * When a non-file endpoint is attached to a file, keep the file endpoint
51 * open until the nonfile is done. This stops socket sources from
52 * resetting their connection limits too early.
54 * Revision 1.1 1999/07/26 23:33:32 mdw
55 * New sources and targets.
59 /*----- Header files ------------------------------------------------------*/
72 #include <sys/types.h>
79 # include <sys/resource.h>
83 extern char **environ;
91 #include <mLib/alloc.h>
92 #include <mLib/dstr.h>
94 #include <mLib/fdflags.h>
95 #include <mLib/report.h>
97 #include <mLib/selbuf.h>
100 #include <mLib/sym.h>
112 /*----- Data structures ---------------------------------------------------*/
114 /* --- Resource usage --- */
116 #ifdef HAVE_SETRLIMIT
118 typedef struct xlimit {
119 #define R(r, n) struct rlimit n;
125 /* --- Environment variable modifications --- */
127 typedef struct xenv {
137 /* --- Program options --- */
139 typedef struct xopts {
148 #ifdef HAVE_SETRLIMIT
155 /* --- Executable program arguments --- */
157 typedef struct xargs {
163 #define XARGS_SZ(n) (sizeof(xargs) + sizeof(char *) * (n))
165 /* --- Executable endpoints --- */
167 typedef struct xept {
169 struct xept *next, *prev;
179 #define XEF_CLOSE 16u
182 /* --- Executable program data --- */
184 typedef struct xdata {
189 /* --- Executable source block --- */
191 typedef struct xsource {
196 /* --- Executable target block --- */
198 typedef struct xtarget {
203 /*----- Static variables --------------------------------------------------*/
205 static xopts exec_opts = { 1, 0, 0, 0, -1, -1, 0, &exec_opts.env };
206 static xept *xept_list;
208 static sym_table env;
210 /*----- Fiddling about with resource limits -------------------------------*/
212 #ifdef HAVE_SETRLIMIT
214 /* --- Table mapping user-level names to OS interface bits --- */
216 typedef struct rlimit_ent {
223 static rlimit_ent rlimits[] = {
224 #define R(r, n) { #n, #r, r, offsetof(xlimit, n) },
229 #define RLIMIT(xl, o) ((struct rlimit *)((char *)(xl) + (o)))
231 /* --- @rlimit_get@ --- *
233 * Arguments: @xlimit *xl@ = pointer to limit structure
237 * Use: Initializes a limit structure from the current limits.
240 static void rlimit_get(xlimit *xl)
244 for (r = rlimits; r->name; r++) {
245 if (getrlimit(r->r, RLIMIT(xl, r->off))) {
246 moan("couldn't read %s: %s", r->rname, strerror(errno));
252 /* --- @rlimit_set@ --- *
254 * Arguments: @xlimit *xl@ = pointer to limit structure
258 * Use: Sets resource limits from the supplied limits structure.
261 static void rlimit_set(xlimit *xl)
265 for (r = rlimits; r->name; r++) {
266 if (setrlimit(r->r, RLIMIT(xl, r->off))) {
267 moan("couldn't set %s: %s", r->rname, strerror(errno));
273 /* --- @rlimit_option@ --- */
275 static int rlimit_option(xlimit *xl, scanner *sc)
277 CONF_BEGIN(sc, "rlimit", "resource limit")
278 enum { w_soft, w_hard, w_both } which = w_both;
283 /* --- Find out which resource is being fiddled --- */
289 for (r = rlimits; r->name; r++) {
290 if (strncmp(sc->d.buf, r->name, sc->d.len) == 0) {
291 if (r->name[sc->d.len] == 0) {
295 error(sc, "ambiguous resource limit name `%s'", sc->d.buf);
303 rl = RLIMIT(xl, chosen->off);
306 /* --- Look for hard or soft restrictions --- */
312 if (sc->t == CTOK_WORD) {
313 if ((i = conf_enum(sc, "soft,hard",
314 ENUM_ABBREV | ENUM_NONE, "limit type")) != -1)
319 /* --- Now read the new value --- */
323 if (sc->t != CTOK_WORD)
324 error(sc, "parse error, expected limit value");
326 if (conf_enum(sc, "unlimited,infinity",
327 ENUM_ABBREV | ENUM_NONE, "limit value") > -1)
332 v = strtol(sc->d.buf, &p, 0);
334 error(sc, "parse error, invalid limit value `%s'", sc->d.buf);
335 switch (tolower((unsigned char)*p)) {
337 case 'b': v *= 512; break;
340 case 'k': v *= 1024; break;
341 default: error(sc, "parse error, invalid limit scale `%c'", *p);
346 /* --- Store the limit value away --- */
354 if (v > rl->rlim_max)
355 error(sc, "soft limit %l exceeds hard limit %l for %s",
356 v, rl->rlim_max, chosen->rname);
361 if (rl->rlim_cur > v)
372 /*----- Environment fiddling ----------------------------------------------*/
374 /* --- @xenv_option@ --- *
376 * Arguments: @xopts *xo@ = pointer to options block
377 * @scanner *sc@ = pointer to scanner
379 * Returns: Nonzero if claimed
381 * Use: Parses environment variable assignments.
384 static int xenv_option(xopts *xo, scanner *sc)
386 CONF_BEGIN(sc, "env", "environment")
389 /* --- Unset a variable --- */
391 if (strcmp(sc->d.buf, "unset") == 0) {
393 if (sc->t != CTOK_WORD)
394 error(sc, "parse error, expected environment variable name");
396 xe->name = xstrdup(sc->d.buf);
403 /* --- Clear the entire environment --- */
405 if (strcmp(sc->d.buf, "clear") == 0) {
412 /* --- Allow `set' to be omitted if there's a prefix --- */
414 if (strcmp(sc->d.buf, "set") == 0)
419 /* --- Set a variable --- */
421 if (sc->t != CTOK_WORD)
422 error(sc, "parse error, expected environment variable name");
424 xe->name = xstrdup(sc->d.buf);
428 if (sc->t != CTOK_WORD)
429 error(sc, "parse error, expected environment variable value");
430 xe->value = xstrdup(sc->d.buf);
438 xo->etail = &xe->next;
441 /* --- Nothing else to try --- */
446 /* --- @xenv_apply@ --- *
448 * Arguments: @xenv *xe@ = pointer to a variable change list
452 * Use: Modifies the environment (in @env@) according to the list.
455 static void xenv_apply(xenv *xe)
460 env_put(&env, xe->name, xe->value);
471 /* --- @xenv_destroy@ --- *
473 * Arguments: @xenv *xe@ = pointer to a variable change list
477 * Use: Frees the memory used by an environment variable change list.
480 static void xenv_destroy(xenv *xe)
492 /*----- Miscellaneous good things -----------------------------------------*/
494 /* --- @x_tidy@ --- *
496 * Arguments: @xargs *xa@ = pointer to an arguments block
497 * @xopts *xo@ = pointer to an options block
501 * Use: Releases a reference to argument and options blocks.
504 static void x_tidy(xargs *xa, xopts *xo)
512 xenv_destroy(xo->env);
517 /*----- Executable endpoints ----------------------------------------------*/
519 /* --- @attach@ --- */
521 static void xept_error(char */*p*/, size_t /*len*/, void */*v*/);
523 static void xept_attach(endpt *e, reffd *in, reffd *out)
525 xept *xe = (xept *)e;
529 /* --- Make a pipe for standard error --- */
532 fw_log(-1, "[%s] couldn't create pipe: %s", xe->desc, strerror(errno));
535 fdflags(fd[0], O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
537 /* --- Fork a child, and handle an error if there was one --- */
539 if ((kid = fork()) == -1) {
540 fw_log(-1, "[%s] couldn't fork: %s", xe->desc, strerror(errno));
546 /* --- Do the child thing --- */
551 /* --- Fiddle with the file descriptors --- *
553 * Attach the other endpoint's descriptors to standard input and output.
554 * Attach my pipe to standard error. Mark everything as blocking and
555 * not-to-be-closed-on-exec at this end.
559 if (dup2(in->fd, STDIN_FILENO) < 0 ||
560 dup2(out->fd, STDOUT_FILENO) < 0 ||
561 dup2(fd[1], STDERR_FILENO) < 0) {
562 moan("couldn't manipulate file descriptors: %s", strerror(errno));
571 fdflags(STDIN_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
572 fdflags(STDOUT_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
573 fdflags(STDERR_FILENO, O_NONBLOCK, 0, FD_CLOEXEC, 0);
575 /* --- First of all set the @chroot@ prison --- */
577 if (xo->root && chroot(xo->root)) {
578 moan("couldn't set `%s' as filesystem root: %s",
579 xo->root, strerror(errno));
583 /* --- Now set the current directory --- */
585 if (xo->dir ? chdir(xo->dir) : xo->root ? chdir("/") : 0) {
586 moan("couldn't set `%s' as current directory: %s",
587 xo->dir ? xo->dir : "/", strerror(errno));
591 /* --- Set the resource limits --- */
593 #ifdef HAVE_SETRLIMIT
597 /* --- Set group id --- */
599 if (xo->gid != (gid_t)-1) {
600 if (setgid(xo->gid)) {
601 moan("couldn't set gid %i: %s", xo->gid, strerror(errno));
604 #ifdef HAVE_SETGROUPS
605 if (setgroups(1, &xo->gid))
606 moan("warning: couldn't set group list to %i: %s", xo->gid,
611 /* --- Set uid --- */
613 if (xo->uid != (uid_t)-1) {
614 if (setuid(xo->uid)) {
615 moan("couldn't set uid %i: %s", xo->uid, strerror(errno));
620 /* --- Play with signal dispositions --- */
622 signal(SIGPIPE, SIG_DFL);
624 /* --- Fiddle with the environment --- */
626 xenv_apply(exec_opts.env);
627 xenv_apply(xe->xo->env);
628 environ = env_export(&env);
630 /* --- Run the program --- */
632 execvp(xe->xa->file, xe->xa->argv);
633 moan("couldn't execute `%s': %s", xe->xa->file, strerror(errno));
637 /* --- The child's done; see to the parent --- */
640 selbuf_init(&xe->err, sel, fd[0], xept_error, xe);
642 xe->next = xept_list;
645 xept_list->prev = xe;
647 if (!(xe->xo->f & XF_NOLOG))
648 fw_log(-1, "[%s] started with pid %i", xe->desc, kid);
653 /* --- @xept_file@ --- */
655 static void xept_file(endpt *e, endpt *f)
657 xept *xe = (xept *)e;
661 /* --- @xept_close@ --- */
663 static void xept_close(endpt *e)
665 xept *xe = (xept *)e;
668 xe->f->ops->close(xe->f);
669 x_tidy(xe->xa, xe->xo);
675 /* --- @xept_destroy@ --- */
677 static void xept_destroy(xept *xe)
679 /* --- First emit the news about the process --- */
681 if (xe->xo->f & XF_NOLOG)
683 else if (WIFEXITED(xe->st)) {
684 if (WEXITSTATUS(xe->st) == 0)
685 fw_log(-1, "[%s] pid %i exited successfully", xe->desc, xe->kid);
687 fw_log(-1, "[%s] pid %i failed: status %i",
688 xe->desc, xe->kid, WEXITSTATUS(xe->st));
690 } else if (WIFSIGNALED(xe->st)) {
692 #ifdef HAVE_STRSIGNAL
693 s = strsignal(WTERMSIG(xe->st));
694 #elif HAVE__SYS_SIGLIST
695 s = _sys_siglist[WTERMSIG(xe->st)];
698 sprintf(buf, "signal %i", WTERMSIG(xe->st));
701 fw_log(-1, "[%s] pid %i failed: %s", xe->desc, xe->kid, s);
703 fw_log(-1, "[%s] pid %i failed: unrecognized status", xe->desc, xe->kid);
705 /* --- Free up the parent-side resources --- */
708 xe->next->prev = xe->prev;
710 xe->prev->next = xe->next;
712 xept_list = xe->next;
716 xe->f->ops->close(xe->f);
717 x_tidy(xe->xa, xe->xo);
722 /* --- @xept_chld@ --- *
724 * Arguments: @int n@ = signal number
725 * @void *p@ = uninteresting pointer
729 * Use: Deals with child death situations.
732 static void xept_chld(int n, void *p)
737 while ((kid = waitpid(-1, &st, WNOHANG)) > 0) {
738 xept *xe = xept_list;
742 if (kid == xxe->kid) {
744 xxe->e.f |= XEF_EXIT;
745 if (xxe->e.f & XEF_CLOSE)
753 /* --- @xept_error@ --- *
755 * Arguments: @char *p@ = pointer to string read from stderr
756 * @size_t len@ = length of the string
757 * @void *v@ = pointer to by endpoint
761 * Use: Handles error reports from a child process.
764 static void xept_error(char *p, size_t len, void *v)
768 fw_log(-1, "[%s] pid %i: %s", xe->desc, xe->kid, p);
770 close(xe->err.reader.fd);
771 selbuf_destroy(&xe->err);
772 xe->e.f |= XEF_CLOSE;
773 if (xe->e.f & XEF_EXIT)
778 /* --- Endpoint operations --- */
780 static endpt_ops xept_ops = { xept_attach, xept_file, 0, xept_close };
782 /*----- General operations on sources and targets -------------------------*/
784 /* --- @exec_init@ --- *
790 * Use: Initializes the executable problem source and target.
795 #ifdef HAVE_SETRLIMIT
796 rlimit_get(&exec_opts.xl);
798 sig_add(&xept_sig, SIGCHLD, xept_chld, 0);
800 env_import(&env, environ);
803 /* --- @exec_option@ --- */
805 static int exec_option(xdata *x, scanner *sc)
807 xopts *xo = x ? x->xo : &exec_opts;
809 CONF_BEGIN(sc, "exec", "executable");
811 /* --- Logging settings --- */
813 if (strcmp(sc->d.buf, "logging") == 0 ||
814 strcmp(sc->d.buf, "log") == 0) {
818 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
825 /* --- Current directory setting --- *
827 * Lots of possibilities to guard against possible brainoes.
830 if (strcmp(sc->d.buf, "dir") == 0 ||
831 strcmp(sc->d.buf, "cd") == 0 ||
832 strcmp(sc->d.buf, "chdir") == 0 ||
833 strcmp(sc->d.buf, "cwd") == 0) {
838 conf_name(sc, '/', &d);
839 xo->dir = xstrdup(d.buf);
844 /* --- Set a chroot prison --- */
846 if (strcmp(sc->d.buf, "root") == 0 ||
847 strcmp(sc->d.buf, "chroot") == 0) {
852 conf_name(sc, '/', &d);
853 xo->root = xstrdup(d.buf);
858 /* --- Set the target user id --- */
860 if (strcmp(sc->d.buf, "uid") == 0 ||
861 strcmp(sc->d.buf, "user") == 0) {
865 if (sc->t != CTOK_WORD)
866 error(sc, "parse error, expected user name or uid");
867 if (isdigit((unsigned char)*sc->d.buf))
868 xo->uid = atoi(sc->d.buf);
870 struct passwd *pw = getpwnam(sc->d.buf);
872 error(sc, "unknown user name `%s'", sc->d.buf);
873 xo->uid = pw->pw_uid;
879 /* --- Set the target group id --- */
881 if (strcmp(sc->d.buf, "gid") == 0 ||
882 strcmp(sc->d.buf, "group") == 0) {
886 if (sc->t != CTOK_WORD)
887 error(sc, "parse error, expected group name or gid");
888 if (isdigit((unsigned char)*sc->d.buf))
889 xo->gid = atoi(sc->d.buf);
891 struct group *gr = getgrnam(sc->d.buf);
893 error(sc, "unknown user name `%s'", sc->d.buf);
894 xo->gid = gr->gr_gid;
900 /* --- Now try resource limit settings --- */
902 #ifdef HAVE_SETRLIMIT
903 if (rlimit_option(&xo->xl, sc))
907 /* --- And then environment settings --- */
909 if (xenv_option(xo, sc))
912 /* --- Nothing found --- */
917 /* --- @exec_desc@ --- */
919 static void exec_desc(xdata *x, dstr *d)
923 dstr_puts(d, "exec ");
924 if (strcmp(x->xa->file, x->xa->argv[0]) != 0) {
925 dstr_puts(d, x->xa->file);
928 for (p = x->xa->argv; *p; p++) {
937 /* --- @exec_read@ --- */
939 static void exec_read(xdata *x, scanner *sc)
945 /* --- Read the first word --- *
947 * This is either a shell command or the actual program to run.
950 if (sc->t == CTOK_WORD) {
951 dstr_putd(&d, &sc->d); d.len++;
956 /* --- See if there's a list of arguments --- *
958 * If not, then the thing I saw was a shell command, so build the proper
959 * arguments for that.
965 error(sc, "parse error, expected shell command or argument list");
966 xa = xmalloc(XARGS_SZ(3) + 8 + 3 + d.len);
967 p = (char *)(xa->argv + 4);
970 xa->argv[0] = p; memcpy(p, "/bin/sh", 8); p += 8;
971 xa->argv[1] = p; memcpy(p, "-c", 3); p += 3;
972 xa->argv[2] = p; memcpy(p, d.buf, d.len); p += d.len;
976 /* --- Snarf in a list of arguments --- */
983 /* --- Strip off the leading `[' --- *
985 * Allow various handy filename characters to be entered without quoting.
988 conf_undelim(sc, "=:/.", "=:/.");
991 /* --- Read a sequence of arguments --- */
993 while (sc->t == CTOK_WORD) {
994 dstr_putd(&d, &sc->d); d.len++;
998 conf_undelim(sc, 0, 0);
1000 /* --- Expect the closing `]' --- */
1003 error(sc, "parse error, missing `]'");
1006 /* --- If there are no arguments, whinge --- */
1009 error(sc, "must specify at least one argument");
1011 /* --- Allocate a lump of memory for the array --- */
1013 xa = xmalloc(XARGS_SZ(argc) + d.len);
1016 p = (char *)(v + argc + 1);
1017 memcpy(p, d.buf, d.len);
1022 /* --- Start dumping addresses into the @argv@ array --- */
1026 while (*p++ && p < q)
1034 /* --- Do some other setting up --- */
1038 x->xo = CREATE(xopts);
1044 /* --- @exec_endpt@ --- */
1046 static endpt *exec_endpt(xdata *x, const char *desc)
1048 xept *xe = CREATE(xept);
1049 xe->e.ops = &xept_ops;
1053 xe->xa = x->xa; xe->xa->ref++;
1054 xe->xo = x->xo; xe->xo->ref++;
1057 xe->desc = xstrdup(desc);
1061 /* --- @exec_destroy@ --- */
1063 static void exec_destroy(xdata *x)
1065 x_tidy(x->xa, x->xo);
1068 /*----- Source definition -------------------------------------------------*/
1070 /* --- @option@ --- */
1072 static int xsource_option(source *s, scanner *sc)
1074 xsource *xs = (xsource *)s;
1075 return (exec_option(xs ? &xs->x : 0, sc));
1078 /* --- @read@ --- */
1080 static source *xsource_read(scanner *sc)
1084 if (!conf_prefix(sc, "exec"))
1086 xs = CREATE(xsource);
1087 xs->s.ops = &xsource_ops;
1089 exec_read(&xs->x, sc);
1093 /* --- @attach@ --- */
1095 static void xsource_destroy(source */*s*/);
1097 static void xsource_attach(source *s, scanner *sc, target *t)
1099 xsource *xs = (xsource *)s;
1102 /* --- Set up the source description string --- */
1106 exec_desc(&xs->x, &d);
1107 dstr_puts(&d, " -> ");
1108 dstr_puts(&d, t->desc);
1109 xs->s.desc = xstrdup(d.buf);
1113 /* --- Create the endpoints --- */
1115 if ((ee = t->ops->create(t, xs->s.desc)) == 0)
1117 if ((e = exec_endpt(&xs->x, xs->s.desc)) == 0) {
1123 /* --- Dispose of source and target --- */
1127 xsource_destroy(&xs->s);
1130 /* --- @destroy@ --- */
1132 static void xsource_destroy(source *s)
1134 xsource *xs = (xsource *)s;
1136 exec_destroy(&xs->x);
1140 /* --- Executable source operations --- */
1142 source_ops xsource_ops = {
1144 xsource_option, xsource_read, xsource_attach, xsource_destroy
1147 /*----- Exec target description -------------------------------------------*/
1149 /* --- @option@ --- */
1151 static int xtarget_option(target *t, scanner *sc)
1153 xtarget *xt = (xtarget *)t;
1154 return (exec_option(xt ? &xt->x : 0, sc));
1157 /* --- @read@ --- */
1159 static target *xtarget_read(scanner *sc)
1164 if (!conf_prefix(sc, "exec"))
1166 xt = CREATE(xtarget);
1167 xt->t.ops = &xtarget_ops;
1168 exec_read(&xt->x, sc);
1169 exec_desc(&xt->x, &d);
1170 xt->t.desc = xstrdup(d.buf);
1175 /* --- @create@ --- */
1177 static endpt *xtarget_create(target *t, const char *desc)
1179 xtarget *xt = (xtarget *)t;
1180 endpt *e = exec_endpt(&xt->x, desc);
1184 /* --- @destroy@ --- */
1186 static void xtarget_destroy(target *t)
1188 xtarget *xt = (xtarget *)t;
1190 exec_destroy(&xt->x);
1194 /* --- Exec target operations --- */
1196 target_ops xtarget_ops = {
1198 xtarget_option, xtarget_read, xtarget_create, xtarget_destroy
1201 /*----- That's all, folks -------------------------------------------------*/