c2c345c1d3f7089e774ab94b9df16cc932f6bda7
3 * $Id: fw.c,v 1.13 2002/02/22 23:45:20 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.13 2002/02/22 23:45:20 mdw
33 * Add option to change the listen(2) parameter. Receive `fw'-specific
36 * Revision 1.12 2002/01/13 14:49:17 mdw
37 * Track @dstr_vputf@ change.
39 * Revision 1.11 2001/02/03 20:33:26 mdw
40 * Fix flags to be unsigned.
42 * Revision 1.10 2001/02/03 20:30:03 mdw
43 * Support re-reading config files on SIGHUP.
45 * Revision 1.9 2001/01/20 11:55:17 mdw
46 * Handle select errors more robustly.
48 * Revision 1.8 2000/03/23 23:19:19 mdw
49 * Fix changed options in parser table.
51 * Revision 1.7 2000/03/23 00:37:33 mdw
52 * Add option to change user and group after initialization. Naughtily
53 * reassign short equivalents of --grammar and --options.
55 * Revision 1.6 1999/12/22 15:44:10 mdw
56 * Make syslog a separate option, and do it better.
58 * Revision 1.5 1999/10/22 22:47:50 mdw
59 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
61 * Revision 1.4 1999/10/10 16:46:12 mdw
62 * New resolver to initialize. Also, include options for grammar and
65 * Revision 1.3 1999/07/26 23:30:42 mdw
66 * Major reconstruction work for new design.
68 * Revision 1.2 1999/07/03 13:55:17 mdw
69 * Various changes. Add configuration grammar to help text. Change to
70 * root directory and open syslog when forking into background.
72 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
77 /*----- Header files ------------------------------------------------------*/
97 #include <mLib/bres.h>
98 #include <mLib/dstr.h>
99 #include <mLib/mdwopt.h>
100 #include <mLib/quis.h>
101 #include <mLib/report.h>
102 #include <mLib/sel.h>
103 #include <mLib/sig.h>
104 #include <mLib/sub.h>
116 /*----- Global variables --------------------------------------------------*/
118 sel_state
*sel
; /* Multiplexor for nonblocking I/O */
120 /*----- Static variables --------------------------------------------------*/
122 typedef struct conffile
{
123 struct conffile
*next
;
127 static unsigned flags
= 0; /* Global state flags */
128 static unsigned active
= 0; /* Number of active things */
129 static conffile
*conffiles
= 0; /* List of configuration files */
135 /*----- Configuration parsing ---------------------------------------------*/
139 * Arguments: @scanner *sc@ = pointer to scanner definition
143 * Use: Parses a configuration file from the scanner.
146 static source_ops
*sources
[] =
147 { &xsource_ops
, &fsource_ops
, &ssource_ops
, 0 };
148 static target_ops
*targets
[] =
149 { &xtarget_ops
, &ftarget_ops
, &starget_ops
, 0 };
151 void parse(scanner
*sc
)
156 if (sc
->t
== CTOK_EOF
)
158 if (sc
->t
!= CTOK_WORD
)
159 error(sc
, "parse error, keyword expected");
161 /* --- Handle a forwarding request --- */
163 if (strcmp(sc
->d
.buf
, "forward") == 0 ||
164 strcmp(sc
->d
.buf
, "fw") == 0 ||
165 strcmp(sc
->d
.buf
, "from") == 0) {
171 /* --- Read a source description --- */
176 /* --- Try to find a source type which understands --- */
179 for (sops
= sources
; *sops
; sops
++) {
180 if ((s
= (*sops
)->read(sc
)) != 0)
183 error(sc
, "unknown source name `%s'", sc
->d
.buf
);
185 /* --- Read any source-specific options --- */
190 while (sc
->t
== CTOK_WORD
) {
191 if (!s
->ops
->option
|| !s
->ops
->option(s
, sc
)) {
192 error(sc
, "unknown %s source option `%s'",
193 s
->ops
->name
, sc
->d
.buf
);
199 error(sc
, "parse error, missing `}'");
204 /* --- Read a destination description --- */
206 if (sc
->t
== CTOK_WORD
&& (strcmp(sc
->d
.buf
, "to") == 0 ||
207 strcmp(sc
->d
.buf
, "->") == 0))
213 /* --- Try to find a target which understands --- */
216 for (tops
= targets
; *tops
; tops
++) {
217 if ((t
= (*tops
)->read(sc
)) != 0)
220 error(sc
, "unknown target name `%s'", sc
->d
.buf
);
222 /* --- Read any target-specific options --- */
227 while (sc
->t
== CTOK_WORD
) {
228 if (!t
->ops
->option
|| !t
->ops
->option(t
, sc
)) {
229 error(sc
, "unknown %s target option `%s'",
230 t
->ops
->name
, sc
->d
.buf
);
236 error(sc
, "parse error, `}' expected");
241 /* --- Combine the source and target --- */
243 s
->ops
->attach(s
, sc
, t
);
246 /* --- Include configuration from a file --- *
248 * Slightly tricky. Scan the optional semicolon from the including
249 * stream, not the included one.
252 else if (strcmp(sc
->d
.buf
, "include") == 0) {
257 conf_name(sc
, '/', &d
);
258 if ((fp
= fopen(d
.buf
, "r")) == 0)
259 error(sc
, "can't include `%s': %s", d
.buf
, strerror(errno
));
263 scan_push(sc
, scan_file(fp
, d
.buf
, 0));
266 continue; /* Don't parse a trailing `;' */
269 /* --- Other configuration is handled elsewhere --- */
273 /* --- First try among the sources --- */
278 for (sops
= sources
; *sops
; sops
++) {
279 if ((*sops
)->option
&& (*sops
)->option(0, sc
))
284 /* --- Then try among the targets --- */
289 for (tops
= targets
; *tops
; tops
++) {
290 if ((*tops
)->option
&& (*tops
)->option(0, sc
))
295 /* --- Nobody wants the option --- */
297 error(sc
, "unknown global option or prefix `%s'", sc
->d
.buf
);
307 /*----- General utility functions -----------------------------------------*/
309 /* --- @fw_log@ --- *
311 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
312 * @const char *fmt@ = format string to fill in
313 * @...@ = other arguments
317 * Use: Logs a connection.
320 void fw_log(time_t t
, const char *fmt
, ...)
326 if (flags
& FW_QUIET
)
333 d
.len
+= strftime(d
.buf
, d
.sz
, "%Y-%m-%d %H:%M:%S ", tm
);
335 dstr_vputf(&d
, fmt
, &ap
);
337 if (flags
& FW_SYSLOG
)
338 syslog(LOG_NOTICE
, "%s", d
.buf
);
341 dstr_write(&d
, stderr
);
346 /* --- @fw_inc@, @fw_dec@ --- *
352 * Use: Increments or decrements the active thing count. `fw' won't
353 * quit while there are active things.
356 void fw_inc(void) { flags
|= FW_SET
; active
++; }
357 void fw_dec(void) { if (active
) active
--; }
359 /* --- @fw_exit@ --- *
365 * Use: Exits when appropriate.
368 static void fw_exit(void)
374 /* --- @fw_tidy@ --- *
376 * Arguments: @int n@ = signal number
377 * @void *p@ = an uninteresting argument
381 * Use: Handles various signals and causes a clean tidy-up.
384 static void fw_tidy(int n
, void *p
)
388 case SIGTERM
: sn
= "SIGTERM"; break;
389 case SIGINT
: sn
= "SIGINT"; break;
393 fw_log(-1, "closing down gracefully on %s", sn
);
397 /* --- @fw_die@ --- *
399 * Arguments: @int n@ = signal number
400 * @void *p@ = an uninteresting argument
404 * Use: Handles various signals and causes an abrupt shutdown.
407 static void fw_die(int n
, void *p
)
411 case SIGQUIT
: sn
= "SIGQUIT"; break;
415 fw_log(-1, "closing down abruptly on %s", sn
);
420 /* --- @fw_reload@ --- *
422 * Arguments: @int n@ = a signal number
423 * @void *p@ = an uninteresting argument
427 * Use: Handles a hangup signal by re-reading configuration files.
430 static void fw_reload(int n
, void *p
)
438 fw_log(-1, "no configuration files to reload: ignoring SIGHUP");
441 fw_log(-1, "reloading configuration files...");
444 for (cf
= conffiles
; cf
; cf
= cf
->next
) {
445 if ((fp
= fopen(cf
->name
, "r")) == 0)
446 fw_log(-1, "error loading `%s': %s", cf
->name
, strerror(errno
));
448 scan_add(&sc
, scan_file(fp
, cf
->name
, 0));
451 fw_log(-1, "... reload completed OK");
454 /*----- Startup and options parsing ---------------------------------------*/
456 /* --- Standard GNU help options --- */
458 static void version(FILE *fp
)
460 pquis(fp
, "$ version " VERSION
"\n");
463 static void usage(FILE *fp
)
465 pquis(fp
, "Usage: $ [-dql] [-f file] [config statements...]\n");
468 static void help(FILE *fp
)
474 An excessively full-featured port-forwarder, which subsumes large chunks\n\
475 of the functionality of inetd, netcat, and normal cat. Options available\n\
478 -h, --help Display this help message.\n\
479 -v, --version Display the program's version number.\n\
480 -u, --usage Display a terse usage summary.\n\
482 -G, --grammar Show a summary of the configuration language.\n\
483 -O, --options Show a summary of the source and target options.\n\
485 -f, --file=FILE Read configuration from a file.\n\
486 -q, --quiet Don't emit any logging information.\n\
487 -d, --daemon Fork into background after initializing.\n\
488 -l, --syslog Send log output to the system logger.\n\
489 -s, --setuid=USER Change uid to USER after initializing sources.\n\
490 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
492 Configuration may be supplied in one or more configuration files, or on\n\
493 the command line (or both). If no `-f' option is present, and no\n\
494 configuration is given on the command line, the standard input stream is\n\
497 Configuration is free-form. Comments begin with a `#' character and\n\
498 continue to the end of the line. Each command line argument is considered\n\
499 to be a separate line.\n\
501 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
502 For a summary of the various options, run `$ --options'.\n\
506 /* --- Other helpful options --- */
508 static void grammar(FILE *fp
)
515 file ::= empty | file stmt [`;']\n\
516 stmt ::= option-stmt | fw-stmt\n\
517 fw-stmt ::= `fw' source options [`to'|`->'] target options\n\
518 options ::= `{' option-seq `}'\n\
519 option-seq ::= empty | option-stmt [`;'] option-seq\n\
522 option-stmt ::= q-option\n\
523 q-option ::= option\n\
524 | prefix `.' q-option\n\
525 | prefix `{' option-seq `}'\n\
528 File source and target\n\
531 file ::= `file' [`.'] fspec [`,' fspec]\n\
532 fspec ::= fd-spec | name-spec | null-spec\n\
533 fd-spec ::= [[`:']`fd'[`:']] number|`stdin'|`stdout'\n\
534 name-spec ::= [[`:']`file'[`:']] file-name\n\
535 file-name ::= path-seq | [ path-seq ]\n\
536 path-seq ::= path-elt | path-seq path-elt\n\
537 path-elt ::= `/' | word\n\
538 null-spec ::= [`:']`null'[`:']\n\
540 Exec source and target\n\
543 exec ::= `exec' [`.'] cmd-spec\n\
544 cmd-spec ::= shell-cmd | [prog-name] `[' argv0 arg-seq `]'\n\
545 arg-seq ::= word | arg-seq word\n\
546 shell-cmd ::= word\n\
549 Socket source and target\n\
550 source ::= socket-source\n\
551 target ::= socket-target\n\
552 socket-source ::= [`socket'[`.']] [[`:']addr-type[`:']] source-addr\n\
553 socket-target ::= [`socket'[`.']] [[`:']addr-type[`:']] target-addr\n\
555 inet-source-addr ::= [port] port\n\
556 inet-target-addr ::= address [`:'] port\n\
557 address ::= addr-elt | address addr-elt\n\
558 addr-elt ::= `.' | word\n\
560 unix-source-addr ::= file-name\n\
561 unix-target-addr ::= file-name\n\
565 static void options(FILE *fp
)
571 File attributes (`fattr')\n\
572 prefix.fattr.mode [=] mode\n\
573 prefix.fattr.owner [=] user\n\
574 prefix.fattr.group [=] group\n\
577 file.create [=] yes|no\n\
578 file.open [=] no|truncate|append\n\
582 exec.logging [=] yes|no\n\
583 exec.dir [=] file-name\n\
584 exec.root [=] file-name\n\
585 exec.user [=] user\n\
586 exec.group [=] group\n\
587 exec.rlimit.limit[.hard|.soft] [=] value\n\
589 exec.env.unset var\n\
590 exec.env.[set] var [=] value\n\
593 socket.conn [=] number|unlimited|one-shot\n\
594 socket.listen [=] number\n\
595 socket.logging [=] yes|no\n\
597 socket.inet.[allow|deny] [from] address [/ address]\n\
599 socket.unix.fattr.*\n\
605 * Arguments: @int argc@ = number of command line arguments
606 * @char *argv[]@ = vector of argument strings
610 * Use: Simple port-forwarding server.
613 int main(int argc
, char *argv
[])
617 sig s_term
, s_quit
, s_int
, s_hup
;
621 conffile
*cf
, **cff
= &conffiles
;
628 /* --- Initialize things --- */
638 fattr_init(&fattr_global
);
643 /* --- Parse command line options --- */
646 static struct option opts
[] = {
648 /* --- Standard GNU help options --- */
650 { "help", 0, 0, 'h' },
651 { "version", 0, 0, 'v' },
652 { "usage", 0, 0, 'u' },
654 /* --- Other help options --- */
656 { "grammar", 0, 0, 'G' },
657 { "options", 0, 0, 'O' },
659 /* --- Other useful arguments --- */
661 { "file", OPTF_ARGREQ
, 0, 'f' },
662 { "fork", 0, 0, 'd' },
663 { "daemon", 0, 0, 'd' },
664 { "syslog", 0, 0, 'l' },
665 { "log", 0, 0, 'l' },
666 { "quiet", 0, 0, 'q' },
667 { "setuid", OPTF_ARGREQ
, 0, 's' },
668 { "uid", OPTF_ARGREQ
, 0, 's' },
669 { "setgid", OPTF_ARGREQ
, 0, 'g' },
670 { "gid", OPTF_ARGREQ
, 0, 'g' },
672 /* --- Magic terminator --- */
676 int i
= mdwopt(argc
, argv
, "+hvu GO f:dls:g:", opts
, 0, 0, 0);
702 if (strcmp(optarg
, "-") == 0)
703 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
706 if ((fp
= fopen(optarg
, "r")) == 0)
707 die(1, "couldn't open file `%s': %s", optarg
, strerror(errno
));
708 cf
= CREATE(conffile
);
712 scan_add(&sc
, scan_file(fp
, optarg
, 0));
726 if (isdigit((unsigned char )optarg
[0])) {
728 drop
= strtol(optarg
, &q
, 0);
730 die(1, "bad uid `%s'", optarg
);
732 struct passwd
*pw
= getpwnam(optarg
);
734 die(1, "unknown user `%s'", optarg
);
739 if (isdigit((unsigned char )optarg
[0])) {
741 dropg
= strtol(optarg
, &q
, 0);
743 die(1, "bad gid `%s'", optarg
);
745 struct group
*gr
= getgrnam(optarg
);
747 die(1, "unknown group `%s'", optarg
);
763 /* --- Deal with the remaining arguments --- */
766 scan_add(&sc
, scan_argv(argv
+ optind
));
769 else if (!isatty(STDIN_FILENO
))
770 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
772 moan("no configuration given and stdin is a terminal.");
773 moan("type `%s --help' for usage information.", QUIS
);
777 /* --- Parse the configuration now gathered --- */
781 /* --- Set up some signal handlers --- *
783 * Don't enable @SIGINT@ if the caller already disabled it.
789 sig_add(&s_term
, SIGTERM
, fw_tidy
, 0);
790 sig_add(&s_quit
, SIGQUIT
, fw_die
, 0);
791 sigaction(SIGINT
, 0, &sa
);
792 if (sa
.sa_handler
!= SIG_IGN
)
793 sig_add(&s_int
, SIGINT
, fw_tidy
, 0);
794 sig_add(&s_hup
, SIGHUP
, fw_reload
, 0);
797 /* --- Drop privileges --- */
799 #ifdef HAVE_SETGROUPS
800 if ((dropg
!= -1 && (setgid(dropg
) || setgroups(1, &dropg
))) ||
801 (drop
!= -1 && setuid(drop
)))
802 die(1, "couldn't drop privileges: %s", strerror(errno
));
804 if ((dropg
!= -1 && setgid(dropg
)) ||
805 (drop
!= -1 && setuid(drop
)))
806 die(1, "couldn't drop privileges: %s", strerror(errno
));
809 /* --- Fork into the background --- */
816 die(1, "couldn't fork: %s", strerror(errno
));
820 close(0); close(1); close(2);
831 openlog(QUIS
, 0, LOG_DAEMON
);
834 /* --- Let rip --- */
836 if (!(flags
& FW_SET
))
837 moan("nothing to do!");
838 signal(SIGPIPE
, SIG_IGN
);
843 if (!sel_select(sel
))
845 else if (errno
!= EINTR
&& errno
!= EAGAIN
) {
846 fw_log(-1, "error from select: %s", strerror(errno
));
849 fw_log(-1, "too many consecutive select errors: bailing out");
859 /*----- That's all, folks -------------------------------------------------*/