Skip to main content

viva_fake_gige/
resend.rs

1//! Packet resend, as a GigE Vision device answers `PACKETRESEND_CMD`.
2//!
3//! Written with this crate's **own** constants and offsets (ADR-0019), never
4//! the client's encoder: a fake that parsed requests with `viva-gige`'s layout
5//! would agree with any mistake in it. The request payload, from the field
6//! table Wireshark's `packet-gvcp.c` dissects (`dissect_packetresend_cmd`):
7//!
8//! | Bytes | Standard ids (12)              | Extended ids (20, flag `0x10`) |
9//! |-------|--------------------------------|--------------------------------|
10//! | 0–1   | stream channel index           | stream channel index           |
11//! | 2–3   | block id (16 bits)             | reserved                       |
12//! | 4–7   | first packet id (low 24 bits)  | first packet id (32 bits)      |
13//! | 8–11  | last packet id (low 24 bits)   | last packet id (32 bits)       |
14//! | 12–19 | —                              | block id (64 bits)             |
15//!
16//! The command asks for no acknowledgement, and the fake sends none. The
17//! packets go out again from the **stream** socket, byte for byte as first
18//! built, status `0x0000` like the first time; each packet the fake no longer
19//! holds is answered with a header-only GVSP packet of its own, data packet
20//! format, carrying `PACKET_UNAVAILABLE` (`0x800C`), the block id and that
21//! packet's id. That is how an Allied Vision Manta G-125B answered, for a
22//! block it no longer held, a packet past a block's end and a block not yet
23//! sent, wherever the request came from; it held about 23 blocks.
24
25use std::collections::VecDeque;
26use std::net::SocketAddr;
27use std::sync::Arc;
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use tokio::net::UdpSocket;
31
32use crate::gvsp::{Datagram, header_only};
33
34// GVCP vocabulary, imported (ADR-0030).
35pub(crate) use viva_gige::consts::PACKET_RESEND_COMMAND as PACKETRESEND_CMD;
36use viva_gige::consts::PACKET_RESEND_EXTENDED_IDS as EXTENDED_IDS_FLAG;
37/// GVSP status of a packet the device can no longer send.
38pub(crate) const STATUS_PACKET_UNAVAILABLE: u16 = viva_gige::GigeStatus::PacketUnavailable.to_raw();
39/// Packets of the last blocks the fake keeps for resending, by default.
40pub const DEFAULT_RETENTION: usize = 4;
41
42/// One `PACKETRESEND_CMD`, as the fake reads it.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct ResendRequest {
45    /// Stream channel index.
46    pub channel: u16,
47    /// Block id: 16 bits widened, or the 64-bit extended id.
48    pub block_id: u64,
49    /// First packet id asked for.
50    pub first: u32,
51    /// Last packet id asked for, inclusive.
52    pub last: u32,
53    /// Whether the request used the extended-id layout.
54    pub extended_ids: bool,
55}
56
57/// Read a `PACKETRESEND_CMD` payload, or `None` if it is too short for the
58/// layout its flag announces.
59pub fn parse_request(flags: u8, payload: &[u8]) -> Option<ResendRequest> {
60    let u16_at = |at: usize| u16::from_be_bytes([payload[at], payload[at + 1]]);
61    let u32_at = |at: usize| {
62        u32::from_be_bytes([
63            payload[at],
64            payload[at + 1],
65            payload[at + 2],
66            payload[at + 3],
67        ])
68    };
69    if flags & EXTENDED_IDS_FLAG != 0 {
70        if payload.len() < 20 {
71            return None;
72        }
73        let mut block = [0u8; 8];
74        block.copy_from_slice(&payload[12..20]);
75        Some(ResendRequest {
76            channel: u16_at(0),
77            block_id: u64::from_be_bytes(block),
78            first: u32_at(4),
79            last: u32_at(8),
80            extended_ids: true,
81        })
82    } else {
83        if payload.len() < 12 {
84            return None;
85        }
86        Some(ResendRequest {
87            channel: u16_at(0),
88            block_id: u64::from(u16_at(2)),
89            first: u32_at(4) & 0x00FF_FFFF,
90            last: u32_at(8) & 0x00FF_FFFF,
91            extended_ids: false,
92        })
93    }
94}
95
96/// What the fake did with resend requests, counted on the device side.
97#[derive(Debug, Default)]
98pub struct ResendCounters {
99    requests: AtomicU64,
100    packets_resent: AtomicU64,
101    packets_unavailable: AtomicU64,
102}
103
104/// A snapshot of the fake's resend counters.
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
106pub struct ResendStats {
107    /// `PACKETRESEND_CMD`s received, served or not.
108    pub requests: u64,
109    /// Packets sent again.
110    pub packets_resent: u64,
111    /// Packets asked for that the fake no longer held.
112    pub packets_unavailable: u64,
113}
114
115impl ResendCounters {
116    /// Take a snapshot.
117    pub fn snapshot(&self) -> ResendStats {
118        ResendStats {
119            requests: self.requests.load(Ordering::Relaxed),
120            packets_resent: self.packets_resent.load(Ordering::Relaxed),
121            packets_unavailable: self.packets_unavailable.load(Ordering::Relaxed),
122        }
123    }
124}
125
126/// The stream socket and where it sends, as the current acquisition set them.
127#[derive(Debug, Clone)]
128pub(crate) struct StreamPath {
129    pub socket: Arc<UdpSocket>,
130    pub dest: SocketAddr,
131    pub max_on_wire: Option<u32>,
132}
133
134/// The packets of the last few blocks, as built, before any scripted damage.
135#[derive(Debug)]
136pub(crate) struct Retention {
137    capacity: usize,
138    blocks: VecDeque<(u64, Vec<Vec<u8>>)>,
139    path: Option<StreamPath>,
140}
141
142/// How a request is answered: packets to send again, and a header-only
143/// packet for each one the fake no longer holds.
144#[derive(Debug, Default, PartialEq, Eq)]
145pub(crate) struct Answer {
146    pub resend: Vec<Vec<u8>>,
147    pub unavailable: Vec<Vec<u8>>,
148}
149
150impl Retention {
151    pub fn new(capacity: usize) -> Self {
152        Self {
153            capacity,
154            blocks: VecDeque::new(),
155            path: None,
156        }
157    }
158
159    pub fn set_path(&mut self, path: StreamPath) {
160        self.path = Some(path);
161    }
162
163    pub fn path(&self) -> Option<StreamPath> {
164        self.path.clone()
165    }
166
167    /// Keep a block's datagrams, indexed by packet id, evicting the oldest.
168    pub fn retain(&mut self, block_id: u64, datagrams: &[Datagram]) {
169        if self.capacity == 0 {
170            return;
171        }
172        let mut by_id: Vec<Vec<u8>> = Vec::new();
173        for d in datagrams {
174            let at = d.packet_id as usize;
175            if by_id.len() <= at {
176                by_id.resize(at + 1, Vec::new());
177            }
178            by_id[at] = d.bytes.clone();
179        }
180        self.blocks.retain(|(id, _)| *id != block_id);
181        while self.blocks.len() >= self.capacity {
182            self.blocks.pop_front();
183        }
184        self.blocks.push_back((block_id, by_id));
185    }
186
187    /// Answer `request`: the packets still held, and an unavailable packet
188    /// for each that is not.
189    pub fn answer(&self, request: &ResendRequest) -> Answer {
190        let mut answer = Answer::default();
191        if request.first > request.last {
192            return answer;
193        }
194        let held = self
195            .blocks
196            .iter()
197            .find(|(id, _)| *id == request.block_id)
198            .map(|(_, packets)| packets);
199        for id in request.first..=request.last {
200            match held
201                .and_then(|p| p.get(id as usize))
202                .filter(|b| !b.is_empty())
203            {
204                Some(bytes) => answer.resend.push(bytes.clone()),
205                None => answer.unavailable.push(header_only(
206                    request.block_id,
207                    request.extended_ids,
208                    id,
209                    STATUS_PACKET_UNAVAILABLE,
210                )),
211            }
212        }
213        answer
214    }
215}
216
217/// Serve one request: count it, and if the device supports resend, send what
218/// it still holds from the stream socket.
219pub(crate) async fn serve(
220    supported: bool,
221    retention: &std::sync::Mutex<Retention>,
222    counters: &ResendCounters,
223    flags: u8,
224    payload: &[u8],
225) {
226    counters.requests.fetch_add(1, Ordering::Relaxed);
227    if !supported {
228        tracing::debug!("PACKETRESEND_CMD ignored: the device does not support resend");
229        return;
230    }
231    let Some(request) = parse_request(flags, payload) else {
232        tracing::debug!(len = payload.len(), "malformed PACKETRESEND_CMD");
233        return;
234    };
235    let (answer, path) = match retention.lock() {
236        Ok(retention) => (retention.answer(&request), retention.path()),
237        Err(_) => return,
238    };
239    let Some(path) = path else {
240        return;
241    };
242    tracing::debug!(?request, resent = answer.resend.len(), "PACKETRESEND_CMD");
243    for packet in &answer.resend {
244        let on_wire = packet.len() + 28;
245        if path.max_on_wire.is_some_and(|max| on_wire > max as usize) {
246            continue;
247        }
248        if path.socket.send_to(packet, path.dest).await.is_ok() {
249            counters.packets_resent.fetch_add(1, Ordering::Relaxed);
250        }
251    }
252    for packet in &answer.unavailable {
253        counters.packets_unavailable.fetch_add(1, Ordering::Relaxed);
254        let _ = path.socket.send_to(packet, path.dest).await;
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use crate::gvsp::{BlockSpec, block_datagrams};
262
263    /// The standard request, written out from the field table.
264    #[test]
265    fn a_standard_request_is_read_at_its_own_offsets() {
266        #[rustfmt::skip]
267        let payload = [
268            0x00, 0x02,             // channel 2
269            0x12, 0x34,             // block 0x1234
270            0xFF, 0x00, 0x00, 0x05, // first 5 (the top byte is not part of the id)
271            0x00, 0x00, 0x00, 0x09, // last 9
272        ];
273        assert_eq!(
274            parse_request(0x00, &payload),
275            Some(ResendRequest {
276                channel: 2,
277                block_id: 0x1234,
278                first: 5,
279                last: 9,
280                extended_ids: false,
281            })
282        );
283        assert_eq!(parse_request(0x00, &payload[..11]), None);
284    }
285
286    #[test]
287    fn an_extended_request_is_read_at_its_own_offsets() {
288        #[rustfmt::skip]
289        let payload = [
290            0x00, 0x00,             // channel 0
291            0x00, 0x00,             // reserved
292            0x01, 0x00, 0x00, 0x05, // first 0x0100_0005: all 32 bits
293            0x01, 0x00, 0x00, 0x07, // last
294            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, // block 2^32 + 2
295        ];
296        assert_eq!(
297            parse_request(0x10, &payload),
298            Some(ResendRequest {
299                channel: 0,
300                block_id: (1 << 32) + 2,
301                first: 0x0100_0005,
302                last: 0x0100_0007,
303                extended_ids: true,
304            })
305        );
306        assert_eq!(parse_request(0x10, &payload[..19]), None);
307    }
308
309    fn block(id: u64) -> Vec<Datagram> {
310        block_datagrams(
311            &BlockSpec::image(id, 10, 1, 0x0108_0001, 28 + 8 + 4),
312            &[7u8; 10],
313        )
314    }
315
316    fn request(block_id: u64, first: u32, last: u32) -> ResendRequest {
317        ResendRequest {
318            channel: 0,
319            block_id,
320            first,
321            last,
322            extended_ids: false,
323        }
324    }
325
326    #[test]
327    fn a_retained_range_is_sent_again_as_built() {
328        let mut retention = Retention::new(2);
329        let datagrams = block(1);
330        retention.retain(1, &datagrams);
331        let answer = retention.answer(&request(1, 1, 2));
332        assert_eq!(
333            answer.resend,
334            vec![datagrams[1].bytes.clone(), datagrams[2].bytes.clone()]
335        );
336        assert!(answer.unavailable.is_empty());
337    }
338
339    #[test]
340    fn a_block_beyond_retention_is_answered_unavailable() {
341        let mut retention = Retention::new(2);
342        for id in 1..=3 {
343            retention.retain(id, &block(id));
344        }
345        let answer = retention.answer(&request(1, 2, 3));
346        assert!(answer.resend.is_empty());
347        // One per packet, as the Manta G-125B answered.
348        assert_eq!(
349            answer.unavailable,
350            [
351                vec![0x80, 0x0C, 0x00, 0x01, 0x03, 0x00, 0x00, 0x02],
352                vec![0x80, 0x0C, 0x00, 0x01, 0x03, 0x00, 0x00, 0x03],
353            ]
354        );
355        // Block 3 is still held.
356        assert_eq!(retention.answer(&request(3, 1, 1)).resend.len(), 1);
357    }
358}