-indentation
[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
168
169 /**
170  * Function called from #GNUNET_NAT_register whenever someone asks us
171  * to do connection reversal.
172  *
173  * @param cls closure, our `struct GNUNET_NAT_Handle`
174  * @param addr public IP address of the other peer
175  * @param addrlen actual lenght of the address
176  */
177 static void
178 reversal_cb (void *cls,
179              const struct sockaddr *addr,
180              socklen_t addrlen)
181 {
182   struct GNUNET_NAT_Test *h = cls;
183   const struct sockaddr_in *sa;
184
185   if (sizeof (struct sockaddr_in) != addrlen)
186     return;
187   sa = (const struct sockaddr_in *) addr;
188   if (h->data != sa->sin_port)
189   {
190     LOG (GNUNET_ERROR_TYPE_DEBUG,
191          "Received connection reversal request for wrong port\n");
192     return;                     /* wrong port */
193   }
194   /* report success */
195   h->report (h->report_cls, GNUNET_NAT_ERROR_SUCCESS);
196 }
197
198
199 /**
200  * Activity on our incoming socket.  Read data from the
201  * incoming connection.
202  *
203  * @param cls the `struct GNUNET_NAT_Test`
204  * @param tc scheduler context
205  */
206 static void
207 do_udp_read (void *cls,
208              const struct GNUNET_SCHEDULER_TaskContext *tc)
209 {
210   struct GNUNET_NAT_Test *tst = cls;
211   uint16_t data;
212
213   tst->ltask =
214       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
215                                      tst->lsock,
216                                      &do_udp_read, tst);
217   if ((NULL != tc->write_ready) &&
218       (GNUNET_NETWORK_fdset_isset (tc->read_ready, tst->lsock)) &&
219       (sizeof (data) ==
220        GNUNET_NETWORK_socket_recv (tst->lsock, &data, sizeof (data))))
221   {
222     if (data == tst->data)
223       tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS);
224     else
225       LOG (GNUNET_ERROR_TYPE_DEBUG,
226            "Received data mismatches expected value\n");
227   }
228   else
229     LOG (GNUNET_ERROR_TYPE_DEBUG,
230          "Failed to receive data from inbound connection\n");
231 }
232
233
234 /**
235  * Activity on our incoming socket.  Read data from the
236  * incoming connection.
237  *
238  * @param cls the `struct NatActivity`
239  * @param tc scheduler context
240  */
241 static void
242 do_read (void *cls,
243          const struct GNUNET_SCHEDULER_TaskContext *tc)
244 {
245   struct NatActivity *na = cls;
246   struct GNUNET_NAT_Test *tst;
247   uint16_t data;
248
249   na->rtask = GNUNET_SCHEDULER_NO_TASK;
250   tst = na->h;
251   GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, na);
252   if ((NULL != tc->write_ready) &&
253       (GNUNET_NETWORK_fdset_isset (tc->read_ready, na->sock)) &&
254       (sizeof (data) ==
255        GNUNET_NETWORK_socket_recv (na->sock, &data, sizeof (data))))
256   {
257     if (data == tst->data)
258       tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS);
259     else
260       LOG (GNUNET_ERROR_TYPE_DEBUG,
261            "Received data does not match expected value\n");
262   }
263   else
264     LOG (GNUNET_ERROR_TYPE_DEBUG,
265          "Failed to receive data from inbound connection\n");
266   GNUNET_NETWORK_socket_close (na->sock);
267   GNUNET_free (na);
268 }
269
270
271 /**
272  * Activity on our listen socket. Accept the
273  * incoming connection.
274  *
275  * @param cls the `struct GNUNET_NAT_Test`
276  * @param tc scheduler context
277  */
278 static void
279 do_accept (void *cls,
280            const struct GNUNET_SCHEDULER_TaskContext *tc)
281 {
282   struct GNUNET_NAT_Test *tst = cls;
283   struct GNUNET_NETWORK_Handle *s;
284   struct NatActivity *wl;
285
286   tst->ltask = GNUNET_SCHEDULER_NO_TASK;
287   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
288     return;
289   tst->ltask =
290       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, tst->lsock,
291                                      &do_accept, tst);
292   s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL);
293   if (NULL == s)
294   {
295     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept");
296     return;                     /* odd error */
297   }
298   LOG (GNUNET_ERROR_TYPE_DEBUG,
299        "Got an inbound connection, waiting for data\n");
300   wl = GNUNET_new (struct NatActivity);
301   wl->sock = s;
302   wl->h = tst;
303   wl->rtask =
304     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
305                                    wl->sock,
306                                    &do_read, wl);
307   GNUNET_CONTAINER_DLL_insert (tst->na_head, tst->na_tail, wl);
308 }
309
310
311 /**
312  * Address-callback, used to send message to gnunet-nat-server.
313  *
314  * @param cls closure
315  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
316  *     the previous (now invalid) one
317  * @param addr either the previous or the new public IP address
318  * @param addrlen actual length of the @a addr
319  */
320 static void
321 addr_cb (void *cls,
322          int add_remove,
323          const struct sockaddr *addr,
324          socklen_t addrlen)
325 {
326   struct GNUNET_NAT_Test *h = cls;
327   struct ClientActivity *ca;
328   struct GNUNET_CLIENT_Connection *client;
329   struct GNUNET_NAT_TestMessage msg;
330   const struct sockaddr_in *sa;
331
332   if (GNUNET_YES != add_remove)
333     return;
334   if (addrlen != sizeof (struct sockaddr_in))
335   {
336     LOG (GNUNET_ERROR_TYPE_DEBUG,
337          "NAT test ignores IPv6 address `%s' returned from NAT library\n",
338          GNUNET_a2s (addr, addrlen));
339     return;                     /* ignore IPv6 here */
340   }
341   LOG (GNUNET_ERROR_TYPE_INFO,
342        "Asking gnunet-nat-server to connect to `%s'\n",
343        GNUNET_a2s (addr, addrlen));
344   sa = (const struct sockaddr_in *) addr;
345   msg.header.size = htons (sizeof (struct GNUNET_NAT_TestMessage));
346   msg.header.type = htons (GNUNET_MESSAGE_TYPE_NAT_TEST);
347   msg.dst_ipv4 = sa->sin_addr.s_addr;
348   msg.dport = sa->sin_port;
349   msg.data = h->data;
350   msg.is_tcp = htonl ((uint32_t) h->is_tcp);
351
352   client = GNUNET_CLIENT_connect ("gnunet-nat-server", h->cfg);
353   if (NULL == client)
354   {
355     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
356                 _("Failed to connect to `gnunet-nat-server'\n"));
357     return;
358   }
359   ca = GNUNET_new (struct ClientActivity);
360   ca->client = client;
361   GNUNET_CONTAINER_DLL_insert (h->ca_head, h->ca_tail, ca);
362   GNUNET_break (GNUNET_OK ==
363                 GNUNET_CLIENT_transmit_and_get_response (client, &msg.header,
364                                                          NAT_SERVER_TIMEOUT,
365                                                          GNUNET_YES, NULL,
366                                                          NULL));
367 }
368
369
370 /**
371  * Timeout task for a nat test. 
372  * Calls the report-callback with a timeout return value
373  * 
374  * @param cls handle to the timed out NAT test
375  * @param tc not used
376  */
377 static void
378 do_timeout (void *cls,
379                  const struct GNUNET_SCHEDULER_TaskContext * tc)
380 {
381   struct GNUNET_NAT_Test *nh = (struct GNUNET_NAT_Test *) cls;
382   
383   nh->ttask = GNUNET_SCHEDULER_NO_TASK;
384   nh->report (nh->report_cls, GNUNET_NAT_ERROR_TIMEOUT);
385   
386   GNUNET_NAT_test_stop(nh);
387 }
388
389
390 /**
391  * Start testing if NAT traversal works using the
392  * given configuration (IPv4-only).
393  * 
394  * ALL failures are reported directly to the report callback
395  *
396  * @param cfg configuration for the NAT traversal
397  * @param is_tcp #GNUNET_YES to test TCP, #GNUNET_NO to test UDP
398  * @param bnd_port port to bind to, 0 for connection reversal
399  * @param adv_port externally advertised port to use
400  * @param timeout delay after which the test should be aborted
401  * @param report function to call with the result of the test
402  * @param report_cls closure for @a report
403  * @return handle to cancel NAT test
404  */
405 struct GNUNET_NAT_Test *
406 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
407                        int is_tcp,
408                        uint16_t bnd_port,
409                        uint16_t adv_port,
410                        struct GNUNET_TIME_Relative timeout,
411                        GNUNET_NAT_TestCallback report,
412                        void *report_cls)
413 {
414   struct GNUNET_NAT_Test *nh;
415   struct sockaddr_in sa;
416   const struct sockaddr *addrs[] = { (const struct sockaddr *) &sa };
417   const socklen_t addrlens[] = { sizeof (sa) };
418
419   memset (&sa, 0, sizeof (sa));
420   sa.sin_family = AF_INET;
421   sa.sin_port = htons (bnd_port);
422 #if HAVE_SOCKADDR_IN_SIN_LEN
423   sa.sin_len = sizeof (sa);
424 #endif
425
426   nh = GNUNET_new (struct GNUNET_NAT_Test);
427   nh->cfg = cfg;
428   nh->is_tcp = is_tcp;
429   nh->data = bnd_port;
430   nh->adv_port = adv_port;
431   nh->report = report;
432   nh->report_cls = report_cls;
433   nh->ttask = GNUNET_SCHEDULER_NO_TASK;
434   if (0 == bnd_port)
435   {
436     nh->nat =
437         GNUNET_NAT_register (cfg, is_tcp, 0, 0, NULL, NULL, &addr_cb,
438                              &reversal_cb, nh);
439   }
440   else
441   {
442     nh->lsock =
443         GNUNET_NETWORK_socket_create (AF_INET,
444                                       (is_tcp ==
445                                        GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM,
446                                       0);
447     if ((nh->lsock == NULL) ||
448         (GNUNET_OK !=
449          GNUNET_NETWORK_socket_bind (nh->lsock, (const struct sockaddr *) &sa,
450                                      sizeof (sa))))
451     {
452       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
453                   _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
454                   GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)),
455                   STRERROR (errno));
456       if (NULL != nh->lsock)
457         GNUNET_NETWORK_socket_close (nh->lsock);
458       GNUNET_free (nh);
459       return NULL;
460     }
461     if (GNUNET_YES == is_tcp)
462     {
463       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_listen (nh->lsock, 5));
464       nh->ltask =
465           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
466                                          nh->lsock, &do_accept, nh);
467     }
468     else
469     {
470       nh->ltask =
471           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
472                                          nh->lsock, &do_udp_read, nh);
473     }
474     LOG (GNUNET_ERROR_TYPE_DEBUG,
475          "NAT test listens on port %u (%s)\n",
476          bnd_port,
477          (GNUNET_YES == is_tcp) ? "tcp" : "udp");
478     nh->nat = GNUNET_NAT_register (cfg, is_tcp, adv_port, 1, addrs, addrlens,
479                              &addr_cb, NULL, nh);
480     if (NULL == nh->nat)
481     {
482       LOG (GNUNET_ERROR_TYPE_ERROR,
483           _("NAT test failed to start NAT library\n"));
484       if (GNUNET_SCHEDULER_NO_TASK != nh->ltask)
485         GNUNET_SCHEDULER_cancel (nh->ltask);
486       if (NULL != nh->lsock)
487         GNUNET_NETWORK_socket_close (nh->lsock);
488       GNUNET_free (nh);
489       return NULL;
490     }
491   }
492   nh->ttask = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);
493   return nh;
494 }
495
496
497 /**
498  * Stop an active NAT test.
499  *
500  * @param tst test to stop.
501  */
502 void
503 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
504 {
505   struct NatActivity *pos;
506   struct ClientActivity *cpos;
507
508   LOG (GNUNET_ERROR_TYPE_DEBUG,
509        "Stopping NAT test\n");
510   while (NULL != (cpos = tst->ca_head))
511   {
512     GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, cpos);
513     GNUNET_CLIENT_disconnect (cpos->client);
514     GNUNET_free (cpos);
515   }
516   while (NULL != (pos = tst->na_head))
517   {
518     GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, pos);
519     GNUNET_SCHEDULER_cancel (pos->rtask);
520     GNUNET_NETWORK_socket_close (pos->sock);
521     GNUNET_free (pos);
522   }
523   if (GNUNET_SCHEDULER_NO_TASK != tst->ttask)
524     GNUNET_SCHEDULER_cancel (tst->ttask);
525   if (GNUNET_SCHEDULER_NO_TASK != tst->ltask)
526     GNUNET_SCHEDULER_cancel (tst->ltask);
527   if (NULL != tst->lsock)
528     GNUNET_NETWORK_socket_close (tst->lsock);
529   GNUNET_NAT_unregister (tst->nat);
530   GNUNET_free (tst);
531 }
532
533 /* end of nat_test.c */