Skip to content

TIKA-5026: Parse Mobipocket and Kindle ebooks (.mobi, .prc, .azw, .azw3) - #3520

Merged
tballison merged 8 commits into
apache:mainfrom
dschmidt:TIKA-5026-mobi-parser
Nov 5, 2026
Merged

tballison merged 8 commits into
apache:mainfrom
dschmidt:TIKA-5026-mobi-parser

Conversation

@dschmidt

@dschmidt dschmidt commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Tika detects Mobipocket books (application/x-mobipocket-ebook, by the BOOKMOBI magic) and Kindle .azw files, but no parser handles them: /rmeta returns 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 in tika-mimetypes.xml.

This adds MobiParser next to EpubParser in 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:

  • Metadata from EXTH: title (503, else the full name), creators (100), publisher (101), description (103), identifiers (104 ISBN, 113/504 ASIN, deduplicated), subjects (105), publishing date (106, ISO date with or without time), contributor (108), rights (109), language (524, else the Windows language id in the header's locale). The content type is set from the header's file version: 8 and up is application/vnd.amazon.mobi8-ebook. A record index of 0xFFFFFFFF in EXTH 121, 201 or 202 means "none", as the writers use it.
  • Images: every image record from the header's first image index on, recognised by its JPEG/PNG/GIF/BMP magic (index, font and boundary records sit among them and are skipped). The record EXTH 201 points at is emitted as the THUMBNAIL embedded document named cover.<ext>, the EXTH 202 thumbnail and the other images as INLINE; when 201 is absent or NULL, the 202 record is the THUMBNAIL. 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.
  • Hybrid files: kindlegen's dual file holds a version 6 book and, behind a BOUNDARY record, 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:hybrid stays 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 embedded application/vnd.amazon.mobi8-ebook of type ALTERNATE_FORMAT_CHUNK named kf8.azw3, so the same parser reads it and a client sees both renditions.
  • Keys: mobi:version, mobi:compression (none, palmdoc, huffcdic, unknown), mobi:encryption (none, old-mobipocket, mobipocket, unknown), mobi:cde-type (EXTH 501, EBOK/PDOC) and mobi:hybrid, in a new Mobi interface next to Epub; Content-Encoding carries the codepage. The metadata registry is regenerated (five keys added, gate tests pass).
  • Text: the text records (stored, PalmDOC-compressed or HUFF/CDIC-compressed) with their trailing entries stripped per the header's flags at 0xF2, concatenated and decoded once (a multibyte character may straddle two records; codepage 1252 or 65001), then handed to JSoupParser.parseString. HUFF/CDIC is the canonical Huffman code over a phrase dictionary that the HUFF and CDIC records 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 the HuffCdic javadoc summarises it. The decoder is written from that summary in its own form (a 32-bit window read at a bit position, one Phrase per dictionary entry, explicit budgets); no code was taken from those readers, which are GPL or LGPL licensed. The generator in src/test/python encodes 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.
  • Encrypted books (encryption type != 0): record 0, EXTH and the image records are not encrypted, so metadata and cover come out in full; the locked text is recorded as an EncryptedDocumentException in the warning metadata, with mobi:encryption naming the scheme, rather than thrown: tika-server answers a thrown exception with 422, and a client asking /unpack/preset/thumbnail for the cover would get nothing although the cover is there.

Detection: application/vnd.amazon.mobi8-ebook with glob *.azw3 and application/vnd.amazon.ebook (*.azw) both become sub-types of application/x-mobipocket-ebook, so a file whose name says .azw3 and whose content says BOOKMOBI resolves 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; maxTextLength on 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 a TikaException. maxTextLength must 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). MobiParserTest covers 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 a TikaException but nothing else (an IOException would 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); TikaDetectionTest gets x.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

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
dschmidt force-pushed the TIKA-5026-mobi-parser branch from dbaae72 to 8d41f61 Compare November 3, 2026 15:02
@dschmidt
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
dschmidt force-pushed the TIKA-5026-mobi-parser branch from 5510d04 to ce391d0 Compare November 4, 2026 16:10
@tballison

Copy link
Copy Markdown
Contributor

A couple of important finds and some that are meh? Let me know what you think.

