aodv 0.2.2

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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use std::io;
use std::net::Ipv4Addr;

use crate::config::{Config, DataPlaneMode};
use crate::engine::{Action, BufferedPacket};

#[derive(Debug)]
pub enum DataPlaneEvent {
    Packet {
        destination: Ipv4Addr,
        packet: BufferedPacket,
    },
    LocalDelivery {
        packet: BufferedPacket,
    },
}

pub enum DataPlane {
    // ControlOnly is useful for protocol testing and route visibility: the
    // daemon runs the RFC control plane but only logs data-plane actions.
    ControlOnly,
    #[cfg(any(target_os = "linux", target_os = "windows"))]
    TunOverlay(tun_overlay::TunOverlay),
    #[cfg(target_os = "linux")]
    KernelRoutes(linux_routes::KernelRoutes),
}

impl DataPlane {
    pub async fn new(config: &Config) -> io::Result<Self> {
        match config.data_plane {
            DataPlaneMode::ControlOnly => Ok(Self::ControlOnly),
            DataPlaneMode::TunOverlay => {
                #[cfg(any(target_os = "linux", target_os = "windows"))]
                {
                    tun_overlay::TunOverlay::new(config)
                        .await
                        .map(Self::TunOverlay)
                }
                #[cfg(not(any(target_os = "linux", target_os = "windows")))]
                {
                    unsupported("tun-overlay")
                }
            }
            DataPlaneMode::KernelRoutes => {
                #[cfg(target_os = "linux")]
                {
                    linux_routes::KernelRoutes::new(config)
                        .await
                        .map(Self::KernelRoutes)
                }
                #[cfg(not(target_os = "linux"))]
                {
                    unsupported("kernel-routes")
                }
            }
        }
    }

    pub fn has_events(&self) -> bool {
        #[cfg(any(target_os = "linux", target_os = "windows"))]
        {
            matches!(self, Self::TunOverlay(_))
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            false
        }
    }

    pub async fn next_event(&mut self) -> io::Result<DataPlaneEvent> {
        match self {
            // No payload source exists in control-only mode, so this branch is
            // never selected unless has_events() is changed incorrectly.
            Self::ControlOnly => std::future::pending().await,
            #[cfg(any(target_os = "linux", target_os = "windows"))]
            Self::TunOverlay(tun) => tun.next_event().await,
            #[cfg(target_os = "linux")]
            Self::KernelRoutes(_) => std::future::pending().await,
        }
    }

    pub async fn handle_action(&mut self, action: Action) -> io::Result<()> {
        match self {
            Self::ControlOnly => log_control_action(action),
            #[cfg(any(target_os = "linux", target_os = "windows"))]
            Self::TunOverlay(tun) => tun.handle_action(action).await,
            #[cfg(target_os = "linux")]
            Self::KernelRoutes(routes) => routes.handle_action(action).await,
        }
    }

    pub async fn deliver_local(&mut self, packet: BufferedPacket) -> io::Result<()> {
        match self {
            Self::ControlOnly => {
                tracing::debug!(
                    id = packet.id,
                    length = packet.payload.len(),
                    "local data packet"
                );
                Ok(())
            }
            #[cfg(any(target_os = "linux", target_os = "windows"))]
            Self::TunOverlay(tun) => tun.deliver_local(packet).await,
            #[cfg(target_os = "linux")]
            Self::KernelRoutes(_) => Ok(()),
        }
    }
}

fn log_control_action(action: Action) -> io::Result<()> {
    match action {
        Action::ForwardBufferedPackets {
            destination,
            next_hop,
            packets,
        } => tracing::info!(
            %destination,
            %next_hop,
            count = packets.len(),
            "buffered packets ready to forward"
        ),
        Action::DropBufferedPackets {
            destination,
            packets,
        } => tracing::warn!(
            %destination,
            count = packets.len(),
            "dropping buffered packets"
        ),
        Action::RouteDiscovered {
            destination,
            next_hop,
            hop_count,
        } => tracing::info!(%destination, %next_hop, hop_count, "route discovered"),
        Action::RouteInvalidated {
            destination,
            next_hop,
        } => tracing::info!(%destination, %next_hop, "route invalidated"),
        Action::RouteDiscoveryFailed { destination } => {
            tracing::warn!(%destination, "route discovery failed");
        }
        Action::LocalRepairStarted { destination, ttl } => {
            tracing::info!(%destination, ttl, "local repair started");
        }
        Action::LocalRepairFailed { destination } => {
            tracing::warn!(%destination, "local repair failed");
        }
        Action::Send(_) => {}
    }
    Ok(())
}

