Repository navigation
TIKA-5026: Parse Mobipocket and Kindle ebooks (.mobi, .prc, .azw, .azw3) - #3520
Merged
Merged
Conversation
3 of 4 tasks
MobiParser reads the Palm Database container: EXTH metadata from record 0 (title, creators, publisher, description, ISBN and ASIN, subjects, date, contributor, rights, language with the header's locale as fallback), the cover (EXTH 201, else 202) as the THUMBNAIL embedded document and the other image records as INLINE, and the text records, stored, PalmDOC- or HUFF/CDIC-compressed, with their trailing entries stripped and the bytes decoded once, through the HTML parser. A hybrid file yields its KF8 book, rebuilt as a Palm Database of its own records with the header's record indices rebased, as an embedded ALTERNATE_FORMAT_CHUNK; an encrypted book keeps metadata and images and ends in an EncryptedDocumentException. New keys mobi:version, mobi:compression, mobi:encryption, mobi:cde-type and mobi:hybrid, plus Content-Encoding; the registry is regenerated. application/vnd.amazon.mobi8-ebook (*.azw3) is new, and with application/vnd.amazon.ebook a sub-type of application/x-mobipocket-ebook. Everything the file can make the parser allocate is bounded: the file at 256 MB, the text at maxTextLength (64 MB, a parser setting), the CDIC dictionary at 16 MB counting an overhead per phrase, a decoded phrase at 64 KB, phrase nesting at 32 levels; a record index of 0xFFFFFFFF means none. There is no published specification of the HUFF and CDIC records; their layout is known from the open-source readers of the format and is summarised in the HuffCdic javadoc, from which the decoder is written. Tests: seven fixtures of 2 to 6 KB built by src/test/python/make_mobi_fixtures.py (deterministic; a real canonical Huffman code with 8, 10 and 12 bit codes, a hybrid, an encrypted book, unreadable HUFF tables, an unknown compression), metadata, text, images, KF8, HUFF/CDIC, hybrid and encrypted behaviour, truncated input, byte flips over every fixture, and hand-built tables that hit each limit.
dschmidt
force-pushed
the
TIKA-5026-mobi-parser
branch
from
November 3, 2026 15:02
dbaae72 to
8d41f61
Compare
dschmidt
marked this pull request as ready for review
November 3, 2026 15:41
tika-server answers a thrown EncryptedDocumentException with 422, and the client loses the cover and the metadata that an encrypted Mobipocket book does give up. The parser records the exception as a warning now, with mobi:encryption saying which scheme, and the unpack and rmeta endpoints answer with what there is.
A download that stopped leaves a record table that lists records past the end of the file; the parser refused the whole book, cover and metadata included. The records that are there are read now, the missing ones are dropped, and a warning says how many of the listed records the file holds. Found with the regression corpus sample on the ticket, where the one-MiB cut of a hybrid still carries its cover.
dschmidt
force-pushed
the
TIKA-5026-mobi-parser
branch
from
November 4, 2026 16:10
5510d04 to
ce391d0
Compare
Contributor
|
A couple of important finds and some that are meh? Let me know what you think. |
…imits A hybrid's KF8 half is emitted only with extractKf8; its header's record indices already count from its own record 0, so they are kept as they are. KF8 text ends at the first FDST flow. Encrypted books set tika:encrypted. maxFileSize (256 MB) reads the beginning of a larger book, the text is cut at 16 MB and at 32 times the file size, EXTH records and values per type are bounded, a bad HUFF code keeps the text decoded before it, dates go through TikaDates, unknown codepages read as windows-1252, and a file that is not a Mobipocket book yields a warning instead of an exception. The fixtures follow real hybrids and carry FDST records; supported-formats.adoc is regenerated.
Contributor
Author
|
Thanks, all fifteen addressed in b9ad505.
Also re-run against your 19-file sample and the Gutenberg books: covers match the index (the 1 MiB cut lacks its cover, which is behind the cut), no container exceptions. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Tika detects Mobipocket books (
application/x-mobipocket-ebook, by theBOOKMOBImagic) and Kindle.azwfiles, but no parser handles them:/rmetareturns the content type and nothing else, while the EPUB of the same book yields title, author, text and the cover. The KF8 generation (.azw3) is not even intika-mimetypes.xml.This adds
MobiParsernext toEpubParserin the miscoffice module. All three formats share one container, a Palm Database whose record 0 holds the PalmDOC header, the MOBI header and the EXTH metadata records, followed by the text records and the images; KF8 only has a longer MOBI header and a different text layout, so one parser serves them all:application/vnd.amazon.mobi8-ebook. A record index of 0xFFFFFFFF in EXTH 121, 201 or 202 means "none", as the writers use it.THUMBNAILembedded document namedcover.<ext>, the EXTH 202 thumbnail and the other images asINLINE; when 201 is absent or NULL, the 202 record is theTHUMBNAIL. In a hybrid file the images are read up to the KF8 half the parser accepted (see below); the two halves share them. An EXTH 121 that leads nowhere does not cut them.BOUNDARYrecord, a KF8 book for newer readers. The first is the document; the second, whose record 0 has to carry a KF8 header (anything else behind the boundary is not a hybrid:mobi:hybridstays false and a warning names the record), is rebuilt as a Palm Database of the records from its record 0 on, with the header's record index fields rebased to count from there and the first image index cleared (the halves share the images, which the first has emitted), and emitted as an embeddedapplication/vnd.amazon.mobi8-ebookof typeALTERNATE_FORMAT_CHUNKnamedkf8.azw3, so the same parser reads it and a client sees both renditions.mobi:version,mobi:compression(none, palmdoc, huffcdic, unknown),mobi:encryption(none, old-mobipocket, mobipocket, unknown),mobi:cde-type(EXTH 501, EBOK/PDOC) andmobi:hybrid, in a newMobiinterface next toEpub;Content-Encodingcarries the codepage. The metadata registry is regenerated (five keys added, gate tests pass).JSoupParser.parseString. HUFF/CDIC is the canonical Huffman code over a phrase dictionary that theHUFFandCDICrecords hold: a first-byte table (code length, whether the first byte settles the code, index base), a per-length table (smallest code, index base), phrases counted down from the base, phrases that are code streams themselves decoded on first use. There is no published specification of these two records; their layout is known from the open-source readers of the format, and theHuffCdicjavadoc summarises it. The decoder is written from that summary in its own form (a 32-bit window read at a bit position, onePhraseper dictionary entry, explicit budgets); no code was taken from those readers, which are GPL or LGPL licensed. The generator insrc/test/pythonencodes the fixtures and checks them against its own code table, not by reading the records back. KF8 text is taken as the records hold it, skeletons and fragments in order, without reassembly; the text comes out in reading order, the markup is not what a reader would render. An unknown compression type leaves a warning and yields metadata and images only.EncryptedDocumentExceptionin the warning metadata, withmobi:encryptionnaming the scheme, rather than thrown: tika-server answers a thrown exception with 422, and a client asking/unpack/preset/thumbnailfor the cover would get nothing although the cover is there.Detection:
application/vnd.amazon.mobi8-ebookwith glob*.azw3andapplication/vnd.amazon.ebook(*.azw) both become sub-types ofapplication/x-mobipocket-ebook, so a file whose name says.azw3and whose content saysBOOKMOBIresolves to the specific type and reaches the parser either way. The generation is only visible from the header version, which the parser reports.Limits, since every size comes from the file: the book is read up to 256 MB (refused up front when the stream knows its length), the text is cut at 64 MB whatever the header declares (with a warning;
maxTextLengthon the parser changes it), the CDIC dictionary may hold 16 MB of literal and decoded phrases (every phrase counting an overhead, so a table of empty phrases is bounded too), a code-stream phrase may decode to 64 KB and phrases may nest 32 deep; anything beyond ends in aTikaException.maxTextLengthmust be positive. Every offset and length is checked before use.The miscoffice module gains a dependency on
tika-parser-html-module(as the mail and microsoft modules have) for the text.Tests: seven fixtures of 2 to 6 KB, built by
src/test/python/make_mobi_fixtures.py(in the module, so they can be regenerated) rather than by a reader application, described in the test's javadoc: a version 6 book in CP1252 with two PalmDOC-compressed text records, trailing entries, a JPEG cover, a PNG thumbnail, an inline GIF and FLIS/FCIS/EOF records; the same as a version 8 book in UTF-8 with KF8-style markup; a HUFF/CDIC variant whose text is a real canonical Huffman code (lengths 8, 10 and 12, so both the first-byte table and the per-length climb are exercised, over a phrase dictionary split across two CDIC records, one phrase itself a code stream) built by the generator and checked against its own code table, an encrypted variant, one with an unknown compression type and a NULL cover index, one whose HUFF index points at a text record, and a hybrid (version 6 book, shared images,BOUNDARY, version 8 book with different text, no EXTH 524 so the language comes from the locale).MobiParserTestcovers metadata and the new keys, text, the embedded image order and types, KF8, HUFF/CDIC, the hybrid's two renditions, the encrypted (warning, cover, no text), unknown-compression and unreadable-HUFF behaviour, date parsing and the trailing-entry arithmetic, plus truncated input at eight lengths, 200 rounds of random byte flips over each of the seven fixtures, which may end in aTikaExceptionbut nothing else (anIOExceptionwould fail the test), EXTH 121 pointing at every kind of record that is not a KF8 header, a version 6 header included, and hand-built HUFF/CDIC tables that hit the nesting, cycle, dictionary size, dictionary count and phrase-size limits and a text cap that is actually reached, so removing any of those limits fails a test (the 256 MB file cap has none, it would need a 256 MB fixture);TikaDetectionTestgetsx.azw3. Also run against Project Gutenberg's Frankenstein as.mobi(version 6) and.azw3(version 8): metadata, cover and 450k characters of text each; against an encrypted retail KF8 book: metadata and cover, no text; and against the 19-file regression corpus sample attached to the ticket (CommonCrawl: PalmDOC in CP1252 and UTF-8, stored, HUFF/CDIC, KF8-only, hybrids, DRM, versions 4 to 8, no-cover books, a hybrid cut at 1 MiB): every file's cover presence, text and metadata match the sample's index. The truncated one made the parser refuse the whole book at first; it now reads the records that are there and warns how many are missing.Docs: formats page, CHANGES.
Follow-up, out of scope here: KF8 skeleton/fragment reassembly (reading the INDX records to put the fragments back into their skeletons, which gives real XHTML documents instead of the records' order).
https://issues.apache.org/jira/browse/TIKA-5026