Skip to main content

brep_kernel/io/solidworks/
container.rs

1//! The two containers a SolidWorks document comes in: an OLE compound file
2//! (before 2015) and SolidWorks' own ZIP-like archive (2015 and later).
3//! Only the streams a caller wants are read.
4
5/// The bound on any one stream's size (bytes): a part's partition is a few
6/// megabytes; a stream claiming more than this is refused, not allocated.
7const MAX_STREAM: usize = 1 << 30;
8
9/// The streams of a SolidWorks document whose path (`Storage/Stream`) `want`
10/// accepts, decompressed.
11pub fn solidworks_streams(bytes: &[u8], want: &dyn Fn(&str) -> bool) -> Result<Vec<(String, Vec<u8>)>, String> {
12    if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) {
13        return ole_streams(bytes, want);
14    }
15    if bytes.len() >= 8 && bytes[4..8] == [0, 0, 0, 4] {
16        return archive_streams(bytes, want);
17    }
18    Err("not a SolidWorks document (neither an OLE compound file nor a SolidWorks archive)".into())
19}
20
21fn u16_at(data: &[u8], at: usize) -> Result<usize, String> {
22    data.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize).ok_or_else(|| "the file is cut short".to_string())
23}
24
25fn u32_at(data: &[u8], at: usize) -> Result<usize, String> {
26    data.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or_else(|| "the file is cut short".to_string())
27}
28
29/// SolidWorks' archive: an eight-byte prefix whose last byte is the key the
30/// stream names are rotated by, then a ZIP-like body whose end record holds
31/// the entry count twice, the directory's size and offset. Each directory
32/// entry gives the CRC, sizes, the name's length (and the extra and comment
33/// lengths), the local header's offset and the rotated name; the data is raw
34/// DEFLATE after the local header.
35fn archive_streams(bytes: &[u8], want: &dyn Fn(&str) -> bool) -> Result<Vec<(String, Vec<u8>)>, String> {
36    let key = u32::from(bytes[7] & 7);
37    let body = &bytes[8..];
38    let mut directory = None;
39    if body.len() >= 22 {
40        for i in (0..=body.len() - 22).rev() {
41            let (Ok(a), Ok(b), Ok(size), Ok(offset), Ok(zero)) =
42                (u16_at(body, i + 8), u16_at(body, i + 10), u32_at(body, i + 12), u32_at(body, i + 16), u16_at(body, i + 20))
43            else {
44                continue;
45            };
46            if a == b && a > 0 && offset + size == i && zero == 0 && body[i + 4..i + 8] == [0, 0, 0, 0] {
47                directory = Some((a, offset));
48                break;
49            }
50        }
51    }
52    let (count, offset) = directory.ok_or("the SolidWorks archive has no end record")?;
53    let mut out = Vec::new();
54    let mut at = offset;
55    for _ in 0..count {
56        let crc = u32_at(body, at + 16)? as u32;
57        let packed = u32_at(body, at + 20)?;
58        let full = u32_at(body, at + 24)?;
59        let (name_len, extra_len, comment_len) = (u16_at(body, at + 28)?, u16_at(body, at + 30)?, u16_at(body, at + 32)?);
60        let local = u32_at(body, at + 42)?;
61        let raw_name = body.get(at + 46..at + 46 + name_len).ok_or("an archive entry's name runs past the directory")?;
62        let name: String = raw_name.iter().map(|&c| char::from(c.rotate_right(key))).collect();
63        at += 46 + name_len + extra_len + comment_len;
64        if !want(&name) {
65            continue;
66        }
67        if full > MAX_STREAM {
68            return Err(format!("{name} claims {full} bytes"));
69        }
70        let start = local + 30 + u16_at(body, local + 26)? + u16_at(body, local + 28)?;
71        let data = body.get(start..start + packed).ok_or_else(|| format!("{name}'s data runs past the archive"))?;
72        let data = if packed == 0 {
73            Vec::new()
74        } else {
75            crate::three_mf::inflate::inflate(data, full.max(1)).map_err(|e| format!("{name}: {e}"))?
76        };
77        if data.len() != full || crc32(&data) != crc {
78            return Err(format!("{name} does not inflate to its stated size and checksum"));
79        }
80        out.push((name, data));
81    }
82    Ok(out)
83}
84
85fn crc32(data: &[u8]) -> u32 {
86    let mut crc = !0u32;
87    for &b in data {
88        crc ^= u32::from(b);
89        for _ in 0..8 {
90            crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
91        }
92    }
93    !crc
94}
95
96/// An OLE compound file ([MS-CFB]): sectors chained by the FAT (whose own
97/// sectors the header's DIFAT lists), a directory of 128-byte entries in a
98/// red-black tree, and streams below the cutoff in the mini stream (64-byte
99/// sectors chained by the mini FAT).
100fn ole_streams(bytes: &[u8], want: &dyn Fn(&str) -> bool) -> Result<Vec<(String, Vec<u8>)>, String> {
101    const END: usize = 0xFFFF_FFFE;
102    const FREE: usize = 0xFFFF_FFFF;
103    let shift = u16_at(bytes, 30)?;
104    let mini_shift = u16_at(bytes, 32)?;
105    if !(7..=16).contains(&shift) || !(2..=shift).contains(&mini_shift) {
106        return Err(format!("an OLE file with sector shift {shift}"));
107    }
108    let size = 1usize << shift;
109    let mini = 1usize << mini_shift;
110    let first_dir = u32_at(bytes, 48)?;
111    let cutoff = u32_at(bytes, 56)?;
112    let first_mini_fat = u32_at(bytes, 60)?;
113    let mut difat_next = u32_at(bytes, 68)?;
114    let sector = |n: usize| -> Result<&[u8], String> {
115        let at = (n + 1).checked_mul(size).ok_or("an OLE sector number overflows")?;
116        bytes.get(at..at + size).ok_or_else(|| format!("OLE sector {n} is past the file's end"))
117    };
118    // The FAT's own sectors: the header's 109, then the DIFAT chain.
119    let mut fat_sectors = Vec::new();
120    for k in 0..109 {
121        let s = u32_at(bytes, 76 + 4 * k)?;
122        if s != FREE && s != END {
123            fat_sectors.push(s);
124        }
125    }
126    let mut guard = 0;
127    while difat_next != END && difat_next != FREE {
128        guard += 1;
129        if guard > bytes.len() / size + 1 {
130            return Err("the OLE DIFAT chain loops".into());
131        }
132        let s = sector(difat_next)?;
133        for k in 0..size / 4 - 1 {
134            let n = u32_at(s, 4 * k)?;
135            if n != FREE && n != END {
136                fat_sectors.push(n);
137            }
138        }
139        difat_next = u32_at(s, size - 4)?;
140    }
141    let mut fat = Vec::with_capacity(fat_sectors.len() * size / 4);
142    for n in fat_sectors {
143        let s = sector(n)?;
144        for k in 0..size / 4 {
145            fat.push(u32_at(s, 4 * k)?);
146        }
147    }
148    let chain = |start: usize, table: &[usize]| -> Result<Vec<usize>, String> {
149        let mut out = Vec::new();
150        let mut at = start;
151        while at != END {
152            if at >= table.len() || out.len() > table.len() {
153                return Err("an OLE sector chain runs off its table or loops".into());
154            }
155            out.push(at);
156            at = table[at];
157        }
158        Ok(out)
159    };
160    let read_chain = |start: usize| -> Result<Vec<u8>, String> {
161        let mut out = Vec::new();
162        for n in chain(start, &fat)? {
163            out.extend_from_slice(sector(n)?);
164            if out.len() > MAX_STREAM {
165                return Err("an OLE stream is larger than any part".into());
166            }
167        }
168        Ok(out)
169    };
170    let directory = read_chain(first_dir)?;
171    struct Entry {
172        name: String,
173        kind: u8,
174        left: usize,
175        right: usize,
176        child: usize,
177        start: usize,
178        size: usize,
179    }
180    let entries: Vec<Entry> = directory
181        .chunks_exact(128)
182        .map(|e| {
183            let name_len = (u16::from_le_bytes([e[64], e[65]]) as usize).min(64);
184            let units: Vec<u16> = e[..name_len.saturating_sub(2)].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
185            Entry {
186                name: String::from_utf16_lossy(&units),
187                kind: e[66],
188                left: u32::from_le_bytes([e[68], e[69], e[70], e[71]]) as usize,
189                right: u32::from_le_bytes([e[72], e[73], e[74], e[75]]) as usize,
190                child: u32::from_le_bytes([e[76], e[77], e[78], e[79]]) as usize,
191                start: u32::from_le_bytes([e[116], e[117], e[118], e[119]]) as usize,
192                size: u32::from_le_bytes([e[120], e[121], e[122], e[123]]) as usize,
193            }
194        })
195        .collect();
196    let root = entries.first().ok_or("the OLE file has no directory")?;
197    // The mini stream (the root's data) and its FAT, read only if needed.
198    let mut mini_stream: Option<Vec<u8>> = None;
199    let mut mini_fat: Option<Vec<usize>> = None;
200    // Walk the tree: each storage's children hang from its `child` as a
201    // binary tree through `left` and `right`.
202    let mut paths: Vec<(String, usize)> = Vec::new();
203    let mut stack: Vec<(usize, String)> = vec![(root.child, String::new())];
204    let mut visits = 0;
205    while let Some((at, prefix)) = stack.pop() {
206        if at >= entries.len() {
207            continue;
208        }
209        visits += 1;
210        if visits > 4 * entries.len() {
211            return Err("the OLE directory tree loops".into());
212        }
213        let e = &entries[at];
214        stack.push((e.left, prefix.clone()));
215        stack.push((e.right, prefix.clone()));
216        match e.kind {
217            1 => stack.push((e.child, format!("{prefix}{}/", e.name))),
218            2 => paths.push((format!("{prefix}{}", e.name), at)),
219            _ => {}
220        }
221    }
222    let mut out = Vec::new();
223    for (path, at) in paths {
224        if !want(&path) {
225            continue;
226        }
227        let e = &entries[at];
228        if e.size > MAX_STREAM {
229            return Err(format!("{path} claims {} bytes", e.size));
230        }
231        let mut data = if e.size < cutoff {
232            if mini_stream.is_none() {
233                mini_stream = Some(read_chain(root.start)?);
234                let table = read_chain(first_mini_fat)?;
235                mini_fat = Some(table.chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as usize).collect());
236            }
237            let (stream, table) = (mini_stream.as_ref().unwrap(), mini_fat.as_ref().unwrap());
238            let mut d = Vec::new();
239            for n in chain(e.start, table)? {
240                d.extend_from_slice(stream.get(n * mini..(n + 1) * mini).ok_or_else(|| format!("{path}'s mini sector {n} is past the mini stream"))?);
241            }
242            d
243        } else {
244            read_chain(e.start)?
245        };
246        if data.len() < e.size {
247            return Err(format!("{path} is shorter than its stated {} bytes", e.size));
248        }
249        data.truncate(e.size);
250        out.push((path, data));
251    }
252    Ok(out)
253}