3 * $Id: fw.c,v 1.12 2002/01/13 14:49:17 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.12 2002/01/13 14:49:17 mdw
33 * Track @dstr_vputf@ change.
35 * Revision 1.11 2001/02/03 20:33:26 mdw
36 * Fix flags to be unsigned.
38 * Revision 1.10 2001/02/03 20:30:03 mdw
39 * Support re-reading config files on SIGHUP.
41 * Revision 1.9 2001/01/20 11:55:17 mdw
42 * Handle select errors more robustly.
44 * Revision 1.8 2000/03/23 23:19:19 mdw
45 * Fix changed options in parser table.
47 * Revision 1.7 2000/03/23 00:37:33 mdw
48 * Add option to change user and group after initialization. Naughtily
49 * reassign short equivalents of --grammar and --options.
51 * Revision 1.6 1999/12/22 15:44:10 mdw
52 * Make syslog a separate option, and do it better.
54 * Revision 1.5 1999/10/22 22:47:50 mdw
55 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
57 * Revision 1.4 1999/10/10 16:46:12 mdw
58 * New resolver to initialize. Also, include options for grammar and
61 * Revision 1.3 1999/07/26 23:30:42 mdw
62 * Major reconstruction work for new design.
64 * Revision 1.2 1999/07/03 13:55:17 mdw
65 * Various changes. Add configuration grammar to help text. Change to
66 * root directory and open syslog when forking into background.
68 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
73 /*----- Header files ------------------------------------------------------*/
93 #include <mLib/bres.h>
94 #include <mLib/dstr.h>
95 #include <mLib/mdwopt.h>
96 #include <mLib/quis.h>
97 #include <mLib/report.h>
100 #include <mLib/sub.h>
110 /*----- Global variables --------------------------------------------------*/
112 sel_state
*sel
; /* Multiplexor for nonblocking I/O */
114 /*----- Static variables --------------------------------------------------*/
116 typedef struct conffile
{
117 struct conffile
*next
;
121 static unsigned flags
= 0; /* Global state flags */
122 static unsigned active
= 0; /* Number of active things */
123 static conffile
*conffiles
= 0; /* List of configuration files */
129 /*----- Main code ---------------------------------------------------------*/
131 /* --- @fw_log@ --- *
133 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
134 * @const char *fmt@ = format string to fill in
135 * @...@ = other arguments
139 * Use: Logs a connection.
142 void fw_log(time_t t
, const char *fmt
, ...)
148 if (flags
& FW_QUIET
)
155 d
.len
+= strftime(d
.buf
, d
.sz
, "%Y-%m-%d %H:%M:%S ", tm
);
157 dstr_vputf(&d
, fmt
, &ap
);
159 if (flags
& FW_SYSLOG
)
160 syslog(LOG_NOTICE
, "%s", d
.buf
);
163 dstr_write(&d
, stderr
);
168 /* --- @fw_inc@, @fw_dec@ --- *
174 * Use: Increments or decrements the active thing count. `fw' won't
175 * quit while there are active things.
178 void fw_inc(void) { flags
|= FW_SET
; active
++; }
179 void fw_dec(void) { if (active
) active
--; }
181 /* --- @fw_exit@ --- *
187 * Use: Exits when appropriate.
190 static void fw_exit(void)
196 /* --- @fw_tidy@ --- *
198 * Arguments: @int n@ = signal number
199 * @void *p@ = an uninteresting argument
203 * Use: Handles various signals and causes a clean tidy-up.
206 static void fw_tidy(int n
, void *p
)
210 case SIGTERM
: sn
= "SIGTERM"; break;
211 case SIGINT
: sn
= "SIGINT"; break;
215 fw_log(-1, "closing down gracefully on %s", sn
);
219 /* --- @fw_die@ --- *
221 * Arguments: @int n@ = signal number
222 * @void *p@ = an uninteresting argument
226 * Use: Handles various signals and causes an abrupt shutdown.
229 static void fw_die(int n
, void *p
)
233 case SIGQUIT
: sn
= "SIGQUIT"; break;
237 fw_log(-1, "closing down abruptly on %s", sn
);
242 /* --- @fw_reload@ --- *
244 * Arguments: @int n@ = a signal number
245 * @void *p@ = an uninteresting argument
249 * Use: Handles a hangup signal by re-reading configuration files.
252 static void fw_reload(int n
, void *p
)
260 fw_log(-1, "no configuration files to reload: ignoring SIGHUP");
263 fw_log(-1, "reloading configuration files...");
266 for (cf
= conffiles
; cf
; cf
= cf
->next
) {
267 if ((fp
= fopen(cf
->name
, "r")) == 0)
268 fw_log(-1, "error loading `%s': %s", cf
->name
, strerror(errno
));
270 scan_add(&sc
, scan_file(fp
, cf
->name
, 0));
273 fw_log(-1, "... reload completed OK");
276 /* --- Standard GNU help options --- */
278 static void version(FILE *fp
)
280 pquis(fp
, "$ version " VERSION
"\n");
283 static void usage(FILE *fp
)
285 pquis(fp
, "Usage: $ [-dql] [-f file] [config statements...]\n");
288 static void help(FILE *fp
)
294 An excessively full-featured port-forwarder, which subsumes large chunks\n\
295 of the functionality of inetd, netcat, and normal cat. Options available\n\
298 -h, --help Display this help message.\n\
299 -v, --version Display the program's version number.\n\
300 -u, --usage Display a terse usage summary.\n\
302 -G, --grammar Show a summary of the configuration language.\n\
303 -O, --options Show a summary of the source and target options.\n\
305 -f, --file=FILE Read configuration from a file.\n\
306 -q, --quiet Don't emit any logging information.\n\
307 -d, --daemon Fork into background after initializing.\n\
308 -l, --syslog Send log output to the system logger.\n\
309 -s, --setuid=USER Change uid to USER after initializing sources.\n\
310 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
312 Configuration may be supplied in one or more configuration files, or on\n\
313 the command line (or both). If no `-f' option is present, and no\n\
314 configuration is given on the command line, the standard input stream is\n\
317 Configuration is free-form. Comments begin with a `#' character and\n\
318 continue to the end of the line. Each command line argument is considered\n\
319 to be a separate line.\n\
321 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
322 For a summary of the various options, run `$ --options'.\n\
326 /* --- Other helpful options --- */
328 static void grammar(FILE *fp
)
335 file ::= empty | file stmt [`;']\n\
336 stmt ::= option-stmt | fw-stmt\n\
337 fw-stmt ::= `fw' source options [`to'|`->'] target options\n\
338 options ::= `{' option-seq `}'\n\
339 option-seq ::= empty | option-stmt [`;'] option-seq\n\
342 option-stmt ::= q-option\n\
343 q-option ::= option\n\
344 | prefix `.' q-option\n\
345 | prefix `{' option-seq `}'\n\
348 File source and target\n\
351 file ::= `file' [`.'] fspec [`,' fspec]\n\
352 fspec ::= fd-spec | name-spec | null-spec\n\
353 fd-spec ::= [[`:']`fd'[`:']] number|`stdin'|`stdout'\n\
354 name-spec ::= [[`:']`file'[`:']] file-name\n\
355 file-name ::= path-seq | [ path-seq ]\n\
356 path-seq ::= path-elt | path-seq path-elt\n\
357 path-elt ::= `/' | word\n\
358 null-spec ::= [`:']`null'[`:']\n\
360 Exec source and target\n\
363 exec ::= `exec' [`.'] cmd-spec\n\
364 cmd-spec ::= shell-cmd | [prog-name] `[' argv0 arg-seq `]'\n\
365 arg-seq ::= word | arg-seq word\n\
366 shell-cmd ::= word\n\
369 Socket source and target\n\
370 source ::= socket-source\n\
371 target ::= socket-target\n\
372 socket-source ::= [`socket'[`.']] [[`:']addr-type[`:']] source-addr\n\
373 socket-target ::= [`socket'[`.']] [[`:']addr-type[`:']] target-addr\n\
375 inet-source-addr ::= [port] port\n\
376 inet-target-addr ::= address [`:'] port\n\
377 address ::= addr-elt | address addr-elt\n\
378 addr-elt ::= `.' | word\n\
380 unix-source-addr ::= file-name\n\
381 unix-target-addr ::= file-name\n\
385 static void options(FILE *fp
)
391 File attributes (`fattr')\n\
392 prefix.fattr.mode [=] mode\n\
393 prefix.fattr.owner [=] user\n\
394 prefix.fattr.group [=] group\n\
397 file.create [=] yes|no\n\
398 file.open [=] no|truncate|append\n\
402 exec.logging [=] yes|no\n\
403 exec.dir [=] file-name\n\
404 exec.root [=] file-name\n\
405 exec.user [=] user\n\
406 exec.group [=] group\n\
407 exec.rlimit.limit[.hard|.soft] [=] value\n\
409 exec.env.unset var\n\
410 exec.env.[set] var [=] value\n\
413 socket.conn [=] number|unlimited|one-shot\n\
414 socket.logging [=] yes|no\n\
415 socket.inet.[allow|deny] [from] address [/ address]\n\
416 socket.unix.fattr.*\n\
422 * Arguments: @int argc@ = number of command line arguments
423 * @char *argv[]@ = vector of argument strings
427 * Use: Simple port-forwarding server.
430 int main(int argc
, char *argv
[])
434 sig s_term
, s_quit
, s_int
, s_hup
;
438 conffile
*cf
, **cff
= &conffiles
;
445 /* --- Initialize things --- */
455 fattr_init(&fattr_global
);
460 /* --- Parse command line options --- */
463 static struct option opts
[] = {
465 /* --- Standard GNU help options --- */
467 { "help", 0, 0, 'h' },
468 { "version", 0, 0, 'v' },
469 { "usage", 0, 0, 'u' },
471 /* --- Other help options --- */
473 { "grammar", 0, 0, 'G' },
474 { "options", 0, 0, 'O' },
476 /* --- Other useful arguments --- */
478 { "file", OPTF_ARGREQ
, 0, 'f' },
479 { "fork", 0, 0, 'd' },
480 { "daemon", 0, 0, 'd' },
481 { "syslog", 0, 0, 'l' },
482 { "log", 0, 0, 'l' },
483 { "quiet", 0, 0, 'q' },
484 { "setuid", OPTF_ARGREQ
, 0, 's' },
485 { "uid", OPTF_ARGREQ
, 0, 's' },
486 { "setgid", OPTF_ARGREQ
, 0, 'g' },
487 { "gid", OPTF_ARGREQ
, 0, 'g' },
489 /* --- Magic terminator --- */
493 int i
= mdwopt(argc
, argv
, "+hvu GO f:dls:g:", opts
, 0, 0, 0);
519 if (strcmp(optarg
, "-") == 0)
520 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
523 if ((fp
= fopen(optarg
, "r")) == 0)
524 die(1, "couldn't open file `%s': %s", optarg
, strerror(errno
));
525 cf
= CREATE(conffile
);
529 scan_add(&sc
, scan_file(fp
, optarg
, 0));
543 if (isdigit((unsigned char )optarg
[0])) {
545 drop
= strtol(optarg
, &q
, 0);
547 die(1, "bad uid `%s'", optarg
);
549 struct passwd
*pw
= getpwnam(optarg
);
551 die(1, "unknown user `%s'", optarg
);
556 if (isdigit((unsigned char )optarg
[0])) {
558 dropg
= strtol(optarg
, &q
, 0);
560 die(1, "bad gid `%s'", optarg
);
562 struct group
*gr
= getgrnam(optarg
);
564 die(1, "unknown group `%s'", optarg
);
580 /* --- Deal with the remaining arguments --- */
583 scan_add(&sc
, scan_argv(argv
+ optind
));
586 else if (!isatty(STDIN_FILENO
))
587 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
589 moan("no configuration given and stdin is a terminal.");
590 moan("type `%s --help' for usage information.", QUIS
);
594 /* --- Parse the configuration now gathered --- */
598 /* --- Set up some signal handlers --- *
600 * Don't enable @SIGINT@ if the caller already disabled it.
606 sig_add(&s_term
, SIGTERM
, fw_tidy
, 0);
607 sig_add(&s_quit
, SIGQUIT
, fw_die
, 0);
608 sigaction(SIGINT
, 0, &sa
);
609 if (sa
.sa_handler
!= SIG_IGN
)
610 sig_add(&s_int
, SIGINT
, fw_tidy
, 0);
611 sig_add(&s_hup
, SIGHUP
, fw_reload
, 0);
614 /* --- Drop privileges --- */
616 #ifdef HAVE_SETGROUPS
617 if ((dropg
!= -1 && (setgid(dropg
) || setgroups(1, &dropg
))) ||
618 (drop
!= -1 && setuid(drop
)))
619 die(1, "couldn't drop privileges: %s", strerror(errno
));
621 if ((dropg
!= -1 && setgid(dropg
)) ||
622 (drop
!= -1 && setuid(drop
)))
623 die(1, "couldn't drop privileges: %s", strerror(errno
));
626 /* --- Fork into the background --- */
633 die(1, "couldn't fork: %s", strerror(errno
));
637 close(0); close(1); close(2);
648 openlog(QUIS
, 0, LOG_DAEMON
);
651 /* --- Let rip --- */
653 if (!(flags
& FW_SET
))
654 moan("nothing to do!");
655 signal(SIGPIPE
, SIG_IGN
);
660 if (!sel_select(sel
))
662 else if (errno
!= EINTR
&& errno
!= EAGAIN
) {
663 fw_log(-1, "error from select: %s", strerror(errno
));
666 fw_log(-1, "too many consecutive select errors: bailing out");
676 /*----- That's all, folks -------------------------------------------------*/