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