Debian Codegraph @

src/com/adobe/internal/xmp/impl/XMPMetaParser.java

raw symbols SCIP
1 // =================================================================================================
2 // ADOBE SYSTEMS INCORPORATED
3 // Copyright 2006 Adobe Systems Incorporated
4 // All Rights Reserved
5 //
6 // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
7 // of the Adobe license agreement accompanying it.
8 // =================================================================================================
9
10 package com.adobe.internal.xmp.impl;
11
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.io.Reader;
16 import java.io.StringReader;
17 import java.io.UnsupportedEncodingException;
18
19 import javax.xml.XMLConstants;
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
23
24 import org.w3c.dom.Document;
25 import org.w3c.dom.Node;
26 import org.w3c.dom.NodeList;
27 import org.w3c.dom.ProcessingInstruction;
28 import org.xml.sax.InputSource;
29 import org.xml.sax.SAXException;
30
31 import com.adobe.internal.xmp.XMPConst;
32 import com.adobe.internal.xmp.XMPError;
33 import com.adobe.internal.xmp.XMPException;
34 import com.adobe.internal.xmp.XMPMeta;
35 import com.adobe.internal.xmp.options.ParseOptions;
36
37
38
39 /**
40 * This class replaces the <code>ExpatAdapter.cpp</code> and does the
41 * XML-parsing and fixes the prefix. After the parsing several normalisations
42 * are applied to the XMPTree.
43 *
44 * @author Stefan Makswit
45 * @version $Revision$
46 * @since 01.02.2006
47 */
48
49 public class XMPMetaParser
50 {
51 /** */
52
53 private static final Object XMP_RDF = new Object();
54 // <#AdobePrivate>
55 // The Plain XMP format is disabled
56 /** */
57 // private static final Object XMP_PLAIN = new Object();
58 // </#AdobePrivate>
59 /** the DOM Parser Factory, options are set */
60 private static DocumentBuilderFactory factory = createDocumentBuilderFactory();
61
62 /**
63 * Hidden constructor, initialises the SAX parser handler.
64 */
65 private XMPMetaParser()
66 {
67 // EMPTY
68 }
69
70
71
72 /**
73 * Parses the input source into an XMP metadata object, including
74 * de-aliasing and normalisation.
75 *
76 * @param input the input can be an <code>InputStream</code>, a <code>String</code> or
77 * a byte buffer containing the XMP packet.
78 * @param options the parse options
79 * @return Returns the resulting XMP metadata object
80 * @throws XMPException Thrown if parsing or normalisation fails.
81 */
82 public static XMPMeta parse(Object input, ParseOptions options) throws XMPException
83 {
84 ParameterAsserts.assertNotNull(input);
85 options = options != null ? options : new ParseOptions();
86
87 Document document = parseXml(input, options);
88
89 boolean xmpmetaRequired = options.getRequireXMPMeta();
90 Object[] result = new Object[3];
91 result = findRootNode(document, xmpmetaRequired, result);
92
93 if (result != null && result[1] == XMP_RDF)
94 {
95 XMPMetaImpl xmp = ParseRDF.parse((Node) result[0], options);
96 xmp.setPacketHeader((String) result[2]);
97
98 // Check if the XMP object shall be normalized
99 if (!options.getOmitNormalization())
100 {
101 return XMPNormalizer.process(xmp, options);
102 }
103 else
104 {
105 return xmp;
106 }
107 }
108 // <#AdobePrivate>
109 // The Plain XMP format is disabled
110 // else if (result != null && result[1] == XMP_PLAIN)
111 // {
112 // XMPMetaImpl xmp = ParsePlainXMP.parse((Node) result[0]);
113 // xmp.setPacketHeader((String) result[2]);
114 // return XMPNormalizer.process(xmp, options);
115 // }
116 // </#AdobePrivate>
117 else
118 {
119 // no appropriate root node found, return empty metadata object
120 return new XMPMetaImpl();
121 }
122 }
123
124
125 /**
126 * Parses the raw XML metadata packet considering the parsing options.
127 * Latin-1/ISO-8859-1 can be accepted when the input is a byte stream
128 * (some old toolkits versions such packets). The stream is
129 * then wrapped in another stream that converts Latin-1 to UTF-8.
130 * <p>
131 * If control characters shall be fixed, a reader is used that fixes the chars to spaces
132 * (if the input is a byte stream is has to be read as character stream).
133 * <p>
134 * Both options reduce the performance of the parser.
135 *
136 * @param input the input can be an <code>InputStream</code>, a <code>String</code> or
137 * a byte buffer containing the XMP packet.
138 * @param options the parsing options
139 * @return Returns the parsed XML document or an exception.
140 * @throws XMPException Thrown if the parsing fails for different reasons
141 */
142 private static Document parseXml(Object input, ParseOptions options)
143 throws XMPException
144 {
145 if (input instanceof InputStream)
146 {
147 return parseXmlFromInputStream((InputStream) input, options);
148 }
149 else if (input instanceof byte[])
150 {
151 return parseXmlFromBytebuffer(new ByteBuffer((byte[]) input), options);
152 }
153 else
154 {
155 return parseXmlFromString((String) input, options);
156 }
157 }
158
159
160 /**
161 * Parses XML from an {@link InputStream},
162 * fixing the encoding (Latin-1 to UTF-8) and illegal control character optionally.
163 *
164 * @param stream an <code>InputStream</code>
165 * @param options the parsing options
166 * @return Returns an XML DOM-Document.
167 * @throws XMPException Thrown when the parsing fails.
168 */
169 private static Document parseXmlFromInputStream(InputStream stream, ParseOptions options)
170 throws XMPException
171 {
172 if (!options.getAcceptLatin1() &&
173 !options.getFixControlChars() &&
174 !options.getDisallowDoctype())
175 {
176 return parseInputSource(new InputSource(stream));
177 }
178 else
179 {
180 // load stream into ByteBuffer to apply advanced options
181 try
182 {
183 ByteBuffer buffer = new ByteBuffer(stream);
184 return parseXmlFromBytebuffer(buffer, options);
185 }
186 catch (IOException e)
187 {
188 throw new XMPException("Error reading the XML-file",
189 XMPError.BADSTREAM, e);
190 }
191 }
192 }
193
194
195 /**
196 * Parses XML from a byte buffer,
197 * fixing the encoding (Latin-1 to UTF-8) and illegal control character optionally.
198 * To improve the performance on legal files, it is first tried to parse normally,
199 * while the character fixing is only done when the first pass fails.
200 *
201 * @param buffer a byte buffer containing the XMP packet
202 * @param options the parsing options
203 * @return Returns an XML DOM-Document.
204 * @throws XMPException Thrown when the parsing fails.
205 */
206 private static Document parseXmlFromBytebuffer(ByteBuffer buffer, ParseOptions options)
207 throws XMPException
208 {
209 try
210 {
211 InputSource source = new InputSource(buffer.getByteStream());
212 try
213 {
214 if (options.getDisallowDoctype())
215 {
216 try
217 {
218 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
219 }
220 catch(Throwable e)
221 {
222
223 }
224 }
225
226 return parseInputSource(source);
227 }
228 catch (XMPException e)
229 {
230 if ("DOCTYPE is disallowed".equals(e.getCause().getMessage()))
231 {
232 throw new XMPException(e.getCause().getMessage(), XMPError.BADXML);
233 }
234 else if (e.getErrorCode() == XMPError.BADXML ||
235 e.getErrorCode() == XMPError.BADSTREAM)
236 {
237 if (options.getAcceptLatin1())
238 {
239 buffer = Latin1Converter.convert(buffer);
240 }
241
242 if (options.getFixControlChars())
243 {
244 String encoding = buffer.getEncoding();
245 Reader fixReader = new FixASCIIControlsReader(
246 new InputStreamReader(
247 buffer.getByteStream(), encoding));
248 return parseInputSource(new InputSource(fixReader));
249 }
250 source = new InputSource(buffer.getByteStream());
251 return parseInputSource(source);
252 }
253 else
254 {
255 throw e;
256 }
257 }
258 }
259 catch (UnsupportedEncodingException e)
260 {
261 // can normally not happen as the encoding is provided by a util function
262 throw new XMPException("Unsupported Encoding",
263 XMPError.INTERNALFAILURE, e);
264 }
265 }
266
267
268 /**
269 * Parses XML from a {@link String},
270 * fixing the illegal control character or disallow DOCTYPEs optionally.
271 *
272 * @param input a <code>String</code> containing the XMP packet
273 * @param options the parsing options
274 * @return Returns an XML DOM-Document.
275 * @throws XMPException Thrown when the parsing fails.
276 */
277 private static Document parseXmlFromString(String input, ParseOptions options)
278 throws XMPException
279 {
280 InputSource source;
281 try
282 {
283 if (options.getDisallowDoctype())
284 {
285 try
286 {
287 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
288 }
289 catch(Throwable e)
290 {
291
292 }
293 }
294 source = new InputSource(new StringReader(input));
295 return parseInputSource(source);
296 }
297 catch (XMPException e)
298 {
299 if (e.getErrorCode() == XMPError.BADXML && options.getFixControlChars())
300 {
301 source = new InputSource(new FixASCIIControlsReader(new StringReader(input)));
302 return parseInputSource(source);
303 }
304 else
305 {
306 throw e;
307 }
308 }
309 }
310
311
312 /**
313 * Runs the XML-Parser.
314 * @param source an <code>InputSource</code>
315 * @return Returns an XML DOM-Document.
316 * @throws XMPException Wraps parsing and I/O-exceptions into an XMPException.
317 */
318 private static Document parseInputSource(InputSource source) throws XMPException
319 {
320 try
321 {
322 DocumentBuilder builder = factory.newDocumentBuilder();
323 builder.setErrorHandler(null);
324
325 return builder.parse(source);
326 }
327 catch (SAXException e)
328 {
329 throw new XMPException("XML parsing failure", XMPError.BADXML, e);
330 }
331 catch (ParserConfigurationException e)
332 {
333 throw new XMPException("XML Parser not correctly configured",
334 XMPError.UNKNOWN, e);
335 }
336 catch (IOException e)
337 {
338 throw new XMPException("Error reading the XML-file", XMPError.BADSTREAM, e);
339 }
340 }
341
342
343 /**
344 * Find the XML node that is the root of the XMP data tree. Generally this
345 * will be an outer node, but it could be anywhere if a general XML document
346 * is parsed (e.g. SVG). The XML parser counted all rdf:RDF and
347 * pxmp:XMP_Packet nodes, and kept a pointer to the last one. If there is
348 * more than one possible root use PickBestRoot to choose among them.
349 * <p>
350 * If there is a root node, try to extract the version of the previous XMP
351 * toolkit.
352 * <p>
353 * Pick the first x:xmpmeta among multiple root candidates. If there aren't
354 * any, pick the first bare rdf:RDF if that is allowed. The returned root is
355 * the rdf:RDF child if an x:xmpmeta element was chosen. The search is
356 * breadth first, so a higher level candiate is chosen over a lower level
357 * one that was textually earlier in the serialized XML.
358 *
359 * @param root the root of the xml document
360 * @param xmpmetaRequired flag if the xmpmeta-tag is still required, might be set
361 * initially to <code>true</code>, if the parse option "REQUIRE_XMP_META" is set
362 * @param result The result array that is filled during the recursive process.
363 * @return Returns an array that contains the result or <code>null</code>.
364 * The array contains:
365 * <ul>
366 * <li>[0] - the rdf:RDF-node
367 * <li>[1] - an object that is either XMP_RDF or XMP_PLAIN (the latter is decrecated)
368 * <li>[2] - the body text of the xpacket-instruction.
369 * </ul>
370 *
371 */
372 private static Object[] findRootNode(Node root, boolean xmpmetaRequired, Object[] result)
373 {
374 // Look among this parent's content for x:xapmeta or x:xmpmeta.
375 // The recursion for x:xmpmeta is broader than the strictly defined choice,
376 // but gives us smaller code.
377 NodeList children = root.getChildNodes();
378 for (int i = 0; i < children.getLength(); i++)
379 {
380 root = children.item(i);
381 if (Node.PROCESSING_INSTRUCTION_NODE == root.getNodeType() &&
382 XMPConst.XMP_PI.equals(((ProcessingInstruction) root).getTarget()))
383
384 {
385 // Store the processing instructions content
386 if (result != null)
387 {
388 result[2] = ((ProcessingInstruction) root).getData();
389 }
390 }
391 else if (Node.TEXT_NODE != root.getNodeType() &&
392 Node.PROCESSING_INSTRUCTION_NODE != root.getNodeType())
393 {
394 String rootNS = root.getNamespaceURI();
395 String rootLocal = root.getLocalName();
396 if (
397 (
398 XMPConst.TAG_XMPMETA.equals(rootLocal) ||
399 XMPConst.TAG_XAPMETA.equals(rootLocal)
400 ) &&
401 XMPConst.NS_X.equals(rootNS)
402 )
403 {
404 // by not passing the RequireXMPMeta-option, the rdf-Node will be valid
405 return findRootNode(root, false, result);
406 }
407 else if (!xmpmetaRequired &&
408 "RDF".equals(rootLocal) &&
409 XMPConst.NS_RDF.equals(rootNS))
410 {
411 if (result != null)
412 {
413 result[0] = root;
414 result[1] = XMP_RDF;
415 }
416 return result;
417 }
418 // <#AdobePrivate>
419 // The Plain XMP format is disabled
420 // else if ("XMP_Packet".equals(rootLocal) &&
421 // XMPConst.NS_PXMP.equals(rootNS))
422 // {
423 // if (result != null)
424 // {
425 // result[0] = root;
426 // result[1] = XMP_PLAIN;
427 // }
428 // return result;
429 // }
430 // </#AdobePrivate>
431 else
432 {
433 // continue searching
434 Object[] newResult = findRootNode(root, xmpmetaRequired, result);
435 if (newResult != null)
436 {
437 return newResult;
438 }
439 else
440 {
441 continue;
442 }
443 }
444 }
445 }
446
447 // no appropriate node has been found
448 return null;
449
450 // *** the version of the toolkit which generated this packet
451 // is extracted here in the C++ Toolkit
452 }
453
454
455 /**
456 * @return Creates, configures and returnes the document builder factory for
457 * the Metadata Parser.
458 */
459 private static DocumentBuilderFactory createDocumentBuilderFactory()
460 {
461 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
462 factory.setNamespaceAware(true);
463 factory.setIgnoringComments(true);
464 factory.setExpandEntityReferences(false);
465
466 try
467 {
468 String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
469 factory.setFeature(FEATURE, true);
470 // If you can't completely disable DTDs, then at least do the
471 // following:
472 // Xerces 1 -
473 // http://xerces.apache.org/xerces-j/features.html#external-general-entities
474 // Xerces 2 -
475 // http://xerces.apache.org/xerces2-j/features.html#external-general-entities
476 // JDK7+ - http://xml.org/sax/features/external-general-entities
477 FEATURE = "http://xml.org/sax/features/external-general-entities";
478 factory.setFeature(FEATURE, false);
479 FEATURE = "http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl";
480 factory.setFeature(FEATURE, false);
481
482 // Xerces 1 -
483 // http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
484 // Xerces 2 -
485 // http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
486 // JDK7+ - http://xml.org/sax/features/external-parameter-entities
487 FEATURE = "http://xml.org/sax/features/external-parameter-entities";
488 factory.setFeature(FEATURE, false);
489
490 FEATURE = "http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities";
491 factory.setFeature(FEATURE, false);
492
493 // Disable external DTDs as well
494 FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
495 factory.setFeature(FEATURE, false);
496
497 // and these as well, per Timothy Morgan's 2014 paper: "XML Schema,
498 // DTD, and Entity Attacks" (see reference below)
499 factory.setXIncludeAware(false);
500 factory.setExpandEntityReferences(false);
501
502 }
503 catch (Throwable e)
504 {
505 // Ignore IllegalArgumentException and ParserConfigurationException
506 // in case the configured XML-Parser does not implement the feature.
507 }
508 return factory;
509 }
510 }