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
/*
 * Created on Tue Dec 15 2020
 *
 * Copyright (c) storycraft. Licensed under the Apache Licence 2.0.
 */

use std::{convert::TryFrom, io::{Cursor, Read, Write}};

use byteorder::LittleEndian;
use encoding::{DecoderTrap, EncoderTrap, Encoding, all::UTF_16LE};

use crate::{XP3Error, XP3ErrorKind, XP3_INDEX_ADLR_IDENTIFIER, XP3_INDEX_INFO_IDENTIFIER, XP3_INDEX_SEGM_IDENTIFIER, XP3_INDEX_TIME_IDENTIFIER};
use byteorder::{ReadBytesExt, WriteBytesExt};

use super::XP3Index;

/// FileIndex for xp3 archive.
/// Contains information about file and data offsets.
#[derive(Debug, Clone)]
pub struct XP3FileIndex {

    info: XP3FileIndexInfo,
    segments: Vec<XP3FileIndexSegment>,
    adler: XP3FileIndexAdler,
    time: Option<XP3FileIndexTime>

}

impl XP3FileIndex {

    pub fn new(
        info: XP3FileIndexInfo,
        segments: Vec<XP3FileIndexSegment>,
        adler: XP3FileIndexAdler,
        time: Option<XP3FileIndexTime>
    ) -> Self {
        Self {
            info,
            segments,
            adler,
            time
        }
    }

    /// File time
    pub fn time(&self) -> Option<XP3FileIndexTime> {
        self.time
    }

    /// File adler hash
    pub fn adler(&self) -> XP3FileIndexAdler {
        self.adler
    }

    /// File information
    pub fn info(&self) -> &XP3FileIndexInfo {
        &self.info
    }

    /// File segments
    pub fn segments(&self) -> &Vec<XP3FileIndexSegment> {
        &self.segments
    }

    /// Read xp3 file index from stream.
    /// Returns read size, XP3FileIndex tuple.
    pub fn from_bytes(file_size: u64, stream: &mut impl Read) -> Result<(u64, Self), XP3Error> {
        let mut info: Option<XP3FileIndexInfo> = None;
        let mut segm: Option<Vec<XP3FileIndexSegment>> = None;
        let mut time: Option<XP3FileIndexTime> = None;
        let mut adler32: Option<XP3FileIndexAdler> = None;

        let mut total_read: u64 = 0;
        while total_read < file_size {
            let (read, index) = XP3Index::from_bytes(stream)?;
            
            let mut data_stream = Cursor::new(&index.data);

            match index.identifier {

                XP3_INDEX_INFO_IDENTIFIER => {
                    if info.is_some() {
                        return Err(XP3Error::new(XP3ErrorKind::InvalidFileIndex, None));
                    }

                    info = Some(XP3FileIndexInfo::from_bytes(&mut data_stream)?.1);
                },

                XP3_INDEX_SEGM_IDENTIFIER => {
                    if segm.is_some() {
                        return Err(XP3Error::new(XP3ErrorKind::InvalidFileIndex, None));
                    }

                    let count = data_stream.get_ref().len() / 28;

                    let mut list: Vec<XP3FileIndexSegment> = Vec::new();
                    for _ in 0..count {
                        list.push(XP3FileIndexSegment::from_bytes(&mut data_stream)?.1);
                    }

                    segm = Some(list);
                },

                XP3_INDEX_ADLR_IDENTIFIER => {
                    adler32 = Some(XP3FileIndexAdler::from_bytes(&mut data_stream)?.1);
                },

                XP3_INDEX_TIME_IDENTIFIER => {
                    time = Some(XP3FileIndexTime::from_bytes(&mut data_stream)?.1);
                },
                
                _ => {
                    // SKIP infos we don't know yet.
                }
            }

            
            total_read += read;
        }

        if info.is_none() || adler32.is_none() || segm.is_none() {
            return Err(XP3Error::new(XP3ErrorKind::InvalidFileIndex, None));
        }

        Ok((total_read, XP3FileIndex::new(info.unwrap(), segm.unwrap(), adler32.unwrap(), time)))
    }

