aboutsummaryrefslogtreecommitdiff
path: root/src/tunnel.rs
blob: df172c0d171c466254b69c84e603eb4f4d1c3132 (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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use crate::{Error, Result};

use std::ffi::{c_char, c_int, CString};
use std::io;
use std::net::{Ipv4Addr, Ipv6Addr};

const SIOCADDTUNNEL: c_int = 0x89F0 + 1;
const SIOCDELTUNNEL: c_int = 0x89F0 + 2;

/// A handle to a 6in4 tunnel. The interface is automatically deleted on drop.
#[derive(Debug)]
pub struct Sit {
    name: String,
}

impl Drop for Sit {
    fn drop(&mut self) {
        let _ = self.do_delete();
    }
}

impl Sit {
    /// Creates a new 6in4 tunnel on a parent device.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the tunnel to be created.
    /// * `master` - The name of the parent interface for actual traffic.
    /// * `laddr` - The address of the local tunnel endpoint,
    ///             e.g. the WAN IPv4 address of a router.
    /// * `raddr` - The address of the remote tunnel endpoint, e.g. a tunnel server.
    pub fn new(name: String, master: String, laddr: Ipv4Addr, raddr: Ipv4Addr) -> Result<Self> {
        let tnlname = CString::new(&*name)?;
        let ifmaster = CString::new(&*master)?;
        let sit0 = CString::new("sit0")?;

        let tnlname_signed = unsafe { &*(tnlname.as_bytes() as *const _ as *const [i8]) };
        let mut tnlname_arr = [0i8; libc::IFNAMSIZ];
        for (&i, o) in tnlname_signed.iter().zip(tnlname_arr.iter_mut()) {
            *o = i;
        }

        let sit0_signed = unsafe { &*(sit0.as_bytes() as *const _ as *const [i8]) };
        let mut sit0_arr = [0i8; libc::IFNAMSIZ];
        for (&i, o) in sit0_signed.iter().zip(sit0_arr.iter_mut()) {
            *o = i;
        }

        let mut vihl = VerIhl::default();

        vihl.set_version(4);
        vihl.set_ihl(5);

        let p = IpTunnelParm4 {
            name: tnlname_arr,
            link: unsafe { libc::if_nametoindex(ifmaster.as_ptr()) },
            i_flags: 0,
            o_flags: 0,
            i_key: 0,
            o_key: 0,
            iph: IpHdr4 {
                vihl,
                tos: 0,
                tot_len: 0,
                id: 0,
                frag_off: 0,
                check: 0,
                ttl: 64,
                protocol: libc::IPPROTO_IPV6 as u8,
                saddr: u32::from(laddr).to_be(),
                daddr: u32::from(raddr).to_be(),
            },
        };

        if p.link == 0 {
            return Err(Error::LinkNotFound(master));
        }

        let ifr = IfReq4 {
            name: sit0_arr,
            ifru_data: &p,
        };

        let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, libc::IPPROTO_IP) };
        if fd < 0 {
            return Err(io::Error::last_os_error().into());
        }

        if unsafe { libc::ioctl(fd, SIOCADDTUNNEL, &ifr) } < 0 {
            return Err(io::Error::last_os_error().into());
        }

        // Errors are safe to ignore because they don't affect tunnel creation
        // but do leave the program in an inconsistent state.
        unsafe {
            libc::close(fd);
        }

        Ok(Self { name })
    }

    fn do_delete(&self) -> Result<()> {
        delete_tunnel(&self.name)
    }
}

/// A handle to a 4in6 tunnel. The interface is automatically deleted on drop.
#[derive(Debug)]
pub struct IpIp6 {
    name: String,
}

impl Drop for IpIp6 {
    fn drop(&mut self) {
        let _ = self.do_delete();
    }
}

