testcase for nat test code
[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_read (void *cls,
200          const struct GNUNET_SCHEDULER_TaskContext *tc)
201 {
202   struct NatActivity *na = cls;
203   struct GNUNET_NAT_Test *tst;
204   uint16_t data;
205
206   na->rtask = GNUNET_SCHEDULER_NO_TASK;
207   tst = na->h;
208   GNUNET_CONTAINER_DLL_remove (tst->na_head,
209                                tst->na_tail,
210                                na);
211   if ( (NULL != tc->write_ready) &&
212        (GNUNET_NETWORK_fdset_isset (tc->read_ready, 
213                                     na->sock)) &&
214        (sizeof (data) ==
215         GNUNET_NETWORK_socket_recv (na->sock,
216                                     &data,
217                                     sizeof (data))) )
218     {
219       if (data == tst->data)
220         tst->report (tst->report_cls, GNUNET_OK);
221       else
222         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
223                     "Received data mismatches expected value\n");
224     }
225   else
226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
227                 "Failed to receive data from inbound connection\n");
228   GNUNET_NETWORK_socket_close (na->sock);
229   GNUNET_free (na);
230 }
231
232
233 /**
234  * Activity on our listen socket. Accept the
235  * incoming connection.
236  *
237  * @param cls the 'struct GNUNET_NAT_Test'
238  * @param tc scheduler context
239  */
240 static void
241 do_accept (void *cls,
242            const struct GNUNET_SCHEDULER_TaskContext *tc)
243 {
244   struct GNUNET_NAT_Test *tst = cls;
245   struct GNUNET_NETWORK_Handle *s;
246   struct NatActivity *wl;
247
248   tst->ltask = GNUNET_SCHEDULER_NO_TASK;
249   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
250     return; 
251   tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
252                                               tst->lsock,
253                                               &do_accept,
254                                               tst);
255   s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL);
256   if (NULL == s)
257     {
258       GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept");
259       return; /* odd error */
260     }
261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
262               "Got an inbound connection, waiting for data\n");
263   wl = GNUNET_malloc (sizeof (struct NatActivity));
264   wl->sock = s;
265   wl->h = tst;
266   wl->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
267                                              wl->sock,
268                                              &do_read,
269                                              wl);
270   GNUNET_CONTAINER_DLL_insert (tst->na_head,
271                                tst->na_tail,
272                                wl);
273 }
274
275
276 /**
277  * Address-callback, used to send message to gnunet-nat-server.
278  *
279  * @param cls closure
280  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
281  *     the previous (now invalid) one
282  * @param addr either the previous or the new public IP address
283  * @param addrlen actual lenght of the address
284  */
285 static void 
286 addr_cb (void *cls,
287          int add_remove,
288          const struct sockaddr *addr,
289          socklen_t addrlen)
290 {
291   struct GNUNET_NAT_Test *h = cls;
292   struct ClientActivity *ca;
293   struct GNUNET_CLIENT_Connection *client;
294   struct GNUNET_NAT_TestMessage msg;
295   const struct sockaddr_in *sa;
296
297   if (GNUNET_YES != add_remove)
298     return;
299   if (addrlen != sizeof (struct sockaddr_in))
300     return; /* ignore IPv6 here */
301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
302               "Asking gnunet-nat-server to connect to `%s'\n",
303               GNUNET_a2s (addr, addrlen));
304   sa = (const struct sockaddr_in*) addr;
305   msg.header.size = htons (sizeof(struct GNUNET_NAT_TestMessage));
306   msg.header.type = htons (GNUNET_MESSAGE_TYPE_NAT_TEST);
307   msg.dst_ipv4 = sa->sin_addr.s_addr;
308   msg.dport = sa->sin_port;
309   msg.data = h->data;
310   msg.is_tcp = htonl ((uint32_t) h->is_tcp);
311
312   client = GNUNET_CLIENT_connect ("gnunet-nat-server",
313                                   h->cfg);
314   if (NULL == client)
315     return;
316   ca = GNUNET_malloc (sizeof (struct ClientActivity));
317   ca->client = client;
318   GNUNET_CONTAINER_DLL_insert (h->ca_head,
319                                h->ca_tail,
320                                ca);
321   GNUNET_break (GNUNET_OK ==
322                 GNUNET_CLIENT_transmit_and_get_response (client,
323                                                          &msg.header,
324                                                          GNUNET_TIME_UNIT_SECONDS,
325                                                          GNUNET_YES,
326                                                          NULL, NULL));
327 }
328
329
330 /**
331  * Start testing if NAT traversal works using the
332  * given configuration (IPv4-only).
333  *
334  * @param cfg configuration for the NAT traversal
335  * @param is_tcp GNUNET_YES to test TCP, GNUNET_NO to test UDP
336  * @param bnd_port port to bind to, 0 for connection reversal
337  * @param adv_port externally advertised port to use
338  * @param report function to call with the result of the test
339  * @param report_cls closure for report
340  * @return handle to cancel NAT test
341  */
342 struct GNUNET_NAT_Test *
343 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
344                        int is_tcp,
345                        uint16_t bnd_port,
346                        uint16_t adv_port,
347                        GNUNET_NAT_TestCallback report,
348                        void *report_cls)
349 {
350   struct GNUNET_NAT_Test *ret;
351   struct sockaddr_in sa;
352   const struct sockaddr *addrs[] = { (const struct sockaddr*) &sa };
353   const socklen_t addrlens[] = { sizeof (sa) };
354
355   memset (&sa, 0, sizeof (sa));
356   sa.sin_port = htons (bnd_port);
357 #if HAVE_SOCKADDR_IN_SIN_LEN
358   sa.sin_len = sizeof (sa);
359 #endif
360   
361   ret = GNUNET_malloc (sizeof (struct GNUNET_NAT_Test));
362   ret->cfg = cfg;
363   ret->is_tcp = is_tcp;
364   ret->data = bnd_port;
365   ret->adv_port = adv_port;
366   ret->report = report;
367   ret->report_cls = report_cls;
368   if (bnd_port == 0)
369     {      
370       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
371                                       0, 
372                                       0, NULL, NULL,
373                                       &addr_cb, &reversal_cb, ret);
374     }
375   else
376     {
377       ret->lsock = GNUNET_NETWORK_socket_create (AF_INET, 
378                                                  (is_tcp==GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM, 0);
379       if ( (ret->lsock == NULL) ||
380            (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret->lsock,
381                                                      (const struct sockaddr*) &sa,
382                                                      sizeof (sa))) )
383         {
384           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
385                       _("Failed to create listen socket for NAT test\n"));
386           if (NULL != ret->lsock)
387             GNUNET_NETWORK_socket_close (ret->lsock);
388           GNUNET_free (ret);
389           return NULL;
390         }
391       GNUNET_break (GNUNET_OK ==
392                     GNUNET_NETWORK_socket_listen (ret->lsock, 5));
393       ret->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
394                                                   ret->lsock,
395                                                   &do_accept,
396                                                   ret);
397       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
398                                       adv_port, 
399                                       1, addrs, addrlens,
400                                       &addr_cb, NULL, ret);
401     }
402   return ret;
403 }
404
405
406 /**
407  * Stop an active NAT test.
408  *
409  * @param tst test to stop.
410  */
411 void
412 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
413 {
414   struct NatActivity *pos;
415   struct ClientActivity *cpos;
416
417   while (NULL != (cpos = tst->ca_head))
418     {
419       GNUNET_CONTAINER_DLL_remove (tst->ca_head,
420                                    tst->ca_tail,
421                                    cpos);
422       GNUNET_CLIENT_disconnect (cpos->client, GNUNET_NO);  
423       GNUNET_free (cpos);
424     }
425   while (NULL != (pos = tst->na_head))
426     {
427       GNUNET_CONTAINER_DLL_remove (tst->na_head,
428                                    tst->na_tail,
429                                    pos);
430       GNUNET_SCHEDULER_cancel (pos->rtask);
431       GNUNET_NETWORK_socket_close (pos->sock);
432       GNUNET_free (pos);
433     }
434   if (GNUNET_SCHEDULER_NO_TASK != tst->ltask)
435     GNUNET_SCHEDULER_cancel (tst->ltask);
436   if (NULL != tst->lsock)
437     GNUNET_NETWORK_socket_close (tst->lsock);
438   GNUNET_NAT_unregister (tst->nat);
439   GNUNET_free (tst);
440 }
441
442 /* end of nat_test.c */