Debian Codegraph @

src/main/org/h2/jdbc/JdbcSQLXML.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.jdbc;
7
8 import java.io.BufferedOutputStream;
9 import java.io.Closeable;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13 import java.io.Reader;
14 import java.io.StringReader;
15 import java.io.StringWriter;
16 import java.io.Writer;
17 import java.sql.SQLException;
18 import java.sql.SQLXML;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import javax.xml.XMLConstants;
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.SAXParserFactory;
26 import javax.xml.stream.XMLInputFactory;
27 import javax.xml.stream.XMLOutputFactory;
28 import javax.xml.transform.Result;
29 import javax.xml.transform.Source;
30 import javax.xml.transform.Transformer;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.URIResolver;
33 import javax.xml.transform.dom.DOMResult;
34 import javax.xml.transform.dom.DOMSource;
35 import javax.xml.transform.sax.SAXResult;
36 import javax.xml.transform.sax.SAXSource;
37 import javax.xml.transform.sax.SAXTransformerFactory;
38 import javax.xml.transform.sax.TransformerHandler;
39 import javax.xml.transform.stax.StAXResult;
40 import javax.xml.transform.stax.StAXSource;
41 import javax.xml.transform.stream.StreamResult;
42 import javax.xml.transform.stream.StreamSource;
43
44 import org.h2.message.DbException;
45 import org.h2.message.TraceObject;
46 import org.h2.value.Value;
47 import org.w3c.dom.Node;
48 import org.xml.sax.EntityResolver;
49 import org.xml.sax.InputSource;
50 import org.xml.sax.XMLReader;
51 import org.xml.sax.helpers.DefaultHandler;
52
53 /**
54 * Represents a SQLXML value.
55 */
56 public final class JdbcSQLXML extends JdbcLob implements SQLXML {
57
58 private static final Map<String,Boolean> secureFeatureMap = new HashMap<>();
59 private static final EntityResolver NOOP_ENTITY_RESOLVER = (pubId, sysId) -> new InputSource(new StringReader(""));
60 private static final URIResolver NOOP_URI_RESOLVER = (href, base) -> new StreamSource(new StringReader(""));
61
62 static {
63 secureFeatureMap.put(XMLConstants.FEATURE_SECURE_PROCESSING, true);
64 secureFeatureMap.put("http://apache.org/xml/features/disallow-doctype-decl", true);
65 secureFeatureMap.put("http://xml.org/sax/features/external-general-entities", false);
66 secureFeatureMap.put("http://xml.org/sax/features/external-parameter-entities", false);
67 secureFeatureMap.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
68 }
69
70 private DOMResult domResult;
71
72 /**
73 * Underlying stream for SAXResult, StAXResult, and StreamResult.
74 */
75 private Closeable closable;
76
77 /**
78 * INTERNAL
79 * @param conn to use
80 * @param value for this JdbcSQLXML
81 * @param state of the LOB
82 * @param id of the trace object
83 */
84 public JdbcSQLXML(JdbcConnection conn, Value value, State state, int id) {
85 super(conn, value, state, TraceObject.SQLXML, id);
86 }
87
88 @Override
89 void checkReadable() throws SQLException, IOException {
90 checkClosed();
91 if (state == State.SET_CALLED) {
92 if (domResult != null) {
93 Node node = domResult.getNode();
94 domResult = null;
95 TransformerFactory factory = TransformerFactory.newInstance();
96 try {
97 Transformer transformer = factory.newTransformer();
98 DOMSource domSource = new DOMSource(node);
99 StringWriter stringWriter = new StringWriter();
100 StreamResult streamResult = new StreamResult(stringWriter);
101 transformer.transform(domSource, streamResult);
102 completeWrite(conn.createClob(new StringReader(stringWriter.toString()), -1));
103 } catch (Exception e) {
104 throw logAndConvert(e);
105 }
106 return;
107 } else if (closable != null) {
108 closable.close();
109 closable = null;
110 return;
111 }
112 throw DbException.getUnsupportedException("Stream setter is not yet closed.");
113 }
114 }
115
116 @Override
117 public InputStream getBinaryStream() throws SQLException {
118 return super.getBinaryStream();
119 }
120
121 @Override
122 public Reader getCharacterStream() throws SQLException {
123 return super.getCharacterStream();
124 }
125
126 @SuppressWarnings("unchecked")
127 @Override
128 public <T extends Source> T getSource(Class<T> sourceClass) throws SQLException {
129 try {
130 if (isDebugEnabled()) {
131 debugCode(
132 "getSource(" + (sourceClass != null ? sourceClass.getSimpleName() + ".class" : "null") + ')');
133 }
134 checkReadable();
135 // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
136 if (sourceClass == null || sourceClass == DOMSource.class) {
137 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
138 for (Map.Entry<String,Boolean> entry : secureFeatureMap.entrySet()) {
139 try {
140 dbf.setFeature(entry.getKey(), entry.getValue());
141 } catch (Exception ignore) {/**/}
142 }
143 dbf.setXIncludeAware(false);
144 dbf.setExpandEntityReferences(false);
145 dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
146 DocumentBuilder db = dbf.newDocumentBuilder();
147 db.setEntityResolver(NOOP_ENTITY_RESOLVER);
148 return (T) new DOMSource(db.parse(new InputSource(value.getInputStream())));
149 } else if (sourceClass == SAXSource.class) {
150 SAXParserFactory spf = SAXParserFactory.newInstance();
151 for (Map.Entry<String,Boolean> entry : secureFeatureMap.entrySet()) {
152 try {
153 spf.setFeature(entry.getKey(), entry.getValue());
154 } catch (Exception ignore) {/**/}
155 }
156 XMLReader reader = spf.newSAXParser().getXMLReader();
157 reader.setEntityResolver(NOOP_ENTITY_RESOLVER);
158 return (T) new SAXSource(reader, new InputSource(value.getInputStream()));
159 } else if (sourceClass == StAXSource.class) {
160 XMLInputFactory xif = XMLInputFactory.newInstance();
161 xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
162 xif.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
163 xif.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
164 return (T) new StAXSource(xif.createXMLStreamReader(value.getInputStream()));
165 } else if (sourceClass == StreamSource.class) {
166 TransformerFactory tf = TransformerFactory.newInstance();
167 tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
168 tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
169 tf.setURIResolver(NOOP_URI_RESOLVER);
170 tf.newTransformer().transform(new StreamSource(value.getInputStream()),
171 new SAXResult(new DefaultHandler()));
172 return (T) new StreamSource(value.getInputStream());
173 }
174 throw unsupported(sourceClass.getName());
175 } catch (Exception e) {
176 throw logAndConvert(e);
177 }
178 }
179
180 @Override
181 public String getString() throws SQLException {
182 try {
183 debugCodeCall("getString");
184 checkReadable();
185 return value.getString();
186 } catch (Exception e) {
187 throw logAndConvert(e);
188 }
189 }
190
191 @Override
192 public OutputStream setBinaryStream() throws SQLException {
193 try {
194 debugCodeCall("setBinaryStream");
195 checkEditable();
196 state = State.SET_CALLED;
197 return new BufferedOutputStream(setClobOutputStreamImpl());
198 } catch (Exception e) {
199 throw logAndConvert(e);
200 }
201 }
202
203 @Override
204 public Writer setCharacterStream() throws SQLException {
205 try {
206 debugCodeCall("setCharacterStream");
207 checkEditable();
208 state = State.SET_CALLED;
209 return setCharacterStreamImpl();
210 } catch (Exception e) {
211 throw logAndConvert(e);
212 }
213 }
214
215 @SuppressWarnings("unchecked")
216 @Override
217 public <T extends Result> T setResult(Class<T> resultClass) throws SQLException {
218 try {
219 if (isDebugEnabled()) {
220 debugCode(
221 "setResult(" + (resultClass != null ? resultClass.getSimpleName() + ".class" : "null") + ')');
222 }
223 checkEditable();
224 if (resultClass == null || resultClass == DOMResult.class) {
225 domResult = new DOMResult();
226 state = State.SET_CALLED;
227 return (T) domResult;
228 } else if (resultClass == SAXResult.class) {
229 SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
230 TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();
231 Writer writer = setCharacterStreamImpl();
232 transformerHandler.setResult(new StreamResult(writer));
233 SAXResult saxResult = new SAXResult(transformerHandler);
234 closable = writer;
235 state = State.SET_CALLED;
236 return (T) saxResult;
237 } else if (resultClass == StAXResult.class) {
238 XMLOutputFactory xof = XMLOutputFactory.newInstance();
239 Writer writer = setCharacterStreamImpl();
240 StAXResult staxResult = new StAXResult(xof.createXMLStreamWriter(writer));
241 closable = writer;
242 state = State.SET_CALLED;
243 return (T) staxResult;
244 } else if (StreamResult.class.equals(resultClass)) {
245 Writer writer = setCharacterStreamImpl();
246 StreamResult streamResult = new StreamResult(writer);
247 closable = writer;
248 state = State.SET_CALLED;
249 return (T) streamResult;
250 }
251 throw unsupported(resultClass.getName());
252 } catch (Exception e) {
253 throw logAndConvert(e);
254 }
255 }
256
257 @Override
258 public void setString(String value) throws SQLException {
259 try {
260 if (isDebugEnabled()) {
261 debugCodeCall("getSource", value);
262 }
263 checkEditable();
264 completeWrite(conn.createClob(new StringReader(value), -1));
265 } catch (Exception e) {
266 throw logAndConvert(e);
267 }
268 }
269
270 }