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
// #[warn(clippy::arithmetic_side_effects)]

/// The archive reader.
pub mod reader;
/// sans-io state machines for reading and writing.
pub mod sans_io;
/// Tokio adapters for archive readers and writers.
#[cfg(feature = "tokio")]
pub mod tokio;
/// The archive writer.
pub mod writer;

pub use self::reader::Reader;
#[cfg(feature = "tokio")]
pub use self::tokio::TokioReader;
#[cfg(feature = "tokio")]
pub use self::tokio::TokioWriter;
pub use self::writer::Writer;

/// The len of the magic number.
const MAGIC_LEN: usize = 7;
/// The magic number.
const MAGIC: [u8; MAGIC_LEN] = *b"RGSSAD\0";
/// The file version
const VERSION: u8 = 1;
/// The size of the header.
const HEADER_LEN: usize = MAGIC_LEN + 1;
/// The default encryption key.
const DEFAULT_KEY: u32 = 0xDEADCAFE;
/// The maximum file name len.
///
/// This was chosen arbirtarily,
/// off of Linux's common 4096 max path length.
/// Note that the real limit for this value is much lower,
/// as this format is for a Windows application and
/// Windows' max path length is 255.
const MAX_FILE_NAME_LEN: u32 = 4096;
/// The size of a u32, in bytes.
const U32_LEN: usize = 4;

/// The library error type
#[derive(Debug)]
pub enum Error {
    /// An I/O error occured.
    Io(std::io::Error),

    /// Invalid internal state, user error
    InvalidState,

    /// There was an error with the sans-io state machine.
    SansIo(self::sans_io::Error),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(_error) => write!(f, "an I/O error occured"),
            Self::InvalidState => write!(f, "user error, invalid internal state"),
            Self::SansIo(error) => error.fmt(f),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::SansIo(error) => error.source(),
            _ => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Self::Io(error)
    }
}

impl From<self::sans_io::Error> for Error {
    fn from(error: self::sans_io::Error) -> Self {
        Self::SansIo(error)
    }
}

/// Encrypt or decrypt an u32, and rotate the key as needed.
fn crypt_u32(key: &mut u32, mut n: u32) -> u32 {
    n ^= *key;
    *key = key.overflowing_mul(7).0.overflowing_add(3).0;
    n
}

/// Encrypt of decrypt a file name, and rotate the key as needed.
fn crypt_name_bytes(key: &mut u32, bytes: &mut [u8]) {
    for byte in bytes.iter_mut() {
        // We mask with 0xFF, this cannot exceed the bounds of a u8.
        *byte ^= u8::try_from(*key & 0xFF).unwrap();
        *key = key.overflowing_mul(7).0.overflowing_add(3).0;
    }
}

