runirip 0.1.2

Unity asset files manipulation library
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
use crate::{
    unitycn::ArchiveStorageDecryptor,
    config::ExtractionConfig,
    files::{SerializedFile, unity_file::{FileEntry, UnityFile}},
    read_ext::{ReadSeekUrexExt, ReadUrexExt}, Error,
};
use bitflags::bitflags;
use byteorder::{BigEndian, ReadBytesExt};
use num_enum::TryFromPrimitive;
use std::io::{Cursor, Read, Seek, SeekFrom};

bitflags! {
    struct ArchiveFlags: u32 {
        const COMPRESSION_TYPE_MASK = 0x3f;
        const BLOCKS_AND_DIRECTORY_INFO_COMBINED = 0x40;
        const BLOCKS_INFO_AT_THE_END = 0x80;
        const OLD_WEB_PLUGIN_COMPATIBILITY = 0x100;
        const BLOCK_INFO_NEED_PADDING_AT_START = 0x200;
        const USES_ASSET_BUNDLE_ENCRYPTION = 0x400;
    }

    struct ArchiveFlagsOld: u32 {
        const COMPRESSION_TYPE_MASK = 0x3f;
        const BLOCKS_AND_DIRECTORY_INFO_COMBINED = 0x40;
        const BLOCKS_INFO_AT_THE_END = 0x80;
        const OLD_WEB_PLUGIN_COMPATIBILITY = 0x100;
        const USES_ASSET_BUNDLE_ENCRYPTION = 0x200;
    }
}

// bitflags! {
//     struct StorageBlockFlags: u32 {
//         const CompressionTypeMask = 0x3f;
//         const Streamed = 0x40;
//         const Encrypted = 0x100;
//     }
// }

#[derive(Debug, Eq, PartialEq, TryFromPrimitive)]
#[repr(u32)]
pub enum CompressionType {
    None = 0,
    Lzma = 1,
    Lz4 = 2,
    Lz4hc = 3,
    Lzham = 4,
}

#[derive(Debug)]
pub struct BundleFileHeader {
    signature: String,
    version: u32,
    unity_version: String,
    unity_revision: String,
    size: u32,
}

impl BundleFileHeader {
    fn from_reader<T: Read + Seek>(reader: &mut T) -> Result<Self, Error> {
        Ok(BundleFileHeader {
            signature: reader.read_cstr()?,
            version: reader.read_u32::<BigEndian>()?,
            unity_version: reader.read_cstr()?,
            unity_revision: reader.read_cstr()?,
            size: 0,
        })
    }

    fn get_revision_tuple(&self, config: &ExtractionConfig) -> Result<(u32, u32, u32), Error> {
        // could be done way better, but this works for now
        let mut revision = self.unity_revision.clone();
        if revision.is_empty() | (revision == "0.0.0") {
            revision = config.fallback_unity_version.clone();
        }
        let mut revision_split = revision.split('.');
        Ok((
            revision_split.next().map(|v| v.parse())
                .transpose()
                .ok()
                .flatten()
                .ok_or_else(|| Error::InvalidRevision(self.unity_revision.clone()))?,
            revision_split.next().map(|v| v.parse())
                .transpose()
                .ok()
                .flatten()
                .ok_or_else(|| Error::InvalidRevision(self.unity_revision.clone()))?,
            {
                let mut val = 0;
                let last_split = revision_split.next()
                    .ok_or_else(|| Error::InvalidRevision(self.unity_revision.clone()))?;

                for (i, c) in last_split.chars().enumerate() {
                    if !c.is_numeric() {
                        val = last_split[..i].parse::<u32>()?;
                        break;
                    }
                }
                val
            },
        ))
    }
}

#[derive(Debug)]
pub struct StorageBlock {
    compressed_size: u32,
    uncompressed_size: u32,
    flags: u32,
}

