improve/fix handling of NAT server logic for ICMP-based autonomous NAT traversal
[oweals/gnunet.git] / src / nat / gnunet-service-nat_helper.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010, 2011, 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 nat/gnunet-service-nat_helper.c
23  * @brief runs the gnunet-helper-nat-server
24  * @author Milan Bouchet-Valat
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet-service-nat_helper.h"
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__)
32
33 /**
34  * Information we keep per NAT helper process.
35  */
36 struct HelperContext
37 {
38
39   /**
40    * IP address we pass to the NAT helper.
41    */
42   struct in_addr internal_address;
43
44   /**
45    * Function to call if we receive a reversal request.
46    */
47   GN_ReversalCallback cb;
48
49   /**
50    * Closure for @e cb.
51    */
52   void *cb_cls;
53   
54   /**
55    * How long do we wait for restarting a crashed gnunet-helper-nat-server?
56    */
57   struct GNUNET_TIME_Relative server_retry_delay;
58
59   /**
60    * ID of select gnunet-helper-nat-server stdout read task
61    */
62   struct GNUNET_SCHEDULER_Task *server_read_task;
63
64   /**
65    * The process id of the server process (if behind NAT)
66    */
67   struct GNUNET_OS_Process *server_proc;
68
69   /**
70    * stdout pipe handle for the gnunet-helper-nat-server process
71    */
72   struct GNUNET_DISK_PipeHandle *server_stdout;
73
74   /**
75    * stdout file handle (for reading) for the gnunet-helper-nat-server process
76    */
77   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
78 };
79
80
81 /**
82  * Task that restarts the gnunet-helper-nat-server process after a crash
83  * after a certain delay.
84  *
85  * @param cls a `struct HelperContext`
86  */
87 static void
88 restart_nat_server (void *cls);
89
90
91 /**
92  * Try again starting the helper later
93  *
94  * @param h context of the helper
95  */
96 static void
97 try_again (struct HelperContext *h)
98 {
99   GNUNET_assert (NULL == h->server_read_task);
100   h->server_retry_delay
101     = GNUNET_TIME_STD_BACKOFF (h->server_retry_delay);
102   h->server_read_task
103     = GNUNET_SCHEDULER_add_delayed (h->server_retry_delay,
104                                     &restart_nat_server,
105                                     h);
106 }
107
108
109 /**
110  * We have been notified that gnunet-helper-nat-server has written
111  * something to stdout.  Handle the output, then reschedule this
112  * function to be called again once more is available.
113  *
114  * @param cls the `struct HelperContext`
115  */
116 static void
117 nat_server_read (void *cls)
118 {
119   struct HelperContext *h = cls;
120   char mybuf[40];
121   ssize_t bytes;
122   int port;
123   const char *port_start;
124   struct sockaddr_in sin_addr;
125
126   h->server_read_task = NULL;
127   memset (mybuf,
128           0,
129           sizeof (mybuf));
130   bytes 
131     = GNUNET_DISK_file_read (h->server_stdout_handle,
132                              mybuf,
133                              sizeof (mybuf));
134   if (bytes < 1)
135   {
136     LOG (GNUNET_ERROR_TYPE_DEBUG,
137          "Finished reading from server stdout with code: %d\n",
138          bytes);
139     if (0 != GNUNET_OS_process_kill (h->server_proc,
140 -                                    GNUNET_TERM_SIG))
141       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
142                                 "nat",
143                                 "kill");
144     GNUNET_OS_process_wait (h->server_proc);
145     GNUNET_OS_process_destroy (h->server_proc);
146     h->server_proc = NULL;
147     GNUNET_DISK_pipe_close (h->server_stdout);
148     h->server_stdout = NULL;
149     h->server_stdout_handle = NULL;
150     try_again (h);
151     return;
152   }
153
154   port_start = NULL;
155   for (size_t i = 0; i < sizeof (mybuf); i++)
156   {
157     if (mybuf[i] == '\n')
158     {
159       mybuf[i] = '\0';
160       break;
161     }
162     if ((mybuf[i] == ':') && (i + 1 < sizeof (mybuf)))
163     {
164       mybuf[i] = '\0';
165       port_start = &mybuf[i + 1];
166     }
167   }
168
169   /* construct socket address of sender */
170   memset (&sin_addr,
171           0,
172           sizeof (sin_addr));
173   sin_addr.sin_family = AF_INET;
174 #if HAVE_SOCKADDR_IN_SIN_LEN
175   sin_addr.sin_len = sizeof (sin_addr);
176 #endif
177   if ( (NULL == port_start) ||
178        (1 != SSCANF (port_start,
179                      "%d",
180                      &port)) ||
181        (-1 == inet_pton (AF_INET,
182                          mybuf,
183                          &sin_addr.sin_addr)))
184   {
185     /* should we restart gnunet-helper-nat-server? */
186     LOG (GNUNET_ERROR_TYPE_WARNING,
187          "nat",
188          _("gnunet-helper-nat-server generated malformed address `%s'\n"),
189          mybuf);
190     h->server_read_task 
191       = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
192                                         h->server_stdout_handle,
193                                         &nat_server_read,
194                                         h);
195     return;
196   }
197   sin_addr.sin_port = htons ((uint16_t) port);
198   LOG (GNUNET_ERROR_TYPE_DEBUG,
199        "gnunet-helper-nat-server read: %s:%d\n",
200        mybuf,
201        port);
202   h->cb (h->cb_cls,
203          &sin_addr);
204   h->server_read_task 
205     = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
206                                       h->server_stdout_handle,
207                                       &nat_server_read,
208                                       h);
209 }
210
211
212 /**
213  * Task that restarts the gnunet-helper-nat-server process after a crash
214  * after a certain delay.
215  *
216  * @param cls a `struct HelperContext`
217  */
218 static void
219 restart_nat_server (void *cls)
220 {
221   struct HelperContext *h = cls;
222   char *binary;
223   char ia[INET_ADDRSTRLEN];
224   
225   h->server_read_task = NULL;
226   h->server_stdout 
227     = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES,
228                         GNUNET_NO, GNUNET_YES);
229   if (NULL == h->server_stdout)
230   {
231     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
232                          "pipe");
233     try_again (h);
234     return;
235   }
236   GNUNET_assert (NULL !=
237                  inet_ntop (AF_INET,
238                             &h->internal_address,
239                             ia,
240                             sizeof (ia)));
241   LOG (GNUNET_ERROR_TYPE_DEBUG,
242        "Starting `%s' at `%s'\n",
243        "gnunet-helper-nat-server",
244        ia);
245   /* Start the server process */
246   binary
247     = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server");
248   h->server_proc 
249     = GNUNET_OS_start_process (GNUNET_NO,
250                                0,
251                                NULL,
252                                h->server_stdout,
253                                NULL,
254                                binary,
255                                "gnunet-helper-nat-server",
256                                ia,
257                                NULL);
258   GNUNET_free (binary);
259   if (NULL == h->server_proc)
260   {
261     LOG (GNUNET_ERROR_TYPE_WARNING,
262          "nat",
263          _("Failed to start %s\n"),
264          "gnunet-helper-nat-server");
265     GNUNET_DISK_pipe_close (h->server_stdout);
266     h->server_stdout = NULL;
267     try_again (h);
268     return;
269   }
270   /* Close the write end of the read pipe */
271   GNUNET_DISK_pipe_close_end (h->server_stdout,
272                               GNUNET_DISK_PIPE_END_WRITE);
273   h->server_stdout_handle 
274     = GNUNET_DISK_pipe_handle (h->server_stdout,
275                                GNUNET_DISK_PIPE_END_READ);
276   h->server_read_task 
277     = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
278                                       h->server_stdout_handle,
279                                       &nat_server_read,
280                                       h);
281 }
282
283
284 /**
285  * Start the gnunet-helper-nat-server and process incoming
286  * requests.
287  *
288  * @param internal_address
289  * @param cb function to call if we receive a request
290  * @param cb_cls closure for @a cb
291  * @return NULL on error
292  */
293 struct HelperContext *
294 GN_start_gnunet_nat_server_ (const struct in_addr *internal_address,
295                              GN_ReversalCallback cb,
296                              void *cb_cls)
297 {
298   struct HelperContext *h;
299
300   h = GNUNET_new (struct HelperContext);
301   h->cb = cb;
302   h->cb_cls = cb_cls;
303   h->internal_address = *internal_address;
304   if (NULL == h->server_stdout)
305   {
306     GN_stop_gnunet_nat_server_ (h);
307     return NULL;
308   }
309   return h;
310 }
311
312
313 /**
314  * Start the gnunet-helper-nat-server and process incoming
315  * requests.
316  *
317  * @param h helper context to stop
318  */
319 void
320 GN_stop_gnunet_nat_server_ (struct HelperContext *h)
321 {  
322   if (NULL != h->server_read_task)
323   {
324     GNUNET_SCHEDULER_cancel (h->server_read_task);
325     h->server_read_task = NULL;
326   }
327   if (NULL != h->server_proc)
328   {
329     if (0 != GNUNET_OS_process_kill (h->server_proc,
330                                      GNUNET_TERM_SIG))
331       GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
332                                 "nat",
333                                 "kill");
334     GNUNET_OS_process_wait (h->server_proc);
335     GNUNET_OS_process_destroy (h->server_proc);
336     h->server_proc = NULL;
337     GNUNET_DISK_pipe_close (h->server_stdout);
338     h->server_stdout = NULL;
339     h->server_stdout_handle = NULL;
340   }
341   if (NULL != h->server_stdout)
342   {
343     GNUNET_DISK_pipe_close (h->server_stdout);
344     h->server_stdout = NULL;
345     h->server_stdout_handle = NULL;
346   }
347   GNUNET_free (h);
348 }
349
350
351 /**
352  * We want to connect to a peer that is behind NAT.  Run the
353  * gnunet-helper-nat-client to send dummy ICMP responses to cause
354  * that peer to connect to us (connection reversal).
355  *
356  * @param internal_address out internal address to use
357  * @param internal_port port to use
358  * @param remote_v4 the address of the peer (IPv4-only)
359  * @return #GNUNET_SYSERR on error,
360  *         #GNUNET_OK otherwise
361  */
362 int
363 GN_request_connection_reversal (const struct in_addr *internal_address,
364                                 uint16_t internal_port,
365                                 const struct in_addr *remote_v4)
366 {
367   char intv4[INET_ADDRSTRLEN];
368   char remv4[INET_ADDRSTRLEN];
369   char port_as_string[6];
370   struct GNUNET_OS_Process *proc;
371   char *binary;
372
373   if (NULL == inet_ntop (AF_INET,
374                          internal_address,
375                          intv4,
376                          INET_ADDRSTRLEN))
377   {
378     GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
379                               "nat",
380                               "inet_ntop");
381     return GNUNET_SYSERR;
382   }
383   if (NULL == inet_ntop (AF_INET,
384                          remote_v4,
385                          remv4,
386                          INET_ADDRSTRLEN))
387   {
388     GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING,
389                               "nat",
390                               "inet_ntop");
391     return GNUNET_SYSERR;
392   }  
393   GNUNET_snprintf (port_as_string,
394                    sizeof (port_as_string),
395                    "%d",
396                    internal_port);
397   LOG (GNUNET_ERROR_TYPE_DEBUG,
398        _("Running gnunet-helper-nat-client %s %s %u\n"),
399        intv4,
400        remv4,
401        internal_port);
402   binary
403     = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client");
404   proc
405     = GNUNET_OS_start_process (GNUNET_NO,
406                                0,
407                                NULL,
408                                NULL,
409                                NULL,
410                                binary,
411                                "gnunet-helper-nat-client",
412                                intv4,
413                                remv4,
414                                port_as_string,
415                                NULL);
416   GNUNET_free (binary);
417   if (NULL == proc)
418     return GNUNET_SYSERR;
419   /* we know that the gnunet-helper-nat-client will terminate virtually
420    * instantly */
421   GNUNET_OS_process_wait (proc);
422   GNUNET_OS_process_destroy (proc);
423   return GNUNET_OK;
424 }
425
426
427 /* end of gnunet-service-nat_helper.c */