Skip to main content

dcmnorm_object/
meta.rs

1//! File Meta Information (group 0002) - the Part 10 preamble, "DICM" magic, and the group-0002
2//! elements (transfer syntax, SOP class/instance UID, implementation identifiers, etc.) that
3//! precede the main data set in every DICOM Part 10 file.
4
5use std::io;
6use std::io::{Read, Write};
7
8use dcmnorm_core::header::{DataElement, Tag};
9use dcmnorm_core::{PrimitiveValue, VR};
10use dcmnorm_encoding::transfer_syntax::TransferSyntax;
11use dcmnorm_encoding::TransferSyntaxIndex;
12use dcmnorm_transcode::TransferSyntaxRegistry;
13
14use crate::error::{ReadError, WithMetaError, WriteError};
15use crate::mem::InMemElement;
16
17pub(crate) const PREAMBLE_LEN: usize = 128;
18pub(crate) const DICM_MAGIC: &[u8; 4] = b"DICM";
19
20pub(crate) mod tags {
21    use dcmnorm_core::header::Tag;
22
23    pub const FILE_META_INFORMATION_GROUP_LENGTH: Tag = Tag(0x0002, 0x0000);
24    pub const FILE_META_INFORMATION_VERSION: Tag = Tag(0x0002, 0x0001);
25    pub const MEDIA_STORAGE_SOP_CLASS_UID: Tag = Tag(0x0002, 0x0002);
26    pub const MEDIA_STORAGE_SOP_INSTANCE_UID: Tag = Tag(0x0002, 0x0003);
27    pub const TRANSFER_SYNTAX_UID: Tag = Tag(0x0002, 0x0010);
28    pub const IMPLEMENTATION_CLASS_UID: Tag = Tag(0x0002, 0x0012);
29    pub const IMPLEMENTATION_VERSION_NAME: Tag = Tag(0x0002, 0x0013);
30    pub const SOURCE_APPLICATION_ENTITY_TITLE: Tag = Tag(0x0002, 0x0016);
31    pub const SENDING_APPLICATION_ENTITY_TITLE: Tag = Tag(0x0002, 0x0017);
32    pub const RECEIVING_APPLICATION_ENTITY_TITLE: Tag = Tag(0x0002, 0x0018);
33    pub const PRIVATE_INFORMATION_CREATOR_UID: Tag = Tag(0x0002, 0x0102);
34    pub const PRIVATE_INFORMATION: Tag = Tag(0x0002, 0x0103);
35}
36
37/// The File Meta Information (group 0002) of a DICOM Part 10 file.
38///
39/// The three "mandatory" fields (`media_storage_sop_class_uid`,
40/// `media_storage_sop_instance_uid`, `implementation_class_uid`) are plain `String`s with no
41/// "absent" state, matching how `dcmnorm`'s `--remove`/`--set` CLI semantics for group-0002
42/// attributes already distinguish "clear to empty string" from "was never set" - see
43/// `dicom_edit.rs`. Everything else is `Option<String>` and uses `.take()` to represent removal.
44///
45/// Unlike `dicom-object`'s equivalent, `information_group_length` is not a field that can go
46/// stale: it's always computed fresh in [`FileMetaTable::write_to`] from whatever meta elements
47/// are actually about to be written, so there's nothing to "refresh" before a write.
48#[derive(Debug, Clone, Default, PartialEq)]
49pub struct FileMetaTable {
50    pub information_version: [u8; 2],
51    pub media_storage_sop_class_uid: String,
52    pub media_storage_sop_instance_uid: String,
53    pub transfer_syntax: String,
54    pub implementation_class_uid: String,
55    pub implementation_version_name: Option<String>,
56    pub source_application_entity_title: Option<String>,
57    pub sending_application_entity_title: Option<String>,
58    pub receiving_application_entity_title: Option<String>,
59    pub private_information_creator_uid: Option<String>,
60    pub private_information: Option<Vec<u8>>,
61}
62
63impl FileMetaTable {
64    /// The transfer syntax UID declared in this meta table (trailing NUL/whitespace not
65    /// trimmed here - callers that need a normalized comparison already trim, see
66    /// `io.rs::normalize_transfer_syntax_uid`).
67    pub fn transfer_syntax(&self) -> &str {
68        &self.transfer_syntax
69    }
70
71    // Method-call-syntax accessors alongside the public fields above, for call sites that
72    // prefer `.media_storage_sop_class_uid()` over the raw field - both forms read/write the
73    // same underlying field.
74    pub fn media_storage_sop_class_uid(&self) -> &str {
75        &self.media_storage_sop_class_uid
76    }
77
78    pub fn media_storage_sop_instance_uid(&self) -> &str {
79        &self.media_storage_sop_instance_uid
80    }
81
82    pub fn implementation_class_uid(&self) -> &str {
83        &self.implementation_class_uid
84    }
85
86    /// Set the declared transfer syntax to the given [`TransferSyntax`]'s UID.
87    pub fn set_transfer_syntax(&mut self, ts: &TransferSyntax) {
88        self.transfer_syntax = ts.uid().to_owned();
89    }
90
91    /// Resolve this table's declared transfer syntax against the registry.
92    pub fn transfer_syntax_ts(&self) -> Option<&'static TransferSyntax> {
93        TransferSyntaxRegistry.get(io_util::trim_uid(&self.transfer_syntax))
94    }
95
96    /// Iterate this meta table's elements in the same shape they'd be written to a file,
97    /// including the group length element itself. Used for JSON export
98    /// (`standard_json.rs`/`flat_json.rs`).
99    pub fn to_element_iter(&self) -> impl Iterator<Item = InMemElement> + '_ {
100        self.elements_for_write()
101    }
102
103    fn elements_for_write(&self) -> std::vec::IntoIter<InMemElement> {
104        let mut elements = Vec::with_capacity(11);
105        elements.push(primitive_element(
106            tags::FILE_META_INFORMATION_GROUP_LENGTH,
107            VR::UL,
108            PrimitiveValue::from(self.encoded_len()),
109        ));
110        elements.extend(self.body_elements());
111        elements.into_iter()
112    }
113
114    /// Every group-0002 element *except* the group-length element itself, in write order. The
115    /// one place that decides which fields are present and how they're encoded - both
116    /// [`Self::elements_for_write`] (prepends the group-length element) and [`Self::encoded_len`]
117    /// (measures this same list's real encoded size) build on top of it, rather than each
118    /// independently hand-duplicating "which fields exist and what VR they use." Adding a new
119    /// meta field only ever needs a change here.
120    fn body_elements(&self) -> Vec<InMemElement> {
121        let mut elements = Vec::with_capacity(10);
122        elements.push(primitive_element(
123            tags::FILE_META_INFORMATION_VERSION,
124            VR::OB,
125            PrimitiveValue::from(self.information_version.to_vec()),
126        ));
127        elements.push(primitive_element(
128            tags::MEDIA_STORAGE_SOP_CLASS_UID,
129            VR::UI,
130            PrimitiveValue::from(self.media_storage_sop_class_uid.clone()),
131        ));
132        elements.push(primitive_element(
133            tags::MEDIA_STORAGE_SOP_INSTANCE_UID,
134            VR::UI,
135            PrimitiveValue::from(self.media_storage_sop_instance_uid.clone()),
136        ));
137        elements.push(primitive_element(
138            tags::TRANSFER_SYNTAX_UID,
139            VR::UI,
140            PrimitiveValue::from(self.transfer_syntax.clone()),
141        ));
142        elements.push(primitive_element(
143            tags::IMPLEMENTATION_CLASS_UID,
144            VR::UI,
145            PrimitiveValue::from(self.implementation_class_uid.clone()),
146        ));
147        if let Some(v) = &self.implementation_version_name {
148            elements.push(primitive_element(
149                tags::IMPLEMENTATION_VERSION_NAME,
150                VR::SH,
151                PrimitiveValue::from(v.clone()),
152            ));
153        }
154        if let Some(v) = &self.source_application_entity_title {
155            elements.push(primitive_element(
156                tags::SOURCE_APPLICATION_ENTITY_TITLE,
157                VR::AE,
158                PrimitiveValue::from(v.clone()),
159            ));
160        }
161        if let Some(v) = &self.sending_application_entity_title {
162            elements.push(primitive_element(
163                tags::SENDING_APPLICATION_ENTITY_TITLE,
164                VR::AE,
165                PrimitiveValue::from(v.clone()),
166            ));
167        }
168        if let Some(v) = &self.receiving_application_entity_title {
169            elements.push(primitive_element(
170                tags::RECEIVING_APPLICATION_ENTITY_TITLE,
171                VR::AE,
172                PrimitiveValue::from(v.clone()),
173            ));
174        }
175        if let Some(v) = &self.private_information_creator_uid {
176            elements.push(primitive_element(
177                tags::PRIVATE_INFORMATION_CREATOR_UID,
178                VR::UI,
179                PrimitiveValue::from(v.clone()),
180            ));
181        }
182        if let Some(v) = &self.private_information {
183            elements.push(primitive_element(
184                tags::PRIVATE_INFORMATION,
185                VR::OB,
186                PrimitiveValue::from(v.clone()),
187            ));
188        }
189        elements
190    }
191
192    /// The byte length of the meta group's elements *excluding* the group length element
193    /// itself - i.e. the value that belongs in (0002,0000). Computed by actually encoding
194    /// [`Self::body_elements`] (Explicit VR Little Endian, the same path [`Self::write_to`]
195    /// uses) into a throwaway buffer and measuring it, rather than a hand-maintained per-field
196    /// byte count - so it can never drift from what's actually written, by construction, not by
197    /// convention.
198    fn encoded_len(&self) -> u32 {
199        let ts = TransferSyntaxRegistry
200            .get(dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN)
201            .expect("Explicit VR Little Endian must be registered");
202        let mut buf = Vec::new();
203        {
204            let mut writer = dcmnorm_parser::dataset::DataSetWriter::with_ts(&mut buf, ts)
205                .expect("Explicit VR Little Endian writer construction cannot fail");
206            for element in self.body_elements() {
207                crate::mem::write_element_tokens(&mut writer, &element)
208                    .expect("encoding a well-formed in-memory meta element cannot fail");
209            }
210        }
211        buf.len() as u32
212    }
213
214    /// Write the 128-byte preamble, "DICM" magic, and this meta group (Explicit VR Little
215    /// Endian, per PS3.10 §7.1) to `to`.
216    pub fn write_to<W: Write>(&self, mut to: W) -> Result<(), WriteError> {
217        to.write_all(&[0u8; PREAMBLE_LEN])
218            .map_err(|source| WriteError::Io {
219                source,
220                context: "writing preamble",
221            })?;
222        to.write_all(DICM_MAGIC).map_err(|source| WriteError::Io {
223            source,
224            context: "writing DICM magic",
225        })?;
226
227        let ts = TransferSyntaxRegistry
228            .get(dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN)
229            .expect("Explicit VR Little Endian must be registered");
230
231        let mut writer = dcmnorm_parser::dataset::DataSetWriter::with_ts(&mut to, ts)
232            .map_err(|source| WriteError::Dataset { source })?;
233        let elements = self.elements_for_write();
234        for element in elements {
235            crate::mem::write_element_tokens(&mut writer, &element)?;
236        }
237        Ok(())
238    }
239
240    /// Try to read the 128-byte preamble + "DICM" magic + group-0002 meta elements from
241    /// `from`. Returns `Ok(None)` (not an error) if the preamble/magic aren't present, so
242    /// callers can fall back to treating the stream as a bare (meta-less) data set - matching
243    /// the permissive trial-parse behavior `dcmnorm` already relies on for raw dumps.
244    pub fn read_from<R: Read>(mut from: R) -> Result<Option<Self>, ReadError> {
245        let mut preamble = [0u8; PREAMBLE_LEN];
246        if from.read_exact(&mut preamble).is_err() {
247            return Ok(None);
248        }
249        let mut magic = [0u8; 4];
250        if from.read_exact(&mut magic).is_err() || &magic != DICM_MAGIC {
251            return Ok(None);
252        }
253
254        Self::read_meta_group(from).map(Some)
255    }
256
257    /// Read the group-0002 meta elements only, assuming the reader is already positioned right
258    /// after the "DICM" magic (i.e. the preamble has already been consumed/verified).
259    ///
260    /// The meta group's own length - the value of its first element, (0002,0000) - is read
261    /// first and used to read *exactly* that many further bytes into a bounded buffer, which
262    /// is then parsed as a self-contained data set. This is deliberate: a token-stream reader
263    /// has no way to "un-read" bytes once it has peeked at the next element's header, so
264    /// detecting the end of group 0002 by peeking at the first element outside it (rather than
265    /// by the declared length) would consume and discard the first several bytes of the main
266    /// data set that follows - byte-desyncing everything read after it.
267    pub fn read_meta_group<R: Read>(mut from: R) -> Result<Self, ReadError> {
268        let group_length = read_group_length_element(&mut from)?;
269
270        // `group_length` is a raw u32 taken directly from the file (up to ~4GiB) - read via
271        // `Take` + `read_to_end` rather than pre-allocating `vec![0u8; group_length]` upfront.
272        // Real meta groups are a few hundred bytes to a few KB; a corrupt/malicious file's first
273        // 12 bytes declaring an implausible group length would otherwise force a multi-GB
274        // allocation attempt before a single further byte is read, and a failing allocation of
275        // that shape aborts the process rather than returning a catchable error. This way, growth
276        // is bounded by bytes actually available on the stream, so a truncated/lying length
277        // surfaces as a clean `ReadError::Io` as soon as the real data runs out.
278        let mut meta_bytes = Vec::new();
279        (&mut from)
280            .take(group_length as u64)
281            .read_to_end(&mut meta_bytes)
282            .map_err(|source| ReadError::Io {
283                source,
284                context: "reading file meta group",
285            })?;
286        if meta_bytes.len() != group_length as usize {
287            return Err(ReadError::Io {
288                source: io::Error::new(
289                    io::ErrorKind::UnexpectedEof,
290                    format!(
291                        "declared meta group length {group_length} exceeds available data ({} bytes read)",
292                        meta_bytes.len()
293                    ),
294                ),
295                context: "reading file meta group",
296            });
297        }
298
299        let ts = TransferSyntaxRegistry
300            .get(dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN)
301            .expect("Explicit VR Little Endian must be registered");
302
303        let mut table = FileMetaTable::default();
304        let reader = dcmnorm_parser::dataset::DataSetReader::new_with_ts(
305            std::io::Cursor::new(meta_bytes),
306            ts,
307        )
308        .map_err(|source| ReadError::Dataset { source })?;
309
310        // The meta group (beyond the group length element already consumed above) is always a
311        // flat sequence of primitive elements (no sequences, no encapsulated pixel data) - fold
312        // ElementHeader+PrimitiveValue token pairs directly. The buffer is exactly
313        // `group_length` bytes, so the reader naturally stops when it's exhausted.
314        let mut pending_tag: Option<Tag> = None;
315        for token in reader {
316            let token = token.map_err(|source| ReadError::Dataset { source })?;
317            match token {
318                dcmnorm_parser::dataset::DataToken::ElementHeader(header) => {
319                    pending_tag = Some(header.tag);
320                }
321                dcmnorm_parser::dataset::DataToken::PrimitiveValue(value) => {
322                    if let Some(tag) = pending_tag.take() {
323                        table.apply(tag, value);
324                    }
325                }
326                _ => {}
327            }
328        }
329
330        Ok(table)
331    }
332
333    fn apply(&mut self, tag: Tag, value: PrimitiveValue) {
334        let text = || value.to_str().trim_end_matches(['\0', ' ']).to_owned();
335        match tag {
336            tags::FILE_META_INFORMATION_GROUP_LENGTH => {}
337            tags::FILE_META_INFORMATION_VERSION => {
338                let bytes = value.to_bytes();
339                if bytes.len() >= 2 {
340                    self.information_version = [bytes[0], bytes[1]];
341                }
342            }
343            tags::MEDIA_STORAGE_SOP_CLASS_UID => self.media_storage_sop_class_uid = text(),
344            tags::MEDIA_STORAGE_SOP_INSTANCE_UID => self.media_storage_sop_instance_uid = text(),
345            tags::TRANSFER_SYNTAX_UID => self.transfer_syntax = text(),
346            tags::IMPLEMENTATION_CLASS_UID => self.implementation_class_uid = text(),
347            tags::IMPLEMENTATION_VERSION_NAME => self.implementation_version_name = Some(text()),
348            tags::SOURCE_APPLICATION_ENTITY_TITLE => {
349                self.source_application_entity_title = Some(text())
350            }
351            tags::SENDING_APPLICATION_ENTITY_TITLE => {
352                self.sending_application_entity_title = Some(text())
353            }
354            tags::RECEIVING_APPLICATION_ENTITY_TITLE => {
355                self.receiving_application_entity_title = Some(text())
356            }
357            tags::PRIVATE_INFORMATION_CREATOR_UID => {
358                self.private_information_creator_uid = Some(text())
359            }
360            tags::PRIVATE_INFORMATION => {
361                self.private_information = Some(value.to_bytes().into_owned());
362            }
363            _ => {}
364        }
365    }
366}
367
368/// Read the (0002,0000) File Meta Information Group Length element directly, by its known
369/// fixed wire format (Explicit VR Little Endian, VR UL, short-form 2-byte length, 4-byte
370/// value - PS3.5 §7.1) rather than through the general-purpose data set reader, since its
371/// value is needed *before* we know how many further bytes belong to the meta group at all.
372fn read_group_length_element<R: Read>(from: &mut R) -> Result<u32, ReadError> {
373    let mut header = [0u8; 8];
374    from.read_exact(&mut header)
375        .map_err(|source| ReadError::Io {
376            source,
377            context: "reading file meta group length element header",
378        })?;
379
380    let tag = Tag(
381        u16::from_le_bytes([header[0], header[1]]),
382        u16::from_le_bytes([header[2], header[3]]),
383    );
384    if tag != tags::FILE_META_INFORMATION_GROUP_LENGTH || &header[4..6] != b"UL" {
385        return Err(ReadError::UnexpectedToken {
386            context: "expected (0002,0000) UL as the first file meta element",
387        });
388    }
389    let value_len = u16::from_le_bytes([header[6], header[7]]);
390    if value_len != 4 {
391        return Err(ReadError::UnexpectedToken {
392            context: "file meta group length element has an unexpected value length",
393        });
394    }
395
396    let mut value = [0u8; 4];
397    from.read_exact(&mut value)
398        .map_err(|source| ReadError::Io {
399            source,
400            context: "reading file meta group length value",
401        })?;
402    Ok(u32::from_le_bytes(value))
403}
404
405fn primitive_element(tag: Tag, vr: VR, value: PrimitiveValue) -> InMemElement {
406    DataElement::new(tag, vr, value)
407}
408
409/// Builder for [`FileMetaTable`], mirroring `dicom-object`'s `FileMetaTableBuilder` fluent API.
410#[derive(Debug, Clone, Default)]
411pub struct FileMetaTableBuilder {
412    table: FileMetaTable,
413}
414
415impl FileMetaTableBuilder {
416    pub fn new() -> Self {
417        Self::default()
418    }
419
420    pub fn information_version(mut self, v: [u8; 2]) -> Self {
421        self.table.information_version = v;
422        self
423    }
424
425    pub fn media_storage_sop_class_uid(mut self, v: impl Into<String>) -> Self {
426        self.table.media_storage_sop_class_uid = v.into();
427        self
428    }
429
430    pub fn media_storage_sop_instance_uid(mut self, v: impl Into<String>) -> Self {
431        self.table.media_storage_sop_instance_uid = v.into();
432        self
433    }
434
435    pub fn transfer_syntax(mut self, v: impl Into<String>) -> Self {
436        self.table.transfer_syntax = v.into();
437        self
438    }
439
440    pub fn implementation_class_uid(mut self, v: impl Into<String>) -> Self {
441        self.table.implementation_class_uid = v.into();
442        self
443    }
444
445    pub fn implementation_version_name(mut self, v: impl Into<String>) -> Self {
446        self.table.implementation_version_name = Some(v.into());
447        self
448    }
449
450    pub fn source_application_entity_title(mut self, v: impl Into<String>) -> Self {
451        self.table.source_application_entity_title = Some(v.into());
452        self
453    }
454
455    pub fn sending_application_entity_title(mut self, v: impl Into<String>) -> Self {
456        self.table.sending_application_entity_title = Some(v.into());
457        self
458    }
459
460    pub fn receiving_application_entity_title(mut self, v: impl Into<String>) -> Self {
461        self.table.receiving_application_entity_title = Some(v.into());
462        self
463    }
464
465    pub fn private_information_creator_uid(mut self, v: impl Into<String>) -> Self {
466        self.table.private_information_creator_uid = Some(v.into());
467        self
468    }
469
470    pub fn private_information(mut self, v: impl Into<Vec<u8>>) -> Self {
471        self.table.private_information = Some(v.into());
472        self
473    }
474
475    /// Build the table. Unset mandatory fields (`media_storage_sop_class_uid`,
476    /// `media_storage_sop_instance_uid`, `implementation_class_uid`) are left as empty
477    /// strings rather than erroring - matching dcmnorm's existing tolerance for building
478    /// meta tables incrementally (e.g. the raw-dataset trial-parse fallback path, which only
479    /// knows the transfer syntax at first).
480    pub fn build(self) -> Result<FileMetaTable, WithMetaError> {
481        if self.table.implementation_class_uid.is_empty() {
482            let mut table = self.table;
483            table.implementation_class_uid = crate::IMPLEMENTATION_CLASS_UID.to_owned();
484            if table.implementation_version_name.is_none() {
485                table.implementation_version_name =
486                    Some(crate::IMPLEMENTATION_VERSION_NAME.to_owned());
487            }
488            return Ok(table);
489        }
490        Ok(self.table)
491    }
492}
493
494/// Read/write helpers shared with `mem.rs`.
495pub(crate) mod io_util {
496    pub fn trim_uid(uid: &str) -> &str {
497        uid.trim_end_matches(|c: char| c.is_whitespace() || c == '\0')
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    /// A corrupt/malicious file can declare an implausible (0002,0000) group length (up to
506    /// ~4GiB) while actually containing only a handful of bytes. Before this was hardened,
507    /// `read_meta_group` allocated `vec![0u8; group_length]` upfront - a failing allocation of
508    /// that shape aborts the process rather than returning a catchable error. This proves the
509    /// fix: the declared length is far larger than the (tiny) actual stream, so this must return
510    /// a clean `Err` quickly, not hang or attempt a multi-GB allocation.
511    #[test]
512    fn read_meta_group_rejects_group_length_exceeding_available_data() {
513        let mut bytes = Vec::new();
514        // (0002,0000) UL, value length 4, declared group length far beyond what follows.
515        bytes.extend_from_slice(&[0x02, 0x00, 0x00, 0x00]); // tag
516        bytes.extend_from_slice(b"UL"); // VR
517        bytes.extend_from_slice(&4u16.to_le_bytes()); // value length
518        bytes.extend_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); // group length: ~4GiB
519        bytes.extend_from_slice(b"only a few more bytes"); // far short of the declared length
520
521        let result = FileMetaTable::read_meta_group(std::io::Cursor::new(bytes));
522        assert!(
523            matches!(result, Err(ReadError::Io { .. })),
524            "expected a clean I/O error for a group length exceeding available data, got {result:?}"
525        );
526    }
527
528    /// A `group_length` of exactly 0 is a degenerate but well-formed case (an empty meta group)
529    /// and must not be confused with the "exceeds available data" error path above.
530    #[test]
531    fn read_meta_group_accepts_zero_group_length_as_empty() {
532        let mut bytes = Vec::new();
533        bytes.extend_from_slice(&[0x02, 0x00, 0x00, 0x00]);
534        bytes.extend_from_slice(b"UL");
535        bytes.extend_from_slice(&4u16.to_le_bytes());
536        bytes.extend_from_slice(&0u32.to_le_bytes()); // group length: 0
537
538        let result = FileMetaTable::read_meta_group(std::io::Cursor::new(bytes));
539        assert!(
540            result.is_ok(),
541            "expected a zero-length meta group to parse as empty, got {result:?}"
542        );
543    }
544}