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
use crate::{
    flavor::ImperatorFlavor,
    models::{HeaderBorrowed, HeaderOwned, Save},
    tokens::TokenLookup,
    FailedResolveStrategy, ImperatorError, ImperatorErrorKind,
};
use jomini::{BinaryDeserializer, TextDeserializer, TextTape};
use serde::de::{Deserialize, DeserializeOwned};
use std::io::{Read, Seek};

// The amount of data that we will scan up to looking for a zip signature
pub(crate) const HEADER_LEN_UPPER_BOUND: usize = 0x10000;

/// Describes the format of the save before decoding
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Encoding {
    /// Save had been generated by the game started with `-debug_mode`
    Debug,

    /// A standard ironman or normal save
    Standard,
}

/// The memory allocation strategy for handling zip files
///
/// When the `mmap` feature is enabled, the extractor can use
/// an anonymous memory map
#[derive(Debug, Clone, Copy)]
pub enum Extraction {
    /// Extract the zip data into memory
    InMemory,

    /// Extract the zip data into a anonymous memory map
    #[cfg(feature = "mmap")]
    MmapTemporaries,
}

/// Customize how a save is extracted
#[derive(Debug, Clone)]
pub struct ImperatorExtractorBuilder {
    extraction: Extraction,
    on_failed_resolve: FailedResolveStrategy,
}

impl Default for ImperatorExtractorBuilder {
    fn default() -> Self {
        ImperatorExtractorBuilder::new()
    }
}

impl ImperatorExtractorBuilder {
    /// Create a new extractor with default values: extract zips into memory
    // and ignore unknown binary tokens
    pub fn new() -> Self {
        ImperatorExtractorBuilder {
            extraction: Extraction::InMemory,
            on_failed_resolve: FailedResolveStrategy::Ignore,
        }
    }

    /// Set the memory allocation extraction behavior for when a zip is encountered
    pub fn with_extraction(mut self, extraction: Extraction) -> Self {
        self.extraction = extraction;
        self
    }

    /// Set the behavior for when an unresolved binary token is encountered
    pub fn with_on_failed_resolve(mut self, strategy: FailedResolveStrategy) -> Self {
        self.on_failed_resolve = strategy;
        self
    }

    /// Extract the header from the save.
    pub fn extract_header_owned(
        &self,
        data: &[u8],
    ) -> Result<(HeaderOwned, Encoding), ImperatorError> {
        self.extract_header_as(data)
    }

    /// Extract the header from the save with zero copy deserialization.
    pub fn extract_header_borrowed<'a>(
        &self,
        data: &'a [u8],
    ) -> Result<(HeaderBorrowed<'a>, Encoding), ImperatorError> {
        self.extract_header_as(data)
    }

    /// Extract the header from the save as a custom type
    pub fn extract_header_as<'de, T>(
        &self,
        data: &'de [u8],
    ) -> Result<(T, Encoding), ImperatorError>
    where
        T: Deserialize<'de>,
    {
        let core_data = skip_save_prefix(&data);
        let data = &core_data[..std::cmp::min(core_data.len(), HEADER_LEN_UPPER_BOUND)];
        let (header, _rest) = split_on_zip(data);
        if sniff_is_binary(header) {
            let res = BinaryDeserializer::builder_flavor(ImperatorFlavor)
                .on_failed_resolve(self.on_failed_resolve)
                .from_slice(header, &TokenLookup)?;

            Ok((res, Encoding::Standard))
        } else {
            let res = TextDeserializer::from_utf8_slice(core_data)?;
            Ok((res, Encoding::Debug))
        }
    }

    /// Extract all info from a save
    pub fn extract_save<R>(&self, reader: R) -> Result<(Save, Encoding), ImperatorError>
    where
        R: Read + Seek,
    {
        self.extract_save_as(reader)
    }

    // todo, customize deserialize type
    fn extract_save_as<R>(&self, mut reader: R) -> Result<(Save, Encoding), ImperatorError>
    where
        R: Read + Seek,
    {
        // First we need to determine if we are in an autosave or a header + zip save.
        // We determine this by examining the first 64KB and if the zip magic header
        // occurs then we know it is a zip file.
        let mut buffer = vec![0; HEADER_LEN_UPPER_BOUND];
        read_upto(&mut reader, &mut buffer)?;

        if zip_index(&buffer).is_some() {
            let mut zip = zip::ZipArchive::new(&mut reader)
                .map_err(ImperatorErrorKind::ZipCentralDirectory)?;
            let res = match self.extraction {
                Extraction::InMemory => {
                    melt_in_memory(&mut buffer, "gamestate", &mut zip, self.on_failed_resolve)
                }
                #[cfg(feature = "mmap")]
                Extraction::MmapTemporaries => {
                    melt_with_temporary("gamestate", &mut zip, self.on_failed_resolve)
                }
            }?;

            Ok((res, Encoding::Standard))
        } else {
            reader.read_to_end(&mut buffer)?;
            let data = skip_save_prefix(&buffer);
            let tape = TextTape::from_slice(data)?;
            let header = TextDeserializer::from_utf8_tape(&tape)?;
            let gamestate = TextDeserializer::from_utf8_tape(&tape)?;
            Ok((Save { header, gamestate }, Encoding::Debug))
        }
    }
}

