Skip to main content

rustflexstack/link_layer/
raw_link_layer.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Raw Ethernet link layer for GeoNetworking.
5//!
6//! [`RawLinkLayer`] opens two `pnet` datalink channels on the same interface
7//! (one for RX, one for TX) and runs each in a dedicated thread.
8//!
9//! # Concurrency design
10//! ```text
11//!   NIC ──RX──► rx_thread ──Sender<Vec<u8>>──► GeoNetworking router
12//!   NIC ◄─TX──  tx_thread ◄──Receiver<Vec<u8>>── GeoNetworking router
13//! ```
14//!
15//! Both threads communicate exclusively through `std::sync::mpsc` channels —
16//! no `Arc`/`Mutex` is needed.  The `pnet` library handles all low-level
17//! socket access; two separate channel objects are opened because `pnet`
18//! requires a distinct handle per thread.
19//!
20//! # Graceful shutdown
21//! Dropping the `tx` side of the GN→NIC channel causes the TX thread to exit
22//! its `while let Ok(...)` loop naturally.  The RX thread polls a
23//! `stop_flag` `AtomicBool` shared via `Arc` so it can also be stopped.
24//!
25//! # Concurrency correctness
26//! On Linux, `AF_PACKET` sockets used by `pnet` are per-open-socket — two
27//! sockets on the same interface do *not* conflict; the kernel delivers
28//! received packets to all matching sockets independently.
29
30use crate::link_layer::packet_consts::ETH_P_GEONET;
31use pnet::datalink::{self, Channel, Config, NetworkInterface};
32use std::sync::atomic::{AtomicBool, Ordering};
33use std::sync::mpsc::{Receiver, Sender};
34use std::sync::Arc;
35use std::thread;
36
37// ------------------------------------------------------------------
38// Helpers
39// ------------------------------------------------------------------
40
41/// Build a minimal 14-byte Ethernet II frame with the GeoNet EtherType.
42fn build_eth_frame(dest_mac: [u8; 6], src_mac: [u8; 6], payload: &[u8]) -> Vec<u8> {
43    let mut frame = Vec::with_capacity(14 + payload.len());
44    frame.extend_from_slice(&dest_mac);
45    frame.extend_from_slice(&src_mac);
46    frame.extend_from_slice(&ETH_P_GEONET.to_be_bytes());
47    frame.extend_from_slice(payload);
48    frame
49}
50
51/// Return `true` if the frame carries the GeoNetworking EtherType (0x8947).
52fn is_geonet_frame(frame: &[u8]) -> bool {
53    frame.len() >= 14 && u16::from_be_bytes([frame[12], frame[13]]) == ETH_P_GEONET
54}
55
56// ------------------------------------------------------------------
57// RawLinkLayer
58// ------------------------------------------------------------------
59
60/// Ethernet link-layer driver for GeoNetworking.
61///
62/// Construct with [`RawLinkLayer::new`], then call [`RawLinkLayer::start`]
63/// to spawn the RX and TX threads.  The struct is consumed by `start` so
64/// ownership is clear.
65pub struct RawLinkLayer {
66    /// Channel endpoint for sending received GN payloads *up* to the GN router.
67    gn_tx: Sender<Vec<u8>>,
68    /// Channel endpoint for receiving GN payloads *from* the GN router for TX.
69    gn_rx: Receiver<Vec<u8>>,
70    /// Network interface name (e.g. `"eth0"`, `"enp0s31f6"`).
71    iface_name: String,
72    /// Local MAC address used as the source address in transmitted frames.
73    mac_address: [u8; 6],
74    /// Shared stop flag.  Setting this to `true` causes the RX thread to exit.
75    stop_flag: Arc<AtomicBool>,
76    /// Optional channel receiving GN payloads together with the Ethernet
77    /// source address (the previous sender, used by the GeoNetworking CBF
78    /// algorithms); when set it replaces `gn_tx` for received frames.
79    sender_tx: Option<Sender<(Vec<u8>, [u8; 6])>>,
80    /// Optional channel of GN payloads addressed to a next hop (destination
81    /// MAC address), e.g. from `Router::set_unicast_sender`.
82    unicast_rx: Option<Receiver<(Vec<u8>, [u8; 6])>>,
83}
84
85impl RawLinkLayer {
86    /// Create a new `RawLinkLayer`.
87    ///
88    /// * `gn_tx`      — sender into the GeoNetworking router (NIC → GN direction).
89    /// * `gn_rx`      — receiver from the GeoNetworking router (GN → NIC direction).
90    /// * `iface_name` — OS network interface name.
91    /// * `mac_address` — MAC address to use as the Ethernet source address.
92    pub fn new(
93        gn_tx: Sender<Vec<u8>>,
94        gn_rx: Receiver<Vec<u8>>,
95        iface_name: &str,
96        mac_address: [u8; 6],
97    ) -> Self {
98        RawLinkLayer {
99            gn_tx,
100            gn_rx,
101            iface_name: iface_name.to_string(),
102            mac_address,
103            stop_flag: Arc::new(AtomicBool::new(false)),
104            sender_tx: None,
105            unicast_rx: None,
106        }
107    }
108
109    /// Deliver received GN payloads with the Ethernet source address of the
110    /// frame, e.g. to `RouterHandle::send_incoming_packet_from`.
111    pub fn with_sender_channel(mut self, sender_tx: Sender<(Vec<u8>, [u8; 6])>) -> Self {
112        self.sender_tx = Some(sender_tx);
113        self
114    }
115
116    /// Transmit the GN payloads of unicast forwarding steps with their
117    /// next-hop MAC address (ETSI TS 103 836-4-1 clause E.2, NH_LL_ADDR),
118    /// e.g. from `Router::set_unicast_sender`. The frames of `gn_rx` keep the
119    /// broadcast address.
120    pub fn with_unicast_receiver(mut self, unicast_rx: Receiver<(Vec<u8>, [u8; 6])>) -> Self {
121        self.unicast_rx = Some(unicast_rx);
122        self
123    }
124
125    /// MID of GN over ITS-G5: the MAC address of the interface (ETSI TS
126    /// 103 836-4-2 clause 6.1).
127    pub fn media_dependent_mid(&self) -> crate::geonet::gn_address::MID {
128        crate::geonet::gn_address::MID::from_its_g5_mac(self.mac_address)
129    }
130
131    /// Return a clone of the stop flag so the caller can signal shutdown.
132    pub fn stop_flag(&self) -> Arc<AtomicBool> {
133        Arc::clone(&self.stop_flag)
134    }
135
136    /// Consume `self` and start the RX and TX background threads.
137    ///
138    /// The threads run until:
139    /// - **RX**: `stop_flag` is set to `true`.
140    /// - **TX**: the `gn_rx` sender is dropped (channel closed).
141    pub fn start(self) {
142        let RawLinkLayer {
143            gn_tx,
144            gn_rx,
145            iface_name,
146            mac_address,
147            stop_flag,
148            sender_tx,
149            unicast_rx,
150        } = self;
151
152        let iface_name_rx = iface_name.clone();
153        let iface_name_tx = iface_name;
154        let stop_flag_rx = Arc::clone(&stop_flag);
155
156        // ── RX thread: NIC ──► GeoNetworking ─────────────────────────────────
157        //
158        // We open our own AF_PACKET / SOCK_RAW socket instead of using a pnet
159        // channel for RX.  This lets us call setsockopt(PACKET_IGNORE_OUTGOING)
160        // immediately after creation so the kernel never echoes our own TX
161        // frames back to us — the only reliable fix for self-reception.
162        thread::spawn(move || {
163            // Resolve the interface index
164            let if_index = match find_interface(&iface_name_rx) {
165                Some(i) => i.index,
166                None => {
167                    return;
168                }
169            };
170
171            // Open AF_PACKET / SOCK_RAW socket filtered to GeoNet EtherType.
172            // htons(ETH_P_GEONET) selects only 0x8947 frames at kernel level.
173            let sock = unsafe {
174                libc::socket(
175                    libc::AF_PACKET,
176                    libc::SOCK_RAW,
177                    ETH_P_GEONET.to_be() as libc::c_int,
178                )
179            };
180            if sock < 0 {
181                return;
182            }
183
184            // PACKET_IGNORE_OUTGOING (value 23, added in Linux 4.20):
185            // tells the kernel to never deliver frames that this host
186            // transmitted to this socket — eliminates self-echo entirely.
187            unsafe {
188                let val: libc::c_int = 1;
189                let _ = libc::setsockopt(
190                    sock,
191                    libc::SOL_PACKET,
192                    23, // PACKET_IGNORE_OUTGOING
193                    &val as *const libc::c_int as *const libc::c_void,
194                    std::mem::size_of::<libc::c_int>() as libc::socklen_t,
195                );
196            }
197
198            // Bind to the specific interface so we don't receive from all NICs.
199            let sll = libc::sockaddr_ll {
200                sll_family: libc::AF_PACKET as u16,
201                sll_protocol: ETH_P_GEONET.to_be(),
202                sll_ifindex: if_index as i32,
203                sll_hatype: 0,
204                sll_pkttype: 0,
205                sll_halen: 0,
206                sll_addr: [0u8; 8],
207            };
208            let ret = unsafe {
209                libc::bind(
210                    sock,
211                    &sll as *const libc::sockaddr_ll as *const libc::sockaddr,
212                    std::mem::size_of::<libc::sockaddr_ll>() as libc::socklen_t,
213                )
214            };
215            if ret < 0 {
216                unsafe {
217                    libc::close(sock);
218                }
219                return;
220            }
221
222            // Set a 100 ms receive timeout so we can check the stop flag.
223            let tv = libc::timeval {
224                tv_sec: 0,
225                tv_usec: 100_000,
226            };
227            unsafe {
228                libc::setsockopt(
229                    sock,
230                    libc::SOL_SOCKET,
231                    libc::SO_RCVTIMEO,
232                    &tv as *const libc::timeval as *const libc::c_void,
233                    std::mem::size_of::<libc::timeval>() as libc::socklen_t,
234                );
235            }
236
237            let mut buf = vec![0u8; 2048];
238            loop {
239                if stop_flag_rx.load(Ordering::Relaxed) {
240                    break;
241                }
242                let n = unsafe {
243                    libc::recv(sock, buf.as_mut_ptr() as *mut libc::c_void, buf.len(), 0)
244                };
245                if n < 0 {
246                    // EAGAIN / EWOULDBLOCK = timeout, just loop
247                    continue;
248                }
249                let frame = &buf[..n as usize];
250                // Ethernet frame: [0..6] dst, [6..12] src, [12..14] ethertype, [14..] payload
251                if frame.len() < 14 {
252                    continue;
253                }
254                // Fallback MAC filter — catches any self-echo if the kernel
255                // doesn't support PACKET_IGNORE_OUTGOING.
256                if frame[6..12] == mac_address {
257                    continue;
258                }
259                // EtherType is already filtered by the socket, but double-check.
260                if !is_geonet_frame(frame) {
261                    continue;
262                }
263                match &sender_tx {
264                    Some(sender_tx) => {
265                        let mut source = [0u8; 6];
266                        source.copy_from_slice(&frame[6..12]);
267                        let _ = sender_tx.send((frame[14..].to_vec(), source));
268                    }
269                    None => {
270                        let _ = gn_tx.send(frame[14..].to_vec());
271                    }
272                }
273            }
274
275            unsafe {
276                libc::close(sock);
277            }
278        });
279
280        // ── TX threads: GeoNetworking ──► NIC ────────────────────────────────
281        if let Some(unicast_rx) = unicast_rx {
282            let iface = iface_name_tx.clone();
283            thread::spawn(move || transmit_loop(&iface, mac_address, || unicast_rx.recv().ok()));
284        }
285        thread::spawn(move || {
286            transmit_loop(&iface_name_tx, mac_address, || {
287                gn_rx.recv().ok().map(|payload| (payload, [0xFF; 6]))
288            })
289        });
290    }
291}
292
293/// Send `(GN payload, destination MAC)` items until `next` returns `None`
294/// (the router dropped its sender).
295fn transmit_loop(
296    iface_name: &str,
297    mac_address: [u8; 6],
298    mut next: impl FnMut() -> Option<(Vec<u8>, [u8; 6])>,
299) {
300    let Some(interface) = find_interface(iface_name) else {
301        return;
302    };
303    let config = Config {
304        write_timeout: None,
305        ..Config::default()
306    };
307    let Ok(Channel::Ethernet(mut tx, _rx)) = datalink::channel(&interface, config) else {
308        return;
309    };
310    while let Some((gn_payload, dest_mac)) = next() {
311        let frame = build_eth_frame(dest_mac, mac_address, &gn_payload);
312        // send_to returns Option<io::Result<()>>; None means no-op.
313        let _ = tx.send_to(&frame, None);
314    }
315}
316
317// ------------------------------------------------------------------
318// Helper
319// ------------------------------------------------------------------
320
321fn find_interface(name: &str) -> Option<NetworkInterface> {
322    datalink::interfaces().into_iter().find(|i| i.name == name)
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use std::sync::mpsc;
329
330    #[test]
331    fn build_eth_frame_basic() {
332        let dest = [0xFF; 6];
333        let src = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
334        let payload = [0xAA, 0xBB];
335        let frame = build_eth_frame(dest, src, &payload);
336        // 6 dest + 6 src + 2 ethertype + 2 payload = 16
337        assert_eq!(frame.len(), 16);
338        assert_eq!(&frame[0..6], &dest);
339        assert_eq!(&frame[6..12], &src);
340        assert_eq!(&frame[12..14], &ETH_P_GEONET.to_be_bytes());
341        assert_eq!(&frame[14..16], &payload);
342    }
343
344    #[test]
345    fn build_eth_frame_empty_payload() {
346        let frame = build_eth_frame([0; 6], [0; 6], &[]);
347        assert_eq!(frame.len(), 14);
348    }
349
350    #[test]
351    fn is_geonet_frame_valid() {
352        let frame = build_eth_frame([0xFF; 6], [0; 6], &[0xCA, 0xFE]);
353        assert!(is_geonet_frame(&frame));
354    }
355
356    #[test]
357    fn is_geonet_frame_too_short() {
358        assert!(!is_geonet_frame(&[0u8; 13]));
359    }
360
361    #[test]
362    fn is_geonet_frame_wrong_ethertype() {
363        let mut frame = build_eth_frame([0xFF; 6], [0; 6], &[0xCA]);
364        // Overwrite ethertype
365        frame[12] = 0x08;
366        frame[13] = 0x00;
367        assert!(!is_geonet_frame(&frame));
368    }
369
370    #[test]
371    fn raw_link_layer_new() {
372        let (gn_tx, _) = mpsc::channel();
373        let (_, gn_rx) = mpsc::channel();
374        let rll = RawLinkLayer::new(gn_tx, gn_rx, "lo", [0x00; 6]);
375        assert_eq!(rll.iface_name, "lo");
376        assert_eq!(rll.mac_address, [0x00; 6]);
377        assert!(!rll.stop_flag.load(Ordering::Relaxed));
378    }
379
380    #[test]
381    fn raw_link_layer_stop_flag_clone() {
382        let (gn_tx, _) = mpsc::channel();
383        let (_, gn_rx) = mpsc::channel();
384        let rll = RawLinkLayer::new(gn_tx, gn_rx, "eth0", [0xAA; 6]);
385        let flag = rll.stop_flag();
386        flag.store(true, Ordering::Relaxed);
387        assert!(rll.stop_flag.load(Ordering::Relaxed));
388    }
389}