tor-fw-helper.c 15 KB

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