lib3mf 0.1.6

Pure Rust implementation for 3MF (3D Manufacturing Format) parsing and writing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Package reading and validation functionality

use super::{
    CONTENT_TYPES_PATH, MODEL_REL_TYPE, Package, RELS_PATH, TEXTURE_REL_TYPE, THUMBNAIL_REL_TYPE,
};
use crate::error::{Error, Result};
use quick_xml::Reader;
use quick_xml::events::Event;
use std::io::Read;
use urlencoding::decode;
use zip::ZipArchive;

/// Maximum bytes to pre-allocate when reading a ZIP entry (64 KB).
///
/// ZIP local file headers contain an attacker-controlled `uncompressed_size` field.
/// Using that value directly as a `with_capacity` hint allows a crafted ZIP to
/// trigger an out-of-memory allocation before a single byte is decompressed.
/// We cap the hint at this safe value; the buffer will still grow as needed.
const MAX_PREALLOC_BYTES: usize = 64 * 1024;

/// Maximum bytes to read from a single ZIP entry (1 GB).
///
/// This prevents decompression bombs (zip bombs) where a small compressed
/// payload decompresses into gigabytes of data, exhausting available memory.
/// 1 GB is generous enough for any legitimate 3MF file while preventing
/// catastrophic memory exhaustion from malicious inputs.
const MAX_FILE_CONTENT_BYTES: usize = 1024 * 1024 * 1024;

/// Open a 3MF package from a reader
pub(super) fn open<R: Read + std::io::Seek>(reader: R, lenient: bool) -> Result<Package<R>> {
    let archive = ZipArchive::new(reader)?;
    let mut package = Package { archive, lenient };

    // Validate required OPC structure
    validate_opc_structure(&mut package, lenient)?;

    Ok(package)
}

/// Validate OPC package structure according to 3MF spec
fn validate_opc_structure<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    lenient: bool,
) -> Result<()> {
    // Validate required files exist
    if !has_file(package, CONTENT_TYPES_PATH) {
        return Err(Error::invalid_format_context(
            "OPC package structure",
            &format!(
                "Missing required file '{}'. \
                 This file defines content types for the package and is required by the OPC specification. \
                 The 3MF file may be corrupt or improperly formatted.",
                CONTENT_TYPES_PATH
            ),
        ));
    }

    if !has_file(package, RELS_PATH) {
        return Err(Error::invalid_format_context(
            "OPC package structure",
            &format!(
                "Missing required file '{}'. \
                 This file defines package relationships and is required by the OPC specification. \
                 The 3MF file may be corrupt or improperly formatted.",
                RELS_PATH
            ),
        ));
    }

    // Validate Content Types
    validate_content_types(package, lenient)?;

    // Validate that model relationship exists and points to valid file
    validate_model_relationship(package)?;

    // Validate all relationships point to existing files
    validate_all_relationships(package, lenient)?;

    Ok(())
}

