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