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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! An implementation of [MOBI](https://wiki.mobileread.com/wiki/MOBI) format data parsing and manipulation, written in Rust.
//!
//! The code is available on [GitHub](https://github.com/wojciechkepka/mobi-rs)
//! 
//! License: [*Apache-2.0*](https://github.com/wojciechkepka/mobi-rs/blob/master/license)
//! 
mod utils;
use byteorder::{BigEndian, ReadBytesExt};
use std::fs;
use std::io::Cursor;
use std::path::Path;

#[derive(Debug)]
/// Structure that holds parsed ebook information and contents
pub struct Mobi {
    pub contents: Vec<u8>,
    pub header: Header,
    pub records: Vec<Record>,
    pub palmdoc: PalmDocHeader,
    pub mobi: MobiHeader,
    pub exth: ExtHeader,
}
impl Mobi {
    /// Construct a Mobi object from passed file path
    pub fn init(file_path: &Path) -> Mobi {
        let contents = fs::read(file_path).unwrap();
        let header = Header::parse(&contents);
        let records = Record::parse_records(&contents, header.num_of_records);
        let palmdoc = PalmDocHeader::parse(&contents, header.num_of_records);
        let mobi = MobiHeader::parse(&contents, header.num_of_records);
        let exth = ExtHeader::parse(&contents, header.num_of_records);
        Mobi {
            contents,
            header,
            records,
            palmdoc,
            mobi,
            exth,
        }
    }
}
/// Parameters of Header
pub enum HeaderData {
    Name,
    Attributes,
    Version,
    Created,
    Modified,
    Backup,
    Modnum,
    AppInfoId,
    SortInfoId,
    TypE,
    Creator,
    UniqueIdSeed,
    NextRecordListId,
    NumOfRecords,
}
/// Parameters of PalmDOC Header
pub enum PalmDocHeaderData {
    Compression,
    TextLength,
    RecordCount,
    RecordSize,
    EncryptionType,
}

#[derive(Debug, PartialEq)]
/// Strcture that holds header information
pub struct Header {
    pub name: String,
    pub attributes: i16,
    pub version: i16,
    pub created: u32,
    pub modified: u32,
    pub backup: u32,
    pub modnum: u32,
    pub app_info_id: u32,
    pub sort_info_id: u32,
    pub typ_e: String,
    pub creator: String,
    pub unique_id_seed: u32,
    pub next_record_list_id: u32,
    pub num_of_records: u16,
}
impl Header {
    /// Parse a header from the content
    pub fn parse(content: &[u8]) -> Header {
        Header {
            name: Header::get_headers_string(content, HeaderData::Name),
            attributes: Header::get_headers_i16(content, HeaderData::Attributes),
            version: Header::get_headers_i16(content, HeaderData::Version),
            created: Header::get_headers_u32(content, HeaderData::Created),
            modified: Header::get_headers_u32(content, HeaderData::Modified),
            backup: Header::get_headers_u32(content, HeaderData::Backup),
            modnum: Header::get_headers_u32(content, HeaderData::Modnum),
            app_info_id: Header::get_headers_u32(content, HeaderData::AppInfoId),
            sort_info_id: Header::get_headers_u32(content, HeaderData::SortInfoId),
            typ_e: Header::get_headers_string(content, HeaderData::TypE),
            creator: Header::get_headers_string(content, HeaderData::Creator),
            unique_id_seed: Header::get_headers_u32(content, HeaderData::UniqueIdSeed),
            next_record_list_id: Header::get_headers_u32(content, HeaderData::NextRecordListId),
            num_of_records: Header::get_headers_u16(content, HeaderData::NumOfRecords),
        }
    }
    /// Gets i16 header value from specific location
    fn get_headers_i16(content: &[u8], header: HeaderData) -> i16 {
        let mut reader = Cursor::new(content);
        let position = match header {
            HeaderData::Attributes => 32,
            HeaderData::Version => 34,
            _ => 0,
        };
        reader.set_position(position);
        reader.read_i16::<BigEndian>().unwrap()
    }
    /// Gets u16 header value from specific location
    pub fn get_headers_u16(content: &[u8], header: HeaderData) -> u16 {
        let mut reader = Cursor::new(content);
        let position = match header {
            HeaderData::NumOfRecords => 76,
            _ => 0,
        };
        reader.set_position(position);
        reader.read_u16::<BigEndian>().unwrap()
    }
    /// Gets u32 header value from specific location
    fn get_headers_u32(content: &[u8], header: HeaderData) -> u32 {
        let mut reader = Cursor::new(content);
        let position = match header {
            HeaderData::Created => 36,
            HeaderData::Modified => 40,
            HeaderData::Backup => 44,
            HeaderData::Modnum => 48,
            HeaderData::AppInfoId => 52,
            HeaderData::SortInfoId => 56,
            HeaderData::UniqueIdSeed => 68,
            HeaderData::NextRecordListId => 72,
            _ => 0,
        };
        reader.set_position(position);
        reader.read_u32::<BigEndian>().unwrap()
    }
    /// Creates a string based on header bytes from specific location
    fn get_headers_string(content: &[u8], header: HeaderData) -> String {
        match header {
            HeaderData::Name => utils::u8_as_string(&content[0..32]),
            HeaderData::TypE => utils::u8_as_string(&content[60..64]),
            HeaderData::Creator => utils::u8_as_string(&content[64..68]),
            _ => String::new(),
        }
    }
}
#[derive(Debug, PartialEq)]
/// Strcture that holds PalmDOC header information
pub struct PalmDocHeader {
    pub compression: u16,
    pub text_length: u32,
    pub record_count: u16,
    pub record_size: u16,
    pub encryption_type: u16,
}
impl PalmDocHeader {
    /// Parse a PalmDOC header from the content
    pub fn parse(content: &[u8], num_of_records: u16) -> PalmDocHeader {
        PalmDocHeader {
            compression: PalmDocHeader::get_headers_u16(
                content,
                PalmDocHeaderData::Compression,
                num_of_records,
            ),
            text_length: PalmDocHeader::get_headers_u32(
                content,
                PalmDocHeaderData::TextLength,
                num_of_records,
            ),
            record_count: PalmDocHeader::get_headers_u16(
                content,
                PalmDocHeaderData::RecordCount,
                num_of_records,
            ),
            record_size: PalmDocHeader::get_headers_u16(
                content,
                PalmDocHeaderData::RecordSize,
                num_of_records,
            ),
            encryption_type: PalmDocHeader::get_headers_u16(
                content,
                PalmDocHeaderData::EncryptionType,
                num_of_records,
            ),
        }
    }
    /// Gets u16 header value from specific location
    fn get_headers_u16(content: &[u8], pdheader: PalmDocHeaderData, num_of_records: u16) -> u16 {
        let mut reader = Cursor::new(content);
        let position = match pdheader {
            PalmDocHeaderData::Compression => 80,
            PalmDocHeaderData::RecordCount => 88,
            PalmDocHeaderData::RecordSize => 90,
            PalmDocHeaderData::EncryptionType => 92,
            _ => 0,
        };
        reader.set_position(position + u64::from(num_of_records * 8));
        reader.read_u16::<BigEndian>().unwrap()
    }
    /// Gets u32 header value from specific location
    fn get_headers_u32(content: &[u8], pdheader: PalmDocHeaderData, num_of_records: u16) -> u32 {
        let mut reader = Cursor::new(content);
        let position = match pdheader {
            PalmDocHeaderData::TextLength => 84,
            _ => 0,
        };
        reader.set_position(position + u64::from(num_of_records * 8));
        reader.read_u32::<BigEndian>().unwrap()
    }
}

#[derive(Debug, PartialEq)]
/// Strcture that holds Mobi header information
pub struct MobiHeader {
    pub identifier: u32,
    pub header_length: u32,
    pub mobi_type: u32,
    pub text_encoding: u32,
    pub id: u32,
    pub gen_version: u32,
    pub first_non_book_index: u32,
    pub name: String,
    pub name_offset: u32,
    pub name_length: u32,
    pub language: u32,
    pub input_language: u32,
    pub output_language: u32,
    pub format_version: u32,
    pub first_image_index: u32,
    pub first_huff_record: u32,
    pub huff_record_count: u32,
    pub first_data_record: u32,
    pub data_record_count: u32,
    pub exth_flags: u32,
    pub has_exth_header: bool,
    pub drm_offset: u32,
    pub drm_count: u32,
    pub drm_size: u32,
    pub drm_flags: u32,
    pub last_image_record: u16,
    pub fcis_record: u32,
    pub flis_record: u32,
}
/// Parameters of Mobi Header
pub enum MobiHeaderData {
    Identifier,
    HeaderLength,
    MobiType,
    TextEncoding,
    Id,
    GenVersion,
    FirstNonBookIndex,
    NameOffset,
    NameLength,
    Language,
    InputLanguage,
    OutputLanguage,
    FormatVersion,
    FirstImageIndex,
    FirstHuffRecord,
    HuffRecordCount,
    FirstDataRecord,
    DataRecordCount,
    ExthFlags,
    DrmOffset,
    DrmCount,
    DrmSize,
    DrmFlags,
    LastImageRecord,
    FcisRecord,
    FlisRecord,
}
impl MobiHeader {
    /// Parse a Mobi header from the content
    pub fn parse(content: &[u8], num_of_records: u16) -> MobiHeader {
        let mut m = MobiHeader {
            identifier: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::Identifier,
                num_of_records,
            ),
            header_length: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::HeaderLength,
                num_of_records,
            ),
            mobi_type: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::MobiType,
                num_of_records,
            ),
            text_encoding: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::TextEncoding,
                num_of_records,
            ),
            id: MobiHeader::get_headers_u32(&content, MobiHeaderData::Id, num_of_records),
            gen_version: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::GenVersion,
                num_of_records,
            ),
            first_non_book_index: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FirstNonBookIndex,
                num_of_records,
            ),
            name: MobiHeader::name(&content, num_of_records),
            name_offset: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::NameOffset,
                num_of_records,
            ),
            name_length: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::NameLength,
                num_of_records,
            ),
            language: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::Language,
                num_of_records,
            ),
            input_language: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::InputLanguage,
                num_of_records,
            ),
            output_language: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::OutputLanguage,
                num_of_records,
            ),
            format_version: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FormatVersion,
                num_of_records,
            ),
            first_image_index: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FirstImageIndex,
                num_of_records,
            ),
            first_huff_record: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FirstHuffRecord,
                num_of_records,
            ),
            huff_record_count: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::HuffRecordCount,
                num_of_records,
            ),
            first_data_record: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FirstDataRecord,
                num_of_records,
            ),
            data_record_count: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::DataRecordCount,
                num_of_records,
            ),
            exth_flags: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::ExthFlags,
                num_of_records,
            ),
            has_exth_header: false,
            drm_offset: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::DrmOffset,
                num_of_records,
            ),
            drm_count: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::DrmCount,
                num_of_records,
            ),
            drm_size: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::DrmSize,
                num_of_records,
            ),
            drm_flags: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::DrmFlags,
                num_of_records,
            ),
            last_image_record: MobiHeader::get_headers_u16(
                &content,
                MobiHeaderData::LastImageRecord,
                num_of_records,
            ),
            fcis_record: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FcisRecord,
                num_of_records,
            ),
            flis_record: MobiHeader::get_headers_u32(
                &content,
                MobiHeaderData::FlisRecord,
                num_of_records,
            ),
        };
        m.exth_header();
        m
    }
    /// Gets u32 header value from specific location
    fn get_headers_u32(content: &[u8], mheader: MobiHeaderData, num_of_records: u16) -> u32 {
        let mut reader = Cursor::new(content);
        let position = match mheader {
            MobiHeaderData::Identifier => 100,
            MobiHeaderData::HeaderLength => 104,
            MobiHeaderData::MobiType => 108,
            MobiHeaderData::TextEncoding => 112,
            MobiHeaderData::Id => 116,
            MobiHeaderData::GenVersion => 120,
            MobiHeaderData::FirstNonBookIndex => 160,
            MobiHeaderData::NameOffset => 164,
            MobiHeaderData::NameLength => 168,
            MobiHeaderData::Language => 172,
            MobiHeaderData::InputLanguage => 176,
            MobiHeaderData::OutputLanguage => 180,
            MobiHeaderData::FormatVersion => 184,
            MobiHeaderData::FirstImageIndex => 188,
            MobiHeaderData::FirstHuffRecord => 192,
            MobiHeaderData::HuffRecordCount => 196,
            MobiHeaderData::FirstDataRecord => 200,
            MobiHeaderData::DataRecordCount => 204,
            MobiHeaderData::ExthFlags => 208,
            MobiHeaderData::DrmOffset => 248,
            MobiHeaderData::DrmCount => 252,
            MobiHeaderData::DrmSize => 256,
            MobiHeaderData::DrmFlags => 260,
            MobiHeaderData::FcisRecord => 280,
            MobiHeaderData::FlisRecord => 288,
            _ => 0,
        };
        reader.set_position(position + u64::from(num_of_records * 8));
        reader.read_u32::<BigEndian>().unwrap()
    }
    /// Gets u16 header value from specific location
    fn get_headers_u16(content: &[u8], mheader: MobiHeaderData, num_of_records: u16) -> u16 {
        let mut reader = Cursor::new(content);
        let position = match mheader {
            MobiHeaderData::LastImageRecord => 274,
            _ => 0,
        };
        reader.set_position(position + u64::from(num_of_records * 8));
        reader.read_u16::<BigEndian>().unwrap()
    }
    /// Returns the book name
    pub fn name(content: &[u8], num_of_records: u16) -> String {
        let name_offset =
            MobiHeader::get_headers_u32(content, MobiHeaderData::NameOffset, num_of_records);
        let name_length =
            MobiHeader::get_headers_u32(content, MobiHeaderData::NameLength, num_of_records);
        let mut name = String::new();
        let mut count = 0;
        for byte in &content[name_offset as usize + (num_of_records * 8) as usize + 80..] {
            if count == name_length {
                break;
            }
            name.push(*byte as char);
            count += 1;
        }
        name
    }
    /// Checks if there is a Exth Header and changes the parameter
    fn exth_header(&mut self) {
        self.has_exth_header = (self.exth_flags & 0x40) != 0;
    }
}
/// Parameters of Exth Header
pub enum ExtHeaderData {
    Identifier,
    HeaderLength,
    RecordCount,
}
#[derive(Debug, Default, PartialEq)]
/// Strcture that holds Exth header information
pub struct ExtHeader {
    pub identifier: u32,
    pub header_length: u32,
    pub record_count: u32,
    pub records: Vec<(u32, u32, String)>,
}
impl ExtHeader {
    /// Parse a Exth header from the content
    pub fn parse(content: &[u8], num_of_records: u16) -> ExtHeader {
        let mut extheader = ExtHeader {
            identifier: ExtHeader::get_headers_u32(
                content,
                ExtHeaderData::Identifier,
                num_of_records,
            ),
            header_length: ExtHeader::get_headers_u32(
                content,
                ExtHeaderData::HeaderLength,
                num_of_records,
            ),
            record_count: ExtHeader::get_headers_u32(
                content,
                ExtHeaderData::RecordCount,
                num_of_records,
            ),
            records: vec![],
        };
        extheader.get_records(content, num_of_records);
        extheader
    }
    /// Gets u32 header value from specific location
    fn get_headers_u32(content: &[u8], extheader: ExtHeaderData, num_of_records: u16) -> u32 {
        let mut reader = Cursor::new(content);
        let position = match extheader {
            ExtHeaderData::Identifier => 328,
            ExtHeaderData::HeaderLength => 332,
            ExtHeaderData::RecordCount => 336,
        };
        reader.set_position(position + u64::from(num_of_records * 8));
        reader.read_u32::<BigEndian>().unwrap()
    }
    /// Gets header records
    fn get_records(&mut self, content: &[u8], num_of_records: u16) {
        let mut records = vec![];
        let mut reader = Cursor::new(content);
        let position: u64 = 340 + u64::from(num_of_records * 8);
        reader.set_position(position);
        for _i in 0..self.record_count {
            let mut record_data = vec![];
            let record_type = reader.read_u32::<BigEndian>().unwrap_or(0);
            let record_len = reader.read_u32::<BigEndian>().unwrap_or(0);
            for _j in 0..record_len - 8 {
                record_data.push(reader.read_u8().unwrap_or(0));
            }
            records.push((
                record_len,
                record_type,
                utils::u8_as_string(&record_data[..]),
            ));
        }
        self.records = records;
    }
}

