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