3 * $Id: fw.c,v 1.7 2000/03/23 00:37:33 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.7 2000/03/23 00:37:33 mdw
33 * Add option to change user and group after initialization. Naughtily
34 * reassign short equivalents of --grammar and --options.
36 * Revision 1.6 1999/12/22 15:44:10 mdw
37 * Make syslog a separate option, and do it better.
39 * Revision 1.5 1999/10/22 22:47:50 mdw
40 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
42 * Revision 1.4 1999/10/10 16:46:12 mdw
43 * New resolver to initialize. Also, include options for grammar and
46 * Revision 1.3 1999/07/26 23:30:42 mdw
47 * Major reconstruction work for new design.
49 * Revision 1.2 1999/07/03 13:55:17 mdw
50 * Various changes. Add configuration grammar to help text. Change to
51 * root directory and open syslog when forking into background.
53 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
58 /*----- Header files ------------------------------------------------------*/
77 #include <mLib/bres.h>
78 #include <mLib/dstr.h>
79 #include <mLib/mdwopt.h>
80 #include <mLib/quis.h>
81 #include <mLib/report.h>
94 /*----- Global variables --------------------------------------------------*/
96 sel_state *sel; /* Multiplexor for nonblocking I/O */
98 /*----- Static variables --------------------------------------------------*/
100 static unsigned flags = 0; /* Global state flags */
101 static unsigned active = 0; /* Number of active things */
107 /*----- Main code ---------------------------------------------------------*/
109 /* --- @fw_log@ --- *
111 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
112 * @const char *fmt@ = format string to fill in
113 * @...@ = other arguments
117 * Use: Logs a connection.
120 void fw_log(time_t t, const char *fmt, ...)
126 if (flags & FW_QUIET)
133 d.len += strftime(d.buf, d.sz, "%Y-%m-%d %H:%M:%S ", tm);
135 dstr_vputf(&d, fmt, ap);
137 if (flags & FW_SYSLOG)
138 syslog(LOG_NOTICE, "%s", d.buf);
141 dstr_write(&d, stderr);
146 /* --- @fw_inc@, @fw_dec@ --- *
152 * Use: Increments or decrements the active thing count. `fw' won't
153 * quit while there are active things.
156 void fw_inc(void) { flags |= FW_SET; active++; }
157 void fw_dec(void) { if (active) active--; }
159 /* --- @fw_exit@ --- *
165 * Use: Exits when appropriate.
168 static void fw_exit(void)
174 /* --- @fw_tidy@ --- *
176 * Arguments: @int n@ = signal number
177 * @void *p@ = an uninteresting argument
181 * Use: Handles various signals and causes a clean tidy-up.
184 static void fw_tidy(int n, void *p)
186 const char *sn = "unexpected signal (bug!)";
189 else if (n == SIGINT)
192 fw_log(-1, "closing down on %s", sn);
196 /* --- Standard GNU help options --- */
198 static void version(FILE *fp)
200 pquis(fp, "$ version " VERSION "\n");
203 static void usage(FILE *fp)
205 pquis(fp, "Usage: $ [-dql] [-f file] [config statements...]\n");
208 static void help(FILE *fp)
214 An excessively full-featured port-forwarder, which subsumes large chunks\n\
215 of the functionality of inetd, netcat, and normal cat. Options available\n\
218 -h, --help Display this help message.\n\
219 -v, --version Display the program's version number.\n\
220 -u, --usage Display a terse usage summary.\n\
222 -G, --grammar Show a summary of the configuration language.\n\
223 -O, --options Show a summary of the source and target options.\n\
225 -f, --file=FILE Read configuration from a file.\n\
226 -q, --quiet Don't emit any logging information.\n\
227 -d, --daemon Fork into background after initializing.\n\
228 -l, --syslog Send log output to the system logger.\n\
229 -s, --setuid=USER Change uid to USER after initializing sources.\n\
230 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
232 Configuration may be supplied in one or more configuration files, or on\n\
233 the command line (or both). If no `-f' option is present, and no\n\
234 configuration is given on the command line, the standard input stream is\n\
237 Configuration is free-form. Comments begin with a `#' character and\n\
238 continue to the end of the line. Each command line argument is considered\n\
239 to be a separate line.\n\
241 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
242 For a summary of the various options, run `$ --options'.\n\
246 /* --- Other helpful options --- */
248 static void grammar(FILE *fp)
255 file ::= empty | file stmt [`;']\n\
256 stmt ::= option-stmt | fw-stmt\n\
257 fw-stmt ::= `fw' source options [`to'|`->'] target options\n\
258 options ::= `{' option-seq `}'\n\
259 option-seq ::= empty | option-stmt [`;'] option-seq\n\
262 option-stmt ::= q-option\n\
263 q-option ::= option\n\
264 | prefix `.' q-option\n\
265 | prefix `{' option-seq `}'\n\
268 File source and target\n\
271 file ::= `file' [`.'] fspec [`,' fspec]\n\
272 fspec ::= fd-spec | name-spec | null-spec\n\
273 fd-spec ::= [[`:']`fd'[`:']] number|`stdin'|`stdout'\n\
274 name-spec ::= [[`:']`file'[`:']] file-name\n\
275 file-name ::= path-seq | [ path-seq ]\n\
276 path-seq ::= path-elt | path-seq path-elt\n\
277 path-elt ::= `/' | word\n\
278 null-spec ::= [`:']`null'[`:']\n\
280 Exec source and target\n\
283 exec ::= `exec' [`.'] cmd-spec\n\
284 cmd-spec ::= shell-cmd | [prog-name] `[' argv0 arg-seq `]'\n\
285 arg-seq ::= word | arg-seq word\n\
286 shell-cmd ::= word\n\
289 Socket source and target\n\
290 source ::= socket-source\n\
291 target ::= socket-target\n\
292 socket-source ::= [`socket'[`.']] [[`:']addr-type[`:']] source-addr\n\
293 socket-target ::= [`socket'[`.']] [[`:']addr-type[`:']] target-addr\n\
295 inet-source-addr ::= [port] port\n\
296 inet-target-addr ::= address [`:'] port\n\
297 address ::= addr-elt | address addr-elt\n\
298 addr-elt ::= `.' | word\n\
300 unix-source-addr ::= file-name\n\
301 unix-target-addr ::= file-name\n\
305 static void options(FILE *fp)
311 File attributes (`fattr')\n\
312 prefix.fattr.mode [=] mode\n\
313 prefix.fattr.owner [=] user\n\
314 prefix.fattr.group [=] group\n\
317 file.create [=] yes|no\n\
318 file.open [=] no|truncate|append\n\
322 exec.logging [=] yes|no\n\
323 exec.dir [=] file-name\n\
324 exec.root [=] file-name\n\
325 exec.user [=] user\n\
326 exec.group [=] group\n\
327 exec.rlimit.limit[.hard|.soft] [=] value\n\
329 exec.env.unset var\n\
330 exec.env.[set] var [=] value\n\
333 socket.conn [=] number|unlimited|one-shot\n\
334 socket.logging [=] yes|no\n\
335 socket.inet.[allow|deny] [from] address [/ address]\n\
336 socket.unix.fattr.*\n\
342 * Arguments: @int argc@ = number of command line arguments
343 * @char *argv[]@ = vector of argument strings
347 * Use: Simple port-forwarding server.
350 int main(int argc, char *argv[])
366 /* --- Initialize things --- */
376 fattr_init(&fattr_global);
379 /* --- Set up some signal handlers --- *
381 * Don't enable @SIGINT@ if the caller already disabled it.
387 sig_add(&s_term, SIGTERM, fw_tidy, 0);
388 sigaction(SIGINT, 0, &sa);
389 if (sa.sa_handler != SIG_IGN)
390 sig_add(&s_int, SIGINT, fw_tidy, 0);
395 /* --- Parse command line options --- */
398 static struct option opts[] = {
400 /* --- Standard GNU help options --- */
402 { "help", 0, 0, 'h' },
403 { "version", 0, 0, 'v' },
404 { "usage", 0, 0, 'u' },
406 /* --- Other help options --- */
408 { "grammar", 0, 0, 'g' },
409 { "options", 0, 0, 'o' },
411 /* --- Other useful arguments --- */
413 { "file", OPTF_ARGREQ, 0, 'f' },
414 { "fork", 0, 0, 'd' },
415 { "daemon", 0, 0, 'd' },
416 { "syslog", 0, 0, 'l' },
417 { "log", 0, 0, 'l' },
418 { "quiet", 0, 0, 'q' },
419 { "setuid", OPTF_ARGREQ, 0, 's' },
420 { "uid", OPTF_ARGREQ, 0, 's' },
421 { "setgid", OPTF_ARGREQ, 0, 'g' },
422 { "gid", OPTF_ARGREQ, 0, 'g' },
424 /* --- Magic terminator --- */
428 int i = mdwopt(argc, argv, "+hvu GO f:dls:g:", opts, 0, 0, 0);
454 if (strcmp(optarg, "-") == 0)
455 scan_add(&sc, scan_file(stdin, "<stdin>", SCF_NOCLOSE));
458 if ((fp = fopen(optarg, "r")) == 0)
459 die(1, "couldn't open file `%s': %s", optarg, strerror(errno));
460 scan_add(&sc, scan_file(fp, optarg, 0));
474 if (isdigit((unsigned char )optarg[0])) {
476 drop = strtol(optarg, &q, 0);
478 die(1, "bad uid `%s'", optarg);
480 struct passwd *pw = getpwnam(optarg);
482 die(1, "unknown user `%s'", optarg);
487 if (isdigit((unsigned char )optarg[0])) {
489 dropg = strtol(optarg, &q, 0);
491 die(1, "bad gid `%s'", optarg);
493 struct group *gr = getgrnam(optarg);
495 die(1, "unknown group `%s'", optarg);
510 /* --- Deal with the remaining arguments --- */
513 scan_add(&sc, scan_argv(argv + optind));
516 else if (!isatty(STDIN_FILENO))
517 scan_add(&sc, scan_file(stdin, "<stdin>", SCF_NOCLOSE));
519 moan("no configuration given and stdin is a terminal.");
520 moan("type `%s --help' for usage information.", QUIS);
524 /* --- Parse the configuration now gathered --- */
528 /* --- Drop privileges --- */
530 #ifdef HAVE_SETGROUPS
531 if ((dropg != -1 && (setgid(dropg) || setgroups(1, &dropg))) ||
533 if ((dropg != -1 && setgid(dropg)) ||
535 (drop != -1 && setuid(drop)))
536 die(1, "couldn't drop privileges: %s", strerror(errno));
538 /* --- Fork into the background --- */
545 die(1, "couldn't fork: %s", strerror(errno));
549 close(0); close(1); close(2);
560 openlog(QUIS, 0, LOG_DAEMON);
563 /* --- Let rip --- */
565 if (!(flags & FW_SET))
566 moan("nothing to do!");
567 signal(SIGPIPE, SIG_IGN);
573 /*----- That's all, folks -------------------------------------------------*/