diff --git a/backend/src/main/java/org/booklore/service/ArchiveService.java b/backend/src/main/java/org/booklore/service/ArchiveService.java index c3cd6040c..78000be22 100644 --- a/backend/src/main/java/org/booklore/service/ArchiveService.java +++ b/backend/src/main/java/org/booklore/service/ArchiveService.java @@ -16,9 +16,11 @@ import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; @@ -71,6 +73,7 @@ public class ArchiveService { private Stream streamEntriesFrom7z(Path path) throws IOException { try (var sevenZFile = new SevenZFile.Builder().setPath(path).get()) { return StreamSupport.stream(sevenZFile.getEntries().spliterator(), false) + .filter(e -> !e.isDirectory()) .map(entry -> new Entry(entry.getName(), entry.getSize())) .toList() .stream(); @@ -247,7 +250,7 @@ public class ArchiveService { } } - public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException { + public void extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException { ReentrantLock lock = getFileLock(path); lock.lock(); @@ -255,7 +258,7 @@ public class ArchiveService { try (OutputStream outputStream = Files.newOutputStream(outputPath, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { hasCreatedFile = true; - return transferEntryTo(path, entryName, outputStream); + transferEntryTo(path, entryName, outputStream); } catch (Exception e) { if (hasCreatedFile) { try { @@ -270,4 +273,36 @@ public class ArchiveService { lock.unlock(); } } + + public List extractToDirectory(Path path, Path outputPath) throws IOException { + return extractToDirectory(path, outputPath, null); + } + + public List extractToDirectory(Path path, Path outputPath, Predicate predicate) throws IOException { + List extractedPaths = new ArrayList<>(); + + for (var entry : getEntries(path)) { + if (predicate != null && !predicate.test(entry)) { + continue; + } + + Path entryPath = outputPath.resolve(entry.name).normalize(); + if (!entryPath.startsWith(outputPath)) { + log.warn("Archive entry outside target directory: {}", entry.name); + throw new IOException("Archive entry outside target directory"); + } + + if (Files.exists(entryPath)) { + log.warn("Entry already exists, skipping: {}", entry.name); + continue; + } + + Files.createDirectories(entryPath.getParent()); + extractEntryToPath(path, entry.name, entryPath); + + extractedPaths.add(entryPath); + } + + return extractedPaths; + } } diff --git a/backend/src/main/java/org/booklore/service/kobo/CbxConversionService.java b/backend/src/main/java/org/booklore/service/kobo/CbxConversionService.java index ed04e0d74..b6f70dcf7 100644 --- a/backend/src/main/java/org/booklore/service/kobo/CbxConversionService.java +++ b/backend/src/main/java/org/booklore/service/kobo/CbxConversionService.java @@ -185,42 +185,28 @@ public class CbxConversionService { } private List extractImagesFromCbx(File cbxFile, Path extractedImagesDir) throws IOException { - List imagePaths = new ArrayList<>(); + var imagePaths = archiveService.extractToDirectory( + cbxFile.toPath(), + extractedImagesDir, + (entry) -> { + if (!isImageFile(entry.name())) { + return false; + } - for (ArchiveService.Entry entry : archiveService.getEntries(cbxFile.toPath())) { - if (!isImageFile(entry.name())) { - continue; - } + if (entry.size() > MAX_IMAGE_SIZE_BYTES) { + log.warn("Image too large, skipping: {} ({})", entry.name(), entry.size()); + return false; + } - validateImageSize(entry.name(), entry.size()); - - try { - Path outputPath = extractedImagesDir.resolve(extractFileName(entry.name())); - - archiveService.extractEntryToPath(cbxFile.toPath(), entry.name(), outputPath); - - imagePaths.add(outputPath); - } catch (Exception e) { - log.warn("Error extracting image {}: {}", entry.name(), e.getMessage()); - } - } + return true; + } + ); log.debug("Found {} image entries in CBR file", imagePaths.size()); imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase())); return imagePaths; } - private String extractFileName(String entryPath) { - return Path.of(entryPath).getFileName().toString(); - } - - private void validateImageSize(String imageName, long size) throws IOException { - if (size > MAX_IMAGE_SIZE_BYTES) { - throw new IOException(String.format("Image '%s' exceeds maximum size limit: %d bytes (max: %d bytes)", - imageName, size, MAX_IMAGE_SIZE_BYTES)); - } - } - private boolean isImageFile(String fileName) { if (shouldIgnoreEntry(fileName)) { return false; diff --git a/backend/src/main/java/org/booklore/service/kobo/KoboSpanMapExtractionService.java b/backend/src/main/java/org/booklore/service/kobo/KoboSpanMapExtractionService.java index ee3674a61..773afbdc5 100644 --- a/backend/src/main/java/org/booklore/service/kobo/KoboSpanMapExtractionService.java +++ b/backend/src/main/java/org/booklore/service/kobo/KoboSpanMapExtractionService.java @@ -3,6 +3,7 @@ package org.booklore.service.kobo; import lombok.extern.slf4j.Slf4j; import org.booklore.model.dto.kobo.KoboSpanPositionMap; import org.booklore.util.SecureXmlUtils; +import org.booklore.util.epub.EpubContentReader; import org.jsoup.Jsoup; import org.jsoup.parser.Parser; import org.springframework.stereotype.Service; @@ -95,21 +96,14 @@ public class KoboSpanMapExtractionService { } private String readOpfPath(ZipFile zipFile) throws Exception { - org.w3c.dom.Document containerDocument = parseXmlEntry(zipFile, CONTAINER_PATH); - NodeList rootfiles = containerDocument.getElementsByTagNameNS(CONTAINER_NS, "rootfile"); - if (rootfiles.getLength() == 0) { - rootfiles = containerDocument.getElementsByTagName("rootfile"); - } - if (rootfiles.getLength() == 0) { - throw new IOException("No rootfile found in container.xml"); + ZipEntry zipEntry = findEntry(zipFile, CONTAINER_PATH); + if (zipEntry == null) { + throw new IOException("Entry not found in archive: " + CONTAINER_PATH); } - Element rootfile = (Element) rootfiles.item(0); - String fullPath = rootfile.getAttribute("full-path"); - if (fullPath == null || fullPath.isEmpty()) { - throw new IOException("No full-path attribute found in container.xml"); + try (InputStream inputStream = zipFile.getInputStream(zipEntry)) { + return EpubContentReader.getOPFHref(inputStream); } - return fullPath; } private org.w3c.dom.Document parseXmlEntry(ZipFile zipFile, String entryName) throws Exception { diff --git a/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java b/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java index 73184d440..a46bfa3fe 100644 --- a/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -12,6 +12,8 @@ import org.booklore.service.ArchiveService; import org.booklore.service.appsettings.AppSettingService; import org.booklore.util.MimeDetector; import org.booklore.util.SecureXmlUtils; +import org.booklore.util.epub.EpubContentReader; +import org.booklore.util.epub.EpubContentWriter; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.w3c.dom.Document; @@ -35,7 +37,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UncheckedIOException; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -45,9 +46,6 @@ import java.nio.file.StandardCopyOption; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; -import java.util.zip.CRC32; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; import java.util.function.Predicate; @Slf4j @@ -76,16 +74,12 @@ public class EpubMetadataWriter implements MetadataWriter { Path tempDir = null; try { tempDir = Files.createTempDirectory("epub_edit_" + UUID.randomUUID()); - extractZipToDirectory(epubFile, tempDir); + archiveService.extractToDirectory(epubFile.toPath(), tempDir); - File opfFile = findOpfFile(tempDir.toFile()); - if (opfFile == null) { - log.warn("Could not locate OPF file in EPUB"); - return; - } + Path opfPath = findOpfPath(tempDir); DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); - Document opfDoc = builder.parse(opfFile); + Document opfDoc = builder.parse(opfPath.toFile()); Element metadataElement = getOrCreateMetadataElement(opfDoc); final String DC_NS = "http://purl.org/dc/elements/1.1/"; @@ -243,10 +237,10 @@ public class EpubMetadataWriter implements MetadataWriter { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile)); + transformer.transform(new DOMSource(opfDoc), new StreamResult(opfPath.toFile())); File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp"); - createEpubZipFromDirectory(tempDir, tempEpub.toPath()); + EpubContentWriter.createEpubFromDirectory(tempDir, tempEpub.toPath()); if (!epubFile.delete()) throw new IOException("Could not delete original EPUB"); if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB"); @@ -447,16 +441,12 @@ public class EpubMetadataWriter implements MetadataWriter { File epubFile = new File(bookEntity.getFullFilePath().toUri()); tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID()); - extractZipToDirectory(epubFile, tempDir); + archiveService.extractToDirectory(epubFile.toPath(), tempDir); - File opfFile = findOpfFile(tempDir.toFile()); - if (opfFile == null) { - log.warn("OPF file not found in EPUB: {}", epubFile.getName()); - return; - } + Path opfPath = findOpfPath(tempDir); DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); - Document opfDoc = builder.parse(opfFile); + Document opfDoc = builder.parse(opfPath.toFile()); applyCoverImageToEpub(tempDir, opfDoc, coverData); @@ -465,10 +455,10 @@ public class EpubMetadataWriter implements MetadataWriter { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile)); + transformer.transform(new DOMSource(opfDoc), new StreamResult(opfPath.toFile())); File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp"); - createEpubZipFromDirectory(tempDir, tempEpub.toPath()); + EpubContentWriter.createEpubFromDirectory(tempDir, tempEpub.toPath()); if (!epubFile.delete()) throw new IOException("Could not delete original EPUB"); if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB"); @@ -658,36 +648,7 @@ public class EpubMetadataWriter implements MetadataWriter { } private Path findOpfPath(Path tempDir) throws IOException, ParserConfigurationException, SAXException { - Path containerXml = tempDir.resolve("META-INF/container.xml"); - if (!Files.exists(containerXml)) { - throw new IOException("container.xml not found at expected location: " + containerXml); - } - - DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(false); - Document containerDoc = builder.parse(containerXml.toFile()); - Node rootfile = containerDoc.getElementsByTagName("rootfile").item(0); - if (rootfile == null) { - throw new IOException("No found in container.xml"); - } - - String opfPath = ((Element) rootfile).getAttribute("full-path"); - if (opfPath.isBlank()) { - throw new IOException("Missing or empty 'full-path' attribute in "); - } - - return tempDir.resolve(opfPath).normalize(); - } - - private File findOpfFile(File rootDir) { - File[] matches = rootDir.listFiles(path -> path.isFile() && path.getName().endsWith(".opf")); - if (matches != null && matches.length > 0) return matches[0]; - for (File file : Objects.requireNonNull(rootDir.listFiles())) { - if (file.isDirectory()) { - File child = findOpfFile(file); - if (child != null) return child; - } - } - return null; + return EpubContentReader.findOPFInExtractedEpub(tempDir); } private byte[] loadImage(String pathOrUrl) { @@ -699,73 +660,6 @@ public class EpubMetadataWriter implements MetadataWriter { } } - private void extractZipToDirectory(File zipSource, Path targetDir) throws IOException { - Path zipPath = zipSource.toPath(); - - if (!Files.isRegularFile(zipPath) || !Files.isReadable(zipPath)) { - throw new IOException("Target is not a readable regular file."); - } - - for (var name : archiveService.getEntryNames(zipPath)) { - Path entryPath = targetDir.resolve(name).normalize(); - if (!entryPath.startsWith(targetDir)) { - throw new IOException("ZIP entry outside target directory: " + name); - } - - if (Files.exists(entryPath)) { - log.warn("EPUB Entry already exists, skipping: {}", entryPath); - continue; - } - - Files.createDirectories(entryPath.getParent()); - archiveService.extractEntryToPath(zipPath, name, entryPath); - } - } - - private void createEpubZipFromDirectory(Path sourceDir, Path targetZip) throws IOException { - try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) { - // EPUB spec requires mimetype to be the first entry in the ZIP, uncompressed (STORED) - Path mimetypeFile = sourceDir.resolve("mimetype"); - if (Files.exists(mimetypeFile)) { - byte[] mimetypeData = Files.readAllBytes(mimetypeFile); - ZipEntry mimetypeEntry = new ZipEntry("mimetype"); - mimetypeEntry.setMethod(ZipEntry.STORED); - mimetypeEntry.setSize(mimetypeData.length); - mimetypeEntry.setCompressedSize(mimetypeData.length); - CRC32 crc = new CRC32(); - crc.update(mimetypeData); - mimetypeEntry.setCrc(crc.getValue()); - zos.putNextEntry(mimetypeEntry); - zos.write(mimetypeData); - zos.closeEntry(); - } else { - log.warn("EPUB mimetype file not found in extracted directory — output may be spec-invalid"); - } - - try (var pathStream = Files.walk(sourceDir)) { - pathStream - .filter(path -> !path.equals(sourceDir)) - .filter(path -> !path.equals(mimetypeFile)) - .sorted() - .forEach(path -> { - try { - String relativePath = sourceDir.relativize(path).toString().replace(File.separatorChar, '/'); - if (Files.isDirectory(path)) { - zos.putNextEntry(new ZipEntry(relativePath + "/")); - zos.closeEntry(); - } else { - zos.putNextEntry(new ZipEntry(relativePath)); - Files.copy(path, zos); - zos.closeEntry(); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }); - } - } - } - private void removeMetaByName(Element metadataElement, String name) { NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta"); for (int i = metas.getLength() - 1; i >= 0; i--) { diff --git a/backend/src/main/java/org/booklore/util/epub/EpubContentReader.java b/backend/src/main/java/org/booklore/util/epub/EpubContentReader.java index 9fa540ff7..5d8f93070 100644 --- a/backend/src/main/java/org/booklore/util/epub/EpubContentReader.java +++ b/backend/src/main/java/org/booklore/util/epub/EpubContentReader.java @@ -1,5 +1,6 @@ package org.booklore.util.epub; +import org.booklore.util.SecureXmlUtils; import org.grimmory.epub4j.domain.Book; import org.grimmory.epub4j.domain.MediaType; import org.grimmory.epub4j.domain.MediaTypes; @@ -7,11 +8,21 @@ import org.grimmory.epub4j.domain.Resource; import org.grimmory.epub4j.domain.Spine; import org.grimmory.epub4j.epub.EpubReader; import lombok.extern.slf4j.Slf4j; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; @@ -19,6 +30,7 @@ import java.util.List; @Slf4j public class EpubContentReader { + private static final String CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container"; private static final List MEDIA_TYPES = new ArrayList<>(); static { @@ -107,6 +119,52 @@ public class EpubContentReader { return hrefs; } + public static Path findOPFInExtractedEpub(Path path) throws IOException { + Path containerXml = path.resolve("META-INF/container.xml"); + if (!Files.exists(containerXml)) { + throw new IOException("container.xml not found at expected location: " + containerXml); + } + + String opfHref; + try (var is = Files.newInputStream(containerXml)) { + opfHref = getOPFHref(is); + } + + Path opfPath = path.resolve(opfHref).normalize(); + + if (!opfPath.startsWith(path)) { + throw new IOException("OPF Path is outside of extracted root"); + } + + return opfPath; + } + + public static String getOPFHref(InputStream xmlInputStream) throws IOException { + Document containerDoc; + try { + DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); + containerDoc = builder.parse(xmlInputStream); + } catch (SAXException | ParserConfigurationException e) { + throw new IOException("Unable to parse container.xml", e); + } + + Node rootfile = containerDoc.getElementsByTagNameNS(CONTAINER_NS, "rootfile").item(0); + if (rootfile == null) { + throw new IOException("No found in container.xml"); + } + + String opfPathAttribute = ((Element) rootfile).getAttribute("full-path"); + if (opfPathAttribute.isBlank()) { + throw new IOException("Missing or empty 'full-path' attribute in "); + } + + // The `full-path` attribute may be percent encoded. + opfPathAttribute = opfPathAttribute.replaceAll("\\+", "%2b"); + opfPathAttribute = URLDecoder.decode(opfPathAttribute, StandardCharsets.UTF_8); + + return opfPathAttribute; + } + public static class EpubReadException extends RuntimeException { public EpubReadException(String message) { super(message); diff --git a/backend/src/main/java/org/booklore/util/epub/EpubContentWriter.java b/backend/src/main/java/org/booklore/util/epub/EpubContentWriter.java new file mode 100644 index 000000000..dde93a6a1 --- /dev/null +++ b/backend/src/main/java/org/booklore/util/epub/EpubContentWriter.java @@ -0,0 +1,60 @@ +package org.booklore.util.epub; + +import lombok.extern.slf4j.Slf4j; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +@Slf4j +public class EpubContentWriter { + private static final String MIMETYPE_VALUE = "application/epub+zip"; + + public static void createEpubFromDirectory(Path sourceDir, Path targetZip) throws IOException { + try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) { + // EPUB spec requires mimetype to be the first entry in the ZIP, uncompressed (STORED) + byte[] mimetypeData = MIMETYPE_VALUE.getBytes(StandardCharsets.UTF_8); + ZipEntry mimetypeEntry = new ZipEntry("mimetype"); + mimetypeEntry.setMethod(ZipEntry.STORED); + mimetypeEntry.setSize(mimetypeData.length); + mimetypeEntry.setCompressedSize(mimetypeData.length); + CRC32 crc = new CRC32(); + crc.update(mimetypeData); + mimetypeEntry.setCrc(crc.getValue()); + zos.putNextEntry(mimetypeEntry); + zos.write(mimetypeData); + zos.closeEntry(); + + Path mimetypeFile = sourceDir.resolve("mimetype"); + + try (var pathStream = Files.walk(sourceDir)) { + pathStream + .filter(path -> !path.equals(sourceDir)) + .filter(path -> !path.equals(mimetypeFile)) + .sorted() + .forEach(path -> { + try { + String relativePath = sourceDir.relativize(path).toString().replace(File.separatorChar, '/'); + if (Files.isDirectory(path)) { + zos.putNextEntry(new ZipEntry(relativePath + "/")); + zos.closeEntry(); + } else { + zos.putNextEntry(new ZipEntry(relativePath)); + Files.copy(path, zos); + zos.closeEntry(); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + } + } + +}