-
Notifications
You must be signed in to change notification settings - Fork 2
/
tun.c
67 lines (57 loc) · 1.42 KB
/
tun.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
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <event2/event.h>
#include "tun.h"
int
tnt_tun_close(struct tnt_tun *tun) {
tapcfg_destroy(tun->handle);
tun->handle = NULL;
return 0;
}
int
tnt_tun_open(struct tnt_tun *tun) {
if (tun->handle == NULL)
tun->handle = tapcfg_init();
if (tapcfg_start(tun->handle, tun->interface, 0) < 0)
return (-1);
tun->fd = tapcfg_get_fd(tun->handle);
tun->interface = strdup(tapcfg_get_ifname(tun->handle));
if (tun->interface == NULL)
return (-1);
return (0);
}
int
tnt_tun_iface_set_ipv4(struct tnt_tun *tun, char const *ipaddr) {
int ret = -1;
char *addr, *ptr;
short netbits = 24;
addr = strdup(ipaddr);
if (addr == NULL)
return (-1);
ptr = strchr(addr, '/');
if (ptr != NULL) {
netbits = (short) evutil_strtoll(ptr + 1, NULL, 10);
if (netbits < 1 || netbits > 32) {
goto fail;
}
*ptr = '\0';
}
ret = tapcfg_iface_set_ipv4(tun->handle, addr, netbits);
fail:
free(addr);
return (ret);
}
int
tnt_tun_iface_set_status(struct tnt_tun *tun, int flags) {
return tapcfg_iface_set_status(tun->handle, flags);
}
int
tnt_tun_write(struct tnt_tun *tun, char const *buf, int n) {
return tapcfg_write(tun->handle, (void *) buf, n);
}
int
tnt_tun_read(struct tnt_tun *tun, char *buf, int n) {
tapcfg_wait_readable(tun->handle, 0); // windows reads while waiting
return tapcfg_read(tun->handle, (void *) buf, n);
}