aodv 0.1.1

Userspace AODV control-plane implementation based on RFC 3561
Documentation
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use std::ffi::CString;
use std::io;
use std::mem::{size_of, zeroed};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::os::fd::AsRawFd;
use std::ptr::{addr_of_mut, null_mut};
use std::time::Instant;

use socket2::{Domain, Protocol, Socket, Type};
use tokio::net::UdpSocket;
use tokio::signal;
use tracing::{debug, info, warn};

use crate::config::Config;
use crate::engine::{Action, Engine, IncomingPacket, SendAction, SendTarget};
use crate::message::Message;

pub async fn run(config: Config) -> io::Result<()> {
    let config = finalize_runtime_config(config)?;
    let socket = bind_socket(&config)?;
    let bind_addr = socket.local_addr()?;

    info!(
        %bind_addr,
        local_ip = %config.local_ip,
        interface = ?config.interface,
        "aodv daemon started"
    );

    let mut engine = Engine::new(config.clone());
    let mut buffer = [0_u8; 2048];

    loop {
        let now = Instant::now();
        let deadline = engine.next_deadline(now);

        tokio::select! {
            biased;
            result = signal::ctrl_c() => {
                result?;
                info!("received shutdown signal");
                return Ok(());
            }
            result = recv_datagram(&socket, &mut buffer) => {
                let (length, source_addr, ttl) = result?;
                let source = match source_addr.ip() {
                    IpAddr::V4(ipv4) => ipv4,
                    IpAddr::V6(_) => {
                        warn!(%source_addr, "ignoring ipv6 sender for ipv4 AODV daemon");
                        continue;
                    }
                };

                match Message::decode(&buffer[..length]) {
                    Ok(message) => {
                        debug!(%source, length, ttl, "received AODV datagram");
                        let actions = engine.handle_incoming(
                            IncomingPacket {
                                source,
                                ttl,
                                message,
                            },
                            Instant::now(),
                        );
                        execute_actions(&socket, &config, actions).await?;
                    }
                    Err(error) => warn!(%source, %error, "dropping invalid datagram"),
                }
            }
            _ = sleep_until_deadline(deadline), if deadline.is_some() => {
                let actions = engine.tick(Instant::now());
                execute_actions(&socket, &config, actions).await?;
            }
        }
    }
}

fn finalize_runtime_config(mut config: Config) -> io::Result<Config> {
    if config.local_ip == Ipv4Addr::UNSPECIFIED {
        if let Some(interface) = &config.interface {
            config.local_ip = interface_ipv4_addr(interface)?;
        } else if config.bind_ip != Ipv4Addr::UNSPECIFIED {
            config.local_ip = config.bind_ip;
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "local_ip is unspecified; pass --local-ip, --bind-ip, or --interface for real-device operation",
            ));
        }
    }

    Ok(config)
}

fn bind_socket(config: &Config) -> io::Result<UdpSocket> {
    let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
    socket.set_reuse_address(true)?;
    socket.set_broadcast(true)?;
    socket.set_nonblocking(true)?;

    if let Some(interface) = &config.interface {
        bind_to_device(socket.as_raw_fd(), interface)?;
    }

    enable_recv_ttl(socket.as_raw_fd())?;

    let bind_addr = SocketAddrV4::new(config.bind_ip, config.aodv_port());
    let bind_result = socket.bind(&bind_addr.into());
    if let Err(error) = bind_result {
        if error.kind() == io::ErrorKind::PermissionDenied && config.aodv_port() < 1024 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!(
                    "binding UDP port {} requires root or CAP_NET_BIND_SERVICE: {error}",
                    config.aodv_port()
                ),
            ));
        }
        return Err(error);
    }

    let std_socket: std::net::UdpSocket = socket.into();
    UdpSocket::from_std(std_socket)
}

async fn recv_datagram(
    socket: &UdpSocket,
    buffer: &mut [u8],
) -> io::Result<(usize, SocketAddr, Option<u8>)> {
    loop {
        socket.readable().await?;
        match try_recv_datagram(socket, buffer) {
            Ok(result) => return Ok(result),
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => continue,
            Err(error) => return Err(error),
        }
    }
}

fn try_recv_datagram(
    socket: &UdpSocket,
    buffer: &mut [u8],
) -> io::Result<(usize, SocketAddr, Option<u8>)> {
    let raw_fd = socket.as_raw_fd();
    let mut source_addr: libc::sockaddr_storage = unsafe { zeroed() };
    let mut iov = libc::iovec {
        iov_base: buffer.as_mut_ptr().cast(),
        iov_len: buffer.len(),
    };
    let mut control = [0_u8; 64];
    let mut message: libc::msghdr = unsafe { zeroed() };
    message.msg_name = addr_of_mut!(source_addr).cast();
    message.msg_namelen = size_of::<libc::sockaddr_storage>() as libc::socklen_t;
    message.msg_iov = addr_of_mut!(iov);
    message.msg_iovlen = 1;
    message.msg_control = control.as_mut_ptr().cast();
    message.msg_controllen = control.len() as _;

    let received = unsafe { libc::recvmsg(raw_fd, &mut message, 0) };
    if received < 0 {
        return Err(io::Error::last_os_error());
    }

    let address = socket_addr_from_storage(&source_addr, message.msg_namelen)?;
    let ttl = unsafe { ttl_from_cmsgs(&message) };
    Ok((received as usize, address, ttl))
}