pub struct BundleFile {
    pub m_Header: BundleFileHeader,
    pub m_BlocksInfo: Vec<StorageBlock>,
    pub m_DirectoryInfo: Vec<FileEntry>,
    pub m_BlockReader: Cursor<Vec<u8>>,
    _decryptor: Option<ArchiveStorageDecryptor>,
}

impl BundleFile {
    pub fn from_reader<T: Read + Seek>(
        reader: &mut T,
        config: &ExtractionConfig,
    ) -> Result<Self, Error> {
        let mut bundle = Self {
            m_Header: BundleFileHeader::from_reader(reader)?,
            m_BlocksInfo: Vec::new(),
            m_DirectoryInfo: Vec::new(),
            m_BlockReader: Cursor::new(Vec::new()),
            _decryptor: None,
        };

        (bundle.m_DirectoryInfo, bundle.m_BlockReader) = match bundle.m_Header.signature.as_str() {
            "UnityArchive" => {
                return Err(Error::Unimplemented("UnityArchive is not supported"));
            }
            "UnityWeb" | "UnityRaw" => {
                if bundle.m_Header.version == 6 {
                    bundle.read_unityfs(reader, config)?
                } else {
                    bundle.read_unity_raw(reader, config)?
                }
            }
            "UnityFS" => bundle.read_unityfs(reader, config)?,
            _ => {
                return Err(Error::UnknownSignature);
            }
        };
        Ok(bundle)
    }

    fn read_unity_raw<T: Read + Seek>(
        &mut self,
        reader: &mut T,
        config: &ExtractionConfig,
    ) -> Result<(Vec<FileEntry>, Cursor<Vec<u8>>), Error> {
        if self.m_Header.version >= 4 {
            let hash = reader.read_u128::<BigEndian>()?;
            let crc = reader.read_u32::<BigEndian>()?;
        }
        let minimum_streamed_bytes = reader.read_u32::<BigEndian>()?;

        self.m_Header.size = reader.read_u32::<BigEndian>()?;

        let number_of_levels_to_download_before_streaming = reader.read_u32::<BigEndian>()?;
        let level_count = reader.read_u32::<BigEndian>()?;

        // jump to last level
        // TODO - keep the levels for use in low-memory block decompressor strategy
        reader
            .seek(std::io::SeekFrom::Current(((level_count - 1) * 8) as i64))?;

        let mut m_BlocksInfo = StorageBlock {
            compressed_size: reader.read_u32::<BigEndian>()?,
            uncompressed_size: reader.read_u32::<BigEndian>()?,
            flags: 0,
        };

        if self.m_Header.version >= 2 {
            let complete_file_size = reader.read_u32::<BigEndian>()?;
        }
        if self.m_Header.version >= 3 {
            let file_info_header_size = reader.read_u128::<BigEndian>()?;
        }
        reader
            .seek(std::io::SeekFrom::Start(self.m_Header.size as u64))?;

        //ReadBlocksAndDirectory
        // is compressed -> lzma compression -> can be passed to decompress_block
        if self.m_Header.signature == "UnityWeb" {
            m_BlocksInfo.flags += CompressionType::Lzma as u32;
        }

        let blocks_info_bytes = self.decompress_block(reader, &m_BlocksInfo, 0)?;
        let mut block_info_reader = Cursor::new(blocks_info_bytes);

        let FileEntrys_count = block_info_reader.read_i32::<BigEndian>()?;
        let m_DirectoryInfo = (0..FileEntrys_count)
            .map(|_| Ok(FileEntry {
                path: block_info_reader.read_cstr()?,
                offset: block_info_reader.read_u32::<BigEndian>()? as i64,
                size: block_info_reader.read_u32::<BigEndian>()? as i64,
                flags: 0,
            }))
            .collect::<Result<Vec<FileEntry>, Error>>()?;

        Ok((m_DirectoryInfo, block_info_reader))
    }