#[cfg(not(target_os = "linux"))]
fn unsupported(mode: &str) -> io::Result<DataPlane> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        format!("{mode} data plane is not supported on this platform"),
    ))
}

#[cfg(any(target_os = "linux", target_os = "windows"))]
mod tun_overlay {
    use std::io;
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    use etherparse::Ipv4HeaderSlice;
    use tokio::net::UdpSocket;
    use tun_rs::{AsyncDevice, DeviceBuilder};

    use super::{DataPlaneEvent, log_control_action};
    use crate::config::Config;
    use crate::engine::{Action, BufferedPacket};

    #[cfg(target_os = "linux")]
    use super::linux_routes::LinuxRoutes;

    pub struct TunOverlay {
        // TUN overlay keeps user IPv4 packets in userspace and forwards them to
        // the next hop over UDP after the AODV engine resolves a route.
        device: AsyncDevice,
        data_socket: UdpSocket,
        data_port: u16,
        mtu: usize,
        #[cfg(target_os = "linux")]
        routes: LinuxRoutes,
    }

    impl TunOverlay {
        pub async fn new(config: &Config) -> io::Result<Self> {
            if let Some(tun_ip) = config.tun_ip
                && config.local_ip != tun_ip
            {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "--local-ip must match --tun-ip in tun-overlay mode; use --bind-ip for the underlay socket address",
                ));
            }

            let mut builder = DeviceBuilder::new()
                .name(config.tun_name.clone())
                .mtu(config.tun_mtu);

            if let Some(tun_ip) = config.tun_ip {
                builder = builder.ipv4(tun_ip, config.tun_prefix, None);
            }

