a758cbce6b98b69969b56f07ae0ce5353b40a0ea
[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     return;
354   ca = GNUNET_malloc (sizeof (struct ClientActivity));
355   ca->client = client;
356   GNUNET_CONTAINER_DLL_insert (h->ca_head,
357                                h->ca_tail,
358                                ca);
359   GNUNET_break (GNUNET_OK ==
360                 GNUNET_CLIENT_transmit_and_get_response (client,
361                                                          &msg.header,
362                                                          GNUNET_TIME_UNIT_SECONDS,
363                                                          GNUNET_YES,
364                                                          NULL, NULL));
365 }
366
367
368 /**
369  * Start testing if NAT traversal works using the
370  * given configuration (IPv4-only).
371  *
372  * @param cfg configuration for the NAT traversal
373  * @param is_tcp GNUNET_YES to test TCP, GNUNET_NO to test UDP
374  * @param bnd_port port to bind to, 0 for connection reversal
375  * @param adv_port externally advertised port to use
376  * @param report function to call with the result of the test
377  * @param report_cls closure for report
378  * @return handle to cancel NAT test
379  */
380 struct GNUNET_NAT_Test *
381 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
382                        int is_tcp,
383                        uint16_t bnd_port,
384                        uint16_t adv_port,
385                        GNUNET_NAT_TestCallback report,
386                        void *report_cls)
387 {
388   struct GNUNET_NAT_Test *ret;
389   struct sockaddr_in sa;
390   const struct sockaddr *addrs[] = { (const struct sockaddr*) &sa };
391   const socklen_t addrlens[] = { sizeof (sa) };
392
393   memset (&sa, 0, sizeof (sa));
394   sa.sin_port = htons (bnd_port);
395 #if HAVE_SOCKADDR_IN_SIN_LEN
396   sa.sin_len = sizeof (sa);
397 #endif
398   
399   ret = GNUNET_malloc (sizeof (struct GNUNET_NAT_Test));
400   ret->cfg = cfg;
401   ret->is_tcp = is_tcp;
402   ret->data = bnd_port;
403   ret->adv_port = adv_port;
404   ret->report = report;
405   ret->report_cls = report_cls;
406   if (bnd_port == 0)
407     {      
408       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
409                                       0, 
410                                       0, NULL, NULL,
411                                       &addr_cb, &reversal_cb, ret);
412     }
413   else
414     {
415       ret->lsock = GNUNET_NETWORK_socket_create (AF_INET, 
416                                                  (is_tcp==GNUNET_YES) 
417                                                  ? SOCK_STREAM 
418                                                  : SOCK_DGRAM, 0);
419       if ( (ret->lsock == NULL) ||
420            (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret->lsock,
421                                                      (const struct sockaddr*) &sa,
422                                                      sizeof (sa))) )
423         {
424           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
425                       _("Failed to create listen socket for NAT test\n"));
426           if (NULL != ret->lsock)
427             GNUNET_NETWORK_socket_close (ret->lsock);
428           GNUNET_free (ret);
429           return NULL;
430         }
431       if (GNUNET_YES == is_tcp)
432         {
433           GNUNET_break (GNUNET_OK ==
434                         GNUNET_NETWORK_socket_listen (ret->lsock, 5));
435           ret->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
436                                                       ret->lsock,
437                                                       &do_accept,
438                                                       ret);
439         }
440       else
441         {
442           ret->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
443                                                      ret->lsock,
444                                                      &do_udp_read,
445                                                      ret);
446         }
447       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
448                                       adv_port, 
449                                       1, addrs, addrlens,
450                                       &addr_cb, NULL, ret);
451     }
452   return ret;
453 }
454
455
456 /**
457  * Stop an active NAT test.
458  *
459  * @param tst test to stop.
460  */
461 void
462 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
463 {
464   struct NatActivity *pos;
465   struct ClientActivity *cpos;
466
467   while (NULL != (cpos = tst->ca_head))
468     {
469       GNUNET_CONTAINER_DLL_remove (tst->ca_head,
470                                    tst->ca_tail,
471                                    cpos);
472       GNUNET_CLIENT_disconnect (cpos->client, GNUNET_NO);  
473       GNUNET_free (cpos);
474     }
475   while (NULL != (pos = tst->na_head))
476     {
477       GNUNET_CONTAINER_DLL_remove (tst->na_head,
478                                    tst->na_tail,
479                                    pos);
480       GNUNET_SCHEDULER_cancel (pos->rtask);
481       GNUNET_NETWORK_socket_close (pos->sock);
482       GNUNET_free (pos);
483     }
484   if (GNUNET_SCHEDULER_NO_TASK != tst->ltask)
485     GNUNET_SCHEDULER_cancel (tst->ltask);
486   if (NULL != tst->lsock)
487     GNUNET_NETWORK_socket_close (tst->lsock);
488   GNUNET_NAT_unregister (tst->nat);
489   GNUNET_free (tst);
490 }
491
492 /* end of nat_test.c */