2e4dd1a38301f940a62b3e0bb0ad2be75b472e5a
[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
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 /**
32  * How long do we give upnpc to create a mapping?
33  */
34 #define MAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
35
36
37 /**
38  * How long do we give upnpc to remove a mapping?
39  */
40 #define UNMAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
41
42 /**
43  * How often do we check for changes in the mapping?
44  */
45 #define MAP_REFRESH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
46
47
48 /**
49  * Try to get the external IPv4 address of this peer.
50  * Note: calling this function may block this process
51  * for a few seconds (!).
52  *
53  * @param addr address to set
54  * @return GNUNET_OK on success,
55  *         GNUNET_NO if the result is questionable,
56  *         GNUNET_SYSERR on error
57  */
58 int
59 GNUNET_NAT_mini_get_external_ipv4 (struct in_addr *addr)
60 {
61   struct GNUNET_OS_Process *eip;
62   struct GNUNET_DISK_PipeHandle *opipe;
63   const struct GNUNET_DISK_FileHandle *r;
64   size_t off;
65   char buf[17];
66   ssize_t ret;
67   int iret;
68
69   opipe = GNUNET_DISK_pipe (GNUNET_YES,
70                             GNUNET_NO,
71                             GNUNET_YES);
72   if (NULL == opipe)
73     return GNUNET_SYSERR;
74   eip = GNUNET_OS_start_process (NULL,
75                                  opipe,
76                                  "external-ip",
77                                  "external-ip", NULL);
78   if (NULL == eip)
79     {
80       GNUNET_DISK_pipe_close (opipe);
81       return GNUNET_SYSERR;
82     }
83   GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
84   iret = GNUNET_SYSERR;
85   r = GNUNET_DISK_pipe_handle (opipe,
86                                GNUNET_DISK_PIPE_END_READ);
87   off = 0;
88   while (0 < (ret = GNUNET_DISK_file_read (r, &buf[off], sizeof (buf)-off)))
89     off += ret;
90   if ( (off > 7) &&    
91        (buf[off-1] == '\n') )    
92     {
93       buf[off-1] = '\0';
94       if (1 == inet_pton (AF_INET, buf, addr))
95         {
96           if (addr->s_addr == 0)
97             iret = GNUNET_NO; /* got 0.0.0.0 */
98           iret = GNUNET_OK;
99         }
100     }
101   (void) GNUNET_OS_process_kill (eip, SIGKILL);
102   GNUNET_OS_process_close (eip);
103   GNUNET_DISK_pipe_close (opipe);
104   return iret; 
105 }
106
107
108 /**
109  * Handle to a mapping created with upnpc.
110  */ 
111 struct GNUNET_NAT_MiniHandle
112 {
113
114   /**
115    * Function to call on mapping changes.
116    */
117   GNUNET_NAT_AddressCallback ac;
118
119   /**
120    * Closure for 'ac'.
121    */
122   void *ac_cls;
123
124   /**
125    * Command used to install the map.
126    */
127   struct GNUNET_OS_CommandHandle *map_cmd;
128
129   /**
130    * Command used to refresh our map information.
131    */
132   struct GNUNET_OS_CommandHandle *refresh_cmd;
133
134   /**
135    * Command used to remove the mapping.
136    */
137   struct GNUNET_OS_CommandHandle *unmap_cmd;
138
139   /**
140    * Our current external mapping (if we have one).
141    */
142   struct sockaddr_in current_addr;
143
144   /**
145    * We check the mapping periodically to see if it
146    * still works.  This task triggers the check.
147    */
148   GNUNET_SCHEDULER_TaskIdentifier refresh_task;
149
150   /**
151    * Are we mapping TCP or UDP?
152    */
153   int is_tcp;
154
155   /**
156    * Did we succeed with creating a mapping?
157    */
158   int did_map;
159
160   /**
161    * Which port are we mapping?
162    */
163   uint16_t port;
164
165 };
166
167
168 /**
169  * Run upnpc -l to find out if our mapping changed.
170  *
171  * @param cls the 'struct GNUNET_NAT_MiniHandle'
172  * @param tc scheduler context
173  */
174 static void
175 do_refresh (void *cls,
176             const struct GNUNET_SCHEDULER_TaskContext *tc);
177
178
179 /**
180  * Process the output from 'upnpc -l' to see if our
181  * external mapping changed.  If so, do the notifications.
182  *
183  * @param cls the 'struct GNUNET_NAT_MiniHandle'
184  * @param line line of output, NULL at the end
185  */
186 static void
187 process_refresh_output (void *cls,
188                         const char *line)
189 {
190   struct GNUNET_NAT_MiniHandle *mini = cls;
191
192   if (NULL == line)
193     {
194       GNUNET_OS_command_stop (mini->refresh_cmd);
195       mini->refresh_cmd = NULL;
196       mini->refresh_task = GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ,
197                                                          &do_refresh,
198                                                          mini);
199       return;
200     }
201   /* FIXME: parse 'line' */
202   fprintf (stderr,
203            "Refresh output: `%s'\n",
204            line);
205 }
206
207
208 /**
209  * Run upnpc -l to find out if our mapping changed.
210  *
211  * @param cls the 'struct GNUNET_NAT_MiniHandle'
212  * @param tc scheduler context
213  */
214 static void
215 do_refresh (void *cls,
216             const struct GNUNET_SCHEDULER_TaskContext *tc)
217 {
218   struct GNUNET_NAT_MiniHandle *mini = cls;
219
220   mini->refresh_task = GNUNET_SCHEDULER_NO_TASK;
221   mini->refresh_cmd = GNUNET_OS_command_run (&process_refresh_output,
222                                              mini,
223                                              MAP_TIMEOUT,
224                                              "upnpc",
225                                              "upnpc",
226                                              "-l",
227                                              NULL);
228 }
229
230
231 /**
232  * Process the output from the 'upnpc -r' command.
233  *
234  * @param cls the 'struct GNUNET_NAT_MiniHandle'
235  * @param line line of output, NULL at the end
236  */
237 static void
238 process_map_output (void *cls,
239                     const char *line)
240 {
241   struct GNUNET_NAT_MiniHandle *mini = cls;
242   const char *ipaddr;
243   char *ipa;
244   const char *pstr;
245   unsigned int port;
246
247   if (NULL == line)
248     {
249       GNUNET_OS_command_stop (mini->map_cmd);
250       mini->map_cmd = NULL;
251       if (mini->did_map == GNUNET_YES)
252         mini->refresh_task = GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ,
253                                                            &do_refresh,
254                                                            mini);
255       return;
256     }
257   /*
258     The upnpc output we're after looks like this:
259
260      "external 87.123.42.204:3000 TCP is redirected to internal 192.168.2.150:3000"
261   */
262   if ( (NULL == (ipaddr = strstr (line, " "))) ||
263        (NULL == (pstr = strstr (ipaddr, ":"))) ||
264        (1 != sscanf (pstr + 1, "%u", &port)) )
265     {
266       fprintf (stderr,
267                "Skipping output `%s'\n",
268                line);
269       return; /* skip line */
270     }
271   ipa = GNUNET_strdup (ipaddr + 1);
272   strstr (ipa, ":")[0] = '\0';
273   if (1 != inet_pton (AF_INET,
274                       ipa, 
275                       &mini->current_addr.sin_addr))
276     {
277       GNUNET_free (ipa);
278       fprintf (stderr,
279                "Skipping output `%s'\n",
280                line);
281       return; /* skip line */
282     }
283   GNUNET_free (ipa);          
284
285   mini->current_addr.sin_port = htons (port);
286   mini->current_addr.sin_family = AF_INET;
287 #if HAVE_SOCKADDR_IN_SIN_LEN
288   mini->current_addr.sin_len = sizeof (struct sockaddr_in);
289 #endif
290   mini->did_map = GNUNET_YES;
291   mini->ac (mini->ac_cls, GNUNET_YES,
292             (const struct sockaddr*) &mini->current_addr,
293             sizeof (mini->current_addr));
294 }
295
296
297 /**
298  * Start mapping the given port using (mini)upnpc.  This function
299  * should typically not be used directly (it is used within the
300  * general-purpose 'GNUNET_NAT_register' code).  However, it can be
301  * used if specifically UPnP-based NAT traversal is to be used or
302  * tested.
303  * 
304  * @param port port to map
305  * @param is_tcp GNUNET_YES to map TCP, GNUNET_NO for UDP
306  * @param ac function to call with mapping result
307  * @param ac_cls closure for 'ac'
308  * @return NULL on error
309  */
310 struct GNUNET_NAT_MiniHandle *
311 GNUNET_NAT_mini_map_start (uint16_t port,
312                            int is_tcp,
313                            GNUNET_NAT_AddressCallback ac,
314                            void *ac_cls)
315 {
316   struct GNUNET_NAT_MiniHandle *ret;
317   char pstr[6];
318
319   ret = GNUNET_malloc (sizeof (struct GNUNET_NAT_MiniHandle));
320   ret->ac = ac;
321   ret->ac_cls = ac_cls;
322   ret->is_tcp = is_tcp;
323   ret->port = port;
324   GNUNET_snprintf (pstr, sizeof (pstr),
325                    "%u",
326                    (unsigned int) port);
327   ret->map_cmd = GNUNET_OS_command_run (&process_map_output,
328                                         ret,
329                                         MAP_TIMEOUT,
330                                         "upnpc",
331                                         "upnpc",
332                                         "-r", pstr, 
333                                         is_tcp ? "tcp" : "udp",
334                                         NULL);
335   
336   return ret;
337 }
338
339
340 /**
341  * Process output from our 'unmap' command.
342  *
343  * @param cls the 'struct GNUNET_NAT_MiniHandle'
344  * @param line line of output, NULL at the end
345  */
346 static void
347 process_unmap_output (void *cls,
348                       const char *line)
349 {
350   struct GNUNET_NAT_MiniHandle *mini = cls;
351
352   if (NULL == line)
353     {
354       GNUNET_OS_command_stop (mini->unmap_cmd);
355       mini->unmap_cmd = NULL;
356       GNUNET_free (mini);
357       return;
358     }
359   /* we don't really care about the output... */
360 }
361
362
363 /**
364  * Remove a mapping created with (mini)upnpc.  Calling
365  * this function will give 'upnpc' 1s to remove tha mapping,
366  * so while this function is non-blocking, a task will be
367  * left with the scheduler for up to 1s past this call.
368  * 
369  * @param mini the handle
370  */
371 void
372 GNUNET_NAT_mini_map_stop (struct GNUNET_NAT_MiniHandle *mini)
373 {
374   char pstr[6];
375
376   if (! mini->did_map)
377     {
378       if (mini->map_cmd != NULL)
379         {
380           GNUNET_OS_command_stop (mini->map_cmd);
381           mini->map_cmd = NULL;
382         }
383       GNUNET_free (mini);
384       return;
385     }
386   if (GNUNET_SCHEDULER_NO_TASK != mini->refresh_task)
387     {
388       GNUNET_SCHEDULER_cancel (mini->refresh_task);
389       mini->refresh_task = GNUNET_SCHEDULER_NO_TASK;
390     }
391   if (mini->refresh_cmd != NULL)
392     {
393       GNUNET_OS_command_stop (mini->refresh_cmd);
394       mini->refresh_cmd = NULL;
395     }
396   mini->ac (mini->ac_cls, GNUNET_NO,
397             (const struct sockaddr*) &mini->current_addr,
398             sizeof (mini->current_addr));
399   GNUNET_snprintf (pstr, sizeof (pstr),
400                    "%u",
401                    (unsigned int) mini->port);
402   mini->unmap_cmd = GNUNET_OS_command_run (&process_unmap_output,
403                                            mini,
404                                            UNMAP_TIMEOUT,
405                                            "upnpc",
406                                            "upnpc",
407                                            "-d", pstr, 
408                                            mini->is_tcp ? "tcp" : "udp",
409                                            NULL);
410 }
411
412
413 /* end of nat_mini.c */