Add missing file
[oweals/gnunet.git] / src / nat / nat_test.c
1 /*
2      This file is part of GNUnet.
3      Copyright (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., 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  */
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   struct GNUNET_SCHEDULER_Task * 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   struct GNUNET_SCHEDULER_Task * ltask;
145
146   /**
147    * Task identifier for the timeout (if any)
148    */
149   struct GNUNET_SCHEDULER_Task * 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 = NULL;
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 = NULL;
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 = cls;
388
389   nh->ttask = NULL;
390   nh->report (nh->report_cls,
391               (GNUNET_NAT_ERROR_SUCCESS == nh->status)
392               ? GNUNET_NAT_ERROR_TIMEOUT
393               : nh->status);
394 }
395
396
397 /**
398  * Start testing if NAT traversal works using the
399  * given configuration (IPv4-only).
400  *
401  * ALL failures are reported directly to the report callback
402  *
403  * @param cfg configuration for the NAT traversal
404  * @param is_tcp #GNUNET_YES to test TCP, #GNUNET_NO to test UDP
405  * @param bnd_port port to bind to, 0 for connection reversal
406  * @param adv_port externally advertised port to use
407  * @param timeout delay after which the test should be aborted
408  * @param report function to call with the result of the test
409  * @param report_cls closure for @a report
410  * @return handle to cancel NAT test or NULL. The error is always indicated via the report callback
411  */
412 struct GNUNET_NAT_Test *
413 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
414                        int is_tcp,
415                        uint16_t bnd_port,
416                        uint16_t adv_port,
417                        struct GNUNET_TIME_Relative timeout,
418                        GNUNET_NAT_TestCallback report,
419                        void *report_cls)
420 {
421   struct GNUNET_NAT_Test *nh;
422   struct sockaddr_in sa;
423   const struct sockaddr *addrs[] = { (const struct sockaddr *) &sa };
424   const socklen_t addrlens[] = { sizeof (sa) };
425
426   memset (&sa, 0, sizeof (sa));
427   sa.sin_family = AF_INET;
428   sa.sin_port = htons (bnd_port);
429 #if HAVE_SOCKADDR_IN_SIN_LEN
430   sa.sin_len = sizeof (sa);
431 #endif
432
433   nh = GNUNET_new (struct GNUNET_NAT_Test);
434   nh->cfg = cfg;
435   nh->is_tcp = is_tcp;
436   nh->data = bnd_port;
437   nh->adv_port = adv_port;
438   nh->report = report;
439   nh->report_cls = report_cls;
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, 
445                              NULL, NULL,
446                              &addr_cb,
447                              &reversal_cb, nh, NULL);
448   }
449   else
450   {
451     nh->lsock =
452         GNUNET_NETWORK_socket_create (AF_INET,
453                                       (is_tcp ==
454                                        GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM,
455                                       0);
456     if ((nh->lsock == NULL) ||
457         (GNUNET_OK !=
458          GNUNET_NETWORK_socket_bind (nh->lsock, (const struct sockaddr *) &sa,
459                                      sizeof (sa))))
460     {
461       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
462                   _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
463                   GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)),
464                   STRERROR (errno));
465       if (NULL != nh->lsock)
466       {
467         GNUNET_NETWORK_socket_close (nh->lsock);
468         nh->lsock = NULL;
469       }
470       nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR;
471       nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh);
472       return nh;
473     }
474     if (GNUNET_YES == is_tcp)
475     {
476       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_listen (nh->lsock, 5));
477       nh->ltask =
478           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
479                                          nh->lsock, &do_accept, nh);
480     }
481     else
482     {
483       nh->ltask =
484           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
485                                          nh->lsock, &do_udp_read, nh);
486     }
487     LOG (GNUNET_ERROR_TYPE_DEBUG,
488          "NAT test listens on port %u (%s)\n",
489          bnd_port,
490          (GNUNET_YES == is_tcp) ? "tcp" : "udp");
491     nh->nat = GNUNET_NAT_register (cfg, is_tcp, adv_port, 1,
492                                    addrs, addrlens,
493                                    &addr_cb, NULL, nh, NULL);
494     if (NULL == nh->nat)
495     {
496       LOG (GNUNET_ERROR_TYPE_ERROR,
497           _("NAT test failed to start NAT library\n"));
498       if (NULL != nh->ltask)
499       {
500         GNUNET_SCHEDULER_cancel (nh->ltask);
501         nh->ltask = NULL;
502       }
503       if (NULL != nh->lsock)
504       {
505         GNUNET_NETWORK_socket_close (nh->lsock);
506         nh->lsock = NULL;
507       }
508       nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED;
509       nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh);
510       return nh;
511     }
512   }
513   nh->ttask = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);
514   return nh;
515 }
516
517
518 /**
519  * Stop an active NAT test.
520  *
521  * @param tst test to stop.
522  */
523 void
524 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
525 {
526   struct NatActivity *pos;
527   struct ClientActivity *cpos;
528
529   LOG (GNUNET_ERROR_TYPE_DEBUG,
530        "Stopping NAT test\n");
531   while (NULL != (cpos = tst->ca_head))
532   {
533     GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, cpos);
534     GNUNET_CLIENT_disconnect (cpos->client);
535     GNUNET_free (cpos);
536   }
537   while (NULL != (pos = tst->na_head))
538   {
539     GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, pos);
540     GNUNET_SCHEDULER_cancel (pos->rtask);
541     GNUNET_NETWORK_socket_close (pos->sock);
542     GNUNET_free (pos);
543   }
544   if (NULL != tst->ttask)
545     GNUNET_SCHEDULER_cancel (tst->ttask);
546   if (NULL != tst->ltask)
547     GNUNET_SCHEDULER_cancel (tst->ltask);
548   if (NULL != tst->lsock)
549     GNUNET_NETWORK_socket_close (tst->lsock);
550   if (NULL != tst->nat)
551     GNUNET_NAT_unregister (tst->nat);
552   GNUNET_free (tst);
553 }
554
555 /* end of nat_test.c */