rustflexstack/facilities/ca_basic_service/
cam_reception.rs1use super::cam_coder::{Cam, CamCoder};
17use super::cam_ldm_adaptation::CABasicServiceLDM;
18use crate::btp::router::BTPRouterHandle;
19use crate::btp::service_access_point::BTPDataIndication;
20use crate::facilities::local_dynamic_map::LdmHandle;
21use std::sync::mpsc::{self, Sender};
22use std::sync::{Arc, RwLock};
23use std::thread;
24use std::time::{SystemTime, UNIX_EPOCH};
25
26pub const CAM_ITS_AID: u64 = 36;
28
29pub type ApplicationCallback = Arc<dyn Fn(&Cam, u64) + Send + Sync>;
31
32#[derive(Clone)]
34pub struct CAMReceptionManagement {
35 pub cam_coder: CamCoder,
36 pub btp_handle: BTPRouterHandle,
37 pub ca_basic_service_ldm: Option<CABasicServiceLDM>,
38 application_callbacks: Arc<RwLock<Vec<ApplicationCallback>>>,
39 cam_tx: Option<Sender<Cam>>,
40}
41
42impl CAMReceptionManagement {
43 pub fn new(
45 btp_handle: BTPRouterHandle,
46 cam_coder: CamCoder,
47 ca_basic_service_ldm: Option<CABasicServiceLDM>,
48 ) -> Self {
49 CAMReceptionManagement {
50 cam_coder,
51 btp_handle,
52 ca_basic_service_ldm,
53 application_callbacks: Arc::new(RwLock::new(Vec::new())),
54 cam_tx: None,
55 }
56 }
57
58 pub fn new_with_channel(
60 btp_handle: BTPRouterHandle,
61 cam_coder: CamCoder,
62 ca_basic_service_ldm: Option<CABasicServiceLDM>,
63 cam_tx: Sender<Cam>,
64 ) -> Self {
65 CAMReceptionManagement {
66 cam_coder,
67 btp_handle,
68 ca_basic_service_ldm,
69 application_callbacks: Arc::new(RwLock::new(Vec::new())),
70 cam_tx: Some(cam_tx),
71 }
72 }
73
74 pub fn add_application_callback<F>(&self, callback: F)
79 where
80 F: Fn(&Cam, u64) + Send + Sync + 'static,
81 {
82 if let Ok(mut cbs) = self.application_callbacks.write() {
83 cbs.push(Arc::new(callback));
84 }
85 }
86
87 pub fn application_callbacks_len(&self) -> usize {
89 self.application_callbacks
90 .read()
91 .map(|cbs| cbs.len())
92 .unwrap_or(0)
93 }
94
95 pub fn reception_callback(&self, btp_indication: &BTPDataIndication) -> Result<Cam, String> {
100 if btp_indication
103 .gn_its_aid
104 .is_some_and(|aid| aid != CAM_ITS_AID)
105 {
106 return Err("Secured CAM with another ITS-AID".to_string());
107 }
108 let cam = match self.cam_coder.decode(&btp_indication.data) {
109 Ok(c) => c,
110 Err(e) => {
111 return Err(e);
112 }
113 };
114
115 if !super::cam_ssp::ssp_consistent(
118 btp_indication.gn_permissions.as_deref(),
119 &cam,
120 Some(&self.cam_coder),
121 ) {
122 return Err("CAM content not permitted by the signer's SSP".to_string());
123 }
124
125 let now_ms = SystemTime::now()
126 .duration_since(UNIX_EPOCH)
127 .unwrap_or_default()
128 .as_millis() as u64;
129
130 let utc_timestamp = cam
131 .cam
132 .generation_delta_time
133 .as_timestamp_in_certain_point(now_ms);
134
135 if let Some(ref ldm) = self.ca_basic_service_ldm {
136 let _ = ldm.add_provider_data_to_ldm(&cam);
137 }
138
139 if let Ok(callbacks) = self.application_callbacks.read() {
140 for cb in callbacks.iter() {
141 let cb = Arc::clone(cb);
142 let cam_ref = &cam;
143 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
144 cb(cam_ref, utc_timestamp);
145 }));
146 }
147 }
148
149 if let Some(ref tx) = self.cam_tx {
150 let _ = tx.send(cam.clone());
151 }
152
153 Ok(cam)
154 }
155
156 pub fn spawn(
165 btp_handle: BTPRouterHandle,
166 coder: CamCoder,
167 cam_tx: Sender<Cam>,
168 ldm: Option<LdmHandle>,
169 ) {
170 let ca_basic_service_ldm = ldm.map(|l| CABasicServiceLDM::new(l, 5));
171 let crm = CAMReceptionManagement::new_with_channel(
172 btp_handle.clone(),
173 coder,
174 ca_basic_service_ldm,
175 cam_tx,
176 );
177
178 let (ind_tx, ind_rx) = mpsc::channel::<BTPDataIndication>();
179 btp_handle.register_port(2001, ind_tx);
180
181 thread::spawn(move || {
182 while let Ok(indication) = ind_rx.recv() {
183 let _ = crm.reception_callback(&indication);
184 }
185 });
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use crate::facilities::ca_basic_service::cam_coder::generate_white_cam_static;
193 use crate::facilities::local_dynamic_map::LdmFacility;
194 use crate::geonet::mib::Mib;
195 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
196
197 fn make_test_indication(data: Vec<u8>) -> BTPDataIndication {
198 let len = data.len() as u16;
199 BTPDataIndication {
200 destination_port: 2001,
201 length: len,
202 data,
203 ..BTPDataIndication::new()
204 }
205 }
206
207 #[test]
208 fn test_crm_init_stores_components() {
209 let (btp_handle, _) = crate::btp::router::Router::spawn(Mib::new());
210 let coder = CamCoder::new();
211 let ldm = LdmFacility::new(415_520_000, 21_340_000, 5_000.0);
212 let ldm_adapter = CABasicServiceLDM::new(ldm, 5);
213
214 let crm = CAMReceptionManagement::new(btp_handle, coder, Some(ldm_adapter));
215 assert!(crm.ca_basic_service_ldm.is_some());
216 assert_eq!(crm.application_callbacks_len(), 0);
217 }
218
219 #[test]
220 fn test_reception_callback_decodes_valid_cam() {
221 let (btp_handle, _) = crate::btp::router::Router::spawn(Mib::new());
222 let coder = CamCoder::new();
223 let crm = CAMReceptionManagement::new(btp_handle, coder.clone(), None);
224
225 let white_cam = generate_white_cam_static();
226 let encoded = coder.encode(&white_cam).unwrap();
227 let ind = make_test_indication(encoded);
228
229 let res = crm.reception_callback(&ind);
230 assert!(res.is_ok());
231 let received = res.unwrap();
232 assert_eq!(received.header.protocol_version.0, 2);
233 }
234
235 #[test]
236 fn test_reception_callback_updates_ldm() {
237 let (btp_handle, _) = crate::btp::router::Router::spawn(Mib::new());
238 let coder = CamCoder::new();
239 let ldm = LdmFacility::new(415_520_000, 21_340_000, 50_000.0);
240 let ldm_adapter = CABasicServiceLDM::new(ldm, 5);
241 let crm = CAMReceptionManagement::new(btp_handle, coder.clone(), Some(ldm_adapter));
242
243 let white_cam = generate_white_cam_static();
244 let encoded = coder.encode(&white_cam).unwrap();
245 let ind = make_test_indication(encoded);
246
247 let res = crm.reception_callback(&ind);
248 assert!(res.is_ok());
249 }
250
251 #[test]
252 fn test_decode_exception_does_not_panic_or_call_callbacks() {
253 let (btp_handle, _) = crate::btp::router::Router::spawn(Mib::new());
254 let coder = CamCoder::new();
255 let crm = CAMReceptionManagement::new(btp_handle, coder, None);
256
257 let called = Arc::new(AtomicBool::new(false));
258 let called_clone = Arc::clone(&called);
259 crm.add_application_callback(move |_, _| {
260 called_clone.store(true, Ordering::SeqCst);
261 });
262
263 let ind = make_test_indication(vec![0xFF, 0xFF]);
265 let res = crm.reception_callback(&ind);
266 assert!(res.is_err());
267 assert!(!called.load(Ordering::SeqCst));
268 }
269
270 #[test]
271 fn test_application_callbacks_called_and_faulty_callback_isolated() {
272 let (btp_handle, _) = crate::btp::router::Router::spawn(Mib::new());
273 let coder = CamCoder::new();
274 let crm = CAMReceptionManagement::new(btp_handle, coder.clone(), None);
275
276 let count = Arc::new(AtomicUsize::new(0));
277
278 let c1 = Arc::clone(&count);
279 crm.add_application_callback(move |_, _| {
280 c1.fetch_add(1, Ordering::SeqCst);
281 });
282
283 crm.add_application_callback(move |_, _| {
285 panic!("Intentional test panic in callback");
286 });
287
288 let c2 = Arc::clone(&count);
289 crm.add_application_callback(move |_, _| {
290 c2.fetch_add(10, Ordering::SeqCst);
291 });
292
293 let white_cam = generate_white_cam_static();
294 let encoded = coder.encode(&white_cam).unwrap();
295 let ind = make_test_indication(encoded);
296
297 let res = crm.reception_callback(&ind);
298 assert!(res.is_ok());
299 assert_eq!(count.load(Ordering::SeqCst), 11);
301 }
302}