Skip to main content

rustflexstack/btp/
router.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! BTP (Basic Transport Protocol) Router — ETSI EN 302 636-5-1.
5//!
6//! The BTP router sits between the Facilities layer (CAM, DENM, …) and the
7//! GeoNetworking layer.  It adds/strips 4-byte BTP-A or BTP-B headers and
8//! dispatches received packets to registered port callbacks.
9//!
10//! Like the GN router, this is implemented as a single-threaded actor.
11//! All interaction goes through the [`BTPRouterHandle`].
12//!
13//! # BTP-A vs BTP-B
14//! - **BTP-A** (`CommonNH::BtpA`): carries a *source port* field.  Used for
15//!   connection-oriented / acknowledged communication.
16//! - **BTP-B** (`CommonNH::BtpB`): carries a *destination port info* field
17//!   instead of a source port.  Used for connectionless broadcast (CAM, DENM).
18
19use std::collections::HashMap;
20use std::convert::TryInto;
21use std::sync::mpsc::{self, Receiver, Sender};
22use std::thread;
23
24use super::btp_header::{BTPAHeader, BTPBHeader};
25use super::service_access_point::{BTPDataIndication, BTPDataRequest};
26use crate::geonet::mib::{GnSecurity, Mib};
27use crate::geonet::service_access_point::{CommonNH, HeaderType};
28use crate::geonet::service_access_point::{GNDataIndication, GNDataRequest};
29
30// ------------------------------------------------------------------
31// Message types
32// ------------------------------------------------------------------
33
34pub enum BTPRouterInput {
35    BTPDataRequest(BTPDataRequest),
36    GNDataIndication(GNDataIndication),
37    RegisterPort(u16, Sender<BTPDataIndication>),
38    /// A port whose service accepts unsecured packets with itsGnSecurity ENABLED.
39    RegisterUnsecuredPort(u16, Sender<BTPDataIndication>),
40    UnregisterPort(u16),
41    Shutdown,
42}
43
44// ------------------------------------------------------------------
45// Router and handle
46// ------------------------------------------------------------------
47
48pub struct Router {
49    mib: Mib,
50    port_callbacks: HashMap<u16, Sender<BTPDataIndication>>,
51    /// Ports open to unsecured packets although itsGnSecurity is ENABLED (the
52    /// CRL / CTL broadcast, ETSI TS 103 601 V2.1.1 clause 5.4.2).
53    unsecured_ports: std::collections::HashSet<u16>,
54    gn_request_tx: Sender<GNDataRequest>,
55}
56
57#[derive(Clone)]
58pub struct BTPRouterHandle {
59    input_tx: Sender<BTPRouterInput>,
60}
61
62impl BTPRouterHandle {
63    pub fn send_btp_data_request(&self, request: BTPDataRequest) {
64        let _ = self.input_tx.send(BTPRouterInput::BTPDataRequest(request));
65    }
66
67    pub fn send_gn_data_indication(&self, indication: GNDataIndication) {
68        let _ = self
69            .input_tx
70            .send(BTPRouterInput::GNDataIndication(indication));
71    }
72
73    pub fn register_port(&self, port: u16, callback_tx: Sender<BTPDataIndication>) {
74        let _ = self
75            .input_tx
76            .send(BTPRouterInput::RegisterPort(port, callback_tx));
77    }
78
79    /// Register `port` for a service whose payload authenticates itself: its
80    /// unsecured packets are delivered although itsGnSecurity is ENABLED (an
81    /// unsecured packet to another port is then discarded).
82    pub fn register_port_accepting_unsecured(
83        &self,
84        port: u16,
85        callback_tx: Sender<BTPDataIndication>,
86    ) {
87        let _ = self
88            .input_tx
89            .send(BTPRouterInput::RegisterUnsecuredPort(port, callback_tx));
90    }
91
92    pub fn unregister_port(&self, port: u16) {
93        let _ = self.input_tx.send(BTPRouterInput::UnregisterPort(port));
94    }
95
96    pub fn shutdown(self) {
97        let _ = self.input_tx.send(BTPRouterInput::Shutdown);
98    }
99}
100
101// ------------------------------------------------------------------
102// Router implementation
103// ------------------------------------------------------------------
104
105impl Router {
106    pub fn new(mib: Mib, gn_request_tx: Sender<GNDataRequest>) -> Self {
107        Router {
108            mib,
109            port_callbacks: HashMap::new(),
110            unsecured_ports: Default::default(),
111            gn_request_tx,
112        }
113    }
114
115    pub fn spawn(mib: Mib) -> (BTPRouterHandle, Receiver<GNDataRequest>) {
116        let (input_tx, input_rx) = mpsc::channel::<BTPRouterInput>();
117        let (gn_request_tx, gn_request_rx) = mpsc::channel::<GNDataRequest>();
118
119        thread::spawn(move || {
120            let mut router = Router::new(mib, gn_request_tx);
121            router.run(input_rx);
122        });
123
124        let handle = BTPRouterHandle { input_tx };
125        (handle, gn_request_rx)
126    }
127
128    fn run(&mut self, input_rx: Receiver<BTPRouterInput>) {
129        loop {
130            match input_rx.recv() {
131                Ok(BTPRouterInput::BTPDataRequest(req)) => {
132                    self.btp_data_request(req);
133                }
134                Ok(BTPRouterInput::GNDataIndication(ind)) => {
135                    self.btp_data_indication(ind);
136                }
137                Ok(BTPRouterInput::RegisterPort(port, tx)) => {
138                    self.port_callbacks.insert(port, tx);
139                }
140                Ok(BTPRouterInput::RegisterUnsecuredPort(port, tx)) => {
141                    self.port_callbacks.insert(port, tx);
142                    self.unsecured_ports.insert(port);
143                }
144                Ok(BTPRouterInput::UnregisterPort(port)) => {
145                    self.port_callbacks.remove(&port);
146                    self.unsecured_ports.remove(&port);
147                }
148                Ok(BTPRouterInput::Shutdown) | Err(_) => break,
149            }
150        }
151    }
152
153    // ------------------------------------------------------------------
154    // Transmit path
155    // ------------------------------------------------------------------
156
157    fn btp_data_request(&mut self, request: BTPDataRequest) {
158        let header_bytes: [u8; 4] = match request.btp_type {
159            CommonNH::BtpA => BTPAHeader::initialize_with_request(&request).encode(),
160            CommonNH::BtpB => BTPBHeader::initialize_with_request(&request).encode(),
161            _ => {
162                return;
163            }
164        };
165
166        let payload: Vec<u8> = header_bytes
167            .iter()
168            .copied()
169            .chain(request.data.iter().copied())
170            .collect();
171
172        let gn_request = GNDataRequest {
173            upper_protocol_entity: request.btp_type.clone(),
174            packet_transport_type: request.gn_packet_transport_type.clone(),
175            communication_profile: request.communication_profile.clone(),
176            traffic_class: request.traffic_class,
177            security_profile: request.security_profile,
178            its_aid: request.its_aid,
179            security_permissions: request.security_permissions.clone(),
180            max_hop_limit: request.gn_max_hop_limit,
181            max_packet_lifetime: request.gn_max_packet_lifetime,
182            // EN 302 636-5-1 table 6: Destination address = GN Destination address
183            // (GeoUnicast); `destination` takes precedence when set.
184            destination: request
185                .destination
186                .or(
187                    (request.gn_packet_transport_type.header_type == HeaderType::GeoUnicast)
188                        .then_some(request.gn_destination_address),
189                ),
190            length: payload.len() as u16,
191            area: request.gn_area,
192            data: payload,
193        };
194        let _ = self.gn_request_tx.send(gn_request);
195    }
196
197    // ------------------------------------------------------------------
198    // Receive path
199    // ------------------------------------------------------------------
200
201    fn btpb_data_indication(&mut self, gn_ind: GNDataIndication) {
202        if gn_ind.data.len() < 4 {
203            return;
204        }
205        let btp_bytes: [u8; 4] = gn_ind.data[0..4].try_into().unwrap();
206        let header = BTPBHeader::decode(btp_bytes);
207
208        let indication = BTPDataIndication::initialize_with_gn_data_indication(&gn_ind)
209            .set_destination_port_and_info(header.destination_port, header.destination_port_info);
210
211        self.deliver(&gn_ind, indication);
212    }
213
214    fn btpa_data_indication(&mut self, gn_ind: GNDataIndication) {
215        if gn_ind.data.len() < 4 {
216            return;
217        }
218        let btp_bytes: [u8; 4] = gn_ind.data[0..4].try_into().unwrap();
219        let header = BTPAHeader::decode(btp_bytes);
220
221        let mut indication = BTPDataIndication::initialize_with_gn_data_indication(&gn_ind)
222            .set_destination_port_and_info(header.destination_port(), 0);
223        indication.source_port = header.source_port();
224
225        self.deliver(&gn_ind, indication);
226    }
227
228    /// Hand `indication` to the service of its port. With itsGnSecurity ENABLED an
229    /// unsecured packet reaches only a port open to unsecured packets.
230    fn deliver(&self, gn_ind: &GNDataIndication, indication: BTPDataIndication) {
231        if gn_ind.security.is_none()
232            && self.mib.itsGnSecurity == GnSecurity::Enabled
233            && !self.unsecured_ports.contains(&indication.destination_port)
234        {
235            return;
236        }
237        if let Some(tx) = self.port_callbacks.get(&indication.destination_port) {
238            let _ = tx.send(indication);
239        }
240    }
241
242    fn btp_data_indication(&mut self, gn_ind: GNDataIndication) {
243        match gn_ind.upper_protocol_entity {
244            CommonNH::BtpB => self.btpb_data_indication(gn_ind),
245            CommonNH::BtpA => self.btpa_data_indication(gn_ind),
246            _ => {}
247        }
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::btp::btp_header::{BTPAHeader, BTPBHeader};
255    use crate::geonet::position_vector::LongPositionVector;
256    use crate::geonet::service_access_point::{
257        CommonNH, GNDataIndication, HeaderSubType, HeaderType, PacketTransportType,
258        TopoBroadcastHST, TrafficClass, UnspecifiedHST,
259    };
260    use std::sync::mpsc;
261    use std::time::Duration;
262
263    fn make_mib() -> Mib {
264        Mib::new()
265    }
266
267    fn make_gn_data_indication(nh: CommonNH, data: Vec<u8>) -> GNDataIndication {
268        GNDataIndication {
269            upper_protocol_entity: nh,
270            packet_transport_type: PacketTransportType {
271                header_type: HeaderType::Tsb,
272                header_sub_type: HeaderSubType::TopoBroadcast(TopoBroadcastHST::SingleHop),
273            },
274            source_position_vector: LongPositionVector::decode([0u8; 24]),
275            traffic_class: TrafficClass {
276                scf: false,
277                channel_offload: false,
278                tc_id: 0,
279            },
280            destination_area: None,
281            destination: None,
282            remaining_packet_lifetime: None,
283            remaining_hop_limit: None,
284            security: None,
285            length: data.len() as u16,
286            data,
287        }
288    }
289
290    #[test]
291    fn spawn_and_shutdown() {
292        let mib = make_mib();
293        let (handle, _gn_rx) = Router::spawn(mib);
294        handle.shutdown();
295    }
296
297    #[test]
298    fn btpb_request_produces_gn_request() {
299        let mib = make_mib();
300        let (handle, gn_rx) = Router::spawn(mib);
301
302        let mut req = BTPDataRequest::new();
303        req.btp_type = CommonNH::BtpB;
304        req.destination_port = 2001;
305        req.destination_port_info = 0;
306        req.gn_packet_transport_type = PacketTransportType {
307            header_type: HeaderType::Tsb,
308            header_sub_type: HeaderSubType::TopoBroadcast(TopoBroadcastHST::SingleHop),
309        };
310        req.data = vec![0xCA, 0xFE];
311        req.length = 2;
312
313        handle.send_btp_data_request(req);
314
315        let gn_req = gn_rx.recv_timeout(Duration::from_secs(1)).unwrap();
316        // Payload should be 4 (BTP-B header) + 2 (data) = 6 bytes
317        assert_eq!(gn_req.data.len(), 6);
318        // First two bytes should be destination port 2001 = 0x07D1
319        assert_eq!(gn_req.data[0], 0x07);
320        assert_eq!(gn_req.data[1], 0xD1);
321        // Next two bytes — port info = 0
322        assert_eq!(gn_req.data[2], 0x00);
323        assert_eq!(gn_req.data[3], 0x00);
324        // Payload
325        assert_eq!(gn_req.data[4], 0xCA);
326        assert_eq!(gn_req.data[5], 0xFE);
327
328        handle.shutdown();
329    }
330
331    /// Destination port, destination port info and payload
332    /// of a BTP-B packet built by the router (EN 302 636-5-1 clause 7.3.2).
333    #[test]
334    fn btpb_request_with_destination_port_info() {
335        let mib = make_mib();
336        let (handle, gn_rx) = Router::spawn(mib);
337
338        let mut req = BTPDataRequest::new();
339        req.btp_type = CommonNH::BtpB;
340        req.destination_port = 2001;
341        req.destination_port_info = 0x1234;
342        req.gn_packet_transport_type = PacketTransportType {
343            header_type: HeaderType::Tsb,
344            header_sub_type: HeaderSubType::TopoBroadcast(TopoBroadcastHST::SingleHop),
345        };
346        req.data = vec![0xCA, 0xFE];
347        req.length = 2;
348
349        handle.send_btp_data_request(req);
350
351        let gn_req = gn_rx.recv_timeout(Duration::from_secs(1)).unwrap();
352        assert_eq!(gn_req.upper_protocol_entity, CommonNH::BtpB);
353        assert_eq!(gn_req.data, vec![0x07, 0xD1, 0x12, 0x34, 0xCA, 0xFE]);
354
355        handle.shutdown();
356    }
357
358    #[test]
359    fn btpa_request_produces_gn_request() {
360        let mib = make_mib();
361        let (handle, gn_rx) = Router::spawn(mib);
362
363        let mut req = BTPDataRequest::new();
364        req.btp_type = CommonNH::BtpA;
365        req.destination_port = 2001;
366        req.source_port = 3000;
367        req.gn_packet_transport_type = PacketTransportType {
368            header_type: HeaderType::GeoUnicast,
369            header_sub_type: HeaderSubType::Unspecified(UnspecifiedHST::Unspecified),
370        };
371        req.data = vec![0xDE, 0xAD];
372        req.length = 2;
373
374        handle.send_btp_data_request(req);
375
376        let gn_req = gn_rx.recv_timeout(Duration::from_secs(1)).unwrap();
377        assert_eq!(gn_req.data.len(), 6);
378        // BTP-A header: dest port (2001) + source port (3000)
379        let btpa = BTPAHeader::decode(gn_req.data[0..4].try_into().unwrap());
380        assert_eq!(btpa.destination_port(), 2001);
381        assert_eq!(btpa.source_port(), 3000);
382
383        handle.shutdown();
384    }
385
386    /// With itsGnSecurity ENABLED an unsecured packet (no security indication)
387    /// reaches only a port registered with `register_port_accepting_unsecured`
388    /// (the CRL / CTL broadcast, ETSI TS 103 601 V2.1.1 clause 5.4.2).
389    #[test]
390    fn unsecured_packet_only_to_ports_open_to_it() {
391        let mut mib = make_mib();
392        mib.itsGnSecurity = GnSecurity::Enabled;
393        let (handle, _gn_rx) = Router::spawn(mib);
394        let (closed_tx, closed_rx) = mpsc::channel();
395        let (open_tx, open_rx) = mpsc::channel();
396        handle.register_port(2001, closed_tx);
397        handle.register_port_accepting_unsecured(2015, open_tx);
398        for port in [2001u16, 2015] {
399            let mut payload = BTPBHeader {
400                destination_port: port,
401                destination_port_info: 0,
402            }
403            .encode()
404            .to_vec();
405            payload.push(0xCC);
406            handle.send_gn_data_indication(make_gn_data_indication(CommonNH::BtpB, payload));
407        }
408        assert!(open_rx.recv_timeout(Duration::from_secs(1)).is_ok());
409        assert!(closed_rx.recv_timeout(Duration::from_millis(200)).is_err());
410        handle.shutdown();
411    }
412
413    #[test]
414    fn btpb_indication_dispatches_to_registered_port() {
415        let mib = make_mib();
416        let (handle, _gn_rx) = Router::spawn(mib);
417
418        // Register a callback on port 2001
419        let (port_tx, port_rx) = mpsc::channel();
420        handle.register_port(2001, port_tx);
421
422        // Small sleep to let registration take effect
423        std::thread::sleep(Duration::from_millis(50));
424
425        // Build a GN indication with BTP-B header for port 2001
426        let btpb = BTPBHeader {
427            destination_port: 2001,
428            destination_port_info: 0,
429        };
430        let mut payload = btpb.encode().to_vec();
431        payload.extend_from_slice(&[0xAA, 0xBB]);
432
433        let gn_ind = make_gn_data_indication(CommonNH::BtpB, payload);
434        handle.send_gn_data_indication(gn_ind);
435
436        let ind = port_rx.recv_timeout(Duration::from_secs(1)).unwrap();
437        assert_eq!(ind.destination_port, 2001);
438        assert_eq!(ind.data, vec![0xAA, 0xBB]);
439
440        handle.shutdown();
441    }
442
443    #[test]
444    fn btpa_indication_dispatches_to_registered_port() {
445        let mib = make_mib();
446        let (handle, _gn_rx) = Router::spawn(mib);
447
448        let (port_tx, port_rx) = mpsc::channel();
449        handle.register_port(2001, port_tx);
450        std::thread::sleep(Duration::from_millis(50));
451
452        let btpa = BTPAHeader::decode([
453            (2001u16 >> 8) as u8,
454            (2001u16 & 0xFF) as u8,
455            (5000u16 >> 8) as u8,
456            (5000u16 & 0xFF) as u8,
457        ]);
458        let mut payload = btpa.encode().to_vec();
459        payload.extend_from_slice(&[0xCC, 0xDD]);
460
461        let gn_ind = make_gn_data_indication(CommonNH::BtpA, payload);
462        handle.send_gn_data_indication(gn_ind);
463
464        let ind = port_rx.recv_timeout(Duration::from_secs(1)).unwrap();
465        assert_eq!(ind.destination_port, 2001);
466        assert_eq!(ind.source_port, 5000);
467        assert_eq!(ind.data, vec![0xCC, 0xDD]);
468
469        handle.shutdown();
470    }
471
472    #[test]
473    fn unregister_port_stops_dispatch() {
474        let mib = make_mib();
475        let (handle, _gn_rx) = Router::spawn(mib);
476
477        let (port_tx, port_rx) = mpsc::channel();
478        handle.register_port(2001, port_tx);
479        std::thread::sleep(Duration::from_millis(50));
480
481        handle.unregister_port(2001);
482        std::thread::sleep(Duration::from_millis(50));
483
484        let btpb = BTPBHeader {
485            destination_port: 2001,
486            destination_port_info: 0,
487        };
488        let gn_ind = make_gn_data_indication(CommonNH::BtpB, btpb.encode().to_vec());
489        handle.send_gn_data_indication(gn_ind);
490
491        // Should NOT receive anything
492        assert!(port_rx.recv_timeout(Duration::from_millis(200)).is_err());
493
494        handle.shutdown();
495    }
496
497    #[test]
498    fn indication_with_no_registered_port_does_not_crash() {
499        let mib = make_mib();
500        let (handle, _gn_rx) = Router::spawn(mib);
501
502        let btpb = BTPBHeader {
503            destination_port: 9999,
504            destination_port_info: 0,
505        };
506        let gn_ind = make_gn_data_indication(CommonNH::BtpB, btpb.encode().to_vec());
507        handle.send_gn_data_indication(gn_ind);
508
509        std::thread::sleep(Duration::from_millis(100));
510        handle.shutdown();
511    }
512}