If 0 max search, use r5n dht
[oweals/gnunet.git] / src / nat / nat_test.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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  */
38 struct 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   GNUNET_SCHEDULER_TaskIdentifier rtask;
64 };
65
66
67 /**
68  * Entry we keep for each connection to the gnunet-nat-service.
69  */
70 struct 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_CLIENT_Connection *client;
86
87 };
88
89
90 /**
91  * Handle to a NAT test.
92  */
93 struct GNUNET_NAT_Test
94 {
95
96   /**
97    * Configuration used
98    */
99   const struct GNUNET_CONFIGURATION_Handle *cfg;
100
101   /**
102    * Function to call with success report
103    */
104   GNUNET_NAT_TestCallback report;
105
106   /**
107    * Closure for @e report.
108    */
109   void *report_cls;
110
111   /**
112    * Handle to NAT traversal in use
113    */
114   struct GNUNET_NAT_Handle *nat;
115
116   /**
117    * Handle to listen socket, or NULL
118    */
119   struct GNUNET_NETWORK_Handle *lsock;
120
121   /**
122    * Head of list of nat activities.
123    */
124   struct NatActivity *na_head;
125
126   /**
127    * Tail of list of nat activities.
128    */
129   struct NatActivity *na_tail;
130
131   /**
132    * Head of list of client activities.
133    */
134   struct ClientActivity *ca_head;
135
136   /**
137    * Tail of list of client activities.
138    */
139   struct ClientActivity *ca_tail;
140
141   /**
142    * Identity of task for the listen socket (if any)
143    */
144   GNUNET_SCHEDULER_TaskIdentifier ltask;
145   
146   /**
147    * Task identifier for the timeout (if any)
148    */
149   GNUNET_SCHEDULER_TaskIdentifier ttask;
150
151   /**
152    * GNUNET_YES if we're testing TCP
153    */
154   int is_tcp;
155
156   /**
157    * Data that should be transmitted or source-port.
158    */
159   uint16_t data;
160
161   /**
162    * Advertised port to the other peer.
163    */
164   uint16_t adv_port;
165
166   /**
167    * Status code to be reported to the timeout/status call
168    */
169   enum GNUNET_NAT_StatusCode status;
170 };
171
172
173 /**
174  * Function called from #GNUNET_NAT_register whenever someone asks us
175  * to do connection reversal.
176  *
177  * @param cls closure, our `struct GNUNET_NAT_Handle`
178  * @param addr public IP address of the other peer
179  * @param addrlen actual lenght of the address
180  */
181 static void
182 reversal_cb (void *cls,
183              const struct sockaddr *addr,
184              socklen_t addrlen)
185 {
186   struct GNUNET_NAT_Test *h = cls;
187   const struct sockaddr_in *sa;
188
189   if (sizeof (struct sockaddr_in) != addrlen)
190     return;
191   sa = (const struct sockaddr_in *) addr;
192   if (h->data != sa->sin_port)
193   {
194     LOG (GNUNET_ERROR_TYPE_DEBUG,
195          "Received connection reversal request for wrong port\n");
196     return;                     /* wrong port */
197   }
198   /* report success */
199   h->report (h->report_cls, GNUNET_NAT_ERROR_SUCCESS);
200 }
201
202
203 /**
204  * Activity on our incoming socket.  Read data from the
205  * incoming connection.
206  *
207  * @param cls the `struct GNUNET_NAT_Test`
208  * @param tc scheduler context
209  */
210 static void
211 do_udp_read (void *cls,
212              const struct GNUNET_SCHEDULER_TaskContext *tc)
213 {
214   struct GNUNET_NAT_Test *tst = cls;
215   uint16_t data;
216
217   tst->ltask =
218       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
219                                      tst->lsock,
220                                      &do_udp_read, tst);
221   if ((NULL != tc->write_ready) &&
222       (GNUNET_NETWORK_fdset_isset (tc->read_ready, tst->lsock)) &&
223       (sizeof (data) ==
224        GNUNET_NETWORK_socket_recv (tst->lsock, &data, sizeof (data))))
225   {
226     if (data == tst->data)
227       tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS);
228     else
229       LOG (GNUNET_ERROR_TYPE_DEBUG,
230            "Received data mismatches expected value\n");
231   }
232   else
233     LOG (GNUNET_ERROR_TYPE_DEBUG,
234          "Failed to receive data from inbound connection\n");
235 }
236
237
238 /**
239  * Activity on our incoming socket.  Read data from the
240  * incoming connection.
241  *
242  * @param cls the `struct NatActivity`
243  * @param tc scheduler context
244  */
245 static void
246 do_read (void *cls,
247          const struct GNUNET_SCHEDULER_TaskContext *tc)
248 {
249   struct NatActivity *na = cls;
250   struct GNUNET_NAT_Test *tst;
251   uint16_t data;
252
253   na->rtask = GNUNET_SCHEDULER_NO_TASK;
254   tst = na->h;
255   GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, na);
256   if ((NULL != tc->write_ready) &&
257       (GNUNET_NETWORK_fdset_isset (tc->read_ready, na->sock)) &&
258       (sizeof (data) ==
259        GNUNET_NETWORK_socket_recv (na->sock, &data, sizeof (data))))
260   {
261     if (data == tst->data)
262       tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS);
263     else
264       LOG (GNUNET_ERROR_TYPE_DEBUG,
265            "Received data does not match expected value\n");
266   }
267   else
268     LOG (GNUNET_ERROR_TYPE_DEBUG,
269          "Failed to receive data from inbound connection\n");
270   GNUNET_NETWORK_socket_close (na->sock);
271   GNUNET_free (na);
272 }
273
274
275 /**
276  * Activity on our listen socket. Accept the
277  * incoming connection.
278  *
279  * @param cls the `struct GNUNET_NAT_Test`
280  * @param tc scheduler context
281  */
282 static void
283 do_accept (void *cls,
284            const struct GNUNET_SCHEDULER_TaskContext *tc)
285 {
286   struct GNUNET_NAT_Test *tst = cls;
287   struct GNUNET_NETWORK_Handle *s;
288   struct NatActivity *wl;
289
290   tst->ltask = GNUNET_SCHEDULER_NO_TASK;
291   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
292     return;
293   tst->ltask =
294       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, tst->lsock,
295                                      &do_accept, tst);
296   s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL);
297   if (NULL == s)
298   {
299     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept");
300     return;                     /* odd error */
301   }
302   LOG (GNUNET_ERROR_TYPE_DEBUG,
303        "Got an inbound connection, waiting for data\n");
304   wl = GNUNET_new (struct NatActivity);
305   wl->sock = s;
306   wl->h = tst;
307   wl->rtask =
308     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
309                                    wl->sock,
310                                    &do_read, wl);
311   GNUNET_CONTAINER_DLL_insert (tst->na_head, tst->na_tail, wl);
312 }
313
314
315 /**
316  * Address-callback, used to send message to gnunet-nat-server.
317  *
318  * @param cls closure
319  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
320  *     the previous (now invalid) one
321  * @param addr either the previous or the new public IP address
322  * @param addrlen actual length of the @a addr
323  */
324 static void
325 addr_cb (void *cls,
326          int add_remove,
327          const struct sockaddr *addr,
328          socklen_t addrlen)
329 {
330   struct GNUNET_NAT_Test *h = cls;
331   struct ClientActivity *ca;
332   struct GNUNET_CLIENT_Connection *client;
333   struct GNUNET_NAT_TestMessage msg;
334   const struct sockaddr_in *sa;
335
336   if (GNUNET_YES != add_remove)
337     return;
338   if (addrlen != sizeof (struct sockaddr_in))
339   {
340     LOG (GNUNET_ERROR_TYPE_DEBUG,
341          "NAT test ignores IPv6 address `%s' returned from NAT library\n",
342          GNUNET_a2s (addr, addrlen));
343     return;                     /* ignore IPv6 here */
344   }
345   LOG (GNUNET_ERROR_TYPE_INFO,
346        "Asking gnunet-nat-server to connect to `%s'\n",
347        GNUNET_a2s (addr, addrlen));
348   sa = (const struct sockaddr_in *) addr;
349   msg.header.size = htons (sizeof (struct GNUNET_NAT_TestMessage));
350   msg.header.type = htons (GNUNET_MESSAGE_TYPE_NAT_TEST);
351   msg.dst_ipv4 = sa->sin_addr.s_addr;
352   msg.dport = sa->sin_port;
353   msg.data = h->data;
354   msg.is_tcp = htonl ((uint32_t) h->is_tcp);
355
356   client = GNUNET_CLIENT_connect ("gnunet-nat-server", h->cfg);
357   if (NULL == client)
358   {
359     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
360                 _("Failed to connect to `gnunet-nat-server'\n"));
361     return;
362   }
363   ca = GNUNET_new (struct ClientActivity);
364   ca->client = client;
365   GNUNET_CONTAINER_DLL_insert (h->ca_head, h->ca_tail, ca);
366   GNUNET_break (GNUNET_OK ==
367                 GNUNET_CLIENT_transmit_and_get_response (client, &msg.header,
368                                                          NAT_SERVER_TIMEOUT,
369                                                          GNUNET_YES, NULL,
370                                                          NULL));
371 }
372
373
374 /**
375  * Timeout task for a nat test. 
376  * Calls the report-callback with a timeout return value
377  * 
378  * Destroys the nat handle after the callback has been processed.
379  * 
380  * @param cls handle to the timed out NAT test
381  * @param tc not used
382  */
383 static void
384 do_timeout (void *cls,
385                  const struct GNUNET_SCHEDULER_TaskContext * tc)
386 {
387   struct GNUNET_NAT_Test *nh = (struct GNUNET_NAT_Test *) cls;
388   
389   nh->ttask = GNUNET_SCHEDULER_NO_TASK;
390   nh->report (nh->report_cls, (GNUNET_NAT_ERROR_SUCCESS == nh->status)? GNUNET_NAT_ERROR_TIMEOUT: nh->status );
391   
392   GNUNET_NAT_test_stop(nh);
393 }
394
395
396 /**
397  * Start testing if NAT traversal works using the
398  * given configuration (IPv4-only).
399  * 
400  * ALL failures are reported directly to the report callback
401  *
402  * @param cfg configuration for the NAT traversal
403  * @param is_tcp #GNUNET_YES to test TCP, #GNUNET_NO to test UDP
404  * @param bnd_port port to bind to, 0 for connection reversal
405  * @param adv_port externally advertised port to use
406  * @param timeout delay after which the test should be aborted
407  * @param report function to call with the result of the test
408  * @param report_cls closure for @a report
409  * @return handle to cancel NAT test or NULL. The error is always indicated via the report callback
410  */
411 struct GNUNET_NAT_Test *
412 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
413                        int is_tcp,
414                        uint16_t bnd_port,
415                        uint16_t adv_port,
416                        struct GNUNET_TIME_Relative timeout,
417                        GNUNET_NAT_TestCallback report,
418                        void *report_cls)
419 {
420   struct GNUNET_NAT_Test *nh;
421   struct sockaddr_in sa;
422   const struct sockaddr *addrs[] = { (const struct sockaddr *) &sa };
423   const socklen_t addrlens[] = { sizeof (sa) };
424
425   memset (&sa, 0, sizeof (sa));
426   sa.sin_family = AF_INET;
427   sa.sin_port = htons (bnd_port);
428 #if HAVE_SOCKADDR_IN_SIN_LEN
429   sa.sin_len = sizeof (sa);
430 #endif
431
432   nh = GNUNET_new (struct GNUNET_NAT_Test);
433   nh->cfg = cfg;
434   nh->is_tcp = is_tcp;
435   nh->data = bnd_port;
436   nh->adv_port = adv_port;
437   nh->report = report;
438   nh->report_cls = report_cls;
439   nh->ttask = GNUNET_SCHEDULER_NO_TASK;
440   nh->status = GNUNET_NAT_ERROR_SUCCESS;
441   if (0 == bnd_port)
442   {
443     nh->nat =
444         GNUNET_NAT_register (cfg, is_tcp, 0, 0, NULL, NULL, &addr_cb,
445                              &reversal_cb, nh);
446   }
447   else
448   {
449     nh->lsock =
450         GNUNET_NETWORK_socket_create (AF_INET,
451                                       (is_tcp ==
452                                        GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM,
453                                       0);
454     if ((nh->lsock == NULL) ||
455         (GNUNET_OK !=
456          GNUNET_NETWORK_socket_bind (nh->lsock, (const struct sockaddr *) &sa,
457                                      sizeof (sa))))
458     {
459       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
460                   _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
461                   GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)),
462                   STRERROR (errno));
463       if (NULL != nh->lsock)
464         GNUNET_NETWORK_socket_close (nh->lsock);
465       nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR;
466       nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh);
467       return NULL;
468     }
469     if (GNUNET_YES == is_tcp)
470     {
471       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_listen (nh->lsock, 5));
472       nh->ltask =
473           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
474                                          nh->lsock, &do_accept, nh);
475     }
476     else
477     {
478       nh->ltask =
479           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
480                                          nh->lsock, &do_udp_read, nh);
481     }
482     LOG (GNUNET_ERROR_TYPE_DEBUG,
483          "NAT test listens on port %u (%s)\n",
484          bnd_port,
485          (GNUNET_YES == is_tcp) ? "tcp" : "udp");
486     nh->nat = GNUNET_NAT_register (cfg, is_tcp, adv_port, 1, addrs, addrlens,
487                              &addr_cb, NULL, nh);
488     if (NULL == nh->nat)
489     {
490       LOG (GNUNET_ERROR_TYPE_ERROR,
491           _("NAT test failed to start NAT library\n"));
492       if (GNUNET_SCHEDULER_NO_TASK != nh->ltask){
493         GNUNET_SCHEDULER_cancel (nh->ltask);
494         nh->ltask = GNUNET_SCHEDULER_NO_TASK;
495       }
496       if (NULL != nh->lsock){
497         GNUNET_NETWORK_socket_close (nh->lsock);
498         nh->lsock = NULL;
499       }
500       nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED;
501       nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh);
502       return NULL;
503     }
504   }
505   nh->ttask = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);
506   return nh;
507 }
508
509
510 /**
511  * Stop an active NAT test.
512  *
513  * @param tst test to stop.
514  */
515 void
516 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
517 {
518   struct NatActivity *pos;
519   struct ClientActivity *cpos;
520
521   LOG (GNUNET_ERROR_TYPE_DEBUG,
522        "Stopping NAT test\n");
523   while (NULL != (cpos = tst->ca_head))
524   {
525     GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, cpos);
526     GNUNET_CLIENT_disconnect (cpos->client);
527     GNUNET_free (cpos);
528   }
529   while (NULL != (pos = tst->na_head))
530   {
531     GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, pos);
532     GNUNET_SCHEDULER_cancel (pos->rtask);
533     GNUNET_NETWORK_socket_close (pos->sock);
534     GNUNET_free (pos);
535   }
536   if (GNUNET_SCHEDULER_NO_TASK != tst->ttask)
537     GNUNET_SCHEDULER_cancel (tst->ttask);
538   if (GNUNET_SCHEDULER_NO_TASK != tst->ltask)
539     GNUNET_SCHEDULER_cancel (tst->ltask);
540   if (NULL != tst->lsock)
541     GNUNET_NETWORK_socket_close (tst->lsock);
542   GNUNET_NAT_unregister (tst->nat);
543   GNUNET_free (tst);
544 }
545
546 /* end of nat_test.c */