aboutsummaryrefslogtreecommitdiff
path: root/netlinkd_sys/netlinkd/netlinkd.c
blob: 13bc4545960dda66cb42d978383fa5d68353b5c8 (plain) (blame)
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
107
108
109
#include <net/if.h>
#include <netinet/in.h>
#include <linux/if_tunnel.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>

int netlinkd_delete_tunnel(const char *tnlname)
{
	struct ip_tunnel_parm p;

	strcpy(p.name, tnlname);

	struct ifreq ifr;

	strcpy(ifr.ifr_name, tnlname);
	ifr.ifr_ifru.ifru_data = (char *) &p;

	int fd;
	if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP)) < 0) {
		return -1;
	}

	if (ioctl(fd, SIOCDELTUNNEL, &ifr)) {
		return -1;
	}

	close(fd);
	return 0;
}

int netlinkd_create_6in4(
	const char *tnlname,
	const char *ifmaster,
	unsigned int saddr,
	unsigned int daddr
)
{
	struct ip_tunnel_parm p;

	strcpy(p.name, tnlname);
	p.iph.version = 4;
	p.iph.ihl = 5;
	p.iph.protocol = IPPROTO_IPV6;
	p.iph.saddr = saddr;
	p.iph.daddr = daddr;
	p.link = if_nametoindex(ifmaster);

	if (!p.link) {
		return -1;
	}

	struct ifreq ifr;

	strcpy(ifr.ifr_name, "sit0");
	ifr.ifr_ifru.ifru_data = (char *) &p;

	int fd;
	if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0) {
		return -1;
	}

	if (ioctl(fd, SIOCADDTUNNEL, &ifr)) {
		return -1;
	}

	close(fd);
	return 0;
}

int netlinkd_create_4in6(
	const char *tnlname,
	const char *ifmaster,
	const unsigned char saddr[16],
	const unsigned char daddr[16]
)
{
	struct ip_tunnel_parm p;

	strcpy(p.name, tnlname);
	p.iph.version = 2;
	p.iph.ihl = 0;
	p.iph.protocol = IPPROTO_IP;
	p.iph.saddr = saddr[0];
	p.iph.daddr = daddr[0];
	p.link = if_nametoindex(ifmaster);

	if (!p.link) {
		return -1;
	}

	struct ifreq ifr;

	strcpy(ifr.ifr_name, "ip6tnl0");
	ifr.ifr_ifru.ifru_data = (char *) &p;

	int fd;
	if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IP)) < 0) {
		return -1;
	}

	if (ioctl(fd, SIOCADDTUNNEL, &ifr)) {
		return -1;
	}

	close(fd);
	return 0;
}