-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtunw.c
98 lines (75 loc) · 1.93 KB
/
tunw.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
/* Wrap around TUN/TAP functionalities.
*
* Copyright (c) 2016 Kewin Rausch <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors and changes:
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <net/if.h>
#include <linux/if_tun.h>
#include "tunw.h"
#define TUN_PATH "/dev/net/tun"
int tun_async_io(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if(flags < 0) {
return flags;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
int tun_close(int fd) {
return close(fd);
}
int tun_create(char * name, int type, int persistent) {
int fd = 0;
int err = 0;
struct ifreq i = {0};
if(type == TUNW_MODE_TAP) {
printf("TAP not supported yet.\n");
return -1;
}
if(persistent) {
printf("Creation of persistent device not supported yet.\n");
return -1;
}
fd = open(TUN_PATH, O_RDWR);
if(fd < 0) {
return -1;
}
/* We go stright for a TUN at the moment. */
i.ifr_flags = IFF_TUN;
if(strlen(name) != 0) {
strncpy(i.ifr_name, name, IFNAMSIZ);
}
err = ioctl(fd, TUNSETIFF, (void *)&i);
if(err < 0) {
close(fd);
return -1;
}
/* Get the name assigned by the kernel. */
strncpy(name, i.ifr_name, IFNAMSIZ);
return fd;
}
int tun_read(int fd, char * buf, int size) {
return read(fd, buf, size);
}
int tun_write(int fd, char * buf, int size) {
return write(fd, buf, size);
}