General tweaks and fixes for Nick's comments.
[tor.git] / src / tools / tor-fw-helper / tor-fw-helper.c
blobd02b75791c1a1f5ce897cac182f8a4ad55170d2e
1 /* Copyright (c) 2010, Jacob Appelbaum, Steven J. Murdoch.
2 * Copyright (c) 2010-2012, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file tor-fw-helper.c
7 * \brief The main wrapper around our firewall helper logic.
8 **/
11 * tor-fw-helper is a tool for opening firewalls with NAT-PMP and UPnP; this
12 * tool is designed to be called by hand or by Tor by way of a exec() at a
13 * later date.
16 #include "orconfig.h"
17 #include <stdio.h>
18 #include <stdint.h>
19 #include <stdlib.h>
20 #include <getopt.h>
21 #include <time.h>
22 #include <string.h>
23 #include <assert.h>
25 #include "container.h"
27 #ifdef _WIN32
28 #include <winsock2.h>
29 #endif
31 #include "tor-fw-helper.h"
32 #ifdef NAT_PMP
33 #include "tor-fw-helper-natpmp.h"
34 #endif
35 #ifdef MINIUPNPC
36 #include "tor-fw-helper-upnp.h"
37 #endif
39 /** This is our meta storage type - it holds information about each helper
40 including the total number of helper backends, function pointers, and helper
41 state. */
42 typedef struct backends_t {
43 /** The total number of backends */
44 int n_backends;
45 /** The backend functions as an array */
46 tor_fw_backend_t backend_ops[MAX_BACKENDS];
47 /** The internal backend state */
48 void *backend_state[MAX_BACKENDS];
49 } backends_t;
51 /** Initialize each backend helper with the user input stored in <b>options</b>
52 * and put the results in the <b>backends</b> struct. */
53 static int
54 init_backends(tor_fw_options_t *options, backends_t *backends)
56 int n_available = 0;
57 int i, r, n;
58 tor_fw_backend_t *backend_ops_list[MAX_BACKENDS];
59 void *data = NULL;
60 /* First, build a list of the working backends. */
61 n = 0;
62 #ifdef MINIUPNPC
63 backend_ops_list[n++] = (tor_fw_backend_t *) tor_fw_get_miniupnp_backend();
64 #endif
65 #ifdef NAT_PMP
66 backend_ops_list[n++] = (tor_fw_backend_t *) tor_fw_get_natpmp_backend();
67 #endif
68 n_available = n;
70 /* Now, for each backend that might work, try to initialize it.
71 * That's how we roll, initialized.
73 n = 0;
74 for (i=0; i<n_available; ++i) {
75 data = calloc(1, backend_ops_list[i]->state_len);
76 if (!data) {
77 perror("calloc");
78 exit(1);
80 r = backend_ops_list[i]->init(options, data);
81 if (r == 0) {
82 backends->backend_ops[n] = *backend_ops_list[i];
83 backends->backend_state[n] = data;
84 n++;
85 } else {
86 free(data);
89 backends->n_backends = n;
91 return n;
94 /** Return the proper commandline switches when the user needs information. */
95 static void
96 usage(void)
98 fprintf(stderr, "tor-fw-helper usage:\n"
99 " [-h|--help]\n"
100 " [-T|--Test]\n"
101 " [-v|--verbose]\n"
102 " [-g|--fetch-public-ip]\n"
103 " [-p|--forward-port ([<external port>]:<internal port>])\n");
106 /** Log commandline options to a hardcoded file <b>tor-fw-helper.log</b> in the
107 * current working directory. */
108 static int
109 log_commandline_options(int argc, char **argv)
111 int i, retval;
112 FILE *logfile;
113 time_t now;
115 /* Open the log file */
116 logfile = fopen("tor-fw-helper.log", "a");
117 if (NULL == logfile)
118 return -1;
120 /* Send all commandline arguments to the file */
121 now = time(NULL);
122 retval = fprintf(logfile, "START: %s\n", ctime(&now));
123 for (i = 0; i < argc; i++) {
124 retval = fprintf(logfile, "ARG: %d: %s\n", i, argv[i]);
125 if (retval < 0)
126 goto error;
128 retval = fprintf(stderr, "ARG: %d: %s\n", i, argv[i]);
129 if (retval < 0)
130 goto error;
132 now = time(NULL);
133 retval = fprintf(logfile, "END: %s\n", ctime(&now));
135 /* Close and clean up */
136 retval = fclose(logfile);
137 return retval;
139 /* If there was an error during writing */
140 error:
141 fclose(logfile);
142 return -1;
145 /** Iterate over over each of the supported <b>backends</b> and attempt to
146 * fetch the public ip. */
147 static void
148 tor_fw_fetch_public_ip(tor_fw_options_t *tor_fw_options,
149 backends_t *backends)
151 int i;
152 int r = 0;
154 if (tor_fw_options->verbose)
155 fprintf(stderr, "V: tor_fw_fetch_public_ip\n");
157 for (i=0; i<backends->n_backends; ++i) {
158 if (tor_fw_options->verbose) {
159 fprintf(stderr, "V: running backend_state now: %i\n", i);
160 fprintf(stderr, "V: size of backend state: %u\n",
161 (int)(backends->backend_ops)[i].state_len);
162 fprintf(stderr, "V: backend state name: %s\n",
163 (char *)(backends->backend_ops)[i].name);
165 r = backends->backend_ops[i].fetch_public_ip(tor_fw_options,
166 backends->backend_state[i]);
167 fprintf(stderr, "tor-fw-helper: tor_fw_fetch_public_ip backend %s "
168 " returned: %i\n", (char *)(backends->backend_ops)[i].name, r);
172 /** Print a spec-conformant string to stdout describing the results of
173 * the TCP port forwarding operation from <b>external_port</b> to
174 * <b>internal_port</b>. */
175 static void
176 tor_fw_helper_report_port_fw_results(uint16_t internal_port,
177 uint16_t external_port,
178 int succeded,
179 const char *message)
181 char *report_string = NULL;
183 tor_asprintf(&report_string, "%s %s %u %u %s %s\n",
184 "tor-fw-helper",
185 "tcp-forward",
186 external_port, internal_port,
187 succeded ? "SUCCESS" : "FAIL",
188 message);
189 fprintf(stdout, "%s", report_string);
190 fflush(stdout);
191 tor_free(report_string);
194 #define tor_fw_helper_report_port_fw_fail(i, e, m) \
195 tor_fw_helper_report_port_fw_results((i), (e), 0, (m))
197 #define tor_fw_helper_report_port_fw_success(i, e, m) \
198 tor_fw_helper_report_port_fw_results((i), (e), 1, (m))
200 /** Return a heap-allocated string containing the list of our
201 * backends. It can be used in log messages. Be sure to free it
202 * afterwards! */
203 static char *
204 get_list_of_backends_string(backends_t *backends)
206 char *backend_names = NULL;
207 int i;
208 smartlist_t *backend_names_sl = smartlist_new();
210 assert(backends->n_backends);
212 for (i=0; i<backends->n_backends; ++i)
213 smartlist_add(backend_names_sl, (char *) backends->backend_ops[i].name);
215 backend_names = smartlist_join_strings(backend_names_sl, ", ", 0, NULL);
216 smartlist_free(backend_names_sl);
218 return backend_names;
221 /** Iterate over each of the supported <b>backends</b> and attempt to add a
222 * port forward for the port stored in <b>tor_fw_options</b>. */
223 static void
224 tor_fw_add_ports(tor_fw_options_t *tor_fw_options,
225 backends_t *backends)
227 int i;
228 int r = 0;
229 int succeeded = 0;
231 if (tor_fw_options->verbose)
232 fprintf(stderr, "V: %s\n", __func__);
234 /** Loop all ports that need to be forwarded, and try to use our
235 * backends for each port. If a backend succeeds, break the loop,
236 * report success and get to the next port. If all backends fail,
237 * report failure for that port. */
238 SMARTLIST_FOREACH_BEGIN(tor_fw_options->ports_to_forward,
239 port_to_forward_t *, port_to_forward) {
241 succeeded = 0;
243 for (i=0; i<backends->n_backends; ++i) {
244 if (tor_fw_options->verbose) {
245 fprintf(stderr, "V: running backend_state now: %i\n", i);
246 fprintf(stderr, "V: size of backend state: %u\n",
247 (int)(backends->backend_ops)[i].state_len);
248 fprintf(stderr, "V: backend state name: %s\n",
249 (const char *) backends->backend_ops[i].name);
253 backends->backend_ops[i].add_tcp_mapping(port_to_forward->internal_port,
254 port_to_forward->external_port,
255 tor_fw_options->verbose,
256 backends->backend_state[i]);
257 if (r == 0) { /* backend success */
258 tor_fw_helper_report_port_fw_success(port_to_forward->internal_port,
259 port_to_forward->external_port,
260 backends->backend_ops[i].name);
261 succeeded = 1;
262 break;
265 fprintf(stderr, "tor-fw-helper: tor_fw_add_port backend %s "
266 "returned: %i\n",
267 (const char *) backends->backend_ops[i].name, r);
270 if (!succeeded) { /* all backends failed */
271 char *list_of_backends_str = get_list_of_backends_string(backends);
272 char *fail_msg = NULL;
273 tor_asprintf(&fail_msg, "All port forwarding backends (%s) failed.",
274 list_of_backends_str);
275 tor_fw_helper_report_port_fw_fail(port_to_forward->internal_port,
276 port_to_forward->external_port,
277 fail_msg);
278 tor_free(list_of_backends_str);
279 tor_free(fail_msg);
282 } SMARTLIST_FOREACH_END(port_to_forward);
285 /** Called before we make any calls to network-related functions.
286 * (Some operating systems require their network libraries to be
287 * initialized.) (from common/compat.c) */
288 static int
289 tor_fw_helper_network_init(void)
291 #ifdef _WIN32
292 /* This silly exercise is necessary before windows will allow
293 * gethostbyname to work. */
294 WSADATA WSAData;
295 int r;
296 r = WSAStartup(0x101, &WSAData);
297 if (r) {
298 fprintf(stderr, "E: Error initializing Windows network layer "
299 "- code was %d", r);
300 return -1;
302 /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
303 * We might use it to complain if we're trying to be a server but have
304 * too few sockets available. */
305 #endif
306 return 0;
309 /** Parse the '-p' argument of tor-fw-helper. Its format is
310 * [<external port>]:<internal port>, and <external port> is optional.
311 * Return NULL if <b>arg</b> was c0rrupted. */
312 static port_to_forward_t *
313 parse_port(const char *arg)
315 smartlist_t *sl = smartlist_new();
316 port_to_forward_t *port_to_forward = NULL;
317 char *port_str = NULL;
318 int ok;
319 int port;
321 smartlist_split_string(sl, arg, ":", 0, 0);
322 if (smartlist_len(sl) != 2)
323 goto err;
325 port_to_forward = tor_malloc(sizeof(port_to_forward_t));
326 if (!port_to_forward)
327 goto err;
329 port_str = smartlist_get(sl, 0); /* macroify ? */
330 port = (int)tor_parse_long(port_str, 10, 1, 65535, &ok, NULL);
331 if (!ok && strlen(port_str)) /* ":1555" is valid */
332 goto err;
333 port_to_forward->external_port = port;
335 port_str = smartlist_get(sl, 1);
336 port = (int)tor_parse_long(port_str, 10, 1, 65535, &ok, NULL);
337 if (!ok)
338 goto err;
339 port_to_forward->internal_port = port;
341 goto done;
343 err:
344 tor_free(port_to_forward);
346 done:
347 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
348 smartlist_free(sl);
350 return port_to_forward;
353 /** Report a failure of epic proportions: We didn't manage to
354 * initialize any port forwarding backends. */
355 static void
356 report_full_fail(const smartlist_t *ports_to_forward, backends_t *backends)
358 char *list_of_backends_str = NULL;
359 char *fail_msg = NULL;
361 if (!ports_to_forward)
362 return;
364 list_of_backends_str = get_list_of_backends_string(backends);
365 tor_asprintf(&fail_msg,
366 "Port forwarding backends (%s) could not be initialized.",
367 list_of_backends_str);
369 SMARTLIST_FOREACH_BEGIN(ports_to_forward,
370 const port_to_forward_t *, port_to_forward) {
371 tor_fw_helper_report_port_fw_fail(port_to_forward->internal_port,
372 port_to_forward->external_port,
373 fail_msg);
374 } SMARTLIST_FOREACH_END(port_to_forward);
376 tor_free(list_of_backends_str);
377 tor_free(fail_msg);
381 main(int argc, char **argv)
383 int r = 0;
384 int c = 0;
386 tor_fw_options_t tor_fw_options;
387 backends_t backend_state;
389 memset(&tor_fw_options, 0, sizeof(tor_fw_options));
390 memset(&backend_state, 0, sizeof(backend_state));
392 // Parse CLI arguments.
393 while (1) {
394 int option_index = 0;
395 static struct option long_options[] =
397 {"verbose", 0, 0, 'v'},
398 {"help", 0, 0, 'h'},
399 {"port", 1, 0, 'p'},
400 {"fetch-public-ip", 0, 0, 'g'},
401 {"test-commandline", 0, 0, 'T'},
402 {0, 0, 0, 0}
405 c = getopt_long(argc, argv, "vhp:gT",
406 long_options, &option_index);
407 if (c == -1)
408 break;
410 switch (c) {
411 case 'v': tor_fw_options.verbose = 1; break;
412 case 'h': tor_fw_options.help = 1; usage(); exit(1); break;
413 case 'p': {
414 port_to_forward_t *port_to_forward = parse_port(optarg);
415 if (!port_to_forward) {
416 fprintf(stderr, "E: Failed to parse '%s'.\n", optarg);
417 usage();
418 exit(1);
421 /* If no external port was given (it's optional), set it to be
422 * equal with the internal port. */
423 if (!port_to_forward->external_port) {
424 assert(port_to_forward->internal_port);
425 if (tor_fw_options.verbose)
426 fprintf(stderr, "V: No external port was given. Setting to %u.\n",
427 port_to_forward->internal_port);
428 port_to_forward->external_port = port_to_forward->internal_port;
431 if (!tor_fw_options.ports_to_forward)
432 tor_fw_options.ports_to_forward = smartlist_new();
434 smartlist_add(tor_fw_options.ports_to_forward, port_to_forward);
436 break;
438 case 'g': tor_fw_options.fetch_public_ip = 1; break;
439 case 'T': tor_fw_options.test_commandline = 1; break;
440 case '?': break;
441 default : fprintf(stderr, "Unknown option!\n"); usage(); exit(1);
445 { // Verbose output
447 if (tor_fw_options.verbose)
448 fprintf(stderr, "V: tor-fw-helper version %s\n"
449 "V: We were called with the following arguments:\n"
450 "V: verbose = %d, help = %d, fetch_public_ip = %u\n",
451 tor_fw_version, tor_fw_options.verbose, tor_fw_options.help,
452 tor_fw_options.fetch_public_ip);
454 if (tor_fw_options.verbose && tor_fw_options.ports_to_forward) {
455 fprintf(stderr, "V: TCP forwarding:\n");
456 SMARTLIST_FOREACH(tor_fw_options.ports_to_forward,
457 const port_to_forward_t *, port_to_forward,
458 fprintf(stderr, "V: External: %u, Internal: %u\n",
459 port_to_forward->external_port,
460 port_to_forward->internal_port));
464 if (tor_fw_options.test_commandline) {
465 return log_commandline_options(argc, argv);
468 // See if the user actually wants us to do something.
469 if (!tor_fw_options.fetch_public_ip && !tor_fw_options.ports_to_forward) {
470 fprintf(stderr, "E: We require a port to be forwarded or "
471 "fetch_public_ip request!\n");
472 usage();
473 exit(1);
476 // Initialize networking
477 if (tor_fw_helper_network_init())
478 exit(1);
480 // Initalize the various fw-helper backend helpers
481 r = init_backends(&tor_fw_options, &backend_state);
482 if (!r) { // all backends failed:
483 // report our failure
484 report_full_fail(tor_fw_options.ports_to_forward, &backend_state);
485 fprintf(stderr, "V: tor-fw-helper: All backends failed.\n");
486 exit(1);
487 } else { // some backends succeeded:
488 fprintf(stderr, "tor-fw-helper: %i NAT traversal helper(s) loaded\n", r);
491 // Forward TCP ports.
492 if (tor_fw_options.ports_to_forward) {
493 tor_fw_add_ports(&tor_fw_options, &backend_state);
496 // Fetch our public IP.
497 if (tor_fw_options.fetch_public_ip) {
498 tor_fw_fetch_public_ip(&tor_fw_options, &backend_state);
501 // Cleanup and exit.
502 if (tor_fw_options.ports_to_forward) {
503 SMARTLIST_FOREACH(tor_fw_options.ports_to_forward,
504 port_to_forward_t *, port,
505 tor_free(port));
506 smartlist_free(tor_fw_options.ports_to_forward);
509 exit(r);