            #[cfg(target_os = "windows")]
            {
                if config.tun_ip.is_none() {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "--tun-ip is required for Windows tun-overlay mode",
                    ));
                }

                builder = builder
                    .description(format!("aodv-rs {}", config.tun_name))
                    .metric(config.route_metric.min(u16::MAX as u32) as u16);
            }

            let device = builder.build_async().map_err(|error| {
                #[cfg(target_os = "windows")]
                {
                    if error.kind() == io::ErrorKind::NotFound {
                        return io::Error::new(
                            error.kind(),
                            format!(
                                "failed to create/open Wintun adapter {}: {error}; ensure wintun.dll is available next to the executable or in PATH",
                                config.tun_name
                            ),
                        );
                    }
                }

                io::Error::new(
                    error.kind(),
                    format!(
                        "failed to create/open TUN device {}: {error}",
                        config.tun_name
                    ),
                )
            })?;
            let actual_name = device.name()?;
            let data_socket = UdpSocket::bind((config.bind_ip, config.data_port())).await?;

            #[cfg(target_os = "linux")]
            let routes = LinuxRoutes::new(actual_name.clone(), config.route_metric).await?;

            tracing::info!(
                tun = %actual_name,
                data_port = config.data_port(),
                mtu = config.tun_mtu,
                tun_ip = ?config.tun_ip,
                tun_prefix = config.tun_prefix,
                "TUN overlay data plane started"
            );

            Ok(Self {
                device,
                data_socket,
                data_port: config.data_port(),
                mtu: config.tun_mtu as usize,
                #[cfg(target_os = "linux")]
                routes,
            })
        }

        pub async fn next_event(&mut self) -> io::Result<DataPlaneEvent> {
            let mut tun_buffer = vec![0_u8; self.mtu.max(1500)];
            let mut udp_buffer = vec![0_u8; self.mtu.max(1500)];

            tokio::select! {
                result = self.device.recv(&mut tun_buffer) => {
                    // Packets from the TUN device are original IPv4 payloads
                    // that need route discovery if the destination is unknown.
                    let length = result?;
                    tun_buffer.truncate(length);
                    let destination = ipv4_destination(&tun_buffer)?;
                    Ok(DataPlaneEvent::Packet {
                        destination,
                        packet: BufferedPacket {
                            id: 0,
                            payload: tun_buffer,
                        },
                    })
                }
                result = self.data_socket.recv_from(&mut udp_buffer) => {
                    // Overlay UDP packets have already been forwarded by an
                    // upstream AODV next hop; they either continue through the
                    // engine or are delivered locally.
                    let (length, source) = result?;
                    udp_buffer.truncate(length);
                    let destination = ipv4_destination(&udp_buffer)?;
                    let source = match source.ip() {
                        IpAddr::V4(ip) => ip,
                        IpAddr::V6(_) => Ipv4Addr::UNSPECIFIED,
                    };
                    tracing::debug!(%source, %destination, length, "received overlay data packet");
                    Ok(DataPlaneEvent::Packet {
                        destination,
                        packet: BufferedPacket {
                            id: 0,
                            payload: udp_buffer,
                        },
                    })
                }
            }
        }

        pub async fn handle_action(&mut self, action: Action) -> io::Result<()> {
            match action {
                Action::ForwardBufferedPackets {
                    destination,
                    next_hop,
                    packets,
                } => {
                    for packet in packets {
                        self.forward_packet(destination, next_hop, packet).await?;
                    }
                    Ok(())
                }
                Action::RouteDiscovered { destination, .. } => {
                    self.install_tun_route(destination).await
                }
                Action::RouteInvalidated { destination, .. }
                | Action::RouteDiscoveryFailed { destination } => {
                    self.remove_tun_route(destination).await
                }
                other => log_control_action(other),
            }
        }

        pub async fn deliver_local(&self, packet: BufferedPacket) -> io::Result<()> {
            self.device.send(&packet.payload).await?;
            Ok(())
        }

        async fn forward_packet(
            &self,
            destination: Ipv4Addr,
            next_hop: Ipv4Addr,
            packet: BufferedPacket,
        ) -> io::Result<()> {
            let target = SocketAddr::new(IpAddr::V4(next_hop), self.data_port);
            self.data_socket.send_to(&packet.payload, target).await?;
            tracing::debug!(
                %destination,
                %next_hop,
                id = packet.id,
                length = packet.payload.len(),
                "forwarded overlay data packet"
            );
            Ok(())
        }

        #[cfg(target_os = "linux")]
        async fn install_tun_route(&mut self, destination: Ipv4Addr) -> io::Result<()> {
            // Linux TUN mode installs a host route to the virtual device so the
            // kernel sends future packets for that destination into this daemon.
            self.routes.install_dev_route(destination).await
        }

        #[cfg(target_os = "windows")]
        async fn install_tun_route(&mut self, destination: Ipv4Addr) -> io::Result<()> {
            // Windows Wintun mode relies on the adapter prefix configured by
            // tun-rs. Per-destination route table management is intentionally
            // not part of this userspace-only backend.
            tracing::debug!(%destination, "route discovered for Wintun overlay");
            Ok(())
        }

        #[cfg(target_os = "linux")]
        async fn remove_tun_route(&mut self, destination: Ipv4Addr) -> io::Result<()> {
            self.routes.remove_route(destination).await
        }

        #[cfg(target_os = "windows")]
        async fn remove_tun_route(&mut self, destination: Ipv4Addr) -> io::Result<()> {
            tracing::debug!(%destination, "route removed from Wintun overlay state");
            Ok(())
        }
    }

    fn ipv4_destination(packet: &[u8]) -> io::Result<Ipv4Addr> {
        let header = Ipv4HeaderSlice::from_slice(packet).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("data plane packet is not valid IPv4: {error}"),
            )
        })?;
        Ok(header.destination_addr())
    }
}

#[cfg(target_os = "linux")]
mod linux_routes {
    use std::collections::BTreeSet;
    use std::io;
    use std::net::Ipv4Addr;

