3 * $Id: fw.c,v 1.10 2001/02/03 20:30:03 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.10 2001/02/03 20:30:03 mdw
33 * Support re-reading config files on SIGHUP.
35 * Revision 1.9 2001/01/20 11:55:17 mdw
36 * Handle select errors more robustly.
38 * Revision 1.8 2000/03/23 23:19:19 mdw
39 * Fix changed options in parser table.
41 * Revision 1.7 2000/03/23 00:37:33 mdw
42 * Add option to change user and group after initialization. Naughtily
43 * reassign short equivalents of --grammar and --options.
45 * Revision 1.6 1999/12/22 15:44:10 mdw
46 * Make syslog a separate option, and do it better.
48 * Revision 1.5 1999/10/22 22:47:50 mdw
49 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
51 * Revision 1.4 1999/10/10 16:46:12 mdw
52 * New resolver to initialize. Also, include options for grammar and
55 * Revision 1.3 1999/07/26 23:30:42 mdw
56 * Major reconstruction work for new design.
58 * Revision 1.2 1999/07/03 13:55:17 mdw
59 * Various changes. Add configuration grammar to help text. Change to
60 * root directory and open syslog when forking into background.
62 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
67 /*----- Header files ------------------------------------------------------*/
87 #include <mLib/bres.h>
88 #include <mLib/dstr.h>
89 #include <mLib/mdwopt.h>
90 #include <mLib/quis.h>
91 #include <mLib/report.h>
104 /*----- Global variables --------------------------------------------------*/
106 sel_state
*sel
; /* Multiplexor for nonblocking I/O */
108 /*----- Static variables --------------------------------------------------*/
110 typedef struct conffile
{
111 struct conffile
*next
;
115 static unsigned flags
= 0; /* Global state flags */
116 static unsigned active
= 0; /* Number of active things */
117 static conffile
*conffiles
= 0; /* List of configuration files */
123 /*----- Main code ---------------------------------------------------------*/
125 /* --- @fw_log@ --- *
127 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
128 * @const char *fmt@ = format string to fill in
129 * @...@ = other arguments
133 * Use: Logs a connection.
136 void fw_log(time_t t
, const char *fmt
, ...)
142 if (flags
& FW_QUIET
)
149 d
.len
+= strftime(d
.buf
, d
.sz
, "%Y-%m-%d %H:%M:%S ", tm
);
151 dstr_vputf(&d
, fmt
, ap
);
153 if (flags
& FW_SYSLOG
)
154 syslog(LOG_NOTICE
, "%s", d
.buf
);
157 dstr_write(&d
, stderr
);
162 /* --- @fw_inc@, @fw_dec@ --- *
168 * Use: Increments or decrements the active thing count. `fw' won't
169 * quit while there are active things.
172 void fw_inc(void) { flags
|= FW_SET
; active
++; }
173 void fw_dec(void) { if (active
) active
--; }
175 /* --- @fw_exit@ --- *
181 * Use: Exits when appropriate.
184 static void fw_exit(void)
190 /* --- @fw_tidy@ --- *
192 * Arguments: @int n@ = signal number
193 * @void *p@ = an uninteresting argument
197 * Use: Handles various signals and causes a clean tidy-up.
200 static void fw_tidy(int n
, void *p
)
204 case SIGTERM
: sn
= "SIGTERM"; break;
205 case SIGINT
: sn
= "SIGINT"; break;
209 fw_log(-1, "closing down gracefully on %s", sn
);
213 /* --- @fw_die@ --- *
215 * Arguments: @int n@ = signal number
216 * @void *p@ = an uninteresting argument
220 * Use: Handles various signals and causes an abrupt shutdown.
223 static void fw_die(int n
, void *p
)
227 case SIGQUIT
: sn
= "SIGQUIT"; break;
231 fw_log(-1, "closing down abruptly on %s", sn
);
236 /* --- @fw_reload@ --- *
238 * Arguments: @int n@ = a signal number
239 * @void *p@ = an uninteresting argument
243 * Use: Handles a hangup signal by re-reading configuration files.
246 static void fw_reload(int n
, void *p
)
254 fw_log(-1, "no configuration files to reload: ignoring SIGHUP");
257 fw_log(-1, "reloading configuration files...");
260 for (cf
= conffiles
; cf
; cf
= cf
->next
) {
261 if ((fp
= fopen(cf
->name
, "r")) == 0)
262 fw_log(-1, "error loading `%s': %s", cf
->name
, strerror(errno
));
264 scan_add(&sc
, scan_file(fp
, cf
->name
, 0));
267 fw_log(-1, "... reload completed OK");
270 /* --- Standard GNU help options --- */
272 static void version(FILE *fp
)
274 pquis(fp
, "$ version " VERSION
"\n");
277 static void usage(FILE *fp
)
279 pquis(fp
, "Usage: $ [-dql] [-f file] [config statements...]\n");
282 static void help(FILE *fp
)
288 An excessively full-featured port-forwarder, which subsumes large chunks\n\
289 of the functionality of inetd, netcat, and normal cat. Options available\n\
292 -h, --help Display this help message.\n\
293 -v, --version Display the program's version number.\n\
294 -u, --usage Display a terse usage summary.\n\
296 -G, --grammar Show a summary of the configuration language.\n\
297 -O, --options Show a summary of the source and target options.\n\
299 -f, --file=FILE Read configuration from a file.\n\
300 -q, --quiet Don't emit any logging information.\n\
301 -d, --daemon Fork into background after initializing.\n\
302 -l, --syslog Send log output to the system logger.\n\
303 -s, --setuid=USER Change uid to USER after initializing sources.\n\
304 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
306 Configuration may be supplied in one or more configuration files, or on\n\
307 the command line (or both). If no `-f' option is present, and no\n\
308 configuration is given on the command line, the standard input stream is\n\
311 Configuration is free-form. Comments begin with a `#' character and\n\
312 continue to the end of the line. Each command line argument is considered\n\
313 to be a separate line.\n\
315 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
316 For a summary of the various options, run `$ --options'.\n\
320 /* --- Other helpful options --- */
322 static void grammar(FILE *fp
)
329 file ::= empty | file stmt [`;']\n\
330 stmt ::= option-stmt | fw-stmt\n\
331 fw-stmt ::= `fw' source options [`to'|`->'] target options\n\
332 options ::= `{' option-seq `}'\n\
333 option-seq ::= empty | option-stmt [`;'] option-seq\n\
336 option-stmt ::= q-option\n\
337 q-option ::= option\n\
338 | prefix `.' q-option\n\
339 | prefix `{' option-seq `}'\n\
342 File source and target\n\
345 file ::= `file' [`.'] fspec [`,' fspec]\n\
346 fspec ::= fd-spec | name-spec | null-spec\n\
347 fd-spec ::= [[`:']`fd'[`:']] number|`stdin'|`stdout'\n\
348 name-spec ::= [[`:']`file'[`:']] file-name\n\
349 file-name ::= path-seq | [ path-seq ]\n\
350 path-seq ::= path-elt | path-seq path-elt\n\
351 path-elt ::= `/' | word\n\
352 null-spec ::= [`:']`null'[`:']\n\
354 Exec source and target\n\
357 exec ::= `exec' [`.'] cmd-spec\n\
358 cmd-spec ::= shell-cmd | [prog-name] `[' argv0 arg-seq `]'\n\
359 arg-seq ::= word | arg-seq word\n\
360 shell-cmd ::= word\n\
363 Socket source and target\n\
364 source ::= socket-source\n\
365 target ::= socket-target\n\
366 socket-source ::= [`socket'[`.']] [[`:']addr-type[`:']] source-addr\n\
367 socket-target ::= [`socket'[`.']] [[`:']addr-type[`:']] target-addr\n\
369 inet-source-addr ::= [port] port\n\
370 inet-target-addr ::= address [`:'] port\n\
371 address ::= addr-elt | address addr-elt\n\
372 addr-elt ::= `.' | word\n\
374 unix-source-addr ::= file-name\n\
375 unix-target-addr ::= file-name\n\
379 static void options(FILE *fp
)
385 File attributes (`fattr')\n\
386 prefix.fattr.mode [=] mode\n\
387 prefix.fattr.owner [=] user\n\
388 prefix.fattr.group [=] group\n\
391 file.create [=] yes|no\n\
392 file.open [=] no|truncate|append\n\
396 exec.logging [=] yes|no\n\
397 exec.dir [=] file-name\n\
398 exec.root [=] file-name\n\
399 exec.user [=] user\n\
400 exec.group [=] group\n\
401 exec.rlimit.limit[.hard|.soft] [=] value\n\
403 exec.env.unset var\n\
404 exec.env.[set] var [=] value\n\
407 socket.conn [=] number|unlimited|one-shot\n\
408 socket.logging [=] yes|no\n\
409 socket.inet.[allow|deny] [from] address [/ address]\n\
410 socket.unix.fattr.*\n\
416 * Arguments: @int argc@ = number of command line arguments
417 * @char *argv[]@ = vector of argument strings
421 * Use: Simple port-forwarding server.
424 int main(int argc
, char *argv
[])
428 sig s_term
, s_quit
, s_int
, s_hup
;
432 conffile
*cf
, **cff
= &conffiles
;
439 /* --- Initialize things --- */
449 fattr_init(&fattr_global
);
454 /* --- Parse command line options --- */
457 static struct option opts
[] = {
459 /* --- Standard GNU help options --- */
461 { "help", 0, 0, 'h' },
462 { "version", 0, 0, 'v' },
463 { "usage", 0, 0, 'u' },
465 /* --- Other help options --- */
467 { "grammar", 0, 0, 'G' },
468 { "options", 0, 0, 'O' },
470 /* --- Other useful arguments --- */
472 { "file", OPTF_ARGREQ
, 0, 'f' },
473 { "fork", 0, 0, 'd' },
474 { "daemon", 0, 0, 'd' },
475 { "syslog", 0, 0, 'l' },
476 { "log", 0, 0, 'l' },
477 { "quiet", 0, 0, 'q' },
478 { "setuid", OPTF_ARGREQ
, 0, 's' },
479 { "uid", OPTF_ARGREQ
, 0, 's' },
480 { "setgid", OPTF_ARGREQ
, 0, 'g' },
481 { "gid", OPTF_ARGREQ
, 0, 'g' },
483 /* --- Magic terminator --- */
487 int i
= mdwopt(argc
, argv
, "+hvu GO f:dls:g:", opts
, 0, 0, 0);
513 if (strcmp(optarg
, "-") == 0)
514 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
517 if ((fp
= fopen(optarg
, "r")) == 0)
518 die(1, "couldn't open file `%s': %s", optarg
, strerror(errno
));
519 cf
= CREATE(conffile
);
523 scan_add(&sc
, scan_file(fp
, optarg
, 0));
537 if (isdigit((unsigned char )optarg
[0])) {
539 drop
= strtol(optarg
, &q
, 0);
541 die(1, "bad uid `%s'", optarg
);
543 struct passwd
*pw
= getpwnam(optarg
);
545 die(1, "unknown user `%s'", optarg
);
550 if (isdigit((unsigned char )optarg
[0])) {
552 dropg
= strtol(optarg
, &q
, 0);
554 die(1, "bad gid `%s'", optarg
);
556 struct group
*gr
= getgrnam(optarg
);
558 die(1, "unknown group `%s'", optarg
);
574 /* --- Deal with the remaining arguments --- */
577 scan_add(&sc
, scan_argv(argv
+ optind
));
580 else if (!isatty(STDIN_FILENO
))
581 scan_add(&sc
, scan_file(stdin
, "<stdin>", SCF_NOCLOSE
));
583 moan("no configuration given and stdin is a terminal.");
584 moan("type `%s --help' for usage information.", QUIS
);
588 /* --- Parse the configuration now gathered --- */
592 /* --- Set up some signal handlers --- *
594 * Don't enable @SIGINT@ if the caller already disabled it.
600 sig_add(&s_term
, SIGTERM
, fw_tidy
, 0);
601 sig_add(&s_quit
, SIGQUIT
, fw_die
, 0);
602 sigaction(SIGINT
, 0, &sa
);
603 if (sa
.sa_handler
!= SIG_IGN
)
604 sig_add(&s_int
, SIGINT
, fw_tidy
, 0);
605 sig_add(&s_hup
, SIGHUP
, fw_reload
, 0);
608 /* --- Drop privileges --- */
610 #ifdef HAVE_SETGROUPS
611 if ((dropg
!= -1 && (setgid(dropg
) || setgroups(1, &dropg
))) ||
612 (drop
!= -1 && setuid(drop
)))
613 die(1, "couldn't drop privileges: %s", strerror(errno
));
615 if ((dropg
!= -1 && setgid(dropg
)) ||
616 (drop
!= -1 && setuid(drop
)))
617 die(1, "couldn't drop privileges: %s", strerror(errno
));
620 /* --- Fork into the background --- */
627 die(1, "couldn't fork: %s", strerror(errno
));
631 close(0); close(1); close(2);
642 openlog(QUIS
, 0, LOG_DAEMON
);
645 /* --- Let rip --- */
647 if (!(flags
& FW_SET
))
648 moan("nothing to do!");
649 signal(SIGPIPE
, SIG_IGN
);
654 if (!sel_select(sel
))
656 else if (errno
!= EINTR
&& errno
!= EAGAIN
) {
657 fw_log(-1, "error from select: %s", strerror(errno
));
660 fw_log(-1, "too many consecutive select errors: bailing out");
670 /*----- That's all, folks -------------------------------------------------*/