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