-
Notifications
You must be signed in to change notification settings - Fork 0
/
linuxtun.c
106 lines (87 loc) · 2.19 KB
/
linuxtun.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* vim: set tw=78 ts=8 sts=8 noet fileencoding=utf-8: */
#include <linux/if.h>
#include <linux/if_tun.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include "linuxtun.h"
static int tun_alloc(char* const dev, int flags);
int tun_open(struct tundev_t* const dev, int flags) {
if (dev->fd > 0)
return -EALREADY;
dev->fd = tun_alloc(dev->name, flags);
if (dev->fd < 0)
return -errno;
dev->flags = flags;
return 0;
}
int tun_close(struct tundev_t* const dev) {
if (dev->fd <= 0)
return -EALREADY;
int res = close(dev->fd);
if (res < 0)
return -errno;
dev->fd = 0;
dev->name[0] = 0;
return 0;
}
int tun_read(const struct tundev_t* const dev, struct tundev_frame_t*
const frame, size_t max_sz) {
uint8_t buffer[max_sz];
uint8_t* ptr = buffer;
ssize_t len = read(dev->fd, buffer, max_sz);
if (len < sizeof(frame->info)) {
if (errno)
return -errno;
else
return -EPIPE;
}
/* If IFF_NO_PI is set, this header is omitted */
if (!(dev->flags & IFF_NO_PI)) {
/* First four bytes are the packet information */
memcpy(&(frame->info), ptr, sizeof(frame->info));
ptr += sizeof(frame->info);
len -= sizeof(frame->info);
/* Protocol is in big-endian format */
frame->info.proto = ntohs(frame->info.proto);
} else {
frame->info.flags = 0;
frame->info.proto = 0;
}
/* Rest is the packet data */
memcpy(frame->data, ptr, len);
frame->sz = len;
return len;
}
/* Credit: Documentation/networking/tuntap.txt in the Linux kernel sources */
static int tun_alloc(char* const dev, int flags) {
struct ifreq ifr;
int fd, err;
fd = open("/dev/net/tun", O_RDWR);
if (fd < 0)
return fd;
memset(&ifr, 0, sizeof(ifr));
/* Flags: IFF_TUN - TUN device (no Ethernet headers)
* IFF_TAP - TAP device
*
* IFF_NO_PI - Do not provide packet information
*/
ifr.ifr_flags = flags;
if (*dev)
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
err = ioctl(fd, TUNSETIFF, (void *) &ifr);
if (err < 0){
close(fd);
return err;
}
strcpy(dev, ifr.ifr_name);
return fd;
}