Skip to main content

viva_genapi_xml/
fetch.rs

1//! URL parsing and XML document retrieval utilities.
2
3use std::future::Future;
4
5use crate::XmlError;
6use crate::archive::{self, ArchiveError};
7use crate::util::parse_u64;
8
9/// Address of the first URL register in the GigE Vision bootstrap register map.
10/// GigE Vision spec: GevFirstURL at 0x0200 (512 bytes max).
11const FIRST_URL_ADDRESS: u64 = 0x0200;
12/// Address of the second URL register (GevSecondURL at 0x0400, 512 bytes max).
13/// Used as a fallback when the first URL is empty or cannot be retrieved.
14const SECOND_URL_ADDRESS: u64 = 0x0400;
15/// Maximum length of a URL register string.
16const URL_MAX_LEN: usize = 512;
17
18/// ZIP local file header magic: `PK\x03\x04`.
19const ZIP_MAGIC: &[u8; 4] = b"PK\x03\x04";
20
21/// Upper bound on the decompressed XML size: real GenICam XML documents are
22/// well under 10 MiB, and the cap bounds allocation driven by
23/// device-controlled ZIP metadata.
24const MAX_XML_SIZE: u64 = 64 * 1024 * 1024;
25
26/// If `data` starts with a ZIP signature, extract the first file's contents.
27/// Otherwise return `data` unchanged.
28///
29/// GenICam devices commonly serve their register-description XML as a ZIP
30/// archive (the URL then ends in `.zip`), which the standard requires
31/// consumers to handle transparently.
32pub(crate) fn decompress_if_zip(data: Vec<u8>) -> Result<Vec<u8>, XmlError> {
33    if data.len() < 4 || &data[..4] != ZIP_MAGIC {
34        return Ok(data);
35    }
36    archive::first_file(&data, MAX_XML_SIZE).map_err(|err| match err {
37        ArchiveError::Empty | ArchiveError::TooLarge(_) => {
38            tracing::debug!(error = %err, "XML ZIP archive refused");
39            XmlError::ArchiveSize {
40                limit: MAX_XML_SIZE,
41            }
42        }
43        other => XmlError::Archive(Box::new(other)),
44    })
45}
46
47/// Fetch the GenICam XML document using the provided memory reader closure.
48///
49/// The closure must return the requested number of bytes starting at the
50/// provided address. It can internally perform chunked transfers.
51///
52/// Reads `GevFirstURL`, falling back to `GevSecondURL` when the first URL is
53/// empty or its document cannot be retrieved. ZIP-compressed XML documents
54/// are decompressed transparently.
55pub async fn fetch_and_load_xml<F, Fut>(read_mem: F) -> Result<String, XmlError>
56where
57    F: FnMut(u64, usize) -> Fut,
58    Fut: Future<Output = Result<Vec<u8>, XmlError>>,
59{
60    fetch_document(read_mem, |bytes| {
61        Ok(String::from_utf8(decompress_if_zip(bytes)?)?)
62    })
63    .await
64}
65
66/// Fetch the bytes the device's XML URL points at, exactly as the device
67/// serves them: a ZIP archive is not unpacked and nothing is decoded.
68///
69/// For diagnostics: these are the bytes to look at when
70/// [`fetch_and_load_xml`] refuses a document. The URL registers are read as
71/// they are there, the second one when the first is empty or cannot be read.
72pub async fn fetch_raw_xml<F, Fut>(read_mem: F) -> Result<Vec<u8>, XmlError>
73where
74    F: FnMut(u64, usize) -> Fut,
75    Fut: Future<Output = Result<Vec<u8>, XmlError>>,
76{
77    fetch_document(read_mem, Ok).await
78}
79
80/// Read the document `GevFirstURL` names and `decode` it, falling back to
81/// `GevSecondURL` when either step fails.
82async fn fetch_document<F, Fut, T>(
83    mut read_mem: F,
84    decode: impl Fn(Vec<u8>) -> Result<T, XmlError>,
85) -> Result<T, XmlError>
86where
87    F: FnMut(u64, usize) -> Fut,
88    Fut: Future<Output = Result<Vec<u8>, XmlError>>,
89{
90    let first = fetch_from_url_register(&mut read_mem, FIRST_URL_ADDRESS)
91        .await
92        .and_then(&decode);
93    match first {
94        Ok(document) => Ok(document),
95        Err(first_err) => {
96            tracing::debug!(error = %first_err, "first URL failed, trying GevSecondURL");
97            let second = fetch_from_url_register(&mut read_mem, SECOND_URL_ADDRESS)
98                .await
99                .and_then(&decode);
100            match second {
101                Ok(document) => Ok(document),
102                // The first URL's error is the more useful diagnostic: the
103                // second URL is typically absent on devices where the first
104                // one was already the problem.
105                Err(second_err) => {
106                    tracing::debug!(error = %second_err, "second URL failed as well");
107                    Err(first_err)
108                }
109            }
110        }
111    }
112}
113
114/// Read the document referenced by the URL register at `url_addr`, as served.
115async fn fetch_from_url_register<F, Fut>(
116    read_mem: &mut F,
117    url_addr: u64,
118) -> Result<Vec<u8>, XmlError>
119where
120    F: FnMut(u64, usize) -> Fut,
121    Fut: Future<Output = Result<Vec<u8>, XmlError>>,
122{
123    let url_bytes = read_mem(url_addr, URL_MAX_LEN).await?;
124    let url = first_cstring(&url_bytes).ok_or_else(|| XmlError::Url {
125        url: String::new(),
126        problem: "is empty",
127    })?;
128    let location = UrlLocation::parse(&url)?;
129    match location {
130        UrlLocation::Local { address, length } => read_mem(address, length).await,
131        UrlLocation::Http => Err(XmlError::Url {
132            url,
133            problem: "is an HTTP URL, which is not supported",
134        }),
135        UrlLocation::File => Err(XmlError::Url {
136            url,
137            problem: "is a file URL, which is not supported",
138        }),
139    }
140}
141
142/// Extract the first null-terminated C string from a byte buffer.
143fn first_cstring(bytes: &[u8]) -> Option<String> {
144    let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
145    let slice = &bytes[..end];
146    let value = String::from_utf8_lossy(slice).trim().to_string();
147    if value.is_empty() { None } else { Some(value) }
148}
149
150/// Parsed URL location variants.
151#[derive(Debug)]
152enum UrlLocation {
153    /// Memory-mapped local XML at a fixed address.
154    Local { address: u64, length: usize },
155    /// HTTP(S) remote URL (unsupported).
156    Http,
157    /// File system URL (unsupported).
158    File,
159}
160
161impl UrlLocation {
162    fn parse(url: &str) -> Result<Self, XmlError> {
163        let lower = url.to_ascii_lowercase();
164        if let Some(rest) = lower.strip_prefix("local:") {
165            // Use original URL (case-preserved) for the rest, at same offset.
166            let rest_original = &url[url.len() - rest.len()..];
167            parse_local_url(rest_original)
168        } else if lower.starts_with("http://") || lower.starts_with("https://") {
169            Ok(UrlLocation::Http)
170        } else if lower.starts_with("file://") {
171            Ok(UrlLocation::File)
172        } else {
173            Err(XmlError::Url {
174                url: url.to_string(),
175                problem: "has a scheme that is not local:, http: or file:",
176            })
177        }
178    }
179}
180
181/// Parse a `local:` URL into its components.
182///
183/// Supports two formats:
184///
185/// 1. **Key-value**: `local:address=0x10;length=0x3`
186/// 2. **GenICam standard**: `Local:///filename;hex_address;hex_length`
187///
188/// In format 2, the filename is optional (can be just `///;addr;len`).
189fn parse_local_url(rest: &str) -> Result<UrlLocation, XmlError> {
190    // Strip the `///` prefix used by the standard GenICam URL format.
191    let trimmed = rest.strip_prefix("///").unwrap_or(rest).trim();
192    if trimmed.is_empty() {
193        return Err(XmlError::Url {
194            url: rest.to_string(),
195            problem: "is a local: URL with no address",
196        });
197    }
198
199    let parts: Vec<&str> = trimmed.split(';').collect();
200
201    // GenICam standard format: filename;hex_address;hex_length (3 semicolon-separated parts).
202    if parts.len() >= 3 {
203        let addr_str = parts[parts.len() - 2].trim();
204        let len_str = parts[parts.len() - 1].trim();
205        if let (Ok(address), Ok(length)) = (
206            u64::from_str_radix(addr_str, 16),
207            u64::from_str_radix(len_str, 16),
208        ) {
209            return Ok(UrlLocation::Local {
210                address,
211                length: length as usize,
212            });
213        }
214    }
215
216    // Fall back to key-value parsing.
217    let mut address = None;
218    let mut length = None;
219    for part in parts {
220        let token = part.trim();
221        if token.is_empty() {
222            continue;
223        }
224        if let Some((key, value)) = token.split_once('=') {
225            let key = key.trim().to_ascii_lowercase();
226            let value = value.trim();
227            match key.as_str() {
228                "address" | "addr" | "offset" => {
229                    address = Some(parse_u64(value)?);
230                }
231                "length" | "size" => {
232                    let len = parse_u64(value)?;
233                    length = Some(len.try_into().map_err(|_| XmlError::Url {
234                        url: rest.to_string(),
235                        problem: "declares a length this host cannot address",
236                    })?);
237                }
238                _ => {}
239            }
240        } else if token.starts_with("0x") {
241            address = Some(parse_u64(token)?);
242        }
243        // Ignore unrecognized tokens (like the filename).
244    }
245    match (address, length) {
246        (Some(address), Some(length)) => Ok(UrlLocation::Local { address, length }),
247        _ => Err(XmlError::Url {
248            url: rest.to_string(),
249            problem: "is a local: URL without an address and a length",
250        }),
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    /// Compress `data` into a single-entry ZIP archive (deflate).
259    fn zip_bytes(name: &str, data: &[u8]) -> Vec<u8> {
260        use std::io::Write;
261        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
262        let options = zip::write::SimpleFileOptions::default()
263            .compression_method(zip::CompressionMethod::Deflated);
264        writer.start_file(name, options).expect("start zip entry");
265        writer.write_all(data).expect("write zip entry");
266        writer.finish().expect("finish zip").into_inner()
267    }
268
269    #[tokio::test]
270    async fn fetch_local_zipped_xml() {
271        let url = b"Local:camera.zip;10;9999\0".to_vec();
272        let zipped = zip_bytes("camera.xml", b"<a/>");
273        let mut url_reg = url.clone();
274        url_reg.resize(URL_MAX_LEN, 0);
275        let expected_len = zipped.len();
276        let loaded = fetch_and_load_xml(|addr, len| {
277            let url_reg = url_reg.clone();
278            let zipped = zipped.clone();
279            async move {
280                if addr == FIRST_URL_ADDRESS {
281                    Ok(url_reg)
282                } else if addr == 0x10 && len == 0x9999 {
283                    // Devices serve the advertised length; extra bytes past
284                    // the archive end are padding.
285                    let mut data = zipped;
286                    data.resize(len.max(expected_len), 0);
287                    Ok(data)
288                } else {
289                    Err(XmlError::Transport("unexpected read".into()))
290                }
291            }
292        })
293        .await
294        .expect("load zipped xml");
295        assert_eq!(loaded, "<a/>");
296    }
297
298    /// Serve `document` at 0x10 behind a `Local:` first URL.
299    fn serve(
300        document: Vec<u8>,
301    ) -> impl FnMut(u64, usize) -> std::future::Ready<Result<Vec<u8>, XmlError>> {
302        let mut url_reg = format!("Local:camera.zip;10;{:x}\0", document.len()).into_bytes();
303        url_reg.resize(URL_MAX_LEN, 0);
304        move |addr, len| {
305            std::future::ready(if addr == FIRST_URL_ADDRESS {
306                Ok(url_reg.clone())
307            } else if addr == 0x10 && len == document.len() {
308                Ok(document.clone())
309            } else {
310                Err(XmlError::Transport("unexpected read".into()))
311            })
312        }
313    }
314
315    /// Issue #236: a Basler acA2440-20gc's archive carries an extra field
316    /// that is not ZIP extra records.
317    #[tokio::test]
318    async fn fetch_zipped_xml_with_a_vendor_extra_field() {
319        use crate::archive::tests::{BASLER_EXTRA, zip_with_extra};
320        let zipped = zip_with_extra("camera.xml", b"<a/>", BASLER_EXTRA);
321        let loaded = fetch_and_load_xml(serve(zipped))
322            .await
323            .expect("load zipped xml");
324        assert_eq!(loaded, "<a/>");
325    }
326
327    #[tokio::test]
328    async fn fetch_raw_returns_the_archive_as_served() {
329        let zipped = zip_bytes("camera.xml", b"<a/>");
330        let raw = fetch_raw_xml(serve(zipped.clone())).await.expect("raw");
331        assert_eq!(raw, zipped);
332    }
333
334    #[tokio::test]
335    async fn a_corrupt_archive_is_an_archive_error() {
336        let mut zipped = zip_bytes("camera.xml", b"<a/>");
337        zipped.truncate(zipped.len() - 30);
338        let err = fetch_and_load_xml(serve(zipped))
339            .await
340            .expect_err("truncated archive");
341        assert!(matches!(err, XmlError::Archive(_)), "got: {err:?}");
342    }
343
344    #[tokio::test]
345    async fn falls_back_to_second_url() {
346        let url = b"local:address=0x20;length=0x4\0".to_vec();
347        let loaded = fetch_and_load_xml(|addr, len| {
348            let url = url.clone();
349            async move {
350                if addr == FIRST_URL_ADDRESS {
351                    // Empty first URL register.
352                    Ok(vec![0u8; URL_MAX_LEN])
353                } else if addr == SECOND_URL_ADDRESS {
354                    Ok(url)
355                } else if addr == 0x20 && len == 0x4 {
356                    Ok(b"<b/>".to_vec())
357                } else {
358                    Err(XmlError::Transport("unexpected read".into()))
359                }
360            }
361        })
362        .await
363        .expect("load xml via second URL");
364        assert_eq!(loaded, "<b/>");
365    }
366
367    #[tokio::test]
368    async fn first_url_error_is_reported_when_both_fail() {
369        let err = fetch_and_load_xml(|_, _| async { Ok(vec![0u8; URL_MAX_LEN]) })
370            .await
371            .expect_err("both URLs empty");
372        assert!(matches!(err, XmlError::Url { .. }), "got: {err:?}");
373    }
374
375    #[test]
376    fn decompress_rejects_oversized_declared_xml() {
377        let mut zipped = zip_bytes("camera.xml", b"<a/>");
378        // Patch the uncompressed-size field in both the local file header
379        // (offset 22 from `PK\x03\x04`) and the central directory header
380        // (offset 24 from `PK\x01\x02`) to claim ~4 GiB.
381        let huge = 0xFFFF_FFF0u32.to_le_bytes();
382        for (magic, offset) in [(b"PK\x03\x04", 22usize), (b"PK\x01\x02", 24usize)] {
383            let pos = zipped
384                .windows(4)
385                .position(|w| w == magic)
386                .expect("zip header signature");
387            zipped[pos + offset..pos + offset + 4].copy_from_slice(&huge);
388        }
389        let err = decompress_if_zip(zipped).expect_err("oversized declared XML");
390        assert!(matches!(err, XmlError::ArchiveSize { .. }), "got: {err:?}");
391    }
392
393    #[test]
394    fn decompress_passes_through_plain_xml() {
395        let data = b"<plain/>".to_vec();
396        assert_eq!(decompress_if_zip(data.clone()).unwrap(), data);
397    }
398
399    #[tokio::test]
400    async fn fetch_local_xml() {
401        let data = b"local:address=0x10;length=0x3\0".to_vec();
402        let xml_payload = b"<a/>".to_vec();
403        let loaded = fetch_and_load_xml(|addr, len| {
404            let data = data.clone();
405            let xml_payload = xml_payload.clone();
406            async move {
407                if addr == FIRST_URL_ADDRESS {
408                    Ok(data)
409                } else if addr == 0x10 && len == 0x3 {
410                    Ok(xml_payload)
411                } else {
412                    Err(XmlError::Transport("unexpected read".into()))
413                }
414            }
415        })
416        .await
417        .expect("load xml");
418        assert_eq!(loaded, "<a/>");
419    }
420}