    use futures_util::TryStreamExt;
    use rtnetlink::{Handle, RouteMessageBuilder, new_connection};

    use super::log_control_action;
    use crate::config::Config;
    use crate::engine::Action;

    #[derive(Debug)]
    pub struct KernelRoutes {
        routes: LinuxRoutes,
    }

    #[derive(Debug)]
    pub struct LinuxRoutes {
        handle: Handle,
        interface: String,
        route_metric: u32,
        managed: BTreeSet<Ipv4Addr>,
    }

    impl KernelRoutes {
        pub async fn new(config: &Config) -> io::Result<Self> {
            let interface = config.interface.clone().ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "--interface is required for kernel-routes data plane",
                )
            })?;
            Ok(Self {
                routes: LinuxRoutes::new(interface, config.route_metric).await?,
            })
        }

        pub async fn handle_action(&mut self, action: Action) -> io::Result<()> {
            match action {
                Action::RouteDiscovered {
                    destination,
                    next_hop,
                    ..
                } => {
                    // Kernel-routes mode lets the OS forward packets directly
                    // to the AODV next hop once the control plane discovers it.
                    self.routes
                        .install_gateway_route(destination, next_hop)
                        .await
                }
                Action::RouteInvalidated { destination, .. }
                | Action::RouteDiscoveryFailed { destination } => {
                    self.routes.remove_route(destination).await
                }
                other => log_control_action(other),
            }
        }
    }

    impl LinuxRoutes {
        pub async fn new(interface: String, route_metric: u32) -> io::Result<Self> {
            let (connection, handle, _) =
                new_connection().map_err(|error| io::Error::other(error.to_string()))?;
            tokio::spawn(connection);
            Ok(Self {
                handle,
                interface,
                route_metric,
                managed: BTreeSet::new(),
            })
        }

        pub async fn install_dev_route(&mut self, destination: Ipv4Addr) -> io::Result<()> {
            let ifindex = self.interface_index().await?;
            self.remove_route(destination).await?;
            let mut route = RouteMessageBuilder::<Ipv4Addr>::new()
                .destination_prefix(destination, 32)
                .output_interface(ifindex)
                .build();
            route
                .attributes
                .push(rtnetlink::packet_route::route::RouteAttribute::Priority(
                    self.route_metric,
                ));
            self.handle
                .route()
                .add(route)
                .execute()
                .await
                .map_err(|error| io::Error::other(error.to_string()))?;
            self.managed.insert(destination);
            Ok(())
        }

        async fn install_gateway_route(
            &mut self,
            destination: Ipv4Addr,
            next_hop: Ipv4Addr,
        ) -> io::Result<()> {
            let ifindex = self.interface_index().await?;
            self.remove_route(destination).await?;
            let mut route = RouteMessageBuilder::<Ipv4Addr>::new()
                .destination_prefix(destination, 32)
                .gateway(next_hop)
                .output_interface(ifindex)
                .build();
            route
                .attributes
                .push(rtnetlink::packet_route::route::RouteAttribute::Priority(
                    self.route_metric,
                ));
            self.handle
                .route()
                .add(route)
                .execute()
                .await
                .map_err(|error| io::Error::other(error.to_string()))?;
            self.managed.insert(destination);
            Ok(())
        }

        pub async fn remove_route(&mut self, destination: Ipv4Addr) -> io::Result<()> {
            if !self.managed.remove(&destination) {
                return Ok(());
            }
            let route = RouteMessageBuilder::<Ipv4Addr>::new()
                .destination_prefix(destination, 32)
                .build();
            match self.handle.route().del(route).execute().await {
                Ok(()) => Ok(()),
                Err(error) => {
                    tracing::debug!(%destination, %error, "managed route removal failed");
                    Ok(())
                }
            }
        }

        async fn interface_index(&self) -> io::Result<u32> {
            let link = self
                .handle
                .link()
                .get()
                .match_name(self.interface.clone())
                .execute()
                .try_next()
                .await
                .map_err(|error| io::Error::other(error.to_string()))?
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("no interface found named {}", self.interface),
                    )
                })?;
            Ok(link.header.index)
        }
    }
}