Source

mobidump / mobidump

  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
#!/usr/bin/env python

# Copyright (c) 2009 SUZUKI Tetsuya <suzuki@spice-of-life.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from optparse import OptionParser, OptionGroup
from struct import pack, unpack
from cStringIO import StringIO
import os
import sys

VERSION = '0.1'

parser = OptionParser(usage='%prog [options] file',
        version='mobidump %s' % VERSION)

parser.remove_option('-h')
parser.add_option('-h', '--help', dest='help',
        action='store_true', default=False,
        help='Prints this help message and exit.')

opt = parser.get_option('--version')
parser.remove_option('--version')
opt.help = 'Prints version and exit.'
opt._short_opts = ['-V']
parser.add_option(opt)

parser.add_option('-d', '--debug', dest='debug',
        action='store_true', default=False,
        help='Prints debug messages.')

parser.add_option('-M', '--MOBI', dest='until_mobi_header',
        action='store_true', default=False,
        help='Parses and dumps until MOBI header.')

debug = False
until_mobi_header = False

def main():
    global parser
    options, args = parser.parse_args()
    if options.help:
        parser.print_help()
    elif len(args) != 1:
        parser.print_usage()
    else:
        path = args[0]
        if os.path.exists(path):
            global debug, until_mobi_header 
            debug = options.debug
            until_mobi_header = options.until_mobi_header 
            mobi = parse(path)
            dump(mobi)
        else:
            print '%s: no such file -- %s' % (sys.argv[0], path)

def parse(path):
    global until_mobi_header 

    mobi = MOBIData()
    f = open(path, "rb")
    parse_pdb_header(mobi, f)
    pdoc_f = StringIO(mobi.records[0].content)
    parse_palm_doc_header(mobi, pdoc_f)
    parse_mobi_header(mobi, pdoc_f)
    if not until_mobi_header: 
        if mobi.has_exth_record():
            parse_exth_header(mobi, pdoc_f)

    # get full name
    pdoc_f.seek(mobi.mobi_full_name_offset)
    mobi.mobi_full_name = pdoc_f.read(mobi.mobi_full_name_length)

    f.close()
    return mobi

def parse_pdb_header(mobi, f):
    mobi.name = parse_str(f, 32, True)
    mobi.attrs = parse_ushort(f)
    mobi.version = parse_ushort(f)
    mobi.creation_date = parse_uint(f)
    mobi.modification_date = parse_uint(f)
    mobi.last_backup_date = parse_uint(f)
    mobi.modification_number = parse_uint(f)
    mobi.app_info_id = parse_uint(f)
    mobi.sort_info_id = parse_uint(f)
    mobi.type = parse_str(f, 4)
    mobi.creator = parse_str(f, 4)
    mobi.unique_id_seed = parse_uint(f)
    mobi.next_record_list_id = parse_uint(f)
    mobi.record_count = parse_ushort(f)

    # record list
    mobi.records = []
    for i in xrange(0, mobi.record_count):
        rec = MOBIRecord(mobi)
        rec.offset = parse_uint(f)
        rec.attrs = parse_ubyte(f)
        rec.uid = parse_u3bytes(f)
        mobi.records.append(rec)

    # gap to data
    f.read(2)

    # records
    for i, rec in enumerate(mobi.records):
        if i+1 < mobi.record_count:
            next = mobi.records[i+1]
            bytes = f.read(next.offset - rec.offset)
        else:
            bytes = f.read()
        rec.content = bytes
        rec.length = len(bytes)

def parse_palm_doc_header(mobi, f):
    mobi.palm_doc_compression = parse_ushort(f)
    # unused
    f.read(2)
    mobi.palm_doc_text_length = parse_uint(f)
    mobi.palm_doc_record_count = parse_ushort(f)
    mobi.palm_doc_record_size = parse_ushort(f)
    mobi.palm_doc_current_position = parse_uint(f)

