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