    /// Write xp3 file index to stream.
    pub fn write_bytes(&self, stream: &mut impl Write) -> Result<u64, XP3Error> {
        let mut written = 0_u64;

        if self.time.is_some() {
            let mut buffer = Vec::<u8>::new();
            self.time.unwrap().write_bytes(&mut buffer)?;
            written += XP3Index { identifier: XP3_INDEX_TIME_IDENTIFIER, data: buffer }.write_bytes(stream)?;
        }

        {
            let mut buffer = Vec::<u8>::new();
            self.adler.write_bytes(&mut buffer)?;
            written += XP3Index { identifier: XP3_INDEX_ADLR_IDENTIFIER, data: buffer }.write_bytes(stream)?;
        }

        {
            let mut buffer = Vec::<u8>::new();
            for segment in self.segments.iter() {
                segment.write_bytes(&mut buffer)?;
            }

            written += XP3Index { identifier: XP3_INDEX_SEGM_IDENTIFIER, data: buffer }.write_bytes(stream)?;
        }

        {
            let mut buffer = Vec::<u8>::new();
            self.info.write_bytes(&mut buffer)?;
            written += XP3Index { identifier: XP3_INDEX_INFO_IDENTIFIER, data: buffer }.write_bytes(stream)?;
        }

        Ok(written)
    }

}

#[derive(Debug, Copy, Clone)]
#[repr(u32)]
pub enum IndexInfoFlag {

    NotProtected = 0,
    Protected = 2147483648

}

impl TryFrom<u32> for IndexInfoFlag {

    type Error = XP3Error;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {

            value if value == Self::NotProtected as u32 => Ok(Self::NotProtected),
            value if value == Self::Protected as u32 => Ok(Self::Protected),

            _ => Err(XP3Error::new(XP3ErrorKind::InvalidFileIndexFlag, None))
        }
    }
}

#[derive(Debug, Clone)]
/// Index info represents file metadatas like name.
pub struct XP3FileIndexInfo {

    flag: IndexInfoFlag,
    file_size: u64,
    saved_file_size: u64,
    name: String

}

impl XP3FileIndexInfo {

    pub fn new(
        flag: IndexInfoFlag,
        file_size: u64,
        saved_file_size: u64,
        name: String
    ) -> Self {
        Self {
            flag,
            file_size,
            saved_file_size,
            name
        }
    }

    pub fn flag(&self) -> IndexInfoFlag {
        self.flag
    }

    pub fn set_flag(&mut self, flag: IndexInfoFlag) {
        self.flag = flag;
    }

    pub fn file_size(&self) -> u64 {
        self.file_size
    }

    pub fn set_file_size(&mut self, file_size: u64) {
        self.file_size = file_size;
    }

    pub fn saved_file_size(&self) -> u64 {
        self.saved_file_size
    }

    pub fn set_saved_file_size(&mut self, saved_file_size: u64) {
        self.saved_file_size = saved_file_size;
    }
    
    pub fn name(&self) -> &String {
        &self.name
    }

    pub fn set_name(&mut self, name: String) {
        self.name = name;
    }

    /// Read xp3 file index info from stream.
    pub fn from_bytes(stream: &mut impl Read) -> Result<(u64, Self), XP3Error> {
        let flag = IndexInfoFlag::try_from(stream.read_u32::<LittleEndian>()?)?;

        let file_size = stream.read_u64::<LittleEndian>()?;
        let saved_file_size = stream.read_u64::<LittleEndian>()?;
        
        let name_byte_size = stream.read_u16::<LittleEndian>()? * 2;
        let name = {
            let mut name_buffer = Vec::with_capacity(name_byte_size as usize);
            stream.take(name_byte_size as u64).read_to_end(&mut name_buffer)?;
            
            UTF_16LE.decode(&name_buffer, DecoderTrap::Replace).unwrap()
        };

        Ok((22 + name_byte_size as u64, Self::new(flag, file_size, saved_file_size, name)))
    }

    /// Write xp3 file index info to stream.
    /// Returns written size.
    pub fn write_bytes(&self, stream: &mut impl Write) -> Result<u64, XP3Error> {
        stream.write_u32::<LittleEndian>(self.flag as u32)?;
        
        stream.write_u64::<LittleEndian>(self.file_size)?;
        stream.write_u64::<LittleEndian>(self.saved_file_size)?;

        let encoded = UTF_16LE.encode(&self.name, EncoderTrap::Replace).unwrap();
        let name_byte_size = encoded.len().min(65536);
        stream.write_u16::<LittleEndian>((name_byte_size / 2) as u16)?;
        stream.write_all(&encoded[..name_byte_size])?;

        Ok(22 + name_byte_size as u64)
    }

}

#[derive(Debug, Copy, Clone)]
#[repr(u32)]
pub enum IndexSegmentFlag {

    UnCompressed = 0,
    Compressed = 1

}

#[derive(Debug, Copy, Clone)]
/// Index segments representing data fragments of target file.
/// Almost all archive have 1 segments each files but there can be more.
pub struct XP3FileIndexSegment {

