1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.net; 28 29 import java.io.IOException; 30 import java.io.InvalidObjectException; 31 import java.io.ObjectInputStream; 32 import java.io.ObjectOutputStream; 33 import java.io.Serializable; 34 import java.nio.ByteBuffer; 35 import java.nio.CharBuffer; 36 import java.nio.charset.CharsetDecoder; 37 import java.nio.charset.CoderResult; 38 import java.nio.charset.CodingErrorAction; 39 import java.nio.charset.CharacterCodingException; 40 import java.text.Normalizer; 41 import sun.nio.cs.ThreadLocalCoders; 42 43 import java.lang.Character; // for javadoc 44 import java.lang.NullPointerException; // for javadoc 45 46 47 /** 48 * Represents a Uniform Resource Identifier (URI) reference. 49 * 50 * <p> Aside from some minor deviations noted below, an instance of this 51 * class represents a URI reference as defined by 52 * <a href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC 2396: Uniform 53 * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a 54 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC 2732: Format for 55 * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format 56 * also supports scope_ids. The syntax and usage of scope_ids is described 57 * <a href="Inet6Address.html#scoped">here</a>. 58 * This class provides constructors for creating URI instances from 59 * their components or by parsing their string forms, methods for accessing the 60 * various components of an instance, and methods for normalizing, resolving, 61 * and relativizing URI instances. Instances of this class are immutable. 62 * 63 * 64 * <h4> URI syntax and components </h4> 65 * 66 * At the highest level a URI reference (hereinafter simply "URI") in string 67 * form has the syntax 68 * 69 * <blockquote> 70 * [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>] 71 * </blockquote> 72 * 73 * where square brackets [...] delineate optional components and the characters 74 * <tt><b>:</b></tt> and <tt><b>#</b></tt> stand for themselves. 75 * 76 * <p> An <i>absolute</i> URI specifies a scheme; a URI that is not absolute is 77 * said to be <i>relative</i>. URIs are also classified according to whether 78 * they are <i>opaque</i> or <i>hierarchical</i>. 79 * 80 * <p> An <i>opaque</i> URI is an absolute URI whose scheme-specific part does 81 * not begin with a slash character (<tt>'/'</tt>). Opaque URIs are not 82 * subject to further parsing. Some examples of opaque URIs are: 83 * 84 * <blockquote><table cellpadding=0 cellspacing=0 summary="layout"> 85 * <tr><td><tt>mailto:java-net@java.sun.com</tt><td></tr> 86 * <tr><td><tt>news:comp.lang.java</tt><td></tr> 87 * <tr><td><tt>urn:isbn:096139210x</tt></td></tr> 88 * </table></blockquote> 89 * 90 * <p> A <i>hierarchical</i> URI is either an absolute URI whose 91 * scheme-specific part begins with a slash character, or a relative URI, that 92 * is, a URI that does not specify a scheme. Some examples of hierarchical 93 * URIs are: 94 * 95 * <blockquote> 96 * <tt>http://java.sun.com/j2se/1.3/</tt><br> 97 * <tt>docs/guide/collections/designfaq.html#28</tt><br> 98 * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java</tt><br> 99 * <tt>file:///~/calendar</tt> 100 * </blockquote> 101 * 102 * <p> A hierarchical URI is subject to further parsing according to the syntax 103 * 104 * <blockquote> 105 * [<i>scheme</i><tt><b>:</b></tt>][<tt><b>//</b></tt><i>authority</i>][<i>path</i>][<tt><b>?</b></tt><i>query</i>][<tt><b>#</b></tt><i>fragment</i>] 106 * </blockquote> 107 * 108 * where the characters <tt><b>:</b></tt>, <tt><b>/</b></tt>, 109 * <tt><b>?</b></tt>, and <tt><b>#</b></tt> stand for themselves. The 110 * scheme-specific part of a hierarchical URI consists of the characters 111 * between the scheme and fragment components. 112 * 113 * <p> The authority component of a hierarchical URI is, if specified, either 114 * <i>server-based</i> or <i>registry-based</i>. A server-based authority 115 * parses according to the familiar syntax 116 * 117 * <blockquote> 118 * [<i>user-info</i><tt><b>@</b></tt>]<i>host</i>[<tt><b>:</b></tt><i>port</i>] 119 * </blockquote> 120 * 121 * where the characters <tt><b>@</b></tt> and <tt><b>:</b></tt> stand for 122 * themselves. Nearly all URI schemes currently in use are server-based. An 123 * authority component that does not parse in this way is considered to be 124 * registry-based. 125 * 126 * <p> The path component of a hierarchical URI is itself said to be absolute 127 * if it begins with a slash character (<tt>'/'</tt>); otherwise it is 128 * relative. The path of a hierarchical URI that is either absolute or 129 * specifies an authority is always absolute. 130 * 131 * <p> All told, then, a URI instance has the following nine components: 132 * 133 * <blockquote><table summary="Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment"> 134 * <tr><th><i>Component</i></th><th><i>Type</i></th></tr> 135 * <tr><td>scheme</td><td><tt>String</tt></td></tr> 136 * <tr><td>scheme-specific-part </td><td><tt>String</tt></td></tr> 137 * <tr><td>authority</td><td><tt>String</tt></td></tr> 138 * <tr><td>user-info</td><td><tt>String</tt></td></tr> 139 * <tr><td>host</td><td><tt>String</tt></td></tr> 140 * <tr><td>port</td><td><tt>int</tt></td></tr> 141 * <tr><td>path</td><td><tt>String</tt></td></tr> 142 * <tr><td>query</td><td><tt>String</tt></td></tr> 143 * <tr><td>fragment</td><td><tt>String</tt></td></tr> 144 * </table></blockquote> 145 * 146 * In a given instance any particular component is either <i>undefined</i> or 147 * <i>defined</i> with a distinct value. Undefined string components are 148 * represented by <tt>null</tt>, while undefined integer components are 149 * represented by <tt>-1</tt>. A string component may be defined to have the 150 * empty string as its value; this is not equivalent to that component being 151 * undefined. 152 * 153 * <p> Whether a particular component is or is not defined in an instance 154 * depends upon the type of the URI being represented. An absolute URI has a 155 * scheme component. An opaque URI has a scheme, a scheme-specific part, and 156 * possibly a fragment, but has no other components. A hierarchical URI always 157 * has a path (though it may be empty) and a scheme-specific-part (which at 158 * least contains the path), and may have any of the other components. If the 159 * authority component is present and is server-based then the host component 160 * will be defined and the user-information and port components may be defined. 161 * 162 * 163 * <h4> Operations on URI instances </h4> 164 * 165 * The key operations supported by this class are those of 166 * <i>normalization</i>, <i>resolution</i>, and <i>relativization</i>. 167 * 168 * <p> <i>Normalization</i> is the process of removing unnecessary <tt>"."</tt> 169 * and <tt>".."</tt> segments from the path component of a hierarchical URI. 170 * Each <tt>"."</tt> segment is simply removed. A <tt>".."</tt> segment is 171 * removed only if it is preceded by a non-<tt>".."</tt> segment. 172 * Normalization has no effect upon opaque URIs. 173 * 174 * <p> <i>Resolution</i> is the process of resolving one URI against another, 175 * <i>base</i> URI. The resulting URI is constructed from components of both 176 * URIs in the manner specified by RFC 2396, taking components from the 177 * base URI for those not specified in the original. For hierarchical URIs, 178 * the path of the original is resolved against the path of the base and then 179 * normalized. The result, for example, of resolving 180 * 181 * <blockquote> 182 * <tt>docs/guide/collections/designfaq.html#28 </tt>(1) 183 * </blockquote> 184 * 185 * against the base URI <tt>http://java.sun.com/j2se/1.3/</tt> is the result 186 * URI 187 * 188 * <blockquote> 189 * <tt>http://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28</tt> 190 * </blockquote> 191 * 192 * Resolving the relative URI 193 * 194 * <blockquote> 195 * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java </tt>(2) 196 * </blockquote> 197 * 198 * against this result yields, in turn, 199 * 200 * <blockquote> 201 * <tt>http://java.sun.com/j2se/1.3/demo/jfc/SwingSet2/src/SwingSet2.java</tt> 202 * </blockquote> 203 * 204 * Resolution of both absolute and relative URIs, and of both absolute and 205 * relative paths in the case of hierarchical URIs, is supported. Resolving 206 * the URI <tt>file:///~calendar</tt> against any other URI simply yields the 207 * original URI, since it is absolute. Resolving the relative URI (2) above 208 * against the relative base URI (1) yields the normalized, but still relative, 209 * URI 210 * 211 * <blockquote> 212 * <tt>demo/jfc/SwingSet2/src/SwingSet2.java</tt> 213 * </blockquote> 214 * 215 * <p> <i>Relativization</i>, finally, is the inverse of resolution: For any 216 * two normalized URIs <i>u</i> and <i>v</i>, 217 * 218 * <blockquote> 219 * <i>u</i><tt>.relativize(</tt><i>u</i><tt>.resolve(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt> and<br> 220 * <i>u</i><tt>.resolve(</tt><i>u</i><tt>.relativize(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt> .<br> 221 * </blockquote> 222 * 223 * This operation is often useful when constructing a document containing URIs 224 * that must be made relative to the base URI of the document wherever 225 * possible. For example, relativizing the URI 226 * 227 * <blockquote> 228 * <tt>http://java.sun.com/j2se/1.3/docs/guide/index.html</tt> 229 * </blockquote> 230 * 231 * against the base URI 232 * 233 * <blockquote> 234 * <tt>http://java.sun.com/j2se/1.3</tt> 235 * </blockquote> 236 * 237 * yields the relative URI <tt>docs/guide/index.html</tt>. 238 * 239 * 240 * <h4> Character categories </h4> 241 * 242 * RFC 2396 specifies precisely which characters are permitted in the 243 * various components of a URI reference. The following categories, most of 244 * which are taken from that specification, are used below to describe these 245 * constraints: 246 * 247 * <blockquote><table cellspacing=2 summary="Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other"> 248 * <tr><th valign=top><i>alpha</i></th> 249 * <td>The US-ASCII alphabetic characters, 250 * <tt>'A'</tt> through <tt>'Z'</tt> 251 * and <tt>'a'</tt> through <tt>'z'</tt></td></tr> 252 * <tr><th valign=top><i>digit</i></th> 253 * <td>The US-ASCII decimal digit characters, 254 * <tt>'0'</tt> through <tt>'9'</tt></td></tr> 255 * <tr><th valign=top><i>alphanum</i></th> 256 * <td>All <i>alpha</i> and <i>digit</i> characters</td></tr> 257 * <tr><th valign=top><i>unreserved</i> </th> 258 * <td>All <i>alphanum</i> characters together with those in the string 259 * <tt>"_-!.~'()*"</tt></td></tr> 260 * <tr><th valign=top><i>punct</i></th> 261 * <td>The characters in the string <tt>",;:$&+="</tt></td></tr> 262 * <tr><th valign=top><i>reserved</i></th> 263 * <td>All <i>punct</i> characters together with those in the string 264 * <tt>"?/[]@"</tt></td></tr> 265 * <tr><th valign=top><i>escaped</i></th> 266 * <td>Escaped octets, that is, triplets consisting of the percent 267 * character (<tt>'%'</tt>) followed by two hexadecimal digits 268 * (<tt>'0'</tt>-<tt>'9'</tt>, <tt>'A'</tt>-<tt>'F'</tt>, and 269 * <tt>'a'</tt>-<tt>'f'</tt>)</td></tr> 270 * <tr><th valign=top><i>other</i></th> 271 * <td>The Unicode characters that are not in the US-ASCII character set, 272 * are not control characters (according to the {@link 273 * java.lang.Character#isISOControl(char) Character.isISOControl} 274 * method), and are not space characters (according to the {@link 275 * java.lang.Character#isSpaceChar(char) Character.isSpaceChar} 276 * method) <i>(<b>Deviation from RFC 2396</b>, which is 277 * limited to US-ASCII)</i></td></tr> 278 * </table></blockquote> 279 * 280 * <p><a name="legal-chars"></a> The set of all legal URI characters consists of 281 * the <i>unreserved</i>, <i>reserved</i>, <i>escaped</i>, and <i>other</i> 282 * characters. 283 * 284 * 285 * <h4> Escaped octets, quotation, encoding, and decoding </h4> 286 * 287 * RFC 2396 allows escaped octets to appear in the user-info, path, query, and 288 * fragment components. Escaping serves two purposes in URIs: 289 * 290 * <ul> 291 * 292 * <li><p> To <i>encode</i> non-US-ASCII characters when a URI is required to 293 * conform strictly to RFC 2396 by not containing any <i>other</i> 294 * characters. </p></li> 295 * 296 * <li><p> To <i>quote</i> characters that are otherwise illegal in a 297 * component. The user-info, path, query, and fragment components differ 298 * slightly in terms of which characters are considered legal and illegal. 299 * </p></li> 300 * 301 * </ul> 302 * 303 * These purposes are served in this class by three related operations: 304 * 305 * <ul> 306 * 307 * <li><p><a name="encode"></a> A character is <i>encoded</i> by replacing it 308 * with the sequence of escaped octets that represent that character in the 309 * UTF-8 character set. The Euro currency symbol (<tt>'\u20AC'</tt>), 310 * for example, is encoded as <tt>"%E2%82%AC"</tt>. <i>(<b>Deviation from 311 * RFC 2396</b>, which does not specify any particular character 312 * set.)</i> </p></li> 313 * 314 * <li><p><a name="quote"></a> An illegal character is <i>quoted</i> simply by 315 * encoding it. The space character, for example, is quoted by replacing it 316 * with <tt>"%20"</tt>. UTF-8 contains US-ASCII, hence for US-ASCII 317 * characters this transformation has exactly the effect required by 318 * RFC 2396. </p></li> 319 * 320 * <li><p><a name="decode"></a> 321 * A sequence of escaped octets is <i>decoded</i> by 322 * replacing it with the sequence of characters that it represents in the 323 * UTF-8 character set. UTF-8 contains US-ASCII, hence decoding has the 324 * effect of de-quoting any quoted US-ASCII characters as well as that of 325 * decoding any encoded non-US-ASCII characters. If a <a 326 * href="../nio/charset/CharsetDecoder.html#ce">decoding error</a> occurs 327 * when decoding the escaped octets then the erroneous octets are replaced by 328 * <tt>'\uFFFD'</tt>, the Unicode replacement character. </p></li> 329 * 330 * </ul> 331 * 332 * These operations are exposed in the constructors and methods of this class 333 * as follows: 334 * 335 * <ul> 336 * 337 * <li><p> The {@link #URI(java.lang.String) <code>single-argument 338 * constructor</code>} requires any illegal characters in its argument to be 339 * quoted and preserves any escaped octets and <i>other</i> characters that 340 * are present. </p></li> 341 * 342 * <li><p> The {@link 343 * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String) 344 * <code>multi-argument constructors</code>} quote illegal characters as 345 * required by the components in which they appear. The percent character 346 * (<tt>'%'</tt>) is always quoted by these constructors. Any <i>other</i> 347 * characters are preserved. </p></li> 348 * 349 * <li><p> The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath() 350 * getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment() 351 * getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link 352 * #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the 353 * values of their corresponding components in raw form, without interpreting 354 * any escaped octets. The strings returned by these methods may contain 355 * both escaped octets and <i>other</i> characters, and will not contain any 356 * illegal characters. </p></li> 357 * 358 * <li><p> The {@link #getUserInfo() getUserInfo}, {@link #getPath() 359 * getPath}, {@link #getQuery() getQuery}, {@link #getFragment() 360 * getFragment}, {@link #getAuthority() getAuthority}, and {@link 361 * #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped 362 * octets in their corresponding components. The strings returned by these 363 * methods may contain both <i>other</i> characters and illegal characters, 364 * and will not contain any escaped octets. </p></li> 365 * 366 * <li><p> The {@link #toString() toString} method returns a URI string with 367 * all necessary quotation but which may contain <i>other</i> characters. 368 * </p></li> 369 * 370 * <li><p> The {@link #toASCIIString() toASCIIString} method returns a fully 371 * quoted and encoded URI string that does not contain any <i>other</i> 372 * characters. </p></li> 373 * 374 * </ul> 375 * 376 * 377 * <h4> Identities </h4> 378 * 379 * For any URI <i>u</i>, it is always the case that 380 * 381 * <blockquote> 382 * <tt>new URI(</tt><i>u</i><tt>.toString()).equals(</tt><i>u</i><tt>)</tt> . 383 * </blockquote> 384 * 385 * For any URI <i>u</i> that does not contain redundant syntax such as two 386 * slashes before an empty authority (as in <tt>file:///tmp/</tt> ) or a 387 * colon following a host name but no port (as in 388 * <tt>http://java.sun.com:</tt> ), and that does not encode characters 389 * except those that must be quoted, the following identities also hold: 390 * 391 * <blockquote> 392 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br> 393 * </tt><i>u</i><tt>.getSchemeSpecificPart(),<br> 394 * </tt><i>u</i><tt>.getFragment())<br> 395 * .equals(</tt><i>u</i><tt>)</tt> 396 * </blockquote> 397 * 398 * in all cases, 399 * 400 * <blockquote> 401 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br> 402 * </tt><i>u</i><tt>.getUserInfo(), </tt><i>u</i><tt>.getAuthority(),<br> 403 * </tt><i>u</i><tt>.getPath(), </tt><i>u</i><tt>.getQuery(),<br> 404 * </tt><i>u</i><tt>.getFragment())<br> 405 * .equals(</tt><i>u</i><tt>)</tt> 406 * </blockquote> 407 * 408 * if <i>u</i> is hierarchical, and 409 * 410 * <blockquote> 411 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br> 412 * </tt><i>u</i><tt>.getUserInfo(), </tt><i>u</i><tt>.getHost(), </tt><i>u</i><tt>.getPort(),<br> 413 * </tt><i>u</i><tt>.getPath(), </tt><i>u</i><tt>.getQuery(),<br> 414 * </tt><i>u</i><tt>.getFragment())<br> 415 * .equals(</tt><i>u</i><tt>)</tt> 416 * </blockquote> 417 * 418 * if <i>u</i> is hierarchical and has either no authority or a server-based 419 * authority. 420 * 421 * 422 * <h4> URIs, URLs, and URNs </h4> 423 * 424 * A URI is a uniform resource <i>identifier</i> while a URL is a uniform 425 * resource <i>locator</i>. Hence every URL is a URI, abstractly speaking, but 426 * not every URI is a URL. This is because there is another subcategory of 427 * URIs, uniform resource <i>names</i> (URNs), which name resources but do not 428 * specify how to locate them. The <tt>mailto</tt>, <tt>news</tt>, and 429 * <tt>isbn</tt> URIs shown above are examples of URNs. 430 * 431 * <p> The conceptual distinction between URIs and URLs is reflected in the 432 * differences between this class and the {@link URL} class. 433 * 434 * <p> An instance of this class represents a URI reference in the syntactic 435 * sense defined by RFC 2396. A URI may be either absolute or relative. 436 * A URI string is parsed according to the generic syntax without regard to the 437 * scheme, if any, that it specifies. No lookup of the host, if any, is 438 * performed, and no scheme-dependent stream handler is constructed. Equality, 439 * hashing, and comparison are defined strictly in terms of the character 440 * content of the instance. In other words, a URI instance is little more than 441 * a structured string that supports the syntactic, scheme-independent 442 * operations of comparison, normalization, resolution, and relativization. 443 * 444 * <p> An instance of the {@link URL} class, by contrast, represents the 445 * syntactic components of a URL together with some of the information required 446 * to access the resource that it describes. A URL must be absolute, that is, 447 * it must always specify a scheme. A URL string is parsed according to its 448 * scheme. A stream handler is always established for a URL, and in fact it is 449 * impossible to create a URL instance for a scheme for which no handler is 450 * available. Equality and hashing depend upon both the scheme and the 451 * Internet address of the host, if any; comparison is not defined. In other 452 * words, a URL is a structured string that supports the syntactic operation of 453 * resolution as well as the network I/O operations of looking up the host and 454 * opening a connection to the specified resource. 455 * 456 * 457 * @author Mark Reinhold 458 * @since 1.4 459 * 460 * @see <a href="http://www.ietf.org/rfc/rfc2279.txt">RFC 2279: UTF-8, a transformation format of ISO 10646</a> 461 * @see <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373: IPv6 Addressing Architecture</a> 462 * @see <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax</a> 463 * @see <a href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732: Format for Literal IPv6 Addresses in URLs</a> 464 */ 465 // Android changed: Reformat @see links. 466 public final class URI 467 implements Comparable<URI>, Serializable 468 { 469 // Note: Comments containing the word "ASSERT" indicate places where a 470 // throw of an InternalError should be replaced by an appropriate assertion 471 // statement once asserts are enabled in the build. 472 473 static final long serialVersionUID = -6052424284110960213L; 474 475 476 // -- Properties and components of this instance -- 477 478 // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>] 479 private transient String scheme; // null ==> relative URI 480 private transient String fragment; 481 482 // Hierarchical URI components: [//<authority>]<path>[?<query>] 483 private transient String authority; // Registry or server 484 485 // Server-based authority: [<userInfo>@]<host>[:<port>] 486 private transient String userInfo; 487 private transient String host; // null ==> registry-based 488 private transient int port = -1; // -1 ==> undefined 489 490 // Remaining components of hierarchical URIs 491 private transient String path; // null ==> opaque 492 private transient String query; 493 494 // The remaining fields may be computed on demand 495 496 private volatile transient String schemeSpecificPart; 497 private volatile transient int hash; // Zero ==> undefined 498 499 private volatile transient String decodedUserInfo = null; 500 private volatile transient String decodedAuthority = null; 501 private volatile transient String decodedPath = null; 502 private volatile transient String decodedQuery = null; 503 private volatile transient String decodedFragment = null; 504 private volatile transient String decodedSchemeSpecificPart = null; 505 506 /** 507 * The string form of this URI. 508 * 509 * @serial 510 */ 511 private volatile String string; // The only serializable field 512 513 514 515 // -- Constructors and factories -- 516 URI()517 private URI() { } // Used internally 518 519 /** 520 * Constructs a URI by parsing the given string. 521 * 522 * <p> This constructor parses the given string exactly as specified by the 523 * grammar in <a 524 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>, 525 * Appendix A, <b><i>except for the following deviations:</i></b> </p> 526 * 527 * <ul type=disc> 528 * 529 * <li><p> An empty authority component is permitted as long as it is 530 * followed by a non-empty path, a query component, or a fragment 531 * component. This allows the parsing of URIs such as 532 * <tt>"file:///foo/bar"</tt>, which seems to be the intent of 533 * RFC 2396 although the grammar does not permit it. If the 534 * authority component is empty then the user-information, host, and port 535 * components are undefined. </p></li> 536 * 537 * <li><p> Empty relative paths are permitted; this seems to be the 538 * intent of RFC 2396 although the grammar does not permit it. The 539 * primary consequence of this deviation is that a standalone fragment 540 * such as <tt>"#foo"</tt> parses as a relative URI with an empty path 541 * and the given fragment, and can be usefully <a 542 * href="#resolve-frag">resolved</a> against a base URI. 543 * 544 * <li><p> IPv4 addresses in host components are parsed rigorously, as 545 * specified by <a 546 * href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732</a>: Each 547 * element of a dotted-quad address must contain no more than three 548 * decimal digits. Each element is further constrained to have a value 549 * no greater than 255. </p></li> 550 * 551 * <li> <p> Hostnames in host components that comprise only a single 552 * domain label are permitted to start with an <i>alphanum</i> 553 * character. This seems to be the intent of <a 554 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a> 555 * section 3.2.2 although the grammar does not permit it. The 556 * consequence of this deviation is that the authority component of a 557 * hierarchical URI such as <tt>s://123</tt>, will parse as a server-based 558 * authority. </p></li> 559 * 560 * <li><p> IPv6 addresses are permitted for the host component. An IPv6 561 * address must be enclosed in square brackets (<tt>'['</tt> and 562 * <tt>']'</tt>) as specified by <a 563 * href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732</a>. The 564 * IPv6 address itself must parse according to <a 565 * href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a>. IPv6 566 * addresses are further constrained to describe no more than sixteen 567 * bytes of address information, a constraint implicit in RFC 2373 568 * but not expressible in the grammar. </p></li> 569 * 570 * <li><p> Characters in the <i>other</i> category are permitted wherever 571 * RFC 2396 permits <i>escaped</i> octets, that is, in the 572 * user-information, path, query, and fragment components, as well as in 573 * the authority component if the authority is registry-based. This 574 * allows URIs to contain Unicode characters beyond those in the US-ASCII 575 * character set. </p></li> 576 * 577 * </ul> 578 * 579 * @param str The string to be parsed into a URI 580 * 581 * @throws NullPointerException 582 * If <tt>str</tt> is <tt>null</tt> 583 * 584 * @throws URISyntaxException 585 * If the given string violates RFC 2396, as augmented 586 * by the above deviations 587 */ URI(String str)588 public URI(String str) throws URISyntaxException { 589 new Parser(str).parse(false); 590 } 591 592 /** 593 * Constructs a hierarchical URI from the given components. 594 * 595 * <p> If a scheme is given then the path, if also given, must either be 596 * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a 597 * component of the new URI may be left undefined by passing <tt>null</tt> 598 * for the corresponding parameter or, in the case of the <tt>port</tt> 599 * parameter, by passing <tt>-1</tt>. 600 * 601 * <p> This constructor first builds a URI string from the given components 602 * according to the rules specified in <a 603 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>, 604 * section 5.2, step 7: </p> 605 * 606 * <ol> 607 * 608 * <li><p> Initially, the result string is empty. </p></li> 609 * 610 * <li><p> If a scheme is given then it is appended to the result, 611 * followed by a colon character (<tt>':'</tt>). </p></li> 612 * 613 * <li><p> If user information, a host, or a port are given then the 614 * string <tt>"//"</tt> is appended. </p></li> 615 * 616 * <li><p> If user information is given then it is appended, followed by 617 * a commercial-at character (<tt>'@'</tt>). Any character not in the 618 * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i> 619 * categories is <a href="#quote">quoted</a>. </p></li> 620 * 621 * <li><p> If a host is given then it is appended. If the host is a 622 * literal IPv6 address but is not enclosed in square brackets 623 * (<tt>'['</tt> and <tt>']'</tt>) then the square brackets are added. 624 * </p></li> 625 * 626 * <li><p> If a port number is given then a colon character 627 * (<tt>':'</tt>) is appended, followed by the port number in decimal. 628 * </p></li> 629 * 630 * <li><p> If a path is given then it is appended. Any character not in 631 * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i> 632 * categories, and not equal to the slash character (<tt>'/'</tt>) or the 633 * commercial-at character (<tt>'@'</tt>), is quoted. </p></li> 634 * 635 * <li><p> If a query is given then a question-mark character 636 * (<tt>'?'</tt>) is appended, followed by the query. Any character that 637 * is not a <a href="#legal-chars">legal URI character</a> is quoted. 638 * </p></li> 639 * 640 * <li><p> Finally, if a fragment is given then a hash character 641 * (<tt>'#'</tt>) is appended, followed by the fragment. Any character 642 * that is not a legal URI character is quoted. </p></li> 643 * 644 * </ol> 645 * 646 * <p> The resulting URI string is then parsed as if by invoking the {@link 647 * #URI(String)} constructor and then invoking the {@link 648 * #parseServerAuthority()} method upon the result; this may cause a {@link 649 * URISyntaxException} to be thrown. </p> 650 * 651 * @param scheme Scheme name 652 * @param userInfo User name and authorization information 653 * @param host Host name 654 * @param port Port number 655 * @param path Path 656 * @param query Query 657 * @param fragment Fragment 658 * 659 * @throws URISyntaxException 660 * If both a scheme and a path are given but the path is relative, 661 * if the URI string constructed from the given components violates 662 * RFC 2396, or if the authority component of the string is 663 * present but cannot be parsed as a server-based authority 664 */ URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment)665 public URI(String scheme, 666 String userInfo, String host, int port, 667 String path, String query, String fragment) 668 throws URISyntaxException 669 { 670 String s = toString(scheme, null, 671 null, userInfo, host, port, 672 path, query, fragment); 673 checkPath(s, scheme, path); 674 new Parser(s).parse(true); 675 } 676 677 /** 678 * Constructs a hierarchical URI from the given components. 679 * 680 * <p> If a scheme is given then the path, if also given, must either be 681 * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a 682 * component of the new URI may be left undefined by passing <tt>null</tt> 683 * for the corresponding parameter. 684 * 685 * <p> This constructor first builds a URI string from the given components 686 * according to the rules specified in <a 687 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>, 688 * section 5.2, step 7: </p> 689 * 690 * <ol> 691 * 692 * <li><p> Initially, the result string is empty. </p></li> 693 * 694 * <li><p> If a scheme is given then it is appended to the result, 695 * followed by a colon character (<tt>':'</tt>). </p></li> 696 * 697 * <li><p> If an authority is given then the string <tt>"//"</tt> is 698 * appended, followed by the authority. If the authority contains a 699 * literal IPv6 address then the address must be enclosed in square 700 * brackets (<tt>'['</tt> and <tt>']'</tt>). Any character not in the 701 * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i> 702 * categories, and not equal to the commercial-at character 703 * (<tt>'@'</tt>), is <a href="#quote">quoted</a>. </p></li> 704 * 705 * <li><p> If a path is given then it is appended. Any character not in 706 * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i> 707 * categories, and not equal to the slash character (<tt>'/'</tt>) or the 708 * commercial-at character (<tt>'@'</tt>), is quoted. </p></li> 709 * 710 * <li><p> If a query is given then a question-mark character 711 * (<tt>'?'</tt>) is appended, followed by the query. Any character that 712 * is not a <a href="#legal-chars">legal URI character</a> is quoted. 713 * </p></li> 714 * 715 * <li><p> Finally, if a fragment is given then a hash character 716 * (<tt>'#'</tt>) is appended, followed by the fragment. Any character 717 * that is not a legal URI character is quoted. </p></li> 718 * 719 * </ol> 720 * 721 * <p> The resulting URI string is then parsed as if by invoking the {@link 722 * #URI(String)} constructor and then invoking the {@link 723 * #parseServerAuthority()} method upon the result; this may cause a {@link 724 * URISyntaxException} to be thrown. </p> 725 * 726 * @param scheme Scheme name 727 * @param authority Authority 728 * @param path Path 729 * @param query Query 730 * @param fragment Fragment 731 * 732 * @throws URISyntaxException 733 * If both a scheme and a path are given but the path is relative, 734 * if the URI string constructed from the given components violates 735 * RFC 2396, or if the authority component of the string is 736 * present but cannot be parsed as a server-based authority 737 */ URI(String scheme, String authority, String path, String query, String fragment)738 public URI(String scheme, 739 String authority, 740 String path, String query, String fragment) 741 throws URISyntaxException 742 { 743 String s = toString(scheme, null, 744 authority, null, null, -1, 745 path, query, fragment); 746 checkPath(s, scheme, path); 747 new Parser(s).parse(false); 748 } 749 750 /** 751 * Constructs a hierarchical URI from the given components. 752 * 753 * <p> A component may be left undefined by passing <tt>null</tt>. 754 * 755 * <p> This convenience constructor works as if by invoking the 756 * seven-argument constructor as follows: 757 * 758 * <blockquote><tt> 759 * new {@link #URI(String, String, String, int, String, String, String) 760 * URI}(scheme, null, host, -1, path, null, fragment); 761 * </tt></blockquote> 762 * 763 * @param scheme Scheme name 764 * @param host Host name 765 * @param path Path 766 * @param fragment Fragment 767 * 768 * @throws URISyntaxException 769 * If the URI string constructed from the given components 770 * violates RFC 2396 771 */ URI(String scheme, String host, String path, String fragment)772 public URI(String scheme, String host, String path, String fragment) 773 throws URISyntaxException 774 { 775 this(scheme, null, host, -1, path, null, fragment); 776 } 777 778 /** 779 * Constructs a URI from the given components. 780 * 781 * <p> A component may be left undefined by passing <tt>null</tt>. 782 * 783 * <p> This constructor first builds a URI in string form using the given 784 * components as follows: </p> 785 * 786 * <ol> 787 * 788 * <li><p> Initially, the result string is empty. </p></li> 789 * 790 * <li><p> If a scheme is given then it is appended to the result, 791 * followed by a colon character (<tt>':'</tt>). </p></li> 792 * 793 * <li><p> If a scheme-specific part is given then it is appended. Any 794 * character that is not a <a href="#legal-chars">legal URI character</a> 795 * is <a href="#quote">quoted</a>. </p></li> 796 * 797 * <li><p> Finally, if a fragment is given then a hash character 798 * (<tt>'#'</tt>) is appended to the string, followed by the fragment. 799 * Any character that is not a legal URI character is quoted. </p></li> 800 * 801 * </ol> 802 * 803 * <p> The resulting URI string is then parsed in order to create the new 804 * URI instance as if by invoking the {@link #URI(String)} constructor; 805 * this may cause a {@link URISyntaxException} to be thrown. </p> 806 * 807 * @param scheme Scheme name 808 * @param ssp Scheme-specific part 809 * @param fragment Fragment 810 * 811 * @throws URISyntaxException 812 * If the URI string constructed from the given components 813 * violates RFC 2396 814 */ URI(String scheme, String ssp, String fragment)815 public URI(String scheme, String ssp, String fragment) 816 throws URISyntaxException 817 { 818 new Parser(toString(scheme, ssp, 819 null, null, null, -1, 820 null, null, fragment)) 821 .parse(false); 822 } 823 824 /** 825 * Creates a URI by parsing the given string. 826 * 827 * <p> This convenience factory method works as if by invoking the {@link 828 * #URI(String)} constructor; any {@link URISyntaxException} thrown by the 829 * constructor is caught and wrapped in a new {@link 830 * IllegalArgumentException} object, which is then thrown. 831 * 832 * <p> This method is provided for use in situations where it is known that 833 * the given string is a legal URI, for example for URI constants declared 834 * within in a program, and so it would be considered a programming error 835 * for the string not to parse as such. The constructors, which throw 836 * {@link URISyntaxException} directly, should be used situations where a 837 * URI is being constructed from user input or from some other source that 838 * may be prone to errors. </p> 839 * 840 * @param str The string to be parsed into a URI 841 * @return The new URI 842 * 843 * @throws NullPointerException 844 * If <tt>str</tt> is <tt>null</tt> 845 * 846 * @throws IllegalArgumentException 847 * If the given string violates RFC 2396 848 */ create(String str)849 public static URI create(String str) { 850 try { 851 return new URI(str); 852 } catch (URISyntaxException x) { 853 throw new IllegalArgumentException(x.getMessage(), x); 854 } 855 } 856 857 858 // -- Operations -- 859 860 /** 861 * Attempts to parse this URI's authority component, if defined, into 862 * user-information, host, and port components. 863 * 864 * <p> If this URI's authority component has already been recognized as 865 * being server-based then it will already have been parsed into 866 * user-information, host, and port components. In this case, or if this 867 * URI has no authority component, this method simply returns this URI. 868 * 869 * <p> Otherwise this method attempts once more to parse the authority 870 * component into user-information, host, and port components, and throws 871 * an exception describing why the authority component could not be parsed 872 * in that way. 873 * 874 * <p> This method is provided because the generic URI syntax specified in 875 * <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a> 876 * cannot always distinguish a malformed server-based authority from a 877 * legitimate registry-based authority. It must therefore treat some 878 * instances of the former as instances of the latter. The authority 879 * component in the URI string <tt>"//foo:bar"</tt>, for example, is not a 880 * legal server-based authority but it is legal as a registry-based 881 * authority. 882 * 883 * <p> In many common situations, for example when working URIs that are 884 * known to be either URNs or URLs, the hierarchical URIs being used will 885 * always be server-based. They therefore must either be parsed as such or 886 * treated as an error. In these cases a statement such as 887 * 888 * <blockquote> 889 * <tt>URI </tt><i>u</i><tt> = new URI(str).parseServerAuthority();</tt> 890 * </blockquote> 891 * 892 * <p> can be used to ensure that <i>u</i> always refers to a URI that, if 893 * it has an authority component, has a server-based authority with proper 894 * user-information, host, and port components. Invoking this method also 895 * ensures that if the authority could not be parsed in that way then an 896 * appropriate diagnostic message can be issued based upon the exception 897 * that is thrown. </p> 898 * 899 * @return A URI whose authority field has been parsed 900 * as a server-based authority 901 * 902 * @throws URISyntaxException 903 * If the authority component of this URI is defined 904 * but cannot be parsed as a server-based authority 905 * according to RFC 2396 906 */ parseServerAuthority()907 public URI parseServerAuthority() 908 throws URISyntaxException 909 { 910 // We could be clever and cache the error message and index from the 911 // exception thrown during the original parse, but that would require 912 // either more fields or a more-obscure representation. 913 if ((host != null) || (authority == null)) 914 return this; 915 defineString(); 916 new Parser(string).parse(true); 917 return this; 918 } 919 920 /** 921 * Normalizes this URI's path. 922 * 923 * <p> If this URI is opaque, or if its path is already in normal form, 924 * then this URI is returned. Otherwise a new URI is constructed that is 925 * identical to this URI except that its path is computed by normalizing 926 * this URI's path in a manner consistent with <a 927 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>, 928 * section 5.2, step 6, sub-steps c through f; that is: 929 * </p> 930 * 931 * <ol> 932 * 933 * <li><p> All <tt>"."</tt> segments are removed. </p></li> 934 * 935 * <li><p> If a <tt>".."</tt> segment is preceded by a non-<tt>".."</tt> 936 * segment then both of these segments are removed. This step is 937 * repeated until it is no longer applicable. </p></li> 938 * 939 * <li><p> If the path is relative, and if its first segment contains a 940 * colon character (<tt>':'</tt>), then a <tt>"."</tt> segment is 941 * prepended. This prevents a relative URI with a path such as 942 * <tt>"a:b/c/d"</tt> from later being re-parsed as an opaque URI with a 943 * scheme of <tt>"a"</tt> and a scheme-specific part of <tt>"b/c/d"</tt>. 944 * <b><i>(Deviation from RFC 2396)</i></b> </p></li> 945 * 946 * </ol> 947 * 948 * <p> A normalized path will begin with one or more <tt>".."</tt> segments 949 * if there were insufficient non-<tt>".."</tt> segments preceding them to 950 * allow their removal. A normalized path will begin with a <tt>"."</tt> 951 * segment if one was inserted by step 3 above. Otherwise, a normalized 952 * path will not contain any <tt>"."</tt> or <tt>".."</tt> segments. </p> 953 * 954 * @return A URI equivalent to this URI, 955 * but whose path is in normal form 956 */ normalize()957 public URI normalize() { 958 return normalize(this); 959 } 960 961 /** 962 * Resolves the given URI against this URI. 963 * 964 * <p> If the given URI is already absolute, or if this URI is opaque, then 965 * the given URI is returned. 966 * 967 * <p><a name="resolve-frag"></a> If the given URI's fragment component is 968 * defined, its path component is empty, and its scheme, authority, and 969 * query components are undefined, then a URI with the given fragment but 970 * with all other components equal to those of this URI is returned. This 971 * allows a URI representing a standalone fragment reference, such as 972 * <tt>"#foo"</tt>, to be usefully resolved against a base URI. 973 * 974 * <p> Otherwise this method constructs a new hierarchical URI in a manner 975 * consistent with <a 976 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>, 977 * section 5.2; that is: </p> 978 * 979 * <ol> 980 * 981 * <li><p> A new URI is constructed with this URI's scheme and the given 982 * URI's query and fragment components. </p></li> 983 * 984 * <li><p> If the given URI has an authority component then the new URI's 985 * authority and path are taken from the given URI. </p></li> 986 * 987 * <li><p> Otherwise the new URI's authority component is copied from 988 * this URI, and its path is computed as follows: </p> 989 * 990 * <ol type=a> 991 * 992 * <li><p> If the given URI's path is absolute then the new URI's path 993 * is taken from the given URI. </p></li> 994 * 995 * <li><p> Otherwise the given URI's path is relative, and so the new 996 * URI's path is computed by resolving the path of the given URI 997 * against the path of this URI. This is done by concatenating all but 998 * the last segment of this URI's path, if any, with the given URI's 999 * path and then normalizing the result as if by invoking the {@link 1000 * #normalize() normalize} method. </p></li> 1001 * 1002 * </ol></li> 1003 * 1004 * </ol> 1005 * 1006 * <p> The result of this method is absolute if, and only if, either this 1007 * URI is absolute or the given URI is absolute. </p> 1008 * 1009 * @param uri The URI to be resolved against this URI 1010 * @return The resulting URI 1011 * 1012 * @throws NullPointerException 1013 * If <tt>uri</tt> is <tt>null</tt> 1014 */ resolve(URI uri)1015 public URI resolve(URI uri) { 1016 return resolve(this, uri); 1017 } 1018 1019 /** 1020 * Constructs a new URI by parsing the given string and then resolving it 1021 * against this URI. 1022 * 1023 * <p> This convenience method works as if invoking it were equivalent to 1024 * evaluating the expression <tt>{@link #resolve(java.net.URI) 1025 * resolve}(URI.{@link #create(String) create}(str))</tt>. </p> 1026 * 1027 * @param str The string to be parsed into a URI 1028 * @return The resulting URI 1029 * 1030 * @throws NullPointerException 1031 * If <tt>str</tt> is <tt>null</tt> 1032 * 1033 * @throws IllegalArgumentException 1034 * If the given string violates RFC 2396 1035 */ resolve(String str)1036 public URI resolve(String str) { 1037 return resolve(URI.create(str)); 1038 } 1039 1040 /** 1041 * Relativizes the given URI against this URI. 1042 * 1043 * <p> The relativization of the given URI against this URI is computed as 1044 * follows: </p> 1045 * 1046 * <ol> 1047 * 1048 * <li><p> If either this URI or the given URI are opaque, or if the 1049 * scheme and authority components of the two URIs are not identical, or 1050 * if the path of this URI is not a prefix of the path of the given URI, 1051 * then the given URI is returned. </p></li> 1052 * 1053 * <li><p> Otherwise a new relative hierarchical URI is constructed with 1054 * query and fragment components taken from the given URI and with a path 1055 * component computed by removing this URI's path from the beginning of 1056 * the given URI's path. </p></li> 1057 * 1058 * </ol> 1059 * 1060 * @param uri The URI to be relativized against this URI 1061 * @return The resulting URI 1062 * 1063 * @throws NullPointerException 1064 * If <tt>uri</tt> is <tt>null</tt> 1065 */ relativize(URI uri)1066 public URI relativize(URI uri) { 1067 return relativize(this, uri); 1068 } 1069 1070 /** 1071 * Constructs a URL from this URI. 1072 * 1073 * <p> This convenience method works as if invoking it were equivalent to 1074 * evaluating the expression <tt>new URL(this.toString())</tt> after 1075 * first checking that this URI is absolute. </p> 1076 * 1077 * @return A URL constructed from this URI 1078 * 1079 * @throws IllegalArgumentException 1080 * If this URL is not absolute 1081 * 1082 * @throws MalformedURLException 1083 * If a protocol handler for the URL could not be found, 1084 * or if some other error occurred while constructing the URL 1085 */ toURL()1086 public URL toURL() 1087 throws MalformedURLException { 1088 if (!isAbsolute()) 1089 throw new IllegalArgumentException("URI is not absolute"); 1090 return new URL(toString()); 1091 } 1092 1093 // -- Component access methods -- 1094 1095 /** 1096 * Returns the scheme component of this URI. 1097 * 1098 * <p> The scheme component of a URI, if defined, only contains characters 1099 * in the <i>alphanum</i> category and in the string <tt>"-.+"</tt>. A 1100 * scheme always starts with an <i>alpha</i> character. <p> 1101 * 1102 * The scheme component of a URI cannot contain escaped octets, hence this 1103 * method does not perform any decoding. 1104 * 1105 * @return The scheme component of this URI, 1106 * or <tt>null</tt> if the scheme is undefined 1107 */ getScheme()1108 public String getScheme() { 1109 return scheme; 1110 } 1111 1112 /** 1113 * Tells whether or not this URI is absolute. 1114 * 1115 * <p> A URI is absolute if, and only if, it has a scheme component. </p> 1116 * 1117 * @return <tt>true</tt> if, and only if, this URI is absolute 1118 */ isAbsolute()1119 public boolean isAbsolute() { 1120 return scheme != null; 1121 } 1122 1123 /** 1124 * Tells whether or not this URI is opaque. 1125 * 1126 * <p> A URI is opaque if, and only if, it is absolute and its 1127 * scheme-specific part does not begin with a slash character ('/'). 1128 * An opaque URI has a scheme, a scheme-specific part, and possibly 1129 * a fragment; all other components are undefined. </p> 1130 * 1131 * @return <tt>true</tt> if, and only if, this URI is opaque 1132 */ isOpaque()1133 public boolean isOpaque() { 1134 return path == null; 1135 } 1136 1137 /** 1138 * Returns the raw scheme-specific part of this URI. The scheme-specific 1139 * part is never undefined, though it may be empty. 1140 * 1141 * <p> The scheme-specific part of a URI only contains legal URI 1142 * characters. </p> 1143 * 1144 * @return The raw scheme-specific part of this URI 1145 * (never <tt>null</tt>) 1146 */ getRawSchemeSpecificPart()1147 public String getRawSchemeSpecificPart() { 1148 defineSchemeSpecificPart(); 1149 return schemeSpecificPart; 1150 } 1151 1152 /** 1153 * Returns the decoded scheme-specific part of this URI. 1154 * 1155 * <p> The string returned by this method is equal to that returned by the 1156 * {@link #getRawSchemeSpecificPart() getRawSchemeSpecificPart} method 1157 * except that all sequences of escaped octets are <a 1158 * href="#decode">decoded</a>. </p> 1159 * 1160 * @return The decoded scheme-specific part of this URI 1161 * (never <tt>null</tt>) 1162 */ getSchemeSpecificPart()1163 public String getSchemeSpecificPart() { 1164 if (decodedSchemeSpecificPart == null) 1165 decodedSchemeSpecificPart = decode(getRawSchemeSpecificPart()); 1166 return decodedSchemeSpecificPart; 1167 } 1168 1169 /** 1170 * Returns the raw authority component of this URI. 1171 * 1172 * <p> The authority component of a URI, if defined, only contains the 1173 * commercial-at character (<tt>'@'</tt>) and characters in the 1174 * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and <i>other</i> 1175 * categories. If the authority is server-based then it is further 1176 * constrained to have valid user-information, host, and port 1177 * components. </p> 1178 * 1179 * @return The raw authority component of this URI, 1180 * or <tt>null</tt> if the authority is undefined 1181 */ getRawAuthority()1182 public String getRawAuthority() { 1183 return authority; 1184 } 1185 1186 /** 1187 * Returns the decoded authority component of this URI. 1188 * 1189 * <p> The string returned by this method is equal to that returned by the 1190 * {@link #getRawAuthority() getRawAuthority} method except that all 1191 * sequences of escaped octets are <a href="#decode">decoded</a>. </p> 1192 * 1193 * @return The decoded authority component of this URI, 1194 * or <tt>null</tt> if the authority is undefined 1195 */ getAuthority()1196 public String getAuthority() { 1197 if (decodedAuthority == null) 1198 decodedAuthority = decode(authority); 1199 return decodedAuthority; 1200 } 1201 1202 /** 1203 * Returns the raw user-information component of this URI. 1204 * 1205 * <p> The user-information component of a URI, if defined, only contains 1206 * characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and 1207 * <i>other</i> categories. </p> 1208 * 1209 * @return The raw user-information component of this URI, 1210 * or <tt>null</tt> if the user information is undefined 1211 */ getRawUserInfo()1212 public String getRawUserInfo() { 1213 return userInfo; 1214 } 1215 1216 /** 1217 * Returns the decoded user-information component of this URI. 1218 * 1219 * <p> The string returned by this method is equal to that returned by the 1220 * {@link #getRawUserInfo() getRawUserInfo} method except that all 1221 * sequences of escaped octets are <a href="#decode">decoded</a>. </p> 1222 * 1223 * @return The decoded user-information component of this URI, 1224 * or <tt>null</tt> if the user information is undefined 1225 */ getUserInfo()1226 public String getUserInfo() { 1227 if ((decodedUserInfo == null) && (userInfo != null)) 1228 decodedUserInfo = decode(userInfo); 1229 return decodedUserInfo; 1230 } 1231 1232 /** 1233 * Returns the host component of this URI. 1234 * 1235 * <p> The host component of a URI, if defined, will have one of the 1236 * following forms: </p> 1237 * 1238 * <ul type=disc> 1239 * 1240 * <li><p> A domain name consisting of one or more <i>labels</i> 1241 * separated by period characters (<tt>'.'</tt>), optionally followed by 1242 * a period character. Each label consists of <i>alphanum</i> characters 1243 * as well as hyphen characters (<tt>'-'</tt>), though hyphens never 1244 * occur as the first or last characters in a label. The rightmost 1245 * label of a domain name consisting of two or more labels, begins 1246 * with an <i>alpha</i> character. </li> 1247 * 1248 * <li><p> A dotted-quad IPv4 address of the form 1249 * <i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+</tt>, 1250 * where no <i>digit</i> sequence is longer than three characters and no 1251 * sequence has a value larger than 255. </p></li> 1252 * 1253 * <li><p> An IPv6 address enclosed in square brackets (<tt>'['</tt> and 1254 * <tt>']'</tt>) and consisting of hexadecimal digits, colon characters 1255 * (<tt>':'</tt>), and possibly an embedded IPv4 address. The full 1256 * syntax of IPv6 addresses is specified in <a 1257 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 2373: IPv6 1258 * Addressing Architecture</i></a>. </p></li> 1259 * 1260 * </ul> 1261 * 1262 * The host component of a URI cannot contain escaped octets, hence this 1263 * method does not perform any decoding. 1264 * 1265 * @return The host component of this URI, 1266 * or <tt>null</tt> if the host is undefined 1267 */ getHost()1268 public String getHost() { 1269 return host; 1270 } 1271 1272 /** 1273 * Returns the port number of this URI. 1274 * 1275 * <p> The port component of a URI, if defined, is a non-negative 1276 * integer. </p> 1277 * 1278 * @return The port component of this URI, 1279 * or <tt>-1</tt> if the port is undefined 1280 */ getPort()1281 public int getPort() { 1282 return port; 1283 } 1284 1285 /** 1286 * Returns the raw path component of this URI. 1287 * 1288 * <p> The path component of a URI, if defined, only contains the slash 1289 * character (<tt>'/'</tt>), the commercial-at character (<tt>'@'</tt>), 1290 * and characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, 1291 * and <i>other</i> categories. </p> 1292 * 1293 * @return The path component of this URI, 1294 * or <tt>null</tt> if the path is undefined 1295 */ getRawPath()1296 public String getRawPath() { 1297 return path; 1298 } 1299 1300 /** 1301 * Returns the decoded path component of this URI. 1302 * 1303 * <p> The string returned by this method is equal to that returned by the 1304 * {@link #getRawPath() getRawPath} method except that all sequences of 1305 * escaped octets are <a href="#decode">decoded</a>. </p> 1306 * 1307 * @return The decoded path component of this URI, 1308 * or <tt>null</tt> if the path is undefined 1309 */ getPath()1310 public String getPath() { 1311 if ((decodedPath == null) && (path != null)) 1312 decodedPath = decode(path); 1313 return decodedPath; 1314 } 1315 1316 /** 1317 * Returns the raw query component of this URI. 1318 * 1319 * <p> The query component of a URI, if defined, only contains legal URI 1320 * characters. </p> 1321 * 1322 * @return The raw query component of this URI, 1323 * or <tt>null</tt> if the query is undefined 1324 */ getRawQuery()1325 public String getRawQuery() { 1326 return query; 1327 } 1328 1329 /** 1330 * Returns the decoded query component of this URI. 1331 * 1332 * <p> The string returned by this method is equal to that returned by the 1333 * {@link #getRawQuery() getRawQuery} method except that all sequences of 1334 * escaped octets are <a href="#decode">decoded</a>. </p> 1335 * 1336 * @return The decoded query component of this URI, 1337 * or <tt>null</tt> if the query is undefined 1338 */ getQuery()1339 public String getQuery() { 1340 if ((decodedQuery == null) && (query != null)) 1341 decodedQuery = decode(query); 1342 return decodedQuery; 1343 } 1344 1345 /** 1346 * Returns the raw fragment component of this URI. 1347 * 1348 * <p> The fragment component of a URI, if defined, only contains legal URI 1349 * characters. </p> 1350 * 1351 * @return The raw fragment component of this URI, 1352 * or <tt>null</tt> if the fragment is undefined 1353 */ getRawFragment()1354 public String getRawFragment() { 1355 return fragment; 1356 } 1357 1358 /** 1359 * Returns the decoded fragment component of this URI. 1360 * 1361 * <p> The string returned by this method is equal to that returned by the 1362 * {@link #getRawFragment() getRawFragment} method except that all 1363 * sequences of escaped octets are <a href="#decode">decoded</a>. </p> 1364 * 1365 * @return The decoded fragment component of this URI, 1366 * or <tt>null</tt> if the fragment is undefined 1367 */ getFragment()1368 public String getFragment() { 1369 if ((decodedFragment == null) && (fragment != null)) 1370 decodedFragment = decode(fragment); 1371 return decodedFragment; 1372 } 1373 1374 1375 // -- Equality, comparison, hash code, toString, and serialization -- 1376 1377 /** 1378 * Tests this URI for equality with another object. 1379 * 1380 * <p> If the given object is not a URI then this method immediately 1381 * returns <tt>false</tt>. 1382 * 1383 * <p> For two URIs to be considered equal requires that either both are 1384 * opaque or both are hierarchical. Their schemes must either both be 1385 * undefined or else be equal without regard to case. Their fragments 1386 * must either both be undefined or else be equal. 1387 * 1388 * <p> For two opaque URIs to be considered equal, their scheme-specific 1389 * parts must be equal. 1390 * 1391 * <p> For two hierarchical URIs to be considered equal, their paths must 1392 * be equal and their queries must either both be undefined or else be 1393 * equal. Their authorities must either both be undefined, or both be 1394 * registry-based, or both be server-based. If their authorities are 1395 * defined and are registry-based, then they must be equal. If their 1396 * authorities are defined and are server-based, then their hosts must be 1397 * equal without regard to case, their port numbers must be equal, and 1398 * their user-information components must be equal. 1399 * 1400 * <p> When testing the user-information, path, query, fragment, authority, 1401 * or scheme-specific parts of two URIs for equality, the raw forms rather 1402 * than the encoded forms of these components are compared and the 1403 * hexadecimal digits of escaped octets are compared without regard to 1404 * case. 1405 * 1406 * <p> This method satisfies the general contract of the {@link 1407 * java.lang.Object#equals(Object) Object.equals} method. </p> 1408 * 1409 * @param ob The object to which this object is to be compared 1410 * 1411 * @return <tt>true</tt> if, and only if, the given object is a URI that 1412 * is identical to this URI 1413 */ equals(Object ob)1414 public boolean equals(Object ob) { 1415 if (ob == this) 1416 return true; 1417 if (!(ob instanceof URI)) 1418 return false; 1419 URI that = (URI)ob; 1420 if (this.isOpaque() != that.isOpaque()) return false; 1421 if (!equalIgnoringCase(this.scheme, that.scheme)) return false; 1422 if (!equal(this.fragment, that.fragment)) return false; 1423 1424 // Opaque 1425 if (this.isOpaque()) 1426 return equal(this.schemeSpecificPart, that.schemeSpecificPart); 1427 1428 // Hierarchical 1429 if (!equal(this.path, that.path)) return false; 1430 if (!equal(this.query, that.query)) return false; 1431 1432 // Authorities 1433 if (this.authority == that.authority) return true; 1434 if (this.host != null) { 1435 // Server-based 1436 if (!equal(this.userInfo, that.userInfo)) return false; 1437 if (!equalIgnoringCase(this.host, that.host)) return false; 1438 if (this.port != that.port) return false; 1439 } else if (this.authority != null) { 1440 // Registry-based 1441 if (!equal(this.authority, that.authority)) return false; 1442 } else if (this.authority != that.authority) { 1443 return false; 1444 } 1445 1446 return true; 1447 } 1448 1449 /** 1450 * Returns a hash-code value for this URI. The hash code is based upon all 1451 * of the URI's components, and satisfies the general contract of the 1452 * {@link java.lang.Object#hashCode() Object.hashCode} method. 1453 * 1454 * @return A hash-code value for this URI 1455 */ hashCode()1456 public int hashCode() { 1457 if (hash != 0) 1458 return hash; 1459 int h = hashIgnoringCase(0, scheme); 1460 h = hash(h, fragment); 1461 if (isOpaque()) { 1462 h = hash(h, schemeSpecificPart); 1463 } else { 1464 h = hash(h, path); 1465 h = hash(h, query); 1466 if (host != null) { 1467 h = hash(h, userInfo); 1468 h = hashIgnoringCase(h, host); 1469 h += 1949 * port; 1470 } else { 1471 h = hash(h, authority); 1472 } 1473 } 1474 hash = h; 1475 return h; 1476 } 1477 1478 /** 1479 * Compares this URI to another object, which must be a URI. 1480 * 1481 * <p> When comparing corresponding components of two URIs, if one 1482 * component is undefined but the other is defined then the first is 1483 * considered to be less than the second. Unless otherwise noted, string 1484 * components are ordered according to their natural, case-sensitive 1485 * ordering as defined by the {@link java.lang.String#compareTo(Object) 1486 * String.compareTo} method. String components that are subject to 1487 * encoding are compared by comparing their raw forms rather than their 1488 * encoded forms. 1489 * 1490 * <p> The ordering of URIs is defined as follows: </p> 1491 * 1492 * <ul type=disc> 1493 * 1494 * <li><p> Two URIs with different schemes are ordered according the 1495 * ordering of their schemes, without regard to case. </p></li> 1496 * 1497 * <li><p> A hierarchical URI is considered to be less than an opaque URI 1498 * with an identical scheme. </p></li> 1499 * 1500 * <li><p> Two opaque URIs with identical schemes are ordered according 1501 * to the ordering of their scheme-specific parts. </p></li> 1502 * 1503 * <li><p> Two opaque URIs with identical schemes and scheme-specific 1504 * parts are ordered according to the ordering of their 1505 * fragments. </p></li> 1506 * 1507 * <li><p> Two hierarchical URIs with identical schemes are ordered 1508 * according to the ordering of their authority components: </p> 1509 * 1510 * <ul type=disc> 1511 * 1512 * <li><p> If both authority components are server-based then the URIs 1513 * are ordered according to their user-information components; if these 1514 * components are identical then the URIs are ordered according to the 1515 * ordering of their hosts, without regard to case; if the hosts are 1516 * identical then the URIs are ordered according to the ordering of 1517 * their ports. </p></li> 1518 * 1519 * <li><p> If one or both authority components are registry-based then 1520 * the URIs are ordered according to the ordering of their authority 1521 * components. </p></li> 1522 * 1523 * </ul></li> 1524 * 1525 * <li><p> Finally, two hierarchical URIs with identical schemes and 1526 * authority components are ordered according to the ordering of their 1527 * paths; if their paths are identical then they are ordered according to 1528 * the ordering of their queries; if the queries are identical then they 1529 * are ordered according to the order of their fragments. </p></li> 1530 * 1531 * </ul> 1532 * 1533 * <p> This method satisfies the general contract of the {@link 1534 * java.lang.Comparable#compareTo(Object) Comparable.compareTo} 1535 * method. </p> 1536 * 1537 * @param that 1538 * The object to which this URI is to be compared 1539 * 1540 * @return A negative integer, zero, or a positive integer as this URI is 1541 * less than, equal to, or greater than the given URI 1542 * 1543 * @throws ClassCastException 1544 * If the given object is not a URI 1545 */ compareTo(URI that)1546 public int compareTo(URI that) { 1547 int c; 1548 1549 if ((c = compareIgnoringCase(this.scheme, that.scheme)) != 0) 1550 return c; 1551 1552 if (this.isOpaque()) { 1553 if (that.isOpaque()) { 1554 // Both opaque 1555 if ((c = compare(this.schemeSpecificPart, 1556 that.schemeSpecificPart)) != 0) 1557 return c; 1558 return compare(this.fragment, that.fragment); 1559 } 1560 return +1; // Opaque > hierarchical 1561 } else if (that.isOpaque()) { 1562 return -1; // Hierarchical < opaque 1563 } 1564 1565 // Hierarchical 1566 if ((this.host != null) && (that.host != null)) { 1567 // Both server-based 1568 if ((c = compare(this.userInfo, that.userInfo)) != 0) 1569 return c; 1570 if ((c = compareIgnoringCase(this.host, that.host)) != 0) 1571 return c; 1572 if ((c = this.port - that.port) != 0) 1573 return c; 1574 } else { 1575 // If one or both authorities are registry-based then we simply 1576 // compare them in the usual, case-sensitive way. If one is 1577 // registry-based and one is server-based then the strings are 1578 // guaranteed to be unequal, hence the comparison will never return 1579 // zero and the compareTo and equals methods will remain 1580 // consistent. 1581 if ((c = compare(this.authority, that.authority)) != 0) return c; 1582 } 1583 1584 if ((c = compare(this.path, that.path)) != 0) return c; 1585 if ((c = compare(this.query, that.query)) != 0) return c; 1586 return compare(this.fragment, that.fragment); 1587 } 1588 1589 /** 1590 * Returns the content of this URI as a string. 1591 * 1592 * <p> If this URI was created by invoking one of the constructors in this 1593 * class then a string equivalent to the original input string, or to the 1594 * string computed from the originally-given components, as appropriate, is 1595 * returned. Otherwise this URI was created by normalization, resolution, 1596 * or relativization, and so a string is constructed from this URI's 1597 * components according to the rules specified in <a 1598 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>, 1599 * section 5.2, step 7. </p> 1600 * 1601 * @return The string form of this URI 1602 */ toString()1603 public String toString() { 1604 defineString(); 1605 return string; 1606 } 1607 1608 /** 1609 * Returns the content of this URI as a US-ASCII string. 1610 * 1611 * <p> If this URI does not contain any characters in the <i>other</i> 1612 * category then an invocation of this method will return the same value as 1613 * an invocation of the {@link #toString() toString} method. Otherwise 1614 * this method works as if by invoking that method and then <a 1615 * href="#encode">encoding</a> the result. </p> 1616 * 1617 * @return The string form of this URI, encoded as needed 1618 * so that it only contains characters in the US-ASCII 1619 * charset 1620 */ toASCIIString()1621 public String toASCIIString() { 1622 defineString(); 1623 return encode(string); 1624 } 1625 1626 1627 // -- Serialization support -- 1628 1629 /** 1630 * Saves the content of this URI to the given serial stream. 1631 * 1632 * <p> The only serializable field of a URI instance is its <tt>string</tt> 1633 * field. That field is given a value, if it does not have one already, 1634 * and then the {@link java.io.ObjectOutputStream#defaultWriteObject()} 1635 * method of the given object-output stream is invoked. </p> 1636 * 1637 * @param os The object-output stream to which this object 1638 * is to be written 1639 */ writeObject(ObjectOutputStream os)1640 private void writeObject(ObjectOutputStream os) 1641 throws IOException 1642 { 1643 defineString(); 1644 os.defaultWriteObject(); // Writes the string field only 1645 } 1646 1647 /** 1648 * Reconstitutes a URI from the given serial stream. 1649 * 1650 * <p> The {@link java.io.ObjectInputStream#defaultReadObject()} method is 1651 * invoked to read the value of the <tt>string</tt> field. The result is 1652 * then parsed in the usual way. 1653 * 1654 * @param is The object-input stream from which this object 1655 * is being read 1656 */ readObject(ObjectInputStream is)1657 private void readObject(ObjectInputStream is) 1658 throws ClassNotFoundException, IOException 1659 { 1660 port = -1; // Argh 1661 is.defaultReadObject(); 1662 try { 1663 new Parser(string).parse(false); 1664 } catch (URISyntaxException x) { 1665 IOException y = new InvalidObjectException("Invalid URI"); 1666 y.initCause(x); 1667 throw y; 1668 } 1669 } 1670 1671 1672 // -- End of public methods -- 1673 1674 1675 // -- Utility methods for string-field comparison and hashing -- 1676 1677 // These methods return appropriate values for null string arguments, 1678 // thereby simplifying the equals, hashCode, and compareTo methods. 1679 // 1680 // The case-ignoring methods should only be applied to strings whose 1681 // characters are all known to be US-ASCII. Because of this restriction, 1682 // these methods are faster than the similar methods in the String class. 1683 1684 // US-ASCII only toLower(char c)1685 private static int toLower(char c) { 1686 if ((c >= 'A') && (c <= 'Z')) 1687 return c + ('a' - 'A'); 1688 return c; 1689 } 1690 equal(String s, String t)1691 private static boolean equal(String s, String t) { 1692 if (s == t) return true; 1693 if ((s != null) && (t != null)) { 1694 if (s.length() != t.length()) 1695 return false; 1696 if (s.indexOf('%') < 0) 1697 return s.equals(t); 1698 int n = s.length(); 1699 for (int i = 0; i < n;) { 1700 char c = s.charAt(i); 1701 char d = t.charAt(i); 1702 if (c != '%') { 1703 if (c != d) 1704 return false; 1705 i++; 1706 continue; 1707 } 1708 if (d != '%') 1709 return false; 1710 i++; 1711 if (toLower(s.charAt(i)) != toLower(t.charAt(i))) 1712 return false; 1713 i++; 1714 if (toLower(s.charAt(i)) != toLower(t.charAt(i))) 1715 return false; 1716 i++; 1717 } 1718 return true; 1719 } 1720 return false; 1721 } 1722 1723 // US-ASCII only equalIgnoringCase(String s, String t)1724 private static boolean equalIgnoringCase(String s, String t) { 1725 if (s == t) return true; 1726 if ((s != null) && (t != null)) { 1727 int n = s.length(); 1728 if (t.length() != n) 1729 return false; 1730 for (int i = 0; i < n; i++) { 1731 if (toLower(s.charAt(i)) != toLower(t.charAt(i))) 1732 return false; 1733 } 1734 return true; 1735 } 1736 return false; 1737 } 1738 hash(int hash, String s)1739 private static int hash(int hash, String s) { 1740 if (s == null) return hash; 1741 return hash * 127 + s.hashCode(); 1742 } 1743 1744 // US-ASCII only hashIgnoringCase(int hash, String s)1745 private static int hashIgnoringCase(int hash, String s) { 1746 if (s == null) return hash; 1747 int h = hash; 1748 int n = s.length(); 1749 for (int i = 0; i < n; i++) 1750 h = 31 * h + toLower(s.charAt(i)); 1751 return h; 1752 } 1753 compare(String s, String t)1754 private static int compare(String s, String t) { 1755 if (s == t) return 0; 1756 if (s != null) { 1757 if (t != null) 1758 return s.compareTo(t); 1759 else 1760 return +1; 1761 } else { 1762 return -1; 1763 } 1764 } 1765 1766 // US-ASCII only compareIgnoringCase(String s, String t)1767 private static int compareIgnoringCase(String s, String t) { 1768 if (s == t) return 0; 1769 if (s != null) { 1770 if (t != null) { 1771 int sn = s.length(); 1772 int tn = t.length(); 1773 int n = sn < tn ? sn : tn; 1774 for (int i = 0; i < n; i++) { 1775 int c = toLower(s.charAt(i)) - toLower(t.charAt(i)); 1776 if (c != 0) 1777 return c; 1778 } 1779 return sn - tn; 1780 } 1781 return +1; 1782 } else { 1783 return -1; 1784 } 1785 } 1786 1787 1788 // -- String construction -- 1789 1790 // If a scheme is given then the path, if given, must be absolute 1791 // 1792 private static void checkPath(String s, String scheme, String path) 1793 throws URISyntaxException 1794 { 1795 if (scheme != null) { 1796 if ((path != null) 1797 && ((path.length() > 0) && (path.charAt(0) != '/'))) 1798 throw new URISyntaxException(s, 1799 "Relative path in absolute URI"); 1800 } 1801 } 1802 1803 private void appendAuthority(StringBuffer sb, 1804 String authority, 1805 String userInfo, 1806 String host, 1807 int port) 1808 { 1809 if (host != null) { 1810 sb.append("//"); 1811 if (userInfo != null) { 1812 sb.append(quote(userInfo, L_USERINFO, H_USERINFO)); 1813 sb.append('@'); 1814 } 1815 boolean needBrackets = ((host.indexOf(':') >= 0) 1816 && !host.startsWith("[") 1817 && !host.endsWith("]")); 1818 if (needBrackets) sb.append('['); 1819 sb.append(host); 1820 if (needBrackets) sb.append(']'); 1821 if (port != -1) { 1822 sb.append(':'); 1823 sb.append(port); 1824 } 1825 } else if (authority != null) { 1826 sb.append("//"); 1827 if (authority.startsWith("[")) { 1828 // authority should (but may not) contain an embedded IPv6 address 1829 int end = authority.indexOf("]"); 1830 String doquote = authority, dontquote = ""; 1831 if (end != -1 && authority.indexOf(":") != -1) { 1832 // the authority contains an IPv6 address 1833 if (end == authority.length()) { 1834 dontquote = authority; 1835 doquote = ""; 1836 } else { 1837 dontquote = authority.substring(0 , end + 1); 1838 doquote = authority.substring(end + 1); 1839 } 1840 } 1841 sb.append(dontquote); 1842 sb.append(quote(doquote, 1843 L_REG_NAME | L_SERVER, 1844 H_REG_NAME | H_SERVER)); 1845 } else { 1846 sb.append(quote(authority, 1847 L_REG_NAME | L_SERVER, 1848 H_REG_NAME | H_SERVER)); 1849 } 1850 } 1851 } 1852 appendSchemeSpecificPart(StringBuffer sb, String opaquePart, String authority, String userInfo, String host, int port, String path, String query)1853 private void appendSchemeSpecificPart(StringBuffer sb, 1854 String opaquePart, 1855 String authority, 1856 String userInfo, 1857 String host, 1858 int port, 1859 String path, 1860 String query) 1861 { 1862 if (opaquePart != null) { 1863 /* check if SSP begins with an IPv6 address 1864 * because we must not quote a literal IPv6 address 1865 */ 1866 if (opaquePart.startsWith("//[")) { 1867 int end = opaquePart.indexOf("]"); 1868 if (end != -1 && opaquePart.indexOf(":")!=-1) { 1869 String doquote, dontquote; 1870 if (end == opaquePart.length()) { 1871 dontquote = opaquePart; 1872 doquote = ""; 1873 } else { 1874 dontquote = opaquePart.substring(0,end+1); 1875 doquote = opaquePart.substring(end+1); 1876 } 1877 sb.append (dontquote); 1878 sb.append(quote(doquote, L_URIC, H_URIC)); 1879 } 1880 } else { 1881 sb.append(quote(opaquePart, L_URIC, H_URIC)); 1882 } 1883 } else { 1884 appendAuthority(sb, authority, userInfo, host, port); 1885 if (path != null) 1886 sb.append(quote(path, L_PATH, H_PATH)); 1887 if (query != null) { 1888 sb.append('?'); 1889 sb.append(quote(query, L_URIC, H_URIC)); 1890 } 1891 } 1892 } 1893 appendFragment(StringBuffer sb, String fragment)1894 private void appendFragment(StringBuffer sb, String fragment) { 1895 if (fragment != null) { 1896 sb.append('#'); 1897 sb.append(quote(fragment, L_URIC, H_URIC)); 1898 } 1899 } 1900 toString(String scheme, String opaquePart, String authority, String userInfo, String host, int port, String path, String query, String fragment)1901 private String toString(String scheme, 1902 String opaquePart, 1903 String authority, 1904 String userInfo, 1905 String host, 1906 int port, 1907 String path, 1908 String query, 1909 String fragment) 1910 { 1911 StringBuffer sb = new StringBuffer(); 1912 if (scheme != null) { 1913 sb.append(scheme); 1914 sb.append(':'); 1915 } 1916 appendSchemeSpecificPart(sb, opaquePart, 1917 authority, userInfo, host, port, 1918 path, query); 1919 appendFragment(sb, fragment); 1920 return sb.toString(); 1921 } 1922 defineSchemeSpecificPart()1923 private void defineSchemeSpecificPart() { 1924 if (schemeSpecificPart != null) return; 1925 StringBuffer sb = new StringBuffer(); 1926 appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(), 1927 host, port, getPath(), getQuery()); 1928 if (sb.length() == 0) return; 1929 schemeSpecificPart = sb.toString(); 1930 } 1931 defineString()1932 private void defineString() { 1933 if (string != null) return; 1934 1935 StringBuffer sb = new StringBuffer(); 1936 if (scheme != null) { 1937 sb.append(scheme); 1938 sb.append(':'); 1939 } 1940 if (isOpaque()) { 1941 sb.append(schemeSpecificPart); 1942 } else { 1943 if (host != null) { 1944 sb.append("//"); 1945 if (userInfo != null) { 1946 sb.append(userInfo); 1947 sb.append('@'); 1948 } 1949 boolean needBrackets = ((host.indexOf(':') >= 0) 1950 && !host.startsWith("[") 1951 && !host.endsWith("]")); 1952 if (needBrackets) sb.append('['); 1953 sb.append(host); 1954 if (needBrackets) sb.append(']'); 1955 if (port != -1) { 1956 sb.append(':'); 1957 sb.append(port); 1958 } 1959 } else if (authority != null) { 1960 sb.append("//"); 1961 sb.append(authority); 1962 } 1963 if (path != null) 1964 sb.append(path); 1965 if (query != null) { 1966 sb.append('?'); 1967 sb.append(query); 1968 } 1969 } 1970 if (fragment != null) { 1971 sb.append('#'); 1972 sb.append(fragment); 1973 } 1974 string = sb.toString(); 1975 } 1976 1977 1978 // -- Normalization, resolution, and relativization -- 1979 1980 // RFC2396 5.2 (6) resolvePath(String base, String child, boolean absolute)1981 private static String resolvePath(String base, String child, 1982 boolean absolute) 1983 { 1984 int i = base.lastIndexOf('/'); 1985 int cn = child.length(); 1986 String path = ""; 1987 1988 if (cn == 0) { 1989 // 5.2 (6a) 1990 if (i >= 0) 1991 path = base.substring(0, i + 1); 1992 } else { 1993 StringBuffer sb = new StringBuffer(base.length() + cn); 1994 // 5.2 (6a) 1995 if (i >= 0) 1996 sb.append(base.substring(0, i + 1)); 1997 // 5.2 (6b) 1998 sb.append(child); 1999 path = sb.toString(); 2000 } 2001 2002 // 5.2 (6c-f) 2003 String np = normalize(path, true); 2004 2005 // 5.2 (6g): If the result is absolute but the path begins with "../", 2006 // then we simply leave the path as-is 2007 2008 return np; 2009 } 2010 2011 // RFC2396 5.2 resolve(URI base, URI child)2012 private static URI resolve(URI base, URI child) { 2013 // check if child if opaque first so that NPE is thrown 2014 // if child is null. 2015 if (child.isOpaque() || base.isOpaque()) 2016 return child; 2017 2018 // 5.2 (2): Reference to current document (lone fragment) 2019 if ((child.scheme == null) && (child.authority == null) 2020 && child.path.equals("") && (child.fragment != null) 2021 && (child.query == null)) { 2022 if ((base.fragment != null) 2023 && child.fragment.equals(base.fragment)) { 2024 return base; 2025 } 2026 URI ru = new URI(); 2027 ru.scheme = base.scheme; 2028 ru.authority = base.authority; 2029 ru.userInfo = base.userInfo; 2030 ru.host = base.host; 2031 ru.port = base.port; 2032 ru.path = base.path; 2033 ru.fragment = child.fragment; 2034 ru.query = base.query; 2035 return ru; 2036 } 2037 2038 // 5.2 (3): Child is absolute 2039 if (child.scheme != null) 2040 return child; 2041 2042 URI ru = new URI(); // Resolved URI 2043 ru.scheme = base.scheme; 2044 ru.query = child.query; 2045 ru.fragment = child.fragment; 2046 2047 // 5.2 (4): Authority 2048 if (child.authority == null) { 2049 ru.authority = base.authority; 2050 ru.host = base.host; 2051 ru.userInfo = base.userInfo; 2052 ru.port = base.port; 2053 2054 if (child.path == null || child.path.isEmpty()) { 2055 // This is an addtional path from RFC 3986 RI, which fixes following RFC 2396 2056 // "normal" examples: 2057 // Base: http://a/b/c/d;p?q 2058 // "?y" = "http://a/b/c/d;p?y" 2059 // "" = "http://a/b/c/d;p?q" 2060 // http://b/25897693 2061 ru.path = base.path; 2062 ru.query = child.query != null ? child.query : base.query; 2063 } else if ((child.path.length() > 0) && (child.path.charAt(0) == '/')) { 2064 // 5.2 (5): Child path is absolute 2065 // 2066 // There is an additional step from RFC 3986 RI, requiring to remove dots for 2067 // absolute path as well. 2068 // http://b/25897693 2069 ru.path = normalize(child.path, true); 2070 } else { 2071 // 5.2 (6): Resolve relative path 2072 ru.path = resolvePath(base.path, child.path, base.isAbsolute()); 2073 } 2074 } else { 2075 ru.authority = child.authority; 2076 ru.host = child.host; 2077 ru.userInfo = child.userInfo; 2078 ru.host = child.host; 2079 ru.port = child.port; 2080 ru.path = child.path; 2081 } 2082 2083 // 5.2 (7): Recombine (nothing to do here) 2084 return ru; 2085 } 2086 2087 // If the given URI's path is normal then return the URI; 2088 // o.w., return a new URI containing the normalized path. 2089 // normalize(URI u)2090 private static URI normalize(URI u) { 2091 if (u.isOpaque() || (u.path == null) || (u.path.length() == 0)) 2092 return u; 2093 2094 String np = normalize(u.path); 2095 if (np == u.path) 2096 return u; 2097 2098 URI v = new URI(); 2099 v.scheme = u.scheme; 2100 v.fragment = u.fragment; 2101 v.authority = u.authority; 2102 v.userInfo = u.userInfo; 2103 v.host = u.host; 2104 v.port = u.port; 2105 v.path = np; 2106 v.query = u.query; 2107 return v; 2108 } 2109 2110 // If both URIs are hierarchical, their scheme and authority components are 2111 // identical, and the base path is a prefix of the child's path, then 2112 // return a relative URI that, when resolved against the base, yields the 2113 // child; otherwise, return the child. 2114 // relativize(URI base, URI child)2115 private static URI relativize(URI base, URI child) { 2116 // check if child if opaque first so that NPE is thrown 2117 // if child is null. 2118 if (child.isOpaque() || base.isOpaque()) 2119 return child; 2120 if (!equalIgnoringCase(base.scheme, child.scheme) 2121 || !equal(base.authority, child.authority)) 2122 return child; 2123 2124 String bp = normalize(base.path); 2125 String cp = normalize(child.path); 2126 if (!bp.equals(cp)) { 2127 // Android-changed: The original OpenJdk implementation would append a trailing slash 2128 // to paths like "/a/b" before relativizing them. This would relativize /a/b/c to 2129 // "/c" against "/a/b" the android implementation did not do this. It would assume that 2130 // "b" wasn't a directory and relativize the path to "/b/c". The spec is pretty vague 2131 // about this but this change is being made because we have several tests that expect 2132 // this behaviour. 2133 if (bp.indexOf('/') != -1) { 2134 bp = bp.substring(0, bp.lastIndexOf('/') + 1); 2135 } 2136 2137 if (!cp.startsWith(bp)) 2138 return child; 2139 } 2140 2141 URI v = new URI(); 2142 v.path = cp.substring(bp.length()); 2143 v.query = child.query; 2144 v.fragment = child.fragment; 2145 return v; 2146 } 2147 2148 2149 2150 // -- Path normalization -- 2151 2152 // The following algorithm for path normalization avoids the creation of a 2153 // string object for each segment, as well as the use of a string buffer to 2154 // compute the final result, by using a single char array and editing it in 2155 // place. The array is first split into segments, replacing each slash 2156 // with '\0' and creating a segment-index array, each element of which is 2157 // the index of the first char in the corresponding segment. We then walk 2158 // through both arrays, removing ".", "..", and other segments as necessary 2159 // by setting their entries in the index array to -1. Finally, the two 2160 // arrays are used to rejoin the segments and compute the final result. 2161 // 2162 // This code is based upon src/solaris/native/java/io/canonicalize_md.c 2163 2164 2165 // Check the given path to see if it might need normalization. A path 2166 // might need normalization if it contains duplicate slashes, a "." 2167 // segment, or a ".." segment. Return -1 if no further normalization is 2168 // possible, otherwise return the number of segments found. 2169 // 2170 // This method takes a string argument rather than a char array so that 2171 // this test can be performed without invoking path.toCharArray(). 2172 // needsNormalization(String path)2173 static private int needsNormalization(String path) { 2174 boolean normal = true; 2175 int ns = 0; // Number of segments 2176 int end = path.length() - 1; // Index of last char in path 2177 int p = 0; // Index of next char in path 2178 2179 // Skip initial slashes 2180 while (p <= end) { 2181 if (path.charAt(p) != '/') break; 2182 p++; 2183 } 2184 if (p > 1) normal = false; 2185 2186 // Scan segments 2187 while (p <= end) { 2188 2189 // Looking at "." or ".." ? 2190 if ((path.charAt(p) == '.') 2191 && ((p == end) 2192 || ((path.charAt(p + 1) == '/') 2193 || ((path.charAt(p + 1) == '.') 2194 && ((p + 1 == end) 2195 || (path.charAt(p + 2) == '/')))))) { 2196 normal = false; 2197 } 2198 ns++; 2199 2200 // Find beginning of next segment 2201 while (p <= end) { 2202 if (path.charAt(p++) != '/') 2203 continue; 2204 2205 // Skip redundant slashes 2206 while (p <= end) { 2207 if (path.charAt(p) != '/') break; 2208 normal = false; 2209 p++; 2210 } 2211 2212 break; 2213 } 2214 } 2215 2216 return normal ? -1 : ns; 2217 } 2218 2219 2220 // Split the given path into segments, replacing slashes with nulls and 2221 // filling in the given segment-index array. 2222 // 2223 // Preconditions: 2224 // segs.length == Number of segments in path 2225 // 2226 // Postconditions: 2227 // All slashes in path replaced by '\0' 2228 // segs[i] == Index of first char in segment i (0 <= i < segs.length) 2229 // split(char[] path, int[] segs)2230 static private void split(char[] path, int[] segs) { 2231 int end = path.length - 1; // Index of last char in path 2232 int p = 0; // Index of next char in path 2233 int i = 0; // Index of current segment 2234 2235 // Skip initial slashes 2236 while (p <= end) { 2237 if (path[p] != '/') break; 2238 path[p] = '\0'; 2239 p++; 2240 } 2241 2242 while (p <= end) { 2243 2244 // Note start of segment 2245 segs[i++] = p++; 2246 2247 // Find beginning of next segment 2248 while (p <= end) { 2249 if (path[p++] != '/') 2250 continue; 2251 path[p - 1] = '\0'; 2252 2253 // Skip redundant slashes 2254 while (p <= end) { 2255 if (path[p] != '/') break; 2256 path[p++] = '\0'; 2257 } 2258 break; 2259 } 2260 } 2261 2262 if (i != segs.length) 2263 throw new InternalError(); // ASSERT 2264 } 2265 2266 2267 // Join the segments in the given path according to the given segment-index 2268 // array, ignoring those segments whose index entries have been set to -1, 2269 // and inserting slashes as needed. Return the length of the resulting 2270 // path. 2271 // 2272 // Preconditions: 2273 // segs[i] == -1 implies segment i is to be ignored 2274 // path computed by split, as above, with '\0' having replaced '/' 2275 // 2276 // Postconditions: 2277 // path[0] .. path[return value] == Resulting path 2278 // join(char[] path, int[] segs)2279 static private int join(char[] path, int[] segs) { 2280 int ns = segs.length; // Number of segments 2281 int end = path.length - 1; // Index of last char in path 2282 int p = 0; // Index of next path char to write 2283 2284 if (path[p] == '\0') { 2285 // Restore initial slash for absolute paths 2286 path[p++] = '/'; 2287 } 2288 2289 for (int i = 0; i < ns; i++) { 2290 int q = segs[i]; // Current segment 2291 if (q == -1) 2292 // Ignore this segment 2293 continue; 2294 2295 if (p == q) { 2296 // We're already at this segment, so just skip to its end 2297 while ((p <= end) && (path[p] != '\0')) 2298 p++; 2299 if (p <= end) { 2300 // Preserve trailing slash 2301 path[p++] = '/'; 2302 } 2303 } else if (p < q) { 2304 // Copy q down to p 2305 while ((q <= end) && (path[q] != '\0')) 2306 path[p++] = path[q++]; 2307 if (q <= end) { 2308 // Preserve trailing slash 2309 path[p++] = '/'; 2310 } 2311 } else 2312 throw new InternalError(); // ASSERT false 2313 } 2314 2315 return p; 2316 } 2317 2318 2319 // Remove "." segments from the given path, and remove segment pairs 2320 // consisting of a non-".." segment followed by a ".." segment. 2321 // removeDots(char[] path, int[] segs, boolean removeLeading)2322 private static void removeDots(char[] path, int[] segs, boolean removeLeading) { 2323 int ns = segs.length; 2324 int end = path.length - 1; 2325 2326 for (int i = 0; i < ns; i++) { 2327 int dots = 0; // Number of dots found (0, 1, or 2) 2328 2329 // Find next occurrence of "." or ".." 2330 do { 2331 int p = segs[i]; 2332 if (path[p] == '.') { 2333 if (p == end) { 2334 dots = 1; 2335 break; 2336 } else if (path[p + 1] == '\0') { 2337 dots = 1; 2338 break; 2339 } else if ((path[p + 1] == '.') 2340 && ((p + 1 == end) 2341 || (path[p + 2] == '\0'))) { 2342 dots = 2; 2343 break; 2344 } 2345 } 2346 i++; 2347 } while (i < ns); 2348 if ((i > ns) || (dots == 0)) 2349 break; 2350 2351 if (dots == 1) { 2352 // Remove this occurrence of "." 2353 segs[i] = -1; 2354 } else { 2355 // If there is a preceding non-".." segment, remove both that 2356 // segment and this occurrence of ".." 2357 int j; 2358 for (j = i - 1; j >= 0; j--) { 2359 if (segs[j] != -1) break; 2360 } 2361 if (j >= 0) { 2362 int q = segs[j]; 2363 if (!((path[q] == '.') 2364 && (path[q + 1] == '.') 2365 && (path[q + 2] == '\0'))) { 2366 segs[i] = -1; 2367 segs[j] = -1; 2368 } 2369 } else if (removeLeading) { 2370 // This is a leading ".." segment. Per RFC 3986 RI, this should be removed as 2371 // well. This fixes RFC 2396 "abnormal" examples. 2372 // http://b/25897693 2373 segs[i] = -1; 2374 } 2375 } 2376 } 2377 } 2378 2379 2380 // DEVIATION: If the normalized path is relative, and if the first 2381 // segment could be parsed as a scheme name, then prepend a "." segment 2382 // maybeAddLeadingDot(char[] path, int[] segs)2383 private static void maybeAddLeadingDot(char[] path, int[] segs) { 2384 2385 if (path[0] == '\0') 2386 // The path is absolute 2387 return; 2388 2389 int ns = segs.length; 2390 int f = 0; // Index of first segment 2391 while (f < ns) { 2392 if (segs[f] >= 0) 2393 break; 2394 f++; 2395 } 2396 if ((f >= ns) || (f == 0)) 2397 // The path is empty, or else the original first segment survived, 2398 // in which case we already know that no leading "." is needed 2399 return; 2400 2401 int p = segs[f]; 2402 while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++; 2403 if (p >= path.length || path[p] == '\0') 2404 // No colon in first segment, so no "." needed 2405 return; 2406 2407 // At this point we know that the first segment is unused, 2408 // hence we can insert a "." segment at that position 2409 path[0] = '.'; 2410 path[1] = '\0'; 2411 segs[0] = 0; 2412 } 2413 2414 2415 // Normalize the given path string. A normal path string has no empty 2416 // segments (i.e., occurrences of "//"), no segments equal to ".", and no 2417 // segments equal to ".." that are preceded by a segment not equal to "..". 2418 // In contrast to Unix-style pathname normalization, for URI paths we 2419 // always retain trailing slashes. 2420 // normalize(String ps)2421 private static String normalize(String ps) { 2422 return normalize(ps, false); 2423 } 2424 normalize(String ps, boolean removeLeading)2425 private static String normalize(String ps, boolean removeLeading) { 2426 2427 // Does this path need normalization? 2428 int ns = needsNormalization(ps); // Number of segments 2429 if (ns < 0) 2430 // Nope -- just return it 2431 return ps; 2432 2433 char[] path = ps.toCharArray(); // Path in char-array form 2434 2435 // Split path into segments 2436 int[] segs = new int[ns]; // Segment-index array 2437 split(path, segs); 2438 2439 // Remove dots 2440 removeDots(path, segs, removeLeading); 2441 2442 // Prevent scheme-name confusion 2443 maybeAddLeadingDot(path, segs); 2444 2445 // Join the remaining segments and return the result 2446 String s = new String(path, 0, join(path, segs)); 2447 if (s.equals(ps)) { 2448 // string was already normalized 2449 return ps; 2450 } 2451 return s; 2452 } 2453 2454 2455 2456 // -- Character classes for parsing -- 2457 2458 // RFC2396 precisely specifies which characters in the US-ASCII charset are 2459 // permissible in the various components of a URI reference. We here 2460 // define a set of mask pairs to aid in enforcing these restrictions. Each 2461 // mask pair consists of two longs, a low mask and a high mask. Taken 2462 // together they represent a 128-bit mask, where bit i is set iff the 2463 // character with value i is permitted. 2464 // 2465 // This approach is more efficient than sequentially searching arrays of 2466 // permitted characters. It could be made still more efficient by 2467 // precompiling the mask information so that a character's presence in a 2468 // given mask could be determined by a single table lookup. 2469 2470 // Compute the low-order mask for the characters in the given string lowMask(String chars)2471 private static long lowMask(String chars) { 2472 int n = chars.length(); 2473 long m = 0; 2474 for (int i = 0; i < n; i++) { 2475 char c = chars.charAt(i); 2476 if (c < 64) 2477 m |= (1L << c); 2478 } 2479 return m; 2480 } 2481 2482 // Compute the high-order mask for the characters in the given string highMask(String chars)2483 private static long highMask(String chars) { 2484 int n = chars.length(); 2485 long m = 0; 2486 for (int i = 0; i < n; i++) { 2487 char c = chars.charAt(i); 2488 if ((c >= 64) && (c < 128)) 2489 m |= (1L << (c - 64)); 2490 } 2491 return m; 2492 } 2493 2494 // Compute a low-order mask for the characters 2495 // between first and last, inclusive lowMask(char first, char last)2496 private static long lowMask(char first, char last) { 2497 long m = 0; 2498 int f = Math.max(Math.min(first, 63), 0); 2499 int l = Math.max(Math.min(last, 63), 0); 2500 for (int i = f; i <= l; i++) 2501 m |= 1L << i; 2502 return m; 2503 } 2504 2505 // Compute a high-order mask for the characters 2506 // between first and last, inclusive highMask(char first, char last)2507 private static long highMask(char first, char last) { 2508 long m = 0; 2509 int f = Math.max(Math.min(first, 127), 64) - 64; 2510 int l = Math.max(Math.min(last, 127), 64) - 64; 2511 for (int i = f; i <= l; i++) 2512 m |= 1L << i; 2513 return m; 2514 } 2515 2516 // Tell whether the given character is permitted by the given mask pair match(char c, long lowMask, long highMask)2517 private static boolean match(char c, long lowMask, long highMask) { 2518 if (c == 0) // 0 doesn't have a slot in the mask. So, it never matches. 2519 return false; 2520 if (c < 64) 2521 return ((1L << c) & lowMask) != 0; 2522 if (c < 128) 2523 return ((1L << (c - 64)) & highMask) != 0; 2524 return false; 2525 } 2526 2527 // Character-class masks, in reverse order from RFC2396 because 2528 // initializers for static fields cannot make forward references. 2529 2530 // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | 2531 // "8" | "9" 2532 private static final long L_DIGIT = lowMask('0', '9'); 2533 private static final long H_DIGIT = 0L; 2534 2535 // upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | 2536 // "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | 2537 // "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" 2538 private static final long L_UPALPHA = 0L; 2539 private static final long H_UPALPHA = highMask('A', 'Z'); 2540 2541 // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | 2542 // "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | 2543 // "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" 2544 private static final long L_LOWALPHA = 0L; 2545 private static final long H_LOWALPHA = highMask('a', 'z'); 2546 2547 // alpha = lowalpha | upalpha 2548 private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA; 2549 private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA; 2550 2551 // alphanum = alpha | digit 2552 private static final long L_ALPHANUM = L_DIGIT | L_ALPHA; 2553 private static final long H_ALPHANUM = H_DIGIT | H_ALPHA; 2554 2555 // hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | 2556 // "a" | "b" | "c" | "d" | "e" | "f" 2557 private static final long L_HEX = L_DIGIT; 2558 private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f'); 2559 2560 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | 2561 // "(" | ")" 2562 private static final long L_MARK = lowMask("-_.!~*'()"); 2563 private static final long H_MARK = highMask("-_.!~*'()"); 2564 2565 // unreserved = alphanum | mark 2566 private static final long L_UNRESERVED = L_ALPHANUM | L_MARK; 2567 private static final long H_UNRESERVED = H_ALPHANUM | H_MARK; 2568 2569 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | 2570 // "$" | "," | "[" | "]" 2571 // Added per RFC2732: "[", "]" 2572 private static final long L_RESERVED = lowMask(";/?:@&=+$,[]"); 2573 private static final long H_RESERVED = highMask(";/?:@&=+$,[]"); 2574 2575 // The zero'th bit is used to indicate that escape pairs and non-US-ASCII 2576 // characters are allowed; this is handled by the scanEscape method below. 2577 private static final long L_ESCAPED = 1L; 2578 private static final long H_ESCAPED = 0L; 2579 2580 // uric = reserved | unreserved | escaped 2581 private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED; 2582 private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED; 2583 2584 // pchar = unreserved | escaped | 2585 // ":" | "@" | "&" | "=" | "+" | "$" | "," 2586 private static final long L_PCHAR 2587 = L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,"); 2588 private static final long H_PCHAR 2589 = H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,"); 2590 2591 // All valid path characters 2592 private static final long L_PATH = L_PCHAR | lowMask(";/"); 2593 private static final long H_PATH = H_PCHAR | highMask(";/"); 2594 2595 // Dash, for use in domainlabel and toplabel 2596 private static final long L_DASH = lowMask("-"); 2597 private static final long H_DASH = highMask("-"); 2598 2599 // UNDERSCORE, for use in domainlabel and toplabel 2600 private static final long L_UNDERSCORE = lowMask("_"); 2601 private static final long H_UNDERSCORE = highMask("_"); 2602 2603 // Dot, for use in hostnames 2604 private static final long L_DOT = lowMask("."); 2605 private static final long H_DOT = highMask("."); 2606 2607 // userinfo = *( unreserved | escaped | 2608 // ";" | ":" | "&" | "=" | "+" | "$" | "," ) 2609 private static final long L_USERINFO 2610 = L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,"); 2611 private static final long H_USERINFO 2612 = H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,"); 2613 2614 // reg_name = 1*( unreserved | escaped | "$" | "," | 2615 // ";" | ":" | "@" | "&" | "=" | "+" ) 2616 private static final long L_REG_NAME 2617 = L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+"); 2618 private static final long H_REG_NAME 2619 = H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+"); 2620 2621 // All valid characters for server-based authorities 2622 private static final long L_SERVER 2623 = L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]"); 2624 private static final long H_SERVER 2625 = H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]"); 2626 2627 // Special case of server authority that represents an IPv6 address 2628 // In this case, a % does not signify an escape sequence 2629 private static final long L_SERVER_PERCENT 2630 = L_SERVER | lowMask("%"); 2631 private static final long H_SERVER_PERCENT 2632 = H_SERVER | highMask("%"); 2633 private static final long L_LEFT_BRACKET = lowMask("["); 2634 private static final long H_LEFT_BRACKET = highMask("["); 2635 2636 // scheme = alpha *( alpha | digit | "+" | "-" | "." ) 2637 private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-."); 2638 private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-."); 2639 2640 // uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" | 2641 // "&" | "=" | "+" | "$" | "," 2642 private static final long L_URIC_NO_SLASH 2643 = L_UNRESERVED | L_ESCAPED | lowMask(";?:@&=+$,"); 2644 private static final long H_URIC_NO_SLASH 2645 = H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,"); 2646 2647 2648 // -- Escaping and encoding -- 2649 2650 private final static char[] hexDigits = { 2651 '0', '1', '2', '3', '4', '5', '6', '7', 2652 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 2653 }; 2654 appendEscape(StringBuffer sb, byte b)2655 private static void appendEscape(StringBuffer sb, byte b) { 2656 sb.append('%'); 2657 sb.append(hexDigits[(b >> 4) & 0x0f]); 2658 sb.append(hexDigits[(b >> 0) & 0x0f]); 2659 } 2660 appendEncoded(StringBuffer sb, char c)2661 private static void appendEncoded(StringBuffer sb, char c) { 2662 ByteBuffer bb = null; 2663 try { 2664 bb = ThreadLocalCoders.encoderFor("UTF-8") 2665 .encode(CharBuffer.wrap("" + c)); 2666 } catch (CharacterCodingException x) { 2667 assert false; 2668 } 2669 while (bb.hasRemaining()) { 2670 int b = bb.get() & 0xff; 2671 if (b >= 0x80) 2672 appendEscape(sb, (byte)b); 2673 else 2674 sb.append((char)b); 2675 } 2676 } 2677 2678 // Quote any characters in s that are not permitted 2679 // by the given mask pair 2680 // quote(String s, long lowMask, long highMask)2681 private static String quote(String s, long lowMask, long highMask) { 2682 int n = s.length(); 2683 StringBuffer sb = null; 2684 boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0); 2685 for (int i = 0; i < s.length(); i++) { 2686 char c = s.charAt(i); 2687 if (c < '\u0080') { 2688 if (!match(c, lowMask, highMask)) { 2689 if (sb == null) { 2690 sb = new StringBuffer(); 2691 sb.append(s.substring(0, i)); 2692 } 2693 appendEscape(sb, (byte)c); 2694 } else { 2695 if (sb != null) 2696 sb.append(c); 2697 } 2698 } else if (allowNonASCII 2699 && (Character.isSpaceChar(c) 2700 || Character.isISOControl(c))) { 2701 if (sb == null) { 2702 sb = new StringBuffer(); 2703 sb.append(s.substring(0, i)); 2704 } 2705 appendEncoded(sb, c); 2706 } else { 2707 if (sb != null) 2708 sb.append(c); 2709 } 2710 } 2711 return (sb == null) ? s : sb.toString(); 2712 } 2713 2714 // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets, 2715 // assuming that s is otherwise legal 2716 // encode(String s)2717 private static String encode(String s) { 2718 int n = s.length(); 2719 if (n == 0) 2720 return s; 2721 2722 // First check whether we actually need to encode 2723 for (int i = 0;;) { 2724 if (s.charAt(i) >= '\u0080') 2725 break; 2726 if (++i >= n) 2727 return s; 2728 } 2729 2730 String ns = Normalizer.normalize(s, Normalizer.Form.NFC); 2731 ByteBuffer bb = null; 2732 try { 2733 bb = ThreadLocalCoders.encoderFor("UTF-8") 2734 .encode(CharBuffer.wrap(ns)); 2735 } catch (CharacterCodingException x) { 2736 assert false; 2737 } 2738 2739 StringBuffer sb = new StringBuffer(); 2740 while (bb.hasRemaining()) { 2741 int b = bb.get() & 0xff; 2742 if (b >= 0x80) 2743 appendEscape(sb, (byte)b); 2744 else 2745 sb.append((char)b); 2746 } 2747 return sb.toString(); 2748 } 2749 decode(char c)2750 private static int decode(char c) { 2751 if ((c >= '0') && (c <= '9')) 2752 return c - '0'; 2753 if ((c >= 'a') && (c <= 'f')) 2754 return c - 'a' + 10; 2755 if ((c >= 'A') && (c <= 'F')) 2756 return c - 'A' + 10; 2757 assert false; 2758 return -1; 2759 } 2760 decode(char c1, char c2)2761 private static byte decode(char c1, char c2) { 2762 return (byte)( ((decode(c1) & 0xf) << 4) 2763 | ((decode(c2) & 0xf) << 0)); 2764 } 2765 2766 // Evaluates all escapes in s, applying UTF-8 decoding if needed. Assumes 2767 // that escapes are well-formed syntactically, i.e., of the form %XX. If a 2768 // sequence of escaped octets is not valid UTF-8 then the erroneous octets 2769 // are replaced with '\uFFFD'. 2770 // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal 2771 // with a scope_id 2772 // decode(String s)2773 private static String decode(String s) { 2774 if (s == null) 2775 return s; 2776 int n = s.length(); 2777 if (n == 0) 2778 return s; 2779 if (s.indexOf('%') < 0) 2780 return s; 2781 2782 StringBuffer sb = new StringBuffer(n); 2783 ByteBuffer bb = ByteBuffer.allocate(n); 2784 CharBuffer cb = CharBuffer.allocate(n); 2785 CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8") 2786 .onMalformedInput(CodingErrorAction.REPLACE) 2787 .onUnmappableCharacter(CodingErrorAction.REPLACE); 2788 2789 // This is not horribly efficient, but it will do for now 2790 char c = s.charAt(0); 2791 boolean betweenBrackets = false; 2792 2793 for (int i = 0; i < n;) { 2794 assert c == s.charAt(i); // Loop invariant 2795 if (c == '[') { 2796 betweenBrackets = true; 2797 } else if (betweenBrackets && c == ']') { 2798 betweenBrackets = false; 2799 } 2800 if (c != '%' || betweenBrackets) { 2801 sb.append(c); 2802 if (++i >= n) 2803 break; 2804 c = s.charAt(i); 2805 continue; 2806 } 2807 bb.clear(); 2808 int ui = i; 2809 for (;;) { 2810 assert (n - i >= 2); 2811 bb.put(decode(s.charAt(++i), s.charAt(++i))); 2812 if (++i >= n) 2813 break; 2814 c = s.charAt(i); 2815 if (c != '%') 2816 break; 2817 } 2818 bb.flip(); 2819 cb.clear(); 2820 dec.reset(); 2821 CoderResult cr = dec.decode(bb, cb, true); 2822 assert cr.isUnderflow(); 2823 cr = dec.flush(cb); 2824 assert cr.isUnderflow(); 2825 sb.append(cb.flip().toString()); 2826 } 2827 2828 return sb.toString(); 2829 } 2830 2831 2832 // -- Parsing -- 2833 2834 // For convenience we wrap the input URI string in a new instance of the 2835 // following internal class. This saves always having to pass the input 2836 // string as an argument to each internal scan/parse method. 2837 2838 private class Parser { 2839 2840 private String input; // URI input string 2841 private boolean requireServerAuthority = false; 2842 Parser(String s)2843 Parser(String s) { 2844 input = s; 2845 string = s; 2846 } 2847 2848 // -- Methods for throwing URISyntaxException in various ways -- 2849 fail(String reason)2850 private void fail(String reason) throws URISyntaxException { 2851 throw new URISyntaxException(input, reason); 2852 } 2853 fail(String reason, int p)2854 private void fail(String reason, int p) throws URISyntaxException { 2855 throw new URISyntaxException(input, reason, p); 2856 } 2857 failExpecting(String expected, int p)2858 private void failExpecting(String expected, int p) 2859 throws URISyntaxException 2860 { 2861 fail("Expected " + expected, p); 2862 } 2863 failExpecting(String expected, String prior, int p)2864 private void failExpecting(String expected, String prior, int p) 2865 throws URISyntaxException 2866 { 2867 fail("Expected " + expected + " following " + prior, p); 2868 } 2869 2870 2871 // -- Simple access to the input string -- 2872 2873 // Return a substring of the input string 2874 // substring(int start, int end)2875 private String substring(int start, int end) { 2876 return input.substring(start, end); 2877 } 2878 2879 // Return the char at position p, 2880 // assuming that p < input.length() 2881 // charAt(int p)2882 private char charAt(int p) { 2883 return input.charAt(p); 2884 } 2885 2886 // Tells whether start < end and, if so, whether charAt(start) == c 2887 // at(int start, int end, char c)2888 private boolean at(int start, int end, char c) { 2889 return (start < end) && (charAt(start) == c); 2890 } 2891 2892 // Tells whether start + s.length() < end and, if so, 2893 // whether the chars at the start position match s exactly 2894 // at(int start, int end, String s)2895 private boolean at(int start, int end, String s) { 2896 int p = start; 2897 int sn = s.length(); 2898 if (sn > end - p) 2899 return false; 2900 int i = 0; 2901 while (i < sn) { 2902 if (charAt(p++) != s.charAt(i)) { 2903 break; 2904 } 2905 i++; 2906 } 2907 return (i == sn); 2908 } 2909 2910 2911 // -- Scanning -- 2912 2913 // The various scan and parse methods that follow use a uniform 2914 // convention of taking the current start position and end index as 2915 // their first two arguments. The start is inclusive while the end is 2916 // exclusive, just as in the String class, i.e., a start/end pair 2917 // denotes the left-open interval [start, end) of the input string. 2918 // 2919 // These methods never proceed past the end position. They may return 2920 // -1 to indicate outright failure, but more often they simply return 2921 // the position of the first char after the last char scanned. Thus 2922 // a typical idiom is 2923 // 2924 // int p = start; 2925 // int q = scan(p, end, ...); 2926 // if (q > p) 2927 // // We scanned something 2928 // ...; 2929 // else if (q == p) 2930 // // We scanned nothing 2931 // ...; 2932 // else if (q == -1) 2933 // // Something went wrong 2934 // ...; 2935 2936 2937 // Scan a specific char: If the char at the given start position is 2938 // equal to c, return the index of the next char; otherwise, return the 2939 // start position. 2940 // scan(int start, int end, char c)2941 private int scan(int start, int end, char c) { 2942 if ((start < end) && (charAt(start) == c)) 2943 return start + 1; 2944 return start; 2945 } 2946 2947 // Scan forward from the given start position. Stop at the first char 2948 // in the err string (in which case -1 is returned), or the first char 2949 // in the stop string (in which case the index of the preceding char is 2950 // returned), or the end of the input string (in which case the length 2951 // of the input string is returned). May return the start position if 2952 // nothing matches. 2953 // scan(int start, int end, String err, String stop)2954 private int scan(int start, int end, String err, String stop) { 2955 int p = start; 2956 while (p < end) { 2957 char c = charAt(p); 2958 if (err.indexOf(c) >= 0) 2959 return -1; 2960 if (stop.indexOf(c) >= 0) 2961 break; 2962 p++; 2963 } 2964 return p; 2965 } 2966 2967 // Scan a potential escape sequence, starting at the given position, 2968 // with the given first char (i.e., charAt(start) == c). 2969 // 2970 // This method assumes that if escapes are allowed then visible 2971 // non-US-ASCII chars are also allowed. 2972 // scanEscape(int start, int n, char first)2973 private int scanEscape(int start, int n, char first) 2974 throws URISyntaxException 2975 { 2976 int p = start; 2977 char c = first; 2978 if (c == '%') { 2979 // Process escape pair 2980 if ((p + 3 <= n) 2981 && match(charAt(p + 1), L_HEX, H_HEX) 2982 && match(charAt(p + 2), L_HEX, H_HEX)) { 2983 return p + 3; 2984 } 2985 fail("Malformed escape pair", p); 2986 } else if ((c > 128) 2987 && !Character.isSpaceChar(c) 2988 && !Character.isISOControl(c)) { 2989 // Allow unescaped but visible non-US-ASCII chars 2990 return p + 1; 2991 } 2992 return p; 2993 } 2994 2995 // Scan chars that match the given mask pair 2996 // scan(int start, int n, long lowMask, long highMask)2997 private int scan(int start, int n, long lowMask, long highMask) 2998 throws URISyntaxException 2999 { 3000 int p = start; 3001 while (p < n) { 3002 char c = charAt(p); 3003 if (match(c, lowMask, highMask)) { 3004 p++; 3005 continue; 3006 } 3007 if ((lowMask & L_ESCAPED) != 0) { 3008 int q = scanEscape(p, n, c); 3009 if (q > p) { 3010 p = q; 3011 continue; 3012 } 3013 } 3014 break; 3015 } 3016 return p; 3017 } 3018 3019 // Check that each of the chars in [start, end) matches the given mask 3020 // checkChars(int start, int end, long lowMask, long highMask, String what)3021 private void checkChars(int start, int end, 3022 long lowMask, long highMask, 3023 String what) 3024 throws URISyntaxException 3025 { 3026 int p = scan(start, end, lowMask, highMask); 3027 if (p < end) 3028 fail("Illegal character in " + what, p); 3029 } 3030 3031 // Check that the char at position p matches the given mask 3032 // checkChar(int p, long lowMask, long highMask, String what)3033 private void checkChar(int p, 3034 long lowMask, long highMask, 3035 String what) 3036 throws URISyntaxException 3037 { 3038 checkChars(p, p + 1, lowMask, highMask, what); 3039 } 3040 3041 3042 // -- Parsing -- 3043 3044 // [<scheme>:]<scheme-specific-part>[#<fragment>] 3045 // parse(boolean rsa)3046 void parse(boolean rsa) throws URISyntaxException { 3047 requireServerAuthority = rsa; 3048 int ssp; // Start of scheme-specific part 3049 int n = input.length(); 3050 int p = scan(0, n, "/?#", ":"); 3051 if ((p >= 0) && at(p, n, ':')) { 3052 if (p == 0) 3053 failExpecting("scheme name", 0); 3054 checkChar(0, L_ALPHA, H_ALPHA, "scheme name"); 3055 checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name"); 3056 scheme = substring(0, p); 3057 p++; // Skip ':' 3058 ssp = p; 3059 if (at(p, n, '/')) { 3060 p = parseHierarchical(p, n); 3061 } else { 3062 int q = scan(p, n, "", "#"); 3063 if (q <= p) 3064 failExpecting("scheme-specific part", p); 3065 checkChars(p, q, L_URIC, H_URIC, "opaque part"); 3066 p = q; 3067 } 3068 } else { 3069 ssp = 0; 3070 p = parseHierarchical(0, n); 3071 } 3072 schemeSpecificPart = substring(ssp, p); 3073 if (at(p, n, '#')) { 3074 checkChars(p + 1, n, L_URIC, H_URIC, "fragment"); 3075 fragment = substring(p + 1, n); 3076 p = n; 3077 } 3078 if (p < n) 3079 fail("end of URI", p); 3080 } 3081 3082 // [//authority]<path>[?<query>] 3083 // 3084 // DEVIATION from RFC2396: We allow an empty authority component as 3085 // long as it's followed by a non-empty path, query component, or 3086 // fragment component. This is so that URIs such as "file:///foo/bar" 3087 // will parse. This seems to be the intent of RFC2396, though the 3088 // grammar does not permit it. If the authority is empty then the 3089 // userInfo, host, and port components are undefined. 3090 // 3091 // DEVIATION from RFC2396: We allow empty relative paths. This seems 3092 // to be the intent of RFC2396, but the grammar does not permit it. 3093 // The primary consequence of this deviation is that "#f" parses as a 3094 // relative URI with an empty path. 3095 // parseHierarchical(int start, int n)3096 private int parseHierarchical(int start, int n) 3097 throws URISyntaxException 3098 { 3099 int p = start; 3100 if (at(p, n, '/') && at(p + 1, n, '/')) { 3101 p += 2; 3102 int q = scan(p, n, "", "/?#"); 3103 if (q > p) { 3104 p = parseAuthority(p, q); 3105 } else if (q < n) { 3106 // DEVIATION: Allow empty authority prior to non-empty 3107 // path, query component or fragment identifier 3108 } else 3109 failExpecting("authority", p); 3110 } 3111 int q = scan(p, n, "", "?#"); // DEVIATION: May be empty 3112 checkChars(p, q, L_PATH, H_PATH, "path"); 3113 path = substring(p, q); 3114 p = q; 3115 if (at(p, n, '?')) { 3116 p++; 3117 q = scan(p, n, "", "#"); 3118 checkChars(p, q, L_URIC, H_URIC, "query"); 3119 query = substring(p, q); 3120 p = q; 3121 } 3122 return p; 3123 } 3124 3125 // authority = server | reg_name 3126 // 3127 // Ambiguity: An authority that is a registry name rather than a server 3128 // might have a prefix that parses as a server. We use the fact that 3129 // the authority component is always followed by '/' or the end of the 3130 // input string to resolve this: If the complete authority did not 3131 // parse as a server then we try to parse it as a registry name. 3132 // parseAuthority(int start, int n)3133 private int parseAuthority(int start, int n) 3134 throws URISyntaxException 3135 { 3136 int p = start; 3137 int q = p; 3138 URISyntaxException ex = null; 3139 3140 boolean serverChars; 3141 boolean regChars; 3142 3143 if (scan(p, n, "", "]") > p) { 3144 // contains a literal IPv6 address, therefore % is allowed 3145 serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n); 3146 } else { 3147 serverChars = (scan(p, n, L_SERVER, H_SERVER) == n); 3148 } 3149 regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n); 3150 3151 if (regChars && !serverChars) { 3152 // Must be a registry-based authority 3153 authority = substring(p, n); 3154 return n; 3155 } 3156 3157 if (serverChars) { 3158 // Might be (probably is) a server-based authority, so attempt 3159 // to parse it as such. If the attempt fails, try to treat it 3160 // as a registry-based authority. 3161 try { 3162 q = parseServer(p, n); 3163 if (q < n) 3164 failExpecting("end of authority", q); 3165 authority = substring(p, n); 3166 } catch (URISyntaxException x) { 3167 // Undo results of failed parse 3168 userInfo = null; 3169 host = null; 3170 port = -1; 3171 if (requireServerAuthority) { 3172 // If we're insisting upon a server-based authority, 3173 // then just re-throw the exception 3174 throw x; 3175 } else { 3176 // Save the exception in case it doesn't parse as a 3177 // registry either 3178 ex = x; 3179 q = p; 3180 } 3181 } 3182 } 3183 3184 if (q < n) { 3185 if (regChars) { 3186 // Registry-based authority 3187 authority = substring(p, n); 3188 } else if (ex != null) { 3189 // Re-throw exception; it was probably due to 3190 // a malformed IPv6 address 3191 throw ex; 3192 } else { 3193 fail("Illegal character in authority", q); 3194 } 3195 } 3196 3197 return n; 3198 } 3199 3200 3201 // [<userinfo>@]<host>[:<port>] 3202 // parseServer(int start, int n)3203 private int parseServer(int start, int n) 3204 throws URISyntaxException 3205 { 3206 int p = start; 3207 int q; 3208 3209 // userinfo 3210 q = scan(p, n, "/?#", "@"); 3211 if ((q >= p) && at(q, n, '@')) { 3212 checkChars(p, q, L_USERINFO, H_USERINFO, "user info"); 3213 userInfo = substring(p, q); 3214 p = q + 1; // Skip '@' 3215 } 3216 3217 // hostname, IPv4 address, or IPv6 address 3218 if (at(p, n, '[')) { 3219 // DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732 3220 p++; 3221 q = scan(p, n, "/?#", "]"); 3222 if ((q > p) && at(q, n, ']')) { 3223 // look for a "%" scope id 3224 int r = scan (p, q, "", "%"); 3225 if (r > p) { 3226 parseIPv6Reference(p, r); 3227 if (r+1 == q) { 3228 fail ("scope id expected"); 3229 } 3230 checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM, 3231 "scope id"); 3232 } else { 3233 parseIPv6Reference(p, q); 3234 } 3235 host = substring(p-1, q+1); 3236 p = q + 1; 3237 } else { 3238 failExpecting("closing bracket for IPv6 address", q); 3239 } 3240 } else { 3241 q = parseIPv4Address(p, n); 3242 if (q <= p) 3243 q = parseHostname(p, n); 3244 p = q; 3245 } 3246 3247 // port 3248 if (at(p, n, ':')) { 3249 p++; 3250 q = scan(p, n, "", "/"); 3251 if (q > p) { 3252 checkChars(p, q, L_DIGIT, H_DIGIT, "port number"); 3253 try { 3254 port = Integer.parseInt(substring(p, q)); 3255 } catch (NumberFormatException x) { 3256 fail("Malformed port number", p); 3257 } 3258 p = q; 3259 } 3260 } 3261 if (p < n) 3262 failExpecting("port number", p); 3263 3264 return p; 3265 } 3266 3267 // Scan a string of decimal digits whose value fits in a byte 3268 // scanByte(int start, int n)3269 private int scanByte(int start, int n) 3270 throws URISyntaxException 3271 { 3272 int p = start; 3273 int q = scan(p, n, L_DIGIT, H_DIGIT); 3274 if (q <= p) return q; 3275 if (Integer.parseInt(substring(p, q)) > 255) return p; 3276 return q; 3277 } 3278 3279 // Scan an IPv4 address. 3280 // 3281 // If the strict argument is true then we require that the given 3282 // interval contain nothing besides an IPv4 address; if it is false 3283 // then we only require that it start with an IPv4 address. 3284 // 3285 // If the interval does not contain or start with (depending upon the 3286 // strict argument) a legal IPv4 address characters then we return -1 3287 // immediately; otherwise we insist that these characters parse as a 3288 // legal IPv4 address and throw an exception on failure. 3289 // 3290 // We assume that any string of decimal digits and dots must be an IPv4 3291 // address. It won't parse as a hostname anyway, so making that 3292 // assumption here allows more meaningful exceptions to be thrown. 3293 // scanIPv4Address(int start, int n, boolean strict)3294 private int scanIPv4Address(int start, int n, boolean strict) 3295 throws URISyntaxException 3296 { 3297 int p = start; 3298 int q; 3299 int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT); 3300 if ((m <= p) || (strict && (m != n))) 3301 return -1; 3302 for (;;) { 3303 // Per RFC2732: At most three digits per byte 3304 // Further constraint: Each element fits in a byte 3305 if ((q = scanByte(p, m)) <= p) break; p = q; 3306 if ((q = scan(p, m, '.')) <= p) break; p = q; 3307 if ((q = scanByte(p, m)) <= p) break; p = q; 3308 if ((q = scan(p, m, '.')) <= p) break; p = q; 3309 if ((q = scanByte(p, m)) <= p) break; p = q; 3310 if ((q = scan(p, m, '.')) <= p) break; p = q; 3311 if ((q = scanByte(p, m)) <= p) break; p = q; 3312 if (q < m) break; 3313 return q; 3314 } 3315 fail("Malformed IPv4 address", q); 3316 return -1; 3317 } 3318 3319 // Take an IPv4 address: Throw an exception if the given interval 3320 // contains anything except an IPv4 address 3321 // takeIPv4Address(int start, int n, String expected)3322 private int takeIPv4Address(int start, int n, String expected) 3323 throws URISyntaxException 3324 { 3325 int p = scanIPv4Address(start, n, true); 3326 if (p <= start) 3327 failExpecting(expected, start); 3328 return p; 3329 } 3330 3331 // Attempt to parse an IPv4 address, returning -1 on failure but 3332 // allowing the given interval to contain [:<characters>] after 3333 // the IPv4 address. 3334 // parseIPv4Address(int start, int n)3335 private int parseIPv4Address(int start, int n) { 3336 int p; 3337 3338 try { 3339 p = scanIPv4Address(start, n, false); 3340 } catch (URISyntaxException x) { 3341 return -1; 3342 } catch (NumberFormatException nfe) { 3343 return -1; 3344 } 3345 3346 if (p > start && p < n) { 3347 // IPv4 address is followed by something - check that 3348 // it's a ":" as this is the only valid character to 3349 // follow an address. 3350 if (charAt(p) != ':') { 3351 p = -1; 3352 } 3353 } 3354 3355 if (p > start) 3356 host = substring(start, p); 3357 3358 return p; 3359 } 3360 3361 // hostname = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ] 3362 // domainlabel = alphanum | alphanum *( alphanum | "-" | "_" ) alphanum 3363 // toplabel = alpha | alpha *( alphanum | "-" | "_" ) alphanum 3364 // parseHostname(int start, int n)3365 private int parseHostname(int start, int n) 3366 throws URISyntaxException 3367 { 3368 int p = start; 3369 int q; 3370 int l = -1; // Start of last parsed label 3371 3372 do { 3373 // domainlabel = alphanum [ *( alphanum | "-" | "_" ) alphanum ] 3374 3375 // RFC1034#section-3.5 doesn't permit empty labels in hostnames, but we accepted 3376 // this prior to N and the behavior is used by some apps. They're accepted for 3377 // compatibility but we produce a warning in the log. 3378 // http://b/25991669 3379 if (p < n && charAt(p) == '.') { 3380 java.lang.System.logE("URI " + substring(start, n) + " has empty labels in " + 3381 "the hostname. This is malformed and will not be accepted" + 3382 "in future Android releases."); 3383 q = ++p; 3384 continue; 3385 } 3386 3387 // The RFCs don't permit underscores in hostnames, but URI has to because a certain 3388 // large website doesn't seem to care about standards and specs. 3389 // http://code.google.com/p/android/issues/detail?id=37577 3390 // http://b/17579865 3391 // http://b/18016625 3392 // http://b/18023709 3393 q = scan(p, n, L_ALPHANUM, H_ALPHANUM); 3394 if (q <= p) 3395 break; 3396 l = p; 3397 if (q > p) { 3398 p = q; 3399 q = scan(p, n, L_ALPHANUM | L_DASH | L_UNDERSCORE, H_ALPHANUM | H_DASH | H_UNDERSCORE); 3400 if (q > p) { 3401 if (charAt(q - 1) == '-') 3402 fail("Illegal character in hostname", q - 1); 3403 p = q; 3404 } 3405 } 3406 q = scan(p, n, '.'); 3407 if (q <= p) 3408 break; 3409 p = q; 3410 } while (p < n); 3411 3412 if ((p < n) && !at(p, n, ':')) 3413 fail("Illegal character in hostname", p); 3414 3415 if (l < 0) 3416 failExpecting("hostname", start); 3417 3418 // for a fully qualified hostname check that the rightmost 3419 // label starts with an alpha character. 3420 if (l > start && !match(charAt(l), L_ALPHA, H_ALPHA)) { 3421 fail("Illegal character in hostname", l); 3422 } 3423 3424 host = substring(start, p); 3425 return p; 3426 } 3427 3428 3429 // IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture 3430 // 3431 // Bug: The grammar in RFC2373 Appendix B does not allow addresses of 3432 // the form ::12.34.56.78, which are clearly shown in the examples 3433 // earlier in the document. Here is the original grammar: 3434 // 3435 // IPv6address = hexpart [ ":" IPv4address ] 3436 // hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ] 3437 // hexseq = hex4 *( ":" hex4) 3438 // hex4 = 1*4HEXDIG 3439 // 3440 // We therefore use the following revised grammar: 3441 // 3442 // IPv6address = hexseq [ ":" IPv4address ] 3443 // | hexseq [ "::" [ hexpost ] ] 3444 // | "::" [ hexpost ] 3445 // hexpost = hexseq | hexseq ":" IPv4address | IPv4address 3446 // hexseq = hex4 *( ":" hex4) 3447 // hex4 = 1*4HEXDIG 3448 // 3449 // This covers all and only the following cases: 3450 // 3451 // hexseq 3452 // hexseq : IPv4address 3453 // hexseq :: 3454 // hexseq :: hexseq 3455 // hexseq :: hexseq : IPv4address 3456 // hexseq :: IPv4address 3457 // :: hexseq 3458 // :: hexseq : IPv4address 3459 // :: IPv4address 3460 // :: 3461 // 3462 // Additionally we constrain the IPv6 address as follows :- 3463 // 3464 // i. IPv6 addresses without compressed zeros should contain 3465 // exactly 16 bytes. 3466 // 3467 // ii. IPv6 addresses with compressed zeros should contain 3468 // less than 16 bytes. 3469 3470 private int ipv6byteCount = 0; 3471 parseIPv6Reference(int start, int n)3472 private int parseIPv6Reference(int start, int n) 3473 throws URISyntaxException 3474 { 3475 int p = start; 3476 int q; 3477 boolean compressedZeros = false; 3478 3479 q = scanHexSeq(p, n); 3480 3481 if (q > p) { 3482 p = q; 3483 if (at(p, n, "::")) { 3484 compressedZeros = true; 3485 p = scanHexPost(p + 2, n); 3486 } else if (at(p, n, ':')) { 3487 p = takeIPv4Address(p + 1, n, "IPv4 address"); 3488 ipv6byteCount += 4; 3489 } 3490 } else if (at(p, n, "::")) { 3491 compressedZeros = true; 3492 p = scanHexPost(p + 2, n); 3493 } 3494 if (p < n) 3495 fail("Malformed IPv6 address", start); 3496 if (ipv6byteCount > 16) 3497 fail("IPv6 address too long", start); 3498 if (!compressedZeros && ipv6byteCount < 16) 3499 fail("IPv6 address too short", start); 3500 if (compressedZeros && ipv6byteCount == 16) 3501 fail("Malformed IPv6 address", start); 3502 3503 return p; 3504 } 3505 scanHexPost(int start, int n)3506 private int scanHexPost(int start, int n) 3507 throws URISyntaxException 3508 { 3509 int p = start; 3510 int q; 3511 3512 if (p == n) 3513 return p; 3514 3515 q = scanHexSeq(p, n); 3516 if (q > p) { 3517 p = q; 3518 if (at(p, n, ':')) { 3519 p++; 3520 p = takeIPv4Address(p, n, "hex digits or IPv4 address"); 3521 ipv6byteCount += 4; 3522 } 3523 } else { 3524 p = takeIPv4Address(p, n, "hex digits or IPv4 address"); 3525 ipv6byteCount += 4; 3526 } 3527 return p; 3528 } 3529 3530 // Scan a hex sequence; return -1 if one could not be scanned 3531 // scanHexSeq(int start, int n)3532 private int scanHexSeq(int start, int n) 3533 throws URISyntaxException 3534 { 3535 int p = start; 3536 int q; 3537 3538 q = scan(p, n, L_HEX, H_HEX); 3539 if (q <= p) 3540 return -1; 3541 if (at(q, n, '.')) // Beginning of IPv4 address 3542 return -1; 3543 if (q > p + 4) 3544 fail("IPv6 hexadecimal digit sequence too long", p); 3545 ipv6byteCount += 2; 3546 p = q; 3547 while (p < n) { 3548 if (!at(p, n, ':')) 3549 break; 3550 if (at(p + 1, n, ':')) 3551 break; // "::" 3552 p++; 3553 q = scan(p, n, L_HEX, H_HEX); 3554 if (q <= p) 3555 failExpecting("digits for an IPv6 address", p); 3556 if (at(q, n, '.')) { // Beginning of IPv4 address 3557 p--; 3558 break; 3559 } 3560 if (q > p + 4) 3561 fail("IPv6 hexadecimal digit sequence too long", p); 3562 ipv6byteCount += 2; 3563 p = q; 3564 } 3565 3566 return p; 3567 } 3568 3569 } 3570 3571 } 3572