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