uncrustify as demanded.
[oweals/gnunet.git] / src / nat-auto / gnunet-nat-auto_legacy.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 /**
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 \
34   GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
35
36 /**
37  * Entry we keep for each incoming connection.
38  */
39 struct NatActivity {
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   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    * This is a doubly-linked list.
73    */
74   struct ClientActivity *next;
75
76   /**
77    * This is a doubly-linked list.
78    */
79   struct ClientActivity *prev;
80
81   /**
82    * Socket of the incoming connection.
83    */
84   struct GNUNET_MQ_Handle *mq;
85
86   /**
87    * Handle to overall NAT test.
88    */
89   struct GNUNET_NAT_Test *h;
90 };
91
92
93 /**
94  * Handle to a NAT test.
95  */
96 struct GNUNET_NAT_Test {
97   /**
98    * Configuration used
99    */
100   const struct GNUNET_CONFIGURATION_Handle *cfg;
101
102   /**
103    * Function to call with success report
104    */
105   GNUNET_NAT_TestCallback report;
106
107   /**
108    * Closure for @e report.
109    */
110   void *report_cls;
111
112   /**
113    * Handle to NAT traversal in use
114    */
115   struct GNUNET_NAT_Handle *nat;
116
117   /**
118    * Handle to listen socket, or NULL
119    */
120   struct GNUNET_NETWORK_Handle *lsock;
121
122   /**
123    * Head of list of nat activities.
124    */
125   struct NatActivity *na_head;
126
127   /**
128    * Tail of list of nat activities.
129    */
130   struct NatActivity *na_tail;
131
132   /**
133    * Head of list of client activities.
134    */
135   struct ClientActivity *ca_head;
136
137   /**
138    * Tail of list of client activities.
139    */
140   struct ClientActivity *ca_tail;
141
142   /**
143    * Identity of task for the listen socket (if any)
144    */
145   struct GNUNET_SCHEDULER_Task *ltask;
146
147   /**
148    * Task identifier for the timeout (if any)
149    */
150   struct GNUNET_SCHEDULER_Task *ttask;
151
152   /**
153    * #GNUNET_YES if we're testing TCP
154    */
155   int is_tcp;
156
157   /**
158    * Data that should be transmitted or source-port.
159    */
160   uint16_t data;
161
162   /**
163    * Advertised port to the other peer.
164    */
165   uint16_t adv_port;
166
167   /**
168    * Status code to be reported to the timeout/status call
169    */
170   enum GNUNET_NAT_StatusCode status;
171 };
172
173
174 /**
175  * Function called from #GNUNET_NAT_register whenever someone asks us
176  * to do connection reversal.
177  *
178  * @param cls closure, our `struct GNUNET_NAT_Handle`
179  * @param addr public IP address of the other peer
180  * @param addrlen actual lenght of the @a addr
181  */
182 static void
183 reversal_cb(void *cls, const struct sockaddr *addr, socklen_t addrlen)
184 {
185   struct GNUNET_NAT_Test *h = cls;
186   const struct sockaddr_in *sa;
187
188   if (sizeof(struct sockaddr_in) != addrlen)
189     return;
190   sa = (const struct sockaddr_in *)addr;
191   if (h->data != sa->sin_port)
192     {
193       LOG(GNUNET_ERROR_TYPE_DEBUG,
194           "Received connection reversal request for wrong port\n");
195       return; /* wrong port */
196     }
197   /* report success */
198   h->report(h->report_cls, GNUNET_NAT_ERROR_SUCCESS);
199 }
200
201
202 /**
203  * Activity on our incoming socket.  Read data from the
204  * incoming connection.
205  *
206  * @param cls the `struct GNUNET_NAT_Test`
207  */
208 static void
209 do_udp_read(void *cls)
210 {
211   struct GNUNET_NAT_Test *tst = cls;
212   uint16_t data;
213   const struct GNUNET_SCHEDULER_TaskContext *tc;
214
215   tc = GNUNET_SCHEDULER_get_task_context();
216   tst->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
217                                              tst->lsock,
218                                              &do_udp_read,
219                                              tst);
220   if ((NULL != tc->write_ready) &&
221       (GNUNET_NETWORK_fdset_isset(tc->read_ready, tst->lsock)) &&
222       (sizeof(data) ==
223        GNUNET_NETWORK_socket_recv(tst->lsock, &data, sizeof(data))))
224     {
225       if (data == tst->data)
226         tst->report(tst->report_cls, GNUNET_NAT_ERROR_SUCCESS);
227       else
228         LOG(GNUNET_ERROR_TYPE_DEBUG,
229             "Received data mismatches expected value\n");
230     }
231   else
232     LOG(GNUNET_ERROR_TYPE_DEBUG,
233         "Failed to receive data from inbound connection\n");
234 }
235
236
237 /**
238  * Activity on our incoming socket.  Read data from the
239  * incoming connection.
240  *
241  * @param cls the `struct NatActivity`
242  */
243 static void
244 do_read(void *cls)
245 {
246   struct NatActivity *na = cls;
247   struct GNUNET_NAT_Test *tst;
248   uint16_t data;
249   const struct GNUNET_SCHEDULER_TaskContext *tc;
250
251   tc = GNUNET_SCHEDULER_get_task_context();
252   na->rtask = NULL;
253   tst = na->h;
254   GNUNET_CONTAINER_DLL_remove(tst->na_head, tst->na_tail, na);
255   if ((NULL != tc->write_ready) &&
256       (GNUNET_NETWORK_fdset_isset(tc->read_ready, na->sock)) &&
257       (sizeof(data) ==
258        GNUNET_NETWORK_socket_recv(na->sock, &data, sizeof(data))))
259     {
260       if (data == tst->data)
261         tst->report(tst->report_cls, GNUNET_NAT_ERROR_SUCCESS);
262       else
263         LOG(GNUNET_ERROR_TYPE_DEBUG,
264             "Received data does not match expected value\n");
265     }
266   else
267     LOG(GNUNET_ERROR_TYPE_DEBUG,
268         "Failed to receive data from inbound connection\n");
269   GNUNET_NETWORK_socket_close(na->sock);
270   GNUNET_free(na);
271 }
272
273
274 /**
275  * Activity on our listen socket. Accept the
276  * incoming connection.
277  *
278  * @param cls the `struct GNUNET_NAT_Test`
279  */
280 static void
281 do_accept(void *cls)
282 {
283   struct GNUNET_NAT_Test *tst = cls;
284   struct GNUNET_NETWORK_Handle *s;
285   struct NatActivity *wl;
286
287   tst->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
288                                              tst->lsock,
289                                              &do_accept,
290                                              tst);
291   s = GNUNET_NETWORK_socket_accept(tst->lsock, NULL, NULL);
292   if (NULL == s)
293     {
294       GNUNET_log_strerror(GNUNET_ERROR_TYPE_INFO, "accept");
295       return; /* odd error */
296     }
297   LOG(GNUNET_ERROR_TYPE_DEBUG,
298       "Got an inbound connection, waiting for data\n");
299   wl = GNUNET_new(struct NatActivity);
300   wl->sock = s;
301   wl->h = tst;
302   wl->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
303                                             wl->sock,
304                                             &do_read,
305                                             wl);
306   GNUNET_CONTAINER_DLL_insert(tst->na_head, tst->na_tail, wl);
307 }
308
309
310 /**
311  * We got disconnected from the NAT server.  Stop
312  * waiting for a reply.
313  *
314  * @param cls the `struct ClientActivity`
315  * @param error error code
316  */
317 static void
318 mq_error_handler(void *cls, enum GNUNET_MQ_Error error)
319 {
320   struct ClientActivity *ca = cls;
321   struct GNUNET_NAT_Test *tst = ca->h;
322
323   GNUNET_CONTAINER_DLL_remove(tst->ca_head, tst->ca_tail, ca);
324   GNUNET_MQ_destroy(ca->mq);
325   GNUNET_free(ca);
326 }
327
328
329 /**
330  * Address-callback, used to send message to gnunet-nat-server.
331  *
332  * @param cls closure
333  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
334  *     the previous (now invalid) one
335  * @param addr either the previous or the new public IP address
336  * @param addrlen actual length of the @a addr
337  */
338 static void
339 addr_cb(void *cls,
340         int add_remove,
341         const struct sockaddr *addr,
342         socklen_t addrlen)
343 {
344   struct GNUNET_NAT_Test *h = cls;
345   struct ClientActivity *ca;
346   struct GNUNET_MQ_Envelope *env;
347   struct GNUNET_NAT_TestMessage *msg;
348   const struct sockaddr_in *sa;
349
350   if (GNUNET_YES != add_remove)
351     return;
352   if (addrlen != sizeof(struct sockaddr_in))
353     {
354       LOG(GNUNET_ERROR_TYPE_DEBUG,
355           "NAT test ignores IPv6 address `%s' returned from NAT library\n",
356           GNUNET_a2s(addr, addrlen));
357       return; /* ignore IPv6 here */
358     }
359   LOG(GNUNET_ERROR_TYPE_INFO,
360       "Asking gnunet-nat-server to connect to `%s'\n",
361       GNUNET_a2s(addr, addrlen));
362
363   ca = GNUNET_new(struct ClientActivity);
364   ca->h = h;
365   ca->mq = GNUNET_CLIENT_connect(h->cfg,
366                                  "gnunet-nat-server",
367                                  NULL,
368                                  &mq_error_handler,
369                                  ca);
370   if (NULL == ca->mq)
371     {
372       GNUNET_free(ca);
373       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
374                  _("Failed to connect to `gnunet-nat-server'\n"));
375       return;
376     }
377   GNUNET_CONTAINER_DLL_insert(h->ca_head, h->ca_tail, ca);
378   sa = (const struct sockaddr_in *)addr;
379   env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAT_TEST);
380   msg->dst_ipv4 = sa->sin_addr.s_addr;
381   msg->dport = sa->sin_port;
382   msg->data = h->data;
383   msg->is_tcp = htonl((uint32_t)h->is_tcp);
384   GNUNET_MQ_send(ca->mq, env);
385 }
386
387
388 /**
389  * Timeout task for a nat test.
390  * Calls the report-callback with a timeout return value
391  *
392  * Destroys the nat handle after the callback has been processed.
393  *
394  * @param cls handle to the timed out NAT test
395  */
396 static void
397 do_timeout(void *cls)
398 {
399   struct GNUNET_NAT_Test *nh = cls;
400
401   nh->ttask = NULL;
402   nh->report(nh->report_cls,
403              (GNUNET_NAT_ERROR_SUCCESS == nh->status)
404              ? GNUNET_NAT_ERROR_TIMEOUT
405              : nh->status);
406 }
407
408
409 /**
410  * Start testing if NAT traversal works using the
411  * given configuration (IPv4-only).
412  *
413  * ALL failures are reported directly to the report callback
414  *
415  * @param cfg configuration for the NAT traversal
416  * @param is_tcp #GNUNET_YES to test TCP, #GNUNET_NO to test UDP
417  * @param bnd_port port to bind to, 0 for connection reversal
418  * @param adv_port externally advertised port to use
419  * @param timeout delay after which the test should be aborted
420  * @param report function to call with the result of the test
421  * @param report_cls closure for @a report
422  * @return handle to cancel NAT test or NULL. The error is always indicated via the report callback
423  */
424 struct GNUNET_NAT_Test *
425 GNUNET_NAT_test_start(const struct GNUNET_CONFIGURATION_Handle *cfg,
426                       int is_tcp,
427                       uint16_t bnd_port,
428                       uint16_t adv_port,
429                       struct GNUNET_TIME_Relative timeout,
430                       GNUNET_NAT_TestCallback report,
431                       void *report_cls)
432 {
433   struct GNUNET_NAT_Test *nh;
434   struct sockaddr_in sa;
435   const struct sockaddr *addrs[] = { (const struct sockaddr *)&sa };
436   const socklen_t addrlens[] = { sizeof(sa) };
437
438   memset(&sa, 0, sizeof(sa));
439   sa.sin_family = AF_INET;
440   sa.sin_port = htons(bnd_port);
441 #if HAVE_SOCKADDR_IN_SIN_LEN
442   sa.sin_len = sizeof(sa);
443 #endif
444
445   nh = GNUNET_new(struct GNUNET_NAT_Test);
446   nh->cfg = cfg;
447   nh->is_tcp = is_tcp;
448   nh->data = bnd_port;
449   nh->adv_port = adv_port;
450   nh->report = report;
451   nh->report_cls = report_cls;
452   nh->status = GNUNET_NAT_ERROR_SUCCESS;
453   if (0 == bnd_port)
454     {
455       nh->nat = GNUNET_NAT_register(cfg,
456                                     is_tcp,
457                                     0,
458                                     0,
459                                     NULL,
460                                     NULL,
461                                     &addr_cb,
462                                     &reversal_cb,
463                                     nh,
464                                     NULL);
465     }
466   else
467     {
468       nh->lsock =
469         GNUNET_NETWORK_socket_create(AF_INET,
470                                      (is_tcp == GNUNET_YES) ? SOCK_STREAM
471                                      : SOCK_DGRAM,
472                                      0);
473       if ((nh->lsock == NULL) ||
474           (GNUNET_OK != GNUNET_NETWORK_socket_bind(nh->lsock,
475                                                    (const struct sockaddr *)&sa,
476                                                    sizeof(sa))))
477         {
478           GNUNET_log(
479             GNUNET_ERROR_TYPE_ERROR,
480             _("Failed to create listen socket bound to `%s' for NAT test: %s\n"),
481             GNUNET_a2s((const struct sockaddr *)&sa, sizeof(sa)),
482             strerror(errno));
483           if (NULL != nh->lsock)
484             {
485               GNUNET_NETWORK_socket_close(nh->lsock);
486               nh->lsock = NULL;
487             }
488           nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR;
489           nh->ttask = GNUNET_SCHEDULER_add_now(&do_timeout, nh);
490           return nh;
491         }
492       if (GNUNET_YES == is_tcp)
493         {
494           GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_listen(nh->lsock, 5));
495           nh->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
496                                                     nh->lsock,
497                                                     &do_accept,
498                                                     nh);
499         }
500       else
501         {
502           nh->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
503                                                     nh->lsock,
504                                                     &do_udp_read,
505                                                     nh);
506         }
507       LOG(GNUNET_ERROR_TYPE_INFO,
508           "NAT test listens on port %u (%s)\n",
509           bnd_port,
510           (GNUNET_YES == is_tcp) ? "tcp" : "udp");
511       nh->nat = GNUNET_NAT_register(cfg,
512                                     is_tcp,
513                                     adv_port,
514                                     1,
515                                     addrs,
516                                     addrlens,
517                                     &addr_cb,
518                                     NULL,
519                                     nh,
520                                     NULL);
521       if (NULL == nh->nat)
522         {
523           LOG(GNUNET_ERROR_TYPE_INFO,
524               _("NAT test failed to start NAT library\n"));
525           if (NULL != nh->ltask)
526             {
527               GNUNET_SCHEDULER_cancel(nh->ltask);
528               nh->ltask = NULL;
529             }
530           if (NULL != nh->lsock)
531             {
532               GNUNET_NETWORK_socket_close(nh->lsock);
533               nh->lsock = NULL;
534             }
535           nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED;
536           nh->ttask = GNUNET_SCHEDULER_add_now(&do_timeout, nh);
537           return nh;
538         }
539     }
540   nh->ttask = GNUNET_SCHEDULER_add_delayed(timeout, &do_timeout, nh);
541   return nh;
542 }
543
544
545 /**
546  * Stop an active NAT test.
547  *
548  * @param tst test to stop.
549  */
550 void
551 GNUNET_NAT_test_stop(struct GNUNET_NAT_Test *tst)
552 {
553   struct NatActivity *pos;
554   struct ClientActivity *cpos;
555
556   LOG(GNUNET_ERROR_TYPE_DEBUG, "Stopping NAT test\n");
557   while (NULL != (cpos = tst->ca_head))
558     {
559       GNUNET_CONTAINER_DLL_remove(tst->ca_head, tst->ca_tail, cpos);
560       GNUNET_MQ_destroy(cpos->mq);
561       GNUNET_free(cpos);
562     }
563   while (NULL != (pos = tst->na_head))
564     {
565       GNUNET_CONTAINER_DLL_remove(tst->na_head, tst->na_tail, pos);
566       GNUNET_SCHEDULER_cancel(pos->rtask);
567       GNUNET_NETWORK_socket_close(pos->sock);
568       GNUNET_free(pos);
569     }
570   if (NULL != tst->ttask)
571     {
572       GNUNET_SCHEDULER_cancel(tst->ttask);
573       tst->ttask = NULL;
574     }
575   if (NULL != tst->ltask)
576     {
577       GNUNET_SCHEDULER_cancel(tst->ltask);
578       tst->ltask = NULL;
579     }
580   if (NULL != tst->lsock)
581     {
582       GNUNET_NETWORK_socket_close(tst->lsock);
583       tst->lsock = NULL;
584     }
585   if (NULL != tst->nat)
586     {
587       GNUNET_NAT_unregister(tst->nat);
588       tst->nat = NULL;
589     }
590   GNUNET_free(tst);
591 }
592
593 /* end of nat_test.c */