Skip to main content

viva_fake_gige/
gvcp_server.rs

1//! GVCP control channel server: discovery + GenCP register read/write.
2
3use std::collections::{HashMap, HashSet};
4use std::net::{Ipv4Addr, SocketAddr};
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
7use std::time::Duration;
8
9use bytes::{BufMut, BytesMut};
10use tokio::net::UdpSocket;
11use tokio::sync::{Mutex, Notify, oneshot};
12use tokio::task::JoinSet;
13use tracing::{debug, trace, warn};
14
15use crate::registers::RegisterMap;
16use crate::resend::{self, PACKETRESEND_CMD, ResendCounters, Retention};
17
18// GVCP's opcodes and key byte are vocabulary, imported from the transport
19// crates (ADR-0030); their values are pinned to the specification by
20// `viva-gige`'s own literal table. How the fake answers each command is its
21// own reading of the specification.
22use viva_gencp::{OpCode, StatusCode};
23use viva_gige::consts::{
24    ACTION_ACK, ACTION_COMMAND as ACTION_CMD, DISCOVERY_ACK, DISCOVERY_COMMAND as DISCOVERY_CMD,
25    FORCEIP_ACK, FORCEIP_COMMAND as FORCEIP_CMD, GVCP_CMD_KEY, PENDING_ACK,
26};
27
28const READREG_CMD: u16 = OpCode::ReadRegister.command_code();
29const WRITEREG_CMD: u16 = OpCode::WriteRegister.command_code();
30const READMEM_CMD: u16 = OpCode::ReadMem.command_code();
31const WRITEMEM_CMD: u16 = OpCode::WriteMem.command_code();
32const READREG_ACK: u16 = OpCode::ReadRegister.ack_code();
33const WRITEREG_ACK: u16 = OpCode::WriteRegister.ack_code();
34const READMEM_ACK: u16 = OpCode::ReadMem.ack_code();
35const WRITEMEM_ACK: u16 = OpCode::WriteMem.ack_code();
36
37/// Action keys the fake accepts. A command whose keys do not match is ignored
38/// without an acknowledgement, which is how a real device behaves — the command
39/// is broadcast to every camera on the subnet and only the addressed group acts.
40pub const FAKE_DEVICE_KEY: u32 = 0x0000_0042;
41/// Group key the fake belongs to.
42pub const FAKE_GROUP_KEY: u32 = 0x0000_0001;
43/// Group mask bits the fake responds to.
44pub const FAKE_GROUP_MASK: u32 = 0x0000_0001;
45
46/// MAC address the fake camera reports. Public so tests can assert the exact
47/// bytes rather than merely that a MAC is present (ADR-0019).
48pub const FAKE_MAC: [u8; 6] = [0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE];
49/// Manufacturer name reported in the Discovery ACK.
50pub const FAKE_MANUFACTURER: &str = "viva-genicam";
51/// Model name reported in the Discovery ACK.
52pub const FAKE_MODEL: &str = "FakeGigE";
53/// Device version reported in the Discovery ACK.
54pub const FAKE_VERSION: &str = "1.0.0";
55/// Serial number reported in the Discovery ACK.
56pub const FAKE_SERIAL: &str = "FAKE-001";
57/// User-defined name reported in the Discovery ACK.
58pub const FAKE_USER_NAME: &str = "FakeCamera";
59
60/// Subnet mask the fake reports unless told otherwise: loopback's `/8`, the
61/// network every test fake lives on.
62pub const FAKE_SUBNET_MASK: Ipv4Addr = Ipv4Addr::new(255, 0, 0, 0);
63
64/// The per-instance identity a fake reports: the `FAKE_*` constants unless the
65/// builder overrides them. Two fakes with one identity are indistinguishable,
66/// which reproduces #137 but cannot demonstrate its fix.
67#[derive(Debug, Clone)]
68pub(crate) struct Identity {
69    pub(crate) mac: [u8; 6],
70    pub(crate) model: String,
71    pub(crate) serial: String,
72    pub(crate) user_name: String,
73    /// The address the camera believes it has; `None` reports the one it is
74    /// bound to. A camera on the wrong subnet answers a broadcast all the same,
75    /// with an address the host cannot reach.
76    pub(crate) ip: Option<Ipv4Addr>,
77    pub(crate) subnet_mask: Ipv4Addr,
78    pub(crate) gateway: Ipv4Addr,
79}
80
81impl Default for Identity {
82    fn default() -> Self {
83        Self {
84            mac: FAKE_MAC,
85            model: FAKE_MODEL.to_string(),
86            serial: FAKE_SERIAL.to_string(),
87            user_name: FAKE_USER_NAME.to_string(),
88            ip: None,
89            subnet_mask: FAKE_SUBNET_MASK,
90            gateway: Ipv4Addr::UNSPECIFIED,
91        }
92    }
93}
94
95/// One `DISCOVERY_CMD` the fake received.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct DiscoveryRequest {
98    /// Where it came from.
99    pub from: SocketAddr,
100    /// The command's flag byte: `0x01` asks for an acknowledgement, `0x10`
101    /// allows the device to broadcast it.
102    pub flags: u8,
103}
104
105// GigE Vision status codes, imported as vocabulary (ADR-0030).
106const STATUS_SUCCESS: u16 = StatusCode::Success.to_raw();
107const STATUS_NOT_IMPLEMENTED: u16 = StatusCode::NotImplemented.to_raw();
108const STATUS_INVALID_PARAMETER: u16 = StatusCode::InvalidParameter.to_raw();
109const STATUS_BAD_ALIGNMENT: u16 = StatusCode::BadAlignment.to_raw();
110const STATUS_ACCESS_DENIED: u16 = StatusCode::AccessDenied.to_raw();
111const STATUS_INVALID_ADDRESS: u16 = StatusCode::InvalidAddress.to_raw();
112
113/// The four GVCP register-access commands, as the fake counts them.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub enum GvcpCommand {
116    /// `READREG_CMD` (0x0080).
117    ReadReg,
118    /// `WRITEREG_CMD` (0x0082).
119    WriteReg,
120    /// `READMEM_CMD` (0x0084).
121    ReadMem,
122    /// `WRITEMEM_CMD` (0x0086).
123    WriteMem,
124}
125
126/// How the fake refuses READREG and WRITEREG when told to.
127///
128/// Both are shapes a non-conformant device can take, and a controller has to
129/// survive either: one answers with a status it can act on, the other leaves
130/// it waiting out its retry budget.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum RegisterCommandRefusal {
133    /// Acknowledge with `NOT_IMPLEMENTED` (0x8001) and do nothing.
134    NotImplemented,
135    /// Drop the command without any acknowledgement.
136    NoReply,
137}
138
139/// Per-command, per-address count of register-access commands received.
140///
141/// Counted on receipt, before the command is served or refused: the question a
142/// test asks is which command left the host, and a refused command did leave
143/// it. Without this nothing could assert *how* a value reached the device, only
144/// that it did — and READMEM and READREG deliver identical bytes.
145#[derive(Debug, Default)]
146pub struct CommandCounters {
147    counts: std::sync::Mutex<HashMap<(GvcpCommand, u64), u64>>,
148    sequence: std::sync::Mutex<Vec<(GvcpCommand, u64, SocketAddr)>>,
149}
150
151impl CommandCounters {
152    fn record(&self, command: GvcpCommand, addr: u64, peer: SocketAddr) {
153        if let Ok(mut counts) = self.counts.lock() {
154            *counts.entry((command, addr)).or_default() += 1;
155        }
156        if let Ok(mut sequence) = self.sequence.lock() {
157            sequence.push((command, addr, peer));
158        }
159    }
160
161    /// Every register-access command `peer` sent since the last
162    /// [`reset`](Self::reset), in arrival order: what one application did,
163    /// when several talk to the camera.
164    pub fn from(&self, peer: SocketAddr) -> Vec<(GvcpCommand, u64)> {
165        self.sequence
166            .lock()
167            .map(|sequence| {
168                sequence
169                    .iter()
170                    .filter(|(_, _, from)| *from == peer)
171                    .map(|&(command, addr, _)| (command, addr))
172                    .collect()
173            })
174            .unwrap_or_default()
175    }
176
177    /// Every register-access command received since the last
178    /// [`reset`](Self::reset), in arrival order: for a test about the order in
179    /// which a controller configures the device.
180    pub fn sequence(&self) -> Vec<(GvcpCommand, u64)> {
181        self.sequence
182            .lock()
183            .map(|sequence| {
184                sequence
185                    .iter()
186                    .map(|&(command, addr, _)| (command, addr))
187                    .collect()
188            })
189            .unwrap_or_default()
190    }
191
192    /// How many `command`s have been received, at any address.
193    pub fn total(&self, command: GvcpCommand) -> u64 {
194        self.counts.lock().map_or(0, |counts| {
195            counts
196                .iter()
197                .filter(|((cmd, _), _)| *cmd == command)
198                .map(|(_, n)| n)
199                .sum()
200        })
201    }
202
203    /// How many `command`s have been received for `addr`.
204    ///
205    /// A READMEM or WRITEMEM counts at its start address; a multi-register
206    /// READREG or WRITEREG counts once at each address it names.
207    pub fn at(&self, command: GvcpCommand, addr: u64) -> u64 {
208        self.counts.lock().map_or(0, |counts| {
209            counts.get(&(command, addr)).copied().unwrap_or(0)
210        })
211    }
212
213    /// Forget every count so far.
214    pub fn reset(&self) {
215        if let Ok(mut counts) = self.counts.lock() {
216            counts.clear();
217        }
218        if let Ok(mut sequence) = self.sequence.lock() {
219            sequence.clear();
220        }
221    }
222}
223
224/// Behaviour of the GVCP server beyond the register store.
225#[derive(Debug)]
226pub(crate) struct ServerOptions {
227    /// End reception and drain delayed replies before releasing the socket.
228    pub shutdown: oneshot::Receiver<()>,
229    /// Counts of every register-access command received.
230    pub counters: Arc<CommandCounters>,
231    /// Refuse READREG/WRITEREG in this way, if set.
232    pub refuse_register_commands: Option<RegisterCommandRefusal>,
233    /// The packets of recent blocks, for `PACKETRESEND_CMD`.
234    pub retention: Arc<std::sync::Mutex<Retention>>,
235    /// What the device did with resend requests.
236    pub resend: Arc<ResendCounters>,
237    /// Every `DISCOVERY_CMD` received.
238    pub discoveries: Arc<std::sync::Mutex<Vec<DiscoveryRequest>>>,
239    /// Commands addressing these registers are acknowledged only after the
240    /// delay, preceded by a `PENDING_ACK` once the controller enabled it.
241    pub delayed_acks: Arc<HashMap<u64, Duration>>,
242    /// How often the heartbeat rule has revoked control privilege.
243    pub expiries: Arc<AtomicU64>,
244    /// Action commands addressed to this device and acted on.
245    pub actions: Arc<AtomicU64>,
246    /// Whether action commands are implemented at all.
247    pub action_commands: bool,
248    /// Set while the camera's link is down ([`FakeCamera::unplug`]): every
249    /// datagram that arrives is lost, unanswered.
250    ///
251    /// [`FakeCamera::unplug`]: crate::FakeCamera::unplug
252    pub link_down: Arc<AtomicBool>,
253}
254
255/// Run the GVCP control server loop.
256///
257/// Listens for GVCP commands and sends appropriate responses.
258/// Notifies `acq_notify` when AcquisitionStart is written.
259pub async fn run(
260    socket: Arc<UdpSocket>,
261    regs: Arc<Mutex<RegisterMap>>,
262    acq_start_notify: Arc<Notify>,
263    acq_stop_flag: Arc<AtomicBool>,
264    bind_ip: std::net::Ipv4Addr,
265    mut options: ServerOptions,
266    identity: Identity,
267) {
268    let mut buf = [0u8; 2048];
269    // Delayed commands not yet acknowledged, by sender and request id: a
270    // retry of one is the same command, not a second one to execute.
271    let in_flight: Arc<std::sync::Mutex<HashSet<(SocketAddr, u16)>>> = Arc::default();
272    let mut delayed = JoinSet::new();
273    loop {
274        while delayed.try_join_next().is_some() {}
275        let received = tokio::select! {
276            biased;
277            _ = &mut options.shutdown => break,
278            received = socket.recv_from(&mut buf) => received,
279        };
280        let (len, peer) = match received {
281            Ok(r) => r,
282            Err(e) => {
283                warn!(error = %e, "GVCP recv error");
284                continue;
285            }
286        };
287        if options.link_down.load(Ordering::Relaxed) {
288            trace!(%peer, "link down: datagram lost");
289            continue;
290        }
291        let pkt = &buf[..len];
292        if len < 8 || pkt[0] != GVCP_CMD_KEY {
293            trace!(len, "ignoring non-GVCP packet");
294            continue;
295        }
296
297        let flags = pkt[1];
298        let command = u16::from_be_bytes([pkt[2], pkt[3]]);
299        let _length = u16::from_be_bytes([pkt[4], pkt[5]]);
300        let request_id = u16::from_be_bytes([pkt[6], pkt[7]]);
301        let payload = &pkt[8..];
302        let register_access = matches!(
303            command,
304            READREG_CMD | WRITEREG_CMD | READMEM_CMD | WRITEMEM_CMD
305        );
306
307        // Register access from the controller refreshes its heartbeat timer.
308        // Discovery and FORCEIP do not: they are broadcast by any application
309        // on the subnet. The command is still served after an expiry — a real
310        // device answers register reads from a non-controller, it only
311        // refuses configuration.
312        if register_access && regs.lock().await.note_register_command(peer) {
313            options.expiries.fetch_add(1, Ordering::Relaxed);
314            warn!(%peer, "heartbeat expired; control privilege released");
315        }
316
317        record_command(&options.counters, command, payload, peer);
318
319        if matches!(command, READREG_CMD | WRITEREG_CMD)
320            && let Some(refusal) = options.refuse_register_commands
321        {
322            if refusal == RegisterCommandRefusal::NotImplemented {
323                let ack = if command == READREG_CMD {
324                    READREG_ACK
325                } else {
326                    WRITEREG_ACK
327                };
328                let resp = build_error_ack(ack, request_id, STATUS_NOT_IMPLEMENTED);
329                let _ = socket.send_to(&resp, peer).await;
330            }
331            debug!(%peer, command, ?refusal, "register command refused");
332            continue;
333        }
334
335        let delay = register_access
336            .then(|| first_address(payload))
337            .flatten()
338            .and_then(|addr| options.delayed_acks.get(&addr).copied());
339        if delay.is_some()
340            && in_flight
341                .lock()
342                .is_ok_and(|pending| pending.contains(&(peer, request_id)))
343        {
344            debug!(%peer, request_id, "retry of a command still in progress; not executed again");
345            continue;
346        }
347
348        let acquisition = Acquisition {
349            start: &acq_start_notify,
350            stop: &acq_stop_flag,
351        };
352        let reply = match command {
353            DISCOVERY_CMD => {
354                if let Ok(mut seen) = options.discoveries.lock() {
355                    seen.push(DiscoveryRequest { from: peer, flags });
356                }
357                let resp = build_discovery_ack(request_id, bind_ip, &identity);
358                let _ = socket.send_to(&resp, peer).await;
359                debug!(%peer, flags, "discovery response sent");
360                continue;
361            }
362            FORCEIP_CMD => {
363                handle_forceip(&socket, peer, request_id, payload, bind_ip, identity.mac).await;
364                continue;
365            }
366            READREG_CMD => handle_readreg(peer, request_id, payload, &regs).await,
367            WRITEREG_CMD => {
368                handle_writereg(peer, request_id, payload, bind_ip, &regs, acquisition).await
369            }
370            READMEM_CMD => handle_readmem(peer, request_id, payload, &regs).await,
371            WRITEMEM_CMD => {
372                handle_writemem(peer, request_id, payload, bind_ip, &regs, acquisition).await
373            }
374            ACTION_CMD if !options.action_commands => {
375                // What the Manta G-125B sent: the error under the command's
376                // own opcode, whatever the keys.
377                let resp = build_error_ack(ACTION_CMD, request_id, STATUS_NOT_IMPLEMENTED);
378                let _ = socket.send_to(&resp, peer).await;
379                continue;
380            }
381            ACTION_CMD => {
382                if handle_action(&socket, peer, request_id, flags, payload).await {
383                    options.actions.fetch_add(1, Ordering::Relaxed);
384                }
385                continue;
386            }
387            // No acknowledgement: the command asks for none, and the answer
388            // is the packets themselves, sent from the stream socket.
389            PACKETRESEND_CMD => {
390                let supported = regs.lock().await.packet_resend_supported();
391                resend::serve(
392                    supported,
393                    &options.retention,
394                    &options.resend,
395                    flags,
396                    payload,
397                )
398                .await;
399                continue;
400            }
401            _ => {
402                debug!(command, "unsupported GVCP command");
403                continue;
404            }
405        };
406        let Some(reply) = reply else {
407            continue;
408        };
409
410        match delay {
411            None => reply.send(&socket, peer).await,
412            Some(delay) => {
413                if regs.lock().await.pending_ack_enabled() {
414                    let resp = build_pending_ack(request_id, pending_estimate(delay));
415                    let _ = socket.send_to(&resp, peer).await;
416                }
417                if let Ok(mut pending) = in_flight.lock() {
418                    pending.insert((peer, request_id));
419                }
420                let socket = socket.clone();
421                let in_flight = in_flight.clone();
422                debug!(%peer, request_id, ?delay, "acknowledging after a delay");
423                delayed.spawn(async move {
424                    tokio::time::sleep(delay).await;
425                    if let Ok(mut pending) = in_flight.lock() {
426                        pending.remove(&(peer, request_id));
427                    }
428                    reply.send(&socket, peer).await;
429                });
430            }
431        }
432    }
433    // A delayed reply owns an Arc of the listening socket. Aborting only the
434    // receive loop leaves that old socket bound during the next fixture.
435    delayed.shutdown().await;
436}
437
438/// The time a `PENDING_ACK` asks for: the delay and half again, so the
439/// acknowledgement cannot race the controller's extended deadline.
440fn pending_estimate(delay: Duration) -> u16 {
441    let millis = delay.as_millis().saturating_mul(3) / 2;
442    u16::try_from(millis).unwrap_or(u16::MAX)
443}
444
445/// A `PENDING_ACK` for `request_id`: status 0, opcode 0x0089, length 4, then
446/// two reserved bytes and `time_to_completion` in milliseconds.
447fn build_pending_ack(request_id: u16, millis: u16) -> Vec<u8> {
448    let mut buf = BytesMut::with_capacity(12);
449    buf.put_u16(STATUS_SUCCESS);
450    buf.put_u16(PENDING_ACK);
451    buf.put_u16(4);
452    buf.put_u16(request_id);
453    buf.put_u16(0);
454    buf.put_u16(millis);
455    buf.to_vec()
456}
457
458/// The first register address a register-access command names.
459fn first_address(payload: &[u8]) -> Option<u64> {
460    let word: [u8; 4] = payload.get(..4)?.try_into().ok()?;
461    Some(u64::from(u32::from_be_bytes(word)))
462}
463
464/// What a register-access command answers, and a test packet to fire after
465/// the acknowledgement.
466struct Reply {
467    ack: Vec<u8>,
468    test_packet: Option<TestPacket>,
469}
470
471/// A fire-test-packet request, captured while the register lock was held.
472struct TestPacket {
473    size: u32,
474    source_ip: Ipv4Addr,
475    dest_ip: Ipv4Addr,
476    dest_port: u16,
477    max_on_wire: Option<u32>,
478}
479
480impl Reply {
481    fn ack(ack: Vec<u8>) -> Option<Self> {
482        Some(Self {
483            ack,
484            test_packet: None,
485        })
486    }
487
488    /// Send the acknowledgement, then the test packet. A real device answers
489    /// the write and then emits the packet, and a controller that waits for
490    /// the ack before listening must not miss it.
491    async fn send(self, socket: &UdpSocket, peer: SocketAddr) {
492        let _ = socket.send_to(&self.ack, peer).await;
493        if let Some(t) = self.test_packet {
494            fire_test_packet(t.size, t.source_ip, t.dest_ip, t.dest_port, t.max_on_wire).await;
495        }
496    }
497}
498
499/// Build a 256-byte discovery ACK payload (GVCP header + device info).
500fn build_discovery_ack(request_id: u16, ip: std::net::Ipv4Addr, identity: &Identity) -> Vec<u8> {
501    // Discovery ack payload is 248 bytes (as defined by the GigE Vision spec).
502    let payload_len: u16 = 248;
503    let mut buf = BytesMut::with_capacity(8 + payload_len as usize);
504
505    // ACK header: status(2) + ack_cmd(2) + length(2) + request_id(2)
506    buf.put_u16(STATUS_SUCCESS);
507    buf.put_u16(DISCOVERY_ACK);
508    buf.put_u16(payload_len);
509    buf.put_u16(request_id);
510
511    // Discovery payload (248 bytes). Offsets below are payload-relative and
512    // come from the specification's field table, NOT from what our own parser
513    // happens to read — see ADR-0019. This layout previously placed the MAC at
514    // offset 12 because `parse_discovery_payload` read it there; both were
515    // wrong, and agreeing with each other is what hid it (#57).
516    buf.put_u16(2); // 0   Spec major version
517    buf.put_u16(0); // 2   Spec minor version
518    buf.put_u32(0); // 4   Device mode
519
520    // 8   Reserved: the padding half of the MAC-high register, 2 bytes only.
521    buf.put_slice(&[0u8; 2]);
522
523    // 10  MAC address (6 bytes): FAKE_MAC DE:AD:BE:EF:CA:FE unless overridden
524    buf.put_slice(&identity.mac);
525
526    buf.put_u32(0x0000_0007); // 16  Supported IP config (DHCP + persistent + LLA)
527    buf.put_u32(0x0000_0005); // 20  Current IP config
528
529    // 24  Reserved (12 bytes)
530    buf.put_slice(&[0u8; 12]);
531
532    // 36  Current IP address
533    buf.put_slice(&identity.ip.unwrap_or(ip).octets());
534
535    // 40  Reserved (12 bytes)
536    buf.put_slice(&[0u8; 12]);
537
538    // 52  Subnet mask
539    buf.put_slice(&identity.subnet_mask.octets());
540
541    // 56  Reserved (12 bytes)
542    buf.put_slice(&[0u8; 12]);
543
544    // 68  Default gateway
545    buf.put_slice(&identity.gateway.octets());
546
547    // Manufacturer name (32 bytes)
548    put_fixed_string(&mut buf, FAKE_MANUFACTURER, 32); // 72
549    // Model name (32 bytes)
550    put_fixed_string(&mut buf, &identity.model, 32); // 104
551    // Device version (32 bytes)
552    put_fixed_string(&mut buf, FAKE_VERSION, 32); // 136
553    // Manufacturer specific info (48 bytes)
554    put_fixed_string(&mut buf, "Fake camera for testing", 48); // 168
555    // Serial number (16 bytes)
556    put_fixed_string(&mut buf, &identity.serial, 16); // 216
557    // User defined name (16 bytes)
558    put_fixed_string(&mut buf, &identity.user_name, 16); // 232
559
560    buf.to_vec()
561}
562
563fn put_fixed_string(buf: &mut BytesMut, s: &str, len: usize) {
564    let bytes = s.as_bytes();
565    let copy_len = bytes.len().min(len);
566    buf.put_slice(&bytes[..copy_len]);
567    for _ in copy_len..len {
568        buf.put_u8(0);
569    }
570}
571
572/// Build a generic GVCP ACK header + payload.
573fn build_ack(ack_cmd: u16, request_id: u16, payload: &[u8]) -> Vec<u8> {
574    let mut buf = BytesMut::with_capacity(8 + payload.len());
575    buf.put_u16(STATUS_SUCCESS);
576    buf.put_u16(ack_cmd);
577    buf.put_u16(payload.len() as u16);
578    buf.put_u16(request_id);
579    buf.put_slice(payload);
580    buf.to_vec()
581}
582
583/// Build a payload-less error ACK (8-byte header only), as real cameras send.
584fn build_error_ack(ack_cmd: u16, request_id: u16, status: u16) -> Vec<u8> {
585    let mut buf = BytesMut::with_capacity(8);
586    buf.put_u16(status);
587    buf.put_u16(ack_cmd);
588    buf.put_u16(0);
589    buf.put_u16(request_id);
590    buf.to_vec()
591}
592
593async fn handle_readreg(
594    peer: SocketAddr,
595    request_id: u16,
596    payload: &[u8],
597    regs: &Mutex<RegisterMap>,
598) -> Option<Reply> {
599    // READREG payload: one or more 4-byte addresses
600    if payload.len() < 4 || !payload.len().is_multiple_of(4) {
601        return None;
602    }
603    let store = regs.lock().await;
604    if !store.may_access(peer, false) {
605        debug!(%peer, "READREG refused: another application holds exclusive access");
606        return Reply::ack(build_error_ack(
607            READREG_ACK,
608            request_id,
609            STATUS_ACCESS_DENIED,
610        ));
611    }
612    let mut resp_payload = BytesMut::new();
613    for chunk in payload.chunks(4) {
614        let addr = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) as u64;
615        // A register is a 32-bit word on a 32-bit boundary; anything else is
616        // not a register, and GVCP says so with its own status.
617        let refusal = if !addr.is_multiple_of(4) {
618            Some(STATUS_BAD_ALIGNMENT)
619        } else if store.is_invalid_address(addr, 4) {
620            Some(STATUS_INVALID_ADDRESS)
621        } else if store.is_write_only(addr, 4) {
622            Some(STATUS_ACCESS_DENIED)
623        } else {
624            None
625        };
626        if let Some(status) = refusal {
627            debug!(%peer, addr = format!("0x{addr:x}"), status, "READREG refused");
628            return Reply::ack(build_error_ack(READREG_ACK, request_id, status));
629        }
630        let data = store.read(addr, 4);
631        resp_payload.put_slice(&data);
632    }
633    trace!(%peer, regs = payload.len() / 4, "READREG response");
634    Reply::ack(build_ack(READREG_ACK, request_id, &resp_payload))
635}
636
637/// Apply a write from `peer` of `data` at `addr`, CCP included, or refuse it
638/// with `ACCESS_DENIED` while another application holds control.
639fn write_checked(
640    store: &mut RegisterMap,
641    peer: SocketAddr,
642    addr: u64,
643    data: &[u8],
644    acquisition: Acquisition<'_>,
645) -> Result<(), u16> {
646    if addr == crate::registers::CONTROL_CHANNEL_PRIVILEGE && data.len() == 4 {
647        let value = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
648        return if store.write_ccp(peer, value) {
649            Ok(())
650        } else {
651            Err(STATUS_ACCESS_DENIED)
652        };
653    }
654    if !store.may_access(peer, true) {
655        return Err(STATUS_ACCESS_DENIED);
656    }
657    store.write(addr, data);
658    store.handle_special_write(addr);
659    check_acquisition(addr, data, acquisition.start, acquisition.stop);
660    Ok(())
661}
662
663/// The test packet the last write asked for, if any, with where it goes.
664fn take_test_packet(store: &mut RegisterMap, source_ip: Ipv4Addr) -> Option<TestPacket> {
665    let size = store.take_pending_test_packet()?;
666    Some(TestPacket {
667        size,
668        source_ip,
669        dest_ip: store.stream_dest_ip(),
670        dest_port: store.stream_dest_port(),
671        max_on_wire: store.max_on_wire(),
672    })
673}
674
675async fn handle_writereg(
676    peer: SocketAddr,
677    request_id: u16,
678    payload: &[u8],
679    source_ip: std::net::Ipv4Addr,
680    regs: &Mutex<RegisterMap>,
681    acquisition: Acquisition<'_>,
682) -> Option<Reply> {
683    // WRITEREG payload: pairs of (address: u32, value: u32)
684    if payload.len() < 8 || !payload.len().is_multiple_of(8) {
685        return None;
686    }
687    let mut store = regs.lock().await;
688    for (index, chunk) in payload.chunks(8).enumerate() {
689        let addr = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) as u64;
690        if let Err(status) = write_checked(&mut store, peer, addr, &chunk[4..8], acquisition) {
691            debug!(%peer, addr = format!("0x{addr:x}"), status, "WRITEREG refused");
692            debug!(%peer, index, "WRITEREG stopped at this register");
693            return Reply::ack(build_error_ack(WRITEREG_ACK, request_id, status));
694        }
695    }
696    // `GevSCPSPacketSize` is a single register, so a controller that writes
697    // registers with WRITEREG fires the test packet this way. Serving it only
698    // from WRITEMEM would make the probe depend on which command the host
699    // happened to choose — silently, since the write itself still succeeds.
700    let test_packet = take_test_packet(&mut store, source_ip);
701    trace!(%peer, "WRITEREG response");
702    // WRITEREG ACK includes a 4-byte data index placeholder.
703    Some(Reply {
704        ack: build_ack(WRITEREG_ACK, request_id, &[0, 0, 0, 0]),
705        test_packet,
706    })
707}
708
709async fn handle_readmem(
710    peer: SocketAddr,
711    request_id: u16,
712    payload: &[u8],
713    regs: &Mutex<RegisterMap>,
714) -> Option<Reply> {
715    // READMEM payload: address(4) + reserved(2) + count(2)
716    if payload.len() < 8 {
717        return None;
718    }
719    let addr = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as u64;
720    let count = u16::from_be_bytes([payload[6], payload[7]]) as usize;
721
722    // GVCP requires the address and byte count to be multiples of 4. Real
723    // cameras (e.g. Hikrobot) reject violations with INVALID_PARAMETER and a
724    // bare 8-byte ack header; be equally strict so that client bugs are
725    // caught by the in-tree fake (regression guard for issue #35).
726    if !addr.is_multiple_of(4) || count == 0 || !count.is_multiple_of(4) {
727        debug!(%peer, addr = format!("0x{addr:x}"), count, "READMEM rejected: unaligned");
728        return Reply::ack(build_error_ack(
729            READMEM_ACK,
730            request_id,
731            STATUS_INVALID_PARAMETER,
732        ));
733    }
734
735    let store = regs.lock().await;
736    if store.is_invalid_address(addr, count) {
737        debug!(%peer, addr = format!("0x{addr:x}"), count, "READMEM refused: no such register");
738        return Reply::ack(build_error_ack(
739            READMEM_ACK,
740            request_id,
741            STATUS_INVALID_ADDRESS,
742        ));
743    }
744    // A write-only register is no more readable through READMEM than through
745    // READREG. Serving the stored bytes here is what let a read-modify-write
746    // of a WO bitfield pass against the fake and fail on hardware (#135).
747    if store.is_write_only(addr, count) || !store.may_access(peer, false) {
748        debug!(%peer, addr = format!("0x{addr:x}"), count, "READMEM refused");
749        return Reply::ack(build_error_ack(
750            READMEM_ACK,
751            request_id,
752            STATUS_ACCESS_DENIED,
753        ));
754    }
755    let data = store.read(addr, count);
756
757    // READMEM ACK payload: address(4) + data(N)
758    let mut resp_payload = BytesMut::with_capacity(4 + data.len());
759    resp_payload.put_u32(addr as u32);
760    resp_payload.put_slice(&data);
761    trace!(%peer, addr = format!("0x{addr:x}"), count, "READMEM response");
762    Reply::ack(build_ack(READMEM_ACK, request_id, &resp_payload))
763}
764
765async fn handle_writemem(
766    peer: SocketAddr,
767    request_id: u16,
768    payload: &[u8],
769    source_ip: std::net::Ipv4Addr,
770    regs: &Mutex<RegisterMap>,
771    acquisition: Acquisition<'_>,
772) -> Option<Reply> {
773    // WRITEMEM payload: address(4) + data(N)
774    if payload.len() < 4 {
775        return None;
776    }
777    let addr = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as u64;
778    let data = &payload[4..];
779    // The same rule as READMEM: a 32-bit aligned address and a whole number
780    // of 32-bit words (TC-32). No device has been seen to enforce it on a
781    // write; the fake does, so a client that relies on a lenient device
782    // fails here first.
783    if !addr.is_multiple_of(4) || data.is_empty() || !data.len().is_multiple_of(4) {
784        debug!(%peer, addr = format!("0x{addr:x}"), len = data.len(), "WRITEMEM rejected: unaligned");
785        return Reply::ack(build_error_ack(
786            WRITEMEM_ACK,
787            request_id,
788            STATUS_INVALID_PARAMETER,
789        ));
790    }
791    let mut store = regs.lock().await;
792    if let Err(status) = write_checked(&mut store, peer, addr, data, acquisition) {
793        debug!(%peer, addr = format!("0x{addr:x}"), status, "WRITEMEM refused");
794        return Reply::ack(build_error_ack(WRITEMEM_ACK, request_id, status));
795    }
796    let test_packet = take_test_packet(&mut store, source_ip);
797
798    // WRITEMEM ACK payload: address(4)
799    let mut resp_payload = BytesMut::with_capacity(4);
800    resp_payload.put_u32(addr as u32);
801    trace!(%peer, addr = format!("0x{addr:x}"), len = data.len(), "WRITEMEM response");
802    Some(Reply {
803        ack: build_ack(WRITEMEM_ACK, request_id, &resp_payload),
804        test_packet,
805    })
806}
807
808/// Emit one GVSP test packet of `size` bytes to the configured stream
809/// destination, unless the configured path ceiling would have swallowed it.
810///
811/// `size` is the IP datagram size the controller asked for, so the UDP payload
812/// is `size` minus the 20-byte IPv4 and 8-byte UDP headers. What matters to the
813/// probe is only whether *something* arrives, but sending the right length lets
814/// a caller check it.
815///
816/// The `max_on_wire` arm is the point of the whole mechanism: a path that
817/// cannot carry the frame drops it with nobody to report the loss, which is
818/// exactly what a register read cannot discover
819/// ([#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112)).
820async fn fire_test_packet(
821    size: u32,
822    source_ip: std::net::Ipv4Addr,
823    dest_ip: std::net::Ipv4Addr,
824    dest_port: u16,
825    max_on_wire: Option<u32>,
826) {
827    if dest_port == 0 {
828        debug!("test packet requested before a stream destination was set");
829        return;
830    }
831    if max_on_wire.is_some_and(|max| size > max) {
832        debug!(
833            size,
834            "test packet exceeds the path ceiling; dropped in flight"
835        );
836        return;
837    }
838
839    const IP_AND_UDP_HEADERS: u32 = 28;
840    let payload_len = size.saturating_sub(IP_AND_UDP_HEADERS) as usize;
841    // From the camera's own address, as every GVSP packet a device sends.
842    let Ok(sock) = UdpSocket::bind((source_ip, 0)).await else {
843        return;
844    };
845    // A test packet is a GVSP payload-format datagram; the controller only
846    // checks that it arrived, so the header just has to be well formed.
847    let mut pkt = BytesMut::with_capacity(payload_len.max(8));
848    pkt.put_u16(0); // status
849    pkt.put_u16(0); // block id — a test packet belongs to no block
850    pkt.put_u8(0x03); // packet format: payload
851    pkt.put_u8(0);
852    pkt.put_u16(0); // packet id
853    pkt.resize(payload_len.max(8), 0);
854    let _ = sock.send_to(&pkt, (dest_ip, dest_port)).await;
855    debug!(size, %dest_ip, dest_port, "test packet sent");
856}
857
858/// Handle a GVCP `ACTION_CMD` (0x0100).
859///
860/// Payload is `device_key`, `group_key`, `group_mask` — 12 bytes — plus a
861/// 64-bit action time when flags bit 7 is set. A 24-byte payload, or one
862/// carrying a scheduled time without the flag, is malformed and gets no reply:
863/// the client used to send exactly that, under opcode 0x0080 (`READREG`).
864///
865/// Returns whether the device acts on it: its keys are this device's.
866async fn handle_action(
867    socket: &UdpSocket,
868    peer: SocketAddr,
869    request_id: u16,
870    flags: u8,
871    payload: &[u8],
872) -> bool {
873    const SCHEDULED: u8 = 0x80;
874    const ACK_REQUIRED: u8 = 0x01;
875
876    let scheduled = flags & SCHEDULED != 0;
877    let expected = if scheduled { 20 } else { 12 };
878    if payload.len() < expected {
879        warn!(
880            len = payload.len(),
881            expected, scheduled, "malformed action command payload"
882        );
883        return false;
884    }
885
886    let device_key = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
887    let group_key = u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
888    let group_mask = u32::from_be_bytes([payload[8], payload[9], payload[10], payload[11]]);
889
890    if device_key != FAKE_DEVICE_KEY
891        || group_key != FAKE_GROUP_KEY
892        || group_mask & FAKE_GROUP_MASK == 0
893    {
894        debug!(
895            device_key,
896            group_key, group_mask, "action command not addressed to this device"
897        );
898        return false;
899    }
900
901    debug!(%peer, scheduled, "action command accepted");
902    if flags & ACK_REQUIRED != 0 {
903        let mut buf = BytesMut::with_capacity(8);
904        buf.put_u16(STATUS_SUCCESS);
905        buf.put_u16(ACTION_ACK);
906        buf.put_u16(0);
907        buf.put_u16(request_id);
908        let _ = socket.send_to(&buf, peer).await;
909    }
910    true
911}
912
913async fn handle_forceip(
914    socket: &UdpSocket,
915    peer: SocketAddr,
916    request_id: u16,
917    payload: &[u8],
918    bind_ip: std::net::Ipv4Addr,
919    fake_mac: [u8; 6],
920) {
921    // FORCEIP payload: 56 bytes
922    // [0..2]   reserved
923    // [2..8]   target MAC address
924    // [8..20]  reserved
925    // [20..24] static IP
926    // [24..36] reserved
927    // [36..40] subnet mask
928    // [40..52] reserved
929    // [52..56] gateway
930    if payload.len() < 56 {
931        warn!(len = payload.len(), "FORCEIP payload too short");
932        return;
933    }
934
935    let target_mac = &payload[2..8];
936    if target_mac != fake_mac {
937        debug!(
938            target = ?target_mac,
939            "FORCEIP: MAC mismatch, ignoring"
940        );
941        return;
942    }
943
944    let ip = std::net::Ipv4Addr::new(payload[20], payload[21], payload[22], payload[23]);
945    let subnet = std::net::Ipv4Addr::new(payload[36], payload[37], payload[38], payload[39]);
946    let gateway = std::net::Ipv4Addr::new(payload[52], payload[53], payload[54], payload[55]);
947
948    debug!(
949        %bind_ip,
950        %ip,
951        %subnet,
952        %gateway,
953        "FORCEIP accepted (fake camera ignores IP change)"
954    );
955
956    // Send FORCEIP_ACK (empty payload).
957    let resp = build_ack(FORCEIP_ACK, request_id, &[]);
958    let _ = socket.send_to(&resp, peer).await;
959}
960
961/// Count a register-access command against every address it names.
962fn record_command(counters: &CommandCounters, command: u16, payload: &[u8], peer: SocketAddr) {
963    let word = |chunk: &[u8]| u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) as u64;
964    match command {
965        READREG_CMD => {
966            for addr in payload.as_chunks::<4>().0 {
967                counters.record(GvcpCommand::ReadReg, word(addr), peer);
968            }
969        }
970        WRITEREG_CMD => {
971            for pair in payload.as_chunks::<8>().0 {
972                counters.record(GvcpCommand::WriteReg, word(pair), peer);
973            }
974        }
975        READMEM_CMD if payload.len() >= 4 => {
976            counters.record(GvcpCommand::ReadMem, word(payload), peer)
977        }
978        WRITEMEM_CMD if payload.len() >= 4 => {
979            counters.record(GvcpCommand::WriteMem, word(payload), peer)
980        }
981        _ => {}
982    }
983}
984
985/// How a register write starts and stops the GVSP sender.
986#[derive(Clone, Copy)]
987pub(crate) struct Acquisition<'a> {
988    start: &'a Notify,
989    stop: &'a AtomicBool,
990}
991
992/// Check if a write targets an acquisition register and notify accordingly.
993fn check_acquisition(addr: u64, data: &[u8], acq_start: &Notify, acq_stop_flag: &AtomicBool) {
994    use crate::registers::{REG_ACQ_START, REG_ACQ_STOP};
995
996    if addr == REG_ACQ_START && data.len() >= 4 {
997        let val = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
998        if val != 0 {
999            debug!("AcquisitionStart triggered");
1000            acq_stop_flag.store(false, Ordering::SeqCst);
1001            acq_start.notify_one();
1002        }
1003    } else if addr == REG_ACQ_STOP && data.len() >= 4 {
1004        let val = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
1005        if val != 0 {
1006            debug!("AcquisitionStop triggered");
1007            acq_stop_flag.store(true, Ordering::SeqCst);
1008        }
1009    }
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use super::*;
1015
1016    #[tokio::test]
1017    async fn stopping_the_server_releases_delayed_reply_socket() {
1018        let socket = Arc::new(UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap());
1019        let address = socket.local_addr().unwrap();
1020        let weak = Arc::downgrade(&socket);
1021        let regs = Arc::new(Mutex::new(RegisterMap::new(
1022            64,
1023            48,
1024            crate::MONO8,
1025            None,
1026            Default::default(),
1027        )));
1028        let (shutdown, stopped) = oneshot::channel();
1029        let options = ServerOptions {
1030            shutdown: stopped,
1031            counters: Arc::default(),
1032            refuse_register_commands: None,
1033            retention: Arc::new(std::sync::Mutex::new(Retention::new(4))),
1034            resend: Arc::default(),
1035            discoveries: Arc::default(),
1036            delayed_acks: Arc::new(HashMap::from([(crate::REG_WIDTH, Duration::from_secs(60))])),
1037            expiries: Arc::default(),
1038            actions: Arc::default(),
1039            action_commands: true,
1040            link_down: Arc::default(),
1041        };
1042        let server = tokio::spawn(run(
1043            socket,
1044            regs,
1045            Arc::default(),
1046            Arc::default(),
1047            Ipv4Addr::LOCALHOST,
1048            options,
1049            Identity::default(),
1050        ));
1051        let client = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
1052        let mut request = vec![GVCP_CMD_KEY, 1, 0, 0x80, 0, 4, 0, 1];
1053        request.extend_from_slice(&(crate::REG_WIDTH as u32).to_be_bytes());
1054        client.send_to(&request, address).await.unwrap();
1055        tokio::time::timeout(Duration::from_secs(5), async {
1056            while weak.strong_count() < 2 {
1057                tokio::task::yield_now().await;
1058            }
1059        })
1060        .await
1061        .expect("the delayed reply owns a socket clone");
1062
1063        shutdown.send(()).unwrap();
1064        tokio::time::timeout(Duration::from_secs(5), server)
1065            .await
1066            .expect("shutdown drains pending replies without waiting for their delay")
1067            .expect("server");
1068        assert!(
1069            weak.upgrade().is_none(),
1070            "delayed reply retained the stopped server's socket"
1071        );
1072    }
1073}