74b2dddecbd66e672da41aa894d1d43462e5d830
[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  * Handle to a NAT test.
66  */
67 struct GNUNET_NAT_Test
68 {
69
70   /**
71    * Configuration used
72    */
73   const struct GNUNET_CONFIGURATION_Handle *cfg;
74
75   /**
76    * Function to call with success report
77    */
78   GNUNET_NAT_TestCallback report;
79   
80   /**
81    * Closure for 'report'.
82    */
83   void *report_cls;
84
85   /**
86    * Handle to NAT traversal in use
87    */
88   struct GNUNET_NAT_Handle *nat;
89
90   /**
91    * Handle to listen socket, or NULL
92    */
93   struct GNUNET_NETWORK_Handle *lsock;
94
95   /**
96    * Head of list of nat activities.
97    */
98   struct NatActivity *head;
99
100   /**
101    * Tail of list of nat activities.
102    */
103   struct NatActivity *tail;
104
105   /**
106    * Identity of task for the listen socket (if any)
107    */
108   GNUNET_SCHEDULER_TaskIdentifier ltask;
109
110   /**
111    * GNUNET_YES if we're testing TCP
112    */
113   int is_tcp;
114
115   /**
116    * Data that should be transmitted or source-port.
117    */
118   uint16_t data;
119
120   /**
121    * Advertised port to the other peer.
122    */
123   uint16_t adv_port;
124
125 };
126
127
128 /**
129  * Function called from GNUNET_NAT_register whenever someone asks us
130  * to do connection reversal.
131  *
132  * @param cls closure, our 'struct GNUNET_NAT_Handle'
133  * @param addr public IP address of the other peer
134  * @param addrlen actual lenght of the address
135  */
136 static void
137 reversal_cb (void *cls, 
138              const struct sockaddr *addr,
139              socklen_t addrlen)
140 {
141   struct GNUNET_NAT_Test *h = cls;
142   const struct sockaddr_in *sa;
143
144   if (addrlen != sizeof (struct sockaddr_in))
145     return;
146   sa = (const struct sockaddr_in *) addr;
147   if (h->data != sa->sin_port)
148     {
149       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
150                   "Received connection reversal request for wrong port\n");
151       return; /* wrong port */
152     }
153   /* report success */
154   h->report (h->report_cls, GNUNET_OK);
155 }
156
157
158 /**
159  * Activity on our incoming socket.  Read data from the
160  * incoming connection.
161  *
162  * @param cls the 'struct NatActivity'
163  * @param tc scheduler context
164  */
165 static void
166 do_read (void *cls,
167          const struct GNUNET_SCHEDULER_TaskContext *tc)
168 {
169   struct NatActivity *na = cls;
170   struct GNUNET_NAT_Test *tst;
171   uint16_t data;
172
173   na->rtask = GNUNET_SCHEDULER_NO_TASK;
174   tst = na->h;
175   GNUNET_CONTAINER_DLL_remove (tst->head,
176                                tst->tail,
177                                na);
178   if ( (NULL != tc->write_ready) &&
179        (GNUNET_NETWORK_fdset_isset (tc->read_ready, 
180                                     na->sock)) &&
181        (sizeof (data) ==
182         GNUNET_NETWORK_socket_recv (na->sock,
183                                     &data,
184                                     sizeof (data))) )
185     {
186       if (data == tst->data)
187         tst->report (tst->report_cls, GNUNET_OK);
188       else
189         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
190                     "Received data mismatches expected value\n");
191     }
192   else
193     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
194                 "Failed to receive data from inbound connection\n");
195   GNUNET_NETWORK_socket_close (na->sock);
196   GNUNET_free (na);
197 }
198
199
200 /**
201  * Activity on our listen socket. Accept the
202  * incoming connection.
203  *
204  * @param cls the 'struct GNUNET_NAT_Test'
205  * @param tc scheduler context
206  */
207 static void
208 do_accept (void *cls,
209            const struct GNUNET_SCHEDULER_TaskContext *tc)
210 {
211   struct GNUNET_NAT_Test *tst = cls;
212   struct GNUNET_NETWORK_Handle *s;
213   struct NatActivity *wl;
214
215   tst->ltask = GNUNET_SCHEDULER_NO_TASK;
216   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
217     return; 
218   tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
219                                               tst->lsock,
220                                               &do_accept,
221                                               tst);
222   s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL);
223   if (NULL == s)
224     {
225       GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept");
226       return; /* odd error */
227     }
228   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
229               "Got an inbound connection, waiting for data\n");
230   wl = GNUNET_malloc (sizeof (struct NatActivity));
231   wl->sock = s;
232   wl->h = tst;
233   wl->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
234                                              wl->sock,
235                                              &do_read,
236                                              wl);
237   GNUNET_CONTAINER_DLL_insert (tst->head,
238                                tst->tail,
239                                wl);
240 }
241
242
243 /**
244  * Address-callback, used to send message to gnunet-nat-server.
245  *
246  * @param cls closure
247  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
248  *     the previous (now invalid) one
249  * @param addr either the previous or the new public IP address
250  * @param addrlen actual lenght of the address
251  */
252 static void 
253 addr_cb (void *cls,
254          int add_remove,
255          const struct sockaddr *addr,
256          socklen_t addrlen)
257 {
258   struct GNUNET_NAT_Test *h = cls;
259   struct GNUNET_CLIENT_Connection *client;
260   struct GNUNET_NAT_TestMessage msg;
261   const struct sockaddr_in *sa;
262
263   if (GNUNET_YES != add_remove)
264     return;
265   if (addrlen != sizeof (struct sockaddr_in))
266     return; /* ignore IPv6 here */
267   sa = (const struct sockaddr_in*) addr;
268   msg.header.size = htons (sizeof(struct GNUNET_NAT_TestMessage));
269   msg.header.type = htons (GNUNET_MESSAGE_TYPE_NAT_TEST);
270   msg.dst_ipv4 = sa->sin_addr.s_addr;
271   msg.dport = sa->sin_port;
272   msg.data = h->data;
273   msg.is_tcp = htonl ((uint32_t) h->is_tcp);
274
275   client = GNUNET_CLIENT_connect ("gnunet-nat-server",
276                                   h->cfg);
277   GNUNET_break (GNUNET_OK ==
278                 GNUNET_CLIENT_transmit_and_get_response (client,
279                                                          &msg.header,
280                                                          GNUNET_TIME_UNIT_SECONDS,
281                                                          GNUNET_YES,
282                                                          NULL, NULL));
283   GNUNET_CLIENT_disconnect (client, GNUNET_YES);  
284 }
285
286
287 /**
288  * Start testing if NAT traversal works using the
289  * given configuration (IPv4-only).
290  *
291  * @param cfg configuration for the NAT traversal
292  * @param is_tcp GNUNET_YES to test TCP, GNUNET_NO to test UDP
293  * @param bnd_port port to bind to, 0 for connection reversal
294  * @param adv_port externally advertised port to use
295  * @param report function to call with the result of the test
296  * @param report_cls closure for report
297  * @return handle to cancel NAT test
298  */
299 struct GNUNET_NAT_Test *
300 GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
301                        int is_tcp,
302                        uint16_t bnd_port,
303                        uint16_t adv_port,
304                        GNUNET_NAT_TestCallback report,
305                        void *report_cls)
306 {
307   struct GNUNET_NAT_Test *ret;
308   struct sockaddr_in sa;
309   const struct sockaddr *addrs[] = { (const struct sockaddr*) &sa };
310   const socklen_t addrlens[] = { sizeof (sa) };
311
312   memset (&sa, 0, sizeof (sa));
313   sa.sin_port = htons (bnd_port);
314 #if HAVE_SOCKADDR_IN_SIN_LEN
315   sa.sin_len = sizeof (sa);
316 #endif
317   
318   ret = GNUNET_malloc (sizeof (struct GNUNET_NAT_Test));
319   ret->cfg = cfg;
320   ret->is_tcp = is_tcp;
321   ret->data = bnd_port;
322   ret->adv_port = adv_port;
323   ret->report = report;
324   ret->report_cls = report_cls;
325   if (bnd_port == 0)
326     {      
327       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
328                                       0, 
329                                       0, NULL, NULL,
330                                       &addr_cb, &reversal_cb, ret);
331     }
332   else
333     {
334       ret->lsock = GNUNET_NETWORK_socket_create (AF_INET, 
335                                                  (is_tcp==GNUNET_YES) ? SOCK_STREAM : SOCK_DGRAM, 0);
336       if ( (ret->lsock == NULL) ||
337            (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret->lsock,
338                                                      (const struct sockaddr*) &sa,
339                                                      sizeof (sa))) )
340         {
341           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
342                       _("Failed to create listen socket for NAT test\n"));
343           if (NULL != ret->lsock)
344             GNUNET_NETWORK_socket_close (ret->lsock);
345           GNUNET_free (ret);
346           return NULL;
347         }
348       GNUNET_break (GNUNET_OK ==
349                     GNUNET_NETWORK_socket_listen (ret->lsock, 5));
350       ret->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
351                                                   ret->lsock,
352                                                   &do_accept,
353                                                   ret);
354       ret->nat = GNUNET_NAT_register (cfg, is_tcp,
355                                       adv_port, 
356                                       1, addrs, addrlens,
357                                       &addr_cb, NULL, ret);
358     }
359   return ret;
360 }
361
362
363 /**
364  * Stop an active NAT test.
365  *
366  * @param tst test to stop.
367  */
368 void
369 GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst)
370 {
371   struct NatActivity *pos;
372
373   while (NULL != (pos = tst->head))
374     {
375       GNUNET_CONTAINER_DLL_remove (tst->head,
376                                    tst->tail,
377                                    pos);
378       GNUNET_SCHEDULER_cancel (pos->rtask);
379       GNUNET_NETWORK_socket_close (pos->sock);
380       GNUNET_free (pos);
381     }
382   if (GNUNET_SCHEDULER_NO_TASK != tst->ltask)
383     GNUNET_SCHEDULER_cancel (tst->ltask);
384   if (NULL != tst->lsock)
385     GNUNET_NETWORK_socket_close (tst->lsock);
386   GNUNET_NAT_unregister (tst->nat);
387   GNUNET_free (tst);
388 }
389
390 /* end of nat_test.c */