NAMESTORE/JSON: fix parsing exp and flags
[oweals/gnunet.git] / src / nat-auto / nat_auto_api_test.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011, 2016 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20 /**
21  * @file nat/nat_auto_api_test.c
22  * @brief functions to test if the NAT configuration is successful at achieving NAT traversal (with the help of a gnunet-nat-server)
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_nat_service.h"
28 #include "gnunet_nat_auto_service.h"
29 #include "nat-auto.h"
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "nat-auto", __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_AUTO_Test *h;
59
60   /**
61    * Task reading from the incoming connection.
62    */
63   struct GNUNET_SCHEDULER_Task *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_MQ_Handle *mq;
86
87   /**
88    * Handle to overall NAT test.
89    */
90   struct GNUNET_NAT_AUTO_Test *h;
91
92 };
93
94
95 /**
96  * Handle to a NAT test.
97  */
98 struct GNUNET_NAT_AUTO_Test
99 {
100
101   /**
102    * Configuration used
103    */
104   const struct GNUNET_CONFIGURATION_Handle *cfg;
105
106   /**
107    * Function to call with success report
108    */
109   GNUNET_NAT_TestCallback report;
110
111   /**
112    * Closure for @e report.
113    */
114   void *report_cls;
115
116   /**
117    * Handle to NAT traversal in use
118    */
119   struct GNUNET_NAT_Handle *nat;
120
121   /**
122    * Handle to listen socket, or NULL
123    */
124   struct GNUNET_NETWORK_Handle *lsock;
125
126   /**
127    * Head of list of nat activities.
128    */
129   struct NatActivity *na_head;
130
131   /**
132    * Tail of list of nat activities.
133    */
134   struct NatActivity *na_tail;
135
136   /**
137    * Head of list of client activities.
138    */
139   struct ClientActivity *ca_head;
140
141   /**
142    * Tail of list of client activities.
143    */
144   struct ClientActivity *ca_tail;
145
146   /**
147    * Identity of task for the listen socket (if any)
148    */
149   struct GNUNET_SCHEDULER_Task *ltask;
150
151   /**
152    * Task identifier for the timeout (if any)
153    */
154   struct GNUNET_SCHEDULER_Task *ttask;
155
156   /**
157    * Section name of plugin to test.
158    */
159   char *section_name;
160
161   /**
162    * IPPROTO_TCP or IPPROTO_UDP.
163    */
164   int proto;
165
166   /**
167    * Data that should be transmitted or source-port.
168    */
169   uint16_t data;
170
171   /**
172    * Status code to be reported to the timeout/status call
173    */
174   enum GNUNET_NAT_StatusCode status;
175 };
176
177
178 /**
179  * Function called from #GNUNET_NAT_register whenever someone asks us
180  * to do connection reversal.
181  *
182  * @param cls closure, our `struct GNUNET_NAT_Handle`
183  * @param addr public IP address of the other peer
184  * @param addrlen actual lenght of the @a addr
185  */
186 static void
187 reversal_cb (void *cls,
188              const struct sockaddr *addr,
189              socklen_t addrlen)
190 {
191   struct GNUNET_NAT_AUTO_Test *h = cls;
192   const struct sockaddr_in *sa;
193
194   if (sizeof (struct sockaddr_in) != addrlen)
195     return;
196   sa = (const struct sockaddr_in *) addr;
197   if (h->data != sa->sin_port)
198   {
199     LOG (GNUNET_ERROR_TYPE_DEBUG,
200          "Received connection reversal request for wrong port\n");
201     return;                     /* wrong port */
202   }
203   /* report success */
204   h->report (h->report_cls,
205              GNUNET_NAT_ERROR_SUCCESS);
206 }
207
208
209 /**
210  * Activity on our incoming socket.  Read data from the
211  * incoming connection.
212  *
213  * @param cls the `struct GNUNET_NAT_AUTO_Test`
214  */
215 static void
216 do_udp_read (void *cls)
217 {
218   struct GNUNET_NAT_AUTO_Test *tst = cls;
219   uint16_t data;
220   const struct GNUNET_SCHEDULER_TaskContext *tc;
221
222   tc = GNUNET_SCHEDULER_get_task_context ();
223   tst->ltask =
224       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
225                                      tst->lsock,
226                                      &do_udp_read,
227                                      tst);
228   if ((NULL != tc->write_ready) &&
229       (GNUNET_NETWORK_fdset_isset (tc->read_ready,
230                                    tst->lsock)) &&
231       (sizeof (data) ==
232        GNUNET_NETWORK_socket_recv (tst->lsock,
233                                    &data,
234                                    sizeof (data))))
235   {
236     if (data == tst->data)
237       tst->report (tst->report_cls,
238                    GNUNET_NAT_ERROR_SUCCESS);
239     else
240       LOG (GNUNET_ERROR_TYPE_DEBUG,
241            "Received data mismatches expected value\n");
242   }
243   else
244     LOG (GNUNET_ERROR_TYPE_DEBUG,
245          "Failed to receive data from inbound connection\n");
246 }
247
248
249 /**
250  * Activity on our incoming socket.  Read data from the
251  * incoming connection.
252  *
253  * @param cls the `struct NatActivity`
254  */
255 static void
256 do_read (void *cls)
257 {
258   struct NatActivity *na = cls;
259   struct GNUNET_NAT_AUTO_Test *tst;
260   uint16_t data;
261   const struct GNUNET_SCHEDULER_TaskContext *tc;
262
263   tc = GNUNET_SCHEDULER_get_task_context ();
264   na->rtask = NULL;
265   tst = na->h;
266   GNUNET_CONTAINER_DLL_remove (tst->na_head,
267                                tst->na_tail,
268                                na);
269   if ((NULL != tc->write_ready) &&
270       (GNUNET_NETWORK_fdset_isset (tc->read_ready,
271                                    na->sock)) &&
272       (sizeof (data) ==
273        GNUNET_NETWORK_socket_recv (na->sock,
274                                    &data,
275                                    sizeof (data))))
276   {
277     if (data == tst->data)
278       tst->report (tst->report_cls,
279                    GNUNET_NAT_ERROR_SUCCESS);
280     else
281       LOG (GNUNET_ERROR_TYPE_DEBUG,
282            "Received data does not match expected value\n");
283   }
284   else
285     LOG (GNUNET_ERROR_TYPE_DEBUG,
286          "Failed to receive data from inbound connection\n");
287   GNUNET_NETWORK_socket_close (na->sock);
288   GNUNET_free (na);
289 }
290
291
292 /**
293  * Activity on our listen socket. Accept the
294  * incoming connection.
295  *
296  * @param cls the `struct GNUNET_NAT_AUTO_Test`
297  */
298 static void
299 do_accept (void *cls)
300 {
301   struct GNUNET_NAT_AUTO_Test *tst = cls;
302   struct GNUNET_NETWORK_Handle *s;
303   struct NatActivity *wl;
304
305   tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
306                                               tst->lsock,
307                                               &do_accept,
308                                               tst);
309   s = GNUNET_NETWORK_socket_accept (tst->lsock,
310                                     NULL,
311                                     NULL);
312   if (NULL == s)
313   {
314     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO,
315                          "accept");
316     return;                     /* odd error */
317   }
318   LOG (GNUNET_ERROR_TYPE_DEBUG,
319        "Got an inbound connection, waiting for data\n");
320   wl = GNUNET_new (struct NatActivity);
321   wl->sock = s;
322   wl->h = tst;
323   wl->rtask =
324     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
325                                    wl->sock,
326                                    &do_read,
327                                    wl);
328   GNUNET_CONTAINER_DLL_insert (tst->na_head,
329                                tst->na_tail,
330                                wl);
331 }
332
333
334 /**
335  * We got disconnected from the NAT server.  Stop
336  * waiting for a reply.
337  *
338  * @param cls the `struct ClientActivity`
339  * @param error error code
340  */
341 static void
342 mq_error_handler (void *cls,
343                   enum GNUNET_MQ_Error error)
344 {
345   struct ClientActivity *ca = cls;
346   struct GNUNET_NAT_AUTO_Test *tst = ca->h;
347
348   GNUNET_CONTAINER_DLL_remove (tst->ca_head,
349                                tst->ca_tail,
350                                ca);
351   GNUNET_MQ_destroy (ca->mq);
352   GNUNET_free (ca);
353 }
354
355
356 /**
357  * Address-callback, used to send message to gnunet-nat-server.
358  *
359  * @param cls closure
360  * @param app_ctx[in,out] location where the app can store stuff
361  *                  on add and retrieve it on remove
362  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
363  *     the previous (now invalid) one
364  * @param ac address class the address belongs to
365  * @param addr either the previous or the new public IP address
366  * @param addrlen actual length of the @a addr
367  */
368 static void
369 addr_cb (void *cls,
370          void **app_ctx,
371          int add_remove,
372          enum GNUNET_NAT_AddressClass ac,
373          const struct sockaddr *addr,
374          socklen_t addrlen)
375 {
376   struct GNUNET_NAT_AUTO_Test *h = cls;
377   struct ClientActivity *ca;
378   struct GNUNET_MQ_Envelope *env;
379   struct GNUNET_NAT_AUTO_TestMessage *msg;
380   const struct sockaddr_in *sa;
381
382   (void) app_ctx;
383   if (GNUNET_YES != add_remove)
384     return;
385   if (addrlen != sizeof (struct sockaddr_in))
386   {
387     LOG (GNUNET_ERROR_TYPE_DEBUG,
388          "NAT test ignores IPv6 address `%s' returned from NAT library\n",
389          GNUNET_a2s (addr,
390                      addrlen));
391     return;                     /* ignore IPv6 here */
392   }
393   LOG (GNUNET_ERROR_TYPE_INFO,
394        "Asking gnunet-nat-server to connect to `%s'\n",
395        GNUNET_a2s (addr,
396                    addrlen));
397
398   ca = GNUNET_new (struct ClientActivity);
399   ca->h = h;
400   ca->mq = GNUNET_CLIENT_connect (h->cfg,
401                                   "gnunet-nat-server",
402                                   NULL,
403                                   &mq_error_handler,
404                                   ca);
405   if (NULL == ca->mq)
406   {
407     GNUNET_free (ca);
408     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
409                 _("Failed to connect to `gnunet-nat-server'\n"));
410     return;
411   }
412   GNUNET_CONTAINER_DLL_insert (h->ca_head,
413                                h->ca_tail,
414                                ca);
415   sa = (const struct sockaddr_in *) addr;
416   env = GNUNET_MQ_msg (msg,
417                        GNUNET_MESSAGE_TYPE_NAT_TEST);
418   msg->dst_ipv4 = sa->sin_addr.s_addr;
419   msg->dport = sa->sin_port;
420   msg->data = h->data;
421   msg->is_tcp = htonl ((uint32_t) (h->proto == IPPROTO_TCP));
422   GNUNET_MQ_send (ca->mq,
423                   env);
424 }
425
426
427 /**
428  * Calls the report-callback reporting failure.
429  *
430  * Destroys the nat handle after the callback has been processed.
431  *
432  * @param cls handle to the timed out NAT test
433  */
434 static void
435 do_fail (void *cls)
436 {
437   struct GNUNET_NAT_AUTO_Test *nh = cls;
438
439   nh->ttask = NULL;
440   nh->report (nh->report_cls,
441               nh->status);
442 }
443
444
445 /**
446  * Start testing if NAT traversal works using the given configuration.
447  *  The transport adapters should be down while using this function.
448  *
449  * @param cfg configuration for the NAT traversal
450  * @param proto protocol to test, i.e. IPPROTO_TCP or IPPROTO_UDP
451  * @param section_name configuration section to use for configuration
452  * @param report function to call with the result of the test
453  * @param report_cls closure for @a report
454  * @return handle to cancel NAT test
455  */
456 struct GNUNET_NAT_AUTO_Test *
457 GNUNET_NAT_AUTO_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
458                             uint8_t proto,
459                             const char *section_name,
460                             GNUNET_NAT_TestCallback report,
461                             void *report_cls)
462 {
463   struct GNUNET_NAT_AUTO_Test *nh;
464   unsigned long long bnd_port;
465   struct sockaddr_in sa;
466   const struct sockaddr *addrs[] = {
467     (const struct sockaddr *) &sa
468   };
469   const socklen_t addrlens[] = {
470     sizeof (sa)
471   };
472
473   if ( (GNUNET_OK !=
474         GNUNET_CONFIGURATION_get_value_number (cfg,
475                                                section_name,
476                                                "PORT",
477                                                &bnd_port)) ||
478        (bnd_port > 65535) )
479   {
480     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
481                 _("Failed to find valid PORT in section `%s'\n"),
482                 section_name);
483     return NULL;
484   }
485
486   memset (&sa, 0, sizeof (sa));
487   sa.sin_family = AF_INET;
488   sa.sin_port = htons ((uint16_t) bnd_port);
489 #if HAVE_SOCKADDR_IN_SIN_LEN
490   sa.sin_len = sizeof (sa);
491 #endif
492
493   nh = GNUNET_new (struct GNUNET_NAT_AUTO_Test);
494   nh->cfg = cfg;
495   nh->proto = proto;
496   nh->section_name = GNUNET_strdup (section_name);
497   nh->report = report;
498   nh->report_cls = report_cls;
499   nh->status = GNUNET_NAT_ERROR_SUCCESS;
500   if (0 == bnd_port)
501   {
502     nh->nat
503       = GNUNET_NAT_register (cfg,
504                              section_name,
505                              proto,
506                              0, NULL, NULL,
507                              &addr_cb,
508                              &reversal_cb,
509                              nh);
510   }
511   else
512   {
513     nh->lsock
514       = GNUNET_NETWORK_socket_create (AF_INET,
515                                       (IPPROTO_UDP == proto)
516                                       ? SOCK_DGRAM
517                                       : SOCK_STREAM,
518                                       proto);
519     if ( (NULL == nh->lsock) ||
520          (GNUNET_OK !=
521           GNUNET_NETWORK_socket_bind (nh->lsock,
522                                       (const struct sockaddr *) &sa,
523                                       sizeof (sa))))
524     {
525       LOG (GNUNET_ERROR_TYPE_ERROR,
526            _("Failed to create socket bound to `%s' for NAT test: %s\n"),
527            GNUNET_a2s ((const struct sockaddr *) &sa,
528                        sizeof (sa)),
529            STRERROR (errno));
530       if (NULL != nh->lsock)
531       {
532         GNUNET_NETWORK_socket_close (nh->lsock);
533         nh->lsock = NULL;
534       }
535       nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR;
536       nh->ttask = GNUNET_SCHEDULER_add_now (&do_fail,
537                                             nh);
538       return nh;
539     }
540     if (IPPROTO_TCP == proto)
541     {
542       GNUNET_break (GNUNET_OK ==
543                     GNUNET_NETWORK_socket_listen (nh->lsock,
544                                                   5));
545       nh->ltask =
546           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
547                                          nh->lsock,
548                                          &do_accept,
549                                          nh);
550     }
551     else
552     {
553       nh->ltask =
554           GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
555                                          nh->lsock,
556                                          &do_udp_read,
557                                          nh);
558     }
559     LOG (GNUNET_ERROR_TYPE_INFO,
560          "NAT test listens on port %llu (%s)\n",
561          bnd_port,
562          (IPPROTO_TCP == proto) ? "tcp" : "udp");
563     nh->nat = GNUNET_NAT_register (cfg,
564                                    section_name,
565                                    proto,
566                                    1,
567                                    addrs,
568                                    addrlens,
569                                    &addr_cb,
570                                    NULL,
571                                    nh);
572     if (NULL == nh->nat)
573     {
574       LOG (GNUNET_ERROR_TYPE_INFO,
575           _("NAT test failed to start NAT library\n"));
576       if (NULL != nh->ltask)
577       {
578         GNUNET_SCHEDULER_cancel (nh->ltask);
579         nh->ltask = NULL;
580       }
581       if (NULL != nh->lsock)
582       {
583         GNUNET_NETWORK_socket_close (nh->lsock);
584         nh->lsock = NULL;
585       }
586       nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED;
587       nh->ttask = GNUNET_SCHEDULER_add_now (&do_fail,
588                                             nh);
589       return nh;
590     }
591   }
592   return nh;
593 }
594
595
596 /**
597  * Stop an active NAT test.
598  *
599  * @param tst test to stop.
600  */
601 void
602 GNUNET_NAT_AUTO_test_stop (struct GNUNET_NAT_AUTO_Test *tst)
603 {
604   struct NatActivity *pos;
605   struct ClientActivity *cpos;
606
607   LOG (GNUNET_ERROR_TYPE_DEBUG,
608        "Stopping NAT test\n");
609   while (NULL != (cpos = tst->ca_head))
610   {
611     GNUNET_CONTAINER_DLL_remove (tst->ca_head,
612                                  tst->ca_tail,
613                                  cpos);
614     GNUNET_MQ_destroy (cpos->mq);
615     GNUNET_free (cpos);
616   }
617   while (NULL != (pos = tst->na_head))
618   {
619     GNUNET_CONTAINER_DLL_remove (tst->na_head,
620                                  tst->na_tail,
621                                  pos);
622     GNUNET_SCHEDULER_cancel (pos->rtask);
623     GNUNET_NETWORK_socket_close (pos->sock);
624     GNUNET_free (pos);
625   }
626   if (NULL != tst->ttask)
627   {
628     GNUNET_SCHEDULER_cancel (tst->ttask);
629     tst->ttask = NULL;
630   }
631   if (NULL != tst->ltask)
632   {
633     GNUNET_SCHEDULER_cancel (tst->ltask);
634     tst->ltask = NULL;
635   }
636   if (NULL != tst->lsock)
637   {
638     GNUNET_NETWORK_socket_close (tst->lsock);
639     tst->lsock = NULL;
640   }
641   if (NULL != tst->nat)
642   {
643     GNUNET_NAT_unregister (tst->nat);
644     tst->nat = NULL;
645   }
646   GNUNET_free (tst->section_name);
647   GNUNET_free (tst);
648 }
649
650 /* end of nat_auto_api_test.c */