    fn read_unityfs<T: Read + Seek>(
        &mut self,
        reader: &mut T,
        config: &ExtractionConfig,
    ) -> Result<(Vec<FileEntry>, Cursor<Vec<u8>>), Error> {
        //ReadHeader
        let unity_ver = self.m_Header.get_revision_tuple(config)?;
        let use_new_archive_flags = !(unity_ver < (2020, 0, 0))
            | ((unity_ver.0 == 2020) & (unity_ver < (2020, 3, 34)))
            | ((unity_ver.0 == 2021) & (unity_ver < (2021, 3, 2)))
            | ((unity_ver.0 == 2022) & (unity_ver < (2022, 1, 1)));
        self.m_Header.size = reader.read_i64::<BigEndian>()? as u32;

        let block_info = StorageBlock {
            compressed_size: reader.read_u32::<BigEndian>()?,
            uncompressed_size: reader.read_u32::<BigEndian>()?,
            flags: reader.read_u32::<BigEndian>()?,
        };

        if self.m_Header.signature != "UnityFS" {
            reader.read_bool()?;
        }

        //ReadBlocksInfoAndDirectory
        if self.m_Header.version >= 7 {
            reader.align(16)?;
        }
        else if unity_ver.0 >= 2019 && unity_ver.1 >= 4 {
            //check if we need to align the reader
            //- align to 16 bytes and check if all are 0
            //- if not, reset the reader to the previous position
            let pre_align = reader.stream_position()?;
            let align_data = reader.read_bytes_sized((16 - (pre_align as usize % 16)) % 16)?;
            if align_data.iter().any(|x| *x != 0) {
                reader.seek(SeekFrom::Start(pre_align))?;
            }
        }

        let blocks_info_bytes: Vec<u8>;
        if block_info.flags & ArchiveFlags::BLOCKS_INFO_AT_THE_END.bits() != 0 {
            //0x80 BlocksInfoAtTheEnd
            let position = reader.stream_position()?;
            // originally reader.length
            reader
                .seek(std::io::SeekFrom::End(block_info.compressed_size as i64))?;
            blocks_info_bytes = self.decompress_block(reader, &block_info, 0)?;
            reader.seek(std::io::SeekFrom::Start(position))?;
        } else {
            //0x40 BlocksAndDirectoryInfoCombined
            if (use_new_archive_flags
                & (block_info.flags & ArchiveFlags::USES_ASSET_BUNDLE_ENCRYPTION.bits() > 0))
                | (!use_new_archive_flags
                    & (block_info.flags & ArchiveFlagsOld::USES_ASSET_BUNDLE_ENCRYPTION.bits() > 0))
            {
                #[cfg(feature = "unitycn_encryption")]
                {
                    self._decryptor = Some(ArchiveStorageDecryptor::from_reader(
                        reader,
                        config.unitycn_key.ok_or_else(|| Error::NoUnityCNKey)?,
                    )?);
                }

                #[cfg(not(feature = "unitycn_encryption"))]
                return Err(Error::FeatureDisabled("unitycn_encryption"));
            }
            blocks_info_bytes = self.decompress_block(reader, &block_info, 0)?;
        }

        let mut block_info_reader = Cursor::new(&blocks_info_bytes);

        let uncompressed_data_hash = block_info_reader.read_u128::<BigEndian>()?;

        let block_info_count = block_info_reader.read_i32::<BigEndian>()?;
        let m_BlocksInfo = (0..block_info_count)
            .map(|_| Ok(StorageBlock {
                uncompressed_size: block_info_reader.read_u32::<BigEndian>()?,
                compressed_size: block_info_reader.read_u32::<BigEndian>()?,
                flags: block_info_reader.read_u16::<BigEndian>()? as u32,
            }))
            .collect::<Result<Vec<StorageBlock>, Error>>()?;

        let FileEntrys_count = block_info_reader.read_i32::<BigEndian>()?;
        let m_DirectoryInfo: Vec<FileEntry> = (0..FileEntrys_count)
            .map(|_| Ok(FileEntry {
                offset: block_info_reader.read_i64::<BigEndian>()?,
                size: block_info_reader.read_i64::<BigEndian>()?,
                flags: block_info_reader.read_u32::<BigEndian>()?,
                path: block_info_reader.read_cstr()?,
            }))
            .collect::<Result<Vec<FileEntry>, Error>>()?;

        if use_new_archive_flags
            & (block_info.flags & ArchiveFlags::BLOCK_INFO_NEED_PADDING_AT_START.bits() > 0)
        {
            reader.align(16)?;
        }

        let block_data_size: u32 = m_BlocksInfo
            .iter()
            .map(|block| block.uncompressed_size)
            .sum();
        let mut block_data = vec![0u8; block_data_size as usize];

        let mut block_offset = 0usize;
        for (i, block) in m_BlocksInfo.iter().enumerate() {
            let end = block_offset + block.uncompressed_size as usize;
            self.decompress_block_into(reader, block, i, &mut block_data[block_offset..end])?;
            block_offset = end;
        }

        let block_reader = Cursor::new(block_data);
        Ok((m_DirectoryInfo, block_reader))
    }

