5a5db0f39151d335d6e11d6e98877857623392fd
3 * $Id: fw.c,v 1.15 2003/11/25 14:46:50 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.15 2003/11/25 14:46:50 mdw
33 * Update docco for new options.
35 * Revision 1.14 2003/01/24 20:12:40 mdw
36 * Correctly cast uid and gid sentinel values.
38 * Revision 1.13 2002/02/22 23:45:20 mdw
39 * Add option to change the listen(2) parameter. Receive `fw'-specific
42 * Revision 1.12 2002/01/13 14:49:17 mdw
43 * Track @dstr_vputf@ change.
45 * Revision 1.11 2001/02/03 20:33:26 mdw
46 * Fix flags to be unsigned.
48 * Revision 1.10 2001/02/03 20:30:03 mdw
49 * Support re-reading config files on SIGHUP.
51 * Revision 1.9 2001/01/20 11:55:17 mdw
52 * Handle select errors more robustly.
54 * Revision 1.8 2000/03/23 23:19:19 mdw
55 * Fix changed options in parser table.
57 * Revision 1.7 2000/03/23 00:37:33 mdw
58 * Add option to change user and group after initialization. Naughtily
59 * reassign short equivalents of --grammar and --options.
61 * Revision 1.6 1999/12/22 15:44:10 mdw
62 * Make syslog a separate option, and do it better.
64 * Revision 1.5 1999/10/22 22:47:50 mdw
65 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
67 * Revision 1.4 1999/10/10 16:46:12 mdw
68 * New resolver to initialize. Also, include options for grammar and
71 * Revision 1.3 1999/07/26 23:30:42 mdw
72 * Major reconstruction work for new design.
74 * Revision 1.2 1999/07/03 13:55:17 mdw
75 * Various changes. Add configuration grammar to help text. Change to
76 * root directory and open syslog when forking into background.
78 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
83 /*----- Header files ------------------------------------------------------*/
103 #include <mLib/bres.h>
104 #include <mLib/dstr.h>
105 #include <mLib/mdwopt.h>
106 #include <mLib/quis.h>
107 #include <mLib/report.h>
108 #include <mLib/sel.h>
109 #include <mLib/sig.h>
110 #include <mLib/sub.h>
122 /*----- Global variables --------------------------------------------------*/
124 sel_state
*sel
; /* Multiplexor for nonblocking I/O */
126 /*----- Static variables --------------------------------------------------*/
128 typedef struct conffile
{
129 struct conffile
*next
;
133 static unsigned flags
= 0; /* Global state flags */
134 static unsigned active
= 0; /* Number of active things */
135 static conffile
*conffiles
= 0; /* List of configuration files */
141 /*----- Configuration parsing ---------------------------------------------*/
145 * Arguments: @scanner *sc@ = pointer to scanner definition
149 * Use: Parses a configuration file from the scanner.
152 static source_ops
*sources
[] =
153 { &xsource_ops
, &fsource_ops
, &ssource_ops
, 0 };
154 static target_ops
*targets
[] =
155 { &xtarget_ops
, &ftarget_ops
, &starget_ops
, 0 };
157 void parse(scanner
*sc
)
162 if (sc
->t
== CTOK_EOF
)
164 if (sc
->t
!= CTOK_WORD
)
165 error(sc
, "parse error, keyword expected");
167 /* --- Handle a forwarding request --- */
169 if (strcmp(sc
->d
.buf
, "forward") == 0 ||
170 strcmp(sc
->d
.buf
, "fw") == 0 ||
171 strcmp(sc
->d
.buf
, "from") == 0) {
177 /* --- Read a source description --- */
182 /* --- Try to find a source type which understands --- */
185 for (sops
= sources
; *sops
; sops
++) {
186 if ((s
= (*sops
)->read(sc
)) != 0)
189 error(sc
, "unknown source name `%s'", sc
->d
.buf
);
191 /* --- Read any source-specific options --- */
196 while (sc
->t
== CTOK_WORD
) {
197 if (!s
->ops
->option
|| !s
->ops
->option(s
, sc
)) {
198 error(sc
, "unknown %s source option `%s'",
199 s
->ops
->name
, sc
->d
.buf
);
205 error(sc
, "parse error, missing `}'");
210 /* --- Read a destination description --- */
212 if (sc
->t
== CTOK_WORD
&& (strcmp(sc
->d
.buf
, "to") == 0 ||
213 strcmp(sc
->d
.buf
, "->") == 0))
219 /* --- Try to find a target which understands --- */
222 for (tops
= targets
; *tops
; tops
++) {
223 if ((t
= (*tops
)->read(sc
)) != 0)
226 error(sc
, "unknown target name `%s'", sc
->d
.buf
);
228 /* --- Read any target-specific options --- */
233 while (sc
->t
== CTOK_WORD
) {
234 if (!t
->ops
->option
|| !t
->ops
->option(t
, sc
)) {
235 error(sc
, "unknown %s target option `%s'",
236 t
->ops
->name
, sc
->d
.buf
);
242 error(sc
, "parse error, `}' expected");
247 /* --- Combine the source and target --- */
249 s
->ops
->attach(s
, sc
, t
);
252 /* --- Include configuration from a file --- *
254 * Slightly tricky. Scan the optional semicolon from the including
255 * stream, not the included one.
258 else if (strcmp(sc
->d
.buf
, "include") == 0) {
263 conf_name(sc
, '/', &d
);
264 if ((fp
= fopen(d
.buf
, "r")) == 0)
265 error(sc
, "can't include `%s': %s", d
.buf
, strerror(errno
));
269 scan_push(sc
, scan_file(fp
, d
.buf
, 0));
272 continue; /* Don't parse a trailing `;' */
275 /* --- Other configuration is handled elsewhere --- */
279 /* --- First try among the sources --- */
284 for (sops
= sources
; *sops
; sops
++) {
285 if ((*sops
)->option
&& (*sops
)->option(0, sc
))
290 /* --- Then try among the targets --- */
295 for (tops
= targets
; *tops
; tops
++) {
296 if ((*tops
)->option
&& (*tops
)->option(0, sc
))
301 /* --- Nobody wants the option --- */
303 error(sc
, "unknown global option or prefix `%s'", sc
->d
.buf
);
313 /*----- General utility functions -----------------------------------------*/
315 /* --- @fw_log@ --- *
317 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
318 * @const char *fmt@ = format string to fill in
319 * @...@ = other arguments
323 * Use: Logs a connection.
326 void fw_log(time_t t
, const char *fmt
, ...)
332 if (flags
& FW_QUIET
)
339 d
.len
+= strftime(d
.buf
, d
.sz
, "%Y-%m-%d %H:%M:%S ", tm
);
341 dstr_vputf(&d
, fmt
, &ap
);
343 if (flags
& FW_SYSLOG
)
344 syslog(LOG_NOTICE
, "%s", d
.buf
);
347 dstr_write(&d
, stderr
);
352 /* --- @fw_inc@, @fw_dec@ --- *
358 * Use: Increments or decrements the active thing count. `fw' won't
359 * quit while there are active things.
362 void fw_inc(void) { flags
|= FW_SET
; active
++; }
363 void fw_dec(void) { if (active
) active
--; }
365 /* --- @fw_exit@ --- *
371 * Use: Exits when appropriate.
374 static void fw_exit(void)
380 /* --- @fw_tidy@ --- *
382 * Arguments: @int n@ = signal number
383 * @void *p@ = an uninteresting argument
387 * Use: Handles various signals and causes a clean tidy-up.
390 static void fw_tidy(int n
, void *p
)
394 case SIGTERM
: sn
= "SIGTERM"; break;
395 case SIGINT
: sn
= "SIGINT"; break;
399 fw_log(-1, "closing down gracefully on %s", sn
);
403 /* --- @fw_die@ --- *
405 * Arguments: @int n@ = signal number
406 * @void *p@ = an uninteresting argument
410 * Use: Handles various signals and causes an abrupt shutdown.
413 static void fw_die(int n
, void *p
)
417 case SIGQUIT
: sn
= "SIGQUIT"; break;
421 fw_log(-1, "closing down abruptly on %s", sn
);
426 /* --- @fw_reload@ --- *
428 * Arguments: @int n@ = a signal number
429 * @void *p@ = an uninteresting argument
433 * Use: Handles a hangup signal by re-reading configuration files.
436 static void fw_reload(int n
, void *p
)
444 fw_log(-1, "no configuration files to reload: ignoring SIGHUP");
447 fw_log(-1, "reloading configuration files...");
450 for (cf
= conffiles
; cf
; cf
= cf
->next
) {
451 if ((fp
= fopen(cf
->name
, "r")) == 0)
452 fw_log(-1, "error loading `%s': %s", cf
->name
, strerror(errno
));
454 scan_add(&sc
, scan_file(fp
, cf
->name
, 0));
457 fw_log(-1, "... reload completed OK");
460 /*----- Startup and options parsing ---------------------------------------*/
462 /* --- Standard GNU help options --- */
464 static void version(FILE *fp
)
466 pquis(fp
, "$ version " VERSION
"\n");
469 static void usage(FILE *fp
)
471 pquis(fp
, "Usage: $ [-dql] [-f file] [config statements...]\n");
474 static void help(FILE *fp
)
480 An excessively full-featured port-forwarder, which subsumes large chunks\n\
481 of the functionality of inetd, netcat, and normal cat. Options available\n\
484 -h, --help Display this help message.\n\
485 -v, --version Display the program's version number.\n\
486 -u, --usage Display a terse usage summary.\n\
488 -G, --grammar Show a summary of the configuration language.\n\
489 -O, --options Show a summary of the source and target options.\n\
491 -f, --file=FILE Read configuration from a file.\n\
492 -q, --quiet Don't emit any logging information.\n\
493 -d, --daemon Fork into background after initializing.\n\
494 -l, --syslog Send log output to the system logger.\n\
495 -s, --setuid=USER Change uid to USER after initializing sources.\n\
496 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
498 Configuration may be supplied in one or more configuration files, or on\n\
499 the command line (or both). If no `-f' option is present, and no\n\
500 configuration is given on the command line, the standard input stream is\n\
503 Configuration is free-form. Comments begin with a `#' character and\n\
504 continue to the end of the line. Each command line argument is considered\n\
505 to be a separate line.\n\
507 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
508 For a summary of the various options, run `$ --options'.\n\
512 /* --- Other helpful options --- */
514 static void grammar(FILE *fp
)
521 FILE ::= EMPTY | FILE STMT [`;']\n\
522 STMT ::= OPTION-STMT | FW-STMT\n\
523 FW-STMT ::= `fw' SOURCE OPTIONS [`to'|`->'] TARGET OPTIONS\n\
524 OPTIONS ::= `{' OPTION-SEQ `}'\n\
525 OPTION-SEQ ::= EMPTY | OPTION-STMT [`;'] OPTION-SEQ\n\
528 OPTION-STMT ::= Q-OPTION\n\
529 Q-OPTION ::= OPTION\n\
530 | PREFIX `.' Q-OPTION\n\
531 | PREFIX `{' OPTION-SEQ `}'\n\
534 File source and target\n\
537 FILE ::= `file' [`.'] FSPEC [`,' FSPEC]\n\
538 FSPEC ::= FD-SPEC | NAME-SPEC | NULL-SPEC\n\
539 FD-SPEC ::= [[`:']`fd'[`:']] NUMBER|`stdin'|`stdout'\n\
540 NAME-SPEC ::= [[`:']`file'[`:']] FILE-NAME\n\
541 FILE-NAME ::= PATH-SEQ | [ PATH-SEQ ]\n\
542 PATH-SEQ ::= PATH-ELT | PATH-SEQ PATH-ELT\n\
543 PATH-ELT ::= `/' | WORD\n\
544 NULL-SPEC ::= [`:']`null'[`:']\n\
546 Exec source and target\n\
549 EXEC ::= `exec' [`.'] CMD-SPEC\n\
550 CMD-SPEC ::= SHELL-CMD | [PROG-NAME] `[' ARGV0 ARG-SEQ `]'\n\
551 ARG-SEQ ::= WORD | ARG-SEQ WORD\n\
552 SHELL-CMD ::= WORD\n\
555 Socket source and target\n\
556 SOURCE ::= SOCKET-SOURCE\n\
557 TARGET ::= SOCKET-TARGET\n\
558 SOCKET-SOURCE ::= [`socket'[`.']] [[`:']ADDR-TYPE[`:']] SOURCE-ADDR\n\
559 SOCKET-TARGET ::= [`socket'[`.']] [[`:']ADDR-TYPE[`:']] TARGET-ADDR\n\
561 INET-SOURCE-ADDR ::= [`port'] PORT\n\
562 INET-TARGET-ADDR ::= ADDRESS [`:'] PORT\n\
563 ADDRESS ::= ADDR-ELT | ADDRESS ADDR-ELT\n\
564 ADDR-ELT ::= `.' | WORD\n\
566 UNIX-SOURCE-ADDR ::= FILE-NAME\n\
567 UNIX-TARGET-ADDR ::= FILE-NAME\n\
571 static void options(FILE *fp
)
577 File attributes (`fattr')\n\
578 prefix.FATTR.MODE [=] MODE\n\
579 prefix.FATTR.OWNER [=] USER\n\
580 prefix.FATTR.GROUP [=] GROUP\n\
583 file.create [=] yes|no\n\
584 file.open [=] no|truncate|append\n\
588 exec.logging [=] yes|no\n\
589 exec.dir [=] FILE-NAME\n\
590 exec.root [=] FILE-NAME\n\
591 exec.user [=] USER\n\
592 exec.group [=] GROUP\n\
593 exec.rlimit.LIMIT[.hard|.soft] [=] VALUE\n\
595 exec.env.unset VAR\n\
596 exec.env.[set] VAR [=] VALUE\n\
599 socket.conn [=] NUMBER|unlimited|one-shot\n\
600 socket.listen [=] NUMBER\n\
601 socket.logging [=] yes|no\n\
603 socket.inet.source.[allow|deny] [host] ADDR [/ ADDR]\n\
604 socket.inet.source.[allow|deny] priv-port\n\
605 socket.inet.source.addr [=] any|ADDR\n\
606 socket.inet.dest.addr [=] any|ADDR\n\
608 socket.unix.fattr.*\n\
614 * Arguments: @int argc@ = number of command line arguments
615 * @char *argv[]@ = vector of argument strings
619 * Use: Simple port-forwarding server.
622 int main(int argc
, char *argv
[])
626 sig s_term
, s_quit
, s_int
, s_hup
;
630 conffile
*cf
, **cff
= &conffiles
;
637 /* --- Initialize things --- */
647 fattr_init(&fattr_global
);
652 /* --- Parse command line options --- */
655 static struct option opts
[] = {
657 /* --- Standard GNU help options --- */
659 { "help", 0, 0, 'h' },
660 { "version", 0, 0, 'v' },
661 { "usage", 0, 0, 'u' },
663 /* --- Other help options --- */
665 { "grammar", 0, 0, 'G' },
666 { "options", 0, 0, 'O' },
668 /* --- Other useful arguments --- */
670 { "file", OPTF_ARGREQ
, 0, 'f' },
671 { "fork", 0, 0, 'd' },
672 { "daemon", 0, 0, 'd' },
673 { "syslog", 0, 0, 'l' },
674 { "log", 0, 0, 'l' },
675 { "quiet", 0, 0, 'q' },
676 { "setuid", OPTF_ARGREQ
, 0, 's' },
677 { "uid", OPTF_ARGREQ
, 0, 's' },
678 { "setgid", OPTF_ARGREQ
, 0, 'g' },
679 { "gid", OPTF_ARGREQ
, 0, 'g' },
681 /* --- Magic terminator --- */
685 int i
= mdwopt(argc
, argv
, "+hvu GO f:dls:g:", opts
, 0, 0, 0);
711 if (strcmp(optarg
, "-") == 0)
712 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
715 if ((fp
= fopen(optarg
, "r")) == 0)
716 die(1, "couldn't open file `%s': %s", optarg
, strerror(errno
));
717 cf
= CREATE(conffile
);
721 scan_add(&sc
, scan_file(fp
, optarg
, 0));
735 if (isdigit((unsigned char )optarg
[0])) {
737 drop
= strtol(optarg
, &q
, 0);
739 die(1, "bad uid `%s'", optarg
);
741 struct passwd
*pw
= getpwnam(optarg
);
743 die(1, "unknown user `%s'", optarg
);
748 if (isdigit((unsigned char )optarg
[0])) {
750 dropg
= strtol(optarg
, &q
, 0);
752 die(1, "bad gid `%s'", optarg
);
754 struct group
*gr
= getgrnam(optarg
);
756 die(1, "unknown group `%s'", optarg
);
772 /* --- Deal with the remaining arguments --- */
775 scan_add(&sc
, scan_argv(argv
+ optind
));
778 else if (!isatty(STDIN_FILENO
))
779 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
781 moan("no configuration given and stdin is a terminal.");
782 moan("type `%s --help' for usage information.", QUIS
);
786 /* --- Parse the configuration now gathered --- */
790 /* --- Set up some signal handlers --- *
792 * Don't enable @SIGINT@ if the caller already disabled it.
798 sig_add(&s_term
, SIGTERM
, fw_tidy
, 0);
799 sig_add(&s_quit
, SIGQUIT
, fw_die
, 0);
800 sigaction(SIGINT
, 0, &sa
);
801 if (sa
.sa_handler
!= SIG_IGN
)
802 sig_add(&s_int
, SIGINT
, fw_tidy
, 0);
803 sig_add(&s_hup
, SIGHUP
, fw_reload
, 0);
806 /* --- Drop privileges --- */
808 #ifdef HAVE_SETGROUPS
809 if ((dropg
!= (gid_t
)-1 && (setgid(dropg
) || setgroups(1, &dropg
))) ||
810 (drop
!= (uid_t
)-1 && setuid(drop
)))
811 die(1, "couldn't drop privileges: %s", strerror(errno
));
813 if ((dropg
!= (gid_t
)-1 && setgid(dropg
)) ||
814 (drop
!= (uid_t
)-1 && setuid(drop
)))
815 die(1, "couldn't drop privileges: %s", strerror(errno
));
818 /* --- Fork into the background --- */
825 die(1, "couldn't fork: %s", strerror(errno
));
829 close(0); close(1); close(2);
840 openlog(QUIS
, 0, LOG_DAEMON
);
843 /* --- Let rip --- */
845 if (!(flags
& FW_SET
))
846 moan("nothing to do!");
847 signal(SIGPIPE
, SIG_IGN
);
852 if (!sel_select(sel
))
854 else if (errno
!= EINTR
&& errno
!= EAGAIN
) {
855 fw_log(-1, "error from select: %s", strerror(errno
));
858 fw_log(-1, "too many consecutive select errors: bailing out");
868 /*----- That's all, folks -------------------------------------------------*/