async fn sleep_until_deadline(deadline: Option<Instant>) {
    if let Some(deadline) = deadline {
        tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;
    }
}

async fn execute_actions(
    socket: &UdpSocket,
    config: &Config,
    actions: Vec<Action>,
) -> io::Result<()> {
    for action in actions {
        match action {
            Action::Send(send) => send_action(socket, config, &send).await?,
            Action::ForwardBufferedPackets {
                destination,
                next_hop,
                packets,
            } => info!(
                %destination,
                %next_hop,
                count = packets.len(),
                "buffered packets ready to forward"
            ),
            Action::DropBufferedPackets {
                destination,
                packets,
            } => warn!(
                %destination,
                count = packets.len(),
                "dropping buffered packets"
            ),
            Action::RouteDiscovered {
                destination,
                next_hop,
                hop_count,
            } => info!(%destination, %next_hop, hop_count, "route discovered"),
            Action::RouteInvalidated {
                destination,
                next_hop,
            } => {
                info!(%destination, %next_hop, "route invalidated");
            }
            Action::RouteDiscoveryFailed { destination } => {
                warn!(%destination, "route discovery failed");
            }
            Action::LocalRepairStarted { destination, ttl } => {
                info!(%destination, ttl, "local repair started");
            }
            Action::LocalRepairFailed { destination } => {
                warn!(%destination, "local repair failed");
            }
        }
    }
    Ok(())
}

pub(crate) async fn send_action(
    socket: &UdpSocket,
    config: &Config,
    action: &SendAction,
) -> io::Result<()> {
    socket.set_ttl(action.ttl as u32)?;
    let ip = match action.target {
        SendTarget::Unicast(ip) => ip,
        SendTarget::Broadcast => config.broadcast_ip,
    };
    let destination = SocketAddr::new(IpAddr::V4(ip), config.aodv_port());
    let bytes = action.message.encode();
    socket.send_to(bytes.as_ref(), destination).await?;
    Ok(())
}

fn interface_ipv4_addr(interface: &str) -> io::Result<Ipv4Addr> {
    let mut ifaddrs = null_mut();
    let result = unsafe { libc::getifaddrs(&mut ifaddrs) };
    if result != 0 {
        return Err(io::Error::last_os_error());
    }

    let mut current = ifaddrs;
    let mut found = None;

    while !current.is_null() {
        let entry = unsafe { &*current };
        if !entry.ifa_name.is_null() && !entry.ifa_addr.is_null() {
            let name = unsafe { std::ffi::CStr::from_ptr(entry.ifa_name) };
            if name.to_string_lossy() == interface {
                let family = unsafe { (*entry.ifa_addr).sa_family as i32 };
                if family == libc::AF_INET {
                    let sockaddr = unsafe { &*(entry.ifa_addr as *const libc::sockaddr_in) };
                    let ip = Ipv4Addr::from(u32::from_be(sockaddr.sin_addr.s_addr));
                    found = Some(ip);
                    break;
                }
            }
        }
        current = unsafe { (*current).ifa_next };
    }

    unsafe { libc::freeifaddrs(ifaddrs) };

    found.ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            format!("no IPv4 address found for interface {interface}"),
        )
    })
}

fn bind_to_device(fd: std::os::fd::RawFd, interface: &str) -> io::Result<()> {
    let device = CString::new(interface)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "interface contains NUL"))?;
    let result = unsafe {
        libc::setsockopt(
            fd,
            libc::SOL_SOCKET,
            libc::SO_BINDTODEVICE,
            device.as_ptr().cast(),
            (device.as_bytes_with_nul().len()) as libc::socklen_t,
        )
    };
    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::new(
            io::Error::last_os_error().kind(),
            format!(
                "failed to bind socket to interface {interface}: {}",
                io::Error::last_os_error()
            ),
        ))
    }
}