def parse_mobi_header(mobi, f):
    # identifier (MOBI)
    ident = f.read(4)
    if ident != 'MOBI':
        raise IOError, 'expected MOBI'
    mobi.mobi_header_length = parse_uint(f)
    mobi.mobi_type = parse_uint(f)
    mobi.mobi_text_encoding = parse_uint(f)
    mobi.mobi_unique_id = parse_uint(f) # random
    mobi.mobi_generator_version = parse_uint(f)
    f.read(40) # reserved (40)
    mobi.mobi_first_non_book_index = parse_uint(f)
    mobi.mobi_full_name_offset = parse_uint(f)
    mobi.mobi_full_name_length = parse_uint(f)
    mobi.mobi_language = parse_uint(f)
    mobi.mobi_input_language = parse_uint(f)
    mobi.mobi_output_language = parse_uint(f)
    mobi.mobi_format_version = parse_uint(f)
    if not (1 <= mobi.mobi_format_version and \
            mobi.mobi_format_version <= mobi.mobi_generator_version):
        raise IOError, 'format version error -- %d' % mobi.mobi_format_version
    mobi.mobi_first_image_index = parse_uint(f)
    f.read(16) # often zeros (16)
    mobi.mobi_exth_flags = parse_uint(f)
    f.read(36) # unknown (36)
    mobi.mobi_drm_offset = parse_uint(f)
    mobi.mobi_drm_count = parse_ushort(f)
    mobi.mobi_drm_size = parse_ushort(f)
    mobi.mobi_drm_flags = parse_uint(f)
    f.read(62) # unknown (62)
    mobi.mobi_extra_data_flags = parse_ushort(f)

    if mobi.has_long_mobi_header():
        parse_uint(f) # unknown

def parse_exth_header(mobi, f):
    ident = f.read(4)
    if ident != 'EXTH':
        raise IOError, 'EXTH identifier is not found'
    mobi.exth_header_length = parse_uint(f)
    mobi.exth_record_count = parse_uint(f)
    mobi.exth_records = []
    for i in xrange(0, mobi.exth_record_count):
        rec = EXTHRecord()
        rec.type = parse_uint(f)
        rec.length = parse_uint(f)
        rec.content = f.read(rec.length - 8)
        mobi.exth_records.append(rec)

def parse_str(f, l, null=False):
    value, = unpack('%ds' % l, f.read(l))
    if null:
        return value[:value.index('\0')]
    else:
        return value

def parse_ubyte(f):
    return unpack('!B', f.read(1))[0]

def parse_ushort(f):
    return unpack('!H', f.read(2))[0]

def parse_u3bytes(f):
    return unpack('!I', '\0' + f.read(3))[0]

def parse_uint(f):
    return unpack('!I', f.read(4))[0]

def decompress_palmdoc(bytes):
    blen = len(bytes)
    bytes = [ord(c) for c in bytes]
    outlen = 6000 # greater than 4096 (PalmDOC header record size)
    out = [0] * outlen
    i = 0
    j = 0
    while i < blen:
        c = bytes[i]
        i += 1
        if c >= 0xc0:
            # "Type C" command
            out[j] = 32 # ' '
            j += 1
            out[j] = c & 0x7f
            j += 1

        elif c >= 0x80:
            # "Type B" command
            c = (c << 8) | bytes[i]
            i += 1
            wdist = (c >> 3) & 0x07ff
            wcopy = j - wdist
            wlen = min((c & 7) + 3, outlen - j)
            for _ in xrange(0, wlen):
                out[j] = out[wcopy]
                j += 1
                wcopy += 1

        elif c >= 0x09:
            # copy unmodified
            out[j] = c
            j += 1

        elif c >= 0x01:
            c = min(c, outlen - j)
            for _ in xrange(0, c):
                out[j] = bytes[i]
                i += 1
                j += 1
    
        else:
            # copy unmodified
            out[j] = c
            j += 1

    from StringIO import StringIO
    s = StringIO()
    for c in out:
        if c > 0:
            s.write(chr(c))
        else:
            break
    return s.getvalue()