Contract (fix first)

  1. A hybrid file's book text comes out twice. Three reviewers found this independently.
     - Most kindlegen .mobi files are hybrids, carrying the same book in both halves. The second (KF8) half is emitted
       as an embedded document with full text, so /tika and text output contain the book twice, /rmeta has two
       near-duplicate documents, and the work is done twice.
     - It's marked ALTERNATE_FORMAT_CHUNK, which in Tika means OOXML altChunk: content that is part of the document,
       not a second copy.
     - The test fixture hides this because its two halves have different text.
     - Suggested shape: parse the first half by default and make the KF8 half opt-in, the way
       RFC822Parser.extractAllAlternatives works.
  2. The hybrid rebuild gets the record numbering backwards. I checked this against KindleUnpack's source.
     - In a real hybrid, the second header's record-index fields count from the KF8 record 0; KindleUnpack adds that
       record's index to each of them. The PR assumes they count from the start of the file and subtracts.
     - Most fields therefore become "none". A hybrid whose second half uses HUFF/CDIC compression would lose its text.
     - The generator makes the same assumption, so the test confirms the bug.
     - The PR says it matched a real 19-file sample. PalmDOC hybrids hide the bug because nothing they need reads
       those fields yet.
  3. KF8 text includes the CSS and SVG. The parser ignores the FDST record, which marks where each content flow starts
     and ends. Raw stylesheet rules after </html> end up as book text. The fix depends on #2.
  4. Encrypted books never set tika:encrypted. Recording a warning instead of throwing (the settled choice) skips the
     code that normally sets the flag. Setting it explicitly fixes this.
  5. TikaCLITest.testSupportedFormatsPartialIsCurrent will fail. I confirmed the generated
     docs/.../partials/supported-formats.adoc has no mobi entry; it needs regenerating.

  Edge cases

  6. Small files can force huge HTML parses. With HUFF/CDIC, a file of about 45 KB can decode to the 64 MB text cap,
     and jsoup then builds roughly a 2 GB tree in memory. Two things make it worse:
     - The HTML pass writes metadata into new Metadata() instead of Metadata.newInstance(context), so repeated <meta>
       tags skip the write limiter and hit the quadratic Metadata.add path. The estimate is about an hour of CPU,
       extrapolated from component timings, not run end to end.
     - Fix: use newInstance(context) and lower the default cap, or tie it to the expansion ratio.
  7. The number of EXTH metadata records is unbounded. Header metadata entries are limited only by record 0's size,
     and each value is added to metadata (quadratic). Roughly 10 minutes of CPU for a 10 MB file, and out-of-memory
     near the 256 MB cap. Cap the record count and the number of values per key.
  8. A hybrid holds about 4–5 copies of the book in memory at once, and builds them before asking whether embedded
     documents should be parsed at all. Ask first, then build the rebuilt file straight from slices.
  9. One bad HUFF code loses all the text decoded so far, even from records that decoded fine. Four reviewers flagged
     it. It contradicts the PR's own "read what's there" policy for truncated and otherwise broken books.
  10. Some .prc/.azw files go from empty success to an exception. A Palm app or PalmDOC .prc, or a Topaz or KFX .azw
      (format details unverified), is routed here by file extension alone and now throws. Return metadata only, or
      document it. Plain PalmDOC books would be a cheap follow-up, since the decompressor is already there.
  11. .azw files now detect as vnd.amazon.ebook instead of x-mobipocket-ebook. This affects anyone routing on the
      type. It needs a CHANGES line and a detection test (BOOKMOBI bytes plus a .azw/.azw3 name).
  12. The 256 MB cap is hard-coded and undocumented, and a book over it returns no metadata at all. Comic and manga
      books can plausibly be that large (unverified).
  13. Dates: EXTH 106 dates are parsed by hand instead of with TikaDates. Date-only values gain an invented midnight
      UTC time, and non-ISO dates are silently dropped.
  14. Unknown or zero codepage falls back to UTF-8. KindleUnpack uses windows-1252, so old .prc files would get
      garbled accented characters.
  15. Test gaps:
      - The 256 MB cap has no test; a sparse file would cover it without a 256 MB fixture.
      - The fuzz test never feeds mutated input into the hybrid's KF8 half and has no @Timeout.
      - Two tests suppress exceptions without asserting there wasn't one.
      - Untested: EXTH 524 taking precedence over the header locale, stored (uncompressed) text, the title fallback,
        and a positive cde-type.

…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.
@dschmidt

dschmidt commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, all fifteen addressed in b9ad505.

  1. A hybrid yields its version 6 book only; extractKf8 (off by default, like extractAllAlternatives) emits the KF8 copy, with no resource type instead of ALTERNATE_FORMAT_CHUNK.
  2. Right, checked against the four hybrids in your sample: read relative to the KF8 record 0, the indices land on HUFF, FDST, FCIS, FLIS, INDX and DATP; read from the file start, on unrelated records. The KF8 record 0 is now kept as it is (only the first image index is cleared), and the generator writes the indices that way. With extractKf8, the three of them that use HUFF/CDIC give 2391, 3703 and 37256 characters of KF8 text, where the KF8 half had about 60 and a warning before; the PalmDOC one hid the bug, as you suspected.
  3. KF8 text ends at the end of the first FDST flow. Both KF8-only books in the sample had stylesheet text before and have none now.
  4. tika:encrypted is set alongside the warning.
  5. supported-formats.adoc regenerated; testSupportedFormatsPartialIsCurrent passes.
  6. The HTML pass uses Metadata.newInstance(context); the text is cut at maxTextLength (now 16 MB) and at 32 times the file size.
  7. EXTH is read up to 1024 records and 64 values per type.
  8. The KF8 half is built only when it is extracted and the extractor wants it, straight from the file's records into one array.
  9. A record that does not decode keeps the text of the records before it, with a warning.
  10. A file that is not a Mobipocket book (another Palm Database type, or no Palm Database at all, as a Topaz or KFX book named .azw) yields a warning and nothing else. PalmDOC TEXtREAd text would be a cheap follow-up.
  11. CHANGES says so, and a detection test covers .mobi, .azw, .azw3 and .prc with BOOKMOBI content.
  12. maxFileSize (256 MB by default) is a setting and documented; of a larger book the beginning is read as a truncated one is, so the metadata and what fits come out.
  13. EXTH 106 goes through TikaDates.toMetadataString: a date-only value stays a date, non-ISO dates parse.
  14. Unknown and zero codepages read as windows-1252.
  15. Tests for the file limit (with a small maxFileSize), the fuzz test with extractKf8 and a @Timeout, the two tests that swallowed exceptions now assert, and a new stored-text fixture covers EXTH 524 over the locale, the title fallback and a cde-type.

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.

@tballison
tballison merged commit 67645ba into apache:main Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants