- fixing compile error
[oweals/gnunet.git] / src / exit / gnunet-helper-exit.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010, 2011, 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 exit/gnunet-helper-exit.c 
23  *
24  * @brief the helper for exit nodes. Opens a virtual
25  * network-interface, sends data received on the if to stdout, sends
26  * data received on stdin to the interface.  The code also enables
27  * IPv4/IPv6 forwarding and NAT on the current system (the latter on
28  * an interface specified on the command-line); these changes to the
29  * network configuration are NOT automatically undone when the program
30  * is stopped (this is because we cannot be sure that some other
31  * application didn't enable them before or after us; also, these
32  * changes should be mostly harmless as it simply turns the system
33  * into a router).
34  *
35  * @author Philipp Tölke
36  * @author Christian Grothoff
37  *
38  * The following list of people have reviewed this code and considered
39  * it safe since the last modification (if you reviewed it, please
40  * have your name added to the list):
41  *
42  * - Philipp Tölke
43  */
44 #include "platform.h"
45 #include <linux/if_tun.h>
46
47 /**
48  * Need 'struct GNUNET_MessageHeader'.
49  */
50 #include "gnunet_common.h"
51
52 /**
53  * Need VPN message types.
54  */
55 #include "gnunet_protocols.h"
56
57 /**
58  * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
59  */
60 #define MAX_SIZE 65536
61
62 /**
63  * Path to 'sysctl' binary.
64  */
65 static const char *sbin_sysctl;
66
67 /**
68  * Path to 'iptables' binary.
69  */
70 static const char *sbin_iptables;
71
72
73 #ifndef _LINUX_IN6_H
74 /**
75  * This is in linux/include/net/ipv6.h, but not always exported...
76  */
77 struct in6_ifreq
78 {
79   struct in6_addr ifr6_addr;
80   uint32_t ifr6_prefixlen;
81   unsigned int ifr6_ifindex;
82 };
83 #endif
84
85
86
87 /**
88  * Run the given command and wait for it to complete.
89  * 
90  * @param file name of the binary to run
91  * @param cmd command line arguments (as given to 'execv')
92  * @return 0 on success, 1 on any error
93  */
94 static int
95 fork_and_exec (const char *file, 
96                char *const cmd[])
97 {
98   int status;
99   pid_t pid;
100   pid_t ret;
101
102   pid = fork ();
103   if (-1 == pid)
104   {
105     fprintf (stderr, 
106              "fork failed: %s\n", 
107              strerror (errno));
108     return 1;
109   }
110   if (0 == pid)
111   {
112     /* we are the child process */
113     /* close stdin/stdout to not cause interference
114        with the helper's main protocol! */
115     (void) close (0); 
116     (void) close (1); 
117     (void) execv (file, cmd);
118     /* can only get here on error */
119     fprintf (stderr, 
120              "exec `%s' failed: %s\n", 
121              file,
122              strerror (errno));
123     _exit (1);
124   }
125   /* keep running waitpid as long as the only error we get is 'EINTR' */
126   while ( (-1 == (ret = waitpid (pid, &status, 0))) &&
127           (errno == EINTR) ); 
128   if (-1 == ret)
129   {
130     fprintf (stderr, 
131              "waitpid failed: %s\n", 
132              strerror (errno));
133     return 1;
134   }
135   if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status))))
136     return 1;
137   /* child process completed and returned success, we're happy */
138   return 0;
139 }
140
141
142 /**
143  * Creates a tun-interface called dev;
144  *
145  * @param dev is asumed to point to a char[IFNAMSIZ]
146  *        if *dev == '\\0', uses the name supplied by the kernel;
147  * @return the fd to the tun or -1 on error
148  */
149 static int
150 init_tun (char *dev)
151 {
152   struct ifreq ifr;
153   int fd;
154
155   if (NULL == dev)
156   {
157     errno = EINVAL;
158     return -1;
159   }
160
161   if (-1 == (fd = open ("/dev/net/tun", O_RDWR)))
162   {
163     fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun",
164              strerror (errno));
165     return -1;
166   }
167
168   if (fd >= FD_SETSIZE)
169   {
170     fprintf (stderr, "File descriptor to large: %d", fd);
171     return -1;
172   }
173
174   memset (&ifr, 0, sizeof (ifr));
175   ifr.ifr_flags = IFF_TUN;
176
177   if ('\0' != *dev)
178     strncpy (ifr.ifr_name, dev, IFNAMSIZ);
179
180   if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr))
181   {
182     fprintf (stderr, "Error with ioctl on `%s': %s\n", "/dev/net/tun",
183              strerror (errno));
184     (void) close (fd);
185     return -1;
186   }
187   strcpy (dev, ifr.ifr_name);
188   return fd;
189 }
190
191
192 /**
193  * @brief Sets the IPv6-Address given in address on the interface dev
194  *
195  * @param dev the interface to configure
196  * @param address the IPv6-Address
197  * @param prefix_len the length of the network-prefix
198  */
199 static void
200 set_address6 (const char *dev, const char *address, unsigned long prefix_len)
201 {
202   struct ifreq ifr;
203   struct in6_ifreq ifr6;
204   struct sockaddr_in6 sa6;
205   int fd;
206
207   /*
208    * parse the new address
209    */
210   memset (&sa6, 0, sizeof (struct sockaddr_in6));
211   sa6.sin6_family = AF_INET6;
212   if (1 != inet_pton (AF_INET6, address, sa6.sin6_addr.s6_addr))
213   {
214     fprintf (stderr, "Failed to parse address `%s': %s\n", address,
215              strerror (errno));
216     exit (1);
217   }
218
219   if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0)))
220   {
221     fprintf (stderr, "Error creating socket: %s\n", strerror (errno));
222     exit (1);
223   }
224
225   memset (&ifr, 0, sizeof (struct ifreq));
226   /*
227    * Get the index of the if
228    */
229   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
230   if (-1 == ioctl (fd, SIOGIFINDEX, &ifr))
231   {
232     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
233     (void) close (fd);
234     exit (1);
235   }
236
237   memset (&ifr6, 0, sizeof (struct in6_ifreq));
238   ifr6.ifr6_addr = sa6.sin6_addr;
239   ifr6.ifr6_ifindex = ifr.ifr_ifindex;
240   ifr6.ifr6_prefixlen = prefix_len;
241
242   /*
243    * Set the address
244    */
245   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6))
246   {
247     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
248              strerror (errno));
249     (void) close (fd);
250     exit (1);
251   }
252
253   /*
254    * Get the flags
255    */
256   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
257   {
258     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
259              strerror (errno));
260     (void) close (fd);
261     exit (1);
262   }
263
264   /*
265    * Add the UP and RUNNING flags
266    */
267   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
268   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
269   {
270     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
271              strerror (errno));
272     (void) close (fd);
273     exit (1);
274   }
275
276   if (0 != close (fd))
277   {
278     fprintf (stderr, "close failed: %s\n", strerror (errno));
279     exit (1);
280   }
281 }
282
283
284 /**
285  * @brief Sets the IPv4-Address given in address on the interface dev
286  *
287  * @param dev the interface to configure
288  * @param address the IPv4-Address
289  * @param mask the netmask
290  */
291 static void
292 set_address4 (const char *dev, const char *address, const char *mask)
293 {
294   int fd;
295   struct sockaddr_in *addr;
296   struct ifreq ifr;
297
298   memset (&ifr, 0, sizeof (struct ifreq));
299   addr = (struct sockaddr_in *) &(ifr.ifr_addr);
300   addr->sin_family = AF_INET;
301
302   /*
303    * Parse the address
304    */
305   if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr))
306   {
307     fprintf (stderr, "Failed to parse address `%s': %s\n", address,
308              strerror (errno));
309     exit (1);
310   }
311
312   if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0)))
313   {
314     fprintf (stderr, "Error creating socket: %s\n", strerror (errno));
315     exit (1);
316   }
317
318   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
319
320   /*
321    * Set the address
322    */
323   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr))
324   {
325     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
326     (void) close (fd);
327     exit (1);
328   }
329
330   /*
331    * Parse the netmask
332    */
333   addr = (struct sockaddr_in *) &(ifr.ifr_netmask);
334   if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr))
335   {
336     fprintf (stderr, "Failed to parse address `%s': %s\n", mask,
337              strerror (errno));
338     (void) close (fd);
339     exit (1);
340   }
341
342   /*
343    * Set the netmask
344    */
345   if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr))
346   {
347     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
348              strerror (errno));
349     (void) close (fd);
350     exit (1);
351   }
352
353   /*
354    * Get the flags
355    */
356   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
357   {
358     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
359              strerror (errno));
360     (void) close (fd);
361     exit (1);
362   }
363
364   /*
365    * Add the UP and RUNNING flags
366    */
367   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
368   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
369   {
370     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
371              strerror (errno));
372     (void) close (fd);
373     exit (1);
374   }
375
376   if (0 != close (fd))
377   {
378     fprintf (stderr, "close failed: %s\n", strerror (errno));
379     (void) close (fd);
380     exit (1);
381   }
382 }
383
384
385 /**
386  * Start forwarding to and from the tunnel.
387  *
388  * @param fd_tun tunnel FD
389  */
390 static void
391 run (int fd_tun)
392 {
393   /*
394    * The buffer filled by reading from fd_tun
395    */
396   unsigned char buftun[MAX_SIZE];
397   ssize_t buftun_size = 0;
398   unsigned char *buftun_read = NULL;
399
400   /*
401    * The buffer filled by reading from stdin
402    */
403   unsigned char bufin[MAX_SIZE];
404   ssize_t bufin_size = 0;
405   size_t bufin_rpos = 0;
406   unsigned char *bufin_read = NULL;
407
408   fd_set fds_w;
409   fd_set fds_r;
410
411   /* read refers to reading from fd_tun, writing to stdout */
412   int read_open = 1;
413
414   /* write refers to reading from stdin, writing to fd_tun */
415   int write_open = 1;
416
417   while ((1 == read_open) || (1 == write_open))
418   {
419     FD_ZERO (&fds_w);
420     FD_ZERO (&fds_r);
421
422     /*
423      * We are supposed to read and the buffer is empty
424      * -> select on read from tun
425      */
426     if (read_open && (0 == buftun_size))
427       FD_SET (fd_tun, &fds_r);
428
429     /*
430      * We are supposed to read and the buffer is not empty
431      * -> select on write to stdout
432      */
433     if (read_open && (0 != buftun_size))
434       FD_SET (1, &fds_w);
435
436     /*
437      * We are supposed to write and the buffer is empty
438      * -> select on read from stdin
439      */
440     if (write_open && (NULL == bufin_read))
441       FD_SET (0, &fds_r);
442
443     /*
444      * We are supposed to write and the buffer is not empty
445      * -> select on write to tun
446      */
447     if (write_open && (NULL != bufin_read))
448       FD_SET (fd_tun, &fds_w);
449
450     int r = select (fd_tun + 1, &fds_r, &fds_w, NULL, NULL);
451
452     if (-1 == r)
453     {
454       if (EINTR == errno)
455         continue;
456       fprintf (stderr, "select failed: %s\n", strerror (errno));
457       exit (1);
458     }
459
460     if (r > 0)
461     {
462       if (FD_ISSET (fd_tun, &fds_r))
463       {
464         buftun_size =
465             read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader),
466                   MAX_SIZE - sizeof (struct GNUNET_MessageHeader));
467         if (-1 == buftun_size)
468         {
469           fprintf (stderr, "read-error: %s\n", strerror (errno));
470           shutdown (fd_tun, SHUT_RD);
471           shutdown (1, SHUT_WR);
472           read_open = 0;
473           buftun_size = 0;
474         }
475         else if (0 == buftun_size)
476         {
477           fprintf (stderr, "EOF on tun\n");
478           shutdown (fd_tun, SHUT_RD);
479           shutdown (1, SHUT_WR);
480           read_open = 0;
481           buftun_size = 0;
482         }
483         else
484         {
485           buftun_read = buftun;
486           struct GNUNET_MessageHeader *hdr =
487               (struct GNUNET_MessageHeader *) buftun;
488           buftun_size += sizeof (struct GNUNET_MessageHeader);
489           hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
490           hdr->size = htons (buftun_size);
491         }
492       }
493       else if (FD_ISSET (1, &fds_w))
494       {
495         ssize_t written = write (1, buftun_read, buftun_size);
496
497         if (-1 == written)
498         {
499           fprintf (stderr, "write-error to stdout: %s\n", strerror (errno));
500           shutdown (fd_tun, SHUT_RD);
501           shutdown (1, SHUT_WR);
502           read_open = 0;
503           buftun_size = 0;
504         }
505         else if (0 == written)
506         {
507           fprintf (stderr, "write returned 0!?\n");
508           exit (1);
509         }
510         else
511         {
512           buftun_size -= written;
513           buftun_read += written;
514         }
515       }
516
517       if (FD_ISSET (0, &fds_r))
518       {
519         bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos);
520         if (-1 == bufin_size)
521         {
522           fprintf (stderr, "read-error: %s\n", strerror (errno));
523           shutdown (0, SHUT_RD);
524           shutdown (fd_tun, SHUT_WR);
525           write_open = 0;
526           bufin_size = 0;
527         }
528         else if (0 == bufin_size)
529         {
530           fprintf (stderr, "EOF on stdin\n");
531           shutdown (0, SHUT_RD);
532           shutdown (fd_tun, SHUT_WR);
533           write_open = 0;
534           bufin_size = 0;
535         }
536         else
537         {
538           struct GNUNET_MessageHeader *hdr;
539
540 PROCESS_BUFFER:
541           bufin_rpos += bufin_size;
542           if (bufin_rpos < sizeof (struct GNUNET_MessageHeader))
543             continue;
544           hdr = (struct GNUNET_MessageHeader *) bufin;
545           if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER)
546           {
547             fprintf (stderr, "protocol violation!\n");
548             exit (1);
549           }
550           if (ntohs (hdr->size) > bufin_rpos)
551             continue;
552           bufin_read = bufin + sizeof (struct GNUNET_MessageHeader);
553           bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader);
554           bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader);
555         }
556       }
557       else if (FD_ISSET (fd_tun, &fds_w))
558       {
559         ssize_t written = write (fd_tun, bufin_read, bufin_size);
560
561         if (-1 == written)
562         {
563           fprintf (stderr, "write-error to tun: %s\n", strerror (errno));
564           shutdown (0, SHUT_RD);
565           shutdown (fd_tun, SHUT_WR);
566           write_open = 0;
567           bufin_size = 0;
568         }
569         else if (0 == written)
570         {
571           fprintf (stderr, "write returned 0!?\n");
572           exit (1);
573         }
574         else
575         {
576           bufin_size -= written;
577           bufin_read += written;
578           if (0 == bufin_size)
579           {
580             memmove (bufin, bufin_read, bufin_rpos);
581             bufin_read = NULL;  /* start reading again */
582             bufin_size = 0;
583             goto PROCESS_BUFFER;
584           }
585         }
586       }
587     }
588   }
589 }
590
591
592 /**
593  * Open VPN tunnel interface.
594  *
595  * @param argc must be 6
596  * @param argv 0: binary name ("gnunet-helper-vpn")
597  *             1: tunnel interface name ("gnunet-vpn")
598  *             2: IPv4 "physical" interface name ("eth0"), or "%" to not do IPv4 NAT
599  *             3: IPv6 address ("::1"), or "-" to skip IPv6
600  *             4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
601  *             5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
602  *             6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
603  */
604 int
605 main (int argc, char **argv)
606 {
607   char dev[IFNAMSIZ];
608   int fd_tun;
609   int global_ret;
610
611   if (7 != argc)
612   {
613     fprintf (stderr, "Fatal: must supply 5 arguments!\n");
614     return 1;
615   }
616   if ( (0 == strcmp (argv[3], "-")) &&
617        (0 == strcmp (argv[5], "-")) )
618   {
619     fprintf (stderr, "Fatal: disabling both IPv4 and IPv6 makes no sense.\n");
620     return 1;
621   }
622   if (0 == access ("/sbin/iptables", X_OK))
623     sbin_iptables = "/sbin/iptables";
624   else if (0 == access ("/usr/sbin/iptables", X_OK))
625     sbin_iptables = "/usr/sbin/iptables";
626   else
627   {
628     fprintf (stderr, 
629              "Fatal: executable iptables not found in approved directories: %s\n",
630              strerror (errno));
631     return 1;
632   }
633   if (0 == access ("/sbin/sysctl", X_OK))
634     sbin_sysctl = "/sbin/sysctl";
635   else if (0 == access ("/usr/sbin/sysctl", X_OK))
636     sbin_sysctl = "/usr/sbin/sysctl";
637   else
638   {
639     fprintf (stderr,
640              "Fatal: executable sysctl not found in approved directories: %s\n",
641              strerror (errno));
642     return 1;
643   }
644
645   strncpy (dev, argv[1], IFNAMSIZ);
646   dev[IFNAMSIZ - 1] = '\0';
647
648   if (-1 == (fd_tun = init_tun (dev)))
649   {
650     fprintf (stderr, "Fatal: could not initialize tun-interface\n");
651     return 1;
652   }
653
654   if (0 != strcmp (argv[3], "-"))
655   {
656     {
657       const char *address = argv[3];
658       long prefix_len = atol (argv[4]);
659       
660       if ((prefix_len < 1) || (prefix_len > 127))
661       {
662         fprintf (stderr, "Fatal: prefix_len out of range\n");
663         return 1;
664       }      
665       set_address6 (dev, address, prefix_len);    
666     }
667     {
668       char *const sysctl_args[] =
669         {
670           "sysctl", "-w", "net.ipv6.conf.all.forwarding=1", NULL
671         };
672       if (0 != fork_and_exec (sbin_sysctl,
673                               sysctl_args))
674       {
675         fprintf (stderr,
676                  "Failed to enable IPv6 forwarding.  Will continue anyway.\n");
677       }    
678     }
679   }
680
681   if (0 != strcmp (argv[5], "-"))
682   {
683     {
684       const char *address = argv[5];
685       const char *mask = argv[6];
686       
687       set_address4 (dev, address, mask);
688     }
689     {
690       char *const sysctl_args[] =
691         {
692           "sysctl", "-w", "net.ipv4.ip_forward=1", NULL
693         };
694       if (0 != fork_and_exec (sbin_sysctl,
695                               sysctl_args))
696       {
697         fprintf (stderr,
698                  "Failed to enable IPv4 forwarding.  Will continue anyway.\n");
699       }    
700     }
701     if (0 != strcmp (argv[2], "%"))
702     {
703       char *const iptables_args[] =
704         {
705           "iptables", "-t", "nat", "-A", "POSTROUTING", "-o", argv[2], "-j", "MASQUERADE", NULL
706         };
707       if (0 != fork_and_exec (sbin_iptables,
708                               iptables_args))
709       {
710         fprintf (stderr,
711                  "Failed to enable IPv4 masquerading (NAT).  Will continue anyway.\n");
712       }    
713     }
714   }
715   
716   uid_t uid = getuid ();
717 #ifdef HAVE_SETRESUID
718   if (0 != setresuid (uid, uid, uid))
719   {
720     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
721     global_ret = 2;
722     goto cleanup;
723   }
724 #else
725   if (0 != (setuid (uid) | seteuid (uid)))
726   {
727     fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
728     global_ret = 2;
729     goto cleanup;
730   }
731 #endif
732
733   if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
734   {
735     fprintf (stderr, "Failed to protect against SIGPIPE: %s\n",
736              strerror (errno));
737     /* no exit, we might as well die with SIGPIPE should it ever happen */
738   }
739   run (fd_tun);
740   global_ret = 0;
741  cleanup:
742   close (fd_tun);
743   return global_ret;
744 }
745
746 /* end of gnunet-helper-exit.c */