def dump(mobi):
    dump_value('Name', mobi.name)
    dump_hex2('Attributes', mobi.attrs)
    dump_value('Version', mobi.version)
    dump_value('Creation date', mobi.creation_date)
    dump_value('Modification date', mobi.modification_date)
    dump_value('Last backup date', mobi.last_backup_date)
    dump_value('Modification number', mobi.modification_number)
    dump_value('App info ID', mobi.app_info_id)
    dump_value('Sort info ID', mobi.sort_info_id)
    dump_value('Type', mobi.type)
    dump_value('Creator', mobi.creator)
    dump_value('Unique ID seed', mobi.unique_id_seed)
    dump_value('Next record list ID', mobi.next_record_list_id)
    dump_value('Number of records', mobi.record_count)

    print 'Records:'
    for i, rec in enumerate(mobi.records):
        dump_value('Record number', i+1, 1)
        dump_value('Unique ID', rec.uid, 1)
        dump_hex1('Record attributes', rec.attrs, 1)
        dump_hex4('Record data offset', rec.offset, 1)
        dump_value('Record data length', rec.length, 1)
        dump_bytes('Record data', rec.content, 1)
        print

    print 'PalmDOC header:'
    dump_value('Compression', mobi.palm_doc_compression, 1)
    dump_value('Text length', mobi.palm_doc_text_length, 1)
    dump_value('Record count', mobi.palm_doc_record_count, 1)
    dump_value('Record size', mobi.palm_doc_record_size, 1)
    dump_value('Current position', mobi.palm_doc_current_position, 1)
    print

    print 'MOBI header:'
    types = {2:'Mobipocket Book', 3:'PalmDoc Book', 4:'Audio',
            257:'News', 258:'News_Feed', 259:'News_Magazine',
            513:'PICS', 514:'WORD', 515:'XLS', 516:'PPT', 517:'TEXT',
            518:'HTML'}
    encs = {1252:'CP1252, WinLaten1', 65001:'UTF-8'}
    dump_value('Header length', mobi.mobi_header_length, 1)

    if mobi.mobi_type in types:
        desc = '%d (%s)' % (mobi.mobi_type, types[mobi.mobi_type])
    else:
        desc = '%d (unknown)' % mobi.mobi_type
    dump_value('Type', desc, 1)

    if mobi.mobi_text_encoding in encs:
        desc = '%d (%s)' % (mobi.mobi_text_encoding, \
                encs[mobi.mobi_text_encoding])
    else:
        desc = '%d (unknown)' % mobi.mobi_text_encoding
    dump_value('Text encoding', desc, 1)

    dump_value('Unique ID', mobi.mobi_unique_id, 1)
    dump_value('Generator version', mobi.mobi_generator_version, 1)
    dump_value('First non-book index', mobi.mobi_first_non_book_index, 1)
    dump_hex4('Full name offset', mobi.mobi_full_name_offset, 1)
    dump_value('Full name length', mobi.mobi_full_name_length, 1)
    dump_value('Full name', mobi.mobi_full_name, 1)

    lang = '0x%04X (' % mobi.mobi_language
    if mobi.mobi_language & 0x09:
        lang += 'English'
    if mobi.mobi_language & 0x0400:
        lang += ', US'
    elif mobi.mobi_language & 0x0800:
        lang += ', British'
    lang += ')'
    dump_value('Language', lang, 1)

    dump_value('Input language', mobi.mobi_input_language, 1)
    dump_value('Output language', mobi.mobi_output_language, 1)
    dump_value('Format version', mobi.mobi_format_version, 1)
    dump_value('First image index', mobi.mobi_first_image_index, 1)

    if mobi.has_exth_record():
        dump_value('EXTH flags', '0x%08X (exists EXTH record)' % \
                mobi.mobi_exth_flags, 1)
    else:
        dump_hex2('EXTH flags', mobi.mobi_exth_flags, 1)

    if mobi.mobi_drm_offset == 0xffffffff:
        dump_value('DRM offset', '0xFFFFFFFF (no DRM)', 1)
    else:
        dump_hex4('DRM offset', mobi.mobi_drm_offset, 1)
    dump_value('DRM count', mobi.mobi_drm_count, 1)
    dump_value('DRM size', mobi.mobi_drm_size, 1)
    dump_hex4('DRM flags', mobi.mobi_drm_flags, 1)
    dump_hex2('Extra data flags', mobi.mobi_extra_data_flags, 1)
    print

    global until_mobi_header 
    if not until_mobi_header and mobi.has_exth_record():
        dump_exth_header(mobi)

    print "Text content:\n    %s" % mobi.text_string()

