Debian Codegraph @

net/sf/saxon/functions/ResolveURI.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.functions;
9
10 import net.sf.saxon.expr.XPathContext;
11 import net.sf.saxon.om.Sequence;
12 import net.sf.saxon.om.ZeroOrOne;
13 import net.sf.saxon.trans.Err;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.value.AnyURIValue;
16 import net.sf.saxon.value.AtomicValue;
17
18 import java.io.File;
19 import java.net.MalformedURLException;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.net.URL;
23
24 /**
25 * This class supports the resolve-uri() function in XPath 2.0
26 */
27
28 public class ResolveURI extends SystemFunction {
29
30 /**
31 * Evaluate the expression
32 *
33 * @param context the dynamic evaluation context
34 * @param arguments the values of the arguments, supplied as SequenceIterators
35 * @return the result of the evaluation, in the form of a SequenceIterator
36 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs during the evaluation of the expression
37 */
38 /*@Nullable*/
39 public ZeroOrOne<AnyURIValue> call(XPathContext context, Sequence[] arguments) throws XPathException {
40 AtomicValue arg0 = (AtomicValue) arguments[0].head();
41 if (arg0 == null) {
42 return ZeroOrOne.empty();
43 }
44 String relative = arg0.getStringValue();
45 String base;
46 if (getArity() == 2) {
47 //noinspection ConstantConditions
48 base = arguments[1].head().getStringValue();
49 } else {
50 base = getStaticBaseUriString();
51 if (base == null) {
52 throw new XPathException("Base URI in static context of resolve-uri() is unknown", "FONS0005", context);
53 }
54 }
55
56 return new ZeroOrOne<>(resolve(base, relative, context));
57 }
58
59 /*@NotNull*/
60 private AnyURIValue resolve(String base, String relative, XPathContext context) throws XPathException {
61 // try {
62
63 // Rule 4: "The function resolves the relative IRI reference $relative against the base IRI $base using
64 // the algorithm defined in [RFC 3986], adapted by treating any ·character· that would not be valid in
65 // an RFC3986 URI or relative reference in the same way that RFC3986 treats unreserved characters.
66 // No percent-encoding takes place.
67
68 // We rely on the Java implementation, but the Java implementation will not handle invalid characters
69 // notably spaces. If there are spaces present, we escape them to prevent Java objecting, and then unescape
70 // them at the end. We accept the consequence that if the input contains both escaped and unescaped spaces,
71 // they will all be unescaped at the end.
72
73 boolean escaped = false;
74 if (relative.contains(" ")) {
75 relative = escapeSpaces(relative);
76 escaped = true;
77 }
78 if (base.contains(" ")) {
79 base = escapeSpaces(base);
80 escaped = true;
81 }
82
83 URI relativeURI = null;
84 try {
85 relativeURI = new URI(relative);
86 } catch (URISyntaxException e) {
87 throw new XPathException("Relative URI " + Err.wrap(relative) + " is invalid: " + e.getMessage(),
88 "FORG0002", context);
89 }
90 if (relativeURI.isAbsolute()) {
91 return new AnyURIValue(relative);
92 }
93
94 URI absoluteURI = null;
95 try {
96 absoluteURI = new URI(base);
97 } catch (URISyntaxException e) {
98 throw new XPathException("Base URI " + Err.wrap(base) + " is invalid: " + e.getMessage(),
99 "FORG0002", context);
100 }
101 if (!absoluteURI.isAbsolute()) {
102 throw new XPathException("Base URI " + Err.wrap(base) + " is not an absolute URI", "FORG0002", context);
103 }
104 if (absoluteURI.isOpaque() && !base.startsWith("jar:")) {
105 // Special-case JAR file URLs, even though non-conformant
106 throw new XPathException("Base URI " + Err.wrap(base) + " is a non-hierarchic URI", "FORG0002", context);
107 }
108 if (absoluteURI.getRawFragment() != null) {
109 throw new XPathException("Base URI " + Err.wrap(base) + " contains a fragment identifier", "FORG0002", context);
110 }
111 if (!base.startsWith("jar:") && absoluteURI.getPath() != null && absoluteURI.getPath().isEmpty()) {
112 // This deals with cases like base=http://www.example.com - changing it to http://www.example.com/
113 try {
114 absoluteURI = new URI(absoluteURI.getScheme(), absoluteURI.getUserInfo(), absoluteURI.getHost(),
115 absoluteURI.getPort(), "/", absoluteURI.getQuery(), absoluteURI.getFragment());
116 } catch (URISyntaxException e) {
117 throw new XPathException("Failed to parse JAR scheme URI " +
118 Err.wrap(absoluteURI.toASCIIString()), "FORG0002", context);
119
120 }
121 base = absoluteURI.toString();
122 }
123 URI resolved = null;
124 try {
125 resolved = makeAbsolute(relative, base);
126 } catch (URISyntaxException e) {
127 throw new XPathException(e.getMessage(), "FORG0002");
128 }
129 if (!resolved.toASCIIString().startsWith("file:////")) {
130 resolved = resolved.normalize();
131 }
132 String result = escaped ? unescapeSpaces(resolved.toString()) : resolved.toString();
133
134 // Test case XSLT3 resolve-uri-022. Java even after normalization can leave a URI with trailing "../" or ".." parts.
135 // Pragmatically, we just strip these off. This might not be enough if there are query or fragment parts, but it
136 // gets us through the test
137
138 while (result.endsWith("..")) {
139 result = result.substring(0, result.length() - 2);
140 }
141 while (result.endsWith("../")) {
142 result = result.substring(0, result.length() - 3);
143 }
144
145 return new AnyURIValue(result);
146
147 }
148
149 /**
150 * If a system ID can't be parsed as a URL, try to expand it as a relative
151 * URI using the current directory as the base URI.
152 *
153 * @param systemId the supplied systemId. Null is treated as equivalent to ""
154 * @return the systemId itself if it is a valid URL; otherwise the result of resolving
155 * the systemId as a relative file name in the current working directory; or if the
156 * current working directory is not available (e.g. in an applet) the supplied systemId
157 * unchanged (except that null is treated as "").
158 */
159
160 /*@NotNull*/
161 public static String tryToExpand(/*@Nullable*/ String systemId) {
162 if (systemId == null) {
163 systemId = "";
164 }
165 try {
166 new URL(systemId);
167 return systemId; // all is well
168 } catch (MalformedURLException err) {
169 String dir;
170 try {
171 dir = System.getProperty("user.dir");
172 } catch (Exception geterr) {
173 // this doesn't work when running an applet
174 return systemId;
175 }
176 if (!(dir.endsWith("/") || systemId.startsWith("/"))) {
177 dir = dir + '/';
178 }
179
180 try {
181 URI currentDirectoryURI = new File(dir).toURI();
182 URI baseURI = currentDirectoryURI.resolve(systemId);
183 return baseURI.toString();
184 } catch (Exception e) {
185 return systemId;
186 }
187
188 }
189 }
190
191 /**
192 * Construct an absolute URI from a relative URI and a base URI. The method uses the resolve
193 * method of the java.net.URI class, except where the base URI uses the (non-standard) "jar:" scheme,
194 * in which case the method used is <code>new URL(baseURL, relativeURL)</code>.
195 * <p>Spaces in either URI are converted to %20</p>
196 * <p>If no base URI is available, and the relative URI is not an absolute URI, then the current
197 * directory is used as a base URI.</p>
198 *
199 * @param relativeURI the relative URI. Null is permitted provided that the base URI is an absolute URI
200 * @param base the base URI. Null is permitted provided that relativeURI is an absolute URI
201 * @return the absolutized URI
202 * @throws java.net.URISyntaxException if either of the strings is not a valid URI or
203 * if the resolution fails
204 */
205
206 /*@NotNull*/
207 public static URI makeAbsolute(/*@Nullable*/ String relativeURI, /*@Nullable*/ String base) throws URISyntaxException {
208 URI absoluteURI;
209 // System.err.println("makeAbsolute " + relativeURI + " against base " + base);
210 if (relativeURI == null) {
211 if (base == null) {
212 throw new URISyntaxException("", "Relative and Base URI must not both be null");
213 }
214 absoluteURI = new URI(ResolveURI.escapeSpaces(base));
215 if (!absoluteURI.isAbsolute()) {
216 throw new URISyntaxException(base, "Relative URI not supplied, so base URI must be absolute");
217 } else {
218 return absoluteURI;
219 }
220 }
221
222 try {
223 if (base == null || base.isEmpty()) {
224 absoluteURI = new URI(relativeURI);
225 if (!absoluteURI.isAbsolute()) {
226 String expandedBase = ResolveURI.tryToExpand(base);
227 if (!expandedBase.equals(base)) { // prevent infinite recursion
228 return makeAbsolute(relativeURI, expandedBase);
229 }
230 }
231 } else if (base.startsWith("jar:") || base.startsWith("file:////")) {
232
233 // jar: URIs can't be resolved by the java.net.URI class, because they don't actually
234 // conform with the RFC standards for hierarchic URI schemes (quite apart from not being
235 // a registered URI scheme). But they seem to be widely used.
236
237 // URIs starting file://// are accepted by the java.net.URI class, they are used to
238 // represent Windows UNC filenames. However, the java.net.URI algorithm for resolving
239 // a relative URI against such a base URI fails to produce a usable UNC filename (it's not
240 // clear whether Java is implementing RFC 3986 correctly here, it depends on interpretation).
241 // So we use the java.net.URL algorithm for this case too, because it works.
242
243 try {
244 URL baseURL = new URL(base);
245 URL absoluteURL = new URL(baseURL, relativeURI);
246 absoluteURI = absoluteURL.toURI();
247 } catch (MalformedURLException err) {
248 throw new URISyntaxException(base + " " + relativeURI, err.getMessage());
249 }
250 } else if (base.startsWith("classpath:")) {
251 absoluteURI = new URI(relativeURI);
252 if (!absoluteURI.isAbsolute()) {
253 absoluteURI = new URI("classpath:" + relativeURI);
254 }
255 } else {
256 URI baseURI;
257 try {
258 baseURI = new URI(base);
259 } catch (URISyntaxException e) {
260 throw new URISyntaxException(base, "Invalid base URI: " + e.getMessage());
261 }
262 if (baseURI.getFragment() != null) {
263 int hash = base.indexOf('#');
264 if (hash >= 0) {
265 base = base.substring(0, hash);
266 }
267 try {
268 baseURI = new URI(base);
269 } catch (URISyntaxException e) {
270 throw new URISyntaxException(base, "Invalid base URI: " + e.getMessage());
271 }
272 }
273 try {
274 new URI(relativeURI); // for validation only
275 } catch (URISyntaxException e) {
276 throw new URISyntaxException(base, "Invalid relative URI: " + e.getMessage());
277 }
278 absoluteURI = relativeURI.isEmpty() ? baseURI : baseURI.resolve(relativeURI);
279 }
280 } catch (IllegalArgumentException err0) {
281 // can be thrown by resolve() when given a bad URI
282 throw new URISyntaxException(relativeURI, "Cannot resolve URI against base " + Err.wrap(base));
283 }
284
285 return absoluteURI;
286 }
287
288
289 /**
290 * Replace spaces by %20
291 *
292 * @param s the input string
293 * @return the input string with each space replaced by %20
294 */
295
296 /*@NotNull*/
297 public static String escapeSpaces(/*@NotNull*/ String s) {
298 // It's not entirely clear why we have to escape spaces by hand, and not other special characters;
299 // it's just that tests with a variety of filenames show that this approach seems to work.
300 int i = s.indexOf(' ');
301 if (i < 0) {
302 return s;
303 }
304 return (i == 0 ? "" : s.substring(0, i))
305 + "%20"
306 + (i == s.length() - 1 ? "" : escapeSpaces(s.substring(i + 1)));
307 }
308
309 /**
310 * Replace %20 by space
311 *
312 * @param uri the input uri
313 * @return the input URI with each %20 replaced by space
314 */
315
316 /*@NotNull*/
317 public static String unescapeSpaces(/*@NotNull*/ String uri) {
318 return uri.replace("%20", " ");
319 }
320
321 }
322