preparations for proper manual hole punching support in new NAT API
[oweals/gnunet.git] / src / nat / gnunet-nat.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2015, 2016 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file src/nat/gnunet-nat.c
23  * @brief Command-line tool to interact with the NAT service
24  * @author Christian Grothoff
25  * @author Bruno Cabral
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_nat_service.h"
30
31 /**
32  * Value to return from #main().
33  */
34 static int global_ret;
35
36 /**
37  * Handle to ongoing autoconfiguration.
38  */
39 static struct GNUNET_NAT_AutoHandle *ah;
40
41 /**
42  * External hostname and port, if user manually punched
43  * the NAT.  
44  */ 
45 static char *hole_external;
46
47 /**
48  * Flag set to 1 if we use IPPROTO_UDP.
49  */
50 static int use_udp;
51
52 /**
53  * Flag set to 1 if we are to listen for connection reversal requests.
54  */
55 static int listen_reversal;
56
57 /**
58  * Flag set to 1 if we use IPPROTO_TCP.
59  */
60 static int use_tcp;
61
62 /**
63  * If we do auto-configuration, should we write the result
64  * to a file?
65  */
66 static int write_cfg;
67
68 /**
69  * Configuration filename.
70  */ 
71 static const char *cfg_file;
72
73 /**
74  * Original configuration.
75  */
76 static const struct GNUNET_CONFIGURATION_Handle *cfg;
77
78 /**
79  * Protocol to use.
80  */
81 static uint8_t proto;
82
83 /**
84  * Address we are bound to (in test), or should bind to
85  * (if #do_stun is set).
86  */
87 static char *bind_addr;
88
89 /**
90  * External IP address and port to use for the test.
91  * If not set, use #bind_addr.
92  */
93 static char *extern_addr;
94
95 /**
96  * Local address to use for connection reversal request.
97  */
98 static char *local_addr;
99
100 /**
101  * Remote address to use for connection reversal request.
102  */
103 static char *remote_addr;
104
105 /**
106  * Should we actually bind to #bind_addr and receive and process STUN requests?
107  */
108 static unsigned int do_stun;
109
110 /**
111  * Should we run autoconfiguration?
112  */
113 static unsigned int do_auto;
114
115 /**
116  * Handle to a NAT test operation.
117  */
118 static struct GNUNET_NAT_Test *nt;
119
120 /**
121  * Handle to NAT operation.
122  */
123 static struct GNUNET_NAT_Handle *nh;
124
125 /**
126  * Listen socket for STUN processing.
127  */ 
128 static struct GNUNET_NETWORK_Handle *ls;
129
130 /**
131  * Task for reading STUN packets.
132  */
133 static struct GNUNET_SCHEDULER_Task *rtask;
134
135
136 /**
137  * Test if all activities have finished, and if so,
138  * terminate.
139  */
140 static void
141 test_finished ()
142 {
143   if (NULL != ah)
144     return;
145   if (NULL != nt)
146     return;
147   if (NULL != nh)
148     return;
149   if (NULL != rtask)
150     return;
151   GNUNET_SCHEDULER_shutdown ();
152 }
153
154
155 /**
156  * Function to iterate over sugested changes options
157  *
158  * @param cls closure
159  * @param section name of the section
160  * @param option name of the option
161  * @param value value of the option
162  */
163 static void
164 auto_conf_iter (void *cls,
165                 const char *section,
166                 const char *option,
167                 const char *value)
168 {
169   struct GNUNET_CONFIGURATION_Handle *new_cfg = cls;
170   
171   PRINTF ("%s: %s\n",
172           option,
173           value);
174   if (NULL != new_cfg)
175     GNUNET_CONFIGURATION_set_value_string (new_cfg,
176                                            section,
177                                            option,
178                                            value);
179 }
180
181
182 /**
183  * Function called with the result from the autoconfiguration.
184  *
185  * @param cls closure
186  * @param diff minimal suggested changes to the original configuration
187  *             to make it work (as best as we can)
188  * @param result #GNUNET_NAT_ERROR_SUCCESS on success, otherwise the specific error code
189  * @param type what the situation of the NAT
190  */
191 static void
192 auto_config_cb (void *cls,
193                 const struct GNUNET_CONFIGURATION_Handle *diff,
194                 enum GNUNET_NAT_StatusCode result,
195                 enum GNUNET_NAT_Type type)
196 {
197   const char *nat_type;
198   char unknown_type[64];
199   struct GNUNET_CONFIGURATION_Handle *new_cfg;
200
201   ah = NULL;
202   switch (type)
203   {
204   case GNUNET_NAT_TYPE_NO_NAT:
205     nat_type = "NO NAT";
206     break;
207   case GNUNET_NAT_TYPE_UNREACHABLE_NAT:
208     nat_type = "NAT but we can traverse";
209     break;
210   case GNUNET_NAT_TYPE_STUN_PUNCHED_NAT:
211     nat_type = "NAT but STUN is able to identify the correct information";
212     break;
213   case GNUNET_NAT_TYPE_UPNP_NAT:
214     nat_type = "NAT but UPNP opened the ports";
215     break;
216   default:
217     SPRINTF (unknown_type,
218              "NAT unknown, type %u",
219              type);
220     nat_type = unknown_type;
221     break;
222   }
223
224   GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
225               "NAT status: %s/%s\n",
226               GNUNET_NAT_status2string (result),
227               nat_type);
228
229   /* Shortcut: if there are no changes suggested, bail out early. */
230   if (GNUNET_NO ==
231       GNUNET_CONFIGURATION_is_dirty (diff))
232   {
233     test_finished ();
234     return;
235   }
236
237   /* Apply diff to original configuration and show changes
238      to the user */
239   new_cfg = write_cfg ? GNUNET_CONFIGURATION_dup (cfg) : NULL;
240   
241   if (NULL != diff)
242   {
243     GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
244                 _("Suggested configuration changes:\n"));
245     GNUNET_CONFIGURATION_iterate_section_values (diff,
246                                                  "nat",
247                                                  &auto_conf_iter,
248                                                  new_cfg);
249   }
250
251   /* If desired, write configuration to file; we write only the
252      changes to the defaults to keep things compact. */
253   if ( (write_cfg) &&
254        (NULL != diff) )
255   {
256     struct GNUNET_CONFIGURATION_Handle *def_cfg;
257
258     GNUNET_CONFIGURATION_set_value_string (new_cfg,
259                                            "ARM",
260                                            "CONFIG",
261                                            NULL);
262     def_cfg = GNUNET_CONFIGURATION_create ();
263     GNUNET_break (GNUNET_OK ==
264                   GNUNET_CONFIGURATION_load (def_cfg,
265                                              NULL));
266     if (GNUNET_OK !=
267         GNUNET_CONFIGURATION_write_diffs (def_cfg,
268                                           new_cfg,
269                                           cfg_file))
270     {
271       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
272                   _("Failed to write configuration to `%s'\n"),
273                   cfg_file);
274       global_ret = 1;
275     }
276     else
277     {
278       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
279                   _("Wrote updated configuration to `%s'\n"),
280                   cfg_file);
281     }
282     GNUNET_CONFIGURATION_destroy (def_cfg);
283   }
284
285   if (NULL != new_cfg)
286     GNUNET_CONFIGURATION_destroy (new_cfg);
287   test_finished ();
288 }
289
290
291 /**
292  * Function called to report success or failure for
293  * NAT configuration test.
294  *
295  * @param cls closure
296  * @param result #GNUNET_NAT_ERROR_SUCCESS on success, otherwise the specific error code
297  */
298 static void
299 test_report_cb (void *cls,
300                 enum GNUNET_NAT_StatusCode result)
301 {
302   nt = NULL;
303   PRINTF ("NAT test result: %s\n",
304           GNUNET_NAT_status2string (result));
305   test_finished ();
306 }
307
308
309 /**
310  * Signature of the callback passed to #GNUNET_NAT_register() for
311  * a function to call whenever our set of 'valid' addresses changes.
312  *
313  * @param cls closure, NULL
314  * @param add_remove #GNUNET_YES to add a new public IP address, 
315  *                   #GNUNET_NO to remove a previous (now invalid) one
316  * @param ac address class the address belongs to
317  * @param addr either the previous or the new public IP address
318  * @param addrlen actual length of the @a addr
319  */
320 static void
321 address_cb (void *cls,
322             int add_remove,
323             enum GNUNET_NAT_AddressClass ac,
324             const struct sockaddr *addr,
325             socklen_t addrlen)
326 {
327   GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
328               "%s %s (%d)\n",
329               add_remove ? "+" : "-",
330               GNUNET_a2s (addr,
331                           addrlen),
332               (int) ac);
333 }
334
335
336 /**
337  * Signature of the callback passed to #GNUNET_NAT_register().
338  * for a function to call whenever someone asks us to do connection
339  * reversal.
340  *
341  * @param cls closure, NULL
342  * @param remote_addr public IP address of the other peer
343  * @param remote_addrlen actual length of the @a remote_addr
344  */
345 static void
346 reversal_cb (void *cls,
347              const struct sockaddr *remote_addr,
348              socklen_t remote_addrlen)
349 {
350   GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
351               "Connection reversal requested by %s\n",
352               GNUNET_a2s (remote_addr,
353                           remote_addrlen));
354 }
355
356
357 /**
358  * Task run on shutdown.
359  *
360  * @param cls NULL
361  */
362 static void
363 do_shutdown (void *cls)
364 {
365   if (NULL != ah)
366   {
367     GNUNET_NAT_autoconfig_cancel (ah);
368     ah = NULL;
369   }
370   if (NULL != nt)
371   {
372     GNUNET_NAT_test_stop (nt);
373     nt = NULL;
374   }
375   if (NULL != nh)
376   {
377     GNUNET_NAT_unregister (nh);
378     nh = NULL;
379   }
380   if (NULL != ls)
381   {
382     GNUNET_NETWORK_socket_close (ls);
383     ls = NULL;
384   }
385   if (NULL != rtask)
386   {
387     GNUNET_SCHEDULER_cancel (rtask);
388     rtask = NULL;
389   }
390 }
391
392
393 /**
394  * Task to receive incoming packets for STUN processing.
395  */
396 static void
397 stun_read_task (void *cls)
398 {
399   ssize_t size;
400   
401   rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
402                                          ls,
403                                          &stun_read_task,
404                                          NULL);
405   size = GNUNET_NETWORK_socket_recvfrom_amount (ls);
406   if (size > 0)
407   {
408     GNUNET_break (0);
409     GNUNET_SCHEDULER_shutdown ();
410     global_ret = 1;
411     return;
412   }
413   {
414     char buf[size + 1];
415     struct sockaddr_storage sa;
416     socklen_t salen = sizeof (sa);
417     ssize_t ret;
418     
419     ret = GNUNET_NETWORK_socket_recvfrom (ls,
420                                           buf,
421                                           size + 1,
422                                           (struct sockaddr *) &sa,
423                                           &salen);
424     if (ret != size)
425     {
426       GNUNET_break (0);
427       GNUNET_SCHEDULER_shutdown ();
428       global_ret = 1;
429       return;
430     }
431     (void) GNUNET_NAT_stun_handle_packet (nh,
432                                           (const struct sockaddr *) &sa,
433                                           salen,
434                                           buf,
435                                           ret);
436   }
437 }
438
439
440 /**
441  * Main function that will be run.
442  *
443  * @param cls closure
444  * @param args remaining command-line arguments
445  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
446  * @param c configuration
447  */
448 static void
449 run (void *cls,
450      char *const *args,
451      const char *cfgfile,
452      const struct GNUNET_CONFIGURATION_Handle *c)
453 {
454   uint8_t af;
455   struct sockaddr_in bind_sa;
456   struct sockaddr_in extern_sa;
457   struct sockaddr *local_sa;
458   struct sockaddr *remote_sa;
459   socklen_t local_len;
460   size_t remote_len;
461
462   cfg_file = cfgfile;
463   cfg = c;
464   
465   if (use_tcp && use_udp)
466   {
467     GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
468                 "Cannot use TCP and UDP\n");
469     global_ret = 1;
470     return;
471   }
472   proto = 0;
473   if (use_tcp)
474     proto = IPPROTO_TCP;
475   if (use_udp)
476     proto = IPPROTO_UDP;
477
478   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
479                                  NULL);
480
481   if (do_auto)
482   {
483     ah = GNUNET_NAT_autoconfig_start (c,
484                                       &auto_config_cb,
485                                       NULL);
486   }
487
488   if (0 == proto)
489   {
490     if (do_auto)
491       return; /* all good, we just run auto config */
492     GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
493                 "Must specify either TCP or UDP\n");
494     global_ret = 1;
495     return;
496   }
497   if (NULL != bind_addr)
498   {
499     if (GNUNET_OK !=
500         GNUNET_STRINGS_to_address_ipv4 (bind_addr,
501                                         strlen (bind_addr),
502                                         &bind_sa))
503     {
504       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
505                   "Invalid socket address `%s'\n",
506                   bind_addr);
507       global_ret = 1;
508       return;
509     }
510   }
511   if (NULL != extern_addr)
512   {
513     if (GNUNET_OK !=
514         GNUNET_STRINGS_to_address_ipv4 (extern_addr,
515                                         strlen (extern_addr),
516                                         &extern_sa))
517     {
518       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
519                   "Invalid socket address `%s'\n",
520                   extern_addr);
521       global_ret = 1;
522       return;
523     }
524   }
525   if (NULL != local_addr)
526   {
527     local_len = (socklen_t) GNUNET_STRINGS_parse_socket_addr (local_addr,
528                                                               &af,
529                                                               &local_sa);
530     if (0 == local_len)
531     {
532       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
533                   "Invalid socket address `%s'\n",
534                   local_addr);
535       global_ret = 1;
536       return;
537     }
538   }
539   if (NULL != remote_addr)
540   {
541     remote_len = GNUNET_STRINGS_parse_socket_addr (remote_addr,
542                                                    &af,
543                                                    &remote_sa);
544     if (0 == remote_len)
545     {
546       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
547                   "Invalid socket address `%s'\n",
548                   remote_addr);
549       global_ret = 1;
550       return;
551     }
552   }
553
554   if (NULL != bind_addr)
555   {
556     if (NULL == extern_addr)
557       extern_sa = bind_sa;
558     nt = GNUNET_NAT_test_start (c,
559                                 proto,
560                                 bind_sa.sin_addr,
561                                 ntohs (bind_sa.sin_port),
562                                 extern_sa.sin_addr,
563                                 ntohs (extern_sa.sin_port),
564                                 &test_report_cb,
565                                 NULL);
566   }
567
568   if (NULL != local_addr)
569   {
570     nh = GNUNET_NAT_register (c,
571                               proto,
572                               hole_external,
573                               1,
574                               (const struct sockaddr **) &local_sa,
575                               &local_len,
576                               &address_cb,
577                               (listen_reversal) ? &reversal_cb : NULL,
578                               NULL);
579   }
580   else if (listen_reversal)
581   {
582     GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
583                 "Use of `-W` only effective in combination with `-i`\n");    
584     global_ret = 1;
585     GNUNET_SCHEDULER_shutdown ();
586     return;
587   }
588
589   if (NULL != remote_addr)
590   {
591     int ret;
592     
593     if ( (NULL == nh) ||
594          (sizeof (struct sockaddr_in) != local_len) )
595     {
596       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
597                   "Require IPv4 local address to initiate connection reversal\n");
598       global_ret = 1;
599       GNUNET_SCHEDULER_shutdown ();
600       return;
601     }
602     if (sizeof (struct sockaddr_in) != remote_len)
603     {
604       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
605                   "Require IPv4 reversal target address\n");
606       global_ret = 1;
607       GNUNET_SCHEDULER_shutdown ();
608       return;
609     }
610     ret = GNUNET_NAT_request_reversal (nh,
611                                        (const struct sockaddr_in *) &local_sa,
612                                        (const struct sockaddr_in *) &remote_sa);
613     switch (ret)
614     {
615     case GNUNET_SYSERR:
616       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
617                   "Connection reversal internal error\n");
618       break;
619     case GNUNET_NO:
620       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
621                   "Connection reversal unavailable\n");
622       break;
623     case GNUNET_OK:
624       /* operation in progress */
625       break;
626     }
627   }
628   
629   if (do_stun)
630   {
631     if (NULL == local_addr)
632     {
633       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
634                   "Require local address to support STUN requests\n");
635       global_ret = 1;
636       GNUNET_SCHEDULER_shutdown ();
637       return;
638     }
639     if (IPPROTO_UDP != proto)
640     {
641       GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
642                   "STUN only supported over UDP\n");
643       global_ret = 1;
644       GNUNET_SCHEDULER_shutdown ();
645       return;
646     }
647     ls = GNUNET_NETWORK_socket_create (af,
648                                        SOCK_DGRAM,
649                                        IPPROTO_UDP);
650     if (GNUNET_OK !=
651         GNUNET_NETWORK_socket_bind (ls,
652                                     local_sa,
653                                     local_len))
654     {
655       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
656                   "Failed to bind to %s: %s\n",
657                   GNUNET_a2s (local_sa,
658                               local_len),
659                   STRERROR (errno));
660       global_ret = 1;
661       GNUNET_SCHEDULER_shutdown ();
662       return;
663     }
664     rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
665                                            ls,
666                                            &stun_read_task,
667                                            NULL);
668   }
669
670   test_finished ();
671 }
672
673
674 /**
675  * Main function of gnunet-nat
676  *
677  * @param argc number of command-line arguments
678  * @param argv command line
679  * @return 0 on success, -1 on error
680  */
681 int
682 main (int argc,
683       char *const argv[])
684 {
685   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
686     {'a', "auto", NULL,
687      gettext_noop ("run autoconfiguration"),
688      GNUNET_NO, &GNUNET_GETOPT_set_one, &do_auto },
689     {'b', "bind", "ADDRESS",
690      gettext_noop ("which IP and port are we bound to"),
691      GNUNET_YES, &GNUNET_GETOPT_set_string, &bind_addr },
692     {'e', "external", "ADDRESS",
693      gettext_noop ("which external IP and port should be used to test"),
694      GNUNET_YES, &GNUNET_GETOPT_set_string, &extern_addr },
695     {'i', "in", "ADDRESS",
696      gettext_noop ("which IP and port are we locally using to bind/listen to"),
697      GNUNET_YES, &GNUNET_GETOPT_set_string, &local_addr },
698     {'r', "remote", "ADDRESS",
699      gettext_noop ("which remote IP and port should be asked for connection reversal"),
700      GNUNET_YES, &GNUNET_GETOPT_set_string, &remote_addr },
701     {'p', "punched", NULL,
702      gettext_noop ("external hostname and port of NAT, if punched manually; use AUTO for hostname for automatic determination of the external IP"),
703      GNUNET_YES, &GNUNET_GETOPT_set_string, &hole_external },
704     {'s', "stun", NULL,
705      gettext_noop ("enable STUN processing"),
706      GNUNET_NO, &GNUNET_GETOPT_set_one, &do_stun },
707     {'t', "tcp", NULL,
708      gettext_noop ("use TCP"),
709      GNUNET_NO, &GNUNET_GETOPT_set_one, &use_tcp },
710     {'u', "udp", NULL,
711      gettext_noop ("use UDP"),
712      GNUNET_NO, &GNUNET_GETOPT_set_one, &use_udp },
713     {'w', "write", NULL,
714      gettext_noop ("write configuration file (for autoconfiguration)"),
715      GNUNET_NO, &GNUNET_GETOPT_set_one, &write_cfg },
716     {'W', "watch", NULL,
717      gettext_noop ("watch for connection reversal requests"),
718      GNUNET_NO, &GNUNET_GETOPT_set_one, &listen_reversal },
719    GNUNET_GETOPT_OPTION_END
720   };
721
722   if (GNUNET_OK !=
723       GNUNET_STRINGS_get_utf8_args (argc, argv,
724                                     &argc, &argv))
725     return 2;
726   if (GNUNET_OK !=
727       GNUNET_PROGRAM_run (argc, argv,
728                           "gnunet-nat [options]",
729                           _("GNUnet NAT traversal autoconfigure daemon"),
730                           options,
731                           &run,
732                           NULL))
733   {
734     global_ret = 1;
735   }
736   GNUNET_free ((void*) argv);
737   return global_ret;
738 }
739
740
741 /* end of gnunet-nat.c */