    fn read_files<T: Read + Seek>(
        &mut self,
        file_entries: &[FileEntry],
        reader: &mut T,
        config: &ExtractionConfig,
    ) -> Result<Vec<SerializedFile>, Error> {
        file_entries
            .iter()
            .map(|entry| {
                reader.seek(std::io::SeekFrom::Start(entry.offset as u64))?;
                SerializedFile::from_reader(reader, config)
            })
            .collect()
    }

    fn decompress_block_into<T: Read + Seek>(
        &mut self,
        reader: &mut T,
        block: &StorageBlock,
        index: usize,
        output: &mut [u8]
    ) -> Result<(), Error> {
        #[allow(unused_mut)]
        let mut compressed = reader
            .read_bytes_sized(block.compressed_size as usize)?;

        match CompressionType::try_from(block.flags & 0x3F)? {
            CompressionType::Lzma => {
                #[cfg(feature = "lzma")]
                {
                    let mut compressed_reader = Cursor::new(&compressed);
                    lzma_rs::lzma_decompress(&mut compressed_reader, &mut Cursor::new(output))?;
                    Ok(())
                }

                #[cfg(not(feature = "lzma"))]
                Err(Error::FeatureDisabled("lzma"))
            }
            CompressionType::Lz4 | CompressionType::Lz4hc => {
                #[cfg(feature = "lz4")]
                {
                    if block.flags & 0x100 > 0 {
                        // UnityCN encryption
                        #[cfg(feature = "unitycn_encryption")]
                        if let Some(decryptor) = self._decryptor.as_ref() {
                            decryptor.decrypt_block(
                                &mut compressed,
                                block.compressed_size as usize,
                                index,
                            )?;
                        }

                        #[cfg(not(feature = "unitycn_encryption"))]
                        return Err(Error::FeatureDisabled("unitycn_encryption"))
                    }
                    lz4_flex::block::decompress_into(&compressed, output)?;
                    Ok(())
                }

                #[cfg(not(feature = "lz4"))]
                Err(Error::FeatureDisabled("lz4"))
            }
            CompressionType::Lzham => {
                Err(Error::Unimplemented("LZHAM is not supported"))
            }
            CompressionType::None => {
                output.copy_from_slice(&compressed);
                Ok(())
            }
        }
    }

    fn decompress_block<T: Read + Seek>(
        &mut self,
        reader: &mut T,
        block: &StorageBlock,
        index: usize,
    ) -> Result<Vec<u8>, Error> {
        let mut uncompressed = vec![0; block.uncompressed_size as usize];
        self.decompress_block_into(reader, block, index, &mut uncompressed)?;
        Ok(uncompressed)
    }
}

impl UnityFile for BundleFile {
    fn from_reader<T: Read + Seek>(reader: &mut T, config: &ExtractionConfig) -> Result<Self, Error>
    where
        Self: Sized,
    {
        BundleFile::from_reader(reader, config)
    }
}