gnunet-nat, tool to suggest changes to configure based on NAT configuration
[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   printf("Inbound");
291
292   tst->ltask = NULL;
293   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
294     return;
295   tst->ltask =
296       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, tst->lsock,
297                                      &do_accept, tst);
298   s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL);
299   if (NULL == s)
300   {
301     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept");
302     return;                     /* odd error */
303   }
304   LOG (GNUNET_ERROR_TYPE_DEBUG,
305        "Got an inbound connection, waiting for data\n");
306   wl = GNUNET_new (struct NatActivity);
307   wl->sock = s;
308   wl->h = tst;
309   wl->rtask =
310     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
311                                    wl->sock,
312                                    &do_read, wl);
313   GNUNET_CONTAINER_DLL_insert (tst->na_head, tst->na_tail, wl);
314 }
315
316
317 /**
318  * Address-callback, used to send message to gnunet-nat-server.
319  *
320  * @param cls closure
321  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
322  *     the previous (now invalid) one
323  * @param addr either the previous or the new public IP address
324  * @param addrlen actual length of the @a addr
325  */
326 static void
327 addr_cb (void *cls,
328          int add_remove,
329          const struct sockaddr *addr,
330          socklen_t addrlen)
331 {
332   struct GNUNET_NAT_Test *h = cls;
333   struct ClientActivity *ca;
334   struct GNUNET_CLIENT_Connection *client;
335   struct GNUNET_NAT_TestMessage msg;
336   const struct sockaddr_in *sa;
337
338   printf("Addr callback");
339
340   if (GNUNET_YES != add_remove)
341     return;
342   if (addrlen != sizeof (struct sockaddr_in))
343   {
344     LOG (GNUNET_ERROR_TYPE_DEBUG,
345          "NAT test ignores IPv6 address `%s' returned from NAT library\n",
346          GNUNET_a2s (addr, addrlen));
347     return;                     /* ignore IPv6 here */
348   }
349   LOG (GNUNET_ERROR_TYPE_INFO,
350        "Asking gnunet-nat-server to connect to `%s'\n",
351        GNUNET_a2s (addr, addrlen));
352   sa = (const struct sockaddr_in *) addr;
353   msg.header.size = htons (sizeof (struct GNUNET_NAT_TestMessage));
354   msg.header.type = htons (GNUNET_MESSAGE_TYPE_NAT_TEST);
355   msg.dst_ipv4 = sa->sin_addr.s_addr;
356   msg.dport = sa->sin_port;
357   msg.data = h->data;
358   msg.is_tcp = htonl ((uint32_t) h->is_tcp);
359
360   client = GNUNET_CLIENT_connect ("gnunet-nat-server", h->cfg);
361   if (NULL == client)
362   {
363     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
364                 _("Failed to connect to `gnunet-nat-server'\n"));
365     return;
366   }
367   ca = GNUNET_new (struct ClientActivity);
368   ca->client = client;
369   GNUNET_CONTAINER_DLL_insert (h->ca_head, h->ca_tail, ca);
370   GNUNET_break (GNUNET_OK ==
371                 GNUNET_CLIENT_transmit_and_get_response (client, &msg.header,
372                                                          NAT_SERVER_TIMEOUT,
373                                                          GNUNET_YES, NULL,
374                                                          NULL));
375 }
376
377
378 /**
379  * Timeout task for a nat test.
380  * Calls the report-callback with a timeout return value
381  *
382  * Destroys the nat handle after the callback has been processed.
383  *
384  * @param cls handle to the timed out NAT test
385  * @param tc not used
386  */
387 static void
388 do_timeout (void *cls,
389             const struct GNUNET_SCHEDULER_TaskContext *tc)
390 {
391   struct GNUNET_NAT_Test *nh = cls;
392
393   nh->ttask = NULL;
394   nh->report (nh->report_cls,
395               (GNUNET_NAT_ERROR_SUCCESS == nh->status)
396               ? GNUNET_NAT_ERROR_TIMEOUT
397               : nh->status);
398 }
399
400
401 /**
402  * Start testing if NAT traversal works using the
403  * given configuration (IPv4-only).
404  *
405  * ALL failures are reported directly to the report callback
406  *
407  * @param cfg configuration for the NAT traversal
408  * @param is_tcp #GNUNET_YES to test TCP, #GNUNET_NO to test UDP
409  * @param bnd_port port to bind to, 0 for connection reversal
410  * @param adv_port externally advertised port to use
411  * @param timeout delay after which the test should be aborted
412  * @param report function to call with the result of the test
413  * @param report_cls closure for @a report
414  * @return handle to cancel NAT test or NULL. The error is always indicated via the report callback
415  */
416 struct GNUNET_NAT_Test *
417 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
418                        int is_tcp,
419                        uint16_t bnd_port,
420                        uint16_t adv_port,
421                        struct GNUNET_TIME_Relative timeout,
422                        GNUNET_NAT_TestCallback report,
423                        void *report_cls)
424 {
425   struct GNUNET_NAT_Test *nh;
426   struct sockaddr_in sa;
427   const struct sockaddr *addrs[] = { (const struct sockaddr *) &sa };
428   const socklen_t addrlens[] = { sizeof (sa) };
429
430   memset (&sa, 0, sizeof (sa));
431   sa.sin_family = AF_INET;
432   sa.sin_port = htons (bnd_port);
433 #if HAVE_SOCKADDR_IN_SIN_LEN
434   sa.sin_len = sizeof (sa);
435 #endif
436
437   nh = GNUNET_new (struct GNUNET_NAT_Test);
438   nh->cfg = cfg;
439   nh->is_tcp = is_tcp;
440   nh->data = bnd_port;
441   nh->adv_port = adv_port;
442   nh->report = report;
443   nh->report_cls = report_cls;
444   nh->status = GNUNET_NAT_ERROR_SUCCESS;
445   if (0 == bnd_port)
446   {
447     nh->nat 
448       = GNUNET_NAT_register (cfg, is_tcp, 0, 0, 
449                              NULL, NULL,
450                              &addr_cb,
451                              &reversal_cb, nh, NULL);
452   }
453   else
454   {
455     printf("Vou criar o socket");
456     nh->lsock =
457         GNUNET_NETWORK_socket_create (AF_INET,
458                                       (is_tcp ==
459                                        GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM,
460                                       0);
461     if ((nh->lsock == NULL) ||
462         (GNUNET_OK !=
463          GNUNET_NETWORK_socket_bind (nh->lsock, (const struct sockaddr *) &sa,
464                                      sizeof (sa))))
465     {
466       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
467                   _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
468                   GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)),
469                   STRERROR (errno));
470       if (NULL != nh->lsock)
471       {
472         GNUNET_NETWORK_socket_close (nh->lsock);
473         nh->lsock = NULL;
474       }
475       nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR;
476       nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh);
477       return nh;
478     }
479     if (GNUNET_YES == is_tcp)
480     {
481       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_listen (nh->lsock, 5));
482       nh->ltask =
483           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
484                                          nh->lsock, &do_accept, nh);
485     }
486     else
487     {
488       nh->ltask =
489           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
490                                          nh->lsock, &do_udp_read, nh);
491     }
492     LOG (GNUNET_ERROR_TYPE_INFO,
493          "NAT test listens on port %u (%s)\n",
494          bnd_port,
495          (GNUNET_YES == is_tcp) ? "tcp" : "udp");
496     nh->nat = GNUNET_NAT_register (cfg, is_tcp, adv_port, 1,
497                                    addrs, addrlens,
498                                    &addr_cb, NULL, nh, NULL);
499     if (NULL == nh->nat)
500     {
501       LOG (GNUNET_ERROR_TYPE_INFO,
502           _("NAT test failed to start NAT library\n"));
503       if (NULL != nh->ltask)
504       {
505         GNUNET_SCHEDULER_cancel (nh->ltask);
506         nh->ltask = NULL;
507       }
508       if (NULL != nh->lsock)
509       {
510         GNUNET_NETWORK_socket_close (nh->lsock);
511         nh->lsock = NULL;
512       }
513       nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED;
514       nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh);
515       return nh;
516     }
517   }
518   nh->ttask = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);
519   return nh;
520 }
521
522
523 /**
524  * Stop an active NAT test.
525  *
526  * @param tst test to stop.
527  */
528 void
529 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
530 {
531   struct NatActivity *pos;
532   struct ClientActivity *cpos;
533
534   LOG (GNUNET_ERROR_TYPE_DEBUG,
535        "Stopping NAT test\n");
536   while (NULL != (cpos = tst->ca_head))
537   {
538     GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, cpos);
539     GNUNET_CLIENT_disconnect (cpos->client);
540     GNUNET_free (cpos);
541   }
542   while (NULL != (pos = tst->na_head))
543   {
544     GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, pos);
545     GNUNET_SCHEDULER_cancel (pos->rtask);
546     GNUNET_NETWORK_socket_close (pos->sock);
547     GNUNET_free (pos);
548   }
549   if (NULL != tst->ttask)
550     GNUNET_SCHEDULER_cancel (tst->ttask);
551   if (NULL != tst->ltask)
552     GNUNET_SCHEDULER_cancel (tst->ltask);
553   if (NULL != tst->lsock)
554     GNUNET_NETWORK_socket_close (tst->lsock);
555   if (NULL != tst->nat)
556     GNUNET_NAT_unregister (tst->nat);
557   GNUNET_free (tst);
558 }
559
560 /* end of nat_test.c */