/// Validate [Content_Types].xml structure
fn validate_content_types<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    lenient: bool,
) -> Result<()> {
    let content = get_file(package, CONTENT_TYPES_PATH)?;
    let mut reader = Reader::from_str(&content);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();

    let mut found_rels = false;
    let mut found_model = false;
    let mut default_extensions = std::collections::HashSet::new();
    let mut override_parts = std::collections::HashSet::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) | Ok(Event::Start(ref e)) => {
                let name = e.name();
                let name_str = std::str::from_utf8(name.as_ref())
                    .map_err(|e| Error::InvalidXml(e.to_string()))?;

                if name_str.ends_with("Default") {
                    let mut extension = None;
                    let mut content_type = None;

                    for attr in e.attributes() {
                        let attr = attr?;
                        let key = std::str::from_utf8(attr.key.as_ref())
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;
                        let value = std::str::from_utf8(&attr.value)
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;

                        match key {
                            "Extension" => extension = Some(value.to_string()),
                            "ContentType" => content_type = Some(value.to_string()),
                            _ => {}
                        }
                    }

                    if let (Some(ext), Some(ct)) = (extension, content_type) {
                        // N_XPX_0206_01: Check for empty extension
                        if !lenient && ext.is_empty() {
                            return Err(Error::InvalidFormat(
                                "Content type Default element cannot have empty Extension attribute".to_string()
                            ));
                        }

                        // N_XPX_0205_01: Check for duplicate default extensions
                        if !lenient && !default_extensions.insert(ext.clone()) {
                            return Err(Error::InvalidFormat(format!(
                                "Duplicate Default content type mapping for extension '{}'",
                                ext
                            )));
                        }

                        // N_XPX_0404_04: Validate PNG content type
                        if !lenient && ext.eq_ignore_ascii_case("png") && ct != "image/png" {
                            return Err(Error::InvalidFormat(format!(
                                "Invalid content type '{}' for PNG extension, must be 'image/png'",
                                ct
                            )));
                        }

                        // Check for required content types
                        if ext.eq_ignore_ascii_case("rels")
                            && ct == "application/vnd.openxmlformats-package.relationships+xml"
                        {
                            found_rels = true;
                        }
                        // Validate 3dmodel content type mapping
                        if ct == "application/vnd.ms-package.3dmanufacturing-3dmodel+xml" {
                            // Per 3MF spec, the extension for 3D model files is typically "model"
                            // However, "part" is also valid for backward compatibility
                            if !ext.eq_ignore_ascii_case("model")
                                && !ext.eq_ignore_ascii_case("part")
                            {
                                return Err(Error::InvalidFormat(format!(
                                    "Content type '{}' must use Extension='model' or 'part', not Extension='{}'",
                                    ct, ext
                                )));
                            }
                            found_model = true;
                        }
                    }
                } else if name_str.ends_with("Override") {
                    // Override elements can also define model content type
                    let mut part_name = None;
                    let mut content_type = None;

                    for attr in e.attributes() {
                        let attr = attr?;
                        let key = std::str::from_utf8(attr.key.as_ref())
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;
                        let value = std::str::from_utf8(&attr.value)
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;

                        match key {
                            "PartName" => part_name = Some(value.to_string()),
                            "ContentType" => content_type = Some(value.to_string()),
                            _ => {}
                        }
                    }

                    // N_XPX_0207_01: Check for empty PartName
                    if let Some(ref pn) = part_name
                        && pn.is_empty()
                    {
                        return Err(Error::InvalidFormat(
                            "Content type Override element cannot have empty PartName attribute"
                                .to_string(),
                        ));
                    }

                    if let (Some(pn), Some(ct)) = (part_name, content_type) {
                        // N_XPX_0205_02: Check for duplicate override parts
                        if !lenient && !override_parts.insert(pn.clone()) {
                            return Err(Error::InvalidFormat(format!(
                                "Duplicate Override content type for part '{}'",
                                pn
                            )));
                        }

                        if ct == "application/vnd.ms-package.3dmanufacturing-3dmodel+xml" {
                            found_model = true;
                        }
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(Error::Xml(e)),
            _ => {}
        }
        buf.clear();
    }

    if !found_rels {
        return Err(Error::invalid_format_context(
            "Content Types validation",
            "Missing required 'rels' extension definition in [Content_Types].xml. \
             The Content Types file must define a Default element for the '.rels' extension. \
             This is required by the OPC specification.",
        ));
    }

    if !found_model {
        return Err(Error::invalid_format_context(
            "Content Types validation",
            "Missing required model content type definition in [Content_Types].xml. \
             The file must define either a Default or Override element for the 3D model content type \
             ('application/vnd.ms-package.3dmanufacturing-3dmodel+xml'). \
             Check that the model file has a proper content type declaration.",
        ));
    }

    Ok(())
}

/// Validate model relationship exists and points to a valid file
fn validate_model_relationship<R: Read + std::io::Seek>(package: &mut Package<R>) -> Result<()> {
    let model_path = discover_model_path(package)?;

    // N_XXX_0208_01: Validate model filename structure
    // The 3MF spec expects model files to be named "3dmodel.model" or similar with
    // ASCII characters. We reject files that try to masquerade as standard model files
    // by using non-ASCII lookalike characters (e.g., Cyrillic letters that look like Latin).
    // N_SPX_0415_01: Also reject filenames with dot prefix (e.g., ".3dmodel.model")
    if let Some((_dir, filename)) = model_path.rsplit_once('/') {
        // Check for dot prefix (hidden file)
        if filename.starts_with('.') {
            return Err(Error::InvalidFormat(format!(
                "Model filename '{}' starts with a dot (hidden file). \
                 The 3MF specification requires standard naming for model files without dot prefix.",
                filename
            )));
        }

        if filename.contains("3dmodel") {
            // If the filename contains "3dmodel", check that any prefix uses ASCII
            // This catches cases like "Ôª3dmodel.model" (Cyrillic character before "3dmodel")
            if let Some(pos) = filename.find("3dmodel") {
                let prefix = &filename[..pos];
                if !prefix.is_empty() && !prefix.is_ascii() {
                    return Err(Error::InvalidFormat(format!(
                        "Model filename '{}' contains non-ASCII characters before '3dmodel'. \
                         The 3MF specification requires standard ASCII naming for model files.",
                        filename
                    )));
                }
            }
        }
    }

    // Verify the model file actually exists (try both encoded and decoded paths)
    let file_exists = has_file(package, &model_path) || {
        if let Ok(decoded) = decode(&model_path) {
            let decoded_path = decoded.into_owned();
            decoded_path != model_path && has_file(package, &decoded_path)
        } else {
            false
        }
    };

    if !file_exists {
        return Err(Error::InvalidFormat(format!(
            "Model relationship points to non-existent file: {}",
            model_path
        )));
    }

    Ok(())
}

