#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Validate page counts on load and visit shared PDF objects once (#8689)
ConnorYoh465054ba4c78
diff --git a/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.java b/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.javaindex 9a7caefc7d..94f3dc9c5e 100644--- a/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.java+++ b/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.java@@ -6,8 +6,13 @@ import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;+import java.util.ArrayDeque;import java.util.ArrayList;+import java.util.Collections;+import java.util.Deque;+import java.util.IdentityHashMap;import java.util.List;+import java.util.Set;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;@@ -17,6 +22,10 @@ import java.util.concurrent.Semaphore;import java.util.function.Consumer;import org.apache.pdfbox.Loader;+import org.apache.pdfbox.cos.COSArray;+import org.apache.pdfbox.cos.COSBase;+import org.apache.pdfbox.cos.COSDictionary;+import org.apache.pdfbox.cos.COSName;import org.apache.pdfbox.io.IOUtils;import org.apache.pdfbox.io.MemoryUsageSetting;import org.apache.pdfbox.io.RandomAccessReadBufferedFile;@@ -687,6 +696,7 @@ public class CustomPDFDocumentFactory {}private PDDocument maybePostProcess(PDDocument doc, boolean readOnly) throws IOException {+ correctInflatedPageCount(doc);if (!readOnly) {pdfMetadataService.setDefaultMetadata(doc);removePassword(doc);@@ -694,6 +704,77 @@ public class CustomPDFDocumentFactory {return doc;}+ /**+ * Lowers the root /Count to the pages the tree holds when the file declares more. {@code+ * getNumberOfPages()} returns the root /Count as written, and tools size page lists and+ * per-page loops from it. Damaged files often overstate it, so the count is corrected rather+ * than the document refused.+ */+ static void correctInflatedPageCount(PDDocument doc) {+ COSDictionary root =+ doc.getDocumentCatalog().getCOSObject().getCOSDictionary(COSName.PAGES);+ if (root == null) {+ return;+ }+ int declared = root.getInt(COSName.COUNT, 0);+ if (declared <= 0) {+ return;+ }+ long actual = countPages(root, declared);+ if (actual < declared) {+ log.warn(+ "Page tree declares {} pages but holds {}; using {}", declared, actual, actual);+ root.setInt(COSName.COUNT, (int) actual);+ }+ }++ /**+ * Counts leaf pages the way {@code PDPageTree.get} resolves them, visiting each intermediate+ * node once, and stops as soon as {@code stopAt} is reached.+ */+ private static long countPages(COSDictionary root, long stopAt) {+ Set<COSDictionary> visitedNodes = Collections.newSetFromMap(new IdentityHashMap<>());+ Deque<COSDictionary> pending = new ArrayDeque<>();+ pending.push(root);+ long pages = 0;+ while (!pending.isEmpty()) {+ COSDictionary node = pending.pop();+ boolean isTreeNode =+ COSName.PAGES.equals(node.getCOSName(COSName.TYPE))+ || node.containsKey(COSName.KIDS);+ if (!isTreeNode) {+ // get() gives an untyped leaf /Type /Page but throws on any other type+ COSName type = node.getCOSName(COSName.TYPE);+ if (type != null && !COSName.PAGE.equals(type)) {+ continue;+ }+ if (++pages >= stopAt) {+ return pages;+ }+ continue;+ }+ if (!visitedNodes.add(node)) {+ continue;+ }+ COSArray kids = node.getCOSArray(COSName.KIDS);+ if (kids == null) {+ continue;+ }+ for (int i = kids.size() - 1; i >= 0; i--) {+ COSBase kid = kids.getObject(i);+ if (kid instanceof COSDictionary dictionary) {+ pending.push(dictionary);+ } else if (kid == null) {+ // PDPageTree.getKids puts an empty page in place of a null entry+ if (++pages >= stopAt) {+ return pages;+ }+ }+ }+ }+ return pages;+ }+private static void removePassword(PDDocument document) throws IOException {if (document.isEncrypted()) {try {diff --git a/app/common/src/main/java/stirling/software/common/util/FormUtils.java b/app/common/src/main/java/stirling/software/common/util/FormUtils.javaindex 5fece36921..9585489af1 100644--- a/app/common/src/main/java/stirling/software/common/util/FormUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/FormUtils.java@@ -3217,7 +3217,10 @@ public class FormUtils {}if (acroForm != null) {- pruneFieldReferences(acroForm.getFields(), field);+ pruneFieldReferences(+ acroForm.getFields(),+ field,+ Collections.newSetFromMap(new IdentityHashMap<>()));try {COSArray fieldsArray = acroForm.getCOSObject().getCOSArray(COSName.FIELDS);@@ -3248,16 +3251,19 @@ public class FormUtils {}}- private void pruneFieldReferences(List<PDField> fields, PDField target) {+ // /Kids can list a field more than once or point back at an ancestor; walk each one once+ private void pruneFieldReferences(+ List<PDField> fields, PDField target, Set<COSDictionary> visited) {if (fields == null || fields.isEmpty() || target == null) return;fields.removeIf(existing -> isSameFieldReference(existing, target));for (PDField existing : List.copyOf(fields)) {- if (existing instanceof PDNonTerminalField nonTerminal) {+ if (existing instanceof PDNonTerminalField nonTerminal+ && visited.add(nonTerminal.getCOSObject())) {List<PDField> children = nonTerminal.getChildren();if (children != null && !children.isEmpty()) {- pruneFieldReferences(children, target);+ pruneFieldReferences(children, target, visited);}}}@@ -3764,7 +3770,9 @@ public class FormUtils {}Set<COSDictionary> liveWidgets = collectLiveWidgetDictionaries(document);- List<PDField> kept = pruneFieldList(fields, liveWidgets);+ List<PDField> kept =+ pruneFieldList(+ fields, liveWidgets, Collections.newSetFromMap(new IdentityHashMap<>()));if (kept.isEmpty()) {catalog.setAcroForm(null);} else if (kept.size() != fields.size()) {@@ -3789,12 +3797,17 @@ public class FormUtils {return live;}- private List<PDField> pruneFieldList(List<PDField> fields, Set<COSDictionary> liveWidgets) {+ private List<PDField> pruneFieldList(+ List<PDField> fields, Set<COSDictionary> liveWidgets, Set<COSDictionary> visited) {List<PDField> kept = new ArrayList<>(fields.size());for (PDField field : fields) {+ // A repeated /Kids entry or a cycle: the field was already handled, so drop the copy+ if (!visited.add(field.getCOSObject())) {+ continue;+ }if (field instanceof PDNonTerminalField nonTerminal) {List<PDField> children = nonTerminal.getChildren();- List<PDField> remaining = pruneFieldList(children, liveWidgets);+ List<PDField> remaining = pruneFieldList(children, liveWidgets, visited);if (remaining.isEmpty()) {continue;}diff --git a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfUtils.javaindex 3305e176e1..5206c59b38 100644--- a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java@@ -7,9 +7,12 @@ import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;+import java.util.Collections;import java.util.HashMap;+import java.util.IdentityHashMap;import java.util.List;import java.util.Locale;+import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.zip.ZipEntry;@@ -19,6 +22,7 @@ import javax.imageio.*;import javax.imageio.stream.ImageInputStream;import javax.imageio.stream.ImageOutputStream;+import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.cos.COSName;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;@@ -71,21 +75,48 @@ public class PdfUtils {};}+ /**+ * Collects the images reachable from {@code resources}, searching each resources dictionary+ * once. A form XObject can be named any number of times, so a walk that follows every name+ * grows with the number of paths, not the number of objects.+ */public List<RenderedImage> getAllImages(PDResources resources) throws IOException {List<RenderedImage> images = new ArrayList<>();+ collectImages(resources, images, Collections.newSetFromMap(new IdentityHashMap<>()));+ return images;+ }+ private void collectImages(+ PDResources resources, List<RenderedImage> images, Set<COSDictionary> visited)+ throws IOException {+ if (resources == null || !visited.add(resources.getCOSObject())) {+ return;+ }for (COSName name : resources.getXObjectNames()) {PDXObject object = resources.getXObject(name);-- if (object instanceof PDImageXObject) {- images.add(((PDImageXObject) object).getImage());-- } else if (object instanceof PDFormXObject) {- images.addAll(getAllImages(((PDFormXObject) object).getResources()));+ if (object instanceof PDImageXObject image) {+ images.add(image.getImage());+ } else if (object instanceof PDFormXObject form) {+ collectImages(form.getResources(), images, visited);}}+ }- return images;+ private boolean containsImage(PDResources resources, Set<COSDictionary> visited)+ throws IOException {+ if (resources == null || !visited.add(resources.getCOSObject())) {+ return false;+ }+ for (COSName name : resources.getXObjectNames()) {+ if (resources.isImageXObject(name)) {+ return true;+ }+ if (resources.getXObject(name) instanceof PDFormXObject form+ && containsImage(form.getResources(), visited)) {+ return true;+ }+ }+ return false;}public boolean hasImages(PDDocument document, String pagesToCheck) throws IOException {@@ -120,7 +151,8 @@ public class PdfUtils {}public boolean hasImagesOnPage(PDPage page) throws IOException {- return !getAllImages(page.getResources()).isEmpty();+ return containsImage(+ page.getResources(), Collections.newSetFromMap(new IdentityHashMap<>()));}public boolean hasTextOnPage(PDPage page, String phrase) throws IOException {diff --git a/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryPageTreeTest.java b/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryPageTreeTest.javanew file mode 100644index 0000000000..165031d0bc--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryPageTreeTest.java@@ -0,0 +1,172 @@+package stirling.software.common.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatCode;+import static org.mockito.Mockito.mock;++import java.io.ByteArrayOutputStream;++import org.apache.pdfbox.cos.COSArray;+import org.apache.pdfbox.cos.COSDictionary;+import org.apache.pdfbox.cos.COSName;+import org.apache.pdfbox.cos.COSNull;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.junit.jupiter.api.Test;++class CustomPDFDocumentFactoryPageTreeTest {++ private static PDDocument withPages(int pages) {+ PDDocument document = new PDDocument();+ for (int i = 0; i < pages; i++) {+ document.addPage(new PDPage());+ }+ return document;+ }++ private static COSDictionary root(PDDocument document) {+ return document.getDocumentCatalog().getCOSObject().getCOSDictionary(COSName.PAGES);+ }++ private static int iteratedPages(PDDocument document) {+ int pages = 0;+ for (PDPage ignored : document.getPages()) {+ pages++;+ }+ return pages;+ }++ @Test+ void keepsACountTheTreeHolds() throws Exception {+ try (PDDocument document = withPages(3)) {+ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(3);+ }+ }++ @Test+ void leavesADeclaredCountBelowTheRealOne() throws Exception {+ try (PDDocument document = withPages(3)) {+ root(document).setInt(COSName.COUNT, 2);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(2);+ }+ }++ @Test+ void lowersACountAboveWhatTheTreeHolds() throws Exception {+ try (PDDocument document = withPages(1)) {+ root(document).setInt(COSName.COUNT, 1000);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(1);+ assertThatCode(() -> document.getPage(0)).doesNotThrowAnyException();+ }+ }++ @Test+ void countsAnIntermediateNodeListedTwiceOnce() throws Exception {+ try (PDDocument document = withPages(1)) {+ COSDictionary root = root(document);+ COSDictionary page = (COSDictionary) root.getCOSArray(COSName.KIDS).getObject(0);+ COSDictionary node = new COSDictionary();+ node.setItem(COSName.TYPE, COSName.PAGES);+ COSArray nodeKids = new COSArray();+ nodeKids.add(page);+ node.setItem(COSName.KIDS, nodeKids);+ node.setInt(COSName.COUNT, 1);+ COSArray rootKids = new COSArray();+ rootKids.add(node);+ rootKids.add(node);+ root.setItem(COSName.KIDS, rootKids);+ root.setInt(COSName.COUNT, 2);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(iteratedPages(document)).isOne();+ }+ }++ @Test+ void leavesANonPageLeafOutOfTheCount() throws Exception {+ try (PDDocument document = withPages(1)) {+ COSDictionary root = root(document);+ COSDictionary annotation = new COSDictionary();+ annotation.setItem(COSName.TYPE, COSName.ANNOT);+ root.getCOSArray(COSName.KIDS).add(annotation);+ root.setInt(COSName.COUNT, 2);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isOne();+ }+ }++ @Test+ void countsAnUntypedLeafAsAPage() throws Exception {+ try (PDDocument document = withPages(1)) {+ COSDictionary root = root(document);+ COSDictionary untyped = new COSDictionary();+ untyped.setItem(COSName.MEDIA_BOX, new PDPage().getMediaBox().getCOSArray());+ root.getCOSArray(COSName.KIDS).add(untyped);+ root.setInt(COSName.COUNT, 2);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(2);+ assertThatCode(() -> document.getPage(1)).doesNotThrowAnyException();+ }+ }++ @Test+ void countsANullEntryAsThePagePdfBoxPutsInItsPlace() throws Exception {+ try (PDDocument document = withPages(1)) {+ COSDictionary root = root(document);+ COSArray kids = root.getCOSArray(COSName.KIDS);+ COSDictionary realPage = (COSDictionary) kids.getObject(0);+ COSArray withNullFirst = new COSArray();+ withNullFirst.add(COSNull.NULL);+ withNullFirst.add(realPage);+ root.setItem(COSName.KIDS, withNullFirst);+ root.setInt(COSName.COUNT, 2);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(2);+ assertThat(document.getPage(1).getCOSObject()).isSameAs(realPage);+ }+ }++ @Test+ void keepsALeafListedTwiceWhenTheCountAgrees() throws Exception {+ try (PDDocument document = withPages(1)) {+ COSDictionary root = root(document);+ COSArray kids = root.getCOSArray(COSName.KIDS);+ kids.add(kids.getObject(0));+ root.setInt(COSName.COUNT, 2);++ CustomPDFDocumentFactory.correctInflatedPageCount(document);++ assertThat(document.getNumberOfPages()).isEqualTo(2);+ }+ }++ @Test+ void loadingCorrectsTheCount() throws Exception {+ ByteArrayOutputStream saved = new ByteArrayOutputStream();+ try (PDDocument document = withPages(2)) {+ root(document).setInt(COSName.COUNT, 50_000);+ document.save(saved);+ }+ CustomPDFDocumentFactory factory =+ new CustomPDFDocumentFactory(mock(PdfMetadataService.class));++ try (PDDocument loaded = factory.load(saved.toByteArray(), true)) {+ assertThat(loaded.getNumberOfPages()).isEqualTo(2);+ }+ }+}diff --git a/app/common/src/test/java/stirling/software/common/util/SharedReferenceWalkTest.java b/app/common/src/test/java/stirling/software/common/util/SharedReferenceWalkTest.javanew file mode 100644index 0000000000..209f9bf63e--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/SharedReferenceWalkTest.java@@ -0,0 +1,118 @@+package stirling.software.common.util;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;++import java.awt.image.BufferedImage;+import java.time.Duration;+import java.util.List;++import org.apache.pdfbox.cos.COSArray;+import org.apache.pdfbox.cos.COSName;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.PDResources;+import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;+import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;+import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;+import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;+import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;+import org.junit.jupiter.api.Test;++/** Walkers over PDF object graphs must visit a shared or cyclic object once. */+class SharedReferenceWalkTest {++ private static final Duration LIMIT = Duration.ofSeconds(10);++ private static PDFormXObject form(PDDocument document) {+ PDFormXObject form = new PDFormXObject(document);+ form.setResources(new PDResources());+ return form;+ }++ @Test+ void imagesUnderAFormNamedManyTimesAreFoundOnce() throws Exception {+ try (PDDocument document = new PDDocument()) {+ PDImageXObject image =+ LosslessFactory.createFromImage(+ document, new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB));+ PDFormXObject inner = form(document);+ inner.getResources().put(COSName.getPDFName("Im"), image);+ PDFormXObject outer = form(document);+ for (int i = 0; i < 4; i++) {+ outer.getResources().put(COSName.getPDFName("F" + i), inner);+ }+ PDPage page = new PDPage();+ page.setResources(new PDResources());+ for (int i = 0; i < 4; i++) {+ page.getResources().put(COSName.getPDFName("F" + i), outer);+ }+ document.addPage(page);++ assertThat(PdfUtils.getAllImages(page.getResources())).hasSize(1);+ assertThat(PdfUtils.hasImagesOnPage(page)).isTrue();+ }+ }++ @Test+ void aFormThatNamesItselfIsSearchedOnce() throws Exception {+ try (PDDocument document = new PDDocument()) {+ PDFormXObject self = form(document);+ self.getResources().put(COSName.getPDFName("Self"), self);+ PDPage page = new PDPage();+ page.setResources(new PDResources());+ page.getResources().put(COSName.getPDFName("F"), self);+ document.addPage(page);++ assertTimeoutPreemptively(+ LIMIT,+ () -> {+ assertThat(PdfUtils.getAllImages(page.getResources())).isEmpty();+ assertThat(PdfUtils.hasImagesOnPage(page)).isFalse();+ });+ }+ }++ @Test+ void aFormWithoutResourcesIsSkipped() throws Exception {+ try (PDDocument document = new PDDocument()) {+ PDFormXObject bare = new PDFormXObject(document);+ PDPage page = new PDPage();+ page.setResources(new PDResources());+ page.getResources().put(COSName.getPDFName("F"), bare);+ document.addPage(page);++ assertThat(PdfUtils.getAllImages(page.getResources())).isEmpty();+ assertThat(PdfUtils.hasImagesOnPage(page)).isFalse();+ }+ }++ @Test+ void pruningDropsRepeatedAndCyclicFieldKids() throws Exception {+ try (PDDocument document = new PDDocument()) {+ PDPage page = new PDPage();+ document.addPage(page);+ PDAcroForm acroForm = new PDAcroForm(document);+ document.getDocumentCatalog().setAcroForm(acroForm);++ PDNonTerminalField parent = new PDNonTerminalField(acroForm);+ parent.setPartialName("parent");+ PDTextField child = new PDTextField(acroForm);+ child.setPartialName("child");+ child.getWidgets().get(0).setPage(page);+ page.setAnnotations(List.of(child.getWidgets().get(0)));+ parent.setChildren(List.of(child));+ COSArray kids = parent.getCOSObject().getCOSArray(COSName.KIDS);+ kids.add(child.getCOSObject());+ kids.add(parent.getCOSObject());+ acroForm.setFields(List.of(parent));++ assertTimeoutPreemptively(LIMIT, () -> FormUtils.pruneOrphanedFormFields(document));++ COSArray remaining = parent.getCOSObject().getCOSArray(COSName.KIDS);+ assertThat(remaining.size()).isEqualTo(1);+ assertThat(remaining.getObject(0)).isSameAs(child.getCOSObject());+ }+ }+}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTableOfContentsController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTableOfContentsController.javaindex 0cd187f2ec..5b776df9ff 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTableOfContentsController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTableOfContentsController.java@@ -1,14 +1,19 @@package stirling.software.SPDF.controller.api;import java.util.ArrayList;+import java.util.Collections;import java.util.HashMap;+import java.util.IdentityHashMap;import java.util.List;import java.util.Map;+import java.util.Set;+import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;+import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode;import org.springframework.core.io.Resource;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;@@ -41,6 +46,8 @@ import tools.jackson.databind.ObjectMapper;@RequiredArgsConstructorpublic class EditTableOfContentsController {+ private static final int MAX_OUTLINE_DEPTH = 64;+private final CustomPDFDocumentFactory pdfDocumentFactory;private final ObjectMapper objectMapper;private final TempFileManager tempFileManager;@@ -70,84 +77,36 @@ public class EditTableOfContentsController {private List<Map<String, Object>> extractBookmarkItems(PDDocument document, PDDocumentOutline outline) throws Exception {- List<Map<String, Object>> bookmarks = new ArrayList<>();- PDOutlineItem current = outline.getFirstChild();-- while (current != null) {- Map<String, Object> bookmark = new HashMap<>();-- // Get bookmark title- String title = current.getTitle();- bookmark.put("title", title);-- // Get page number (1-based for UI purposes)- PDPage page = current.findDestinationPage(document);- if (page != null) {- int pageIndex = document.getPages().indexOf(page);- bookmark.put("pageNumber", pageIndex + 1);- } else {- bookmark.put("pageNumber", 1);- }-- // Process children if any- PDOutlineItem child = current.getFirstChild();- if (child != null) {- List<Map<String, Object>> children = new ArrayList<>();-- while (child != null) {- // Recursively process child items- Map<String, Object> childBookmark = processChild(document, child);- children.add(childBookmark);- child = child.getNextSibling();- }-- bookmark.put("children", children);- } else {- bookmark.put("children", new ArrayList<>());- }-- bookmarks.add(bookmark);- current = current.getNextSibling();- }-- return bookmarks;+ return processChildren(+ document, outline, Collections.newSetFromMap(new IdentityHashMap<>()), 0);}- private Map<String, Object> processChild(PDDocument document, PDOutlineItem item)+ /**+ * Outline links come from the file and can form cycles through /Next or /First, so each item is+ * emitted once and nesting is capped.+ */+ private List<Map<String, Object>> processChildren(+ PDDocument document, PDOutlineNode parent, Set<COSDictionary> visited, int depth)throws Exception {- Map<String, Object> bookmark = new HashMap<>();-- // Get bookmark title- String title = item.getTitle();- bookmark.put("title", title);-- // Get page number (1-based for UI purposes)- PDPage page = item.findDestinationPage(document);- if (page != null) {- int pageIndex = document.getPages().indexOf(page);- bookmark.put("pageNumber", pageIndex + 1);- } else {- bookmark.put("pageNumber", 1);+ List<Map<String, Object>> children = new ArrayList<>();+ if (depth > MAX_OUTLINE_DEPTH) {+ return children;}-- // Process children if any- PDOutlineItem child = item.getFirstChild();- if (child != null) {- List<Map<String, Object>> children = new ArrayList<>();-- while (child != null) {- // Recursively process child items- Map<String, Object> childBookmark = processChild(document, child);- children.add(childBookmark);- child = child.getNextSibling();+ for (PDOutlineItem item : parent.children()) {+ if (!visited.add(item.getCOSObject())) {+ continue;}+ Map<String, Object> bookmark = new HashMap<>();+ bookmark.put("title", item.getTitle());- bookmark.put("children", children);- } else {- bookmark.put("children", new ArrayList<>());- }+ // 1-based for the UI+ PDPage page = item.findDestinationPage(document);+ bookmark.put("pageNumber", page != null ? document.getPages().indexOf(page) + 1 : 1);- return bookmark;+ bookmark.put("children", processChildren(document, item, visited, depth + 1));+ children.add(bookmark);+ }+ return children;}@AutoJobPostMapping(diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RemoveImagesController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RemoveImagesController.javaindex 44703af863..59045d8775 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RemoveImagesController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RemoveImagesController.java@@ -2,7 +2,10 @@ package stirling.software.SPDF.controller.api.misc;import java.io.IOException;import java.util.ArrayList;+import java.util.Collections;+import java.util.IdentityHashMap;import java.util.List;+import java.util.Set;import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.cos.COSName;@@ -63,10 +66,12 @@ public class RemoveImagesController {int totalPages = pdfDoc.getNumberOfPages();int imagesRemoved = 0;+ // Resources are shared between pages and forms; process each dictionary once+ Set<COSDictionary> visited = Collections.newSetFromMap(new IdentityHashMap<>());for (int pageIndex = 0; pageIndex < totalPages; pageIndex++) {PDPage currentPage = pdfDoc.getPage(pageIndex);- imagesRemoved += removeImagesFromPage(currentPage);+ imagesRemoved += removeImagesFromResources(currentPage.getResources(), visited);}log.info("Removed {} images from PDF with {} pages", imagesRemoved, totalPages);@@ -89,29 +94,9 @@ public class RemoveImagesController {}}- private int removeImagesFromPage(PDPage page) throws IOException {- int imagesRemoved = 0;-- PDResources resources = page.getResources();- if (resources == null) {- return imagesRemoved;- }-- imagesRemoved += removeImagesFromResources(resources);- return imagesRemoved;- }-- private int removeImagesFromFormXObject(PDFormXObject formXObject) throws IOException {- PDResources resources = formXObject.getResources();- if (resources == null) {- return 0;- }-- return removeImagesFromResources(resources);- }-- private int removeImagesFromResources(PDResources resources) throws IOException {- if (resources == null) {+ private int removeImagesFromResources(PDResources resources, Set<COSDictionary> visited)+ throws IOException {+ if (resources == null || !visited.add(resources.getCOSObject())) {return 0;}@@ -139,7 +124,7 @@ public class RemoveImagesController {}// Recursively process nested form XObjectselse if (xObject instanceof PDFormXObject form) {- imagesRemoved += removeImagesFromResources(form.getResources());+ imagesRemoved += removeImagesFromResources(form.getResources(), visited);}} catch (IOException e) {log.warn("Error processing XObject {}: {}", name.getName(), e.getMessage());diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.javaindex 0951bdb84f..72d0c2e60f 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java@@ -9,6 +9,7 @@ import java.time.ZonedDateTime;import java.time.format.DateTimeFormatter;import java.util.*;+import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.cos.COSInputStream;import org.apache.pdfbox.cos.COSName;import org.apache.pdfbox.cos.COSString;@@ -79,24 +80,29 @@ public class GetInfoOnPDF {private static final int MAX_LOGGED_ERRORS = 5;private static final String PAGE_PREFIX = "Page ";private static final long MAX_FILE_SIZE = 100L * 1024 * 1024;+ private static final int MAX_OUTLINE_DEPTH = 64;private static final ObjectMapper objectMapper = JsonMapper.builder().build();private final CustomPDFDocumentFactory pdfDocumentFactory;private final VeraPDFService veraPDFService;- private static void addOutlinesToArray(PDOutlineItem outline, ArrayNode arrayNode) {- if (outline == null) return;+ /**+ * Outline links come from the file and can form cycles through /Next or /First, so each item is+ * emitted once and nesting is capped.+ */+ private static void addOutlinesToArray(+ PDOutlineItem outline, ArrayNode arrayNode, Set<COSDictionary> visited, int depth) {+ if (outline == null || depth > MAX_OUTLINE_DEPTH || !visited.add(outline.getCOSObject())) {+ return;+ }ObjectNode outlineNode = objectMapper.createObjectNode();outlineNode.put("Title", outline.getTitle());- // You can add other properties if neededarrayNode.add(outlineNode);- PDOutlineItem child = outline.getFirstChild();- while (child != null) {- addOutlinesToArray(child, arrayNode);- child = child.getNextSibling();+ for (PDOutlineItem child : outline.children()) {+ addOutlinesToArray(child, arrayNode, visited, depth + 1);}}@@ -219,19 +225,27 @@ public class GetInfoOnPDF {dimensionInfo.put("Height (cm)", String.format(Locale.ROOT, "%.2f", heightInCm));}- private static ArrayNode exploreStructureTree(List<Object> nodes) {+ /**+ * A structure element can be listed under /K many times or be its own ancestor, so each one is+ * expanded once.+ */+ private static ArrayNode exploreStructureTree(List<Object> nodes, Set<COSDictionary> expanded) {ArrayNode elementsArray = objectMapper.createArrayNode();if (nodes != null) {for (Object obj : nodes) {- if (obj instanceof PDStructureNode node) {+ if (obj instanceof PDStructureNode node && expanded.add(node.getCOSObject())) {ObjectNode elementNode = objectMapper.createObjectNode();if (node instanceof PDStructureElement structureElement) {elementNode.put("Type", structureElement.getStructureType());- elementNode.put("Content", getContent(structureElement));-- // Recursively explore child elements- ArrayNode childElements = exploreStructureTree(structureElement.getKids());+ elementNode.put(+ "Content",+ getContent(+ structureElement,+ Collections.newSetFromMap(new IdentityHashMap<>())));++ ArrayNode childElements =+ exploreStructureTree(structureElement.getKids(), expanded);if (!childElements.isEmpty()) {elementNode.set("Children", childElements);}@@ -243,16 +257,18 @@ public class GetInfoOnPDF {return elementsArray;}- private static String getContent(PDStructureElement structureElement) {+ private static String getContent(+ PDStructureElement structureElement, Set<COSDictionary> visited) {StringBuilder contentBuilder = new StringBuilder();+ if (!visited.add(structureElement.getCOSObject())) {+ return "";+ }for (Object item : structureElement.getKids()) {if (item instanceof COSString cosString) {contentBuilder.append(cosString.getString());} else if (item instanceof PDStructureElement pdstructureelement) {- // For simplicity, we're handling only COSString and PDStructureElement here- // but a more comprehensive method would handle other types too- contentBuilder.append(getContent(pdstructureelement));+ contentBuilder.append(getContent(pdstructureelement, visited));}}@@ -582,7 +598,9 @@ public class GetInfoOnPDF {document.getDocumentCatalog().getStructureTreeRoot();if (structureTreeRoot != null) {ArrayNode structureTreeArray =- exploreStructureTree(structureTreeRoot.getKids());+ exploreStructureTree(+ structureTreeRoot.getKids(),+ Collections.newSetFromMap(new IdentityHashMap<>()));other.set("StructureTree", structureTreeArray);}} catch (Exception e) {@@ -737,8 +755,9 @@ public class GetInfoOnPDF {try {PDOutlineNode root = document.getDocumentCatalog().getDocumentOutline();if (root != null) {+ Set<COSDictionary> visited = Collections.newSetFromMap(new IdentityHashMap<>());for (PDOutlineItem child : root.children()) {- addOutlinesToArray(child, bookmarksArray);+ addOutlinesToArray(child, bookmarksArray, visited, 0);}}} catch (Exception e) {diff --git a/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java b/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.javaindex 46ae23ef74..cee144f01f 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/AttachmentService.java@@ -9,9 +9,11 @@ import java.time.Instant;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.ArrayList;+import java.util.Collections;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.HashSet;+import java.util.IdentityHashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;@@ -21,6 +23,7 @@ import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;import org.apache.commons.lang3.StringUtils;+import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDDocumentCatalog;import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;@@ -494,7 +497,16 @@ public class AttachmentService implements AttachmentServiceInterface {PDNameTreeNode<PDComplexFileSpecification> node,Map<String, PDComplexFileSpecification> collector)throws IOException {- if (node == null) {+ collectEmbeddedFiles(node, collector, Collections.newSetFromMap(new IdentityHashMap<>()));+ }++ // A node can be listed in several /Kids arrays or be its own ancestor; visit each one once+ private void collectEmbeddedFiles(+ PDNameTreeNode<PDComplexFileSpecification> node,+ Map<String, PDComplexFileSpecification> collector,+ Set<COSDictionary> visited)+ throws IOException {+ if (node == null || !visited.add(node.getCOSObject())) {return;}@@ -506,7 +518,7 @@ public class AttachmentService implements AttachmentServiceInterface {List<PDNameTreeNode<PDComplexFileSpecification>> kids = node.getKids();if (kids != null) {for (PDNameTreeNode<PDComplexFileSpecification> kid : kids) {- collectEmbeddedFiles(kid, collector);+ collectEmbeddedFiles(kid, collector, visited);}}}diff --git a/app/core/src/test/java/stirling/software/SPDF/SharedReferenceWalkTest.java b/app/core/src/test/java/stirling/software/SPDF/SharedReferenceWalkTest.javanew file mode 100644index 0000000000..b9290b7c5e--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/SharedReferenceWalkTest.java@@ -0,0 +1,155 @@+package stirling.software.SPDF;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.io.ByteArrayInputStream;+import java.lang.reflect.Method;+import java.time.Duration;+import java.util.List;+import java.util.Map;++import org.apache.pdfbox.cos.COSArray;+import org.apache.pdfbox.cos.COSName;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;+import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;+import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;+import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;+import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;+import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;+import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;+import org.junit.jupiter.api.Test;+import org.springframework.http.MediaType;+import org.springframework.mock.web.MockMultipartFile;++import stirling.software.SPDF.controller.api.EditTableOfContentsController;+import stirling.software.SPDF.controller.api.security.GetInfoOnPDF;+import stirling.software.SPDF.service.AttachmentService;+import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.util.TempFileManager;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;++/** Walkers over PDF object graphs must visit a shared or cyclic object once. */+class SharedReferenceWalkTest {++ private static final Duration LIMIT = Duration.ofSeconds(10);++ /** One page, one bookmark whose /Next points back at itself. */+ private static PDDocument selfLinkedOutline() {+ PDDocument document = new PDDocument();+ document.addPage(new PDPage());+ PDDocumentOutline outline = new PDDocumentOutline();+ PDOutlineItem item = new PDOutlineItem();+ item.setTitle("loop");+ outline.addLast(item);+ item.getCOSObject().setItem(COSName.NEXT, item.getCOSObject());+ document.getDocumentCatalog().setDocumentOutline(outline);+ return document;+ }++ @Test+ void extractBookmarksStopsAtAnOutlineCycle() throws Exception {+ CustomPDFDocumentFactory factory = mock(CustomPDFDocumentFactory.class);+ MockMultipartFile file =+ new MockMultipartFile(+ "file", "x.pdf", MediaType.APPLICATION_PDF_VALUE, new byte[1]);+ when(factory.load(file)).thenReturn(selfLinkedOutline());+ EditTableOfContentsController controller =+ new EditTableOfContentsController(+ factory, new ObjectMapper(), mock(TempFileManager.class));++ List<Map<String, Object>> bookmarks =+ assertTimeoutPreemptively(LIMIT, () -> controller.extractBookmarks(file).getBody());++ assertThat(bookmarks).hasSize(1);+ assertThat(bookmarks.get(0)).containsEntry("title", "loop");+ }++ @Test+ void getInfoBookmarksStopAtANestedOutlineCycle() throws Exception {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new PDPage());+ PDDocumentOutline outline = new PDDocumentOutline();+ PDOutlineItem top = new PDOutlineItem();+ top.setTitle("top");+ outline.addLast(top);+ PDOutlineItem child = new PDOutlineItem();+ child.setTitle("child");+ top.addLast(child);+ child.getCOSObject().setItem(COSName.NEXT, child.getCOSObject());+ child.getCOSObject().setItem(COSName.FIRST, child.getCOSObject());+ document.getDocumentCatalog().setDocumentOutline(outline);++ JsonNode bookmarks =+ assertTimeoutPreemptively(+ LIMIT, () -> invokeGetInfo("extractBookmarks", document));++ assertThat(bookmarks.size()).isEqualTo(2);+ }+ }++ @Test+ void getInfoExpandsEachStructureElementOnce() throws Exception {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new PDPage());+ PDStructureTreeRoot root = new PDStructureTreeRoot();+ document.getDocumentCatalog().setStructureTreeRoot(root);+ PDStructureElement section = new PDStructureElement("Sect", root);+ root.appendKid(section);+ PDStructureElement paragraph = new PDStructureElement("P", section);+ for (int i = 0; i < 3; i++) {+ section.appendKid(paragraph);+ }+ section.appendKid(section);++ JsonNode info =+ assertTimeoutPreemptively(+ LIMIT, () -> invokeGetInfo("extractOtherInfo", document));++ JsonNode tree = info.get("StructureTree");+ assertThat(tree.size()).isEqualTo(1);+ assertThat(tree.get(0).get("Children").size()).isEqualTo(1);+ }+ }++ @Test+ void attachmentsInARepeatedOrCyclicNameTreeAreListedOnce() throws Exception {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new PDPage());+ PDComplexFileSpecification spec = new PDComplexFileSpecification();+ spec.setFile("a.txt");+ spec.setEmbeddedFile(+ new PDEmbeddedFile(document, new ByteArrayInputStream(new byte[] {1})));+ PDEmbeddedFilesNameTreeNode leaf = new PDEmbeddedFilesNameTreeNode();+ leaf.setNames(Map.of("a.txt", spec));+ PDEmbeddedFilesNameTreeNode root = new PDEmbeddedFilesNameTreeNode();+ root.setKids(List.of(leaf));+ COSArray kids = root.getCOSObject().getCOSArray(COSName.KIDS);+ kids.add(leaf.getCOSObject());+ kids.add(root.getCOSObject());+ PDDocumentNameDictionary names =+ new PDDocumentNameDictionary(document.getDocumentCatalog());+ names.setEmbeddedFiles(root);+ document.getDocumentCatalog().setNames(names);++ var attachments =+ assertTimeoutPreemptively(+ LIMIT, () -> new AttachmentService().listAttachments(document));++ assertThat(attachments).hasSize(1);+ }+ }++ private static JsonNode invokeGetInfo(String name, PDDocument document) throws Exception {+ Method method = GetInfoOnPDF.class.getDeclaredMethod(name, PDDocument.class);+ method.setAccessible(true);+ return (JsonNode) method.invoke(null, document);+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTableOfContentsControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTableOfContentsControllerTest.javaindex 6b86bc484d..d8b630808b 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTableOfContentsControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTableOfContentsControllerTest.java@@ -11,6 +11,7 @@ import java.util.ArrayList;import java.util.List;import java.util.Map;+import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDDocumentCatalog;import org.apache.pdfbox.pdmodel.PDPage;@@ -93,14 +94,14 @@ class EditTableOfContentsControllerTest {when(pdfDocumentFactory.load(mockFile)).thenReturn(mockDocument);when(mockDocument.getDocumentCatalog()).thenReturn(mockCatalog);when(mockCatalog.getDocumentOutline()).thenReturn(mockOutline);- when(mockOutline.getFirstChild()).thenReturn(mockOutlineItem);+ when(mockOutline.children()).thenReturn(List.of(mockOutlineItem));+ when(mockOutlineItem.getCOSObject()).thenReturn(new COSDictionary());when(mockOutlineItem.getTitle()).thenReturn("Chapter 1");when(mockOutlineItem.findDestinationPage(mockDocument)).thenReturn(mockPage1);when(mockDocument.getPages()).thenReturn(mockPages);when(mockPages.indexOf(mockPage1)).thenReturn(0);- when(mockOutlineItem.getFirstChild()).thenReturn(null);- when(mockOutlineItem.getNextSibling()).thenReturn(null);+ when(mockOutlineItem.children()).thenReturn(List.of());// WhenResponseEntity<List<Map<String, Object>>> response =@@ -147,22 +148,22 @@ class EditTableOfContentsControllerTest {when(pdfDocumentFactory.load(mockFile)).thenReturn(mockDocument);when(mockDocument.getDocumentCatalog()).thenReturn(mockCatalog);when(mockCatalog.getDocumentOutline()).thenReturn(mockOutline);- when(mockOutline.getFirstChild()).thenReturn(mockOutlineItem);+ when(mockOutline.children()).thenReturn(List.of(mockOutlineItem));// Parent bookmark+ when(mockOutlineItem.getCOSObject()).thenReturn(new COSDictionary());when(mockOutlineItem.getTitle()).thenReturn("Chapter 1");when(mockOutlineItem.findDestinationPage(mockDocument)).thenReturn(mockPage1);when(mockDocument.getPages()).thenReturn(mockPages);when(mockPages.indexOf(mockPage1)).thenReturn(0);- when(mockOutlineItem.getFirstChild()).thenReturn(childItem);- when(mockOutlineItem.getNextSibling()).thenReturn(null);+ when(mockOutlineItem.children()).thenReturn(List.of(childItem));// Child bookmark+ when(childItem.getCOSObject()).thenReturn(new COSDictionary());when(childItem.getTitle()).thenReturn("Section 1.1");when(childItem.findDestinationPage(mockDocument)).thenReturn(mockPage2);when(mockPages.indexOf(mockPage2)).thenReturn(1);- when(childItem.getFirstChild()).thenReturn(null);- when(childItem.getNextSibling()).thenReturn(null);+ when(childItem.children()).thenReturn(List.of());// WhenResponseEntity<List<Map<String, Object>>> response =@@ -196,12 +197,12 @@ class EditTableOfContentsControllerTest {when(pdfDocumentFactory.load(mockFile)).thenReturn(mockDocument);when(mockDocument.getDocumentCatalog()).thenReturn(mockCatalog);when(mockCatalog.getDocumentOutline()).thenReturn(mockOutline);- when(mockOutline.getFirstChild()).thenReturn(mockOutlineItem);+ when(mockOutline.children()).thenReturn(List.of(mockOutlineItem));+ when(mockOutlineItem.getCOSObject()).thenReturn(new COSDictionary());when(mockOutlineItem.getTitle()).thenReturn("Chapter 1");when(mockOutlineItem.findDestinationPage(mockDocument)).thenReturn(null); // Page not found- when(mockOutlineItem.getFirstChild()).thenReturn(null);- when(mockOutlineItem.getNextSibling()).thenReturn(null);+ when(mockOutlineItem.children()).thenReturn(List.of());// WhenResponseEntity<List<Map<String, Object>>> response =diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RemoveImagesControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RemoveImagesControllerTest.javaindex db361b4302..89158e7c24 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RemoveImagesControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RemoveImagesControllerTest.java@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;@@ -17,6 +18,7 @@ import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;+import java.time.Duration;import java.util.ArrayList;import java.util.List;@@ -441,6 +443,31 @@ class RemoveImagesControllerTest {}}+ @Test+ @DisplayName("A form shared under many names, or naming itself, is processed once")+ void sharedAndSelfReferencingForms() throws Exception {+ PDDocument doc = new PDDocument();+ PDFormXObject inner = new PDFormXObject(doc);+ inner.setResources(new PDResources());+ inner.getResources()+ .put(COSName.getPDFName("Im"), JPEGFactory.createFromImage(doc, tinyImage()));+ inner.getResources().put(COSName.getPDFName("Self"), inner);+ PDPage page = new PDPage(PDRectangle.LETTER);+ page.setResources(new PDResources());+ for (int i = 0; i < 4; i++) {+ page.getResources().put(COSName.getPDFName("F" + i), inner);+ }+ doc.addPage(page);+ PDFFile req = request(multipart("shared.pdf", new byte[] {1}));+ when(pdfDocumentFactory.load(req)).thenReturn(doc);++ assertTimeoutPreemptively(Duration.ofSeconds(10), () -> controller.removeImages(req));++ List<COSName> remaining = new ArrayList<>();+ inner.getResources().getXObjectNames().forEach(remaining::add);+ assertEquals(List.of(COSName.getPDFName("Self")), remaining);+ }+private static ResponseEntity<Resource> okResponse() {return ResponseEntity.ok(new ByteArrayResource("ok".getBytes()));}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaTagger.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaTagger.javaindex 7f5dcc3739..3447e33509 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaTagger.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaTagger.java@@ -2,12 +2,15 @@ package stirling.software.proprietary.pdf.ua;import java.io.IOException;import java.util.ArrayList;+import java.util.Collections;import java.util.HashSet;+import java.util.IdentityHashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;+import org.apache.pdfbox.cos.COSDictionary;import org.apache.pdfbox.cos.COSName;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDDocumentCatalog;@@ -263,12 +266,16 @@ public class PdfUaTagger {private static final List<String> MEANINGFUL_TYPES =List.of("Table", "TH", "Formula", "L", "LI", "TOC", "Note");- private static Set<String> structureTypes(PDDocument document) {+ static Set<String> structureTypes(PDDocument document) {Set<String> types = new HashSet<>();try {PDStructureTreeRoot root = document.getDocumentCatalog().getStructureTreeRoot();if (root != null) {- collectTypes(root.getKids(), types, 0);+ collectTypes(+ root.getKids(),+ types,+ 0,+ Collections.newSetFromMap(new IdentityHashMap<>()));}} catch (RuntimeException e) {log.debug("Could not read structure types: {}", e.getMessage());@@ -276,16 +283,18 @@ public class PdfUaTagger {return types;}- private static void collectTypes(Object node, Set<String> types, int depth) {+ private static void collectTypes(+ Object node, Set<String> types, int depth, Set<COSDictionary> seen) {// Structure trees can be deep or, in damaged files, cyclic; cap rather than overflow.+ // The depth cap bounds a path, not the number of paths, so each element is walked once.if (node == null || depth > 64) {return;}if (node instanceof List<?> list) {- list.forEach(child -> collectTypes(child, types, depth + 1));- } else if (node instanceof PDStructureElement element) {+ list.forEach(child -> collectTypes(child, types, depth + 1, seen));+ } else if (node instanceof PDStructureElement element && seen.add(element.getCOSObject())) {types.add(element.getStructureType());- collectTypes(element.getKids(), types, depth + 1);+ collectTypes(element.getKids(), types, depth + 1, seen);}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/SourceFacts.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/SourceFacts.javaindex 4f058d6c48..d520f0d484 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/SourceFacts.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/SourceFacts.java@@ -1,11 +1,8 @@package stirling.software.proprietary.pdf.ua;-import java.util.HashSet;import java.util.Set;import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;-import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;import lombok.extern.slf4j.Slf4j;@@ -22,38 +19,18 @@ import lombok.extern.slf4j.Slf4j;@Slf4jpublic record SourceFacts(String language, Set<String> structureTypes, boolean hasUsableTree) {- private static final int MAX_DEPTH = 64;-/** Facts for a document nothing has rewritten, used when font embedding did not run. */public static final SourceFacts NONE = new SourceFacts(null, Set.of(), false);public static SourceFacts of(PDDocument document) {String language = null;- Set<String> types = new HashSet<>();boolean usable = false;try {language = document.getDocumentCatalog().getLanguage();usable = PdfUaTagger.hasUsableStructureTree(document);- PDStructureTreeRoot root = document.getDocumentCatalog().getStructureTreeRoot();- if (root != null) {- collect(root.getKids(), types, 0);- }} catch (RuntimeException e) {log.debug("Could not read source facts: {}", e.getMessage());}- return new SourceFacts(language, Set.copyOf(types), usable);- }-- private static void collect(Object node, Set<String> types, int depth) {- // Damaged files can present a cyclic tree; cap rather than overflow the stack.- if (node == null || depth > MAX_DEPTH) {- return;- }- if (node instanceof java.util.List<?> list) {- list.forEach(child -> collect(child, types, depth + 1));- } else if (node instanceof PDStructureElement element) {- types.add(element.getStructureType());- collect(element.getKids(), types, depth + 1);- }+ return new SourceFacts(language, Set.copyOf(PdfUaTagger.structureTypes(document)), usable);}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/pdf/ua/StructureTypesWalkTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/pdf/ua/StructureTypesWalkTest.javanew file mode 100644index 0000000000..623a1096ff--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/pdf/ua/StructureTypesWalkTest.java@@ -0,0 +1,40 @@+package stirling.software.proprietary.pdf.ua;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;++import java.time.Duration;+import java.util.Set;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;+import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;+import org.junit.jupiter.api.Test;++class StructureTypesWalkTest {++ @Test+ void repeatedAndCyclicElementsAreWalkedOnce() throws Exception {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new PDPage());+ PDStructureTreeRoot root = new PDStructureTreeRoot();+ document.getDocumentCatalog().setStructureTreeRoot(root);+ PDStructureElement section = new PDStructureElement("Sect", root);+ root.appendKid(section);+ PDStructureElement table = new PDStructureElement("Table", section);+ for (int i = 0; i < 3; i++) {+ section.appendKid(table);+ }+ section.appendKid(section);++ Set<String> types =+ assertTimeoutPreemptively(+ Duration.ofSeconds(10), () -> PdfUaTagger.structureTypes(document));+ SourceFacts facts = SourceFacts.of(document);++ assertThat(types).containsExactlyInAnyOrder("Sect", "Table");+ assertThat(facts.structureTypes()).isEqualTo(types);+ }+ }+}