Skip to content

Commit 2f78da1

Browse files
authored
TIKA_4782 -- allow print ticket headers in pdf detection (#3027)
1 parent 43cbdae commit 2f78da1

4 files changed

Lines changed: 187 additions & 0 deletions

File tree

CHANGES.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,11 @@ Release 4.0.0 - ???
151151
closes its connection and recycles the per-client worker, so a
152152
pooled client cannot go back to the queue dirty (TIKA-4815).
153153

154+
* PDFs whose %PDF- header is preceded by a print-composition job ticket are
155+
no longer detected as text/x-matlab. Up to 50 %% comment or blank lines of
156+
up to 150 characters, and nothing else, may now precede the header; the
157+
TIKA-3328 rule this extends only reached 512 bytes (TIKA-4782).
158+
154159

155160
Release 4.0.0-beta-1 - 6/29/2026
156161

tika-core/src/main/resources/org/apache/tika/mime/tika-mimetypes.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -855,6 +855,16 @@
855855
<match value="%PDF-2." type="string" offset="1:512"/>
856856
</match>
857857
</magic>
858+
<magic priority="40">
859+
<!-- Print-composition systems prepend a job ticket of %% comments that can run well
860+
past the 512-byte window above (TIKA-4782). Up to 50 %% comment or blank lines of up
861+
to 150 characters, and nothing else, may precede the header. 50x150 is deliberate:
862+
the worst case stays inside the first 8K, which is all MagicDetector feeds a regex,
863+
so every prefix within those bounds really is reachable.
864+
Every quantifier is bounded and the group is atomic, so this cannot backtrack: without
865+
the (?> a hostile CRLF run splits exponentially and hangs detection. Keep it that way. -->
866+
<match value="(?>(?:%%[^\\r\\n]{0,148})?(?:\\r\\n|[\\r\\n])){1,50}%PDF-[12]\\." type="regex" offset="0"/>
867+
</magic>
858868
<magic priority="20">
859869
<!-- Low priority match for %PDF-#.# near the start of the file -->
860870
<!-- Can trigger false positives, so set the priority rather low here -->
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package org.apache.tika.mime;
18+
19+
import static java.nio.charset.StandardCharsets.ISO_8859_1;
20+
import static org.junit.jupiter.api.Assertions.assertEquals;
21+
import static org.junit.jupiter.api.Assertions.assertNotEquals;
22+
import static org.junit.jupiter.api.Assertions.assertNotNull;
23+
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
24+
25+
import java.io.InputStream;
26+
import java.time.Duration;
27+
28+
import org.junit.jupiter.api.BeforeAll;
29+
import org.junit.jupiter.api.Test;
30+
31+
import org.apache.tika.io.TikaInputStream;
32+
import org.apache.tika.metadata.Metadata;
33+
import org.apache.tika.parser.ParseContext;
34+
35+
/**
36+
* Detection of PDFs whose {@code %PDF-} header is preceded by {@code %%} comment
37+
* lines, which would otherwise be claimed by the matlab {@code %%} magic.
38+
*
39+
* @see <a href="https://issues.apache.org/jira/browse/TIKA-3328">TIKA-3328</a>
40+
* @see <a href="https://issues.apache.org/jira/browse/TIKA-4782">TIKA-4782</a>
41+
*/
42+
public class PdfDetectionTest {
43+
44+
private static final MediaType PDF = MediaType.application("pdf");
45+
46+
private static final MediaType MATLAB = MediaType.text("x-matlab");
47+
48+
private static final String PDF_BODY = "%PDF-1.7\r\n1 0 obj\r\n";
49+
50+
private static MimeTypes MIME_TYPES;
51+
52+
@BeforeAll
53+
public static void setUp() {
54+
MIME_TYPES = MimeTypes.getDefaultMimeTypes();
55+
}
56+
57+
/**
58+
* Print-shop job ticket ahead of the header; the {@code %PDF-} lands well past
59+
* the 512-byte window of the older TIKA-3328 rule.
60+
*/
61+
@Test
62+
public void testPrintTicketHeader() throws Exception {
63+
try (InputStream in = getClass().getResourceAsStream("test-pdf-with-print-ticket-header.pdf")) {
64+
assertNotNull(in, "missing test file");
65+
assertEquals(PDF, detect(in));
66+
}
67+
}
68+
69+
/**
70+
* 10 and 50 lines of 60 push the header past the 512-byte window the older rules
71+
* can reach; 1 line keeps TIKA-3328 covered.
72+
*/
73+
@Test
74+
public void testCommentLinesBeforeHeader() throws Exception {
75+
for (int lines : new int[]{1, 10, 50}) {
76+
assertEquals(PDF, detect(commentLines(lines, 60) + PDF_BODY), lines + " comment lines");
77+
}
78+
assertEquals(PDF, detect(commentLines(5, 150) + PDF_BODY), "maximum-length lines");
79+
}
80+
81+
/**
82+
* Both bounds at once. This is the case that catches a prefix sized within the
83+
* documented bounds but past the 8K MagicDetector hands a regex.
84+
*/
85+
@Test
86+
public void testLargestAcceptedPrefix() throws Exception {
87+
assertEquals(PDF, detect(commentLines(50, 150) + PDF_BODY));
88+
}
89+
90+
@Test
91+
public void testBlankLinesAndLineEndings() throws Exception {
92+
assertEquals(PDF, detect("%%BeginTicket\r\n\r\n%%EndTicket\n\n" + PDF_BODY));
93+
assertEquals(PDF, detect("\r\n\r\n" + PDF_BODY));
94+
assertEquals(PDF, detect("%%a\r%%b\r" + PDF_BODY));
95+
assertEquals(PDF, detect("%%a\n%%b\n" + PDF_BODY.replace("%PDF-1.", "%PDF-2.")));
96+
}
97+
98+
/**
99+
* Each negative case puts the header past 512 bytes, so only the TIKA-4782 rule
100+
* could have matched it.
101+
*/
102+
@Test
103+
public void testCommentPrefixIsBounded() throws Exception {
104+
assertNotEquals(PDF, detect(commentLines(51, 60) + PDF_BODY), "51 comment lines");
105+
assertNotEquals(PDF, detect(commentLines(5, 151) + PDF_BODY), "over-long comment lines");
106+
}
107+
108+
/**
109+
* Only comment and blank lines may precede the header: anything else and this is
110+
* some other format that happens to embed a PDF.
111+
*/
112+
@Test
113+
public void testNonCommentPrefixIsNotPdf() throws Exception {
114+
assertNotEquals(PDF, detect(commentLines(10, 60) + "x = 1;\r\n" + PDF_BODY));
115+
}
116+
117+
@Test
118+
public void testMatlabStillDetected() throws Exception {
119+
assertEquals(MATLAB, detect("%% cell one\r\nx = 1;\r\n%% cell two\r\ny = x + 1;\r\n"));
120+
}
121+
122+
/**
123+
* The TIKA-4782 regex must not backtrack. Earlier drafts of it hung Java's matcher
124+
* indefinitely on these inputs; linear forms answer in well under a millisecond, so
125+
* a generous timeout separates the two without being timing-sensitive.
126+
*/
127+
@Test
128+
public void testNoCatastrophicBacktracking() {
129+
String[] hostile = new String[]{
130+
"\r\n".repeat(4096),
131+
"\r".repeat(8192),
132+
"%".repeat(8192),
133+
"%%".repeat(4096),
134+
"%%a\r\n".repeat(1638),
135+
"%%a\r\n\r\n".repeat(1024),
136+
commentLines(50, 150) + "\r\n".repeat(1000)
137+
};
138+
assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
139+
for (String s : hostile) {
140+
detect(s);
141+
}
142+
});
143+
}
144+
145+
/**
146+
* @param lineLength characters per line including the leading {@code %%}, excluding the CRLF
147+
*/
148+
private static String commentLines(int count, int lineLength) {
149+
StringBuilder line = new StringBuilder("%%");
150+
while (line.length() < lineLength) {
151+
line.append('A');
152+
}
153+
line.append("\r\n");
154+
StringBuilder sb = new StringBuilder();
155+
for (int i = 0; i < count; i++) {
156+
sb.append(line);
157+
}
158+
return sb.toString();
159+
}
160+
161+
private static MediaType detect(String bytes) throws Exception {
162+
try (TikaInputStream tis = TikaInputStream.get(bytes.getBytes(ISO_8859_1))) {
163+
return MIME_TYPES.detect(tis, new Metadata(), new ParseContext());
164+
}
165+
}
166+
167+
private static MediaType detect(InputStream in) throws Exception {
168+
try (TikaInputStream tis = TikaInputStream.get(in)) {
169+
return MIME_TYPES.detect(tis, new Metadata(), new ParseContext());
170+
}
171+
}
172+
}
Binary file not shown.

0 commit comments

Comments
 (0)