/// Encrypt or decrypt the encrypted file data, and rotate the key as needed.
fn crypt_file_data(key: &mut u32, counter: &mut u8, buffer: &mut [u8]) {
    // TODO: We can possibly be more efficient here.
    // If we are able to cast this to a slice of u32s,
    // we can crypt that instead and use this byte-wise impl only at the end.
    for byte in buffer.iter_mut() {
        *byte ^= key.to_le_bytes()[usize::from(*counter)];
        if *counter == 3 {
            *key = key.overflowing_mul(7).0.overflowing_add(3).0;
        }
        *counter = (*counter + 1) % 4;
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::cell::RefCell;
    use std::io::Read;
    use std::io::Seek;
    use std::io::SeekFrom;
    use std::io::Write;
    use std::rc::Rc;

    pub const VX_TEST_GAME: &str =
        "test_data/RPGMakerVXTestGame-Export/RPGMakerVXTestGame/Game.rgss2a";

    #[derive(Debug, Clone)]
    struct SlowReader<R> {
        inner: Rc<RefCell<(R, usize, Option<SeekFrom>)>>,
    }

    impl<R> SlowReader<R> {
        pub fn new(reader: R) -> Self {
            Self {
                inner: Rc::new(RefCell::new((reader, 0, None))),
            }
        }

        fn add_fuel(&self, fuel: usize) {
            let mut inner = self.inner.borrow_mut();
            inner.1 += fuel;
        }
    }

    impl<R> Read for SlowReader<R>
    where
        R: Read,
    {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let mut inner = self.inner.borrow_mut();
            let (reader, fuel, _) = &mut *inner;

            assert!(!buf.is_empty());
            let limit = std::cmp::min(*fuel, buf.len());
            let buf = &mut buf[..limit];
            if buf.is_empty() {
                return Err(std::io::Error::from(std::io::ErrorKind::WouldBlock));
            }
            let n = reader.read(buf)?;
            *fuel -= n;

            Ok(n)
        }
    }

    impl<R> Seek for SlowReader<R>
    where
        R: Seek,
    {
        fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
            let mut inner = self.inner.borrow_mut();
            let (reader, _, seek_request) = &mut *inner;
            match seek_request {
                Some(seek_request) => {
                    assert!(pos == *seek_request, "{pos:?} != {seek_request:?}");
                }
                None => {
                    *seek_request = Some(pos);
                    return Err(std::io::Error::from(std::io::ErrorKind::WouldBlock));
                }
            }

            let result = reader.seek(pos);
            *seek_request = None;

            result
        }
    }

    #[derive(Debug, Clone)]
    struct SlowWriter<W> {
        inner: Rc<RefCell<(W, usize, bool)>>,
    }

    impl<W> SlowWriter<W> {
        pub fn new(writer: W) -> Self {
            Self {
                inner: Rc::new(RefCell::new((writer, 0, false))),
            }
        }

        fn add_fuel(&self, fuel: usize) {
            let mut inner = self.inner.borrow_mut();
            inner.1 += fuel;
        }
    }

    impl<W> Write for SlowWriter<W>
    where
        W: Write,
    {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            let mut inner = self.inner.borrow_mut();
            let (writer, fuel, _) = &mut *inner;

            if *fuel == 0 {
                return Err(std::io::Error::from(std::io::ErrorKind::WouldBlock));
            }

            let len = std::cmp::min(*fuel, buf.len());
            let n = writer.write(&buf[..len])?;
            *fuel -= n;

            Ok(n)
        }

        fn flush(&mut self) -> std::io::Result<()> {
            let mut inner = self.inner.borrow_mut();
            let (writer, _, should_flush) = &mut *inner;
            if *should_flush {
                writer.flush()?;
                *should_flush = false;

                Ok(())
            } else {
                *should_flush = true;

                Err(std::io::Error::from(std::io::ErrorKind::WouldBlock))
            }
        }
    }

    #[test]
    fn reader_writer_smoke() {
        let file = std::fs::read(VX_TEST_GAME).expect("failed to open archive");
        let file = std::io::Cursor::new(file);
        let mut reader = Reader::new(file);
        reader.read_header().expect("failed to read header");

        // Read entire archive into a Vec.
        let mut files = Vec::new();
        while let Some(mut file) = reader.read_file().expect("failed to read file") {
            let mut buffer = Vec::new();
            file.read_to_end(&mut buffer).expect("failed to read file");
            files.push((file.name().to_string(), buffer));
        }

        // Write all files into a new archive.
        let mut new_file = Vec::new();
        let mut writer = Writer::new(&mut new_file);
        writer.write_header().expect("failed to write header");
        for (file_name, file_data) in files.iter() {
            writer
                .write_file(
                    file_name,
                    u32::try_from(file_data.len()).expect("file data too large"),
                    &**file_data,
                )
                .expect("failed to write file");
        }
        writer.finish().expect("failed to flush");

        let file = reader.into_inner();

        // Ensure archives are byte-for-byte equivalent.
        assert!(&new_file == file.get_ref());
    }

    #[test]
    fn slow_reader() {
        let file = std::fs::read(VX_TEST_GAME).expect("failed to open archive");
        let file = std::io::Cursor::new(file);
        let file = SlowReader::new(file);
        let mut reader = Reader::new(file.clone());

        loop {
            match reader.read_header() {
                Ok(()) => break,
                Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(error) => {
                    panic!("Error: {error:?}");
                }
            }

            file.add_fuel(1);
        }

        loop {
            match reader.read_file() {
                Ok(Some(_file)) => {}
                Ok(None) => break,
                Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(error) => {
                    panic!("Error: {error:?}");
                }
            }

            file.add_fuel(1);
        }
    }

    #[test]
    fn reader_slow_writer_smoke() {
        let file = std::fs::read(VX_TEST_GAME).expect("failed to open archive");
        let file = std::io::Cursor::new(file);
        let mut reader = Reader::new(file);
        reader.read_header().expect("failed to read header");

        // Read entire archive into Vec.
        let mut files = Vec::new();
        while let Some(mut file) = reader.read_file().expect("failed to read file") {
            let mut buffer = Vec::new();
            file.read_to_end(&mut buffer).expect("failed to read file");
            files.push((file.name().to_string(), buffer));
        }

        // Write all files into new archive.
        let new_file = SlowWriter::new(Vec::<u8>::new());
        let mut writer = Writer::new(new_file.clone());
        loop {
            match writer.write_header() {
                Ok(()) => break,
                Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    new_file.add_fuel(1);
                }
                Err(error) => {
                    panic!("failed to write header: {error}");
                }
            }
        }

        for (file_name, file_data) in files.iter() {
            let len = u32::try_from(file_data.len()).expect("file data too large");
            // We need to pass the same reader, so that updates to its position are persisted.
            let mut reader = &**file_data;

            loop {
                match writer.write_file(file_name, len, &mut reader) {
                    Ok(()) => break,
                    Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock => {
                        new_file.add_fuel(1);
                    }
                    Err(error) => {
                        panic!("failed to write file: {error}");
                    }
                }
            }
        }
        loop {
            match writer.finish() {
                Ok(()) => break,
                Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(error) => {
                    panic!("failed to flush: {error}");
                }
            }
        }

        let file = reader.into_inner();

        // Ensure archives are byte-for-byte equivalent.
        let new_file = new_file.inner.borrow();
        let new_file = &new_file.0;
        let file = file.get_ref();
        dbg!(new_file.len(), file.len());
        assert!(new_file == file);
    }
}