/// Validate all relationships point to existing files
fn validate_all_relationships<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    lenient: bool,
) -> Result<()> {
    // Collect all .rels files in the archive
    let mut rels_files = Vec::new();
    for i in 0..package.archive.len() {
        if let Ok(file) = package.archive.by_index(i) {
            let name = file.name().to_string();
            if name.ends_with(".rels") {
                rels_files.push(name);
            }
        }
    }

    // Validate each .rels file
    for rels_file in &rels_files {
        // For part-specific .rels files (e.g., 3D/_rels/3dmodel.model.rels),
        // verify the .rels file name matches the part file it references
        if rels_file.contains("/_rels/") && rels_file != RELS_PATH {
            // Extract the part name from the .rels file path
            // Format is: <dir>/_rels/<partname>.<ext>.rels
            let parts: Vec<&str> = rels_file.split("/_rels/").collect();
            if parts.len() == 2 {
                let dir = parts[0];
                let rels_filename = parts[1];

                // Remove .rels suffix to get the part filename
                if let Some(part_filename) = rels_filename.strip_suffix(".rels") {
                    // Reconstruct the expected part file path
                    let expected_part_path = if dir.is_empty() {
                        part_filename.to_string()
                    } else {
                        format!("{}/{}", dir, part_filename)
                    };

                    // Verify the corresponding part file exists
                    if !lenient && !has_file(package, &expected_part_path) {
                        return Err(Error::InvalidFormat(format!(
                            "Relationship file '{}' references part '{}' which does not exist in the package.\n\
                             Per OPC specification, part-specific relationship files must have names matching their associated parts.",
                            rels_file, expected_part_path
                        )));
                    }
                }
            }
        }

        // Now validate the content of this .rels file
        let rels_content = get_file(package, rels_file)?;
        let mut reader = Reader::from_str(&rels_content);
        reader.config_mut().trim_text(true);
        let mut buf = Vec::new();

        let mut relationship_ids = std::collections::HashSet::new();
        let mut relationship_targets = std::collections::HashMap::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Empty(ref e)) | Ok(Event::Start(ref e)) => {
                    let name = e.name();
                    let name_str = std::str::from_utf8(name.as_ref())
                        .map_err(|e| Error::InvalidXml(e.to_string()))?;

                    if name_str.ends_with("Relationship") {
                        let mut target = None;
                        let mut rel_type = None;
                        let mut rel_id = None;

                        for attr in e.attributes() {
                            let attr = attr?;
                            let key = std::str::from_utf8(attr.key.as_ref())
                                .map_err(|e| Error::InvalidXml(e.to_string()))?;
                            let value = std::str::from_utf8(&attr.value)
                                .map_err(|e| Error::InvalidXml(e.to_string()))?;

                            match key {
                                "Target" => target = Some(value.to_string()),
                                "Type" => rel_type = Some(value.to_string()),
                                "Id" => rel_id = Some(value.to_string()),
                                _ => {}
                            }
                        }

                        // N_XPX_0413_01: Check for duplicate relationship IDs
                        if let Some(ref id) = rel_id {
                            if !lenient && !relationship_ids.insert(id.clone()) {
                                return Err(Error::InvalidFormat(format!(
                                    "Duplicate relationship ID '{}' in '{}'",
                                    id, rels_file
                                )));
                            }

                            // N_XPX_0405_04: Check if ID starts with a digit (only for root .rels)
                            if !lenient
                                && rels_file == RELS_PATH
                                && let Some(first_char) = id.chars().next()
                                && first_char.is_ascii_digit()
                            {
                                return Err(Error::InvalidFormat(format!(
                                    "Relationship ID '{}' in root .rels cannot start with a digit",
                                    id
                                )));
                            }
                        } else {
                            return Err(Error::InvalidFormat(format!(
                                "Relationship missing required Id attribute in '{}'",
                                rels_file
                            )));
                        }

                        // N_XPX_0405_03 & N_XPX_0405_05: Validate relationship Type values
                        if let Some(ref rt) = rel_type {
                            // N_XPX_0405_03: For 3dmodel.model.rels, check for incorrect model relationship type
                            if rels_file.contains("3dmodel.model.rels")
                                && rt.contains("3dmodel")
                                && rt != MODEL_REL_TYPE
                            {
                                return Err(Error::InvalidFormat(format!(
                                    "Incorrect relationship Type '{}' in 3dmodel.model.rels",
                                    rt
                                )));
                            }

                            // N_XPX_0405_05: For root .rels, check for incorrect thumbnail relationship type
                            if !lenient
                                && rels_file == RELS_PATH
                                && rt.contains("thumbnail")
                                && rt != THUMBNAIL_REL_TYPE
                            {
                                return Err(Error::InvalidFormat(format!(
                                    "Incorrect thumbnail relationship Type '{}' in root .rels",
                                    rt
                                )));
                            }

                            // N_XXM_0605_01: For 3dmodel.model.rels, check for incorrect texture relationship type
                            // If relationship target appears to be an image file (png/jpeg), it should use
                            // TEXTURE_REL_TYPE, not MODEL_REL_TYPE
                            if !lenient
                                && rels_file.contains("3dmodel.model.rels")
                                && let Some(ref t) = target
                            {
                                let target_lower = t.to_lowercase();
                                if (target_lower.ends_with(".png")
                                    || target_lower.ends_with(".jpeg")
                                    || target_lower.ends_with(".jpg"))
                                    && rt == MODEL_REL_TYPE
                                {
                                    return Err(Error::InvalidFormat(format!(
                                        "Incorrect relationship Type '{}' for texture file '{}' in 3dmodel.model.rels.\n\
                                             Per 3MF Material Extension spec, texture files must use relationship type '{}'.",
                                        rt, t, TEXTURE_REL_TYPE
                                    )));
                                }
                            }

                            // Validate relationship Type - must not contain query strings or fragments
                            if !lenient && rt.contains('?') {
                                return Err(Error::InvalidFormat(format!(
                                    "Relationship Type in '{}' cannot contain query string: {}",
                                    rels_file, rt
                                )));
                            }
                            if !lenient && rt.contains('#') {
                                return Err(Error::InvalidFormat(format!(
                                    "Relationship Type in '{}' cannot contain fragment identifier: {}",
                                    rels_file, rt
                                )));
                            }
                        }

                        if let Some(t) = target {
                            // N_XPX_0406_01 & N_XPX_0406_02: Check for duplicate targets
                            if !lenient && let Some(ref rt) = rel_type {
                                let key = (t.clone(), rt.clone());
                                if relationship_targets
                                    .insert(key, rel_id.clone().unwrap_or_default())
                                    .is_some()
                                {
                                    // For root .rels with MODEL_REL_TYPE, this is N_XPX_0406_01
                                    // For other .rels files, this is N_XPX_0406_02
                                    return Err(Error::InvalidFormat(format!(
                                        "Duplicate relationship to same target '{}' with type '{}' in '{}'",
                                        t, rt, rels_file
                                    )));
                                }
                            }

                            // Validate the target is a valid OPC part name
                            validate_opc_part_name(&t)?;

                            // Remove leading slash if present
                            let path_with_slash = if let Some(stripped) = t.strip_prefix('/') {
                                stripped.to_string()
                            } else {
                                t.clone()
                            };

                            // Try to find the file in the ZIP archive.
                            // Per OPC spec, Target attributes should use percent-encoding for non-ASCII,
                            // but in practice, we may encounter:
                            // 1. Percent-encoded in XML, percent-encoded in ZIP (%C3%86 in both)
                            // 2. Percent-encoded in XML, UTF-8 in ZIP (%C3%86 in XML, Æ in ZIP)
                            // 3. UTF-8 in XML, UTF-8 in ZIP (Æ in both)
                            // We try both the original name and the URL-decoded name.
                            let file_exists = if has_file(package, &path_with_slash) {
                                true
                            } else {
                                // Try URL-decoding in case ZIP has UTF-8 but XML has percent-encoding
                                if let Ok(decoded) = decode(&path_with_slash) {
                                    let decoded_path = decoded.into_owned();
                                    if decoded_path != path_with_slash {
                                        has_file(package, &decoded_path)
                                    } else {
                                        false
                                    }
                                } else {
                                    false
                                }
                            };

                            if !file_exists && !lenient {
                                return Err(Error::InvalidFormat(format!(
                                    "Relationship in '{}' points to non-existent file: {}",
                                    rels_file, path_with_slash
                                )));
                            }
                        }
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(Error::Xml(e)),
                _ => {}
            }
            buf.clear();
        }
    }

    Ok(())
}