exth_record_types = {1:'drm_server_id', 2:'drm_commerce_id',
        3:'drm_ebookbase_book_id', 100:'author', 101:'publisher',
        102:'imprint', 103:'description', 104:'isbn', 105:'subject',
        106:'publishingdate', 107:'review', 108:'contributor',
        109:'rights', 110:'subjectcode', 111:'type', 112:'source',
        113:'asin', 114:'versionnumber', 115:'sample', 116:'startreading',
        201:'coveroffset', 202:'thumboffset', 203:'hasfakecover',
        204:'204 Unknown', 205:'205 Unknown', 206:'206 Unknown',
        207:'207 Unknown', 300:'300 Unknown', 401:'clippinglimit',
        402:'publisherlimit', 403:'403 Unknown', 404:'404 ttsflag',
        501:'cdetype', 502:'lastupdatetime', 503:'updatedtitle'}

def dump_exth_header(mobi):
    global exth_record_types

    print 'EXTH header:'
    dump_value('Header length', mobi.exth_header_length, 1)
    dump_value('Record count', mobi.exth_record_count, 1)
    for i, rec in enumerate(mobi.exth_records):
        dump_value('Record number', i+1, 2)

        type = '0x%08X (' % rec.type
        if rec.type in exth_record_types:
            type += exth_record_types[rec.type]
        else:
            type += 'unknown'
        type += ')'
        dump_value('Type', type, 2)
        dump_value('Length', rec.length, 2)
        dump_bytes('Data', rec.content, 2)
        print

def dump_value(name, value, indent=0):
    print '%s%s: %s' % ('    ' * indent,
            name.ljust(20+indent*4), str(value))

def dump_bytes(name, bytes, indent=0):
    if bytes.isalnum():
        value = bytes[:8]
        if len(bytes) > 8:
            value += ' ...'
    else:
        value = '<'
        for b in bytes[:8]:
            value += '%02X ' % ord(b)
        if len(bytes) > 8:
            value += '...>'
        else:
            value += '>'
    dump_value(name, value, indent)

def dump_hex1(name, value, indent=0):
    value = '0x%02X' % value
    dump_value(name, value, indent)

def dump_hex2(name, value, indent=0):
    value = '0x%04X' % value
    dump_value(name, value, indent)

def dump_hex4(name, value, indent=0):
    value = '0x%08X' % value
    dump_value(name, value, indent)

class MOBIData(object):

    def has_exth_record(self):
        return self.mobi_exth_flags & 0x40

    def has_long_mobi_header(self):
        return self.mobi_header_length > 0xe4

    def text_string(self):
        from StringIO import StringIO
        s = StringIO()
        for i in xrange(0, self.palm_doc_record_count):
            rec = self.records[i+1]
            s.write(rec.text_string())
        return s.getvalue()
        

class MOBIRecord(object):

    def __init__(self, header):
        self.header = header

    def text_data(self):
        te_len = self.trailing_entries_length()
        end = len(self.content) - te_len
        return self.content[:end]

    def trailing_entries_length(self):
        def rec_length(ptr, psize):
            bitpos, result = 0, 0
            while True:
                v = ord(ptr[psize-1])
                result |= (v & 0x7F) << bitpos
                bitpos += 7
                psize -= 1
                if (v & 0x80) != 0 or (bitpos >= 28) or (psize == 0):
                    return result

        data = self.content
        num = 0
        size = len(data)
        flags = self.header.mobi_extra_data_flags >> 1
        while flags:
            if flags & 1:
                num += rec_length(data, size - num)
            flags >>= 1
        if self.header.mobi_extra_data_flags & 1:
            num += (ord(data[size - num - 1]) & 0x3) + 1
        return num

    def text_string(self):
        data = self.text_data()
        return decompress_palmdoc(data)


class EXTHRecord(object):
    pass

if __name__ == '__main__':
    main()