summaryrefslogtreecommitdiff
path: root/src/nat
diff options
context:
space:
mode:
authorChristian Grothoff <christian@grothoff.org>2017-01-07 16:47:07 +0100
committerChristian Grothoff <christian@grothoff.org>2017-01-07 16:47:07 +0100
commitddadc570d8fd3ce7a4f658adf9a2c9b9d9c0dcba (patch)
tree076f4d7b4732099d33662de3bdff51c965cae8df /src/nat
parent659e270f9e023112ca864065a22db5e484ba5ef6 (diff)
downloadgnunet-ddadc570d8fd3ce7a4f658adf9a2c9b9d9c0dcba.tar.gz
gnunet-ddadc570d8fd3ce7a4f658adf9a2c9b9d9c0dcba.zip
remove legacy NAT library logic, or preserve if it might still be useful
Diffstat (limited to 'src/nat')
-rw-r--r--src/nat/Makefile.am70
-rw-r--r--src/nat/gnunet-service-nat.c9
-rw-r--r--src/nat/nat.c2054
-rw-r--r--src/nat/nat_auto.c1081
-rw-r--r--src/nat/nat_mini.c712
-rw-r--r--src/nat/nat_stun.c439
-rw-r--r--src/nat/nat_test.c645
7 files changed, 30 insertions, 4980 deletions
diff --git a/src/nat/Makefile.am b/src/nat/Makefile.am
index 456ddfb62..3dc001dd7 100644
--- a/src/nat/Makefile.am
+++ b/src/nat/Makefile.am
@@ -60,22 +60,8 @@ if USE_COVERAGE
60endif 60endif
61 61
62lib_LTLIBRARIES = \ 62lib_LTLIBRARIES = \
63 libgnunetnat.la \
64 libgnunetnatnew.la 63 libgnunetnatnew.la
65 64
66libgnunetnat_la_SOURCES = \
67 nat.c nat.h \
68 nat_auto.c \
69 nat_test.c \
70 nat_mini.c \
71 nat_stun.c
72libgnunetnat_la_LIBADD = \
73 $(top_builddir)/src/util/libgnunetutil.la \
74 $(GN_LIBINTL) @EXT_LIBS@
75libgnunetnat_la_LDFLAGS = \
76 $(GN_LIB_LDFLAGS) $(WINFLAGS) \
77 -version-info 1:1:1
78
79libgnunetnatnew_la_SOURCES = \ 65libgnunetnatnew_la_SOURCES = \
80 nat_api.c \ 66 nat_api.c \
81 nat_api_stun.c nat_stun.h \ 67 nat_api_stun.c nat_stun.h \
@@ -100,40 +86,40 @@ gnunet_service_nat_LDADD = \
100 -lgcrypt \ 86 -lgcrypt \
101 $(GN_LIBINTL) 87 $(GN_LIBINTL)
102 88
103check_PROGRAMS = \ 89#check_PROGRAMS = \
104 test_nat \ 90# test_nat \
105 test_nat_mini \ 91# test_nat_mini \
106 test_nat_test \ 92# test_nat_test \
107 test_stun 93# test_stun
108 94
109if ENABLE_TEST_RUN 95if ENABLE_TEST_RUN
110 AM_TESTS_ENVIRONMENT=export GNUNET_PREFIX=$${GNUNET_PREFIX:-@libdir@};export PATH=$${GNUNET_PREFIX:-@prefix@}/bin:$$PATH; 96 AM_TESTS_ENVIRONMENT=export GNUNET_PREFIX=$${GNUNET_PREFIX:-@libdir@};export PATH=$${GNUNET_PREFIX:-@prefix@}/bin:$$PATH;
111 TESTS = $(check_PROGRAMS) 97 TESTS = $(check_PROGRAMS)
112endif 98endif
113 99
114test_nat_SOURCES = \ 100#test_nat_SOURCES = \
115 test_nat.c 101# test_nat.c
116test_nat_LDADD = \ 102#test_nat_LDADD = \
117 libgnunetnat.la \ 103# libgnunetnat.la \
118 $(top_builddir)/src/util/libgnunetutil.la 104# $(top_builddir)/src/util/libgnunetutil.la
119 105
120test_nat_mini_SOURCES = \ 106#test_nat_mini_SOURCES = \
121 test_nat_mini.c 107# test_nat_mini.c
122test_nat_mini_LDADD = \ 108#test_nat_mini_LDADD = \
123 libgnunetnat.la \ 109# libgnunetnat.la \
124 $(top_builddir)/src/util/libgnunetutil.la 110# $(top_builddir)/src/util/libgnunetutil.la
125 111
126test_nat_test_SOURCES = \ 112#test_nat_test_SOURCES = \
127 test_nat_test.c 113# test_nat_test.c
128test_nat_test_LDADD = \ 114#test_nat_test_LDADD = \
129 libgnunetnat.la \ 115# libgnunetnat.la \
130 $(top_builddir)/src/util/libgnunetutil.la 116# $(top_builddir)/src/util/libgnunetutil.la
131 117
132test_stun_SOURCES = \ 118#test_stun_SOURCES = \
133 test_stun.c 119# test_stun.c
134test_stun_LDADD = \ 120#test_stun_LDADD = \
135 libgnunetnat.la \ 121# libgnunetnat.la \
136 $(top_builddir)/src/util/libgnunetutil.la 122# $(top_builddir)/src/util/libgnunetutil.la
137 123
138EXTRA_DIST = \ 124EXTRA_DIST = \
139 test_nat_data.conf \ 125 test_nat_data.conf \
diff --git a/src/nat/gnunet-service-nat.c b/src/nat/gnunet-service-nat.c
index b3e81127b..7fa329b54 100644
--- a/src/nat/gnunet-service-nat.c
+++ b/src/nat/gnunet-service-nat.c
@@ -28,13 +28,8 @@
28 * knowledge about the local network topology. 28 * knowledge about the local network topology.
29 * 29 *
30 * TODO: 30 * TODO:
31 * - adapt existing transports to use new NAT logic 31 * - migrate test cases to new NAT service
32 * - abandon legacy NAT code 32 * - add new traceroute-based logic for external IP detection
33 *
34 * - implement "more" autoconfig:
35 * + consider moving autoconfig-logic into separate service!
36 * + re-work gnunet-nat-server & integrate!
37 * + test manually punched NAT (how?)
38 * 33 *
39 * - implement & test STUN processing to classify NAT; 34 * - implement & test STUN processing to classify NAT;
40 * basically, open port & try different methods. 35 * basically, open port & try different methods.
diff --git a/src/nat/nat.c b/src/nat/nat.c
deleted file mode 100644
index 08dd5dd1e..000000000
--- a/src/nat/nat.c
+++ /dev/null
@@ -1,2054 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2010, 2011 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file nat/nat.c
23 * @brief Library handling UPnP and NAT-PMP port forwarding and
24 * external IP address retrieval
25 * @author Milan Bouchet-Valat
26 * @author Christian Grothoff
27 */
28#include "platform.h"
29#include "gnunet_util_lib.h"
30#include "gnunet_resolver_service.h"
31#include "gnunet_nat_lib.h"
32#include "nat.h"
33
34#define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
35
36/**
37 * How often do we scan for changes in our IP address from our local
38 * interfaces?
39 */
40#define IFC_SCAN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
41
42/**
43 * How often do we scan for changes in how our hostname resolves?
44 */
45#define HOSTNAME_DNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 20)
46
47
48/**
49 * How often do we scan for changes in how our external (dyndns) hostname resolves?
50 */
51#define DYNDNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 7)
52
53/**
54 * How long until we give up trying to resolve our own hostname?
55 */
56#define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
57
58
59/**
60 * How often do we check a STUN server ?
61 */
62#define STUN_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
63
64
65/**
66 * Where did the given local address originate from?
67 * To be used for debugging as well as in the future
68 * to remove all addresses from a certain source when
69 * we reevaluate the source.
70 */
71enum LocalAddressSource
72{
73 /**
74 * Address was obtained by DNS resolution of the external hostname
75 * given in the configuration (i.e. hole-punched DynDNS setup).
76 */
77 LAL_EXTERNAL_IP,
78
79 /**
80 * Address was obtained by an external STUN server
81 */
82 LAL_EXTERNAL_STUN_IP,
83
84 /**
85 * Address was obtained by DNS resolution of the external hostname
86 * given in the configuration (i.e. hole-punched DynDNS setup)
87 * during the previous iteration (see #3213).
88 */
89 LAL_EXTERNAL_IP_OLD,
90
91 /**
92 * Address was obtained by looking up our own hostname in DNS.
93 */
94 LAL_HOSTNAME_DNS,
95
96 /**
97 * Address was obtained by scanning our hosts's network interfaces
98 * and taking their address (no DNS involved).
99 */
100 LAL_INTERFACE_ADDRESS,
101
102 /**
103 * Addresses we were explicitly bound to.
104 */
105 LAL_BINDTO_ADDRESS,
106
107 /**
108 * Addresses from UPnP or PMP
109 */
110 LAL_UPNP,
111
112 /**
113 * End of the list.
114 */
115 LAL_END
116};
117
118
119/**
120 * List of local addresses that we currently deem valid. Actual
121 * struct is followed by the 'struct sockaddr'. Note that the code
122 * intentionally makes no attempt to ensure that a particular address
123 * is only listed once (especially since it may come from different
124 * sources, and the source is an "internal" construct).
125 */
126struct LocalAddressList
127{
128 /**
129 * This is a linked list.
130 */
131 struct LocalAddressList *next;
132
133 /**
134 * Previous entry.
135 */
136 struct LocalAddressList *prev;
137
138 /**
139 * Number of bytes of address that follow.
140 */
141 socklen_t addrlen;
142
143 /**
144 * Origin of the local address.
145 */
146 enum LocalAddressSource source;
147};
148
149
150/**
151 * Handle for miniupnp-based NAT traversal actions.
152 */
153struct MiniList
154{
155
156 /**
157 * Doubly-linked list.
158 */
159 struct MiniList *next;
160
161 /**
162 * Doubly-linked list.
163 */
164 struct MiniList *prev;
165
166 /**
167 * Handle to mini-action.
168 */
169 struct GNUNET_NAT_MiniHandle *mini;
170
171 /**
172 * Local port number that was mapped.
173 */
174 uint16_t port;
175
176};
177
178
179/**
180 * List of STUN servers
181 */
182struct StunServerList
183{
184
185 /**
186 * Doubly-linked list.
187 */
188 struct StunServerList *next;
189
190 /**
191 * Doubly-linked list.
192 */
193 struct StunServerList *prev;
194
195 /**
196 * Address
197 */
198 char * address;
199
200 /**
201 * Server Port
202 */
203 uint16_t port;
204
205};
206
207
208/**
209 * Handle for active NAT registrations.
210 */
211struct GNUNET_NAT_Handle
212{
213
214 /**
215 * Configuration to use.
216 */
217 const struct GNUNET_CONFIGURATION_Handle *cfg;
218
219 /**
220 * Function to call when we learn about a new address.
221 */
222 GNUNET_NAT_AddressCallback address_callback;
223
224 /**
225 * Function to call when we notice another peer asking for
226 * connection reversal.
227 */
228 GNUNET_NAT_ReversalCallback reversal_callback;
229
230 /**
231 * Closure for callbacks (@e address_callback and @e reversal_callback)
232 */
233 void *callback_cls;
234
235 /**
236 * Handle for (DYN)DNS lookup of our external IP.
237 */
238 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
239
240 /**
241 * Handle for request of hostname resolution, non-NULL if pending.
242 */
243 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
244
245 /**
246 * stdout pipe handle for the gnunet-helper-nat-server process
247 */
248 struct GNUNET_DISK_PipeHandle *server_stdout;
249
250 /**
251 * stdout file handle (for reading) for the gnunet-helper-nat-server process
252 */
253 const struct GNUNET_DISK_FileHandle *server_stdout_handle;
254
255 /**
256 * Linked list of currently valid addresses (head).
257 */
258 struct LocalAddressList *lal_head;
259
260 /**
261 * Linked list of currently valid addresses (tail).
262 */
263 struct LocalAddressList *lal_tail;
264
265 /**
266 * How long do we wait for restarting a crashed gnunet-helper-nat-server?
267 */
268 struct GNUNET_TIME_Relative server_retry_delay;
269
270 /**
271 * ID of select gnunet-helper-nat-server stdout read task
272 */
273 struct GNUNET_SCHEDULER_Task *server_read_task;
274
275 /**
276 * ID of interface IP-scan task
277 */
278 struct GNUNET_SCHEDULER_Task *ifc_task;
279
280 /**
281 * ID of hostname DNS lookup task
282 */
283 struct GNUNET_SCHEDULER_Task *hostname_task;
284
285 /**
286 * ID of DynDNS lookup task
287 */
288 struct GNUNET_SCHEDULER_Task *dns_task;
289
290 /**
291 * Active STUN request, if any.
292 */
293 struct GNUNET_NAT_STUN_Handle *stun_request;
294
295 /**
296 * How often do we scan for changes in our IP address from our local
297 * interfaces?
298 */
299 struct GNUNET_TIME_Relative ifc_scan_frequency;
300
301 /**
302 * How often do we scan for changes in how our hostname resolves?
303 */
304 struct GNUNET_TIME_Relative hostname_dns_frequency;
305
306 /**
307 * How often do we scan for changes in how our external (dyndns) hostname resolves?
308 */
309 struct GNUNET_TIME_Relative dyndns_frequency;
310
311 /**
312 * The process id of the server process (if behind NAT)
313 */
314 struct GNUNET_OS_Process *server_proc;
315
316 /**
317 * LAN address as passed by the caller (array).
318 */
319 struct sockaddr **local_addrs;
320
321 /**
322 * Length of the @e local_addrs.
323 */
324 socklen_t *local_addrlens;
325
326 /**
327 * List of handles for UPnP-traversal, one per local port (if
328 * not IPv6-only).
329 */
330 struct MiniList *mini_head;
331
332 /**
333 * List of handles for UPnP-traversal, one per local port (if
334 * not IPv6-only).
335 */
336 struct MiniList *mini_tail;
337
338 /**
339 * Number of entries in 'local_addrs' array.
340 */
341 unsigned int num_local_addrs;
342
343 /**
344 * Our external address (according to config, UPnP may disagree...),
345 * in dotted decimal notation, IPv4-only. Or NULL if not known.
346 */
347 char *external_address;
348
349 /**
350 * Presumably our internal address (according to config)
351 */
352 char *internal_address;
353
354 /**
355 * Is this transport configured to be behind a NAT?
356 */
357 int behind_nat;
358
359 /**
360 * Has the NAT been punched? (according to config)
361 */
362 int nat_punched;
363
364 /**
365 * Is this transport configured to allow connections to NAT'd peers?
366 */
367 int enable_nat_client;
368
369 /**
370 * Should we run the gnunet-helper-nat-server?
371 */
372 int enable_nat_server;
373
374 /**
375 * Are we allowed to try UPnP/PMP for NAT traversal?
376 */
377 int enable_upnp;
378
379 /**
380 * Should we use local addresses (loopback)? (according to config)
381 */
382 int use_localaddresses;
383
384 /**
385 * Should we return local addresses to clients
386 */
387 int return_localaddress;
388
389 /**
390 * Should we do a DNS lookup of our hostname to find out our own IP?
391 */
392 int use_hostname;
393
394 /**
395 * Is using IPv6 disabled?
396 */
397 int disable_ipv6;
398
399 /**
400 * Is this TCP or UDP?
401 */
402 int is_tcp;
403
404 /**
405 * Port we advertise to the outside.
406 */
407 uint16_t adv_port;
408
409 /**
410 * Should we use STUN ?
411 */
412 int use_stun;
413
414 /**
415 * How often should we check STUN ?
416 */
417 struct GNUNET_TIME_Relative stun_frequency;
418
419 /**
420 * STUN socket
421 */
422 struct GNUNET_NETWORK_Handle* socket;
423
424 /*
425 * Am I waiting for a STUN response ?
426 */
427 int waiting_stun;
428
429 /**
430 * STUN request task
431 */
432 struct GNUNET_SCHEDULER_Task *stun_task;
433
434 /**
435 * Head of List of STUN servers
436 */
437 struct StunServerList *stun_servers_head;
438
439 /**
440 * Tail of List of STUN servers
441 */
442 struct StunServerList *stun_servers_tail;
443
444 /**
445 * Actual STUN Server
446 */
447 struct StunServerList *actual_stun_server;
448
449};
450
451
452/**
453 * Try to start the gnunet-helper-nat-server (if it is not
454 * already running).
455 *
456 * @param h handle to NAT
457 */
458static void
459start_gnunet_nat_server (struct GNUNET_NAT_Handle *h);
460
461
462/**
463 * Remove all addresses from the list of 'local' addresses
464 * that originated from the given source.
465 *
466 * @param h handle to NAT
467 * @param src source that identifies addresses to remove
468 */
469static void
470remove_from_address_list_by_source (struct GNUNET_NAT_Handle *h,
471 enum LocalAddressSource src)
472{
473 struct LocalAddressList *pos;
474 struct LocalAddressList *next;
475
476 next = h->lal_head;
477 while (NULL != (pos = next))
478 {
479 next = pos->next;
480 if (pos->source != src)
481 continue;
482 GNUNET_CONTAINER_DLL_remove (h->lal_head,
483 h->lal_tail,
484 pos);
485 if (NULL != h->address_callback)
486 h->address_callback (h->callback_cls,
487 GNUNET_NO,
488 (const struct sockaddr *) &pos[1],
489 pos->addrlen);
490 GNUNET_free (pos);
491 }
492}
493
494
495/**
496 * Add the given address to the list of 'local' addresses, thereby
497 * making it a 'legal' address for this peer to have.
498 *
499 * @param h handle to NAT
500 * @param src where did the local address originate from?
501 * @param arg the address, some `struct sockaddr`
502 * @param arg_size number of bytes in @a arg
503 */
504static void
505add_to_address_list_as_is (struct GNUNET_NAT_Handle *h,
506 enum LocalAddressSource src,
507 const struct sockaddr *arg,
508 socklen_t arg_size)
509{
510 struct LocalAddressList *lal;
511
512 lal = GNUNET_malloc (sizeof (struct LocalAddressList) + arg_size);
513 GNUNET_memcpy (&lal[1], arg, arg_size);
514 lal->addrlen = arg_size;
515 lal->source = src;
516 GNUNET_CONTAINER_DLL_insert (h->lal_head,
517 h->lal_tail,
518 lal);
519 LOG (GNUNET_ERROR_TYPE_DEBUG,
520 "Adding address `%s' from source %d\n",
521 GNUNET_a2s (arg, arg_size),
522 src);
523 if (NULL != h->address_callback)
524 h->address_callback (h->callback_cls,
525 GNUNET_YES,
526 arg,
527 arg_size);
528}
529
530
531/**
532 * Add the given address to the list of 'local' addresses, thereby
533 * making it a 'legal' address for this peer to have. Set the
534 * port number in the process to the advertised port and possibly
535 * also to zero (if we have the gnunet-helper-nat-server).
536 *
537 * @param h handle to NAT
538 * @param src where did the local address originate from?
539 * @param arg the address, some `struct sockaddr`
540 * @param arg_size number of bytes in @a arg
541 */
542static void
543add_to_address_list (struct GNUNET_NAT_Handle *h,
544 enum LocalAddressSource src,
545 const struct sockaddr *arg,
546 socklen_t arg_size)
547{
548 struct sockaddr_in s4;
549 const struct sockaddr_in *in4;
550 struct sockaddr_in6 s6;
551 const struct sockaddr_in6 *in6;
552
553 if (arg_size == sizeof (struct sockaddr_in))
554 {
555 in4 = (const struct sockaddr_in *) arg;
556 s4 = *in4;
557 s4.sin_port = htons (h->adv_port);
558 add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
559 sizeof (struct sockaddr_in));
560 if (GNUNET_YES == h->enable_nat_server)
561 {
562 /* also add with PORT = 0 to indicate NAT server is enabled */
563 s4.sin_port = htons (0);
564 add_to_address_list_as_is (h, src, (const struct sockaddr *) &s4,
565 sizeof (struct sockaddr_in));
566 }
567 }
568 else if (arg_size == sizeof (struct sockaddr_in6))
569 {
570 if (GNUNET_YES != h->disable_ipv6)
571 {
572 in6 = (const struct sockaddr_in6 *) arg;
573 s6 = *in6;
574 s6.sin6_port = htons (h->adv_port);
575 add_to_address_list_as_is (h, src, (const struct sockaddr *) &s6,
576 sizeof (struct sockaddr_in6));
577 }
578 }
579 else
580 {
581 GNUNET_assert (0);
582 }
583}
584
585
586/**
587 * Add the given IP address to the list of 'local' addresses, thereby
588 * making it a 'legal' address for this peer to have.
589 *
590 * @param h handle to NAT
591 * @param src where did the local address originate from?
592 * @param addr the address, some `struct in_addr` or `struct in6_addr`
593 * @param addrlen number of bytes in addr
594 */
595static void
596add_ip_to_address_list (struct GNUNET_NAT_Handle *h,
597 enum LocalAddressSource src,
598 const void *addr,
599 socklen_t addrlen)
600{
601 struct sockaddr_in s4;
602 const struct in_addr *in4;
603 struct sockaddr_in6 s6;
604 const struct in6_addr *in6;
605
606 if (addrlen == sizeof (struct in_addr))
607 {
608 in4 = (const struct in_addr *) addr;
609 memset (&s4, 0, sizeof (s4));
610 s4.sin_family = AF_INET;
611 s4.sin_port = 0;
612#if HAVE_SOCKADDR_IN_SIN_LEN
613 s4.sin_len = (u_char) sizeof (struct sockaddr_in);
614#endif
615 s4.sin_addr = *in4;
616 add_to_address_list (h, src, (const struct sockaddr *) &s4,
617 sizeof (struct sockaddr_in));
618 if (GNUNET_YES == h->enable_nat_server)
619 {
620 /* also add with PORT = 0 to indicate NAT server is enabled */
621 s4.sin_port = htons (0);
622 add_to_address_list (h, src, (const struct sockaddr *) &s4,
623 sizeof (struct sockaddr_in));
624
625 }
626 }
627 else if (addrlen == sizeof (struct in6_addr))
628 {
629 if (GNUNET_YES != h->disable_ipv6)
630 {
631 in6 = (const struct in6_addr *) addr;
632 memset (&s6, 0, sizeof (s6));
633 s6.sin6_family = AF_INET6;
634 s6.sin6_port = htons (h->adv_port);
635#if HAVE_SOCKADDR_IN_SIN_LEN
636 s6.sin6_len = (u_char) sizeof (struct sockaddr_in6);
637#endif
638 s6.sin6_addr = *in6;
639 add_to_address_list (h, src, (const struct sockaddr *) &s6,
640 sizeof (struct sockaddr_in6));
641 }
642 }
643 else
644 {
645 GNUNET_assert (0);
646 }
647}
648
649
650/**
651 * Task to do DNS lookup on our external hostname to
652 * get DynDNS-IP addresses.
653 *
654 * @param cls the NAT handle
655 */
656static void
657resolve_dns (void *cls);
658
659
660/**
661 * Our (external) hostname was resolved and the configuration says that
662 * the NAT was hole-punched.
663 *
664 * @param cls the `struct GNUNET_NAT_Handle`
665 * @param addr NULL on error, otherwise result of DNS lookup
666 * @param addrlen number of bytes in @a addr
667 */
668static void
669process_external_ip (void *cls,
670 const struct sockaddr *addr,
671 socklen_t addrlen)
672{
673 struct GNUNET_NAT_Handle *h = cls;
674 struct in_addr dummy;
675
676 if (NULL == addr)
677 {
678 h->ext_dns = NULL;
679 /* Current iteration is over, remove 'old' IPs now */
680 LOG (GNUNET_ERROR_TYPE_DEBUG,
681 "Purging old IPs for external address\n");
682 remove_from_address_list_by_source (h,
683 LAL_EXTERNAL_IP_OLD);
684 if (1 == inet_pton (AF_INET,
685 h->external_address,
686 &dummy))
687 {
688 LOG (GNUNET_ERROR_TYPE_DEBUG,
689 "Got numeric IP for external address, not repeating lookup\n");
690 return; /* repated lookup pointless: was numeric! */
691 }
692 h->dns_task =
693 GNUNET_SCHEDULER_add_delayed (h->dyndns_frequency,
694 &resolve_dns, h);
695 return;
696 }
697 LOG (GNUNET_ERROR_TYPE_DEBUG,
698 "Got IP `%s' for external address `%s'\n",
699 GNUNET_a2s (addr,
700 addrlen),
701 h->external_address);
702 add_to_address_list (h,
703 LAL_EXTERNAL_IP,
704 addr,
705 addrlen);
706}
707
708
709/**
710 * Task to do a lookup on our hostname for IP addresses.
711 *
712 * @param cls the NAT handle
713 */
714static void
715resolve_hostname (void *cls);
716
717
718/**
719 * Function called by the resolver for each address obtained from DNS
720 * for our own hostname. Add the addresses to the list of our IP
721 * addresses.
722 *
723 * @param cls closure
724 * @param addr one of the addresses of the host, NULL for the last address
725 * @param addrlen length of the @a addr
726 */
727static void
728process_hostname_ip (void *cls,
729 const struct sockaddr *addr,
730 socklen_t addrlen)
731{
732 struct GNUNET_NAT_Handle *h = cls;
733
734 if (NULL == addr)
735 {
736 h->hostname_dns = NULL;
737 h->hostname_task =
738 GNUNET_SCHEDULER_add_delayed (h->hostname_dns_frequency,
739 &resolve_hostname,
740 h);
741 return;
742 }
743 add_to_address_list (h,
744 LAL_HOSTNAME_DNS,
745 addr,
746 addrlen);
747}
748
749
750/**
751 * Length of the interface names returned from os_network.c.
752 * (in that file, hardcoded at 11).
753 */
754#define IF_NAME_LEN 11
755
756
757/**
758 * Add the IP of our network interface to the list of
759 * our IP addresses.
760 *
761 * @param cls the `struct GNUNET_NAT_Handle`
762 * @param name name of the interface
763 * @param isDefault do we think this may be our default interface
764 * @param addr address of the interface
765 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
766 * @param netmask the network mask (can be NULL for unknown or unassigned))
767 * @param addrlen number of bytes in @a addr and @a broadcast_addr
768 * @return #GNUNET_OK to continue iterating
769 */
770static int
771process_interfaces (void *cls,
772 const char *name,
773 int isDefault,
774 const struct sockaddr *addr,
775 const struct sockaddr *broadcast_addr,
776 const struct sockaddr *netmask,
777 socklen_t addrlen)
778{
779 const static struct in6_addr any6 = IN6ADDR_ANY_INIT;
780 struct GNUNET_NAT_Handle *h = cls;
781 const struct sockaddr_in *s4;
782 const struct sockaddr_in6 *s6;
783 const void *ip;
784 char buf[INET6_ADDRSTRLEN];
785 unsigned int i;
786 int have_any;
787 char *tun_if;
788
789 /* skip virtual interfaces created by GNUnet-vpn */
790 if (GNUNET_OK ==
791 GNUNET_CONFIGURATION_get_value_string (h->cfg,
792 "vpn",
793 "IFNAME",
794 &tun_if))
795 {
796 if (0 == strncasecmp (name,
797 tun_if,
798 IF_NAME_LEN))
799 {
800 GNUNET_free (tun_if);
801 return GNUNET_OK;
802 }
803 GNUNET_free (tun_if);
804 }
805 /* skip virtual interfaces created by GNUnet-dns */
806 if (GNUNET_OK ==
807 GNUNET_CONFIGURATION_get_value_string (h->cfg,
808 "dns",
809 "IFNAME",
810 &tun_if))
811 {
812 if (0 == strncasecmp (name,
813 tun_if,
814 IF_NAME_LEN))
815 {
816 GNUNET_free (tun_if);
817 return GNUNET_OK;
818 }
819 GNUNET_free (tun_if);
820 }
821 /* skip virtual interfaces created by GNUnet-exit */
822 if (GNUNET_OK ==
823 GNUNET_CONFIGURATION_get_value_string (h->cfg,
824 "exit",
825 "TUN_IFNAME",
826 &tun_if))
827 {
828 if (0 == strncasecmp (name,
829 tun_if,
830 IF_NAME_LEN))
831 {
832 GNUNET_free (tun_if);
833 return GNUNET_OK;
834 }
835 GNUNET_free (tun_if);
836 }
837
838 switch (addr->sa_family)
839 {
840 case AF_INET:
841 /* check if we're bound to the "ANY" IP address */
842 have_any = GNUNET_NO;
843 for (i=0;i<h->num_local_addrs;i++)
844 {
845 if (h->local_addrs[i]->sa_family != AF_INET)
846 continue;
847#ifndef INADDR_ANY
848#define INADDR_ANY 0
849#endif
850 if (INADDR_ANY == ((struct sockaddr_in*) h->local_addrs[i])->sin_addr.s_addr)
851 {
852 have_any = GNUNET_YES;
853 break;
854 }
855 }
856 if (GNUNET_NO == have_any)
857 return GNUNET_OK; /* not bound to IP 0.0.0.0 but to specific IP addresses,
858 do not use those from interfaces */
859 s4 = (struct sockaddr_in *) addr;
860 ip = &s4->sin_addr;
861
862 /* Check if address is in 127.0.0.0/8 */
863 uint32_t address = ntohl ((uint32_t) (s4->sin_addr.s_addr));
864 uint32_t value = (address & 0xFF000000) ^ 0x7F000000;
865
866 if ((h->return_localaddress == GNUNET_NO) && (value == 0))
867 {
868 return GNUNET_OK;
869 }
870 if ((GNUNET_YES == h->use_localaddresses) || (value != 0))
871 {
872 add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s4->sin_addr,
873 sizeof (struct in_addr));
874 }
875 break;
876 case AF_INET6:
877 /* check if we're bound to the "ANY" IP address */
878 have_any = GNUNET_NO;
879 for (i=0;i<h->num_local_addrs;i++)
880 {
881 if (h->local_addrs[i]->sa_family != AF_INET6)
882 continue;
883 if (0 == memcmp (&any6,
884 &((struct sockaddr_in6*) h->local_addrs[i])->sin6_addr,
885 sizeof (struct in6_addr)))
886 {
887 have_any = GNUNET_YES;
888 break;
889 }
890 }
891 if (GNUNET_NO == have_any)
892 return GNUNET_OK; /* not bound to "ANY" IP (::0) but to specific IP addresses,
893 do not use those from interfaces */
894
895 s6 = (struct sockaddr_in6 *) addr;
896 if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
897 {
898 /* skip link local addresses */
899 return GNUNET_OK;
900 }
901 if ((h->return_localaddress == GNUNET_NO) &&
902 (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr)))
903 {
904 return GNUNET_OK;
905 }
906 ip = &s6->sin6_addr;
907 if (GNUNET_YES == h->use_localaddresses)
908 {
909 add_ip_to_address_list (h, LAL_INTERFACE_ADDRESS, &s6->sin6_addr,
910 sizeof (struct in6_addr));
911 }
912 break;
913 default:
914 GNUNET_break (0);
915 return GNUNET_OK;
916 }
917 if ( (h->internal_address == NULL) &&
918 (h->server_proc == NULL) &&
919 (h->server_read_task == NULL) &&
920 (GNUNET_YES == isDefault) &&
921 ( (addr->sa_family == AF_INET) ||
922 (addr->sa_family == AF_INET6) ) )
923 {
924 /* no internal address configured, but we found a "default"
925 * interface, try using that as our 'internal' address */
926 h->internal_address =
927 GNUNET_strdup (inet_ntop (addr->sa_family, ip, buf, sizeof (buf)));
928 start_gnunet_nat_server (h);
929 }
930 return GNUNET_OK;
931}
932
933
934/**
935 * Task that restarts the gnunet-helper-nat-server process after a crash
936 * after a certain delay.
937 *
938 * @param cls the `struct GNUNET_NAT_Handle`
939 */
940static void
941restart_nat_server (void *cls)
942{
943 struct GNUNET_NAT_Handle *h = cls;
944
945 h->server_read_task = NULL;
946 start_gnunet_nat_server (h);
947}
948
949
950/**
951 * We have been notified that gnunet-helper-nat-server has written
952 * something to stdout. Handle the output, then reschedule this
953 * function to be called again once more is available.
954 *
955 * @param cls the NAT handle
956 */
957static void
958nat_server_read (void *cls)
959{
960 struct GNUNET_NAT_Handle *h = cls;
961 char mybuf[40];
962 ssize_t bytes;
963 size_t i;
964 int port;
965 const char *port_start;
966 struct sockaddr_in sin_addr;
967
968 h->server_read_task = NULL;
969 memset (mybuf, 0, sizeof (mybuf));
970 bytes =
971 GNUNET_DISK_file_read (h->server_stdout_handle, mybuf, sizeof (mybuf));
972 if (bytes < 1)
973 {
974 LOG (GNUNET_ERROR_TYPE_DEBUG,
975 "Finished reading from server stdout with code: %d\n",
976 bytes);
977 if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG))
978 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill");
979 GNUNET_OS_process_wait (h->server_proc);
980 GNUNET_OS_process_destroy (h->server_proc);
981 h->server_proc = NULL;
982 GNUNET_DISK_pipe_close (h->server_stdout);
983 h->server_stdout = NULL;
984 h->server_stdout_handle = NULL;
985 /* now try to restart it */
986 h->server_retry_delay = GNUNET_TIME_STD_BACKOFF (h->server_retry_delay);
987 h->server_read_task =
988 GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
989 &restart_nat_server, h);
990 return;
991 }
992
993 port_start = NULL;
994 for (i = 0; i < sizeof (mybuf); i++)
995 {
996 if (mybuf[i] == '\n')
997 {
998 mybuf[i] = '\0';
999 break;
1000 }
1001 if ((mybuf[i] == ':') && (i + 1 < sizeof (mybuf)))
1002 {
1003 mybuf[i] = '\0';
1004 port_start = &mybuf[i + 1];
1005 }
1006 }
1007
1008 /* construct socket address of sender */
1009 memset (&sin_addr, 0, sizeof (sin_addr));
1010 sin_addr.sin_family = AF_INET;
1011#if HAVE_SOCKADDR_IN_SIN_LEN
1012 sin_addr.sin_len = sizeof (sin_addr);
1013#endif
1014 if ((NULL == port_start) || (1 != SSCANF (port_start, "%d", &port)) ||
1015 (-1 == inet_pton (AF_INET, mybuf, &sin_addr.sin_addr)))
1016 {
1017 /* should we restart gnunet-helper-nat-server? */
1018 LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
1019 _("gnunet-helper-nat-server generated malformed address `%s'\n"),
1020 mybuf);
1021 h->server_read_task =
1022 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1023 h->server_stdout_handle,
1024 &nat_server_read, h);
1025 return;
1026 }
1027 sin_addr.sin_port = htons ((uint16_t) port);
1028 LOG (GNUNET_ERROR_TYPE_DEBUG, "gnunet-helper-nat-server read: %s:%d\n", mybuf,
1029 port);
1030 h->reversal_callback (h->callback_cls, (const struct sockaddr *) &sin_addr,
1031 sizeof (sin_addr));
1032 h->server_read_task =
1033 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1034 h->server_stdout_handle,
1035 &nat_server_read,
1036 h);
1037}
1038
1039
1040/**
1041 * Try to start the gnunet-helper-nat-server (if it is not
1042 * already running).
1043 *
1044 * @param h handle to NAT
1045 */
1046static void
1047start_gnunet_nat_server (struct GNUNET_NAT_Handle *h)
1048{
1049 char *binary;
1050
1051 if ((h->behind_nat == GNUNET_YES) && (h->enable_nat_server == GNUNET_YES) &&
1052 (h->internal_address != NULL) &&
1053 (NULL !=
1054 (h->server_stdout =
1055 GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES))))
1056 {
1057 LOG (GNUNET_ERROR_TYPE_DEBUG,
1058 "Starting `%s' at `%s'\n",
1059 "gnunet-helper-nat-server", h->internal_address);
1060 /* Start the server process */
1061 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
1062 h->server_proc =
1063 GNUNET_OS_start_process (GNUNET_NO, 0, NULL, h->server_stdout, NULL,
1064 binary,
1065 "gnunet-helper-nat-server",
1066 h->internal_address, NULL);
1067 GNUNET_free (binary);
1068 if (h->server_proc == NULL)
1069 {
1070 LOG (GNUNET_ERROR_TYPE_WARNING, "nat", _("Failed to start %s\n"),
1071 "gnunet-helper-nat-server");
1072 GNUNET_DISK_pipe_close (h->server_stdout);
1073 h->server_stdout = NULL;
1074 }
1075 else
1076 {
1077 /* Close the write end of the read pipe */
1078 GNUNET_DISK_pipe_close_end (h->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
1079 h->server_stdout_handle =
1080 GNUNET_DISK_pipe_handle (h->server_stdout, GNUNET_DISK_PIPE_END_READ);
1081 h->server_read_task =
1082 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1083 h->server_stdout_handle,
1084 &nat_server_read, h);
1085 }
1086 }
1087}
1088
1089
1090/**
1091 * Task to scan the local network interfaces for IP addresses.
1092 *
1093 * @param cls the NAT handle
1094 */
1095static void
1096list_interfaces (void *cls)
1097{
1098 struct GNUNET_NAT_Handle *h = cls;
1099
1100 h->ifc_task = NULL;
1101 remove_from_address_list_by_source (h, LAL_INTERFACE_ADDRESS);
1102 GNUNET_OS_network_interfaces_list (&process_interfaces, h);
1103 h->ifc_task =
1104 GNUNET_SCHEDULER_add_delayed (h->ifc_scan_frequency,
1105 &list_interfaces, h);
1106}
1107
1108
1109/**
1110 * Callback with the result from the STUN request.
1111 *
1112 * @param cls the NAT handle
1113 * @param result the status
1114 */
1115static void
1116stun_request_callback (void *cls,
1117 enum GNUNET_NAT_StatusCode result)
1118{
1119 struct GNUNET_NAT_Handle *h = cls;
1120
1121 h->stun_request = NULL;
1122 switch (result)
1123 {
1124 case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR:
1125 LOG (GNUNET_ERROR_TYPE_WARNING,
1126 "Failed to transmit STUN request\n");
1127 break;
1128 case GNUNET_NAT_ERROR_NOT_ONLINE:
1129 LOG (GNUNET_ERROR_TYPE_WARNING,
1130 "Failed to resolve STUN server (are we online?)\n");
1131 break;
1132 case GNUNET_NAT_ERROR_SUCCESS:
1133 /* all good, STUN request active */
1134 h->waiting_stun = GNUNET_YES;
1135 break;
1136 default:
1137 /* unexpected error code for STUN */
1138 GNUNET_break (0);
1139 }
1140}
1141
1142
1143/**
1144 * CHECK if is a valid STUN packet sending to GNUNET_NAT_stun_handle_packet().
1145 * It also check if it can handle the packet based on the NAT handler.
1146 * You don't need to call anything else to check if the packet is valid,
1147 *
1148 * @param cls the NAT handle
1149 * @param data packet
1150 * @param len packet length
1151 * @return #GNUNET_NO if it can't decode, #GNUNET_YES if is a packet
1152 */
1153int
1154GNUNET_NAT_is_valid_stun_packet (void *cls,
1155 const void *data,
1156 size_t len)
1157{
1158 struct GNUNET_NAT_Handle *h = cls;
1159 struct sockaddr_in answer;
1160
1161 /* We are not expecting a STUN message */
1162 if (GNUNET_YES != h->waiting_stun)
1163 return GNUNET_NO;
1164
1165 /* We dont have STUN installed */
1166 if (! h->use_stun)
1167 return GNUNET_NO;
1168
1169 /* Empty the answer structure */
1170 memset (&answer,
1171 0,
1172 sizeof(struct sockaddr_in));
1173
1174 /* Lets handle the packet*/
1175 if (GNUNET_NO ==
1176 GNUNET_NAT_stun_handle_packet (data,
1177 len,
1178 &answer))
1179 return GNUNET_NO;
1180
1181 LOG (GNUNET_ERROR_TYPE_INFO,
1182 "STUN server returned %s:%d\n",
1183 inet_ntoa (answer.sin_addr),
1184 ntohs (answer.sin_port));
1185 /* Remove old IPs from previous STUN calls */
1186 remove_from_address_list_by_source (h,
1187 LAL_EXTERNAL_STUN_IP);
1188 /* Add new IP from STUN packet */
1189 add_to_address_list (h,
1190 LAL_EXTERNAL_STUN_IP,
1191 (const struct sockaddr *) &answer,
1192 sizeof (struct sockaddr_in));
1193 h->waiting_stun = GNUNET_NO;
1194 return GNUNET_YES;
1195}
1196
1197
1198/**
1199 * Task to do a STUN request
1200 *
1201 * @param cls the NAT handle
1202 */
1203static void
1204process_stun (void *cls)
1205{
1206 struct GNUNET_NAT_Handle *h = cls;
1207 struct StunServerList *elem = h->actual_stun_server;
1208
1209 h->stun_task = NULL;
1210 /* Make the request */
1211 LOG (GNUNET_ERROR_TYPE_INFO,
1212 "I will request the stun server %s:%i\n",
1213 elem->address,
1214 elem->port);
1215 if (NULL != h->stun_request)
1216 {
1217 GNUNET_NAT_stun_make_request_cancel (h->stun_request);
1218 h->stun_request = NULL;
1219 }
1220 h->waiting_stun = GNUNET_NO;
1221 h->stun_request
1222 = GNUNET_NAT_stun_make_request (elem->address,
1223 elem->port,
1224 h->socket,
1225 &stun_request_callback,
1226 h);
1227 if (NULL == h->stun_request)
1228 {
1229 LOG (GNUNET_ERROR_TYPE_ERROR,
1230 "STUN request to %s:%i failed\n",
1231 elem->address,
1232 elem->port);
1233 }
1234 h->stun_task =
1235 GNUNET_SCHEDULER_add_delayed (h->stun_frequency,
1236 &process_stun,
1237 h);
1238
1239 /* Set actual Server*/
1240 if (NULL != elem->next)
1241 {
1242 h->actual_stun_server = elem->next;
1243 }
1244 else
1245 {
1246 h->actual_stun_server = h->stun_servers_head;
1247 }
1248}
1249
1250
1251/**
1252 * Task to do a lookup on our hostname for IP addresses.
1253 *
1254 * @param cls the NAT handle
1255 */
1256static void
1257resolve_hostname (void *cls)
1258{
1259 struct GNUNET_NAT_Handle *h = cls;
1260
1261 h->hostname_task = NULL;
1262 remove_from_address_list_by_source (h, LAL_HOSTNAME_DNS);
1263 GNUNET_assert (NULL == h->hostname_dns);
1264 h->hostname_dns =
1265 GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC,
1266 HOSTNAME_RESOLVE_TIMEOUT,
1267 &process_hostname_ip,
1268 h);
1269}
1270
1271
1272/**
1273 * Task to do DNS lookup on our external hostname to
1274 * get DynDNS-IP addresses.
1275 *
1276 * @param cls the NAT handle
1277 */
1278static void
1279resolve_dns (void *cls)
1280{
1281 struct GNUNET_NAT_Handle *h = cls;
1282 struct LocalAddressList *pos;
1283
1284 h->dns_task = NULL;
1285 for (pos = h->lal_head; NULL != pos; pos = pos->next)
1286 if (pos->source == LAL_EXTERNAL_IP)
1287 pos->source = LAL_EXTERNAL_IP_OLD;
1288 LOG (GNUNET_ERROR_TYPE_DEBUG,
1289 "Resolving external address `%s'\n",
1290 h->external_address);
1291 GNUNET_assert (NULL == h->ext_dns);
1292 h->ext_dns =
1293 GNUNET_RESOLVER_ip_get (h->external_address,
1294 AF_INET,
1295 GNUNET_TIME_UNIT_MINUTES,
1296 &process_external_ip,
1297 h);
1298}
1299
1300
1301/**
1302 * Add or remove UPnP-mapped addresses.
1303 *
1304 * @param cls the `struct GNUNET_NAT_Handle`
1305 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
1306 * the previous (now invalid) one
1307 * @param addr either the previous or the new public IP address
1308 * @param addrlen actual lenght of @a addr
1309 * @param ret GNUNET_NAT_ERROR_SUCCESS on success, otherwise an error code
1310 */
1311static void
1312upnp_add (void *cls,
1313 int add_remove,
1314 const struct sockaddr *addr,
1315 socklen_t addrlen,
1316 enum GNUNET_NAT_StatusCode ret)
1317{
1318 struct GNUNET_NAT_Handle *h = cls;
1319 struct LocalAddressList *pos;
1320 struct LocalAddressList *next;
1321
1322
1323 if (GNUNET_NAT_ERROR_SUCCESS != ret)
1324 {
1325 /* Error while running upnp client */
1326 LOG (GNUNET_ERROR_TYPE_ERROR,
1327 _("Error while running upnp client:\n"));
1328 //FIXME: convert error code to string
1329 return;
1330 }
1331
1332 if (GNUNET_YES == add_remove)
1333 {
1334 add_to_address_list (h,
1335 LAL_UPNP,
1336 addr,
1337 addrlen);
1338 return;
1339 }
1340 else if (GNUNET_NO == add_remove)
1341 {
1342 /* remove address */
1343 next = h->lal_head;
1344 while (NULL != (pos = next))
1345 {
1346 next = pos->next;
1347 if ((pos->source != LAL_UPNP) || (pos->addrlen != addrlen) ||
1348 (0 != memcmp (&pos[1], addr, addrlen)))
1349 continue;
1350 GNUNET_CONTAINER_DLL_remove (h->lal_head,
1351 h->lal_tail,
1352 pos);
1353 if (NULL != h->address_callback)
1354 h->address_callback (h->callback_cls,
1355 GNUNET_NO,
1356 (const struct sockaddr *) &pos[1],
1357 pos->addrlen);
1358 GNUNET_free (pos);
1359 return; /* only remove once */
1360 }
1361 /* asked to remove address that does not exist */
1362 LOG (GNUNET_ERROR_TYPE_ERROR,
1363 "Asked to remove unkown address `%s'\n",
1364 GNUNET_a2s(addr, addrlen));
1365 GNUNET_break (0);
1366 }
1367 else
1368 {
1369
1370 GNUNET_break (0);
1371 }
1372}
1373
1374
1375/**
1376 * Try to add a port mapping using UPnP.
1377 *
1378 * @param h overall NAT handle
1379 * @param port port to map with UPnP
1380 */
1381static void
1382add_minis (struct GNUNET_NAT_Handle *h,
1383 uint16_t port)
1384{
1385 struct MiniList *ml;
1386
1387 ml = h->mini_head;
1388 while (NULL != ml)
1389 {
1390 if (port == ml->port)
1391 return; /* already got this port */
1392 ml = ml->next;
1393 }
1394
1395 ml = GNUNET_new (struct MiniList);
1396 ml->port = port;
1397 ml->mini = GNUNET_NAT_mini_map_start (port, h->is_tcp, &upnp_add, h);
1398
1399 if (NULL == ml->mini)
1400 {
1401 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1402 _("Failed to run upnp client for port %u\n"), ml->port);
1403 GNUNET_free (ml);
1404 return;
1405 }
1406
1407 GNUNET_CONTAINER_DLL_insert (h->mini_head,
1408 h->mini_tail,
1409 ml);
1410}
1411
1412
1413/**
1414 * Task to add addresses from original bind to set of valid addrs.
1415 *
1416 * @param h the NAT handle
1417 */
1418static void
1419add_from_bind (struct GNUNET_NAT_Handle *h)
1420{
1421 static struct in6_addr any = IN6ADDR_ANY_INIT;
1422
1423 unsigned int i;
1424 struct sockaddr *sa;
1425 const struct sockaddr_in *v4;
1426
1427 for (i = 0; i < h->num_local_addrs; i++)
1428 {
1429 sa = h->local_addrs[i];
1430 switch (sa->sa_family)
1431 {
1432 case AF_INET:
1433 if (sizeof (struct sockaddr_in) != h->local_addrlens[i])
1434 {
1435 GNUNET_break (0);
1436 break;
1437 }
1438 v4 = (const struct sockaddr_in *) sa;
1439 if (0 != v4->sin_addr.s_addr)
1440 add_to_address_list (h,
1441 LAL_BINDTO_ADDRESS, sa,
1442 sizeof (struct sockaddr_in));
1443 if (h->enable_upnp)
1444 {
1445 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1446 "Running upnp client for address `%s'\n",
1447 GNUNET_a2s (sa,sizeof (struct sockaddr_in)));
1448 add_minis (h, ntohs (v4->sin_port));
1449 }
1450 break;
1451 case AF_INET6:
1452 if (sizeof (struct sockaddr_in6) != h->local_addrlens[i])
1453 {
1454 GNUNET_break (0);
1455 break;
1456 }
1457 if (0 !=
1458 memcmp (&((const struct sockaddr_in6 *) sa)->sin6_addr,
1459 &any,
1460 sizeof (struct in6_addr)))
1461 add_to_address_list (h,
1462 LAL_BINDTO_ADDRESS,
1463 sa,
1464 sizeof (struct sockaddr_in6));
1465 break;
1466 default:
1467 break;
1468 }
1469 }
1470}
1471
1472
1473/**
1474 * Attempt to enable port redirection and detect public IP address contacting
1475 * UPnP or NAT-PMP routers on the local network. Use addr to specify to which
1476 * of the local host's addresses should the external port be mapped. The port
1477 * is taken from the corresponding sockaddr_in[6] field.
1478 *
1479 * @param cfg configuration to use
1480 * @param is_tcp #GNUNET_YES for TCP, #GNUNET_NO for UDP
1481 * @param adv_port advertised port (port we are either bound to or that our OS
1482 * locally performs redirection from to our bound port).
1483 * @param num_addrs number of addresses in @a addrs
1484 * @param addrs the local addresses packets should be redirected to
1485 * @param addrlens actual lengths of the addresses
1486 * @param address_callback function to call everytime the public IP address changes
1487 * @param reversal_callback function to call if someone wants connection reversal from us
1488 * @param callback_cls closure for callbacks
1489 * @param sock used socket
1490 * @return NULL on error, otherwise handle that can be used to unregister
1491 */
1492struct GNUNET_NAT_Handle *
1493GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg,
1494 int is_tcp,
1495 uint16_t adv_port,
1496 unsigned int num_addrs,
1497 const struct sockaddr **addrs,
1498 const socklen_t *addrlens,
1499 GNUNET_NAT_AddressCallback address_callback,
1500 GNUNET_NAT_ReversalCallback reversal_callback,
1501 void *callback_cls,
1502 struct GNUNET_NETWORK_Handle *sock)
1503{
1504 struct GNUNET_NAT_Handle *h;
1505 struct in_addr in_addr;
1506 unsigned int i;
1507 char *binary;
1508
1509 LOG (GNUNET_ERROR_TYPE_DEBUG,
1510 "Registered with NAT service at port %u with %u IP bound local addresses\n",
1511 (unsigned int) adv_port, num_addrs);
1512 h = GNUNET_new (struct GNUNET_NAT_Handle);
1513 h->server_retry_delay = GNUNET_TIME_UNIT_SECONDS;
1514 h->cfg = cfg;
1515 h->is_tcp = is_tcp;
1516 h->address_callback = address_callback;
1517 h->reversal_callback = reversal_callback;
1518 h->callback_cls = callback_cls;
1519 h->num_local_addrs = num_addrs;
1520 h->adv_port = adv_port;
1521 if (0 != num_addrs)
1522 {
1523 h->local_addrs = GNUNET_malloc (num_addrs * sizeof (struct sockaddr *));
1524 h->local_addrlens = GNUNET_malloc (num_addrs * sizeof (socklen_t));
1525 for (i = 0; i < num_addrs; i++)
1526 {
1527 GNUNET_assert (addrlens[i] > 0);
1528 GNUNET_assert (addrs[i] != NULL);
1529 h->local_addrlens[i] = addrlens[i];
1530 h->local_addrs[i] = GNUNET_malloc (addrlens[i]);
1531 GNUNET_memcpy (h->local_addrs[i], addrs[i], addrlens[i]);
1532 }
1533 }
1534 if (GNUNET_OK ==
1535 GNUNET_CONFIGURATION_have_value (cfg, "nat", "INTERNAL_ADDRESS"))
1536 {
1537 (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1538 "INTERNAL_ADDRESS",
1539 &h->internal_address);
1540 }
1541 if ((h->internal_address != NULL) &&
1542 (inet_pton (AF_INET, h->internal_address, &in_addr) != 1))
1543 {
1544 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1545 "nat", "INTERNAL_ADDRESS",
1546 _("malformed"));
1547 GNUNET_free (h->internal_address);
1548 h->internal_address = NULL;
1549 }
1550
1551 if (GNUNET_OK ==
1552 GNUNET_CONFIGURATION_have_value (cfg, "nat", "EXTERNAL_ADDRESS"))
1553 {
1554 (void) GNUNET_CONFIGURATION_get_value_string (cfg, "nat",
1555 "EXTERNAL_ADDRESS",
1556 &h->external_address);
1557 }
1558 h->behind_nat =
1559 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "BEHIND_NAT");
1560 h->nat_punched =
1561 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "PUNCHED_NAT");
1562 h->enable_nat_client =
1563 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_CLIENT");
1564 h->enable_nat_server =
1565 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_ICMP_SERVER");
1566 h->enable_upnp =
1567 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "ENABLE_UPNP");
1568 h->use_localaddresses =
1569 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_LOCALADDR");
1570 h->return_localaddress =
1571 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat",
1572 "RETURN_LOCAL_ADDRESSES");
1573
1574 h->use_hostname =
1575 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "USE_HOSTNAME");
1576 h->disable_ipv6 =
1577 GNUNET_CONFIGURATION_get_value_yesno (cfg, "nat", "DISABLEV6");
1578 if (GNUNET_OK !=
1579 GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "DYNDNS_FREQUENCY",
1580 &h->dyndns_frequency))
1581 h->dyndns_frequency = DYNDNS_FREQUENCY;
1582 if (GNUNET_OK !=
1583 GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "IFC_SCAN_FREQUENCY",
1584 &h->ifc_scan_frequency))
1585 h->ifc_scan_frequency = IFC_SCAN_FREQUENCY;
1586 if (GNUNET_OK !=
1587 GNUNET_CONFIGURATION_get_value_time (cfg, "nat", "HOSTNAME_DNS_FREQUENCY",
1588 &h->hostname_dns_frequency))
1589 h->hostname_dns_frequency = HOSTNAME_DNS_FREQUENCY;
1590
1591 if (NULL == reversal_callback)
1592 h->enable_nat_server = GNUNET_NO;
1593
1594 /* Check for UPnP client, disable immediately if not available */
1595 if ( (GNUNET_YES == h->enable_upnp) &&
1596 (GNUNET_SYSERR ==
1597 GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL)) )
1598 {
1599 LOG (GNUNET_ERROR_TYPE_ERROR,
1600 _("UPnP enabled in configuration, but UPnP client `upnpc` command not found, disabling UPnP \n"));
1601 h->enable_upnp = GNUNET_NO;
1602 }
1603
1604 /* STUN */
1605 h->use_stun =
1606 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1607 "nat",
1608 "USE_STUN");
1609
1610 if (GNUNET_OK !=
1611 GNUNET_CONFIGURATION_get_value_time (cfg,
1612 "nat",
1613 "STUN_FREQUENCY",
1614 &h->stun_frequency))
1615 h->stun_frequency = STUN_FREQUENCY;
1616
1617
1618 /* Check if NAT was hole-punched */
1619 if ((NULL != h->address_callback) &&
1620 (NULL != h->external_address) &&
1621 (GNUNET_YES == h->nat_punched))
1622 {
1623 h->dns_task = GNUNET_SCHEDULER_add_now (&resolve_dns, h);
1624 h->enable_nat_server = GNUNET_NO;
1625 h->enable_upnp = GNUNET_NO;
1626 h->use_stun = GNUNET_NO;
1627 }
1628 else
1629 {
1630 LOG (GNUNET_ERROR_TYPE_DEBUG,
1631 "No external IP address given to add to our list of addresses\n");
1632 }
1633
1634 /* ENABLE STUN ONLY ON UDP */
1635 if( (! is_tcp) &&
1636 (NULL != sock) &&
1637 h->use_stun)
1638 {
1639 char *stun_servers;
1640 size_t urls;
1641 ssize_t pos;
1642 size_t pos_port;
1643
1644 h->socket = sock;
1645 stun_servers = NULL;
1646 /* Lets process the servers*/
1647 (void) GNUNET_CONFIGURATION_get_value_string (cfg,
1648 "nat",
1649 "STUN_SERVERS",
1650 &stun_servers);
1651 urls = 0;
1652 if ( (NULL != stun_servers) &&
1653 (strlen (stun_servers) > 0) )
1654 {
1655 pos_port = 0;
1656 for (pos = strlen (stun_servers) - 1;
1657 pos >= 0;
1658 pos--)
1659 {
1660 if (stun_servers[pos] == ':')
1661 {
1662 pos_port = pos + 1;
1663 stun_servers[pos] = '\0';
1664 continue;
1665 }
1666 if ((stun_servers[pos] == ' ') || (0 == pos))
1667 {
1668 struct StunServerList *ml;
1669
1670 /* Check if we do have a port */
1671 if ((0 == pos_port) || (pos_port <= pos))
1672 {
1673 LOG (GNUNET_ERROR_TYPE_WARNING,
1674 "STUN server format mistake\n");
1675 break;
1676 }
1677 urls++;
1678 ml = GNUNET_new (struct StunServerList);
1679 ml->port = atoi (&stun_servers[pos_port]);
1680
1681 /* Remove trailing space */
1682 if (stun_servers[pos] == ' ')
1683 ml->address = GNUNET_strdup (&stun_servers[pos + 1]);
1684 else
1685 ml->address = GNUNET_strdup (&stun_servers[pos]);
1686 LOG (GNUNET_ERROR_TYPE_DEBUG,
1687 "Found STUN server %s:%i\n",
1688 ml->address,
1689 ml->port);
1690 GNUNET_CONTAINER_DLL_insert (h->stun_servers_head,
1691 h->stun_servers_tail,
1692 ml);
1693 stun_servers[pos] = '\0';
1694 }
1695 }
1696 }
1697 if (0 == urls)
1698 {
1699 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
1700 "nat",
1701 "STUN_SERVERS");
1702 }
1703 else
1704 {
1705 /* Set the actual STUN server*/
1706 h->actual_stun_server = h->stun_servers_head;
1707 }
1708 h->stun_task = GNUNET_SCHEDULER_add_now (&process_stun,
1709 h);
1710 GNUNET_free_non_null (stun_servers);
1711 }
1712
1713
1714 /* Test for SUID binaries */
1715 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
1716 if ( (GNUNET_YES == h->behind_nat) &&
1717 (GNUNET_YES == h->enable_nat_server) &&
1718 (GNUNET_YES !=
1719 GNUNET_OS_check_helper_binary (binary,
1720 GNUNET_YES,
1721 "-d 127.0.0.1" )))
1722 {
1723 // use localhost as source for that one udp-port, ok for testing
1724 h->enable_nat_server = GNUNET_NO;
1725 LOG (GNUNET_ERROR_TYPE_WARNING,
1726 _("Configuration requires `%s', but binary is not installed properly (SUID bit not set). Option disabled.\n"),
1727 "gnunet-helper-nat-server");
1728 }
1729 GNUNET_free (binary);
1730 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1731 if ((GNUNET_YES == h->enable_nat_client) &&
1732 (GNUNET_YES !=
1733 GNUNET_OS_check_helper_binary (binary,
1734 GNUNET_YES,
1735 "-d 127.0.0.1 127.0.0.2 42"))) /* none of these parameters are actually used in privilege testing mode */
1736 {
1737 h->enable_nat_client = GNUNET_NO;
1738 LOG (GNUNET_ERROR_TYPE_WARNING,
1739 _("Configuration requires `%s', but binary is not installed properly (SUID bit not set). Option disabled.\n"),
1740 "gnunet-helper-nat-client");
1741 }
1742 GNUNET_free (binary);
1743 start_gnunet_nat_server (h);
1744
1745 /* FIXME: add support for UPnP, etc */
1746
1747 if (NULL != h->address_callback)
1748 {
1749 h->ifc_task = GNUNET_SCHEDULER_add_now (&list_interfaces,
1750 h);
1751 if (GNUNET_YES == h->use_hostname)
1752 h->hostname_task = GNUNET_SCHEDULER_add_now (&resolve_hostname,
1753 h);
1754 }
1755 add_from_bind (h);
1756
1757 return h;
1758}
1759
1760
1761/**
1762 * Stop port redirection and public IP address detection for the given handle.
1763 * This frees the handle, after having sent the needed commands to close open ports.
1764 *
1765 * @param h the handle to stop
1766 */
1767void
1768GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *h)
1769{
1770 unsigned int i;
1771 struct LocalAddressList *lal;
1772 struct MiniList *ml;
1773 struct StunServerList *ssl;
1774
1775 LOG (GNUNET_ERROR_TYPE_DEBUG,
1776 "NAT unregister called\n");
1777 while (NULL != (ssl = h->stun_servers_head))
1778 {
1779 GNUNET_CONTAINER_DLL_remove (h->stun_servers_head,
1780 h->stun_servers_tail,
1781 ssl);
1782 GNUNET_free (ssl->address);
1783 GNUNET_free (ssl);
1784 }
1785 while (NULL != (lal = h->lal_head))
1786 {
1787 GNUNET_CONTAINER_DLL_remove (h->lal_head,
1788 h->lal_tail,
1789 lal);
1790 if (NULL != h->address_callback)
1791 h->address_callback (h->callback_cls,
1792 GNUNET_NO,
1793 (const struct sockaddr *) &lal[1],
1794 lal->addrlen);
1795 GNUNET_free (lal);
1796 }
1797 while (NULL != (ml = h->mini_head))
1798 {
1799 GNUNET_CONTAINER_DLL_remove (h->mini_head,
1800 h->mini_tail,
1801 ml);
1802 if (NULL != ml->mini)
1803 GNUNET_NAT_mini_map_stop (ml->mini);
1804 GNUNET_free (ml);
1805 }
1806 if (NULL != h->ext_dns)
1807 {
1808 GNUNET_RESOLVER_request_cancel (h->ext_dns);
1809 h->ext_dns = NULL;
1810 }
1811 if (NULL != h->hostname_dns)
1812 {
1813 GNUNET_RESOLVER_request_cancel (h->hostname_dns);
1814 h->hostname_dns = NULL;
1815 }
1816 if (NULL != h->server_read_task)
1817 {
1818 GNUNET_SCHEDULER_cancel (h->server_read_task);
1819 h->server_read_task = NULL;
1820 }
1821 if (NULL != h->ifc_task)
1822 {
1823 GNUNET_SCHEDULER_cancel (h->ifc_task);
1824 h->ifc_task = NULL;
1825 }
1826 if (NULL != h->hostname_task)
1827 {
1828 GNUNET_SCHEDULER_cancel (h->hostname_task);
1829 h->hostname_task = NULL;
1830 }
1831 if (NULL != h->dns_task)
1832 {
1833 GNUNET_SCHEDULER_cancel (h->dns_task);
1834 h->dns_task = NULL;
1835 }
1836 if (NULL != h->stun_task)
1837 {
1838 GNUNET_SCHEDULER_cancel (h->stun_task);
1839 h->stun_task = NULL;
1840 }
1841 if (NULL != h->stun_request)
1842 {
1843 GNUNET_NAT_stun_make_request_cancel (h->stun_request);
1844 h->stun_request = NULL;
1845 }
1846 if (NULL != h->server_proc)
1847 {
1848 if (0 != GNUNET_OS_process_kill (h->server_proc,
1849 GNUNET_TERM_SIG))
1850 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
1851 "nat",
1852 "kill");
1853 GNUNET_OS_process_wait (h->server_proc);
1854 GNUNET_OS_process_destroy (h->server_proc);
1855 h->server_proc = NULL;
1856 GNUNET_DISK_pipe_close (h->server_stdout);
1857 h->server_stdout = NULL;
1858 h->server_stdout_handle = NULL;
1859 }
1860 if (NULL != h->server_stdout)
1861 {
1862 GNUNET_DISK_pipe_close (h->server_stdout);
1863 h->server_stdout = NULL;
1864 h->server_stdout_handle = NULL;
1865 }
1866 for (i = 0; i < h->num_local_addrs; i++)
1867 GNUNET_free (h->local_addrs[i]);
1868 GNUNET_free_non_null (h->local_addrs);
1869 GNUNET_free_non_null (h->local_addrlens);
1870 GNUNET_free_non_null (h->external_address);
1871 GNUNET_free_non_null (h->internal_address);
1872 GNUNET_free (h);
1873}
1874
1875
1876/**
1877 * We learned about a peer (possibly behind NAT) so run the
1878 * gnunet-helper-nat-client to send dummy ICMP responses to cause
1879 * that peer to connect to us (connection reversal).
1880 *
1881 * @param h handle (used for configuration)
1882 * @param sa the address of the peer (IPv4-only)
1883 * @return #GNUNET_SYSERR on error, #GNUNET_NO if nat client is disabled,
1884 * #GNUNET_OK otherwise
1885 */
1886int
1887GNUNET_NAT_run_client (struct GNUNET_NAT_Handle *h,
1888 const struct sockaddr_in *sa)
1889
1890
1891{
1892 char inet4[INET_ADDRSTRLEN];
1893 char port_as_string[6];
1894 struct GNUNET_OS_Process *proc;
1895 char *binary;
1896
1897 if (GNUNET_YES != h->enable_nat_client)
1898 return GNUNET_NO; /* not permitted / possible */
1899
1900 if (h->internal_address == NULL)
1901 {
1902 LOG (GNUNET_ERROR_TYPE_WARNING, "nat",
1903 _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1904 return GNUNET_SYSERR;
1905 }
1906 GNUNET_assert (sa->sin_family == AF_INET);
1907 if (NULL == inet_ntop (AF_INET, &sa->sin_addr, inet4, INET_ADDRSTRLEN))
1908 {
1909 GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
1910 "nat",
1911 "inet_ntop");
1912 return GNUNET_SYSERR;
1913 }
1914 GNUNET_snprintf (port_as_string,
1915 sizeof (port_as_string),
1916 "%d",
1917 h->adv_port);
1918 LOG (GNUNET_ERROR_TYPE_DEBUG,
1919 _("Running gnunet-helper-nat-client %s %s %u\n"),
1920 h->internal_address,
1921 inet4,
1922 (unsigned int) h->adv_port);
1923 binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
1924 proc =
1925 GNUNET_OS_start_process (GNUNET_NO, 0, NULL, NULL, NULL,
1926 binary,
1927 "gnunet-helper-nat-client",
1928 h->internal_address,
1929 inet4, port_as_string, NULL);
1930 GNUNET_free (binary);
1931 if (NULL == proc)
1932 return GNUNET_SYSERR;
1933 /* we know that the gnunet-helper-nat-client will terminate virtually
1934 * instantly */
1935 GNUNET_OS_process_wait (proc);
1936 GNUNET_OS_process_destroy (proc);
1937 return GNUNET_OK;
1938}
1939
1940
1941/**
1942 * Test if the given address is (currently) a plausible IP address for this peer.
1943 *
1944 * @param h the handle returned by register
1945 * @param addr IP address to test (IPv4 or IPv6)
1946 * @param addrlen number of bytes in @a addr
1947 * @return #GNUNET_YES if the address is plausible,
1948 * #GNUNET_NO if the address is not plausible,
1949 * #GNUNET_SYSERR if the address is malformed
1950 */
1951int
1952GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *h,
1953 const void *addr,
1954 socklen_t addrlen)
1955{
1956 struct LocalAddressList *pos;
1957 const struct sockaddr_in *in4;
1958 const struct sockaddr_in6 *in6;
1959 char pbuf[INET6_ADDRSTRLEN+1];
1960
1961 if ((addrlen != sizeof (struct in_addr)) &&
1962 (addrlen != sizeof (struct in6_addr)))
1963 {
1964 GNUNET_break (0);
1965 return GNUNET_SYSERR;
1966 }
1967 for (pos = h->lal_head; NULL != pos; pos = pos->next)
1968 {
1969 if (pos->addrlen == sizeof (struct sockaddr_in))
1970 {
1971 in4 = (struct sockaddr_in *) &pos[1];
1972 if ((addrlen == sizeof (struct in_addr)) &&
1973 (0 == memcmp (&in4->sin_addr, addr, sizeof (struct in_addr))))
1974 return GNUNET_YES;
1975 }
1976 else if (pos->addrlen == sizeof (struct sockaddr_in6))
1977 {
1978 in6 = (struct sockaddr_in6 *) &pos[1];
1979 if ((addrlen == sizeof (struct in6_addr)) &&
1980 (0 == memcmp (&in6->sin6_addr, addr, sizeof (struct in6_addr))))
1981 return GNUNET_YES;
1982 }
1983 else
1984 {
1985 GNUNET_assert (0);
1986 }
1987 }
1988 LOG (GNUNET_ERROR_TYPE_WARNING,
1989 "Asked to validate one of my addresses (%s) and validation failed!\n",
1990 inet_ntop ((addrlen == sizeof(struct in_addr))
1991 ? AF_INET
1992 : AF_INET6,
1993 addr,
1994 pbuf, sizeof (pbuf)));
1995 return GNUNET_NO;
1996}
1997
1998/**
1999 * Converts enum GNUNET_NAT_StatusCode to a string
2000 *
2001 * @param err error code to resolve to a string
2002 * @return pointer to a static string containing the error code
2003 */
2004const char *
2005GNUNET_NAT_status2string (enum GNUNET_NAT_StatusCode err)
2006{
2007 switch (err)
2008 {
2009 case GNUNET_NAT_ERROR_SUCCESS:
2010 return _ ("Operation Successful");
2011 case GNUNET_NAT_ERROR_IPC_FAILURE:
2012 return _ ("Internal Failure (IPC, ...)");
2013 case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR:
2014 return _ ("Failure in network subsystem, check permissions.");
2015 case GNUNET_NAT_ERROR_TIMEOUT:
2016 return _ ("Encountered timeout while performing operation");
2017 case GNUNET_NAT_ERROR_NOT_ONLINE:
2018 return _ ("detected that we are offline");
2019 case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND:
2020 return _ ("`upnpc` command not found");
2021 case GNUNET_NAT_ERROR_UPNPC_FAILED:
2022 return _ ("Failed to run `upnpc` command");
2023 case GNUNET_NAT_ERROR_UPNPC_TIMEOUT:
2024 return _ ("`upnpc' command took too long, process killed");
2025 case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED:
2026 return _ ("`upnpc' command failed to establish port mapping");
2027 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND:
2028 return _ ("`external-ip' command not found");
2029 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED:
2030 return _ ("Failed to run `external-ip` command");
2031 case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID:
2032 return _ ("`external-ip' command output invalid");
2033 case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID:
2034 return _ ("no valid address was returned by `external-ip'");
2035 case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO:
2036 return _ ("Could not determine interface with internal/local network address");
2037 case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND:
2038 return _ ("No functioning gnunet-helper-nat-server installation found");
2039 case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED:
2040 return _ ("NAT test could not be initialized");
2041 case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT:
2042 return _ ("NAT test timeout reached");
2043 case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED:
2044 return _ ("could not register NAT");
2045 case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND:
2046 return _ ("No working gnunet-helper-nat-client installation found");
2047/* case:
2048 return _ ("");*/
2049 default:
2050 return "unknown status code";
2051 }
2052}
2053
2054/* end of nat.c */
diff --git a/src/nat/nat_auto.c b/src/nat/nat_auto.c
deleted file mode 100644
index 061d0cbe6..000000000
--- a/src/nat/nat_auto.c
+++ /dev/null
@@ -1,1081 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2015 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file nat/nat_auto.c
23 * @brief functions for auto-configuration of the network
24 * @author Christian Grothoff
25 * @author Bruno Cabral
26 */
27#include "platform.h"
28#include "gnunet_util_lib.h"
29#include "gnunet_resolver_service.h"
30#include "gnunet_nat_lib.h"
31#include "nat.h"
32
33#define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
34
35
36/**
37 * How long do we wait for the NAT test to report success?
38 */
39#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
40
41#define NAT_SERVER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
42
43/**
44 * Phases of the auto configuration.
45 */
46enum AutoPhase
47{
48 /**
49 * Initial start value.
50 */
51 AUTO_INIT = 0,
52
53 /**
54 * Test our external IP.
55 */
56 AUTO_EXTERNAL_IP,
57
58 /**
59 * Test our external IP.
60 */
61 AUTO_STUN,
62
63 /**
64 * Test our internal IP.
65 */
66 AUTO_LOCAL_IP,
67
68 /**
69 * Test if NAT was punched.
70 */
71 AUTO_NAT_PUNCHED,
72
73 /**
74 * Test if UPnP is working.
75 */
76 AUTO_UPNPC,
77
78 /**
79 * Test if ICMP server works.
80 */
81 AUTO_ICMP_SERVER,
82
83 /**
84 * Test if ICMP client works.
85 */
86 AUTO_ICMP_CLIENT,
87
88 /**
89 * Last phase, we're done.
90 */
91 AUTO_DONE
92
93};
94
95
96/**
97 * Handle to auto-configuration in progress.
98 */
99struct GNUNET_NAT_AutoHandle
100{
101
102 /**
103 * Handle to the active NAT test.
104 */
105 struct GNUNET_NAT_Test *tst;
106
107 /**
108 * Function to call when done.
109 */
110 GNUNET_NAT_AutoResultCallback fin_cb;
111
112 /**
113 * Closure for @e fin_cb.
114 */
115 void *fin_cb_cls;
116
117 /**
118 * Handle for active 'GNUNET_NAT_mini_get_external_ipv4'-operation.
119 */
120 struct GNUNET_NAT_ExternalHandle *eh;
121
122 /**
123 * Current configuration (with updates from previous phases)
124 */
125 struct GNUNET_CONFIGURATION_Handle *cfg;
126
127 /**
128 * Original configuration (used to calculate differences)
129 */
130 struct GNUNET_CONFIGURATION_Handle *initial_cfg;
131
132 /**
133 * Task identifier for the timeout.
134 */
135 struct GNUNET_SCHEDULER_Task *task;
136
137 /**
138 * Message queue to the gnunet-nat-server.
139 */
140 struct GNUNET_MQ_Handle *mq;
141
142 /**
143 * Where are we in the test?
144 */
145 enum AutoPhase phase;
146
147 /**
148 * Situation of the NAT
149 */
150 enum GNUNET_NAT_Type type;
151
152 /**
153 * Do we have IPv6?
154 */
155 int have_v6;
156
157 /**
158 * UPnP already set the external ip address ?
159 */
160 int upnp_set_external_address;
161
162 /**
163 * Did the external server connected back ?
164 */
165 int connected_back;
166
167 /**
168 * Address detected by STUN
169 */
170 char *stun_ip;
171
172 unsigned int stun_port;
173
174 /**
175 * Internal IP is the same as the public one ?
176 */
177 int internal_ip_is_public;
178
179 /**
180 * Error code for better debugging and user feedback
181 */
182 enum GNUNET_NAT_StatusCode ret;
183};
184
185
186/**
187 * The listen socket of the service for IPv4
188 */
189static struct GNUNET_NETWORK_Handle *lsock4;
190
191/**
192 * The listen task ID for IPv4
193 */
194static struct GNUNET_SCHEDULER_Task *ltask4;
195
196/**
197 * The port the test service is running on (default 7895)
198 */
199static unsigned long long port = 7895;
200
201static char *stun_server = "stun.ekiga.net";
202
203static unsigned int stun_port = 3478;
204
205
206/**
207 * Run the next phase of the auto test.
208 *
209 * @param ah auto test handle
210 */
211static void
212next_phase (struct GNUNET_NAT_AutoHandle *ah);
213
214
215static void
216process_stun_reply(struct sockaddr_in *answer,
217 struct GNUNET_NAT_AutoHandle *ah)
218{
219 ah->stun_ip = inet_ntoa(answer->sin_addr);
220 ah->stun_port = ntohs (answer->sin_port);
221 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
222 "External IP is: %s , with port %u\n",
223 ah->stun_ip,
224 ah->stun_port);
225 next_phase (ah);
226}
227
228
229/**
230 * Function that terminates the test.
231 */
232static void
233stop_stun ()
234{
235 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
236 "Stopping STUN and quitting...\n");
237 /* Clean task */
238 if (NULL != ltask4)
239 {
240 GNUNET_SCHEDULER_cancel (ltask4);
241 ltask4 = NULL;
242 }
243 /* Clean socket */
244 if (NULL != lsock4)
245 {
246 GNUNET_NETWORK_socket_close (lsock4);
247 lsock4 = NULL;
248 }
249}
250
251
252/**
253 * Activity on our incoming socket. Read data from the
254 * incoming connection.
255 *
256 * @param cls
257 */
258static void
259do_udp_read (void *cls)
260{
261 struct GNUNET_NAT_AutoHandle *ah = cls;
262 unsigned char reply_buf[1024];
263 ssize_t rlen;
264 struct sockaddr_in answer;
265 const struct GNUNET_SCHEDULER_TaskContext *tc;
266
267 tc = GNUNET_SCHEDULER_get_task_context ();
268 if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
269 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
270 lsock4)))
271 {
272 rlen = GNUNET_NETWORK_socket_recv (lsock4,
273 reply_buf,
274 sizeof (reply_buf));
275
276 //Lets handle the packet
277 memset (&answer, 0, sizeof(struct sockaddr_in));
278 if (ah->phase == AUTO_NAT_PUNCHED)
279 {
280 //Destroy the connection
281 GNUNET_NETWORK_socket_close (lsock4);
282 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
283 "The external server was able to connect back");
284 ah->connected_back = GNUNET_YES;
285 next_phase (ah);
286 }
287 else
288 {
289 if (GNUNET_OK ==
290 GNUNET_NAT_stun_handle_packet (reply_buf, rlen, &answer))
291 {
292 //Process the answer
293 process_stun_reply (&answer, ah);
294 }
295 else
296 {
297 next_phase (ah);
298 }
299 }
300 }
301 else
302 {
303 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
304 "TIMEOUT while waiting for an answer\n");
305 if (ah->phase == AUTO_NAT_PUNCHED)
306 {
307 stop_stun();
308 }
309
310 next_phase (ah);
311 }
312}
313
314
315/**
316 * Create an IPv4 listen socket bound to our port.
317 *
318 * @return NULL on error
319 */
320static struct GNUNET_NETWORK_Handle *
321bind_v4 ()
322{
323 struct GNUNET_NETWORK_Handle *ls;
324 struct sockaddr_in sa4;
325 int eno;
326
327 memset (&sa4, 0, sizeof (sa4));
328 sa4.sin_family = AF_INET;
329 sa4.sin_port = htons (port);
330#if HAVE_SOCKADDR_IN_SIN_LEN
331 sa4.sin_len = sizeof (sa4);
332#endif
333 ls = GNUNET_NETWORK_socket_create (AF_INET,
334 SOCK_DGRAM,
335 0);
336 if (NULL == ls)
337 return NULL;
338 if (GNUNET_OK !=
339 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
340 sizeof (sa4)))
341 {
342 eno = errno;
343 GNUNET_NETWORK_socket_close (ls);
344 errno = eno;
345 return NULL;
346 }
347 return ls;
348}
349
350
351static void
352request_callback (void *cls,
353 enum GNUNET_NAT_StatusCode result)
354{
355 // struct GNUNET_NAT_AutoHandle *ah = cls;
356
357 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
358 "Request callback: stop and quit\n");
359 stop_stun ();
360
361 // next_phase (ah); FIXME this always will be NULL, as called in test_stun()
362}
363
364
365/**
366 * Function called by NAT to report the outcome of the nat-test.
367 * Clean up and update GUI.
368 *
369 * @param cls the auto handle
370 * @param success currently always #GNUNET_OK
371 * @param emsg NULL on success, otherwise an error message
372 */
373static void
374result_callback (void *cls,
375 enum GNUNET_NAT_StatusCode ret)
376{
377 struct GNUNET_NAT_AutoHandle *ah = cls;
378
379 if (GNUNET_NAT_ERROR_SUCCESS == ret)
380 GNUNET_NAT_test_stop (ah->tst);
381 ah->tst = NULL;
382 ah->ret = ret;
383 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
384 GNUNET_NAT_ERROR_SUCCESS == ret
385 ? _("NAT traversal with ICMP Server succeeded.\n")
386 : _("NAT traversal with ICMP Server failed.\n"));
387 GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "ENABLE_ICMP_SERVER",
388 GNUNET_NAT_ERROR_SUCCESS == ret ? "NO" : "YES");
389 next_phase (ah);
390}
391
392
393/**
394 * Main function for the connection reversal test.
395 *
396 * @param cls the `struct GNUNET_NAT_AutoHandle`
397 */
398static void
399reversal_test (void *cls)
400{
401 struct GNUNET_NAT_AutoHandle *ah = cls;
402
403 ah->task = NULL;
404 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
405 _("Testing connection reversal with ICMP server.\n"));
406 GNUNET_RESOLVER_connect (ah->cfg);
407 ah->tst = GNUNET_NAT_test_start (ah->cfg, GNUNET_YES, 0, 0, TIMEOUT,
408 &result_callback, ah);
409}
410
411
412/**
413 * Set our external IPv4 address based on the UPnP.
414 *
415 *
416 * @param cls closure with our setup context
417 * @param addr the address, NULL on errors
418 * @param emsg NULL on success, otherwise an error message
419 */
420static void
421set_external_ipv4 (void *cls,
422 const struct in_addr *addr,
423 enum GNUNET_NAT_StatusCode ret)
424{
425 struct GNUNET_NAT_AutoHandle *ah = cls;
426 char buf[INET_ADDRSTRLEN];
427
428 ah->eh = NULL;
429 ah->ret = ret;
430 if (GNUNET_NAT_ERROR_SUCCESS != ret)
431 {
432 next_phase (ah);
433 return;
434 }
435 /* enable 'behind nat' */
436 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
437 _("Detected external IP `%s'\n"),
438 inet_ntop (AF_INET,
439 addr,
440 buf,
441 sizeof (buf)));
442 GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "BEHIND_NAT", "YES");
443
444 /* set external IP address */
445 if (NULL == inet_ntop (AF_INET, addr, buf, sizeof (buf)))
446 {
447 GNUNET_break (0);
448 /* actually, this should never happen, as the caller already executed just
449 * this check, but for consistency (eg: future changes in the caller)
450 * we still need to report this error...
451 */
452 ah->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID;
453 next_phase (ah);
454 return;
455 }
456 GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "EXTERNAL_ADDRESS",
457 buf);
458 ah->upnp_set_external_address = GNUNET_YES;
459 next_phase (ah);
460}
461
462
463/**
464 * Determine our external IPv4 address.
465 *
466 * @param ah auto setup context
467 */
468static void
469test_external_ip (struct GNUNET_NAT_AutoHandle *ah)
470{
471 if (GNUNET_NAT_ERROR_SUCCESS != ah->ret)
472 next_phase (ah);
473
474 // FIXME: CPS?
475 /* try to detect external IP */
476 ah->eh = GNUNET_NAT_mini_get_external_ipv4 (TIMEOUT,
477 &set_external_ipv4, ah);
478}
479
480
481/**
482 * Determine our external IPv4 address and port using an external STUN server
483 *
484 * @param ah auto setup context
485 */
486static void
487test_stun (struct GNUNET_NAT_AutoHandle *ah)
488{
489
490 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Running STUN test\n");
491
492 /* Get port from the configuration */
493 if (GNUNET_OK !=
494 GNUNET_CONFIGURATION_get_value_number (ah->cfg,
495 "transport-udp",
496 "PORT",
497 &port))
498 {
499 port = 2086;
500 }
501
502 //Lets create the socket
503 lsock4 = bind_v4 ();
504 if (NULL == lsock4)
505 {
506 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
507 next_phase(ah);
508 return;
509 }
510 else
511 {
512 //Lets call our function now when it accepts
513 ltask4 = GNUNET_SCHEDULER_add_read_net (NAT_SERVER_TIMEOUT,
514 lsock4,
515 &do_udp_read,
516 ah);
517 }
518
519
520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
521 "STUN service listens on port %u\n",
522 (unsigned int) port);
523 if (GNUNET_NO ==
524 GNUNET_NAT_stun_make_request (stun_server,
525 stun_port,
526 lsock4,
527 &request_callback,
528 NULL))
529 {
530 /*An error happened*/
531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "STUN error, stopping\n");
532 stop_stun ();
533 next_phase (ah);
534 }
535}
536
537
538/**
539 * Process list of local IP addresses. Find and set the
540 * one of the default interface.
541 *
542 * @param cls our `struct GNUNET_NAT_AutoHandle`
543 * @param name name of the interface (can be NULL for unknown)
544 * @param isDefault is this presumably the default interface
545 * @param addr address of this interface (can be NULL for unknown or unassigned)
546 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
547 * @param netmask the network mask (can be NULL for unknown or unassigned))
548 * @param addrlen length of the @a addr and @a broadcast_addr
549 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
550 */
551static int
552process_if (void *cls,
553 const char *name,
554 int isDefault,
555 const struct sockaddr *addr,
556 const struct sockaddr *broadcast_addr,
557 const struct sockaddr *netmask,
558 socklen_t addrlen)
559{
560 struct GNUNET_NAT_AutoHandle *ah = cls;
561 const struct sockaddr_in *in;
562 char buf[INET_ADDRSTRLEN];
563
564
565 if ( (sizeof (struct sockaddr_in6) == addrlen) &&
566 (0 != memcmp (&in6addr_loopback, &((const struct sockaddr_in6 *) addr)->sin6_addr,
567 sizeof (struct in6_addr))) &&
568 (! IN6_IS_ADDR_LINKLOCAL(&((const struct sockaddr_in6 *) addr)->sin6_addr)) )
569 {
570 ah->have_v6 = GNUNET_YES;
571 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
572 _("This system has a global IPv6 address, setting IPv6 to supported.\n"));
573
574 return GNUNET_OK;
575 }
576 if (addrlen != sizeof (struct sockaddr_in))
577 return GNUNET_OK;
578 in = (const struct sockaddr_in *) addr;
579
580
581 /* set internal IP address */
582 if (NULL == inet_ntop (AF_INET, &in->sin_addr, buf, sizeof (buf)))
583 {
584 GNUNET_break (0);
585 return GNUNET_OK;
586 }
587 GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "INTERNAL_ADDRESS",
588 buf);
589 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
590 _("Detected internal network address `%s'.\n"),
591 buf);
592
593
594 ah->ret = GNUNET_NAT_ERROR_SUCCESS;
595
596 /* Check if our internal IP is the same as the External detect by STUN*/
597 if(ah->stun_ip && (strcmp(buf, ah->stun_ip) == 0) )
598 {
599 ah->internal_ip_is_public = GNUNET_YES;
600 GNUNET_log (GNUNET_ERROR_TYPE_INFO,"A internal IP is the sameas the external");
601 /* No need to continue*/
602 return GNUNET_SYSERR;
603 }
604
605 /* no need to continue iteration if we found the default */
606 if (!isDefault)
607 return GNUNET_OK;
608 else
609 return GNUNET_SYSERR;
610}
611
612
613/**
614 * Determine our local IP addresses; detect internal IP & IPv6-support
615 *
616 * @param ah auto setup context
617 */
618static void
619test_local_ip (struct GNUNET_NAT_AutoHandle *ah)
620{
621 ah->have_v6 = GNUNET_NO;
622 ah->ret = GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO; // reset to success if any of the IFs in below iterator has a valid IP
623 GNUNET_OS_network_interfaces_list (&process_if, ah);
624
625 GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "DISABLEV6",
626 (GNUNET_YES == ah->have_v6) ? "NO" : "YES");
627 next_phase (ah);
628}
629
630
631/**
632 * We got disconnected from the NAT server. Stop
633 * waiting for a reply.
634 *
635 * @param cls the `struct GNUNET_NAT_AutoHandle`
636 * @param error error code
637 */
638static void
639mq_error_handler (void *cls,
640 enum GNUNET_MQ_Error error)
641{
642 struct GNUNET_NAT_AutoHandle *ah = cls;
643
644 GNUNET_MQ_destroy (ah->mq);
645 ah->mq = NULL;
646 /* wait a bit first? */
647 next_phase (ah);
648}
649
650
651/**
652 * Test if NAT has been punched
653 *
654 * @param ah auto setup context
655 */
656static void
657test_nat_punched (struct GNUNET_NAT_AutoHandle *ah)
658{
659 struct GNUNET_NAT_TestMessage *msg;
660 struct GNUNET_MQ_Envelope *env;
661
662 if (! ah->stun_ip)
663 {
664 LOG (GNUNET_ERROR_TYPE_INFO,
665 "We don't have a STUN IP");
666 next_phase (ah);
667 return;
668 }
669
670 LOG (GNUNET_ERROR_TYPE_INFO,
671 "Asking gnunet-nat-server to connect to `%s'\n",
672 ah->stun_ip);
673 ah->mq = GNUNET_CLIENT_connecT (ah->cfg,
674 "gnunet-nat-server",
675 NULL,
676 &mq_error_handler,
677 ah);
678 if (NULL == ah->mq)
679 {
680 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
681 _("Failed to connect to `gnunet-nat-server'\n"));
682 next_phase (ah);
683 return;
684 }
685 env = GNUNET_MQ_msg (msg,
686 GNUNET_MESSAGE_TYPE_NAT_TEST);
687 msg->dst_ipv4 = inet_addr (ah->stun_ip);
688 msg->dport = htons (ah->stun_port);
689 msg->data = port;
690 msg->is_tcp = htonl ((uint32_t) GNUNET_NO);
691 GNUNET_MQ_send (ah->mq,
692 env);
693 if (NULL != ltask4)
694 {
695 GNUNET_SCHEDULER_cancel (ltask4);
696 ltask4 = GNUNET_SCHEDULER_add_read_net (NAT_SERVER_TIMEOUT,
697 lsock4,
698 &do_udp_read,
699 ah);
700 }
701}
702
703
704/**
705 * Test if UPnPC works.
706 *
707 * @param ah auto setup context
708 */
709static void
710test_upnpc (struct GNUNET_NAT_AutoHandle *ah)
711{
712
713 int have_upnpc;
714
715 if (GNUNET_NAT_ERROR_SUCCESS != ah->ret)
716 next_phase (ah);
717
718 // test if upnpc is available
719 have_upnpc = (GNUNET_SYSERR !=
720 GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL));
721 //FIXME: test if upnpc is actually working, that is, if transports start to work once we use UPnP
722 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
723 (have_upnpc)
724 ? _("upnpc found, enabling its use\n")
725 : _("upnpc not found\n"));
726 GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "ENABLE_UPNP",
727 (GNUNET_YES == have_upnpc) ? "YES" : "NO");
728 next_phase (ah);
729
730}
731
732
733/**
734 * Test if ICMP server is working
735 *
736 * @param ah auto setup context
737 */
738static void
739test_icmp_server (struct GNUNET_NAT_AutoHandle *ah)
740{
741
742 int ext_ip;
743 int nated;
744 int binary;
745 char *tmp;
746 char *helper;
747 ext_ip = GNUNET_NO;
748 nated = GNUNET_NO;
749 binary = GNUNET_NO;
750
751 tmp = NULL;
752 helper = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
753 if ( (GNUNET_OK ==
754 GNUNET_CONFIGURATION_get_value_string (ah->cfg,
755 "nat",
756 "EXTERNAL_ADDRESS",
757 &tmp)) &&
758 (0 < strlen (tmp)) )
759 {
760 ext_ip = GNUNET_OK;
761 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
762 _("test_icmp_server not possible, as we have no public IPv4 address\n"));
763 }
764 else
765 goto err;
766
767 if (GNUNET_YES ==
768 GNUNET_CONFIGURATION_get_value_yesno (ah->cfg,
769 "nat",
770 "BEHIND_NAT"))
771 {
772 nated = GNUNET_YES;
773 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
774 _("test_icmp_server not possible, as we are not behind NAT\n"));
775 }
776 else
777 goto err;
778
779 if (GNUNET_YES ==
780 GNUNET_OS_check_helper_binary (helper,
781 GNUNET_YES,
782 "-d 127.0.0.1" ))
783 {
784 binary = GNUNET_OK; // use localhost as source for that one udp-port, ok for testing
785 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
786 _("No working gnunet-helper-nat-server found\n"));
787 }
788err:
789 GNUNET_free_non_null (tmp);
790 GNUNET_free (helper);
791
792 if ( (GNUNET_OK == ext_ip) &&
793 (GNUNET_YES == nated) &&
794 (GNUNET_OK == binary) )
795 ah->task = GNUNET_SCHEDULER_add_now (&reversal_test,
796 ah);
797 else
798 next_phase (ah);
799}
800
801
802/**
803 * Test if ICMP client is working
804 *
805 * @param ah auto setup context
806 */
807static void
808test_icmp_client (struct GNUNET_NAT_AutoHandle *ah)
809{
810 char *tmp;
811 char *helper;
812
813 tmp = NULL;
814 helper = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
815 if ( (GNUNET_OK ==
816 GNUNET_CONFIGURATION_get_value_string (ah->cfg,
817 "nat",
818 "INTERNAL_ADDRESS",
819 &tmp)) &&
820 (0 < strlen (tmp)) )
821 {
822 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
823 _("test_icmp_client not possible, as we have no internal IPv4 address\n"));
824 }
825 else
826 goto err;
827
828 if (GNUNET_YES !=
829 GNUNET_CONFIGURATION_get_value_yesno (ah->cfg,
830 "nat",
831 "BEHIND_NAT"))
832 {
833 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
834 _("test_icmp_server not possible, as we are not behind NAT\n"));
835 }
836 else
837 goto err;
838
839 if (GNUNET_YES ==
840 GNUNET_OS_check_helper_binary (helper,
841 GNUNET_YES,
842 "-d 127.0.0.1 127.0.0.2 42"))
843 {
844 // none of these parameters are actually used in privilege testing mode
845 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
846 _("No working gnunet-helper-nat-server found\n"));
847 }
848err:
849 GNUNET_free_non_null (tmp);
850 GNUNET_free (helper);
851
852 next_phase (ah);
853}
854
855
856/**
857 * Run the next phase of the auto test.
858 */
859static void
860next_phase (struct GNUNET_NAT_AutoHandle *ah)
861{
862 struct GNUNET_CONFIGURATION_Handle *diff;
863
864 ah->phase++;
865 switch (ah->phase)
866 {
867 case AUTO_INIT:
868 GNUNET_assert (0);
869 break;
870 case AUTO_EXTERNAL_IP:
871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872 "Will run AUTO_EXTERNAL_IP\n");
873 test_external_ip (ah);
874 break;
875 case AUTO_STUN:
876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877 "Will run AUTO_STUN\n");
878 test_stun (ah);
879 break;
880 case AUTO_LOCAL_IP:
881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
882 "Will run AUTO_LOCAL_IP\n");
883 test_local_ip (ah);
884 break;
885 case AUTO_NAT_PUNCHED:
886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887 "Will run AUTO_NAT_PUNCHED\n");
888 test_nat_punched (ah);
889 break;
890 case AUTO_UPNPC:
891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
892 "Will run AUTO_UPNPC\n");
893 test_upnpc (ah);
894 break;
895 case AUTO_ICMP_SERVER:
896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
897 "Will run AUTO_ICMP_SERVER\n");
898 test_icmp_server (ah);
899 break;
900 case AUTO_ICMP_CLIENT:
901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
902 "Will run AUTO_ICMP_CLIENT\n");
903 test_icmp_client (ah);
904 break;
905 case AUTO_DONE:
906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
907 "Done with tests\n");
908 if (!ah->internal_ip_is_public)
909 {
910 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
911 "nat",
912 "BEHIND_NAT",
913 "YES");
914
915 if (ah->connected_back)
916 {
917 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
918 "nat",
919 "PUNCHED_NAT",
920 "YES");
921 }
922 else
923 {
924 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
925 "nat",
926 "PUNCHED_NAT",
927 "NO");
928 }
929
930 if (ah->stun_ip)
931 {
932 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
933 "nat",
934 "EXTERNAL_ADDRESS",
935 ah->stun_ip);
936 if (ah->connected_back)
937 {
938 ah->type = GNUNET_NAT_TYPE_STUN_PUNCHED_NAT;
939 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
940 "nat",
941 "USE_STUN",
942 "YES");
943 }
944 else
945 {
946 ah->type = GNUNET_NAT_TYPE_UNREACHABLE_NAT;
947 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
948 "nat",
949 "USE_STUN",
950 "NO");
951 }
952
953 }
954 if (0 != ah->stun_port)
955 {
956 GNUNET_CONFIGURATION_set_value_number (ah->cfg,
957 "transport-udp",
958 "ADVERTISED_PORT",
959 ah->stun_port);
960 }
961
962 }
963 else
964 {
965 //The internal IP is the same as public, but we didn't got a incoming connection
966 if (ah->connected_back)
967 {
968 ah->type = GNUNET_NAT_TYPE_NO_NAT;
969 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
970 "nat",
971 "BEHIND_NAT",
972 "NO");
973 }
974 else
975 {
976 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
977 "nat",
978 "BEHIND_NAT",
979 "YES");
980 ah->type = GNUNET_NAT_TYPE_UNREACHABLE_NAT;
981 if (ah->stun_ip)
982 {
983 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
984 "nat",
985 "EXTERNAL_ADDRESS",
986 ah->stun_ip);
987 }
988 if (0 != ah->stun_port)
989 {
990 GNUNET_CONFIGURATION_set_value_number (ah->cfg,
991 "transport-udp",
992 "ADVERTISED_PORT",
993 ah->stun_port);
994
995 }
996 }
997 }
998
999 diff = GNUNET_CONFIGURATION_get_diff (ah->initial_cfg,
1000 ah->cfg);
1001
1002
1003 ah->fin_cb (ah->fin_cb_cls,
1004 diff,
1005 ah->ret,
1006 ah->type);
1007 GNUNET_CONFIGURATION_destroy (diff);
1008 GNUNET_NAT_autoconfig_cancel (ah);
1009 }
1010}
1011
1012
1013/**
1014 * Start auto-configuration routine. The resolver service should
1015 * be available when this function is called.
1016 *
1017 * @param cfg initial configuration
1018 * @param cb function to call with autoconfiguration result
1019 * @param cb_cls closure for @a cb
1020 * @return handle to cancel operation
1021 */
1022struct GNUNET_NAT_AutoHandle *
1023GNUNET_NAT_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
1024 GNUNET_NAT_AutoResultCallback cb,
1025 void *cb_cls)
1026{
1027 struct GNUNET_NAT_AutoHandle *ah;
1028
1029 ah = GNUNET_new (struct GNUNET_NAT_AutoHandle);
1030 ah->fin_cb = cb;
1031 ah->fin_cb_cls = cb_cls;
1032 ah->ret = GNUNET_NAT_ERROR_SUCCESS;
1033 ah->cfg = GNUNET_CONFIGURATION_dup (cfg);
1034 ah->initial_cfg = GNUNET_CONFIGURATION_dup (cfg);
1035
1036 /* never use loopback addresses if user wanted autoconfiguration */
1037 GNUNET_CONFIGURATION_set_value_string (ah->cfg,
1038 "nat",
1039 "USE_LOCALADDR",
1040 "NO");
1041
1042 next_phase (ah);
1043 return ah;
1044}
1045
1046
1047/**
1048 * Abort autoconfiguration.
1049 *
1050 * @param ah handle for operation to abort
1051 */
1052void
1053GNUNET_NAT_autoconfig_cancel (struct GNUNET_NAT_AutoHandle *ah)
1054{
1055 if (NULL != ah->tst)
1056 {
1057 GNUNET_NAT_test_stop (ah->tst);
1058 ah->tst = NULL;
1059 }
1060 if (NULL != ah->eh)
1061 {
1062 GNUNET_NAT_mini_get_external_ipv4_cancel (ah->eh);
1063 ah->eh = NULL;
1064 }
1065 if (NULL != ah->mq)
1066 {
1067 GNUNET_MQ_destroy (ah->mq);
1068 ah->mq = NULL;
1069 }
1070 if (NULL != ah->task)
1071 {
1072 GNUNET_SCHEDULER_cancel (ah->task);
1073 ah->task = NULL;
1074 }
1075 GNUNET_CONFIGURATION_destroy (ah->cfg);
1076 GNUNET_CONFIGURATION_destroy (ah->initial_cfg);
1077 GNUNET_free (ah);
1078}
1079
1080
1081/* end of nat_auto.c */
diff --git a/src/nat/nat_mini.c b/src/nat/nat_mini.c
deleted file mode 100644
index 915bcbdb6..000000000
--- a/src/nat/nat_mini.c
+++ /dev/null
@@ -1,712 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2011-2014 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file nat/nat_mini.c
23 * @brief functions for interaction with miniupnp; tested with miniupnpc 1.5
24 * @author Christian Grothoff
25 */
26#include "platform.h"
27#include "gnunet_util_lib.h"
28#include "gnunet_nat_lib.h"
29#include "nat.h"
30
31#define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
32
33/**
34 * How long do we give upnpc to create a mapping?
35 */
36#define MAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
37
38/**
39 * How long do we give upnpc to remove a mapping?
40 */
41#define UNMAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
42
43/**
44 * How often do we check for changes in the mapping?
45 */
46#define MAP_REFRESH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
47
48
49
50/**
51 * Opaque handle to cancel "GNUNET_NAT_mini_get_external_ipv4" operation.
52 */
53struct GNUNET_NAT_ExternalHandle
54{
55
56 /**
57 * Function to call with the result.
58 */
59 GNUNET_NAT_IPCallback cb;
60
61 /**
62 * Closure for @e cb.
63 */
64 void *cb_cls;
65
66 /**
67 * Read task.
68 */
69 struct GNUNET_SCHEDULER_Task * task;
70
71 /**
72 * Handle to 'external-ip' process.
73 */
74 struct GNUNET_OS_Process *eip;
75
76 /**
77 * Handle to stdout pipe of 'external-ip'.
78 */
79 struct GNUNET_DISK_PipeHandle *opipe;
80
81 /**
82 * Read handle of @e opipe.
83 */
84 const struct GNUNET_DISK_FileHandle *r;
85
86 /**
87 * When should this operation time out?
88 */
89 struct GNUNET_TIME_Absolute timeout;
90
91 /**
92 * Number of bytes in 'buf' that are valid.
93 */
94 size_t off;
95
96 /**
97 * Destination of our read operation (output of 'external-ip').
98 */
99 char buf[17];
100
101 /**
102 * Error code for better debugging and user feedback
103 */
104 enum GNUNET_NAT_StatusCode ret;
105};
106
107
108/**
109 * Read the output of 'external-ip' into buf. When complete, parse the
110 * address and call our callback.
111 *
112 * @param cls the `struct GNUNET_NAT_ExternalHandle`
113 */
114static void
115read_external_ipv4 (void *cls)
116{
117 struct GNUNET_NAT_ExternalHandle *eh = cls;
118 ssize_t ret;
119 struct in_addr addr;
120 const struct GNUNET_SCHEDULER_TaskContext *tc;
121
122 eh->task = NULL;
123 tc = GNUNET_SCHEDULER_get_task_context ();
124 if (GNUNET_YES ==
125 GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, eh->r))
126 {
127 ret =
128 GNUNET_DISK_file_read (eh->r, &eh->buf[eh->off],
129 sizeof (eh->buf) - eh->off);
130 }
131 else
132 {
133 eh->ret = GNUNET_NAT_ERROR_IPC_FAILURE;
134 ret = -1; /* error reading, timeout, etc. */
135 }
136 if (ret > 0)
137 {
138 /* try to read more */
139 eh->off += ret;
140 eh->task =
141 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
142 (eh->timeout), eh->r,
143 &read_external_ipv4, eh);
144 return;
145 }
146 eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID;
147 if ((eh->off > 7) && (eh->buf[eh->off - 1] == '\n'))
148 {
149 eh->buf[eh->off - 1] = '\0';
150 if (1 == inet_pton (AF_INET, eh->buf, &addr))
151 {
152 if (0 != addr.s_addr)
153 eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID; /* got 0.0.0.0 */
154 else
155 eh->ret = GNUNET_NAT_ERROR_SUCCESS;
156 }
157 }
158 eh->cb (eh->cb_cls,
159 (GNUNET_NAT_ERROR_SUCCESS == eh->ret) ? &addr : NULL,
160 eh->ret);
161 GNUNET_NAT_mini_get_external_ipv4_cancel (eh);
162}
163
164
165/**
166 * (Asynchronously) signal error invoking "external-ip" to client.
167 *
168 * @param cls the `struct GNUNET_NAT_ExternalHandle` (freed)
169 */
170static void
171signal_external_ip_error (void *cls)
172{
173 struct GNUNET_NAT_ExternalHandle *eh = cls;
174
175 eh->task = NULL;
176 eh->cb (eh->cb_cls,
177 NULL,
178 eh->ret);
179 GNUNET_free (eh);
180}
181
182
183/**
184 * Try to get the external IPv4 address of this peer.
185 *
186 * @param timeout when to fail
187 * @param cb function to call with result
188 * @param cb_cls closure for @a cb
189 * @return handle for cancellation (can only be used until @a cb is called), never NULL
190 */
191struct GNUNET_NAT_ExternalHandle *
192GNUNET_NAT_mini_get_external_ipv4 (struct GNUNET_TIME_Relative timeout,
193 GNUNET_NAT_IPCallback cb, void *cb_cls)
194{
195 struct GNUNET_NAT_ExternalHandle *eh;
196
197 eh = GNUNET_new (struct GNUNET_NAT_ExternalHandle);
198 eh->cb = cb;
199 eh->cb_cls = cb_cls;
200 eh->ret = GNUNET_NAT_ERROR_SUCCESS;
201 if (GNUNET_SYSERR ==
202 GNUNET_OS_check_helper_binary ("external-ip", GNUNET_NO, NULL))
203 {
204 LOG (GNUNET_ERROR_TYPE_INFO,
205 _("`external-ip' command not found\n"));
206 eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND;
207 eh->task = GNUNET_SCHEDULER_add_now (&signal_external_ip_error,
208 eh);
209 return eh;
210 }
211 LOG (GNUNET_ERROR_TYPE_DEBUG,
212 "Running `external-ip' to determine our external IP\n");
213 eh->opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
214 if (NULL == eh->opipe)
215 {
216 eh->ret = GNUNET_NAT_ERROR_IPC_FAILURE;
217 eh->task = GNUNET_SCHEDULER_add_now (&signal_external_ip_error,
218 eh);
219 return eh;
220 }
221 eh->eip =
222 GNUNET_OS_start_process (GNUNET_NO, 0, NULL, eh->opipe, NULL,
223 "external-ip", "external-ip",
224 NULL);
225 if (NULL == eh->eip)
226 {
227 GNUNET_DISK_pipe_close (eh->opipe);
228 eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED;
229 eh->task = GNUNET_SCHEDULER_add_now (&signal_external_ip_error,
230 eh);
231 return eh;
232 }
233 GNUNET_DISK_pipe_close_end (eh->opipe, GNUNET_DISK_PIPE_END_WRITE);
234 eh->timeout = GNUNET_TIME_relative_to_absolute (timeout);
235 eh->r = GNUNET_DISK_pipe_handle (eh->opipe, GNUNET_DISK_PIPE_END_READ);
236 eh->task =
237 GNUNET_SCHEDULER_add_read_file (timeout,
238 eh->r,
239 &read_external_ipv4, eh);
240 return eh;
241}
242
243
244/**
245 * Cancel operation.
246 *
247 * @param eh operation to cancel
248 */
249void
250GNUNET_NAT_mini_get_external_ipv4_cancel (struct GNUNET_NAT_ExternalHandle *eh)
251{
252 if (NULL != eh->eip)
253 {
254 (void) GNUNET_OS_process_kill (eh->eip, SIGKILL);
255 GNUNET_OS_process_destroy (eh->eip);
256 }
257 if (NULL != eh->opipe)
258 GNUNET_DISK_pipe_close (eh->opipe);
259 if (NULL != eh->task)
260 GNUNET_SCHEDULER_cancel (eh->task);
261 GNUNET_free (eh);
262}
263
264
265/**
266 * Handle to a mapping created with upnpc.
267 */
268struct GNUNET_NAT_MiniHandle
269{
270
271 /**
272 * Function to call on mapping changes.
273 */
274 GNUNET_NAT_MiniAddressCallback ac;
275
276 /**
277 * Closure for @e ac.
278 */
279 void *ac_cls;
280
281 /**
282 * Command used to install the map.
283 */
284 struct GNUNET_OS_CommandHandle *map_cmd;
285
286 /**
287 * Command used to refresh our map information.
288 */
289 struct GNUNET_OS_CommandHandle *refresh_cmd;
290
291 /**
292 * Command used to remove the mapping.
293 */
294 struct GNUNET_OS_CommandHandle *unmap_cmd;
295
296 /**
297 * Our current external mapping (if we have one).
298 */
299 struct sockaddr_in current_addr;
300
301 /**
302 * We check the mapping periodically to see if it
303 * still works. This task triggers the check.
304 */
305 struct GNUNET_SCHEDULER_Task * refresh_task;
306
307 /**
308 * Are we mapping TCP or UDP?
309 */
310 int is_tcp;
311
312 /**
313 * Did we succeed with creating a mapping?
314 */
315 int did_map;
316
317 /**
318 * Did we find our mapping during refresh scan?
319 */
320 int found;
321
322 /**
323 * Which port are we mapping?
324 */
325 uint16_t port;
326
327};
328
329
330/**
331 * Run "upnpc -l" to find out if our mapping changed.
332 *
333 * @param cls the `struct GNUNET_NAT_MiniHandle`
334 */
335static void
336do_refresh (void *cls);
337
338
339/**
340 * Process the output from the "upnpc -r" command.
341 *
342 * @param cls the `struct GNUNET_NAT_MiniHandle`
343 * @param line line of output, NULL at the end
344 */
345static void
346process_map_output (void *cls, const char *line);
347
348
349/**
350 * Run "upnpc -r" to map our internal port.
351 *
352 * @param mini our handle
353 */
354static void
355run_upnpc_r (struct GNUNET_NAT_MiniHandle *mini)
356{
357 char pstr[6];
358
359 GNUNET_snprintf (pstr,
360 sizeof (pstr),
361 "%u",
362 (unsigned int) mini->port);
363 mini->map_cmd =
364 GNUNET_OS_command_run (&process_map_output, mini, MAP_TIMEOUT,
365 "upnpc", "upnpc", "-r", pstr,
366 mini->is_tcp ? "tcp" : "udp", NULL);
367 if (NULL == mini->map_cmd)
368 {
369 mini->ac (mini->ac_cls,
370 GNUNET_SYSERR,
371 NULL, 0,
372 GNUNET_NAT_ERROR_UPNPC_FAILED);
373 return;
374 }
375}
376
377
378/**
379 * Process the output from "upnpc -l" to see if our
380 * external mapping changed. If so, do the notifications.
381 *
382 * @param cls the `struct GNUNET_NAT_MiniHandle`
383 * @param line line of output, NULL at the end
384 */
385static void
386process_refresh_output (void *cls, const char *line)
387{
388 struct GNUNET_NAT_MiniHandle *mini = cls;
389 char pstr[9];
390 const char *s;
391 unsigned int nport;
392 struct in_addr exip;
393
394 if (NULL == line)
395 {
396 GNUNET_OS_command_stop (mini->refresh_cmd);
397 mini->refresh_cmd = NULL;
398 if (GNUNET_NO == mini->found)
399 {
400 /* mapping disappeared, try to re-create */
401 if (GNUNET_YES == mini->did_map)
402 {
403 mini->ac (mini->ac_cls,
404 GNUNET_NO,
405 (const struct sockaddr *) &mini->current_addr,
406 sizeof (mini->current_addr),
407 GNUNET_NAT_ERROR_SUCCESS);
408 mini->did_map = GNUNET_NO;
409 }
410 run_upnpc_r (mini);
411 }
412 return;
413 }
414 if (!mini->did_map)
415 return; /* never mapped, won't find our mapping anyway */
416
417 /* we're looking for output of the form:
418 * "ExternalIPAddress = 12.134.41.124" */
419
420 s = strstr (line, "ExternalIPAddress = ");
421 if (NULL != s)
422 {
423 s += strlen ("ExternalIPAddress = ");
424 if (1 != inet_pton (AF_INET, s, &exip))
425 return; /* skip */
426 if (exip.s_addr == mini->current_addr.sin_addr.s_addr)
427 return; /* no change */
428 /* update mapping */
429 mini->ac (mini->ac_cls, GNUNET_NO,
430 (const struct sockaddr *) &mini->current_addr,
431 sizeof (mini->current_addr),
432 GNUNET_NAT_ERROR_SUCCESS);
433 mini->current_addr.sin_addr = exip;
434 mini->ac (mini->ac_cls, GNUNET_YES,
435 (const struct sockaddr *) &mini->current_addr,
436 sizeof (mini->current_addr),
437 GNUNET_NAT_ERROR_SUCCESS);
438 return;
439 }
440 /*
441 * we're looking for output of the form:
442 *
443 * "0 TCP 3000->192.168.2.150:3000 'libminiupnpc' ''"
444 * "1 UDP 3001->192.168.2.150:3001 'libminiupnpc' ''"
445 *
446 * the pattern we look for is:
447 *
448 * "%s TCP PORT->STRING:OURPORT *" or
449 * "%s UDP PORT->STRING:OURPORT *"
450 */
451 GNUNET_snprintf (pstr, sizeof (pstr), ":%u ", mini->port);
452 if (NULL == (s = strstr (line, "->")))
453 return; /* skip */
454 if (NULL == strstr (s, pstr))
455 return; /* skip */
456 if (1 !=
457 SSCANF (line,
458 (mini->is_tcp) ? "%*u TCP %u->%*s:%*u %*s" :
459 "%*u UDP %u->%*s:%*u %*s", &nport))
460 return; /* skip */
461 mini->found = GNUNET_YES;
462 if (nport == ntohs (mini->current_addr.sin_port))
463 return; /* no change */
464
465 /* external port changed, update mapping */
466 mini->ac (mini->ac_cls, GNUNET_NO,
467 (const struct sockaddr *) &mini->current_addr,
468 sizeof (mini->current_addr),
469 GNUNET_NAT_ERROR_SUCCESS);
470 mini->current_addr.sin_port = htons ((uint16_t) nport);
471 mini->ac (mini->ac_cls, GNUNET_YES,
472 (const struct sockaddr *) &mini->current_addr,
473 sizeof (mini->current_addr),
474 GNUNET_NAT_ERROR_SUCCESS);
475}
476
477
478/**
479 * Run "upnpc -l" to find out if our mapping changed.
480 *
481 * @param cls the 'struct GNUNET_NAT_MiniHandle'
482 */
483static void
484do_refresh (void *cls)
485{
486 struct GNUNET_NAT_MiniHandle *mini = cls;
487 int ac;
488
489 mini->refresh_task =
490 GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ,
491 &do_refresh, mini);
492 LOG (GNUNET_ERROR_TYPE_DEBUG,
493 "Running `upnpc' to check if our mapping still exists\n");
494 mini->found = GNUNET_NO;
495 ac = GNUNET_NO;
496 if (NULL != mini->map_cmd)
497 {
498 /* took way too long, abort it! */
499 GNUNET_OS_command_stop (mini->map_cmd);
500 mini->map_cmd = NULL;
501 ac = GNUNET_YES;
502 }
503 if (NULL != mini->refresh_cmd)
504 {
505 /* took way too long, abort it! */
506 GNUNET_OS_command_stop (mini->refresh_cmd);
507 mini->refresh_cmd = NULL;
508 ac = GNUNET_YES;
509 }
510 mini->refresh_cmd =
511 GNUNET_OS_command_run (&process_refresh_output, mini, MAP_TIMEOUT,
512 "upnpc", "upnpc", "-l", NULL);
513 if (GNUNET_YES == ac)
514 mini->ac (mini->ac_cls,
515 GNUNET_SYSERR,
516 NULL, 0,
517 GNUNET_NAT_ERROR_UPNPC_TIMEOUT);
518}
519
520
521/**
522 * Process the output from the 'upnpc -r' command.
523 *
524 * @param cls the `struct GNUNET_NAT_MiniHandle`
525 * @param line line of output, NULL at the end
526 */
527static void
528process_map_output (void *cls,
529 const char *line)
530{
531 struct GNUNET_NAT_MiniHandle *mini = cls;
532 const char *ipaddr;
533 char *ipa;
534 const char *pstr;
535 unsigned int port;
536
537 if (NULL == line)
538 {
539 GNUNET_OS_command_stop (mini->map_cmd);
540 mini->map_cmd = NULL;
541 if (GNUNET_YES != mini->did_map)
542 mini->ac (mini->ac_cls,
543 GNUNET_SYSERR,
544 NULL, 0,
545 GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED);
546 if (NULL == mini->refresh_task)
547 mini->refresh_task =
548 GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ,
549 &do_refresh,
550 mini);
551 return;
552 }
553 /*
554 * The upnpc output we're after looks like this:
555 *
556 * "external 87.123.42.204:3000 TCP is redirected to internal 192.168.2.150:3000"
557 */
558 if ((NULL == (ipaddr = strstr (line, " "))) ||
559 (NULL == (pstr = strstr (ipaddr, ":"))) ||
560 (1 != SSCANF (pstr + 1, "%u", &port)))
561 {
562 return; /* skip line */
563 }
564 ipa = GNUNET_strdup (ipaddr + 1);
565 strstr (ipa, ":")[0] = '\0';
566 if (1 != inet_pton (AF_INET, ipa, &mini->current_addr.sin_addr))
567 {
568 GNUNET_free (ipa);
569 return; /* skip line */
570 }
571 GNUNET_free (ipa);
572
573 mini->current_addr.sin_port = htons (port);
574 mini->current_addr.sin_family = AF_INET;
575#if HAVE_SOCKADDR_IN_SIN_LEN
576 mini->current_addr.sin_len = sizeof (struct sockaddr_in);
577#endif
578 mini->did_map = GNUNET_YES;
579 mini->ac (mini->ac_cls, GNUNET_YES,
580 (const struct sockaddr *) &mini->current_addr,
581 sizeof (mini->current_addr),
582 GNUNET_NAT_ERROR_SUCCESS);
583}
584
585
586/**
587 * Start mapping the given port using (mini)upnpc. This function
588 * should typically not be used directly (it is used within the
589 * general-purpose #GNUNET_NAT_register() code). However, it can be
590 * used if specifically UPnP-based NAT traversal is to be used or
591 * tested.
592 *
593 * @param port port to map
594 * @param is_tcp #GNUNET_YES to map TCP, #GNUNET_NO for UDP
595 * @param ac function to call with mapping result
596 * @param ac_cls closure for @a ac
597 * @return NULL on error (no 'upnpc' installed)
598 */
599struct GNUNET_NAT_MiniHandle *
600GNUNET_NAT_mini_map_start (uint16_t port,
601 int is_tcp,
602 GNUNET_NAT_MiniAddressCallback ac,
603 void *ac_cls)
604{
605 struct GNUNET_NAT_MiniHandle *ret;
606
607 if (GNUNET_SYSERR ==
608 GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL))
609 {
610 LOG (GNUNET_ERROR_TYPE_INFO,
611 _("`upnpc' command not found\n"));
612 ac (ac_cls,
613 GNUNET_SYSERR,
614 NULL, 0,
615 GNUNET_NAT_ERROR_UPNPC_NOT_FOUND);
616 return NULL;
617 }
618 LOG (GNUNET_ERROR_TYPE_DEBUG,
619 "Running `upnpc' to install mapping\n");
620 ret = GNUNET_new (struct GNUNET_NAT_MiniHandle);
621 ret->ac = ac;
622 ret->ac_cls = ac_cls;
623 ret->is_tcp = is_tcp;
624 ret->port = port;
625 ret->refresh_task =
626 GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ,
627 &do_refresh,
628 ret);
629 run_upnpc_r (ret);
630 return ret;
631}
632
633
634/**
635 * Process output from our 'unmap' command.
636 *
637 * @param cls the `struct GNUNET_NAT_MiniHandle`
638 * @param line line of output, NULL at the end
639 */
640static void
641process_unmap_output (void *cls, const char *line)
642{
643 struct GNUNET_NAT_MiniHandle *mini = cls;
644
645 if (NULL == line)
646 {
647 LOG (GNUNET_ERROR_TYPE_DEBUG,
648 "UPnP unmap done\n");
649 GNUNET_OS_command_stop (mini->unmap_cmd);
650 mini->unmap_cmd = NULL;
651 GNUNET_free (mini);
652 return;
653 }
654 /* we don't really care about the output... */
655}
656
657
658/**
659 * Remove a mapping created with (mini)upnpc. Calling
660 * this function will give 'upnpc' 1s to remove tha mapping,
661 * so while this function is non-blocking, a task will be
662 * left with the scheduler for up to 1s past this call.
663 *
664 * @param mini the handle
665 */
666void
667GNUNET_NAT_mini_map_stop (struct GNUNET_NAT_MiniHandle *mini)
668{
669 char pstr[6];
670
671 if (NULL != mini->refresh_task)
672 {
673 GNUNET_SCHEDULER_cancel (mini->refresh_task);
674 mini->refresh_task = NULL;
675 }
676 if (NULL != mini->refresh_cmd)
677 {
678 GNUNET_OS_command_stop (mini->refresh_cmd);
679 mini->refresh_cmd = NULL;
680 }
681 if (NULL != mini->map_cmd)
682 {
683 GNUNET_OS_command_stop (mini->map_cmd);
684 mini->map_cmd = NULL;
685 }
686 if (GNUNET_NO == mini->did_map)
687 {
688 GNUNET_free (mini);
689 return;
690 }
691 mini->ac (mini->ac_cls, GNUNET_NO,
692 (const struct sockaddr *) &mini->current_addr,
693 sizeof (mini->current_addr),
694 GNUNET_NAT_ERROR_SUCCESS);
695 /* Note: oddly enough, deletion uses the external port whereas
696 * addition uses the internal port; this rarely matters since they
697 * often are the same, but it might... */
698 GNUNET_snprintf (pstr,
699 sizeof (pstr),
700 "%u",
701 (unsigned int) ntohs (mini->current_addr.sin_port));
702 LOG (GNUNET_ERROR_TYPE_DEBUG,
703 "Unmapping port %u with UPnP\n",
704 ntohs (mini->current_addr.sin_port));
705 mini->unmap_cmd =
706 GNUNET_OS_command_run (&process_unmap_output, mini, UNMAP_TIMEOUT,
707 "upnpc", "upnpc", "-d", pstr,
708 mini->is_tcp ? "tcp" : "udp", NULL);
709}
710
711
712/* end of nat_mini.c */
diff --git a/src/nat/nat_stun.c b/src/nat/nat_stun.c
deleted file mode 100644
index 62916ab84..000000000
--- a/src/nat/nat_stun.c
+++ /dev/null
@@ -1,439 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2015 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * This code provides some support for doing STUN transactions.
22 * We send simplest possible packet ia REQUEST with BIND to a STUN server.
23 *
24 * All STUN packets start with a simple header made of a type,
25 * length (excluding the header) and a 16-byte random transaction id.
26 * Following the header we may have zero or more attributes, each
27 * structured as a type, length and a value (whose format depends
28 * on the type, but often contains addresses).
29 * Of course all fields are in network format.
30 *
31 * This code was based on ministun.c.
32 *
33 * @file nat/nat_stun.c
34 * @brief Functions for STUN functionality
35 * @author Bruno Souza Cabral
36 */
37
38#include "platform.h"
39#include "gnunet_util_lib.h"
40#include "gnunet_resolver_service.h"
41#include "gnunet_nat_lib.h"
42
43
44#include "nat_stun.h"
45
46#define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__)
47
48#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
49
50
51/**
52 * Handle to a request given to the resolver. Can be used to cancel
53 * the request prior to the timeout or successful execution. Also
54 * used to track our internal state for the request.
55 */
56struct GNUNET_NAT_STUN_Handle
57{
58
59 /**
60 * Handle to a pending DNS lookup request.
61 */
62 struct GNUNET_RESOLVER_RequestHandle *dns_active;
63
64 /**
65 * Handle to the listen socket
66 */
67 struct GNUNET_NETWORK_Handle *sock;
68
69 /**
70 * Stun server address
71 */
72 char *stun_server;
73
74 /**
75 * Function to call when a error occours
76 */
77 GNUNET_NAT_STUN_ErrorCallback cb;
78
79 /**
80 * Closure for @e cb.
81 */
82 void *cb_cls;
83
84 /**
85 * Do we got a DNS resolution successfully?
86 */
87 int dns_success;
88
89 /**
90 * STUN port
91 */
92 uint16_t stun_port;
93
94};
95
96
97/**
98 * here we store credentials extracted from a message
99*/
100struct StunState
101{
102 uint16_t attr;
103};
104
105
106/**
107 * Encode a class and method to a compatible STUN format
108 *
109 * @param msg_class class to be converted
110 * @param method method to be converted
111 * @return message in a STUN compatible format
112 */
113static int
114encode_message (enum StunClasses msg_class,
115 enum StunMethods method)
116{
117 return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) |
118 (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
119}
120
121
122/**
123 * Fill the stun_header with a random request_id
124 *
125 * @param req, stun header to be filled
126 */
127static void
128generate_request_id (struct stun_header *req)
129{
130 unsigned int x;
131
132 req->magic = htonl(STUN_MAGIC_COOKIE);
133 for (x = 0; x < 3; x++)
134 req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
135 UINT32_MAX);
136}
137
138
139/**
140 * Extract the STUN_MAPPED_ADDRESS from the stun response.
141 * This is used as a callback for stun_handle_response
142 * when called from stun_request.
143 *
144 * @param st, pointer where we will set the type
145 * @param attr , received stun attribute
146 * @param arg , pointer to a sockaddr_in where we will set the reported IP and port
147 * @param magic , Magic cookie
148 *
149 * @return 0 on success, other value otherwise
150 */
151static int
152stun_get_mapped (struct StunState *st,
153 struct stun_attr *attr,
154 struct sockaddr_in *arg,
155 unsigned int magic)
156{
157 struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
158 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
159 unsigned short type = ntohs(attr->attr);
160
161 switch (type)
162 {
163 case STUN_MAPPED_ADDRESS:
164 if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
165 st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
166 return 1;
167 magic = 0;
168 break;
169 case STUN_MS_XOR_MAPPED_ADDRESS:
170 if (st->attr == STUN_XOR_MAPPED_ADDRESS)
171 return 1;
172 break;
173 case STUN_XOR_MAPPED_ADDRESS:
174 break;
175 default:
176 return 1;
177 }
178 if ( (ntohs(attr->len) < 8) &&
179 (returned_addr->family != 1) )
180 {
181 return 1;
182 }
183 st->attr = type;
184 sa->sin_family = AF_INET;
185 sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
186 sa->sin_addr.s_addr = returned_addr->addr ^ magic;
187 return 0;
188}
189
190
191/**
192 * Handle an incoming STUN message, Do some basic sanity checks on packet size and content,
193 * try to extract a bit of information, and possibly reply.
194 * At the moment this only processes BIND requests, and returns
195 * the externally visible address of the request.
196 * If a callback is specified, invoke it with the attribute.
197 *
198 * @param data the packet
199 * @param len the length of the packet in @a data
200 * @param[out] arg sockaddr_in where we will set our discovered address
201 *
202 * @return, #GNUNET_OK on OK, #GNUNET_NO if the packet is invalid (not a stun packet)
203 */
204int
205GNUNET_NAT_stun_handle_packet (const void *data,
206 size_t len,
207 struct sockaddr_in *arg)
208{
209 const struct stun_header *hdr = (const struct stun_header *)data;
210 struct stun_attr *attr;
211 struct StunState st;
212 int ret = GNUNET_OK;
213 uint32_t advertised_message_size;
214 uint32_t message_magic_cookie;
215
216 /* On entry, 'len' is the length of the udp payload. After the
217 * initial checks it becomes the size of unprocessed options,
218 * while 'data' is advanced accordingly.
219 */
220 if (len < sizeof(struct stun_header))
221 {
222 LOG (GNUNET_ERROR_TYPE_INFO,
223 "STUN packet too short (only %d, wanting at least %d)\n",
224 (int) len,
225 (int) sizeof(struct stun_header));
226 GNUNET_break_op (0);
227 return GNUNET_NO;
228 }
229 /* Skip header as it is already in hdr */
230 len -= sizeof(struct stun_header);
231 data += sizeof(struct stun_header);
232
233 /* len as advertised in the message */
234 advertised_message_size = ntohs(hdr->msglen);
235
236 message_magic_cookie = ntohl(hdr->magic);
237 /* Compare if the cookie match */
238 if (STUN_MAGIC_COOKIE != message_magic_cookie)
239 {
240 LOG (GNUNET_ERROR_TYPE_INFO,
241 "Invalid magic cookie \n");
242 return GNUNET_NO;
243 }
244
245 LOG (GNUNET_ERROR_TYPE_INFO,
246 "STUN Packet, msg %s (%04x), length: %d\n",
247 stun_msg2str(ntohs(hdr->msgtype)),
248 ntohs(hdr->msgtype),
249 advertised_message_size);
250 if (advertised_message_size > len)
251 {
252 LOG (GNUNET_ERROR_TYPE_INFO,
253 "Scrambled STUN packet length (got %d, expecting %d)\n",
254 advertised_message_size,
255 (int)len);
256 return GNUNET_NO;
257 }
258 len = advertised_message_size;
259 memset (&st, 0, sizeof(st));
260
261 while (len > 0)
262 {
263 if (len < sizeof(struct stun_attr))
264 {
265 LOG (GNUNET_ERROR_TYPE_INFO,
266 "Attribute too short (got %d, expecting %d)\n",
267 (int)len,
268 (int) sizeof(struct stun_attr));
269 break;
270 }
271 attr = (struct stun_attr *)data;
272
273 /* compute total attribute length */
274 advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr);
275
276 /* Check if we still have space in our buffer */
277 if (advertised_message_size > len )
278 {
279 LOG (GNUNET_ERROR_TYPE_INFO,
280 "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n",
281 advertised_message_size,
282 (int)len);
283 break;
284 }
285 stun_get_mapped (&st,
286 attr,
287 arg,
288 hdr->magic);
289 /* Clear attribute id: in case previous entry was a string,
290 * this will act as the terminator for the string.
291 */
292 attr->attr = 0;
293 data += advertised_message_size;
294 len -= advertised_message_size;
295 ret = GNUNET_OK;
296 }
297 return ret;
298}
299
300
301/**
302 * Cancel active STUN request. Frees associated resources
303 * and ensures that the callback is no longer invoked.
304 *
305 * @param rh request to cancel
306 */
307void
308GNUNET_NAT_stun_make_request_cancel (struct GNUNET_NAT_STUN_Handle *rh)
309{
310 if (NULL != rh->dns_active)
311 {
312 GNUNET_RESOLVER_request_cancel (rh->dns_active);
313 rh->dns_active = NULL;
314 }
315 GNUNET_free (rh->stun_server);
316 GNUNET_free (rh);
317}
318
319
320/**
321 * Try to establish a connection given the specified address.
322 *
323 * @param cls our `struct GNUNET_NAT_STUN_Handle *`
324 * @param addr address to try, NULL for "last call"
325 * @param addrlen length of @a addr
326 */
327static void
328stun_dns_callback (void *cls,
329 const struct sockaddr *addr,
330 socklen_t addrlen)
331{
332 struct GNUNET_NAT_STUN_Handle *rh = cls;
333 struct stun_header *req;
334 uint8_t reqdata[1024];
335 int reqlen;
336 struct sockaddr_in server;
337
338 if (NULL == addr)
339 {
340 rh->dns_active = NULL;
341 if (GNUNET_NO == rh->dns_success)
342 {
343 LOG (GNUNET_ERROR_TYPE_INFO,
344 "Error resolving host %s\n",
345 rh->stun_server);
346 rh->cb (rh->cb_cls,
347 GNUNET_NAT_ERROR_NOT_ONLINE);
348 }
349 else if (GNUNET_SYSERR == rh->dns_success)
350 {
351 rh->cb (rh->cb_cls,
352 GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR);
353 }
354 else
355 {
356 rh->cb (rh->cb_cls,
357 GNUNET_NAT_ERROR_SUCCESS);
358 }
359 GNUNET_NAT_stun_make_request_cancel (rh);
360 return;
361 }
362
363 rh->dns_success = GNUNET_YES;
364 memset (&server,0, sizeof(server));
365 server.sin_family = AF_INET;
366 server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
367 server.sin_port = htons(rh->stun_port);
368#if HAVE_SOCKADDR_IN_SIN_LEN
369 server.sin_len = (u_char) sizeof (struct sockaddr_in);
370#endif
371
372 /*Craft the simplest possible STUN packet. A request binding*/
373 req = (struct stun_header *)reqdata;
374 generate_request_id (req);
375 reqlen = 0;
376 req->msgtype = 0;
377 req->msglen = 0;
378 req->msglen = htons (reqlen);
379 req->msgtype = htons (encode_message (STUN_REQUEST,
380 STUN_BINDING));
381
382 /* Send the packet */
383 if (-1 ==
384 GNUNET_NETWORK_socket_sendto (rh->sock,
385 req,
386 ntohs(req->msglen) + sizeof(*req),
387 (const struct sockaddr *) &server,
388 sizeof (server)))
389 {
390 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
391 "sendto");
392 rh->dns_success = GNUNET_SYSERR;
393 return;
394 }
395}
396
397
398/**
399 * Make Generic STUN request. Sends a generic stun request to the
400 * server specified using the specified socket, possibly waiting for
401 * a reply and filling the 'reply' field with the externally visible
402 * address.
403 *
404 * @param server the address of the stun server
405 * @param port port of the stun server
406 * @param sock the socket used to send the request
407 * @param cb callback in case of error
408 * @param cb_cls closure for @a cb
409 * @return NULL on error
410 */
411struct GNUNET_NAT_STUN_Handle *
412GNUNET_NAT_stun_make_request (const char *server,
413 uint16_t port,
414 struct GNUNET_NETWORK_Handle *sock,
415 GNUNET_NAT_STUN_ErrorCallback cb,
416 void *cb_cls)
417{
418 struct GNUNET_NAT_STUN_Handle *rh;
419
420 rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle);
421 rh->sock = sock;
422 rh->cb = cb;
423 rh->cb_cls = cb_cls;
424 rh->stun_server = GNUNET_strdup (server);
425 rh->stun_port = port;
426 rh->dns_success = GNUNET_NO;
427 rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server,
428 AF_INET,
429 TIMEOUT,
430 &stun_dns_callback, rh);
431 if (NULL == rh->dns_active)
432 {
433 GNUNET_NAT_stun_make_request_cancel (rh);
434 return NULL;
435 }
436 return rh;
437}
438
439/* end of nat_stun.c */
diff --git a/src/nat/nat_test.c b/src/nat/nat_test.c
deleted file mode 100644
index 803ff23e3..000000000
--- a/src/nat/nat_test.c
+++ /dev/null
@@ -1,645 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2011, 2016 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file nat/nat_test.c
23 * @brief functions to test if the NAT configuration is successful at achieving NAT traversal (with the help of a gnunet-nat-server)
24 * @author Christian Grothoff
25 */
26#include "platform.h"
27#include "gnunet_util_lib.h"
28#include "gnunet_nat_lib.h"
29#include "nat.h"
30
31#define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
32
33#define NAT_SERVER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
34
35/**
36 * Entry we keep for each incoming connection.
37 */
38struct NatActivity
39{
40 /**
41 * This is a doubly-linked list.
42 */
43 struct NatActivity *next;
44
45 /**
46 * This is a doubly-linked list.
47 */
48 struct NatActivity *prev;
49
50 /**
51 * Socket of the incoming connection.
52 */
53 struct GNUNET_NETWORK_Handle *sock;
54
55 /**
56 * Handle of the master context.
57 */
58 struct GNUNET_NAT_Test *h;
59
60 /**
61 * Task reading from the incoming connection.
62 */
63 struct GNUNET_SCHEDULER_Task *rtask;
64};
65
66
67/**
68 * Entry we keep for each connection to the gnunet-nat-service.
69 */
70struct ClientActivity
71{
72 /**
73 * This is a doubly-linked list.
74 */
75 struct ClientActivity *next;
76
77 /**
78 * This is a doubly-linked list.
79 */
80 struct ClientActivity *prev;
81
82 /**
83 * Socket of the incoming connection.
84 */
85 struct GNUNET_MQ_Handle *mq;
86
87 /**
88 * Handle to overall NAT test.
89 */
90 struct GNUNET_NAT_Test *h;
91
92};
93
94
95/**
96 * Handle to a NAT test.
97 */
98struct GNUNET_NAT_Test
99{
100
101 /**
102 * Configuration used
103 */
104 const struct GNUNET_CONFIGURATION_Handle *cfg;
105
106 /**
107 * Function to call with success report
108 */
109 GNUNET_NAT_TestCallback report;
110
111 /**
112 * Closure for @e report.
113 */
114 void *report_cls;
115
116 /**
117 * Handle to NAT traversal in use
118 */
119 struct GNUNET_NAT_Handle *nat;
120
121 /**
122 * Handle to listen socket, or NULL
123 */
124 struct GNUNET_NETWORK_Handle *lsock;
125
126 /**
127 * Head of list of nat activities.
128 */
129 struct NatActivity *na_head;
130
131 /**
132 * Tail of list of nat activities.
133 */
134 struct NatActivity *na_tail;
135
136 /**
137 * Head of list of client activities.
138 */
139 struct ClientActivity *ca_head;
140
141 /**
142 * Tail of list of client activities.
143 */
144 struct ClientActivity *ca_tail;
145
146 /**
147 * Identity of task for the listen socket (if any)
148 */
149 struct GNUNET_SCHEDULER_Task *ltask;
150
151 /**
152 * Task identifier for the timeout (if any)
153 */
154 struct GNUNET_SCHEDULER_Task *ttask;
155
156 /**
157 * #GNUNET_YES if we're testing TCP
158 */
159 int is_tcp;
160
161 /**
162 * Data that should be transmitted or source-port.
163 */
164 uint16_t data;
165
166 /**
167 * Advertised port to the other peer.
168 */
169 uint16_t adv_port;
170
171 /**
172 * Status code to be reported to the timeout/status call
173 */
174 enum GNUNET_NAT_StatusCode status;
175};
176
177
178/**
179 * Function called from #GNUNET_NAT_register whenever someone asks us
180 * to do connection reversal.
181 *
182 * @param cls closure, our `struct GNUNET_NAT_Handle`
183 * @param addr public IP address of the other peer
184 * @param addrlen actual lenght of the @a addr
185 */
186static void
187reversal_cb (void *cls,
188 const struct sockaddr *addr,
189 socklen_t addrlen)
190{
191 struct GNUNET_NAT_Test *h = cls;
192 const struct sockaddr_in *sa;
193
194 if (sizeof (struct sockaddr_in) != addrlen)
195 return;
196 sa = (const struct sockaddr_in *) addr;
197 if (h->data != sa->sin_port)
198 {
199 LOG (GNUNET_ERROR_TYPE_DEBUG,
200 "Received connection reversal request for wrong port\n");
201 return; /* wrong port */
202 }
203 /* report success */
204 h->report (h->report_cls,
205 GNUNET_NAT_ERROR_SUCCESS);
206}
207
208
209/**
210 * Activity on our incoming socket. Read data from the
211 * incoming connection.
212 *
213 * @param cls the `struct GNUNET_NAT_Test`
214 */
215static void
216do_udp_read (void *cls)
217{
218 struct GNUNET_NAT_Test *tst = cls;
219 uint16_t data;
220 const struct GNUNET_SCHEDULER_TaskContext *tc;
221
222 tc = GNUNET_SCHEDULER_get_task_context ();
223 tst->ltask =
224 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
225 tst->lsock,
226 &do_udp_read,
227 tst);
228 if ((NULL != tc->write_ready) &&
229 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
230 tst->lsock)) &&
231 (sizeof (data) ==
232 GNUNET_NETWORK_socket_recv (tst->lsock,
233 &data,
234 sizeof (data))))
235 {
236 if (data == tst->data)
237 tst->report (tst->report_cls,
238 GNUNET_NAT_ERROR_SUCCESS);
239 else
240 LOG (GNUNET_ERROR_TYPE_DEBUG,
241 "Received data mismatches expected value\n");
242 }
243 else
244 LOG (GNUNET_ERROR_TYPE_DEBUG,
245 "Failed to receive data from inbound connection\n");
246}
247
248
249/**
250 * Activity on our incoming socket. Read data from the
251 * incoming connection.
252 *
253 * @param cls the `struct NatActivity`
254 */
255static void
256do_read (void *cls)
257{
258 struct NatActivity *na = cls;
259 struct GNUNET_NAT_Test *tst;
260 uint16_t data;
261 const struct GNUNET_SCHEDULER_TaskContext *tc;
262
263 tc = GNUNET_SCHEDULER_get_task_context ();
264 na->rtask = NULL;
265 tst = na->h;
266 GNUNET_CONTAINER_DLL_remove (tst->na_head,
267 tst->na_tail,
268 na);
269 if ((NULL != tc->write_ready) &&
270 (GNUNET_NETWORK_fdset_isset (tc->read_ready,
271 na->sock)) &&
272 (sizeof (data) ==
273 GNUNET_NETWORK_socket_recv (na->sock,
274 &data,
275 sizeof (data))))
276 {
277 if (data == tst->data)
278 tst->report (tst->report_cls,
279 GNUNET_NAT_ERROR_SUCCESS);
280 else
281 LOG (GNUNET_ERROR_TYPE_DEBUG,
282 "Received data does not match expected value\n");
283 }
284 else
285 LOG (GNUNET_ERROR_TYPE_DEBUG,
286 "Failed to receive data from inbound connection\n");
287 GNUNET_NETWORK_socket_close (na->sock);
288 GNUNET_free (na);
289}
290
291
292/**
293 * Activity on our listen socket. Accept the
294 * incoming connection.
295 *
296 * @param cls the `struct GNUNET_NAT_Test`
297 */
298static void
299do_accept (void *cls)
300{
301 struct GNUNET_NAT_Test *tst = cls;
302 struct GNUNET_NETWORK_Handle *s;
303 struct NatActivity *wl;
304
305 tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
306 tst->lsock,
307 &do_accept,
308 tst);
309 s = GNUNET_NETWORK_socket_accept (tst->lsock,
310 NULL,
311 NULL);
312 if (NULL == s)
313 {
314 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO,
315 "accept");
316 return; /* odd error */
317 }
318 LOG (GNUNET_ERROR_TYPE_DEBUG,
319 "Got an inbound connection, waiting for data\n");
320 wl = GNUNET_new (struct NatActivity);
321 wl->sock = s;
322 wl->h = tst;
323 wl->rtask =
324 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
325 wl->sock,
326 &do_read,
327 wl);
328 GNUNET_CONTAINER_DLL_insert (tst->na_head,
329 tst->na_tail,
330 wl);
331}
332
333
334/**
335 * We got disconnected from the NAT server. Stop
336 * waiting for a reply.
337 *
338 * @param cls the `struct ClientActivity`
339 * @param error error code
340 */
341static void
342mq_error_handler (void *cls,
343 enum GNUNET_MQ_Error error)
344{
345 struct ClientActivity *ca = cls;
346 struct GNUNET_NAT_Test *tst = ca->h;
347
348 GNUNET_CONTAINER_DLL_remove (tst->ca_head,
349 tst->ca_tail,
350 ca);
351 GNUNET_MQ_destroy (ca->mq);
352 GNUNET_free (ca);
353}
354
355
356/**
357 * Address-callback, used to send message to gnunet-nat-server.
358 *
359 * @param cls closure
360 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
361 * the previous (now invalid) one
362 * @param addr either the previous or the new public IP address
363 * @param addrlen actual length of the @a addr
364 */
365static void
366addr_cb (void *cls,
367 int add_remove,
368 const struct sockaddr *addr,
369 socklen_t addrlen)
370{
371 struct GNUNET_NAT_Test *h = cls;
372 struct ClientActivity *ca;
373 struct GNUNET_MQ_Envelope *env;
374 struct GNUNET_NAT_TestMessage *msg;
375 const struct sockaddr_in *sa;
376
377 if (GNUNET_YES != add_remove)
378 return;
379 if (addrlen != sizeof (struct sockaddr_in))
380 {
381 LOG (GNUNET_ERROR_TYPE_DEBUG,
382 "NAT test ignores IPv6 address `%s' returned from NAT library\n",
383 GNUNET_a2s (addr,
384 addrlen));
385 return; /* ignore IPv6 here */
386 }
387 LOG (GNUNET_ERROR_TYPE_INFO,
388 "Asking gnunet-nat-server to connect to `%s'\n",
389 GNUNET_a2s (addr,
390 addrlen));
391
392 ca = GNUNET_new (struct ClientActivity);
393 ca->h = h;
394 ca->mq = GNUNET_CLIENT_connecT (h->cfg,
395 "gnunet-nat-server",
396 NULL,
397 &mq_error_handler,
398 ca);
399 if (NULL == ca->mq)
400 {
401 GNUNET_free (ca);
402 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
403 _("Failed to connect to `gnunet-nat-server'\n"));
404 return;
405 }
406 GNUNET_CONTAINER_DLL_insert (h->ca_head,
407 h->ca_tail,
408 ca);
409 sa = (const struct sockaddr_in *) addr;
410 env = GNUNET_MQ_msg (msg,
411 GNUNET_MESSAGE_TYPE_NAT_TEST);
412 msg->dst_ipv4 = sa->sin_addr.s_addr;
413 msg->dport = sa->sin_port;
414 msg->data = h->data;
415 msg->is_tcp = htonl ((uint32_t) h->is_tcp);
416 GNUNET_MQ_send (ca->mq,
417 env);
418}
419
420
421/**
422 * Timeout task for a nat test.
423 * Calls the report-callback with a timeout return value
424 *
425 * Destroys the nat handle after the callback has been processed.
426 *
427 * @param cls handle to the timed out NAT test
428 */
429static void
430do_timeout (void *cls)
431{
432 struct GNUNET_NAT_Test *nh = cls;
433
434 nh->ttask = NULL;
435 nh->report (nh->report_cls,
436 (GNUNET_NAT_ERROR_SUCCESS == nh->status)
437 ? GNUNET_NAT_ERROR_TIMEOUT
438 : nh->status);
439}
440
441
442/**
443 * Start testing if NAT traversal works using the
444 * given configuration (IPv4-only).
445 *
446 * ALL failures are reported directly to the report callback
447 *
448 * @param cfg configuration for the NAT traversal
449 * @param is_tcp #GNUNET_YES to test TCP, #GNUNET_NO to test UDP
450 * @param bnd_port port to bind to, 0 for connection reversal
451 * @param adv_port externally advertised port to use
452 * @param timeout delay after which the test should be aborted
453 * @param report function to call with the result of the test
454 * @param report_cls closure for @a report
455 * @return handle to cancel NAT test or NULL. The error is always indicated via the report callback
456 */
457struct GNUNET_NAT_Test *
458GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
459 int is_tcp,
460 uint16_t bnd_port,
461 uint16_t adv_port,
462 struct GNUNET_TIME_Relative timeout,
463 GNUNET_NAT_TestCallback report,
464 void *report_cls)
465{
466 struct GNUNET_NAT_Test *nh;
467 struct sockaddr_in sa;
468 const struct sockaddr *addrs[] = {
469 (const struct sockaddr *) &sa
470 };
471 const socklen_t addrlens[] = {
472 sizeof (sa)
473 };
474
475 memset (&sa, 0, sizeof (sa));
476 sa.sin_family = AF_INET;
477 sa.sin_port = htons (bnd_port);
478#if HAVE_SOCKADDR_IN_SIN_LEN
479 sa.sin_len = sizeof (sa);
480#endif
481
482 nh = GNUNET_new (struct GNUNET_NAT_Test);
483 nh->cfg = cfg;
484 nh->is_tcp = is_tcp;
485 nh->data = bnd_port;
486 nh->adv_port = adv_port;
487 nh->report = report;
488 nh->report_cls = report_cls;
489 nh->status = GNUNET_NAT_ERROR_SUCCESS;
490 if (0 == bnd_port)
491 {
492 nh->nat
493 = GNUNET_NAT_register (cfg,
494 is_tcp,
495 0,
496 0,
497 NULL,
498 NULL,
499 &addr_cb,
500 &reversal_cb,
501 nh,
502 NULL);
503 }
504 else
505 {
506 nh->lsock =
507 GNUNET_NETWORK_socket_create (AF_INET,
508 (is_tcp ==
509 GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM,
510 0);
511 if ((nh->lsock == NULL) ||
512 (GNUNET_OK !=
513 GNUNET_NETWORK_socket_bind (nh->lsock,
514 (const struct sockaddr *) &sa,
515 sizeof (sa))))
516 {
517 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
518 _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
519 GNUNET_a2s ((const struct sockaddr *) &sa,
520 sizeof (sa)),
521 STRERROR (errno));
522 if (NULL != nh->lsock)
523 {
524 GNUNET_NETWORK_socket_close (nh->lsock);
525 nh->lsock = NULL;
526 }
527 nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR;
528 nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout,
529 nh);
530 return nh;
531 }
532 if (GNUNET_YES == is_tcp)
533 {
534 GNUNET_break (GNUNET_OK ==
535 GNUNET_NETWORK_socket_listen (nh->lsock,
536 5));
537 nh->ltask =
538 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
539 nh->lsock,
540 &do_accept,
541 nh);
542 }
543 else
544 {
545 nh->ltask =
546 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
547 nh->lsock,
548 &do_udp_read,
549 nh);
550 }
551 LOG (GNUNET_ERROR_TYPE_INFO,
552 "NAT test listens on port %u (%s)\n",
553 bnd_port,
554 (GNUNET_YES == is_tcp) ? "tcp" : "udp");
555 nh->nat = GNUNET_NAT_register (cfg,
556 is_tcp,
557 adv_port,
558 1,
559 addrs,
560 addrlens,
561 &addr_cb,
562 NULL,
563 nh,
564 NULL);
565 if (NULL == nh->nat)
566 {
567 LOG (GNUNET_ERROR_TYPE_INFO,
568 _("NAT test failed to start NAT library\n"));
569 if (NULL != nh->ltask)
570 {
571 GNUNET_SCHEDULER_cancel (nh->ltask);
572 nh->ltask = NULL;
573 }
574 if (NULL != nh->lsock)
575 {
576 GNUNET_NETWORK_socket_close (nh->lsock);
577 nh->lsock = NULL;
578 }
579 nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED;
580 nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout,
581 nh);
582 return nh;
583 }
584 }
585 nh->ttask = GNUNET_SCHEDULER_add_delayed (timeout,
586 &do_timeout,
587 nh);
588 return nh;
589}
590
591
592/**
593 * Stop an active NAT test.
594 *
595 * @param tst test to stop.
596 */
597void
598GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
599{
600 struct NatActivity *pos;
601 struct ClientActivity *cpos;
602
603 LOG (GNUNET_ERROR_TYPE_DEBUG,
604 "Stopping NAT test\n");
605 while (NULL != (cpos = tst->ca_head))
606 {
607 GNUNET_CONTAINER_DLL_remove (tst->ca_head,
608 tst->ca_tail,
609 cpos);
610 GNUNET_MQ_destroy (cpos->mq);
611 GNUNET_free (cpos);
612 }
613 while (NULL != (pos = tst->na_head))
614 {
615 GNUNET_CONTAINER_DLL_remove (tst->na_head,
616 tst->na_tail,
617 pos);
618 GNUNET_SCHEDULER_cancel (pos->rtask);
619 GNUNET_NETWORK_socket_close (pos->sock);
620 GNUNET_free (pos);
621 }
622 if (NULL != tst->ttask)
623 {
624 GNUNET_SCHEDULER_cancel (tst->ttask);
625 tst->ttask = NULL;
626 }
627 if (NULL != tst->ltask)
628 {
629 GNUNET_SCHEDULER_cancel (tst->ltask);
630 tst->ltask = NULL;
631 }
632 if (NULL != tst->lsock)
633 {
634 GNUNET_NETWORK_socket_close (tst->lsock);
635 tst->lsock = NULL;
636 }
637 if (NULL != tst->nat)
638 {
639 GNUNET_NAT_unregister (tst->nat);
640 tst->nat = NULL;
641 }
642 GNUNET_free (tst);
643}
644
645/* end of nat_test.c */