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