fn enable_recv_ttl(fd: std::os::fd::RawFd) -> io::Result<()> {
    let enabled: libc::c_int = 1;
    let result = unsafe {
        libc::setsockopt(
            fd,
            libc::IPPROTO_IP,
            libc::IP_RECVTTL,
            (&enabled as *const libc::c_int).cast(),
            size_of::<libc::c_int>() as libc::socklen_t,
        )
    };
    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

fn socket_addr_from_storage(
    storage: &libc::sockaddr_storage,
    length: libc::socklen_t,
) -> io::Result<SocketAddr> {
    if storage.ss_family as i32 != libc::AF_INET
        || length < size_of::<libc::sockaddr_in>() as libc::socklen_t
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "received non-IPv4 UDP datagram",
        ));
    }

    let address =
        unsafe { &*(storage as *const libc::sockaddr_storage as *const libc::sockaddr_in) };
    let ip = Ipv4Addr::from(u32::from_be(address.sin_addr.s_addr));
    let port = u16::from_be(address.sin_port);
    Ok(SocketAddr::V4(SocketAddrV4::new(ip, port)))
}

unsafe fn ttl_from_cmsgs(message: &libc::msghdr) -> Option<u8> {
    let mut cursor = unsafe { libc::CMSG_FIRSTHDR(message) };
    while !cursor.is_null() {
        let header = unsafe { &*cursor };
        if header.cmsg_level == libc::IPPROTO_IP && header.cmsg_type == libc::IP_TTL {
            let value = unsafe { libc::CMSG_DATA(cursor) as *const libc::c_int };
            return unsafe { (*value).try_into().ok() };
        }
        cursor = unsafe { libc::CMSG_NXTHDR(message, cursor) };
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{Rrep, Rreq};

    fn loopback_config(port: u16) -> Config {
        Config {
            local_ip: Ipv4Addr::new(127, 0, 0, 1),
            bind_ip: Ipv4Addr::new(127, 0, 0, 1),
            port,
            ..Config::default()
        }
    }

    #[tokio::test]
    async fn send_action_writes_udp_datagram() {
        let receiver = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let sender = UdpSocket::bind("127.0.0.1:0").await.unwrap();

        let receiver_addr = receiver.local_addr().unwrap();
        let config = loopback_config(receiver_addr.port());

        let action = SendAction {
            target: SendTarget::Unicast(Ipv4Addr::new(127, 0, 0, 1)),
            ttl: 4,
            message: Message::Rreq(Rreq {
                join: false,
                repair: false,
                gratuitous_rrep: false,
                destination_only: false,
                unknown_sequence_number: true,
                hop_count: 0,
                rreq_id: 9,
                destination_ip: Ipv4Addr::new(10, 0, 0, 9),
                destination_sequence_number: 0,
                originator_ip: Ipv4Addr::new(10, 0, 0, 1),
                originator_sequence_number: 1,
            }),
        };

        send_action(&sender, &config, &action).await.unwrap();

        let mut buffer = [0_u8; 128];
        let (size, _) = receiver.recv_from(&mut buffer).await.unwrap();
        assert!(matches!(
            Message::decode(&buffer[..size]).unwrap(),
            Message::Rreq(_)
        ));

        let hello = SendAction {
            target: SendTarget::Unicast(Ipv4Addr::new(127, 0, 0, 1)),
            ttl: 1,
            message: Message::Rrep(Rrep::hello(Ipv4Addr::new(127, 0, 0, 1), 4, 2_000, 1_000)),
        };
        send_action(&sender, &config, &hello).await.unwrap();
        let (size, _) = receiver.recv_from(&mut buffer).await.unwrap();
        assert!(matches!(
            Message::decode(&buffer[..size]).unwrap(),
            Message::Rrep(_)
        ));
    }

    #[tokio::test]
    async fn recv_datagram_reports_inbound_ttl() {
        let socket = bind_socket(&loopback_config(0)).unwrap();
        let local_addr = socket.local_addr().unwrap();
        let sender = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
        sender.set_ttl(3).unwrap();

        let payload = Rreq {
            join: false,
            repair: false,
            gratuitous_rrep: false,
            destination_only: false,
            unknown_sequence_number: true,
            hop_count: 0,
            rreq_id: 4,
            destination_ip: Ipv4Addr::new(10, 0, 0, 4),
            destination_sequence_number: 0,
            originator_ip: Ipv4Addr::new(10, 0, 0, 1),
            originator_sequence_number: 1,
        }
        .encode();
        sender.send_to(payload.as_ref(), local_addr).unwrap();

        let mut buffer = [0_u8; 128];
        let (size, source_addr, ttl) = recv_datagram(&socket, &mut buffer).await.unwrap();

        assert_eq!(size, payload.len());
        assert_eq!(source_addr.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
        assert_eq!(ttl, Some(3));
        assert!(matches!(
            Message::decode(&buffer[..size]).unwrap(),
            Message::Rreq(_)
        ));
    }

    #[test]
    fn finalize_runtime_config_uses_bind_ip_as_local_ip() {
        let config = Config {
            local_ip: Ipv4Addr::UNSPECIFIED,
            bind_ip: Ipv4Addr::new(192, 0, 2, 4),
            ..Config::default()
        };

        let finalized = finalize_runtime_config(config).unwrap();
        assert_eq!(finalized.local_ip, Ipv4Addr::new(192, 0, 2, 4));
    }
}