-better logging in NAT
[oweals/gnunet.git] / src / nat / nat_mini.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_mini.c
23  * @brief functions for interaction with miniupnp; tested with miniupnpc 1.5
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 /**
34  * How long do we give upnpc to create a mapping?
35  */
36 #define MAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
37
38 /**
39  * How long do we give upnpc to remove a mapping?
40  */
41 #define UNMAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
42
43 /**
44  * How often do we check for changes in the mapping?
45  */
46 #define MAP_REFRESH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
47
48
49
50 /**
51  * Opaque handle to cancel "GNUNET_NAT_mini_get_external_ipv4" operation.
52  */
53 struct GNUNET_NAT_ExternalHandle
54 {
55
56   /**
57    * Function to call with the result.
58    */
59   GNUNET_NAT_IPCallback cb;
60
61   /**
62    * Closure for 'cb'.
63    */
64   void *cb_cls;
65
66   /**
67    * Read task.
68    */
69   GNUNET_SCHEDULER_TaskIdentifier task;
70
71   /**
72    * Handle to 'external-ip' process.
73    */
74   struct GNUNET_OS_Process *eip;
75
76   /**
77    * Handle to stdout pipe of 'external-ip'.
78    */
79   struct GNUNET_DISK_PipeHandle *opipe;
80
81   /**
82    * Read handle of 'opipe'.
83    */
84   const struct GNUNET_DISK_FileHandle *r;
85
86   /**
87    * When should this operation time out?
88    */
89   struct GNUNET_TIME_Absolute timeout;
90
91   /**
92    * Number of bytes in 'buf' that are valid.
93    */
94   size_t off;
95
96   /**
97    * Destination of our read operation (output of 'external-ip').
98    */
99   char buf[17];
100
101 };
102
103
104 /**
105  * Read the output of 'external-ip' into buf.  When complete, parse the
106  * address and call our callback.
107  *
108  * @param cls the 'struct GNUNET_NAT_ExternalHandle'
109  * @param tc scheduler context
110  */
111 static void
112 read_external_ipv4 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
113 {
114   struct GNUNET_NAT_ExternalHandle *eh = cls;
115   ssize_t ret;
116   struct in_addr addr;
117   int iret;
118
119   eh->task = GNUNET_SCHEDULER_NO_TASK;
120   if (GNUNET_YES == GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, eh->r))
121     ret =
122         GNUNET_DISK_file_read (eh->r, &eh->buf[eh->off],
123                                sizeof (eh->buf) - eh->off);
124   else
125     ret = -1;                   /* error reading, timeout, etc. */
126   if (ret > 0)
127   {
128     /* try to read more */
129     eh->off += ret;
130     eh->task =
131         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
132                                         (eh->timeout), eh->r,
133                                         &read_external_ipv4, eh);
134     return;
135   }
136   iret = GNUNET_NO;
137   if ((eh->off > 7) && (eh->buf[eh->off - 1] == '\n'))
138   {
139     eh->buf[eh->off - 1] = '\0';
140     if (1 == inet_pton (AF_INET, eh->buf, &addr))
141     {
142       if (addr.s_addr == 0)
143         iret = GNUNET_NO;       /* got 0.0.0.0 */
144       else
145         iret = GNUNET_OK;
146     }
147   }
148   eh->cb (eh->cb_cls, (iret == GNUNET_OK) ? &addr : NULL);
149   GNUNET_NAT_mini_get_external_ipv4_cancel (eh);
150 }
151
152
153 /**
154  * Try to get the external IPv4 address of this peer.
155  *
156  * @param timeout when to fail
157  * @param cb function to call with result
158  * @param cb_cls closure for 'cb'
159  * @return handle for cancellation (can only be used until 'cb' is called), NULL on error
160  */
161 struct GNUNET_NAT_ExternalHandle *
162 GNUNET_NAT_mini_get_external_ipv4 (struct GNUNET_TIME_Relative timeout,
163                                    GNUNET_NAT_IPCallback cb, void *cb_cls)
164 {
165   struct GNUNET_NAT_ExternalHandle *eh;
166
167   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary ("external-ip"))
168   {
169     LOG (GNUNET_ERROR_TYPE_INFO,
170          _("`external-ip' command not found\n"));
171     return NULL;
172   }
173   LOG (GNUNET_ERROR_TYPE_DEBUG,
174        "Running `external-ip' to determine our external IP\n");
175   eh = GNUNET_malloc (sizeof (struct GNUNET_NAT_ExternalHandle));
176   eh->cb = cb;
177   eh->cb_cls = cb_cls;
178   eh->opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
179   if (NULL == eh->opipe)
180   {
181     GNUNET_free (eh);
182     return NULL;
183   }
184   eh->eip =
185     GNUNET_OS_start_process (GNUNET_NO, 0, NULL, eh->opipe, "external-ip", "external-ip",
186                                NULL);
187   if (NULL == eh->eip)
188   {
189     GNUNET_DISK_pipe_close (eh->opipe);
190     GNUNET_free (eh);
191     return NULL;
192   }
193   GNUNET_DISK_pipe_close_end (eh->opipe, GNUNET_DISK_PIPE_END_WRITE);
194   eh->timeout = GNUNET_TIME_relative_to_absolute (timeout);
195   eh->r = GNUNET_DISK_pipe_handle (eh->opipe, GNUNET_DISK_PIPE_END_READ);
196   eh->task =
197       GNUNET_SCHEDULER_add_read_file (timeout, eh->r, &read_external_ipv4, eh);
198   return eh;
199 }
200
201
202 /**
203  * Cancel operation.
204  *
205  * @param eh operation to cancel
206  */
207 void
208 GNUNET_NAT_mini_get_external_ipv4_cancel (struct GNUNET_NAT_ExternalHandle *eh)
209 {
210   (void) GNUNET_OS_process_kill (eh->eip, SIGKILL);
211   GNUNET_OS_process_destroy (eh->eip);
212   GNUNET_DISK_pipe_close (eh->opipe);
213   if (GNUNET_SCHEDULER_NO_TASK != eh->task)
214     GNUNET_SCHEDULER_cancel (eh->task);
215   GNUNET_free (eh);
216 }
217
218
219 /**
220  * Handle to a mapping created with upnpc.
221  */
222 struct GNUNET_NAT_MiniHandle
223 {
224
225   /**
226    * Function to call on mapping changes.
227    */
228   GNUNET_NAT_AddressCallback ac;
229
230   /**
231    * Closure for 'ac'.
232    */
233   void *ac_cls;
234
235   /**
236    * Command used to install the map.
237    */
238   struct GNUNET_OS_CommandHandle *map_cmd;
239
240   /**
241    * Command used to refresh our map information.
242    */
243   struct GNUNET_OS_CommandHandle *refresh_cmd;
244
245   /**
246    * Command used to remove the mapping.
247    */
248   struct GNUNET_OS_CommandHandle *unmap_cmd;
249
250   /**
251    * Our current external mapping (if we have one).
252    */
253   struct sockaddr_in current_addr;
254
255   /**
256    * We check the mapping periodically to see if it
257    * still works.  This task triggers the check.
258    */
259   GNUNET_SCHEDULER_TaskIdentifier refresh_task;
260
261   /**
262    * Are we mapping TCP or UDP?
263    */
264   int is_tcp;
265
266   /**
267    * Did we succeed with creating a mapping?
268    */
269   int did_map;
270
271   /**
272    * Did we find our mapping during refresh scan?
273    */
274   int found;
275
276   /**
277    * Which port are we mapping?
278    */
279   uint16_t port;
280
281 };
282
283
284 /**
285  * Run upnpc -l to find out if our mapping changed.
286  *
287  * @param cls the 'struct GNUNET_NAT_MiniHandle'
288  * @param tc scheduler context
289  */
290 static void
291 do_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
292
293
294 /**
295  * Process the output from the 'upnpc -r' command.
296  *
297  * @param cls the 'struct GNUNET_NAT_MiniHandle'
298  * @param line line of output, NULL at the end
299  */
300 static void
301 process_map_output (void *cls, const char *line);
302
303
304 /**
305  * Process the output from 'upnpc -l' to see if our
306  * external mapping changed.  If so, do the notifications.
307  *
308  * @param cls the 'struct GNUNET_NAT_MiniHandle'
309  * @param line line of output, NULL at the end
310  */
311 static void
312 process_refresh_output (void *cls, const char *line)
313 {
314   struct GNUNET_NAT_MiniHandle *mini = cls;
315   char pstr[9];
316   const char *s;
317   unsigned int nport;
318   struct in_addr exip;
319
320   if (NULL == line)
321   {
322     GNUNET_OS_command_stop (mini->refresh_cmd);
323     mini->refresh_cmd = NULL;
324     if (mini->found == GNUNET_NO)
325     {
326       /* mapping disappeared, try to re-create */
327       if (mini->did_map)
328       {
329         mini->ac (mini->ac_cls, GNUNET_NO,
330                   (const struct sockaddr *) &mini->current_addr,
331                   sizeof (mini->current_addr));
332         mini->did_map = GNUNET_NO;
333       }
334       GNUNET_snprintf (pstr, sizeof (pstr), "%u", (unsigned int) mini->port);
335       mini->map_cmd =
336           GNUNET_OS_command_run (&process_map_output, mini, MAP_TIMEOUT,
337                                  "upnpc", "upnpc", "-r", pstr,
338                                  mini->is_tcp ? "tcp" : "udp", NULL);
339       if (NULL != mini->map_cmd)
340         return;
341     }
342     mini->refresh_task =
343         GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ, &do_refresh, mini);
344     return;
345   }
346   if (!mini->did_map)
347     return;                     /* never mapped, won't find our mapping anyway */
348
349   /* we're looking for output of the form:
350    * "ExternalIPAddress = 12.134.41.124" */
351
352   s = strstr (line, "ExternalIPAddress = ");
353   if (NULL != s)
354   {
355     s += strlen ("ExternalIPAddress = ");
356     if (1 != inet_pton (AF_INET, s, &exip))
357       return;                   /* skip */
358     if (exip.s_addr == mini->current_addr.sin_addr.s_addr)
359       return;                   /* no change */
360     /* update mapping */
361     mini->ac (mini->ac_cls, GNUNET_NO,
362               (const struct sockaddr *) &mini->current_addr,
363               sizeof (mini->current_addr));
364     mini->current_addr.sin_addr = exip;
365     mini->ac (mini->ac_cls, GNUNET_YES,
366               (const struct sockaddr *) &mini->current_addr,
367               sizeof (mini->current_addr));
368     return;
369   }
370   /*
371    * we're looking for output of the form:
372    *
373    * "0 TCP  3000->192.168.2.150:3000  'libminiupnpc' ''"
374    * "1 UDP  3001->192.168.2.150:3001  'libminiupnpc' ''"
375    *
376    * the pattern we look for is:
377    *
378    * "%s TCP  PORT->STRING:OURPORT *" or
379    * "%s UDP  PORT->STRING:OURPORT *"
380    */
381   GNUNET_snprintf (pstr, sizeof (pstr), ":%u ", mini->port);
382   if (NULL == (s = strstr (line, "->")))
383     return;                     /* skip */
384   if (NULL == strstr (s, pstr))
385     return;                     /* skip */
386   if (1 !=
387       SSCANF (line,
388               (mini->is_tcp) ? "%*u TCP  %u->%*s:%*u %*s" :
389               "%*u UDP  %u->%*s:%*u %*s", &nport))
390     return;                     /* skip */
391   mini->found = GNUNET_YES;
392   if (nport == ntohs (mini->current_addr.sin_port))
393     return;                     /* no change */
394
395   /* external port changed, update mapping */
396   mini->ac (mini->ac_cls, GNUNET_NO,
397             (const struct sockaddr *) &mini->current_addr,
398             sizeof (mini->current_addr));
399   mini->current_addr.sin_port = htons ((uint16_t) nport);
400   mini->ac (mini->ac_cls, GNUNET_YES,
401             (const struct sockaddr *) &mini->current_addr,
402             sizeof (mini->current_addr));
403 }
404
405
406 /**
407  * Run upnpc -l to find out if our mapping changed.
408  *
409  * @param cls the 'struct GNUNET_NAT_MiniHandle'
410  * @param tc scheduler context
411  */
412 static void
413 do_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
414 {
415   struct GNUNET_NAT_MiniHandle *mini = cls;
416
417   LOG (GNUNET_ERROR_TYPE_DEBUG,
418        "Running `upnpc' to check if our mapping still exists\n");
419   mini->refresh_task = GNUNET_SCHEDULER_NO_TASK;
420   mini->found = GNUNET_NO;
421   mini->refresh_cmd =
422       GNUNET_OS_command_run (&process_refresh_output, mini, MAP_TIMEOUT,
423                              "upnpc", "upnpc", "-l", NULL);
424 }
425
426
427 /**
428  * Process the output from the 'upnpc -r' command.
429  *
430  * @param cls the 'struct GNUNET_NAT_MiniHandle'
431  * @param line line of output, NULL at the end
432  */
433 static void
434 process_map_output (void *cls, const char *line)
435 {
436   struct GNUNET_NAT_MiniHandle *mini = cls;
437   const char *ipaddr;
438   char *ipa;
439   const char *pstr;
440   unsigned int port;
441
442   if (NULL == line)
443   {
444     GNUNET_OS_command_stop (mini->map_cmd);
445     mini->map_cmd = NULL;
446     mini->refresh_task =
447         GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ, &do_refresh, mini);
448     return;
449   }
450   /*
451    * The upnpc output we're after looks like this:
452    *
453    * "external 87.123.42.204:3000 TCP is redirected to internal 192.168.2.150:3000"
454    */
455   if ((NULL == (ipaddr = strstr (line, " "))) ||
456       (NULL == (pstr = strstr (ipaddr, ":"))) ||
457       (1 != SSCANF (pstr + 1, "%u", &port)))
458   {
459     return;                     /* skip line */
460   }
461   ipa = GNUNET_strdup (ipaddr + 1);
462   strstr (ipa, ":")[0] = '\0';
463   if (1 != inet_pton (AF_INET, ipa, &mini->current_addr.sin_addr))
464   {
465     GNUNET_free (ipa);
466     return;                     /* skip line */
467   }
468   GNUNET_free (ipa);
469
470   mini->current_addr.sin_port = htons (port);
471   mini->current_addr.sin_family = AF_INET;
472 #if HAVE_SOCKADDR_IN_SIN_LEN
473   mini->current_addr.sin_len = sizeof (struct sockaddr_in);
474 #endif
475   mini->did_map = GNUNET_YES;
476   mini->ac (mini->ac_cls, GNUNET_YES,
477             (const struct sockaddr *) &mini->current_addr,
478             sizeof (mini->current_addr));
479 }
480
481
482 /**
483  * Start mapping the given port using (mini)upnpc.  This function
484  * should typically not be used directly (it is used within the
485  * general-purpose 'GNUNET_NAT_register' code).  However, it can be
486  * used if specifically UPnP-based NAT traversal is to be used or
487  * tested.
488  *
489  * @param port port to map
490  * @param is_tcp GNUNET_YES to map TCP, GNUNET_NO for UDP
491  * @param ac function to call with mapping result
492  * @param ac_cls closure for 'ac'
493  * @return NULL on error (no 'upnpc' installed)
494  */
495 struct GNUNET_NAT_MiniHandle *
496 GNUNET_NAT_mini_map_start (uint16_t port, int is_tcp,
497                            GNUNET_NAT_AddressCallback ac, void *ac_cls)
498 {
499   struct GNUNET_NAT_MiniHandle *ret;
500   char pstr[6];
501
502   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary ("upnpc"))
503   {
504     LOG (GNUNET_ERROR_TYPE_INFO,
505          _("`upnpc' command not found\n"));
506     return NULL;
507   }
508   LOG (GNUNET_ERROR_TYPE_DEBUG,
509        "Running `upnpc' to install mapping\n");
510   ret = GNUNET_malloc (sizeof (struct GNUNET_NAT_MiniHandle));
511   ret->ac = ac;
512   ret->ac_cls = ac_cls;
513   ret->is_tcp = is_tcp;
514   ret->port = port;
515   GNUNET_snprintf (pstr, sizeof (pstr), "%u", (unsigned int) port);
516   ret->map_cmd =
517       GNUNET_OS_command_run (&process_map_output, ret, MAP_TIMEOUT, "upnpc",
518                              "upnpc", "-r", pstr, is_tcp ? "tcp" : "udp", NULL);
519   if (NULL != ret->map_cmd)
520     return ret;
521   ret->refresh_task =
522       GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ, &do_refresh, ret);
523
524   return ret;
525 }
526
527
528 /**
529  * Process output from our 'unmap' command.
530  *
531  * @param cls the 'struct GNUNET_NAT_MiniHandle'
532  * @param line line of output, NULL at the end
533  */
534 static void
535 process_unmap_output (void *cls, const char *line)
536 {
537   struct GNUNET_NAT_MiniHandle *mini = cls;
538
539   if (NULL == line)
540   {
541     LOG (GNUNET_ERROR_TYPE_DEBUG, "UPnP unmap done\n");
542     GNUNET_OS_command_stop (mini->unmap_cmd);
543     mini->unmap_cmd = NULL;
544     GNUNET_free (mini);
545     return;
546   }
547   /* we don't really care about the output... */
548 }
549
550
551 /**
552  * Remove a mapping created with (mini)upnpc.  Calling
553  * this function will give 'upnpc' 1s to remove tha mapping,
554  * so while this function is non-blocking, a task will be
555  * left with the scheduler for up to 1s past this call.
556  *
557  * @param mini the handle
558  */
559 void
560 GNUNET_NAT_mini_map_stop (struct GNUNET_NAT_MiniHandle *mini)
561 {
562   char pstr[6];
563
564   if (GNUNET_SCHEDULER_NO_TASK != mini->refresh_task)
565   {
566     GNUNET_SCHEDULER_cancel (mini->refresh_task);
567     mini->refresh_task = GNUNET_SCHEDULER_NO_TASK;
568   }
569   if (mini->refresh_cmd != NULL)
570   {
571     GNUNET_OS_command_stop (mini->refresh_cmd);
572     mini->refresh_cmd = NULL;
573   }
574   if (!mini->did_map)
575   {
576     if (mini->map_cmd != NULL)
577     {
578       GNUNET_OS_command_stop (mini->map_cmd);
579       mini->map_cmd = NULL;
580     }
581     GNUNET_free (mini);
582     return;
583   }
584   mini->ac (mini->ac_cls, GNUNET_NO,
585             (const struct sockaddr *) &mini->current_addr,
586             sizeof (mini->current_addr));
587   /* Note: oddly enough, deletion uses the external port whereas
588    * addition uses the internal port; this rarely matters since they
589    * often are the same, but it might... */
590   GNUNET_snprintf (pstr, sizeof (pstr), "%u",
591                    (unsigned int) ntohs (mini->current_addr.sin_port));
592   LOG (GNUNET_ERROR_TYPE_DEBUG, "Unmapping port %u with UPnP\n",
593        ntohs (mini->current_addr.sin_port));
594   mini->unmap_cmd =
595       GNUNET_OS_command_run (&process_unmap_output, mini, UNMAP_TIMEOUT,
596                              "upnpc", "upnpc", "-d", pstr,
597                              mini->is_tcp ? "tcp" : "udp", NULL);
598 }
599
600
601 /* end of nat_mini.c */