#[derive(Debug)]
/// A "cell" in the whole books content
pub struct Record {
    record_data_offset: u32,
    id: u32,
    record_data: String,
}
impl Record {
    #[allow(dead_code)]
    fn new() -> Record {
        Record {
            record_data_offset: 0,
            id: 0,
            record_data: String::new(),
        }
    }
    /// Reads into a string the record data based on record_data_offset
    fn record_data(&mut self, content: &[u8]) {
        if self.record_data_offset + 8 < content.len() as u32 {
            let string =
                &content[self.record_data_offset as usize..(self.record_data_offset + 8) as usize];
            self.record_data = utils::u8_as_string(string);
        }
    }
    /// Parses a record from the reader at current position
    fn parse_record(reader: &mut Cursor<&[u8]>) -> Record {
        let record_data_offset = reader.read_u32::<BigEndian>().unwrap();
        let id = reader.read_u32::<BigEndian>().unwrap();
        let mut record = Record {
            record_data_offset,
            id,
            record_data: String::new(),
        };
        record.record_data(*reader.get_ref());
        record
    }
    /// Gets all records in the specified content
    fn parse_records(content: &[u8], num_of_records: u16) -> Vec<Record> {
        let mut reader = Cursor::new(content);
        let mut records = vec![];
        for _i in 0..num_of_records {
            let record = Record::parse_record(&mut reader);
            records.push(record);
        }
        records
    }
    #[allow(dead_code)]
    fn read(&self, content: &[u8], record_num: usize, records: &[Record]) -> String {
        let next_record = &records[record_num + 1];
        println!("{}", self.record_data_offset);
        println!("{}", next_record.record_data_offset);
        utils::u8_as_string(
            &content[self.record_data_offset as usize..next_record.record_data_offset as usize],
        )
    }
    // TODO
    // lz77 decompression
}