8a46a96fab392faf016f3d1e13dc2af07cc8658f
[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
32 /**
33  * Entry we keep for each incoming connection.
34  */
35 struct NatActivity
36 {
37   /**
38    * This is a doubly-linked list.
39    */
40   struct NatActivity *next;
41
42   /**
43    * This is a doubly-linked list.
44    */
45   struct NatActivity *prev;
46
47   /**
48    * Socket of the incoming connection.
49    */
50   struct GNUNET_NETWORK_Handle *sock;
51
52   /**
53    * Handle of the master context.
54    */
55   struct GNUNET_NAT_Test *h;
56
57   /**
58    * Task reading from the incoming connection.
59    */
60   GNUNET_SCHEDULER_TaskIdentifier rtask;
61 };
62
63
64 /**
65  * Entry we keep for each connection to the gnunet-nat-service.
66  */
67 struct ClientActivity
68 {
69   /**
70    * This is a doubly-linked list.
71    */
72   struct ClientActivity *next;
73
74   /**
75    * This is a doubly-linked list.
76    */
77   struct ClientActivity *prev;
78
79   /**
80    * Socket of the incoming connection.
81    */
82   struct GNUNET_CLIENT_Connection *client;
83
84 };
85
86
87 /**
88  * Handle to a NAT test.
89  */
90 struct GNUNET_NAT_Test
91 {
92
93   /**
94    * Configuration used
95    */
96   const struct GNUNET_CONFIGURATION_Handle *cfg;
97
98   /**
99    * Function to call with success report
100    */
101   GNUNET_NAT_TestCallback report;
102   
103   /**
104    * Closure for 'report'.
105    */
106   void *report_cls;
107
108   /**
109    * Handle to NAT traversal in use
110    */
111   struct GNUNET_NAT_Handle *nat;
112
113   /**
114    * Handle to listen socket, or NULL
115    */
116   struct GNUNET_NETWORK_Handle *lsock;
117
118   /**
119    * Head of list of nat activities.
120    */
121   struct NatActivity *na_head;
122
123   /**
124    * Tail of list of nat activities.
125    */
126   struct NatActivity *na_tail;
127
128   /**
129    * Head of list of client activities.
130    */
131   struct ClientActivity *ca_head;
132
133   /**
134    * Tail of list of client activities.
135    */
136   struct ClientActivity *ca_tail;
137
138   /**
139    * Identity of task for the listen socket (if any)
140    */
141   GNUNET_SCHEDULER_TaskIdentifier ltask;
142
143   /**
144    * GNUNET_YES if we're testing TCP
145    */
146   int is_tcp;
147
148   /**
149    * Data that should be transmitted or source-port.
150    */
151   uint16_t data;
152
153   /**
154    * Advertised port to the other peer.
155    */
156   uint16_t adv_port;
157
158 };
159
160
161 /**
162  * Function called from GNUNET_NAT_register whenever someone asks us
163  * to do connection reversal.
164  *
165  * @param cls closure, our 'struct GNUNET_NAT_Handle'
166  * @param addr public IP address of the other peer
167  * @param addrlen actual lenght of the address
168  */
169 static void
170 reversal_cb (void *cls, 
171              const struct sockaddr *addr,
172              socklen_t addrlen)
173 {
174   struct GNUNET_NAT_Test *h = cls;
175   const struct sockaddr_in *sa;
176
177   if (addrlen != sizeof (struct sockaddr_in))
178     return;
179   sa = (const struct sockaddr_in *) addr;
180   if (h->data != sa->sin_port)
181     {
182       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
183                   "Received connection reversal request for wrong port\n");
184       return; /* wrong port */
185     }
186   /* report success */
187   h->report (h->report_cls, GNUNET_OK);
188 }
189
190
191 /**
192  * Activity on our incoming socket.  Read data from the
193  * incoming connection.
194  *
195  * @param cls the 'struct NatActivity'
196  * @param tc scheduler context
197  */
198 static void
199 do_udp_read (void *cls,
200              const struct GNUNET_SCHEDULER_TaskContext *tc)
201 {
202   struct GNUNET_NAT_Test *tst = cls;
203   uint16_t data;
204
205   tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
206                                               tst->lsock,
207                                               &do_udp_read,
208                                               tst);
209   if ( (NULL != tc->write_ready) &&
210        (GNUNET_NETWORK_fdset_isset (tc->read_ready, 
211                                     tst->lsock)) &&
212        (sizeof (data) ==
213         GNUNET_NETWORK_socket_recv (tst->lsock,
214                                     &data,
215                                     sizeof (data))) )
216     {
217       if (data == tst->data)
218         tst->report (tst->report_cls, GNUNET_OK);
219       else
220         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
221                     "Received data mismatches expected value\n");
222     }
223   else
224     GNUNET_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,
247                                tst->na_tail,
248                                na);
249   if ( (NULL != tc->write_ready) &&
250        (GNUNET_NETWORK_fdset_isset (tc->read_ready, 
251                                     na->sock)) &&
252        (sizeof (data) ==
253         GNUNET_NETWORK_socket_recv (na->sock,
254                                     &data,
255                                     sizeof (data))) )
256     {
257       if (data == tst->data)
258         tst->report (tst->report_cls, GNUNET_OK);
259       else
260         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
261                     "Received data mismatches expected value\n");
262     }
263   else
264     GNUNET_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 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
290                                               tst->lsock,
291                                               &do_accept,
292                                               tst);
293   s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL);
294   if (NULL == s)
295     {
296       GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept");
297       return; /* odd error */
298     }
299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
300               "Got an inbound connection, waiting for data\n");
301   wl = GNUNET_malloc (sizeof (struct NatActivity));
302   wl->sock = s;
303   wl->h = tst;
304   wl->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
305                                              wl->sock,
306                                              &do_read,
307                                              wl);
308   GNUNET_CONTAINER_DLL_insert (tst->na_head,
309                                tst->na_tail,
310                                wl);
311 }
312
313
314 /**
315  * Address-callback, used to send message to gnunet-nat-server.
316  *
317  * @param cls closure
318  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
319  *     the previous (now invalid) one
320  * @param addr either the previous or the new public IP address
321  * @param addrlen actual lenght of the address
322  */
323 static void 
324 addr_cb (void *cls,
325          int add_remove,
326          const struct sockaddr *addr,
327          socklen_t addrlen)
328 {
329   struct GNUNET_NAT_Test *h = cls;
330   struct ClientActivity *ca;
331   struct GNUNET_CLIENT_Connection *client;
332   struct GNUNET_NAT_TestMessage msg;
333   const struct sockaddr_in *sa;
334
335   if (GNUNET_YES != add_remove)
336     return;
337   if (addrlen != sizeof (struct sockaddr_in))
338     return; /* ignore IPv6 here */
339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
340               "Asking gnunet-nat-server to connect to `%s'\n",
341               GNUNET_a2s (addr, addrlen));
342   sa = (const struct sockaddr_in*) addr;
343   msg.header.size = htons (sizeof(struct GNUNET_NAT_TestMessage));
344   msg.header.type = htons (GNUNET_MESSAGE_TYPE_NAT_TEST);
345   msg.dst_ipv4 = sa->sin_addr.s_addr;
346   msg.dport = sa->sin_port;
347   msg.data = h->data;
348   msg.is_tcp = htonl ((uint32_t) h->is_tcp);
349
350   client = GNUNET_CLIENT_connect ("gnunet-nat-server",
351                                   h->cfg);
352   if (NULL == client)
353     {
354       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
355                   _("Failed to connect to `gnunet-nat-server'\n"));
356       return;
357     }
358   ca = GNUNET_malloc (sizeof (struct ClientActivity));
359   ca->client = client;
360   GNUNET_CONTAINER_DLL_insert (h->ca_head,
361                                h->ca_tail,
362                                ca);
363   GNUNET_break (GNUNET_OK ==
364                 GNUNET_CLIENT_transmit_and_get_response (client,
365                                                          &msg.header,
366                                                          GNUNET_TIME_UNIT_SECONDS,
367                                                          GNUNET_YES,
368                                                          NULL, NULL));
369 }
370
371
372 /**
373  * Start testing if NAT traversal works using the
374  * given configuration (IPv4-only).
375  *
376  * @param cfg configuration for the NAT traversal
377  * @param is_tcp GNUNET_YES to test TCP, GNUNET_NO to test UDP
378  * @param bnd_port port to bind to, 0 for connection reversal
379  * @param adv_port externally advertised port to use
380  * @param report function to call with the result of the test
381  * @param report_cls closure for report
382  * @return handle to cancel NAT test
383  */
384 struct GNUNET_NAT_Test *
385 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
386                        int is_tcp,
387                        uint16_t bnd_port,
388                        uint16_t adv_port,
389                        GNUNET_NAT_TestCallback report,
390                        void *report_cls)
391 {
392   struct GNUNET_NAT_Test *ret;
393   struct sockaddr_in sa;
394   const struct sockaddr *addrs[] = { (const struct sockaddr*) &sa };
395   const socklen_t addrlens[] = { sizeof (sa) };
396
397   memset (&sa, 0, sizeof (sa));
398   sa.sin_family = AF_INET;
399   sa.sin_port = htons (bnd_port);
400 #if HAVE_SOCKADDR_IN_SIN_LEN
401   sa.sin_len = sizeof (sa);
402 #endif
403   
404   ret = GNUNET_malloc (sizeof (struct GNUNET_NAT_Test));
405   ret->cfg = cfg;
406   ret->is_tcp = is_tcp;
407   ret->data = bnd_port;
408   ret->adv_port = adv_port;
409   ret->report = report;
410   ret->report_cls = report_cls;
411   if (bnd_port == 0)
412     {      
413       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
414                                       0, 
415                                       0, NULL, NULL,
416                                       &addr_cb, &reversal_cb, ret);
417     }
418   else
419     {
420       ret->lsock = GNUNET_NETWORK_socket_create (AF_INET, 
421                                                  (is_tcp==GNUNET_YES) 
422                                                  ? SOCK_STREAM 
423                                                  : SOCK_DGRAM, 0);
424       if ( (ret->lsock == NULL) ||
425            (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret->lsock,
426                                                      (const struct sockaddr*) &sa,
427                                                      sizeof (sa))) )
428         {
429           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
430                       _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
431                       GNUNET_a2s ((const struct sockaddr*)&sa,
432                                   sizeof(sa)),
433                       STRERROR (errno));
434           if (NULL != ret->lsock)
435             GNUNET_NETWORK_socket_close (ret->lsock);
436           GNUNET_free (ret);
437           return NULL;
438         }
439       if (GNUNET_YES == is_tcp)
440         {
441           GNUNET_break (GNUNET_OK ==
442                         GNUNET_NETWORK_socket_listen (ret->lsock, 5));
443           ret->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
444                                                       ret->lsock,
445                                                       &do_accept,
446                                                       ret);
447         }
448       else
449         {
450           ret->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
451                                                      ret->lsock,
452                                                      &do_udp_read,
453                                                      ret);
454         }
455       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
456                                       adv_port, 
457                                       1, addrs, addrlens,
458                                       &addr_cb, NULL, ret);
459     }
460   return ret;
461 }
462
463
464 /**
465  * Stop an active NAT test.
466  *
467  * @param tst test to stop.
468  */
469 void
470 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
471 {
472   struct NatActivity *pos;
473   struct ClientActivity *cpos;
474
475   while (NULL != (cpos = tst->ca_head))
476     {
477       GNUNET_CONTAINER_DLL_remove (tst->ca_head,
478                                    tst->ca_tail,
479                                    cpos);
480       GNUNET_CLIENT_disconnect (cpos->client, GNUNET_NO);  
481       GNUNET_free (cpos);
482     }
483   while (NULL != (pos = tst->na_head))
484     {
485       GNUNET_CONTAINER_DLL_remove (tst->na_head,
486                                    tst->na_tail,
487                                    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 */