-simplify logic, fix double free
[oweals/gnunet.git] / src / vpn / gnunet-helper-vpn.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2010, 2012 Christian Grothoff
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 vpn/gnunet-helper-vpn.c
23  * @brief the helper for the VPN service. Opens a virtual network-interface,
24  * sends data received on the if to stdout, sends data received on stdin to the
25  * interface
26  * @author Philipp Tölke
27  * @author Christian Grothoff
28  *
29  * The following list of people have reviewed this code and considered
30  * it safe since the last modification (if you reviewed it, please
31  * have your name added to the list):
32  *
33  * - Philipp Tölke
34  */
35 #include "platform.h"
36 #include <linux/if_tun.h>
37
38 /**
39  * Need 'struct GNUNET_MessageHeader'.
40  */
41 #include "gnunet_crypto_lib.h"
42 #include "gnunet_common.h"
43
44 /**
45  * Need VPN message types.
46  */
47 #include "gnunet_protocols.h"
48
49 /**
50  * Should we print (interesting|debug) messages that can happen during
51  * normal operation?
52  */
53 #define DEBUG GNUNET_YES
54
55 /**
56  * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
57  */
58 #define MAX_SIZE 65536
59
60 #ifndef _LINUX_IN6_H
61 /**
62  * This is in linux/include/net/ipv6.h, but not always exported...
63  */
64 struct in6_ifreq
65 {
66   struct in6_addr ifr6_addr;
67   uint32_t ifr6_prefixlen;
68   unsigned int ifr6_ifindex;
69 };
70 #endif
71
72
73 /**
74  * Creates a tun-interface called dev;
75  *
76  * @param dev is asumed to point to a char[IFNAMSIZ]
77  *        if *dev == '\\0', uses the name supplied by the kernel;
78  * @return the fd to the tun or -1 on error
79  */
80 static int
81 init_tun (char *dev)
82 {
83   struct ifreq ifr;
84   int fd;
85
86   if (NULL == dev)
87   {
88     errno = EINVAL;
89     return -1;
90   }
91
92   if (-1 == (fd = open ("/dev/net/tun", O_RDWR)))
93   {
94     fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun",
95              strerror (errno));
96     return -1;
97   }
98
99   if (fd >= FD_SETSIZE)
100   {
101     fprintf (stderr, "File descriptor to large: %d", fd);
102     (void) close (fd);
103     return -1;
104   }
105
106   memset (&ifr, 0, sizeof (ifr));
107   ifr.ifr_flags = IFF_TUN;
108
109   if ('\0' != *dev)
110     strncpy (ifr.ifr_name, dev, IFNAMSIZ);
111
112   if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr))
113   {
114     fprintf (stderr,
115              "Error with ioctl on `%s': %s\n",
116              "/dev/net/tun",
117              strerror (errno));
118     (void) close (fd);
119     return -1;
120   }
121   strcpy (dev, ifr.ifr_name);
122   return fd;
123 }
124
125
126 /**
127  * @brief Sets the IPv6-Address given in address on the interface dev
128  *
129  * @param dev the interface to configure
130  * @param address the IPv6-Address
131  * @param prefix_len the length of the network-prefix
132  */
133 static void
134 set_address6 (const char *dev, const char *address, unsigned long prefix_len)
135 {
136   struct ifreq ifr;
137   struct in6_ifreq ifr6;
138   struct sockaddr_in6 sa6;
139   int fd;
140
141   /*
142    * parse the new address
143    */
144   memset (&sa6, 0, sizeof (struct sockaddr_in6));
145   sa6.sin6_family = AF_INET6;
146   if (1 != inet_pton (AF_INET6, address, sa6.sin6_addr.s6_addr))
147   {
148     fprintf (stderr,
149              "Failed to parse IPv6 address `%s'\n",
150              address);
151     exit (1);
152   }
153
154   if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0)))
155   {
156     fprintf (stderr,
157              "Error creating socket: %s\n",
158              strerror (errno));
159     exit (1);
160   }
161
162   memset (&ifr, 0, sizeof (struct ifreq));
163   /*
164    * Get the index of the if
165    */
166   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
167   if (-1 == ioctl (fd, SIOGIFINDEX, &ifr))
168   {
169     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
170     (void) close (fd);
171     exit (1);
172   }
173
174   memset (&ifr6, 0, sizeof (struct in6_ifreq));
175   ifr6.ifr6_addr = sa6.sin6_addr;
176   ifr6.ifr6_ifindex = ifr.ifr_ifindex;
177   ifr6.ifr6_prefixlen = prefix_len;
178
179   /*
180    * Set the address
181    */
182   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6))
183   {
184     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
185              strerror (errno));
186     (void) close (fd);
187     exit (1);
188   }
189
190   /*
191    * Get the flags
192    */
193   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
194   {
195     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
196              strerror (errno));
197     (void) close (fd);
198     exit (1);
199   }
200
201   /*
202    * Add the UP and RUNNING flags
203    */
204   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
205   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
206   {
207     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
208              strerror (errno));
209     (void) close (fd);
210     exit (1);
211   }
212
213   if (0 != close (fd))
214   {
215     fprintf (stderr, "close failed: %s\n", strerror (errno));
216     exit (1);
217   }
218 }
219
220
221 /**
222  * @brief Sets the IPv4-Address given in address on the interface dev
223  *
224  * @param dev the interface to configure
225  * @param address the IPv4-Address
226  * @param mask the netmask
227  */
228 static void
229 set_address4 (const char *dev, const char *address, const char *mask)
230 {
231   int fd;
232   struct sockaddr_in *addr;
233   struct ifreq ifr;
234
235   memset (&ifr, 0, sizeof (struct ifreq));
236   addr = (struct sockaddr_in *) &(ifr.ifr_addr);
237   addr->sin_family = AF_INET;
238
239   /*
240    * Parse the address
241    */
242   if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr))
243   {
244     fprintf (stderr,
245              "Failed to parse IPv4 address `%s'\n",
246              address);
247     exit (1);
248   }
249
250   if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0)))
251   {
252     fprintf (stderr,
253              "Error creating socket: %s\n",
254              strerror (errno));
255     exit (1);
256   }
257
258   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
259
260   /*
261    * Set the address
262    */
263   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr))
264   {
265     fprintf (stderr,
266              "ioctl failed at %d: %s\n",
267              __LINE__,
268              strerror (errno));
269     (void) close (fd);
270     exit (1);
271   }
272
273   /*
274    * Parse the netmask
275    */
276   addr = (struct sockaddr_in *) &(ifr.ifr_netmask);
277   if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr))
278   {
279     fprintf (stderr,
280              "Failed to parse IPv4 address mask `%s'\n",
281              mask);
282     (void) close (fd);
283     exit (1);
284   }
285
286   /*
287    * Set the netmask
288    */
289   if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr))
290   {
291     fprintf (stderr,
292              "ioctl failed at line %d: %s\n",
293              __LINE__,
294              strerror (errno));
295     (void) close (fd);
296     exit (1);
297   }
298
299   /*
300    * Get the flags
301    */
302   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
303   {
304     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
305              strerror (errno));
306     (void) close (fd);
307     exit (1);
308   }
309
310   /*
311    * Add the UP and RUNNING flags
312    */
313   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
314   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
315   {
316     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
317              strerror (errno));
318     (void) close (fd);
319     exit (1);
320   }
321
322   if (0 != close (fd))
323   {
324     fprintf (stderr, "close failed: %s\n", strerror (errno));
325     (void) close (fd);
326     exit (1);
327   }
328 }
329
330
331 /**
332  * Start forwarding to and from the tunnel.
333  *
334  * @param fd_tun tunnel FD
335  */
336 static void
337 run (int fd_tun)
338 {
339   /*
340    * The buffer filled by reading from fd_tun
341    */
342   unsigned char buftun[MAX_SIZE];
343   ssize_t buftun_size = 0;
344   unsigned char *buftun_read = NULL;
345
346   /*
347    * The buffer filled by reading from stdin
348    */
349   unsigned char bufin[MAX_SIZE];
350   ssize_t bufin_size = 0;
351   size_t bufin_rpos = 0;
352   unsigned char *bufin_read = NULL;
353
354   fd_set fds_w;
355   fd_set fds_r;
356
357   /* read refers to reading from fd_tun, writing to stdout */
358   int read_open = 1;
359
360   /* write refers to reading from stdin, writing to fd_tun */
361   int write_open = 1;
362
363   /* FIXME: this should work with '&&', but then 2/5 VPN
364      tests fail. With '||' the tests pass, but this process
365      keeps running --- but only for the 'GNS' test ---
366      even though the stdout is closed :-(. Very confusing. */
367   while ((1 == read_open) && (1 == write_open))
368   {
369     FD_ZERO (&fds_w);
370     FD_ZERO (&fds_r);
371
372     /*
373      * We are supposed to read and the buffer is empty
374      * -> select on read from tun
375      */
376     if (read_open && (0 == buftun_size))
377       FD_SET (fd_tun, &fds_r);
378
379     /*
380      * We are supposed to read and the buffer is not empty
381      * -> select on write to stdout
382      */
383     if (read_open && (0 != buftun_size))
384       FD_SET (1, &fds_w);
385
386     /*
387      * We are supposed to write and the buffer is empty
388      * -> select on read from stdin
389      */
390     if (write_open && (NULL == bufin_read))
391       FD_SET (0, &fds_r);
392
393     /*
394      * We are supposed to write and the buffer is not empty
395      * -> select on write to tun
396      */
397     if (write_open && (NULL != bufin_read))
398       FD_SET (fd_tun, &fds_w);
399
400     int r = select (fd_tun + 1, &fds_r, &fds_w, NULL, NULL);
401
402     if (-1 == r)
403     {
404       if (EINTR == errno)
405         continue;
406       fprintf (stderr, "select failed: %s\n", strerror (errno));
407       exit (1);
408     }
409
410     if (r > 0)
411     {
412       if (FD_ISSET (fd_tun, &fds_r))
413       {
414         buftun_size =
415             read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader),
416                   MAX_SIZE - sizeof (struct GNUNET_MessageHeader));
417         if (-1 == buftun_size)
418         {
419           fprintf (stderr,
420                    "read-error: %s\n",
421                    strerror (errno));
422           shutdown (fd_tun, SHUT_RD);
423           shutdown (1, SHUT_WR);
424           read_open = 0;
425           buftun_size = 0;
426         }
427         else if (0 == buftun_size)
428         {
429           fprintf (stderr, "EOF on tun\n");
430           shutdown (fd_tun, SHUT_RD);
431           shutdown (1, SHUT_WR);
432           read_open = 0;
433           buftun_size = 0;
434         }
435         else
436         {
437           buftun_read = buftun;
438           struct GNUNET_MessageHeader *hdr =
439               (struct GNUNET_MessageHeader *) buftun;
440           buftun_size += sizeof (struct GNUNET_MessageHeader);
441           hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
442           hdr->size = htons (buftun_size);
443         }
444       }
445       else if (FD_ISSET (1, &fds_w))
446       {
447         ssize_t written = write (1, buftun_read, buftun_size);
448
449         if (-1 == written)
450         {
451 #if !DEBUG
452           if (errno != EPIPE)
453 #endif
454             fprintf (stderr,
455                      "write-error to stdout: %s\n",
456                      strerror (errno));
457           shutdown (fd_tun, SHUT_RD);
458           shutdown (1, SHUT_WR);
459           read_open = 0;
460           buftun_size = 0;
461         }
462         else if (0 == written)
463         {
464           fprintf (stderr, "write returned 0!?\n");
465           exit (1);
466         }
467         else
468         {
469           buftun_size -= written;
470           buftun_read += written;
471         }
472       }
473
474       if (FD_ISSET (0, &fds_r))
475       {
476         bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos);
477         if (-1 == bufin_size)
478         {
479           fprintf (stderr,
480                    "read-error: %s\n",
481                    strerror (errno));
482           shutdown (0, SHUT_RD);
483           shutdown (fd_tun, SHUT_WR);
484           write_open = 0;
485           bufin_size = 0;
486         }
487         else if (0 == bufin_size)
488         {
489 #if DEBUG
490           fprintf (stderr, "EOF on stdin\n");
491 #endif
492           shutdown (0, SHUT_RD);
493           shutdown (fd_tun, SHUT_WR);
494           write_open = 0;
495           bufin_size = 0;
496         }
497         else
498         {
499           struct GNUNET_MessageHeader *hdr;
500
501 PROCESS_BUFFER:
502           bufin_rpos += bufin_size;
503           if (bufin_rpos < sizeof (struct GNUNET_MessageHeader))
504             continue;
505           hdr = (struct GNUNET_MessageHeader *) bufin;
506           if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER)
507           {
508             fprintf (stderr, "protocol violation!\n");
509             exit (1);
510           }
511           if (ntohs (hdr->size) > bufin_rpos)
512             continue;
513           bufin_read = bufin + sizeof (struct GNUNET_MessageHeader);
514           bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader);
515           bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader);
516         }
517       }
518       else if (FD_ISSET (fd_tun, &fds_w))
519       {
520         ssize_t written = write (fd_tun, bufin_read, bufin_size);
521
522         if (-1 == written)
523         {
524           fprintf (stderr, "write-error to tun: %s\n", strerror (errno));
525           shutdown (0, SHUT_RD);
526           shutdown (fd_tun, SHUT_WR);
527           write_open = 0;
528           bufin_size = 0;
529         }
530         else if (0 == written)
531         {
532           fprintf (stderr, "write returned 0!?\n");
533           exit (1);
534         }
535         else
536         {
537           bufin_size -= written;
538           bufin_read += written;
539           if (0 == bufin_size)
540           {
541             memmove (bufin, bufin_read, bufin_rpos);
542             bufin_read = NULL;  /* start reading again */
543             bufin_size = 0;
544             goto PROCESS_BUFFER;
545           }
546         }
547       }
548     }
549   }
550   fprintf (stderr, "Existing select() loop\n");
551 }
552
553
554 /**
555  * Open VPN tunnel interface.
556  *
557  * @param argc must be 6
558  * @param argv 0: binary name (gnunet-helper-vpn)
559  *             1: tunnel interface name (gnunet-vpn)
560  *             2: IPv6 address (::1), "-" to disable
561  *             3: IPv6 netmask length in bits (64), ignored if #2 is "-"
562  *             4: IPv4 address (1.2.3.4), "-" to disable
563  *             5: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
564  */
565 int
566 main (int argc, char **argv)
567 {
568   char dev[IFNAMSIZ];
569   int fd_tun;
570   int global_ret;
571
572   fprintf (stderr,
573            "VPN helper running!\n");
574   if (6 != argc)
575   {
576     fprintf (stderr, "Fatal: must supply 5 arguments!\n");
577     return 1;
578   }
579
580   strncpy (dev, argv[1], IFNAMSIZ);
581   dev[IFNAMSIZ - 1] = '\0';
582
583   if (-1 == (fd_tun = init_tun (dev)))
584   {
585     fprintf (stderr, "Fatal: could not initialize tun-interface `%s'  with IPv6 %s/%s and IPv4 %s/%s\n",
586              dev,
587              argv[2],
588              argv[3],
589              argv[4],
590              argv[5]);
591     return 1;
592   }
593
594   if (0 != strcmp (argv[2], "-"))
595   {
596     const char *address = argv[2];
597     long prefix_len = atol (argv[3]);
598
599     if ((prefix_len < 1) || (prefix_len > 127))
600     {
601       fprintf (stderr, "Fatal: prefix_len out of range\n");
602       return 1;
603     }
604
605     set_address6 (dev, address, prefix_len);
606   }
607
608   if (0 != strcmp (argv[4], "-"))
609   {
610     const char *address = argv[4];
611     const char *mask = argv[5];
612
613     set_address4 (dev, address, mask);
614   }
615
616   uid_t uid = getuid ();
617 #ifdef HAVE_SETRESUID
618   if (0 != setresuid (uid, uid, uid))
619   {
620     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
621     global_ret = 2;
622     goto cleanup;
623   }
624 #else
625   if (0 != (setuid (uid) | seteuid (uid)))
626   {
627     fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
628     global_ret = 2;
629     goto cleanup;
630   }
631 #endif
632
633   if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
634   {
635     fprintf (stderr, "Failed to protect against SIGPIPE: %s\n",
636              strerror (errno));
637     /* no exit, we might as well die with SIGPIPE should it ever happen */
638   }
639   run (fd_tun);
640   global_ret = 0;
641  cleanup:
642   close (fd_tun);
643   return global_ret;
644 }