/// Resolve the model file path within the package, trying both direct and URL-decoded paths
fn resolve_model_path<R: Read + std::io::Seek>(package: &mut Package<R>) -> Result<String> {
    // Discover model path from relationships (validation already done in open())
    let model_path = discover_model_path(package)?;

    // Determine which path to use: try the original first, then decoded
    if has_file(package, &model_path) {
        Ok(model_path)
    } else {
        // If the direct path fails, try URL-decoding
        if let Ok(decoded) = decode(&model_path) {
            let decoded_path = decoded.into_owned();
            if decoded_path != model_path && has_file(package, &decoded_path) {
                Ok(decoded_path)
            } else {
                Err(Error::MissingFile(model_path))
            }
        } else {
            Err(Error::MissingFile(model_path))
        }
    }
}

/// Get the main 3D model file content
pub(super) fn get_model<R: Read + std::io::Seek>(package: &mut Package<R>) -> Result<String> {
    let path_to_use = resolve_model_path(package)?;

    // Now read the file
    let mut file = package
        .archive
        .by_name(&path_to_use)
        .map_err(|_| Error::MissingFile(path_to_use.clone()))?;
    // Cap the pre-allocation hint: the ZIP header's `uncompressed_size` field is
    // attacker-controlled and must not be used as-is (ZIP size-deception / OOM).
    let capacity = (file.size() as usize).min(MAX_PREALLOC_BYTES);
    let mut content = String::with_capacity(capacity);
    // Bound the read to prevent decompression bombs from exhausting memory.
    (&mut file)
        .take(MAX_FILE_CONTENT_BYTES as u64 + 1)
        .read_to_string(&mut content)?;
    if content.len() > MAX_FILE_CONTENT_BYTES {
        return Err(Error::InvalidFormat(format!(
            "File '{}' exceeds maximum allowed size of {} bytes",
            path_to_use, MAX_FILE_CONTENT_BYTES
        )));
    }

    Ok(content)
}

