3 * $Id: fw.c,v 1.14 2003/01/24 20:12:40 mdw Exp $
5 * Port forwarding thingy
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.14 2003/01/24 20:12:40 mdw
33 * Correctly cast uid and gid sentinel values.
35 * Revision 1.13 2002/02/22 23:45:20 mdw
36 * Add option to change the listen(2) parameter. Receive `fw'-specific
39 * Revision 1.12 2002/01/13 14:49:17 mdw
40 * Track @dstr_vputf@ change.
42 * Revision 1.11 2001/02/03 20:33:26 mdw
43 * Fix flags to be unsigned.
45 * Revision 1.10 2001/02/03 20:30:03 mdw
46 * Support re-reading config files on SIGHUP.
48 * Revision 1.9 2001/01/20 11:55:17 mdw
49 * Handle select errors more robustly.
51 * Revision 1.8 2000/03/23 23:19:19 mdw
52 * Fix changed options in parser table.
54 * Revision 1.7 2000/03/23 00:37:33 mdw
55 * Add option to change user and group after initialization. Naughtily
56 * reassign short equivalents of --grammar and --options.
58 * Revision 1.6 1999/12/22 15:44:10 mdw
59 * Make syslog a separate option, and do it better.
61 * Revision 1.5 1999/10/22 22:47:50 mdw
62 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
64 * Revision 1.4 1999/10/10 16:46:12 mdw
65 * New resolver to initialize. Also, include options for grammar and
68 * Revision 1.3 1999/07/26 23:30:42 mdw
69 * Major reconstruction work for new design.
71 * Revision 1.2 1999/07/03 13:55:17 mdw
72 * Various changes. Add configuration grammar to help text. Change to
73 * root directory and open syslog when forking into background.
75 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
80 /*----- Header files ------------------------------------------------------*/
100 #include <mLib/bres.h>
101 #include <mLib/dstr.h>
102 #include <mLib/mdwopt.h>
103 #include <mLib/quis.h>
104 #include <mLib/report.h>
105 #include <mLib/sel.h>
106 #include <mLib/sig.h>
107 #include <mLib/sub.h>
119 /*----- Global variables --------------------------------------------------*/
121 sel_state *sel; /* Multiplexor for nonblocking I/O */
123 /*----- Static variables --------------------------------------------------*/
125 typedef struct conffile {
126 struct conffile *next;
130 static unsigned flags = 0; /* Global state flags */
131 static unsigned active = 0; /* Number of active things */
132 static conffile *conffiles = 0; /* List of configuration files */
138 /*----- Configuration parsing ---------------------------------------------*/
142 * Arguments: @scanner *sc@ = pointer to scanner definition
146 * Use: Parses a configuration file from the scanner.
149 static source_ops *sources[] =
150 { &xsource_ops, &fsource_ops, &ssource_ops, 0 };
151 static target_ops *targets[] =
152 { &xtarget_ops, &ftarget_ops, &starget_ops, 0 };
154 void parse(scanner *sc)
159 if (sc->t == CTOK_EOF)
161 if (sc->t != CTOK_WORD)
162 error(sc, "parse error, keyword expected");
164 /* --- Handle a forwarding request --- */
166 if (strcmp(sc->d.buf, "forward") == 0 ||
167 strcmp(sc->d.buf, "fw") == 0 ||
168 strcmp(sc->d.buf, "from") == 0) {
174 /* --- Read a source description --- */
179 /* --- Try to find a source type which understands --- */
182 for (sops = sources; *sops; sops++) {
183 if ((s = (*sops)->read(sc)) != 0)
186 error(sc, "unknown source name `%s'", sc->d.buf);
188 /* --- Read any source-specific options --- */
193 while (sc->t == CTOK_WORD) {
194 if (!s->ops->option || !s->ops->option(s, sc)) {
195 error(sc, "unknown %s source option `%s'",
196 s->ops->name, sc->d.buf);
202 error(sc, "parse error, missing `}'");
207 /* --- Read a destination description --- */
209 if (sc->t == CTOK_WORD && (strcmp(sc->d.buf, "to") == 0 ||
210 strcmp(sc->d.buf, "->") == 0))
216 /* --- Try to find a target which understands --- */
219 for (tops = targets; *tops; tops++) {
220 if ((t = (*tops)->read(sc)) != 0)
223 error(sc, "unknown target name `%s'", sc->d.buf);
225 /* --- Read any target-specific options --- */
230 while (sc->t == CTOK_WORD) {
231 if (!t->ops->option || !t->ops->option(t, sc)) {
232 error(sc, "unknown %s target option `%s'",
233 t->ops->name, sc->d.buf);
239 error(sc, "parse error, `}' expected");
244 /* --- Combine the source and target --- */
246 s->ops->attach(s, sc, t);
249 /* --- Include configuration from a file --- *
251 * Slightly tricky. Scan the optional semicolon from the including
252 * stream, not the included one.
255 else if (strcmp(sc->d.buf, "include") == 0) {
260 conf_name(sc, '/', &d);
261 if ((fp = fopen(d.buf, "r")) == 0)
262 error(sc, "can't include `%s': %s", d.buf, strerror(errno));
266 scan_push(sc, scan_file(fp, d.buf, 0));
269 continue; /* Don't parse a trailing `;' */
272 /* --- Other configuration is handled elsewhere --- */
276 /* --- First try among the sources --- */
281 for (sops = sources; *sops; sops++) {
282 if ((*sops)->option && (*sops)->option(0, sc))
287 /* --- Then try among the targets --- */
292 for (tops = targets; *tops; tops++) {
293 if ((*tops)->option && (*tops)->option(0, sc))
298 /* --- Nobody wants the option --- */
300 error(sc, "unknown global option or prefix `%s'", sc->d.buf);
310 /*----- General utility functions -----------------------------------------*/
312 /* --- @fw_log@ --- *
314 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
315 * @const char *fmt@ = format string to fill in
316 * @...@ = other arguments
320 * Use: Logs a connection.
323 void fw_log(time_t t, const char *fmt, ...)
329 if (flags & FW_QUIET)
336 d.len += strftime(d.buf, d.sz, "%Y-%m-%d %H:%M:%S ", tm);
338 dstr_vputf(&d, fmt, &ap);
340 if (flags & FW_SYSLOG)
341 syslog(LOG_NOTICE, "%s", d.buf);
344 dstr_write(&d, stderr);
349 /* --- @fw_inc@, @fw_dec@ --- *
355 * Use: Increments or decrements the active thing count. `fw' won't
356 * quit while there are active things.
359 void fw_inc(void) { flags |= FW_SET; active++; }
360 void fw_dec(void) { if (active) active--; }
362 /* --- @fw_exit@ --- *
368 * Use: Exits when appropriate.
371 static void fw_exit(void)
377 /* --- @fw_tidy@ --- *
379 * Arguments: @int n@ = signal number
380 * @void *p@ = an uninteresting argument
384 * Use: Handles various signals and causes a clean tidy-up.
387 static void fw_tidy(int n, void *p)
391 case SIGTERM: sn = "SIGTERM"; break;
392 case SIGINT: sn = "SIGINT"; break;
396 fw_log(-1, "closing down gracefully on %s", sn);
400 /* --- @fw_die@ --- *
402 * Arguments: @int n@ = signal number
403 * @void *p@ = an uninteresting argument
407 * Use: Handles various signals and causes an abrupt shutdown.
410 static void fw_die(int n, void *p)
414 case SIGQUIT: sn = "SIGQUIT"; break;
418 fw_log(-1, "closing down abruptly on %s", sn);
423 /* --- @fw_reload@ --- *
425 * Arguments: @int n@ = a signal number
426 * @void *p@ = an uninteresting argument
430 * Use: Handles a hangup signal by re-reading configuration files.
433 static void fw_reload(int n, void *p)
441 fw_log(-1, "no configuration files to reload: ignoring SIGHUP");
444 fw_log(-1, "reloading configuration files...");
447 for (cf = conffiles; cf; cf = cf->next) {
448 if ((fp = fopen(cf->name, "r")) == 0)
449 fw_log(-1, "error loading `%s': %s", cf->name, strerror(errno));
451 scan_add(&sc, scan_file(fp, cf->name, 0));
454 fw_log(-1, "... reload completed OK");
457 /*----- Startup and options parsing ---------------------------------------*/
459 /* --- Standard GNU help options --- */
461 static void version(FILE *fp)
463 pquis(fp, "$ version " VERSION "\n");
466 static void usage(FILE *fp)
468 pquis(fp, "Usage: $ [-dql] [-f file] [config statements...]\n");
471 static void help(FILE *fp)
477 An excessively full-featured port-forwarder, which subsumes large chunks\n\
478 of the functionality of inetd, netcat, and normal cat. Options available\n\
481 -h, --help Display this help message.\n\
482 -v, --version Display the program's version number.\n\
483 -u, --usage Display a terse usage summary.\n\
485 -G, --grammar Show a summary of the configuration language.\n\
486 -O, --options Show a summary of the source and target options.\n\
488 -f, --file=FILE Read configuration from a file.\n\
489 -q, --quiet Don't emit any logging information.\n\
490 -d, --daemon Fork into background after initializing.\n\
491 -l, --syslog Send log output to the system logger.\n\
492 -s, --setuid=USER Change uid to USER after initializing sources.\n\
493 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
495 Configuration may be supplied in one or more configuration files, or on\n\
496 the command line (or both). If no `-f' option is present, and no\n\
497 configuration is given on the command line, the standard input stream is\n\
500 Configuration is free-form. Comments begin with a `#' character and\n\
501 continue to the end of the line. Each command line argument is considered\n\
502 to be a separate line.\n\
504 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
505 For a summary of the various options, run `$ --options'.\n\
509 /* --- Other helpful options --- */
511 static void grammar(FILE *fp)
518 file ::= empty | file stmt [`;']\n\
519 stmt ::= option-stmt | fw-stmt\n\
520 fw-stmt ::= `fw' source options [`to'|`->'] target options\n\
521 options ::= `{' option-seq `}'\n\
522 option-seq ::= empty | option-stmt [`;'] option-seq\n\
525 option-stmt ::= q-option\n\
526 q-option ::= option\n\
527 | prefix `.' q-option\n\
528 | prefix `{' option-seq `}'\n\
531 File source and target\n\
534 file ::= `file' [`.'] fspec [`,' fspec]\n\
535 fspec ::= fd-spec | name-spec | null-spec\n\
536 fd-spec ::= [[`:']`fd'[`:']] number|`stdin'|`stdout'\n\
537 name-spec ::= [[`:']`file'[`:']] file-name\n\
538 file-name ::= path-seq | [ path-seq ]\n\
539 path-seq ::= path-elt | path-seq path-elt\n\
540 path-elt ::= `/' | word\n\
541 null-spec ::= [`:']`null'[`:']\n\
543 Exec source and target\n\
546 exec ::= `exec' [`.'] cmd-spec\n\
547 cmd-spec ::= shell-cmd | [prog-name] `[' argv0 arg-seq `]'\n\
548 arg-seq ::= word | arg-seq word\n\
549 shell-cmd ::= word\n\
552 Socket source and target\n\
553 source ::= socket-source\n\
554 target ::= socket-target\n\
555 socket-source ::= [`socket'[`.']] [[`:']addr-type[`:']] source-addr\n\
556 socket-target ::= [`socket'[`.']] [[`:']addr-type[`:']] target-addr\n\
558 inet-source-addr ::= [port] port\n\
559 inet-target-addr ::= address [`:'] port\n\
560 address ::= addr-elt | address addr-elt\n\
561 addr-elt ::= `.' | word\n\
563 unix-source-addr ::= file-name\n\
564 unix-target-addr ::= file-name\n\
568 static void options(FILE *fp)
574 File attributes (`fattr')\n\
575 prefix.fattr.mode [=] mode\n\
576 prefix.fattr.owner [=] user\n\
577 prefix.fattr.group [=] group\n\
580 file.create [=] yes|no\n\
581 file.open [=] no|truncate|append\n\
585 exec.logging [=] yes|no\n\
586 exec.dir [=] file-name\n\
587 exec.root [=] file-name\n\
588 exec.user [=] user\n\
589 exec.group [=] group\n\
590 exec.rlimit.limit[.hard|.soft] [=] value\n\
592 exec.env.unset var\n\
593 exec.env.[set] var [=] value\n\
596 socket.conn [=] number|unlimited|one-shot\n\
597 socket.listen [=] number\n\
598 socket.logging [=] yes|no\n\
600 socket.inet.[allow|deny] [from] address [/ address]\n\
602 socket.unix.fattr.*\n\
608 * Arguments: @int argc@ = number of command line arguments
609 * @char *argv[]@ = vector of argument strings
613 * Use: Simple port-forwarding server.
616 int main(int argc, char *argv[])
620 sig s_term, s_quit, s_int, s_hup;
624 conffile *cf, **cff = &conffiles;
631 /* --- Initialize things --- */
641 fattr_init(&fattr_global);
646 /* --- Parse command line options --- */
649 static struct option opts[] = {
651 /* --- Standard GNU help options --- */
653 { "help", 0, 0, 'h' },
654 { "version", 0, 0, 'v' },
655 { "usage", 0, 0, 'u' },
657 /* --- Other help options --- */
659 { "grammar", 0, 0, 'G' },
660 { "options", 0, 0, 'O' },
662 /* --- Other useful arguments --- */
664 { "file", OPTF_ARGREQ, 0, 'f' },
665 { "fork", 0, 0, 'd' },
666 { "daemon", 0, 0, 'd' },
667 { "syslog", 0, 0, 'l' },
668 { "log", 0, 0, 'l' },
669 { "quiet", 0, 0, 'q' },
670 { "setuid", OPTF_ARGREQ, 0, 's' },
671 { "uid", OPTF_ARGREQ, 0, 's' },
672 { "setgid", OPTF_ARGREQ, 0, 'g' },
673 { "gid", OPTF_ARGREQ, 0, 'g' },
675 /* --- Magic terminator --- */
679 int i = mdwopt(argc, argv, "+hvu GO f:dls:g:", opts, 0, 0, 0);
705 if (strcmp(optarg, "-") == 0)
706 scan_add(&sc, scan_file(stdin, "<stdin>", SCF_NOCLOSE));
709 if ((fp = fopen(optarg, "r")) == 0)
710 die(1, "couldn't open file `%s': %s", optarg, strerror(errno));
711 cf = CREATE(conffile);
715 scan_add(&sc, scan_file(fp, optarg, 0));
729 if (isdigit((unsigned char )optarg[0])) {
731 drop = strtol(optarg, &q, 0);
733 die(1, "bad uid `%s'", optarg);
735 struct passwd *pw = getpwnam(optarg);
737 die(1, "unknown user `%s'", optarg);
742 if (isdigit((unsigned char )optarg[0])) {
744 dropg = strtol(optarg, &q, 0);
746 die(1, "bad gid `%s'", optarg);
748 struct group *gr = getgrnam(optarg);
750 die(1, "unknown group `%s'", optarg);
766 /* --- Deal with the remaining arguments --- */
769 scan_add(&sc, scan_argv(argv + optind));
772 else if (!isatty(STDIN_FILENO))
773 scan_add(&sc, scan_file(stdin, "<stdin>", SCF_NOCLOSE));
775 moan("no configuration given and stdin is a terminal.");
776 moan("type `%s --help' for usage information.", QUIS);
780 /* --- Parse the configuration now gathered --- */
784 /* --- Set up some signal handlers --- *
786 * Don't enable @SIGINT@ if the caller already disabled it.
792 sig_add(&s_term, SIGTERM, fw_tidy, 0);
793 sig_add(&s_quit, SIGQUIT, fw_die, 0);
794 sigaction(SIGINT, 0, &sa);
795 if (sa.sa_handler != SIG_IGN)
796 sig_add(&s_int, SIGINT, fw_tidy, 0);
797 sig_add(&s_hup, SIGHUP, fw_reload, 0);
800 /* --- Drop privileges --- */
802 #ifdef HAVE_SETGROUPS
803 if ((dropg != (gid_t)-1 && (setgid(dropg) || setgroups(1, &dropg))) ||
804 (drop != (uid_t)-1 && setuid(drop)))
805 die(1, "couldn't drop privileges: %s", strerror(errno));
807 if ((dropg != (gid_t)-1 && setgid(dropg)) ||
808 (drop != (uid_t)-1 && setuid(drop)))
809 die(1, "couldn't drop privileges: %s", strerror(errno));
812 /* --- Fork into the background --- */
819 die(1, "couldn't fork: %s", strerror(errno));
823 close(0); close(1); close(2);
834 openlog(QUIS, 0, LOG_DAEMON);
837 /* --- Let rip --- */
839 if (!(flags & FW_SET))
840 moan("nothing to do!");
841 signal(SIGPIPE, SIG_IGN);
846 if (!sel_select(sel))
848 else if (errno != EINTR && errno != EAGAIN) {
849 fw_log(-1, "error from select: %s", strerror(errno));
852 fw_log(-1, "too many consecutive select errors: bailing out");
862 /*----- That's all, folks -------------------------------------------------*/