Repository navigation
Expand file tree
/
Copy pathreader.rs
More file actions
2141 lines (1999 loc) · 88.5 KB
/
Copy pathreader.rs
File metadata and controls
2141 lines (1999 loc) · 88.5 KB
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! High-level reader API. Opens a `.rvt` / `.rfa` / `.rte` / `.rft` file
//! and exposes its streams + parsed metadata.
use crate::{
Error, Result,
basic_file_info::BasicFileInfo,
class_index, compression,
part_atom::PartAtom,
streams::{
BASIC_FILE_INFO, CONTENTS, FORMATS_LATEST, GLOBAL_CONTENT_DOCUMENTS,
GLOBAL_DOC_INCREMENT_TABLE, GLOBAL_ELEM_TABLE, GLOBAL_HISTORY, GLOBAL_LATEST,
GLOBAL_PARTITION_TABLE, PART_ATOM, PROJECT_INFORMATION, REVIT_PREVIEW_4_0,
TRANSMISSION_DATA,
},
};
use cfb::CompoundFile;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
fs::File,
io::{Cursor, Read},
path::Path,
sync::Arc,
};
/// Default maximum file size accepted by [`RevitFile::open`].
///
/// 2 GiB is above any real-world Revit project we've observed
/// (typical: few MB–a few hundred MB; worksharing extreme: ~1 GiB)
/// and well below "pathological or hostile" territory. Callers with
/// specific larger-file needs should use [`RevitFile::open_with_limits`].
pub const DEFAULT_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
/// Default maximum stream size accepted by [`RevitFile::read_stream`].
///
/// 256 MiB per stream is comfortably above any observed stream. The
/// largest legitimate stream we've seen in the corpus is ~40 MiB
/// (Global/Latest on a large worksharing project). Hostile input
/// with a claimed huge stream size will be rejected before a
/// multi-GB allocation.
pub const DEFAULT_MAX_STREAM_BYTES: u64 = 256 * 1024 * 1024;
/// The most inflated bytes the handle's partition memo holds at once
/// ([`RevitFile::inflated_partition`]). Each stream is capped, at 1 GiB by
/// default, but not their sum, so a crafted file of many streams held every
/// one (#1833). No real file comes near 16 GiB: the 1.13 GB client model
/// peaks at 5.1 GB in all (docs/viewer-api.md). Past it the memo is let go
/// whole before the next stream joins it; a reader keeps the `Arc` it was
/// given, and a later ask inflates again, so no output changes (Griffin,
/// 2026-11-12, "Bound it at 16 GiB").
const INFLATED_MEMO_BUDGET_BYTES: u64 = 16 << 30;
/// The most bytes the memo of [`RevitFile::header_hits`] holds at once. A hit
/// is a `usize`, and a partition carrying the ten-byte element-data header
/// every ten bytes is held again at 0.8 of its size, for each (stream,
/// header), for the handle's life (#1833). RE-144 counts the header's places
/// on the reference models at 50,951 (Core Interior, every partition), 40,149
/// (RE1 Architecture) and 5,277 (Einhoven): 0.4 MiB at most, and this is 165
/// times that. Past it the memo is dropped whole; a reader keeps the `Arc` it
/// was given and a later ask searches again, so no output changes.
const HEADER_HITS_BUDGET_BYTES: usize = 64 * 1024 * 1024;
/// Limits applied when opening a Revit file. Protects against
/// pathological or hostile input that would otherwise force
/// unbounded memory allocation.
///
/// RVT is a file-upload target, and bounded resource
/// consumption is a DoS-safety requirement, not a nice-to-have.
#[derive(Debug, Clone, Copy)]
pub struct OpenLimits {
/// Maximum file size accepted. File bytes are read into memory
/// entirely on open (CFB requires random access), so this
/// doubles as an upper bound on the initial allocation.
pub max_file_bytes: u64,
/// Maximum per-stream size accepted by [`RevitFile::read_stream`].
/// Streams larger than this cause an error rather than a
/// multi-GB alloc.
pub max_stream_bytes: u64,
/// Inflate limits applied to every `compression::inflate_at`
/// call sourced from this `RevitFile`. Keeps bounded-decompression
/// and open-limits consistent so a file opened under restrictive
/// limits doesn't accidentally re-inflate under permissive ones.
pub inflate_limits: compression::InflateLimits,
}
impl Default for OpenLimits {
fn default() -> Self {
Self {
max_file_bytes: DEFAULT_MAX_FILE_BYTES,
max_stream_bytes: DEFAULT_MAX_STREAM_BYTES,
inflate_limits: compression::InflateLimits::default(),
}
}
}
/// A stream a resource limit kept rvt-rs from reading whole (#1075). Every
/// reader that needed it went on without it, so what it holds is missing from
/// whatever the handle produced; [`RevitFile::unread_streams`] lists them.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnreadStream {
/// The stream, e.g. `Partitions/189`.
pub name: String,
/// Its stored size in bytes.
pub stored_bytes: u64,
/// Which limit stopped it.
pub kind: UnreadKind,
/// That limit in bytes.
pub limit: u64,
}
/// One phase of a project: its ElementId and, where the file names it, its
/// name ([`RevitFile::project_phases`]).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[non_exhaustive]
pub struct ProjectPhase {
/// The phase's ElementId, which [`RevitFile::set_export_phase`] takes as
/// well as its name.
pub id: i64,
/// The phase's name (`ProjectPhase.m_name`), if the file holds one.
pub name: Option<String>,
}
/// Which resource limit stopped a stream ([`UnreadStream`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum UnreadKind {
/// The stream is larger than [`OpenLimits::max_stream_bytes`] and was not
/// read at all.
StreamTooLarge,
/// One of its gzip members would inflate past
/// [`compression::InflateLimits::max_output_bytes`] and was left out.
MemberTooLarge,
/// Its members together would inflate past
/// [`compression::InflateLimits::max_stream_total_bytes_for`]; those after
/// the cap were left out.
InflatedTotalTooLarge,
}
impl UnreadKind {
/// Short machine-readable name, as the export diagnostics use it.
pub fn as_str(&self) -> &'static str {
match self {
Self::StreamTooLarge => "stream_too_large",
Self::MemberTooLarge => "inflated_member_too_large",
Self::InflatedTotalTooLarge => "inflated_total_too_large",
}
}
}
impl std::fmt::Display for UnreadStream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let what = match self.kind {
UnreadKind::StreamTooLarge => "is larger than the stream limit",
UnreadKind::MemberTooLarge => {
"has a compressed member that inflates past the inflate limit"
}
UnreadKind::InflatedTotalTooLarge => {
"inflates past the limit on one stream's inflated total"
}
};
// The name is text from the file and is quoted, as the phase error's is: a
// name with a newline or a control character cannot forge a line in a
// log (#1884).
write!(
f,
"stream {:?} ({} bytes stored) {what} of {} bytes, so what it holds is missing",
self.name, self.stored_bytes, self.limit
)
}
}
/// Opened Revit file. Holds the CFB handle + cached stream bytes.
pub struct RevitFile {
cfb: CompoundFile<Cursor<Vec<u8>>>,
/// Limits to apply on subsequent reads. Copied from the
/// `OpenLimits` passed at construction; defaults to
/// `OpenLimits::default()` for back-compat `open`/`open_bytes`.
limits: OpenLimits,
/// Memoised inflate of multi-member streams, keyed by stream path.
/// Every `Partitions/*` consumer (element records, arc walls, plan
/// loops, level records, IFC export overrides, the partition
/// scanner) used to read and inflate the same streams again, and a
/// geometry export runs a dozen of those passes over ~180 MiB of
/// inflated bytes. The streams are immutable for the lifetime of
/// the handle — `RevitFile` never writes — so one inflate serves
/// all of them.
inflated: std::collections::HashMap<String, Arc<compression::InflatedStream>>,
/// The inflated bytes `inflated` holds, kept under
/// [`INFLATED_MEMO_BUDGET_BYTES`].
inflated_bytes: u64,
/// Every `Partitions/*` stream inflated so far, held or not: the
/// progress count, which a count of `inflated`'s keys would lower each
/// time the memo is let go.
partitions_inflated: BTreeSet<String>,
/// Memoised `Partitions/NN` string-record extraction. The UTF-16
/// decode over the whole partition is the single most expensive
/// step after inflate, and unit recovery, storey names and the
/// partition MVP each asked for it independently.
partition_strings: Option<Arc<Vec<crate::object_graph::StringRecord>>>,
/// Memoised RE-35 second-prologue ElementIds. Every category sweep and
/// the unattributed count read the same result, so the record chains
/// are walked once per file.
second_prologue_ids: Option<Arc<crate::partition_element_records::SecondPrologueIds>>,
/// Memoised RE-38 family and type names.
element_names: Option<Arc<crate::partition_names::ElementNames>>,
/// Memoised design option sets and their primary options (RE-40).
design_options: Option<Arc<crate::partition_design_options::DesignOptions>>,
/// Memoised phase order and the elements not in the export phase (#328).
phase_filter: Option<Arc<crate::native_phases::PhaseFilter>>,
/// The ElementId of the phase [`RevitFile::set_export_phase`] chose.
chosen_export_phase: Option<i64>,
/// The Areas of a Revit 2015 to 2023 file the reader left unwritten, by
/// why (RE-324), set when the Areas are read.
unwritten_areas: BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
/// What became of each frame at the markers of a Revit 2008 to 2023 file
/// (#1389), set when its element records are recovered.
element_record_stages: Option<crate::partition_element_records_2023::RecordStages>,
/// Whether the recovery lists the frames that stop, for the log of
/// decisions ([`Self::record_frame_decisions`], #1389).
frame_decisions: bool,
/// The chain records of Revit 2024 and later, declared, whose entry block
/// did not read when the Areas were looked for (RE-333).
dropped_chain_entries: usize,
/// Memoised production walk: the elements
/// [`crate::walker::iter_elements_with_control`] yields for a minimum
/// score and walker limits. An export walks once to write and again for
/// its diagnostics' class counts; the second reuses the first.
// Tracker: B71.
walk: Option<CachedWalk>,
/// Memoised partition ArcWall scan for a release and walker limits: the
/// production walk, the partition MVP and the IFC export (twice) each ran
/// the same scan over every partition.
arc_wall_scan: Option<CachedArcWallScan>,
/// Where an export in progress reports each `Partitions/*` stream it
/// inflates, and how many there are ([`Self::report_partition_inflates_to`]).
/// Held as `AssertUnwindSafe` so the handle keeps the unwind-safety it
/// has without one: a control wraps a caller's closure, which is neither.
partition_progress: Option<(
std::panic::AssertUnwindSafe<crate::control::WalkerControl>,
u64,
)>,
/// The partition recovery's section in progress, plus one, and its number
/// of sections; 0 while no recovery runs ([`Self::report_recovery_section`]).
/// Plain integers, not atomics: interior mutability would take `Freeze` off
/// the handle, a change to its public traits.
recovery_section: u64,
recovery_sections: u64,
/// Memoised data objects (RE-153) of each partition stream: the
/// original symbols, railing types and MEP systems each scanned every
/// partition for them.
// Tracker: B80.
data_objects: std::collections::HashMap<String, PartitionDataObjects>,
/// Memoised offsets of an element-data header in a partition, by stream
/// and header: a dozen element-data readers each searched every partition
/// for the release's header.
header_hits: std::collections::HashMap<(String, Vec<u8>), Arc<Vec<usize>>>,
/// The bytes `header_hits` holds, one `usize` a hit, kept under
/// [`HEADER_HITS_BUDGET_BYTES`].
header_hits_bytes: usize,
/// Memoised native extraction preamble: each native consumer read
/// the schema, the element index and the increments again.
// Tracker: B82.
native_preamble: Option<Arc<crate::native_document::Preamble>>,
/// How many deferred history episode pointers the memoised preamble read:
/// 0 for every file the default reading accepts. Only the research route
/// of RE-342 reads a history that holds any, and the default reading is
/// never answered with a preamble that did.
native_preamble_deferred: usize,
/// Memoised parameter-definition pass of native extraction, with the
/// options it was read under (#1237).
native_definitions: Option<(
crate::native_document::DefinitionKey,
Arc<crate::native_document::DefinitionPass>,
)>,
/// Memoised index of every native record's partitions, one for each
/// channel a pass reads alone (#1032): each native pass walked every
/// partition again to find its records. 102 holds the elements' records,
/// 103 their saved graphics (#1694).
native_record_indexes: BTreeMap<u64, Arc<crate::native_document::RecordIndex>>,
/// How many of its two end faces the Revit solid of each curtain mullion
/// keeps, and how many of those ends have a partner, by ElementId, where the
/// boxes of its curtain wall's mullions say (RE-268, RE-439), set when the
/// partition's mullions are read, for the pass that draws their bodies from
/// saved meshes (RE-404).
mullion_kept_ends: Option<Arc<BTreeMap<u32, crate::partition_schema_mvp::KeptEnds>>>,
/// The unit axis each curtain mullion runs along, in the model's frame, by
/// ElementId, set when the partition's mullions are read, for the pass that
/// draws them from saved meshes (RE-418).
mullion_axes: Option<Arc<BTreeMap<u32, [f64; 3]>>>,
/// Memoised `Formats/Latest` classes: a dozen partition readers each
/// read and parsed the schema again for a few class tags.
schema_classes_memo: Option<Arc<crate::formats::SchemaClasses>>,
layout_release_memo: Option<u32>,
/// Memoised display units of the project's `UnitsElem` (RE-445): the
/// export's model and its diagnostics both ask for them.
project_units_memo:
Option<Arc<Result<Option<crate::native_project_units::ProjectUnits>, String>>>,
/// Memoised material names (RE-58, RE-203), by release and the hash of
/// the declared ids they were read for: half a dozen material steps of
/// an export each asked for them.
material_names: std::collections::HashMap<(u32, u64), Arc<BTreeMap<u32, String>>>,
/// Memoised material appearances, keyed as `material_names` is:
/// the material, wall and layer steps of an export each ask for them.
material_appearances: std::collections::HashMap<
(u32, u64),
Arc<BTreeMap<u32, crate::partition_materials::MaterialAppearance>>,
>,
/// Memoised materials each category's graphics styles name (RE-206).
category_style_materials: Option<Arc<BTreeMap<i64, BTreeSet<u32>>>>,
/// Streams a resource limit kept from being read whole (#1075).
unread_streams: Vec<UnreadStream>,
/// The readers that stopped at a work budget under this handle's walk
/// or exports, with how often (#1833, [`crate::budget`]).
budget_stops: crate::budget::Stops,
/// Doors and windows written as such though their type's record was not
/// read (#1247).
unread_type_doors_windows: BTreeSet<u32>,
/// Types and text parameters (Fire Rating, Manufacturer) left out because
/// the copies of a family type table's entry, or an entry and RE-77's,
/// disagree (RE-354).
disagreeing_type_texts: BTreeSet<(u32, &'static str)>,
/// Memoised steps of the walls' native records that name a cutting element
/// (`research::native_wall_cuts::wall_cut_steps`), by wall, and the walls
/// whose record was looked for, found or not: the openings the walls
/// carry and the walls drawn from their saved mesh (RE-340) each asked for
/// the same records.
pub(crate) wall_cut_steps_memo: BTreeMap<u64, Vec<crate::native_wall_cuts::WallCutStep>>,
pub(crate) wall_cut_steps_asked: BTreeSet<u64>,
/// Of the walls in `wall_cut_steps_asked`, those whose record was read as a
/// wall's and holds no base join (#1046): the same walk of the records
/// gives it (`research::native_wall_cuts::walls_with_no_base_join`).
pub(crate) wall_no_base_join_memo: BTreeSet<u64>,
/// Family instances written as spaces that were left out because their
/// family draws no model form (RE-312, #1262), by class.
bodiless_family_spaces: BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
/// How many family instances written as spaces were not checked for a 3D
/// body, and why, where the check could not run (RE-312).
bodiless_family_space_error: Option<(usize, String)>,
/// Family instances left out because their type draws nothing visible
/// (RE-363), by class, and the error that stopped that check.
invisible_type_instances:
BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
invisible_type_error: Option<(usize, String)>,
/// Curtain panels left out because they are the host panel of another
/// curtain wall's grid (#1975), by class, and the error that stopped that
/// check.
host_panel_instances: BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
host_panel_error: Option<(usize, String)>,
/// The copy of an element's data each reader took a value from, by
/// ElementId, noted where the reader chose it (#1360). `None` unless the
/// export asked for the provenance table: the readers then note nothing.
value_sources: Option<crate::ifc::element_provenance::ValueSourceNotes>,
}
/// The limits it was opened with and how many streams it has inflated so
/// far; the container's bytes and the caches are left out.
impl std::fmt::Debug for RevitFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RevitFile")
.field("limits", &self.limits)
.field("inflated_streams", &self.inflated.len())
.finish_non_exhaustive()
}
}
/// A partition stream's data objects, each at its offset (RE-153).
#[cfg(feature = "unstable-research")]
pub type PartitionDataObjects = Arc<Vec<(usize, crate::partition_room_parameters::DataObject)>>;
#[cfg(not(feature = "unstable-research"))]
pub(crate) type PartitionDataObjects =
Arc<Vec<(usize, crate::partition_room_parameters::DataObject)>>;
/// A memoised walk: its minimum score, its limits and its elements.
type CachedWalk = (
i64,
crate::walker::WalkerLimits,
Arc<Vec<crate::walker::DecodedElement>>,
);
/// A memoised ArcWall scan: its release, its limits and its result.
type CachedArcWallScan = (
u32,
crate::walker::WalkerLimits,
Arc<crate::partition_arc_walls::PartitionArcWallScan>,
);
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Summary {
pub file_size: u64,
pub streams: Vec<String>,
pub version: u32,
pub build: Option<String>,
pub original_path: Option<String>,
pub guid: Option<String>,
pub locale: Option<String>,
pub partition_stream: Option<String>,
pub partatom: Option<PartAtom>,
pub class_name_count: usize,
pub class_name_sample: Vec<String>,
}
impl RevitFile {
/// Open a Revit file from disk, under the default [`OpenLimits`].
///
/// # Errors
///
/// [`Error::Io`] when the file cannot be read (its message names the
/// path), [`Error::NotACfbFile`] when it does not start with the OLE2 /
/// MS-CFB magic bytes (`D0 CF 11 E0 A1 B1 1A E1`), [`Error::TooLarge`]
/// when it is larger than [`OpenLimits::max_file_bytes`], and
/// [`Error::Cfb`] when its container does not open.
///
/// # Examples
///
/// ```
/// use rvt::RevitFile;
///
/// let mut rf = RevitFile::open("corpus/tier1/architectural-2024/architectural-2024.rvt")?;
/// let summary = rf.summarize_strict()?;
/// println!("Revit {}", summary.version);
/// # Ok::<(), rvt::Error>(())
/// ```
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::open_with_limits(path, OpenLimits::default())
}
/// Open a Revit file from disk with explicit resource limits.
///
/// Stats the file before reading; refuses if file size exceeds
/// `limits.max_file_bytes` to prevent multi-GB allocations from
/// a hostile input. Back-compat [`Self::open`] calls this with
/// `OpenLimits::default()` (2 GiB file, 256 MiB per stream, 256
/// MiB per inflate).
///
/// ```
/// use rvt::reader::{OpenLimits, RevitFile};
///
/// // Only accept files up to 100 MB.
/// let limits = OpenLimits {
/// max_file_bytes: 100 * 1024 * 1024,
/// ..OpenLimits::default()
/// };
/// let path = "corpus/tier1/architectural-2024/architectural-2024.rvt";
/// let rf = RevitFile::open_with_limits(path, limits)?;
/// assert!(!rf.stream_names().is_empty());
///
/// // A file over the limit is refused before it is read.
/// let tiny = OpenLimits { max_file_bytes: 1024, ..OpenLimits::default() };
/// assert!(matches!(
/// RevitFile::open_with_limits(path, tiny),
/// Err(rvt::Error::TooLarge { .. })
/// ));
/// # Ok::<(), rvt::Error>(())
/// ```
pub fn open_with_limits(path: impl AsRef<Path>, limits: OpenLimits) -> Result<Self> {
let path = path.as_ref();
// Name the file in I/O errors: a batch run over a folder otherwise
// reports a bare "No such file or directory". The `ErrorKind` is kept
// so callers (and the Python bindings) can still match on it.
let with_path = |e: std::io::Error| {
Error::Io(std::io::Error::new(
e.kind(),
format!("{}: {e}", path.display()),
))
};
let metadata = std::fs::metadata(path).map_err(with_path)?;
if metadata.is_dir() {
return Err(Error::Io(std::io::Error::new(
std::io::ErrorKind::IsADirectory,
format!(
"{}: is a directory, not a .rvt / .rfa / .rte / .rft file",
path.display()
),
)));
}
if metadata.len() > limits.max_file_bytes {
return Err(Error::TooLarge {
what: "the file".into(),
size: metadata.len(),
limit: limits.max_file_bytes,
});
}
let mut f = File::open(path).map_err(with_path)?;
let mut bytes = Vec::with_capacity(metadata.len() as usize);
f.read_to_end(&mut bytes).map_err(with_path)?;
Self::open_bytes_with_limits(bytes, limits).map_err(|e| e.in_file(path))
}
/// Open a Revit file from an in-memory byte buffer.
///
/// Useful for callers that have the file bytes already (e.g. streamed
/// over the network). Equivalent to `open` after a `read_to_end`.
///
/// # Errors
///
/// [`Error::NotACfbFile`] when the bytes do not start with the OLE2 /
/// MS-CFB magic bytes, [`Error::TooLarge`] when they exceed
/// [`OpenLimits::max_file_bytes`], and [`Error::Cfb`] when the container
/// does not open.
///
/// # Examples
///
/// ```
/// use rvt::RevitFile;
/// // Four bytes that are definitely not a valid CFB file.
/// let result = RevitFile::open_bytes(b"nope".to_vec());
/// assert!(matches!(result, Err(rvt::Error::NotACfbFile)));
/// ```
pub fn open_bytes(bytes: Vec<u8>) -> Result<Self> {
Self::open_bytes_with_limits(bytes, OpenLimits::default())
}
/// Open-bytes variant with explicit limits. The byte count check
/// has already been done by the caller if they came through
/// [`Self::open_with_limits`]; here it's repeated for in-memory
/// paths that skip disk stat.
///
/// ```
/// use rvt::reader::{OpenLimits, RevitFile};
///
/// let bytes = std::fs::read("corpus/tier1/architectural-2024/architectural-2024.rvt")?;
/// let rf = RevitFile::open_bytes_with_limits(bytes.clone(), OpenLimits::default())?;
/// assert!(!rf.stream_names().is_empty());
///
/// // Bytes over the limit are refused before they are parsed.
/// let tiny = OpenLimits { max_file_bytes: 1024, ..OpenLimits::default() };
/// assert!(matches!(
/// RevitFile::open_bytes_with_limits(bytes, tiny),
/// Err(rvt::Error::TooLarge { .. })
/// ));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn open_bytes_with_limits(bytes: Vec<u8>, limits: OpenLimits) -> Result<Self> {
if (bytes.len() as u64) > limits.max_file_bytes {
return Err(Error::TooLarge {
what: "the in-memory buffer".into(),
size: bytes.len() as u64,
limit: limits.max_file_bytes,
});
}
if bytes.len() < 8 || bytes[..8] != [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1] {
return Err(Error::NotACfbFile);
}
let cfb = CompoundFile::open(Cursor::new(bytes)).map_err(|e| Error::Cfb {
op: "open",
path: None,
source: e,
})?;
Ok(Self {
cfb,
limits,
inflated: std::collections::HashMap::new(),
inflated_bytes: 0,
partitions_inflated: BTreeSet::new(),
partition_strings: None,
second_prologue_ids: None,
element_names: None,
design_options: None,
phase_filter: None,
chosen_export_phase: None,
unwritten_areas: BTreeMap::new(),
element_record_stages: None,
frame_decisions: false,
dropped_chain_entries: 0,
walk: None,
arc_wall_scan: None,
partition_progress: None,
recovery_section: 0,
recovery_sections: 0,
data_objects: std::collections::HashMap::new(),
header_hits: std::collections::HashMap::new(),
header_hits_bytes: 0,
native_preamble: None,
native_preamble_deferred: 0,
native_definitions: None,
native_record_indexes: BTreeMap::new(),
mullion_kept_ends: None,
mullion_axes: None,
schema_classes_memo: None,
layout_release_memo: None,
project_units_memo: None,
material_names: std::collections::HashMap::new(),
material_appearances: std::collections::HashMap::new(),
category_style_materials: None,
unread_streams: Vec::new(),
budget_stops: crate::budget::Stops::new(),
unread_type_doors_windows: BTreeSet::new(),
disagreeing_type_texts: BTreeSet::new(),
wall_cut_steps_memo: BTreeMap::new(),
wall_cut_steps_asked: BTreeSet::new(),
wall_no_base_join_memo: BTreeSet::new(),
bodiless_family_spaces: BTreeMap::new(),
bodiless_family_space_error: None,
invisible_type_instances: BTreeMap::new(),
invisible_type_error: None,
host_panel_instances: BTreeMap::new(),
host_panel_error: None,
value_sources: None,
})
}
/// The streams a resource limit kept from being read whole since this
/// handle was opened, in the order they were met (#1075). Empty when
/// nothing was cut; when not, the readers went on without them, so
/// anything produced from this handle is missing what they hold.
pub fn unread_streams(&self) -> &[UnreadStream] {
&self.unread_streams
}
/// The readers that stopped at a work budget since this handle was
/// opened, with how often (#1833): what was past each budget is missing
/// from anything produced from this handle, as an unread stream's
/// content is.
pub(crate) fn budget_stops(&self) -> &crate::budget::Stops {
&self.budget_stops
}
/// Keep the stops collected under work done for this handle
/// ([`crate::budget::Notes`]).
pub(crate) fn keep_budget_stops(&mut self, stops: crate::budget::Stops) {
for (what, times) in stops {
*self.budget_stops.entry(what).or_insert(0) += times;
}
}
/// The doors and windows this handle's export wrote as doors and
/// windows though their type's record was not read (#1247), by
/// ElementId: whether each draws geometry, or is its opening alone in
/// Revit's export as a cased opening is, is not known.
pub(crate) fn unread_type_doors_windows(&self) -> &BTreeSet<u32> {
&self.unread_type_doors_windows
}
pub(crate) fn note_unread_type_doors_windows(&mut self, ids: impl IntoIterator<Item = u32>) {
self.unread_type_doors_windows.extend(ids);
}
/// The type text parameters left out for want of agreeing copies (RE-354).
pub(crate) fn disagreeing_type_texts(&self) -> &BTreeSet<(u32, &'static str)> {
&self.disagreeing_type_texts
}
pub(crate) fn note_disagreeing_type_texts(
&mut self,
keys: impl IntoIterator<Item = (u32, &'static str)>,
) {
self.disagreeing_type_texts.extend(keys);
}
/// What became of each frame at the markers of this Revit 2008 to 2023
/// file in the recovery of its element records (#1389); `None` where that
/// recovery has not run, or the file takes another layout.
pub(crate) fn element_record_stages(
&self,
) -> Option<&crate::partition_element_records_2023::RecordStages> {
self.element_record_stages.as_ref()
}
pub(crate) fn note_element_record_stages(
&mut self,
stages: crate::partition_element_records_2023::RecordStages,
) {
self.element_record_stages = Some(stages);
}
/// Note that the walk dropped the element the record recovery handed under
/// `id`, because an element with that ElementId was already in it (#1389).
pub(crate) fn note_id_already_held(&mut self, id: u32) {
if let Some(stages) = self.element_record_stages.as_mut() {
stages.note_held(id);
}
}
/// Start or stop listing, as the recovery of a Revit 2008 to 2023 file's
/// element records goes, each frame that stops (#1389), which the log of
/// decisions holds. The counts need no list and are kept either way.
/// Starting drops the memoised production walk, since a walk made without
/// the list has none to give.
pub(crate) fn record_frame_decisions(&mut self, on: bool) {
if on && !self.frame_decisions {
self.walk = None;
}
self.frame_decisions = on;
}
/// Whether the recovery lists the frames that stop
/// ([`Self::record_frame_decisions`]).
pub(crate) fn recording_frame_decisions(&self) -> bool {
self.frame_decisions
}
/// The family instances written as spaces that this handle's export left
/// out because their family draws no model form (RE-312), by class, each
/// with the frame it was read from (#1326).
pub(crate) fn bodiless_family_spaces(
&self,
) -> &BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>> {
&self.bodiless_family_spaces
}
pub(crate) fn note_bodiless_family_spaces(
&mut self,
classes: BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
) {
self.bodiless_family_spaces = classes;
}
/// The family instances left out because their type draws nothing visible
/// (RE-363), by class.
pub(crate) fn invisible_type_instances(
&self,
) -> &BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>> {
&self.invisible_type_instances
}
pub(crate) fn note_invisible_type_instances(
&mut self,
classes: BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
) {
self.invisible_type_instances = classes;
}
pub(crate) fn invisible_type_error(&self) -> Option<&(usize, String)> {
self.invisible_type_error.as_ref()
}
pub(crate) fn note_invisible_type_error(&mut self, checked: usize, error: String) {
self.invisible_type_error = Some((checked, error));
}
pub(crate) fn host_panel_instances(
&self,
) -> &BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>> {
&self.host_panel_instances
}
pub(crate) fn note_host_panel_instances(
&mut self,
classes: BTreeMap<String, Vec<crate::partition_element_records::LeftOutElement>>,
) {
self.host_panel_instances = classes;
}
pub(crate) fn host_panel_error(&self) -> Option<&(usize, String)> {
self.host_panel_error.as_ref()
}
pub(crate) fn note_host_panel_error(&mut self, checked: usize, error: String) {
self.host_panel_error = Some((checked, error));
}
/// Forget what an earlier production walk noted for its diagnostics: the
/// Areas left unwritten, the family spaces left out for want of a body,
/// the error that stopped that check, and the doors and windows written
/// though their type was not read. The partition recovery notes them, and
/// only when it finds some, so each walk starts from none: the notes
/// follow the memoised walk that produced them.
pub(crate) fn reset_export_notes(&mut self) {
self.element_record_stages = None;
self.unwritten_areas.clear();
self.dropped_chain_entries = 0;
self.bodiless_family_spaces.clear();
self.bodiless_family_space_error = None;
self.invisible_type_instances.clear();
self.invisible_type_error = None;
self.host_panel_instances.clear();
self.host_panel_error = None;
self.unread_type_doors_windows.clear();
self.disagreeing_type_texts.clear();
if let Some(noted) = self.value_sources.as_mut() {
noted.clear();
}
}
/// Whether the readers note the copy they took each value from
/// ([`Self::record_value_sources`]).
pub(crate) fn recording_value_sources(&self) -> bool {
self.value_sources.is_some()
}
/// Start or stop noting the copy each reader takes a value from (#1360),
/// which the provenance table lists. Starting drops the memoised
/// production walk, since a walk made while the readers noted nothing has
/// no notes to give; stopping drops the notes. A reader that is not asked
/// notes nothing, so the default export does no extra work.
pub(crate) fn record_value_sources(&mut self, on: bool) {
if on == self.value_sources.is_some() {
return;
}
if on {
self.value_sources = Some(BTreeMap::new());
self.walk = None;
} else {
self.value_sources = None;
}
}
/// Note that a reader took a value of the element `element_id` from
/// `source`, in place of an earlier note of the same reader's. Does
/// nothing unless [`Self::record_value_sources`] is on.
pub(crate) fn note_value_source(
&mut self,
element_id: u32,
source: crate::ifc::element_provenance::ValueSource,
) {
let Some(noted) = self.value_sources.as_mut() else {
return;
};
let sources = noted.entry(element_id).or_default();
match sources.iter_mut().find(|held| held.reader == source.reader) {
Some(held) => *held = source,
None => sources.push(source),
}
}
/// Note for `owner`, under `as_reader`, the value source that `from` has
/// under `reader`, where the record was read once for `from` and `owner`
/// uses it: a type's parameters, read for the instances of the type
/// (#1368). The record is `from`'s, so it is listed in `parts` with
/// `from`'s id. Does nothing unless [`Self::record_value_sources`] is on
/// and `from` has one.
pub(crate) fn attribute_value_source(
&mut self,
from: u32,
reader: &str,
owner: u32,
as_reader: &str,
) {
let source = self
.value_sources
.as_ref()
.and_then(|noted| noted.get(&from))
.and_then(|sources| sources.iter().find(|held| held.reader == reader))
.cloned();
if let Some(mut source) = source {
source.reader = as_reader.to_string();
// The record is the other element's: name it in `parts`.
if let (true, Some(stream), Some(offset)) = (
source.parts.is_empty(),
source.stream.take(),
source.offset.take(),
) {
source
.parts
.push(crate::ifc::element_provenance::SourcePart {
element_id: from,
stream,
offset,
});
}
self.note_value_source(owner, source);
}
}
/// Note for `owner`, under `as_reader`, one source made of the records
/// that the value sources of `from` under `reader` name, where several
/// records give the value (the run types of a stair's runs, #1368). It
/// lists one part for each of `from`; if any of them has no note, nothing
/// is noted, since a list that left a record out would not be the records
/// the value was read from. `rule` is how each record's copy was chosen.
/// Does nothing unless [`Self::record_value_sources`] is on.
pub(crate) fn attribute_value_sources(
&mut self,
from: impl IntoIterator<Item = u32>,
reader: &str,
owner: u32,
as_reader: &str,
rule: crate::ifc::element_provenance::CopyRule,
) {
let Some(noted) = self.value_sources.as_ref() else {
return;
};
let parts: Option<Vec<crate::ifc::element_provenance::SourcePart>> = from
.into_iter()
.map(|id| {
let source = noted.get(&id)?.iter().find(|held| held.reader == reader)?;
Some(crate::ifc::element_provenance::SourcePart {
element_id: id,
stream: source.stream.clone()?,
offset: source.offset?,
})
})
.collect();
let Some(parts) = parts.filter(|parts| !parts.is_empty()) else {
return;
};
let copies = parts.len();
self.note_value_source(
owner,
crate::ifc::element_provenance::ValueSource::from_parts(as_reader, rule, copies, parts),
);
}
/// Take back the note of `reader` for `element_id`, where the value was
/// not used after all (a record selected, then found not to give the
/// value). Does nothing unless [`Self::record_value_sources`] is on.
pub(crate) fn forget_value_source(&mut self, element_id: u32, reader: &str) {
if let Some(sources) = self
.value_sources
.as_mut()
.and_then(|noted| noted.get_mut(&element_id))
{
sources.retain(|held| held.reader != reader);
}
}
/// The notes of [`Self::note_value_source`], by ElementId; `None` unless
/// [`Self::record_value_sources`] is on.
pub(crate) fn value_sources(
&self,
) -> Option<&crate::ifc::element_provenance::ValueSourceNotes> {
self.value_sources.as_ref()
}
/// How many family instances written as spaces were not checked for a 3D
/// body, and why (RE-312).
pub(crate) fn bodiless_family_space_error(&self) -> Option<&(usize, String)> {
self.bodiless_family_space_error.as_ref()
}
pub(crate) fn note_bodiless_family_space_error(&mut self, checked: usize, error: String) {
self.bodiless_family_space_error = Some((checked, error));
}
fn note_unread(&mut self, unread: UnreadStream) {
if !self
.unread_streams
.iter()
.any(|known| known.name == unread.name && known.kind == unread.kind)
{
self.unread_streams.push(unread);
}
}
/// Record `err` against stream `name` when it is an inflate stopped by a
/// limit, for readers that inflate a stream themselves.
pub(crate) fn note_inflate_error(&mut self, name: &str, stored_bytes: usize, err: &Error) {
if matches!(err, Error::DecompressLimitExceeded(_)) {
self.note_unread(UnreadStream {
name: name.to_string(),
stored_bytes: stored_bytes as u64,
kind: UnreadKind::MemberTooLarge,
limit: self.limits.inflate_limits.max_output_bytes as u64,
});
}
}
/// Resource limits this file was opened under. Use to match
/// the limits when calling bounded-inflate on extracted stream
/// bytes.
pub fn limits(&self) -> OpenLimits {
self.limits
}
/// Drop every inflated partition the handle holds. A later
/// [`Self::inflated_partition`] inflates its stream again; a reader that
/// holds the `Arc` it was given keeps it. The saved-graphics pass calls this
/// once the readers that share the copies are done, so that its own walks
/// do not hold them at the peak (#1694), and `rvt-dump` after each stream
/// it writes (#1885).
pub fn release_inflated_partitions(&mut self) {
self.inflated.clear();
self.inflated_bytes = 0;
}
/// Read and inflate every gzip member of `name`, memoised.
///
/// Repeat calls return the same shared buffer instead of reading
/// the CFB stream and inflating it again. Use this for any
/// multi-member stream a pipeline touches more than once —
/// `Partitions/*` above all, where a geometry export otherwise
/// inflates the same ~180 MiB a dozen times over.
pub fn inflated_partition(&mut self, name: &str) -> Result<Arc<compression::InflatedStream>> {
if let Some(cached) = self.inflated.get(name) {
return Ok(Arc::clone(cached));
}
let raw = self.read_stream(name)?;
let stored_len = raw.len();
let limits = self.limits.inflate_limits;
// The stored bytes are stripped where they are and dropped once the
// members are inflated, so the stream is held once beside its
// inflated form, not twice (#1075).
let (inflated, shortfall) = {
let prepared = compression::prepare_stream_owned(name, raw);
compression::InflatedStream::from_prepared_with_limits(&prepared, stored_len, limits)
};
if shortfall.members_over_limit > 0 {
self.note_unread(UnreadStream {
name: name.to_string(),
stored_bytes: stored_len as u64,
kind: UnreadKind::MemberTooLarge,
limit: limits.max_output_bytes as u64,
});
}
if shortfall.stopped_at_total {
self.note_unread(UnreadStream {
name: name.to_string(),
stored_bytes: stored_len as u64,