    flag: IndexSegmentFlag,
    data_offset: u64,
    original_size: u64,
    saved_size: u64

}

impl XP3FileIndexSegment {

    pub fn new(
        flag: IndexSegmentFlag,
        data_offset: u64,
        original_size: u64,
        saved_size: u64
    ) -> Self {
        Self {
            flag, data_offset, original_size, saved_size
        }
    }

    pub fn flag(&self) -> IndexSegmentFlag {
        self.flag
    }

    pub fn set_flag(&mut self, flag: IndexSegmentFlag) {
        self.flag = flag;
    }

    pub fn data_offset(&self) -> u64 {
        self.data_offset
    }

    pub fn set_data_offset(&mut self, data_offset: u64) {
        self.data_offset = data_offset;
    }

    pub fn original_size(&self) -> u64 {
        self.original_size
    }

    pub fn set_original_size(&mut self, original_size: u64) {
        self.original_size = original_size;
    }

    pub fn saved_size(&self) -> u64 {
        self.saved_size
    }

    pub fn set_saved_size(&mut self, saved_size: u64) {
        self.saved_size = saved_size;
    }

    /// Read xp3 file index segment from stream.
    pub fn from_bytes(stream: &mut impl Read) -> Result<(u64, Self), XP3Error> {
        let flag = {
            let raw_flag = stream.read_u32::<LittleEndian>()?;

            if raw_flag == IndexSegmentFlag::UnCompressed as u32 {
                Ok(IndexSegmentFlag::UnCompressed)
            } else if raw_flag == IndexSegmentFlag::Compressed as u32 {
                Ok(IndexSegmentFlag::Compressed)
            } else {
                Err(XP3Error::new(XP3ErrorKind::InvalidFileIndex, None))
            }
        }?;

        let data_offset = stream.read_u64::<LittleEndian>()?;
        let original_size = stream.read_u64::<LittleEndian>()?;
        let saved_size = stream.read_u64::<LittleEndian>()?;

        Ok((28, Self::new(flag, data_offset, original_size, saved_size)))
    }

    /// Write xp3 file index segment to stream.
    /// Returns written size.
    pub fn write_bytes(&self, stream: &mut impl Write) -> Result<u64, XP3Error> {
        stream.write_u32::<LittleEndian>(self.flag as u32)?;

        stream.write_u64::<LittleEndian>(self.data_offset)?;
        stream.write_u64::<LittleEndian>(self.original_size)?;
        stream.write_u64::<LittleEndian>(self.saved_size)?;

        Ok(28)
    }

}

#[derive(Debug, Copy, Clone)]
/// Index time representing timestamp of target file.
pub struct XP3FileIndexTime {

    timestamp: u64

}

impl XP3FileIndexTime {

    pub fn new(timestamp: u64) -> Self {
        Self {
            timestamp
        }
    }

    pub fn timestamp(&self) -> u64 {
        self.timestamp
    }

    pub fn set_timestamp(&mut self, timestamp: u64) {
        self.timestamp = timestamp;
    }

    /// Read xp3 file index time from stream.
    pub fn from_bytes(stream: &mut impl Read) -> Result<(u64, Self), XP3Error> {
        let timestamp = stream.read_u64::<LittleEndian>()?;

        Ok((8, Self::new(timestamp)))
    }

    /// Write xp3 file time to stream.
    pub fn write_bytes(&self, stream: &mut impl Write) -> Result<u64, XP3Error> {
        stream.write_u64::<LittleEndian>(self.timestamp)?;

        Ok(8)
    }

}

#[derive(Debug, Copy, Clone)]
/// Index adler representing adler32 checksum of target file.
pub struct XP3FileIndexAdler {

    checksum: u32

}

impl XP3FileIndexAdler {

    pub fn new(checksum: u32) -> Self {
        Self {
            checksum
        }
    }

    pub fn checksum(&self) -> u32 {
        self.checksum
    }

    pub fn set_checksum(&mut self, checksum: u32) {
        self.checksum = checksum;
    }

    /// Read xp3 file index time from stream.
    pub fn from_bytes(stream: &mut impl Read) -> Result<(u64, Self), XP3Error> {
        let checksum = stream.read_u32::<LittleEndian>()?;

        Ok((4, Self::new(checksum)))
    }

    /// Write xp3 file time to stream.
    pub fn write_bytes(&self, stream: &mut impl Write) -> Result<u64, XP3Error> {
        stream.write_u32::<LittleEndian>(self.checksum)?;

        Ok(4)
    }

}