impl IpIp6 {
    /// Creates a new 4in6 tunnel on a parent device.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the tunnel to be created.
    /// * `master` - The name of the parent interface for actual traffic.
    /// * `laddr` - The address of the local tunnel endpoint, e.g. the IPv6 GUA of a DS-Lite B4.
    /// * `raddr` - The address of the remote tunnel endpoint, e.g. a DS-Lite AFTR.
    pub fn new(name: String, master: String, laddr: Ipv6Addr, raddr: Ipv6Addr) -> Result<Self> {
        let tnlname = CString::new(&*name)?;
        let ifmaster = CString::new(&*master)?;
        let ip6tnl0 = CString::new("ip6tnl0")?;

        let tnlname_signed = unsafe { &*(tnlname.as_bytes() as *const _ as *const [i8]) };
        let mut tnlname_arr = [0i8; libc::IFNAMSIZ];
        for (&i, o) in tnlname_signed.iter().zip(tnlname_arr.iter_mut()) {
            *o = i;
        }

        let ip6tnl0_signed = unsafe { &*(ip6tnl0.as_bytes() as *const _ as *const [i8]) };
        let mut ip6tnl0_arr = [0i8; libc::IFNAMSIZ];
        for (&i, o) in ip6tnl0_signed.iter().zip(ip6tnl0_arr.iter_mut()) {
            *o = i;
        }

        let p = IpTunnelParm6 {
            name: tnlname_arr,
            link: unsafe { libc::if_nametoindex(ifmaster.as_ptr()) },
            i_flags: 0,
            o_flags: 0,
            i_key: 0,
            o_key: 0,
            iph: IpHdr6 {
                saddr: u128::from(laddr).to_be(),
                daddr: u128::from(raddr).to_be(),
            },
        };

        if p.link == 0 {
            return Err(Error::LinkNotFound(master));
        }

        let ifr = IfReq6 {
            name: ip6tnl0_arr,
            ifru_data: &p,
        };

        let fd = unsafe { libc::socket(libc::AF_INET6, libc::SOCK_DGRAM, libc::IPPROTO_IP) };
        if fd < 0 {
            return Err(io::Error::last_os_error().into());
        }

        if unsafe { libc::ioctl(fd, SIOCADDTUNNEL, &ifr) } < 0 {
            return Err(io::Error::last_os_error().into());
        }

        // Errors are safe to ignore because they don't affect tunnel creation
        // but do leave the program in an inconsistent state.
        unsafe {
            libc::close(fd);
        }

        Ok(Self { name })
    }

    fn do_delete(&self) -> Result<()> {
        delete_tunnel(&self.name)
    }
}

fn delete_tunnel(name: &str) -> Result<()> {
    let tnlname = CString::new(name)?;

    let tnlname_signed = unsafe { &*(tnlname.as_bytes() as *const _ as *const [i8]) };
    let mut tnlname_arr = [0i8; libc::IFNAMSIZ];
    for (&i, o) in tnlname_signed.iter().zip(tnlname_arr.iter_mut()) {
        *o = i;
    }

    let p = IpTunnelParm4 {
        name: tnlname_arr,
        link: 0,
        i_flags: 0,
        o_flags: 0,
        i_key: 0,
        o_key: 0,
        iph: IpHdr4 {
            vihl: VerIhl::default(),
            tos: 0,
            tot_len: 0,
            id: 0,
            frag_off: 0,
            ttl: 0,
            protocol: 0,
            check: 0,
            saddr: 0,
            daddr: 0,
        },
    };

    let ifr = IfReq4 {
        name: tnlname_arr,
        ifru_data: &p,
    };

    let fd = unsafe { libc::socket(libc::AF_INET6, libc::SOCK_DGRAM, libc::IPPROTO_IP) };
    if fd < 0 {
        return Err(io::Error::last_os_error().into());
    }

    if unsafe { libc::ioctl(fd, SIOCDELTUNNEL, &ifr) } < 0 {
        return Err(io::Error::last_os_error().into());
    }

    // Errors are safe to ignore because they don't affect tunnel deletion
    // but do leave the program in an inconsistent state.
    unsafe {
        libc::close(fd);
    }

    Ok(())
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct VerIhl(u8);

impl VerIhl {
    fn set_version(&mut self, version: u8) {
        self.0 = (self.0 & 0x0f) | (version << 4);
    }

    fn set_ihl(&mut self, ihl: u8) {
        self.0 = (self.0 & 0xf0) | (ihl % 0x0f);
    }
}

#[derive(Debug)]
#[repr(C)]
struct IpHdr4 {
    vihl: VerIhl,
    tos: u8,
    tot_len: u16,
    id: u16,
    frag_off: u16,
    ttl: u8,
    protocol: u8,
    check: u16,
    saddr: u32,
    daddr: u32,
}

#[derive(Debug)]
#[repr(C)]
struct IpTunnelParm4 {
    name: [c_char; libc::IFNAMSIZ],
    link: u32,
    i_flags: u16,
    o_flags: u16,
    i_key: u32,
    o_key: u32,
    iph: IpHdr4,
}

#[derive(Debug)]
#[repr(C)]
struct IfReq4 {
    name: [c_char; libc::IFNAMSIZ],
    ifru_data: *const IpTunnelParm4,
}

#[derive(Debug)]
#[repr(C)]
struct IpHdr6 {
    saddr: u128,
    daddr: u128,
}

#[derive(Debug)]
#[repr(C)]
struct IpTunnelParm6 {
    name: [c_char; libc::IFNAMSIZ],
    link: u32,
    i_flags: u16,
    o_flags: u16,
    i_key: u32,
    o_key: u32,
    iph: IpHdr6,
}

#[derive(Debug)]
#[repr(C)]
struct IfReq6 {
    name: [c_char; libc::IFNAMSIZ],
    ifru_data: *const IpTunnelParm6,
}