From 64b6ef4afdd9d41402ad6cfc979f99b5e9e0e6dc Mon Sep 17 00:00:00 2001 From: Tigran Aivazian Date: Mon, 8 Oct 2012 19:46:45 +0100 Subject: [PATCH] Validate DjVu magic string before opening. While browsing libdjvu sources I remembered that I always validated DjVu magic string before passing the file to djvulibre. This is because forcing djvulibre errors on open is a bad idea --- it can lead to very strange side effects, such as refusing to open the next (valid!) DjVu file. So, I have now implemented the same in KPV --- check DjVu magic string before passing it to the proper DjVu :openDocument() method. I timed the difference between opening with and without validation and it was absolutely negligible (i.e. by far most of the time is spent in DjVu document decoding anyway). --- djvureader.lua | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/djvureader.lua b/djvureader.lua index 05ce15267..93cea9f81 100644 --- a/djvureader.lua +++ b/djvureader.lua @@ -2,9 +2,23 @@ require "unireader" DJVUReader = UniReader:new{} +-- check DjVu magic string to validate +function validDJVUFile(filename) + f = io.open(filename, "r") + if not f then return false end + local magic = f:read(8) + f:close() + if not magic or magic ~= "AT&TFORM" then return false end + return true +end + -- open a DJVU file and its settings store -- DJVU does not support password yet function DJVUReader:open(filename) + if not validDJVUFile(filename) then + return false, "Not a valid DjVu file" + end + local ok ok, self.doc = pcall(djvu.openDocument, filename, self.cache_document_size) if not ok then