/// Get a streaming reader for the main 3D model file
///
/// Returns a reader that decompresses the model file on-the-fly from the ZIP archive,
/// avoiding loading the entire file into memory at once. The returned reader implements
/// `Read` and borrows the package for its lifetime.
///
/// The reader is bounded by `MAX_FILE_CONTENT_BYTES` to prevent decompression bombs
/// (zip bombs) from exhausting available memory.
pub(super) fn get_model_reader<'a, R: Read + std::io::Seek>(
    package: &'a mut Package<R>,
) -> Result<impl Read + 'a> {
    let path_to_use = resolve_model_path(package)?;

    let file = package
        .archive
        .by_name(&path_to_use)
        .map_err(|_| Error::MissingFile(path_to_use.clone()))?;

    // Bound the read to prevent decompression bombs from exhausting memory.
    Ok(file.take(MAX_FILE_CONTENT_BYTES as u64 + 1))
}

/// Get a file from the package by name
pub(super) fn get_file<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    name: &str,
) -> Result<String> {
    let mut file = package
        .archive
        .by_name(name)
        .map_err(|_| Error::MissingFile(name.to_string()))?;
    // Cap the pre-allocation hint: the ZIP header's `uncompressed_size` field is
    // attacker-controlled and must not be used as-is (ZIP size-deception / OOM).
    let capacity = (file.size() as usize).min(MAX_PREALLOC_BYTES);
    let mut content = String::with_capacity(capacity);
    // Bound the read to prevent decompression bombs from exhausting memory.
    (&mut file)
        .take(MAX_FILE_CONTENT_BYTES as u64 + 1)
        .read_to_string(&mut content)?;
    if content.len() > MAX_FILE_CONTENT_BYTES {
        return Err(Error::InvalidFormat(format!(
            "File '{}' exceeds maximum allowed size of {} bytes",
            name, MAX_FILE_CONTENT_BYTES
        )));
    }
    Ok(content)
}

/// Check if a file exists in the package
pub(super) fn has_file<R: Read + std::io::Seek>(package: &mut Package<R>, name: &str) -> bool {
    package.archive.by_name(name).is_ok()
}

/// Get the number of files in the package
pub(super) fn len<R: Read + std::io::Seek>(package: &Package<R>) -> usize {
    package.archive.len()
}

/// Check if the package is empty
pub(super) fn is_empty<R: Read + std::io::Seek>(package: &Package<R>) -> bool {
    package.archive.is_empty()
}

/// Get a list of all file names in the package
pub(super) fn file_names<R: Read + std::io::Seek>(package: &mut Package<R>) -> Vec<String> {
    (0..package.archive.len())
        .filter_map(|i| {
            package
                .archive
                .by_index(i)
                .ok()
                .map(|f| f.name().to_string())
        })
        .collect()
}

/// Get a file as binary data
pub(super) fn get_file_binary<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    name: &str,
) -> Result<Vec<u8>> {
    let mut file = package
        .archive
        .by_name(name)
        .map_err(|_| Error::MissingFile(name.to_string()))?;
    let capacity = (file.size() as usize).min(MAX_PREALLOC_BYTES);
    let mut content = Vec::with_capacity(capacity);
    // Bound the read to prevent decompression bombs from exhausting memory.
    (&mut file)
        .take(MAX_FILE_CONTENT_BYTES as u64 + 1)
        .read_to_end(&mut content)?;
    if content.len() > MAX_FILE_CONTENT_BYTES {
        return Err(Error::InvalidFormat(format!(
            "File '{}' exceeds maximum allowed size of {} bytes",
            name, MAX_FILE_CONTENT_BYTES
        )));
    }
    Ok(content)
}

/// Discover the model file path from the relationships file
fn discover_model_path<R: Read + std::io::Seek>(package: &mut Package<R>) -> Result<String> {
    // Read the _rels/.rels file
    let rels_content = get_file(package, RELS_PATH)?;

    // Parse the XML to find the model relationship
    let mut reader = Reader::from_str(&rels_content);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) | Ok(Event::Start(ref e)) => {
                let name = e.name();
                let name_str = std::str::from_utf8(name.as_ref())
                    .map_err(|e| Error::InvalidXml(e.to_string()))?;

                if name_str.ends_with("Relationship") {
                    let mut target = None;
                    let mut rel_type = None;

                    for attr in e.attributes() {
                        let attr = attr?;
                        let key = std::str::from_utf8(attr.key.as_ref())
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;
                        let value = std::str::from_utf8(&attr.value)
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;

                        match key {
                            "Target" => target = Some(value.to_string()),
                            "Type" => rel_type = Some(value.to_string()),
                            _ => {}
                        }
                    }

                    // Check if this is the 3D model relationship
                    if let (Some(t), Some(rt)) = (target, rel_type)
                        && rt == MODEL_REL_TYPE
                    {
                        // Remove leading slash if present
                        let path = if let Some(stripped) = t.strip_prefix('/') {
                            stripped.to_string()
                        } else {
                            t
                        };

                        // Return the path as-is. The caller will handle trying both
                        // percent-encoded and decoded versions when accessing the file.
                        return Ok(path);
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(Error::InvalidXml(e.to_string())),
            _ => {}
        }
        buf.clear();
    }

    Err(Error::MissingFile(
        "3D model relationship not found".to_string(),
    ))
}

/// Validate OPC part name according to OPC specification
///
/// Part names must not contain:
/// - Fragment identifiers (#)
/// - Query strings (?)
/// - Path segments that are "." or ".."
/// - Empty path segments (consecutive slashes)
/// - Segments ending with "." (like "3D.")
/// - Control characters (newlines, tabs, etc.)
///
/// Note: Per OPC spec (ECMA-376), Target attributes should use percent-encoding
/// for non-ASCII characters. However, for compatibility with real-world files,
/// we accept both percent-encoded and UTF-8 characters.
fn validate_opc_part_name(part_name: &str) -> Result<()> {
    // Note: We don't strictly enforce ASCII-only here for compatibility.
    // Per OPC spec, non-ASCII should be percent-encoded, but many real-world
    // files include UTF-8 characters directly. We accept both and handle
    // URL-decoding when looking up files.

    // Check for control characters (newlines, tabs, etc.)
    // Per OPC spec, these are not allowed in part names
    if part_name.chars().any(|c| c.is_control()) {
        return Err(Error::InvalidFormat(format!(
            "Part name cannot contain control characters (newlines, tabs, etc.): {}",
            part_name.escape_debug()
        )));
    }

    // Check for fragment identifiers
    if part_name.contains('#') {
        return Err(Error::InvalidFormat(format!(
            "Part name cannot contain fragment identifier: {}",
            part_name
        )));
    }

    // Check for query strings
    if part_name.contains('?') {
        return Err(Error::InvalidFormat(format!(
            "Part name cannot contain query string: {}",
            part_name
        )));
    }

    // Split into path segments and validate each
    let segments: Vec<&str> = part_name.split('/').collect();

    for (idx, segment) in segments.iter().enumerate() {
        // Check for empty segments (consecutive slashes)
        if segment.is_empty() {
            // Allow leading slash (which creates empty first segment)
            if idx == 0 && part_name.starts_with('/') {
                continue;
            }
            return Err(Error::InvalidFormat(format!(
                "Part name cannot contain empty path segments (consecutive slashes): {}",
                part_name
            )));
        }

        // Check for "." or ".." segments
        if *segment == "." || *segment == ".." {
            return Err(Error::InvalidFormat(format!(
                "Part name cannot contain '.' or '..' segments: {}",
                part_name
            )));
        }

        // Check for segments ending with "."
        if segment.ends_with('.') {
            return Err(Error::InvalidFormat(format!(
                "Part name segments cannot end with '.': {}",
                part_name
            )));
        }
    }

    Ok(())
}

/// Get content type for a file path
#[allow(dead_code)]
fn get_content_type<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    path: &str,
) -> Result<String> {
    let content = get_file(package, CONTENT_TYPES_PATH)?;
    let mut reader = Reader::from_str(&content);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();

    let path_normalized = normalize_path(path);
    let extension = path.rsplit('.').next();

    // Parse content types file once, checking both Override and Default elements
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) | Ok(Event::Start(ref e)) => {
                let name = e.name();
                let name_str = std::str::from_utf8(name.as_ref())
                    .map_err(|e| Error::InvalidXml(e.to_string()))?;

                // Check for Override elements (specific path matches)
                if name_str.ends_with("Override") {
                    let mut part_name = None;
                    let mut content_type = None;

                    for attr in e.attributes() {
                        let attr = attr?;
                        let key = std::str::from_utf8(attr.key.as_ref())
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;
                        let value = std::str::from_utf8(&attr.value)
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;

                        match key {
                            "PartName" => part_name = Some(value.to_string()),
                            "ContentType" => content_type = Some(value.to_string()),
                            _ => {}
                        }
                    }

                    if let (Some(pn), Some(ct)) = (part_name, content_type) {
                        let pn_normalized = normalize_path(&pn);
                        if pn_normalized == path_normalized {
                            return Ok(ct);
                        }
                    }
                }
                // Check for Default elements (extension-based matches)
                else if name_str.ends_with("Default")
                    && let Some(ext) = extension
                {
                    let mut ext_attr = None;
                    let mut content_type = None;

                    for attr in e.attributes() {
                        let attr = attr?;
                        let key = std::str::from_utf8(attr.key.as_ref())
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;
                        let value = std::str::from_utf8(&attr.value)
                            .map_err(|e| Error::InvalidXml(e.to_string()))?;

                        match key {
                            "Extension" => ext_attr = Some(value.to_string()),
                            "ContentType" => content_type = Some(value.to_string()),
                            _ => {}
                        }
                    }

                    if let (Some(e), Some(ct)) = (ext_attr, content_type)
                        && e.eq_ignore_ascii_case(ext)
                    {
                        return Ok(ct);
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(Error::Xml(e)),
            _ => {}
        }
        buf.clear();
    }

    Err(Error::InvalidFormat(format!(
        "No content type found for file: {}",
        path
    )))
}

/// Normalize OPC path by removing leading slash
fn normalize_path(path: &str) -> &str {
    path.strip_prefix('/').unwrap_or(path)
}