/// Logic container for extracting data from an Imperator save
#[derive(Debug, Clone)]
pub struct ImperatorExtractor {}

impl ImperatorExtractor {
    /// Create a customized container
    pub fn builder() -> ImperatorExtractorBuilder {
        ImperatorExtractorBuilder::new()
    }

    /// Extract just the header from the save
    pub fn extract_header(data: &[u8]) -> Result<(HeaderOwned, Encoding), ImperatorError> {
        Self::builder().extract_header_owned(data)
    }

    /// Extract all info from a save
    pub fn extract_save<R>(reader: R) -> Result<(Save, Encoding), ImperatorError>
    where
        R: Read + Seek,
    {
        Self::builder().extract_save(reader)
    }
}

fn melt_in_memory<T, R>(
    mut buffer: &mut Vec<u8>,
    name: &'static str,
    zip: &mut zip::ZipArchive<R>,
    on_failed_resolve: FailedResolveStrategy,
) -> Result<T, ImperatorError>
where
    R: Read + Seek,
    T: DeserializeOwned,
{
    buffer.clear();
    let mut zip_file = zip
        .by_name(name)
        .map_err(|e| ImperatorErrorKind::ZipMissingEntry(name, e))?;

    // protect against excessively large uncompressed data
    if zip_file.size() > 1024 * 1024 * 200 {
        return Err(ImperatorErrorKind::ZipSize(name).into());
    }

    buffer.reserve(zip_file.size() as usize);
    zip_file
        .read_to_end(&mut buffer)
        .map_err(|e| ImperatorErrorKind::ZipExtraction(name, e))?;

    let res = BinaryDeserializer::builder_flavor(ImperatorFlavor)
        .on_failed_resolve(on_failed_resolve)
        .from_slice(buffer, &TokenLookup)
        .map_err(|e| ImperatorErrorKind::Deserialize {
            part: Some(name.to_string()),
            err: e,
        })?;

    Ok(res)
}

#[cfg(feature = "mmap")]
fn melt_with_temporary<T, R>(
    name: &'static str,
    zip: &mut zip::ZipArchive<R>,
    on_failed_resolve: FailedResolveStrategy,
) -> Result<T, ImperatorError>
where
    R: Read + Seek,
    T: DeserializeOwned,
{
    let mut zip_file = zip
        .by_name(name)
        .map_err(|e| ImperatorErrorKind::ZipMissingEntry(name, e))?;

    // protect against excessively large uncompressed data
    if zip_file.size() > 1024 * 1024 * 200 {
        return Err(ImperatorErrorKind::ZipSize(name).into());
    }

    let mut mmap = memmap::MmapMut::map_anon(zip_file.size() as usize)?;
    std::io::copy(&mut zip_file, &mut mmap.as_mut())
        .map_err(|e| ImperatorErrorKind::ZipExtraction(name, e))?;
    let buffer = &mmap[..];

    let res = BinaryDeserializer::builder_flavor(ImperatorFlavor)
        .on_failed_resolve(on_failed_resolve)
        .from_slice(buffer, &TokenLookup)
        .map_err(|e| ImperatorErrorKind::Deserialize {
            part: Some(name.to_string()),
            err: e,
        })?;

    Ok(res)
}

/// Throwaway the first line
fn skip_save_prefix(data: &[u8]) -> &[u8] {
    let id_line_idx = data
        .iter()
        .position(|&x| x == b'\n')
        .map(|x| x + 1)
        .unwrap_or(0);
    &data[id_line_idx..]
}

/// We guess from the initial data (after the save id line) that the save is
/// binary if the 3rd and 4th byte are the binary equals token, which should
/// not occur in a plaintext save
fn sniff_is_binary(data: &[u8]) -> bool {
    data.get(2..4).map_or(false, |x| x == [0x01, 0x00])
}

/// Returns the index in the data where the zip occurs
pub(crate) fn zip_index(data: &[u8]) -> Option<usize> {
    twoway::find_bytes(data, &[0x50, 0x4b, 0x03, 0x04])
}

/// The save embeds a zip after the header. This function finds the zip magic code
/// and splits the data into two so they can be parsed separately.
fn split_on_zip(data: &[u8]) -> (&[u8], &[u8]) {
    if let Some(idx) = zip_index(data) {
        data.split_at(idx)
    } else {
        data.split_at(data.len())
    }
}

// Read until either the reader is out of data or the buffer is filled.
// This is essentially Read::read_exact without the validation at the end
fn read_upto<R>(reader: &mut R, mut buf: &mut [u8]) -> Result<(), std::io::Error>
where
    R: std::io::Read,
{
    while !buf.is_empty() {
        match reader.read(buf) {
            Ok(0) => break,
            Ok(n) => {
                let tmp = buf;
                buf = &mut tmp[n..];
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_skip_save_prefix() {
        let data = b"abc\n123";
        let result = skip_save_prefix(&data[..]);
        assert_eq!(result, b"123");
    }
}