vpn: cleanup of the code
[oweals/gnunet.git] / src / vpn / tun.c
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <sys/ioctl.h>
4 #include <sys/stat.h>
5
6 #include <linux/if.h>
7 #include <linux/if_tun.h>
8
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <stdlib.h>
15
16 #include "debug.h"
17
18 /**
19  * Creates a tun-interface called dev;
20  * if *dev == 0, uses the name supplied by the kernel
21  * returns the fd to the tun or -1
22  */
23 int init_tun(char *dev) { /*{{{*/
24         struct ifreq ifr;
25         int fd, err;
26
27         if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
28                 debug(1, 0, "opening /dev/net/tun: %s\n", strerror(errno));
29                 return -1;
30         }
31
32         memset(&ifr, 0, sizeof(ifr));
33
34         ifr.ifr_flags = IFF_TUN; 
35         if(dev)
36                 strncpy(ifr.ifr_name, dev, IFNAMSIZ);
37
38         if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
39                 close(fd);
40                 debug(1, 0, "ioctl'ing /dev/net/tun: %s\n", strerror(errno));
41                 return err;
42         }
43         strcpy(dev, ifr.ifr_name);
44         return fd;
45 } /*}}}*/
46
47 void n2o(int fd) {
48         char buf[1024];
49         int r, w;
50         for(;;) {
51                 r = read(fd, buf, 1024);
52                 if (r < 0) {
53                         fprintf(stderr, "n2o read: %s\n", strerror(errno));
54                         exit(1);
55                 }
56                 if (r == 0) {
57                         close(fd);
58                         exit(0);
59                 }
60                 while (r > 0) {
61                         w = write(1, buf, r);
62                         if (w < 0) {
63                                 fprintf(stderr, "n2o write: %s\n", strerror(errno));
64                                 close(fd);
65                                 exit(1);
66                         }
67                         r -= w;
68                 }
69         }
70 }
71
72 void o2n(int fd) {
73         char buf[1024];
74         int r, w;
75         for(;;) {
76                 r = read(0, buf, 1024);
77                 if (r < 0) {
78                         fprintf(stderr, "o2n read: %s\n", strerror(errno));
79                         exit(1);
80                 }
81                 if (r == 0) {
82                         close(fd);
83                         exit(0);
84                 }
85                 while (r > 0) {
86                         w = write(fd, buf, r);
87                         if (w < 0) {
88                                 fprintf(stderr, "o2n write: %s\n", strerror(errno));
89                                 close(fd);
90                                 exit(1);
91                         }
92                         r -= w;
93                 }
94         }
95 }