1 /* 2 * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.net; 27 28 import java.io.File; 29 import java.io.IOException; 30 import java.io.InputStream; 31 import java.net.spi.URLStreamHandlerProvider; 32 import java.nio.file.Path; 33 import java.security.AccessController; 34 import java.security.PrivilegedAction; 35 import java.util.Hashtable; 36 import java.io.InvalidObjectException; 37 import java.io.ObjectStreamException; 38 import java.io.ObjectStreamField; 39 import java.io.ObjectInputStream.GetField; 40 import java.util.Iterator; 41 import java.util.Locale; 42 import java.util.NoSuchElementException; 43 import java.util.ServiceConfigurationError; 44 import java.util.ServiceLoader; 45 46 import jdk.internal.access.JavaNetURLAccess; 47 import jdk.internal.access.SharedSecrets; 48 import sun.security.util.SecurityConstants; 49 import sun.security.action.GetPropertyAction; 50 51 /** 52 * Class {@code URL} represents a Uniform Resource 53 * Locator, a pointer to a "resource" on the World 54 * Wide Web. A resource can be something as simple as a file or a 55 * directory, or it can be a reference to a more complicated object, 56 * such as a query to a database or to a search engine. More 57 * information on the types of URLs and their formats can be found at: 58 * <a href= 59 * "http://web.archive.org/web/20051219043731/http://archive.ncsa.uiuc.edu/SDG/Software/Mosaic/Demo/url-primer.html"> 60 * <i>Types of URL</i></a> 61 * <p> 62 * In general, a URL can be broken into several parts. Consider the 63 * following example: 64 * <blockquote><pre> 65 * http://www.example.com/docs/resource1.html 66 * </pre></blockquote> 67 * <p> 68 * The URL above indicates that the protocol to use is 69 * {@code http} (HyperText Transfer Protocol) and that the 70 * information resides on a host machine named 71 * {@code www.example.com}. The information on that host 72 * machine is named {@code /docs/resource1.html}. The exact 73 * meaning of this name on the host machine is both protocol 74 * dependent and host dependent. The information normally resides in 75 * a file, but it could be generated on the fly. This component of 76 * the URL is called the <i>path</i> component. 77 * <p> 78 * A URL can optionally specify a "port", which is the 79 * port number to which the TCP connection is made on the remote host 80 * machine. If the port is not specified, the default port for 81 * the protocol is used instead. For example, the default port for 82 * {@code http} is {@code 80}. An alternative port could be 83 * specified as: 84 * <blockquote><pre> 85 * http://www.example.com:1080/docs/resource1.html 86 * </pre></blockquote> 87 * <p> 88 * The syntax of {@code URL} is defined by <a 89 * href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC 2396: Uniform 90 * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a 91 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC 2732: Format for 92 * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format 93 * also supports scope_ids. The syntax and usage of scope_ids is described 94 * <a href="Inet6Address.html#scoped">here</a>. 95 * <p> 96 * A URL may have appended to it a "fragment", also known 97 * as a "ref" or a "reference". The fragment is indicated by the sharp 98 * sign character "#" followed by more characters. For example, 99 * <blockquote><pre> 100 * http://www.example.com/index.html#chapter1 101 * </pre></blockquote> 102 * <p> 103 * This fragment is not technically part of the URL. Rather, it 104 * indicates that after the specified resource is retrieved, the 105 * application is specifically interested in that part of the 106 * document that has the tag {@code chapter1} attached to it. The 107 * meaning of a tag is resource specific. 108 * <p> 109 * An application can also specify a "relative URL", 110 * which contains only enough information to reach the resource 111 * relative to another URL. Relative URLs are frequently used within 112 * HTML pages. For example, if the contents of the URL: 113 * <blockquote><pre> 114 * http://www.example.com/index.html 115 * </pre></blockquote> 116 * contained within it the relative URL: 117 * <blockquote><pre> 118 * FAQ.html 119 * </pre></blockquote> 120 * it would be a shorthand for: 121 * <blockquote><pre> 122 * http://www.example.com/FAQ.html 123 * </pre></blockquote> 124 * <p> 125 * The relative URL need not specify all the components of a URL. If 126 * the protocol, host name, or port number is missing, the value is 127 * inherited from the fully specified URL. The file component must be 128 * specified. The optional fragment is not inherited. 129 * <p> 130 * The URL class does not itself encode or decode any URL components 131 * according to the escaping mechanism defined in RFC2396. It is the 132 * responsibility of the caller to encode any fields, which need to be 133 * escaped prior to calling URL, and also to decode any escaped fields, 134 * that are returned from URL. Furthermore, because URL has no knowledge 135 * of URL escaping, it does not recognise equivalence between the encoded 136 * or decoded form of the same URL. For example, the two URLs:<br> 137 * <pre> http://foo.com/hello world/ and http://foo.com/hello%20world</pre> 138 * would be considered not equal to each other. 139 * <p> 140 * Note, the {@link java.net.URI} class does perform escaping of its 141 * component fields in certain circumstances. The recommended way 142 * to manage the encoding and decoding of URLs is to use {@link java.net.URI}, 143 * and to convert between these two classes using {@link #toURI()} and 144 * {@link URI#toURL()}. 145 * <p> 146 * The {@link URLEncoder} and {@link URLDecoder} classes can also be 147 * used, but only for HTML form encoding, which is not the same 148 * as the encoding scheme defined in RFC2396. 149 * 150 * @apiNote 151 * 152 * Applications working with file paths and file URIs should take great 153 * care to use the appropriate methods to convert between the two. 154 * The {@link Path#of(URI)} factory method and the {@link File#File(URI)} 155 * constructor can be used to create {@link Path} or {@link File} 156 * objects from a file URI. {@link Path#toUri()} and {@link File#toURI()} 157 * can be used to create a {@link URI} from a file path, which can be 158 * converted to URL using {@link URI#toURL()}. 159 * Applications should never try to {@linkplain #URL(String, String, String) 160 * construct} or {@linkplain #URL(String) parse} a {@code URL} 161 * from the direct string representation of a {@code File} or {@code Path} 162 * instance. 163 * <p> 164 * Some components of a URL or URI, such as <i>userinfo</i>, may 165 * be abused to construct misleading URLs or URIs. Applications 166 * that deal with URLs or URIs should take into account 167 * the recommendations advised in <a 168 * href="https://tools.ietf.org/html/rfc3986#section-7">RFC3986, 169 * Section 7, Security Considerations</a>. 170 * 171 * @author James Gosling 172 * @since 1.0 173 */ 174 public final class URL implements java.io.Serializable { 175 176 static final String BUILTIN_HANDLERS_PREFIX = "sun.net.www.protocol"; 177 static final long serialVersionUID = -7627629688361524110L; 178 179 /** 180 * The property which specifies the package prefix list to be scanned 181 * for protocol handlers. The value of this property (if any) should 182 * be a vertical bar delimited list of package names to search through 183 * for a protocol handler to load. The policy of this class is that 184 * all protocol handlers will be in a class called <protocolname>.Handler, 185 * and each package in the list is examined in turn for a matching 186 * handler. If none are found (or the property is not specified), the 187 * default package prefix, sun.net.www.protocol, is used. The search 188 * proceeds from the first package in the list to the last and stops 189 * when a match is found. 190 */ 191 private static final String protocolPathProp = "java.protocol.handler.pkgs"; 192 193 /** 194 * The protocol to use (ftp, http, nntp, ... etc.) . 195 * @serial 196 */ 197 private String protocol; 198 199 /** 200 * The host name to connect to. 201 * @serial 202 */ 203 private String host; 204 205 /** 206 * The protocol port to connect to. 207 * @serial 208 */ 209 private int port = -1; 210 211 /** 212 * The specified file name on that host. {@code file} is 213 * defined as {@code path[?query]} 214 * @serial 215 */ 216 private String file; 217 218 /** 219 * The query part of this URL. 220 */ 221 private transient String query; 222 223 /** 224 * The authority part of this URL. 225 * @serial 226 */ 227 private String authority; 228 229 /** 230 * The path part of this URL. 231 */ 232 private transient String path; 233 234 /** 235 * The userinfo part of this URL. 236 */ 237 private transient String userInfo; 238 239 /** 240 * # reference. 241 * @serial 242 */ 243 private String ref; 244 245 /** 246 * The host's IP address, used in equals and hashCode. 247 * Computed on demand. An uninitialized or unknown hostAddress is null. 248 */ 249 transient InetAddress hostAddress; 250 251 /** 252 * The URLStreamHandler for this URL. 253 */ 254 transient URLStreamHandler handler; 255 256 /* Our hash code. 257 * @serial 258 */ 259 private int hashCode = -1; 260 261 private transient UrlDeserializedState tempState; 262 263 /** 264 * Creates a {@code URL} object from the specified 265 * {@code protocol}, {@code host}, {@code port} 266 * number, and {@code file}.<p> 267 * 268 * {@code host} can be expressed as a host name or a literal 269 * IP address. If IPv6 literal address is used, it should be 270 * enclosed in square brackets ({@code '['} and {@code ']'}), as 271 * specified by <a 272 * href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732</a>; 273 * However, the literal IPv6 address format defined in <a 274 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 2373: IP 275 * Version 6 Addressing Architecture</i></a> is also accepted.<p> 276 * 277 * Specifying a {@code port} number of {@code -1} 278 * indicates that the URL should use the default port for the 279 * protocol.<p> 280 * 281 * If this is the first URL object being created with the specified 282 * protocol, a <i>stream protocol handler</i> object, an instance of 283 * class {@code URLStreamHandler}, is created for that protocol: 284 * <ol> 285 * <li>If the application has previously set up an instance of 286 * {@code URLStreamHandlerFactory} as the stream handler factory, 287 * then the {@code createURLStreamHandler} method of that instance 288 * is called with the protocol string as an argument to create the 289 * stream protocol handler. 290 * <li>If no {@code URLStreamHandlerFactory} has yet been set up, 291 * or if the factory's {@code createURLStreamHandler} method 292 * returns {@code null}, then the {@linkplain java.util.ServiceLoader 293 * ServiceLoader} mechanism is used to locate {@linkplain 294 * java.net.spi.URLStreamHandlerProvider URLStreamHandlerProvider} 295 * implementations using the system class 296 * loader. The order that providers are located is implementation 297 * specific, and an implementation is free to cache the located 298 * providers. A {@linkplain java.util.ServiceConfigurationError 299 * ServiceConfigurationError}, {@code Error} or {@code RuntimeException} 300 * thrown from the {@code createURLStreamHandler}, if encountered, will 301 * be propagated to the calling thread. The {@code 302 * createURLStreamHandler} method of each provider, if instantiated, is 303 * invoked, with the protocol string, until a provider returns non-null, 304 * or all providers have been exhausted. 305 * <li>If the previous step fails to find a protocol handler, the 306 * constructor reads the value of the system property: 307 * <blockquote>{@systemProperty 308 * java.protocol.handler.pkgs 309 * }</blockquote> 310 * If the value of that system property is not {@code null}, 311 * it is interpreted as a list of packages separated by a vertical 312 * slash character '{@code |}'. The constructor tries to load 313 * the class named: 314 * <blockquote>{@code 315 * <package>.<protocol>.Handler 316 * }</blockquote> 317 * where {@code <package>} is replaced by the name of the package 318 * and {@code <protocol>} is replaced by the name of the protocol. 319 * If this class does not exist, or if the class exists but it is not 320 * a subclass of {@code URLStreamHandler}, then the next package 321 * in the list is tried. 322 * <li>If the previous step fails to find a protocol handler, then the 323 * constructor tries to load a built-in protocol handler. 324 * If this class does not exist, or if the class exists but it is not a 325 * subclass of {@code URLStreamHandler}, then a 326 * {@code MalformedURLException} is thrown. 327 * </ol> 328 * 329 * <p>Protocol handlers for the following protocols are guaranteed 330 * to exist on the search path :- 331 * <blockquote><pre> 332 * http, https, file, and jar 333 * </pre></blockquote> 334 * Protocol handlers for additional protocols may also be available. 335 * Some protocol handlers, for example those used for loading platform 336 * classes or classes on the class path, may not be overridden. The details 337 * of such restrictions, and when those restrictions apply (during 338 * initialization of the runtime for example), are implementation specific 339 * and therefore not specified 340 * 341 * <p>No validation of the inputs is performed by this constructor. 342 * 343 * @param protocol the name of the protocol to use. 344 * @param host the name of the host. 345 * @param port the port number on the host. 346 * @param file the file on the host 347 * @exception MalformedURLException if an unknown protocol or the port 348 * is a negative number other than -1 349 * @see java.lang.System#getProperty(java.lang.String) 350 * @see java.net.URL#setURLStreamHandlerFactory( 351 * java.net.URLStreamHandlerFactory) 352 * @see java.net.URLStreamHandler 353 * @see java.net.URLStreamHandlerFactory#createURLStreamHandler( 354 * java.lang.String) 355 */ 356 public URL(String protocol, String host, int port, String file) 357 throws MalformedURLException 358 { 359 this(protocol, host, port, file, null); 360 } 361 362 /** 363 * Creates a URL from the specified {@code protocol} 364 * name, {@code host} name, and {@code file} name. The 365 * default port for the specified protocol is used. 366 * <p> 367 * This constructor is equivalent to the four-argument 368 * constructor with the only difference of using the 369 * default port for the specified protocol. 370 * 371 * No validation of the inputs is performed by this constructor. 372 * 373 * @param protocol the name of the protocol to use. 374 * @param host the name of the host. 375 * @param file the file on the host. 376 * @exception MalformedURLException if an unknown protocol is specified. 377 * @see java.net.URL#URL(java.lang.String, java.lang.String, 378 * int, java.lang.String) 379 */ 380 public URL(String protocol, String host, String file) 381 throws MalformedURLException { 382 this(protocol, host, -1, file); 383 } 384 385 /** 386 * Creates a {@code URL} object from the specified 387 * {@code protocol}, {@code host}, {@code port} 388 * number, {@code file}, and {@code handler}. Specifying 389 * a {@code port} number of {@code -1} indicates that 390 * the URL should use the default port for the protocol. Specifying 391 * a {@code handler} of {@code null} indicates that the URL 392 * should use a default stream handler for the protocol, as outlined 393 * for: 394 * java.net.URL#URL(java.lang.String, java.lang.String, int, 395 * java.lang.String) 396 * 397 * <p>If the handler is not null and there is a security manager, 398 * the security manager's {@code checkPermission} 399 * method is called with a 400 * {@code NetPermission("specifyStreamHandler")} permission. 401 * This may result in a SecurityException. 402 * 403 * No validation of the inputs is performed by this constructor. 404 * 405 * @param protocol the name of the protocol to use. 406 * @param host the name of the host. 407 * @param port the port number on the host. 408 * @param file the file on the host 409 * @param handler the stream handler for the URL. 410 * @exception MalformedURLException if an unknown protocol or the port 411 is a negative number other than -1 412 * @exception SecurityException 413 * if a security manager exists and its 414 * {@code checkPermission} method doesn't allow 415 * specifying a stream handler explicitly. 416 * @see java.lang.System#getProperty(java.lang.String) 417 * @see java.net.URL#setURLStreamHandlerFactory( 418 * java.net.URLStreamHandlerFactory) 419 * @see java.net.URLStreamHandler 420 * @see java.net.URLStreamHandlerFactory#createURLStreamHandler( 421 * java.lang.String) 422 * @see SecurityManager#checkPermission 423 * @see java.net.NetPermission 424 */ 425 public URL(String protocol, String host, int port, String file, 426 URLStreamHandler handler) throws MalformedURLException { 427 if (handler != null) { 428 SecurityManager sm = System.getSecurityManager(); 429 if (sm != null) { 430 // check for permission to specify a handler 431 checkSpecifyHandler(sm); 432 } 433 } 434 435 protocol = toLowerCase(protocol); 436 this.protocol = protocol; 437 if (host != null) { 438 439 /** 440 * if host is a literal IPv6 address, 441 * we will make it conform to RFC 2732 442 */ 443 if (host.indexOf(':') >= 0 && !host.startsWith("[")) { 444 host = "["+host+"]"; 445 } 446 this.host = host; 447 448 if (port < -1) { 449 throw new MalformedURLException("Invalid port number :" + 450 port); 451 } 452 this.port = port; 453 authority = (port == -1) ? host : host + ":" + port; 454 } 455 456 int index = file.indexOf('#'); 457 this.ref = index < 0 ? null : file.substring(index + 1); 458 file = index < 0 ? file : file.substring(0, index); 459 int q = file.lastIndexOf('?'); 460 if (q != -1) { 461 this.query = file.substring(q + 1); 462 this.path = file.substring(0, q); 463 this.file = path + "?" + query; 464 } else { 465 this.path = file; 466 this.file = path; 467 } 468 469 // Note: we don't do validation of the URL here. Too risky to change 470 // right now, but worth considering for future reference. -br 471 if (handler == null && 472 (handler = getURLStreamHandler(protocol)) == null) { 473 throw new MalformedURLException("unknown protocol: " + protocol); 474 } 475 this.handler = handler; 476 } 477 478 /** 479 * Creates a {@code URL} object from the {@code String} 480 * representation. 481 * <p> 482 * This constructor is equivalent to a call to the two-argument 483 * constructor with a {@code null} first argument. 484 * 485 * @param spec the {@code String} to parse as a URL. 486 * @exception MalformedURLException if no protocol is specified, or an 487 * unknown protocol is found, or {@code spec} is {@code null}, 488 * or the parsed URL fails to comply with the specific syntax 489 * of the associated protocol. 490 * @see java.net.URL#URL(java.net.URL, java.lang.String) 491 */ 492 public URL(String spec) throws MalformedURLException { 493 this(null, spec); 494 } 495 496 /** 497 * Creates a URL by parsing the given spec within a specified context. 498 * 499 * The new URL is created from the given context URL and the spec 500 * argument as described in 501 * RFC2396 "Uniform Resource Identifiers : Generic * Syntax" : 502 * <blockquote><pre> 503 * <scheme>://<authority><path>?<query>#<fragment> 504 * </pre></blockquote> 505 * The reference is parsed into the scheme, authority, path, query and 506 * fragment parts. If the path component is empty and the scheme, 507 * authority, and query components are undefined, then the new URL is a 508 * reference to the current document. Otherwise, the fragment and query 509 * parts present in the spec are used in the new URL. 510 * <p> 511 * If the scheme component is defined in the given spec and does not match 512 * the scheme of the context, then the new URL is created as an absolute 513 * URL based on the spec alone. Otherwise the scheme component is inherited 514 * from the context URL. 515 * <p> 516 * If the authority component is present in the spec then the spec is 517 * treated as absolute and the spec authority and path will replace the 518 * context authority and path. If the authority component is absent in the 519 * spec then the authority of the new URL will be inherited from the 520 * context. 521 * <p> 522 * If the spec's path component begins with a slash character 523 * "/" then the 524 * path is treated as absolute and the spec path replaces the context path. 525 * <p> 526 * Otherwise, the path is treated as a relative path and is appended to the 527 * context path, as described in RFC2396. Also, in this case, 528 * the path is canonicalized through the removal of directory 529 * changes made by occurrences of ".." and ".". 530 * <p> 531 * For a more detailed description of URL parsing, refer to RFC2396. 532 * 533 * @param context the context in which to parse the specification. 534 * @param spec the {@code String} to parse as a URL. 535 * @exception MalformedURLException if no protocol is specified, or an 536 * unknown protocol is found, or {@code spec} is {@code null}, 537 * or the parsed URL fails to comply with the specific syntax 538 * of the associated protocol. 539 * @see java.net.URL#URL(java.lang.String, java.lang.String, 540 * int, java.lang.String) 541 * @see java.net.URLStreamHandler 542 * @see java.net.URLStreamHandler#parseURL(java.net.URL, 543 * java.lang.String, int, int) 544 */ 545 public URL(URL context, String spec) throws MalformedURLException { 546 this(context, spec, null); 547 } 548 549 /** 550 * Creates a URL by parsing the given spec with the specified handler 551 * within a specified context. If the handler is null, the parsing 552 * occurs as with the two argument constructor. 553 * 554 * @param context the context in which to parse the specification. 555 * @param spec the {@code String} to parse as a URL. 556 * @param handler the stream handler for the URL. 557 * @exception MalformedURLException if no protocol is specified, or an 558 * unknown protocol is found, or {@code spec} is {@code null}, 559 * or the parsed URL fails to comply with the specific syntax 560 * of the associated protocol. 561 * @exception SecurityException 562 * if a security manager exists and its 563 * {@code checkPermission} method doesn't allow 564 * specifying a stream handler. 565 * @see java.net.URL#URL(java.lang.String, java.lang.String, 566 * int, java.lang.String) 567 * @see java.net.URLStreamHandler 568 * @see java.net.URLStreamHandler#parseURL(java.net.URL, 569 * java.lang.String, int, int) 570 */ 571 public URL(URL context, String spec, URLStreamHandler handler) 572 throws MalformedURLException 573 { 574 String original = spec; 575 int i, limit, c; 576 int start = 0; 577 String newProtocol = null; 578 boolean aRef=false; 579 boolean isRelative = false; 580 581 // Check for permission to specify a handler 582 if (handler != null) { 583 SecurityManager sm = System.getSecurityManager(); 584 if (sm != null) { 585 checkSpecifyHandler(sm); 586 } 587 } 588 589 try { 590 limit = spec.length(); 591 while ((limit > 0) && (spec.charAt(limit - 1) <= ' ')) { 592 limit--; //eliminate trailing whitespace 593 } 594 while ((start < limit) && (spec.charAt(start) <= ' ')) { 595 start++; // eliminate leading whitespace 596 } 597 598 if (spec.regionMatches(true, start, "url:", 0, 4)) { 599 start += 4; 600 } 601 if (start < spec.length() && spec.charAt(start) == '#') { 602 /* we're assuming this is a ref relative to the context URL. 603 * This means protocols cannot start w/ '#', but we must parse 604 * ref URL's like: "hello:there" w/ a ':' in them. 605 */ 606 aRef=true; 607 } 608 for (i = start ; !aRef && (i < limit) && 609 ((c = spec.charAt(i)) != '/') ; i++) { 610 if (c == ':') { 611 String s = toLowerCase(spec.substring(start, i)); 612 if (isValidProtocol(s)) { 613 newProtocol = s; 614 start = i + 1; 615 } 616 break; 617 } 618 } 619 620 // Only use our context if the protocols match. 621 protocol = newProtocol; 622 if ((context != null) && ((newProtocol == null) || 623 newProtocol.equalsIgnoreCase(context.protocol))) { 624 // inherit the protocol handler from the context 625 // if not specified to the constructor 626 if (handler == null) { 627 handler = context.handler; 628 } 629 630 // If the context is a hierarchical URL scheme and the spec 631 // contains a matching scheme then maintain backwards 632 // compatibility and treat it as if the spec didn't contain 633 // the scheme; see 5.2.3 of RFC2396 634 if (context.path != null && context.path.startsWith("/")) 635 newProtocol = null; 636 637 if (newProtocol == null) { 638 protocol = context.protocol; 639 authority = context.authority; 640 userInfo = context.userInfo; 641 host = context.host; 642 port = context.port; 643 file = context.file; 644 path = context.path; 645 isRelative = true; 646 } 647 } 648 649 if (protocol == null) { 650 throw new MalformedURLException("no protocol: "+original); 651 } 652 653 // Get the protocol handler if not specified or the protocol 654 // of the context could not be used 655 if (handler == null && 656 (handler = getURLStreamHandler(protocol)) == null) { 657 throw new MalformedURLException("unknown protocol: "+protocol); 658 } 659 660 this.handler = handler; 661 662 i = spec.indexOf('#', start); 663 if (i >= 0) { 664 ref = spec.substring(i + 1, limit); 665 limit = i; 666 } 667 668 /* 669 * Handle special case inheritance of query and fragment 670 * implied by RFC2396 section 5.2.2. 671 */ 672 if (isRelative && start == limit) { 673 query = context.query; 674 if (ref == null) { 675 ref = context.ref; 676 } 677 } 678 679 handler.parseURL(this, spec, start, limit); 680 681 } catch(MalformedURLException e) { 682 throw e; 683 } catch(Exception e) { 684 MalformedURLException exception = new MalformedURLException(e.getMessage()); 685 exception.initCause(e); 686 throw exception; 687 } 688 } 689 690 /** 691 * Creates a URL from a URI, as if by invoking {@code uri.toURL()}. 692 * 693 * @see java.net.URI#toURL() 694 */ 695 static URL fromURI(URI uri) throws MalformedURLException { 696 if (!uri.isAbsolute()) { 697 throw new IllegalArgumentException("URI is not absolute"); 698 } 699 String protocol = uri.getScheme(); 700 701 // In general we need to go via Handler.parseURL, but for the jrt 702 // protocol we enforce that the Handler is not overrideable and can 703 // optimize URI to URL conversion. 704 // 705 // Case-sensitive comparison for performance; malformed protocols will 706 // be handled correctly by the slow path. 707 if (protocol.equals("jrt") && !uri.isOpaque() 708 && uri.getRawFragment() == null) { 709 710 String query = uri.getRawQuery(); 711 String path = uri.getRawPath(); 712 String file = (query == null) ? path : path + "?" + query; 713 714 // URL represent undefined host as empty string while URI use null 715 String host = uri.getHost(); 716 if (host == null) { 717 host = ""; 718 } 719 720 int port = uri.getPort(); 721 722 return new URL("jrt", host, port, file, null); 723 } else { 724 return new URL((URL)null, uri.toString(), null); 725 } 726 } 727 728 /* 729 * Returns true if specified string is a valid protocol name. 730 */ 731 private boolean isValidProtocol(String protocol) { 732 int len = protocol.length(); 733 if (len < 1) 734 return false; 735 char c = protocol.charAt(0); 736 if (!Character.isLetter(c)) 737 return false; 738 for (int i = 1; i < len; i++) { 739 c = protocol.charAt(i); 740 if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && 741 c != '-') { 742 return false; 743 } 744 } 745 return true; 746 } 747 748 /* 749 * Checks for permission to specify a stream handler. 750 */ 751 private void checkSpecifyHandler(SecurityManager sm) { 752 sm.checkPermission(SecurityConstants.SPECIFY_HANDLER_PERMISSION); 753 } 754 755 /** 756 * Sets the fields of the URL. This is not a public method so that 757 * only URLStreamHandlers can modify URL fields. URLs are 758 * otherwise constant. 759 * 760 * @param protocol the name of the protocol to use 761 * @param host the name of the host 762 @param port the port number on the host 763 * @param file the file on the host 764 * @param ref the internal reference in the URL 765 */ 766 void set(String protocol, String host, int port, 767 String file, String ref) { 768 synchronized (this) { 769 this.protocol = protocol; 770 this.host = host; 771 authority = port == -1 ? host : host + ":" + port; 772 this.port = port; 773 this.file = file; 774 this.ref = ref; 775 /* This is very important. We must recompute this after the 776 * URL has been changed. */ 777 hashCode = -1; 778 hostAddress = null; 779 int q = file.lastIndexOf('?'); 780 if (q != -1) { 781 query = file.substring(q+1); 782 path = file.substring(0, q); 783 } else 784 path = file; 785 } 786 } 787 788 /** 789 * Sets the specified 8 fields of the URL. This is not a public method so 790 * that only URLStreamHandlers can modify URL fields. URLs are otherwise 791 * constant. 792 * 793 * @param protocol the name of the protocol to use 794 * @param host the name of the host 795 * @param port the port number on the host 796 * @param authority the authority part for the url 797 * @param userInfo the username and password 798 * @param path the file on the host 799 * @param ref the internal reference in the URL 800 * @param query the query part of this URL 801 * @since 1.3 802 */ 803 void set(String protocol, String host, int port, 804 String authority, String userInfo, String path, 805 String query, String ref) { 806 synchronized (this) { 807 this.protocol = protocol; 808 this.host = host; 809 this.port = port; 810 this.file = query == null ? path : path + "?" + query; 811 this.userInfo = userInfo; 812 this.path = path; 813 this.ref = ref; 814 /* This is very important. We must recompute this after the 815 * URL has been changed. */ 816 hashCode = -1; 817 hostAddress = null; 818 this.query = query; 819 this.authority = authority; 820 } 821 } 822 823 /** 824 * Gets the query part of this {@code URL}. 825 * 826 * @return the query part of this {@code URL}, 827 * or <CODE>null</CODE> if one does not exist 828 * @since 1.3 829 */ 830 public String getQuery() { 831 return query; 832 } 833 834 /** 835 * Gets the path part of this {@code URL}. 836 * 837 * @return the path part of this {@code URL}, or an 838 * empty string if one does not exist 839 * @since 1.3 840 */ 841 public String getPath() { 842 return path; 843 } 844 845 /** 846 * Gets the userInfo part of this {@code URL}. 847 * 848 * @return the userInfo part of this {@code URL}, or 849 * <CODE>null</CODE> if one does not exist 850 * @since 1.3 851 */ 852 public String getUserInfo() { 853 return userInfo; 854 } 855 856 /** 857 * Gets the authority part of this {@code URL}. 858 * 859 * @return the authority part of this {@code URL} 860 * @since 1.3 861 */ 862 public String getAuthority() { 863 return authority; 864 } 865 866 /** 867 * Gets the port number of this {@code URL}. 868 * 869 * @return the port number, or -1 if the port is not set 870 */ 871 public int getPort() { 872 return port; 873 } 874 875 /** 876 * Gets the default port number of the protocol associated 877 * with this {@code URL}. If the URL scheme or the URLStreamHandler 878 * for the URL do not define a default port number, 879 * then -1 is returned. 880 * 881 * @return the port number 882 * @since 1.4 883 */ 884 public int getDefaultPort() { 885 return handler.getDefaultPort(); 886 } 887 888 /** 889 * Gets the protocol name of this {@code URL}. 890 * 891 * @return the protocol of this {@code URL}. 892 */ 893 public String getProtocol() { 894 return protocol; 895 } 896 897 /** 898 * Gets the host name of this {@code URL}, if applicable. 899 * The format of the host conforms to RFC 2732, i.e. for a 900 * literal IPv6 address, this method will return the IPv6 address 901 * enclosed in square brackets ({@code '['} and {@code ']'}). 902 * 903 * @return the host name of this {@code URL}. 904 */ 905 public String getHost() { 906 return host; 907 } 908 909 /** 910 * Gets the file name of this {@code URL}. 911 * The returned file portion will be 912 * the same as <CODE>getPath()</CODE>, plus the concatenation of 913 * the value of <CODE>getQuery()</CODE>, if any. If there is 914 * no query portion, this method and <CODE>getPath()</CODE> will 915 * return identical results. 916 * 917 * @return the file name of this {@code URL}, 918 * or an empty string if one does not exist 919 */ 920 public String getFile() { 921 return file; 922 } 923 924 /** 925 * Gets the anchor (also known as the "reference") of this 926 * {@code URL}. 927 * 928 * @return the anchor (also known as the "reference") of this 929 * {@code URL}, or <CODE>null</CODE> if one does not exist 930 */ 931 public String getRef() { 932 return ref; 933 } 934 935 /** 936 * Compares this URL for equality with another object.<p> 937 * 938 * If the given object is not a URL then this method immediately returns 939 * {@code false}.<p> 940 * 941 * Two URL objects are equal if they have the same protocol, reference 942 * equivalent hosts, have the same port number on the host, and the same 943 * file and fragment of the file.<p> 944 * 945 * Two hosts are considered equivalent if both host names can be resolved 946 * into the same IP addresses; else if either host name can't be 947 * resolved, the host names must be equal without regard to case; or both 948 * host names equal to null.<p> 949 * 950 * Since hosts comparison requires name resolution, this operation is a 951 * blocking operation. <p> 952 * 953 * Note: The defined behavior for {@code equals} is known to 954 * be inconsistent with virtual hosting in HTTP. 955 * 956 * @param obj the URL to compare against. 957 * @return {@code true} if the objects are the same; 958 * {@code false} otherwise. 959 */ 960 public boolean equals(Object obj) { 961 if (!(obj instanceof URL)) 962 return false; 963 URL u2 = (URL)obj; 964 965 return handler.equals(this, u2); 966 } 967 968 /** 969 * Creates an integer suitable for hash table indexing.<p> 970 * 971 * The hash code is based upon all the URL components relevant for URL 972 * comparison. As such, this operation is a blocking operation. 973 * 974 * @return a hash code for this {@code URL}. 975 */ 976 public synchronized int hashCode() { 977 if (hashCode != -1) 978 return hashCode; 979 980 hashCode = handler.hashCode(this); 981 return hashCode; 982 } 983 984 /** 985 * Compares two URLs, excluding the fragment component.<p> 986 * 987 * Returns {@code true} if this {@code URL} and the 988 * {@code other} argument are equal without taking the 989 * fragment component into consideration. 990 * 991 * @param other the {@code URL} to compare against. 992 * @return {@code true} if they reference the same remote object; 993 * {@code false} otherwise. 994 */ 995 public boolean sameFile(URL other) { 996 return handler.sameFile(this, other); 997 } 998 999 /** 1000 * Constructs a string representation of this {@code URL}. The 1001 * string is created by calling the {@code toExternalForm} 1002 * method of the stream protocol handler for this object. 1003 * 1004 * @return a string representation of this object. 1005 * @see java.net.URL#URL(java.lang.String, java.lang.String, int, 1006 * java.lang.String) 1007 * @see java.net.URLStreamHandler#toExternalForm(java.net.URL) 1008 */ 1009 public String toString() { 1010 return toExternalForm(); 1011 } 1012 1013 /** 1014 * Constructs a string representation of this {@code URL}. The 1015 * string is created by calling the {@code toExternalForm} 1016 * method of the stream protocol handler for this object. 1017 * 1018 * @return a string representation of this object. 1019 * @see java.net.URL#URL(java.lang.String, java.lang.String, 1020 * int, java.lang.String) 1021 * @see java.net.URLStreamHandler#toExternalForm(java.net.URL) 1022 */ 1023 public String toExternalForm() { 1024 return handler.toExternalForm(this); 1025 } 1026 1027 /** 1028 * Returns a {@link java.net.URI} equivalent to this URL. 1029 * This method functions in the same way as {@code new URI (this.toString())}. 1030 * <p>Note, any URL instance that complies with RFC 2396 can be converted 1031 * to a URI. However, some URLs that are not strictly in compliance 1032 * can not be converted to a URI. 1033 * 1034 * @exception URISyntaxException if this URL is not formatted strictly according to 1035 * RFC2396 and cannot be converted to a URI. 1036 * 1037 * @return a URI instance equivalent to this URL. 1038 * @since 1.5 1039 */ 1040 public URI toURI() throws URISyntaxException { 1041 return new URI (toString()); 1042 } 1043 1044 /** 1045 * Returns a {@link java.net.URLConnection URLConnection} instance that 1046 * represents a connection to the remote object referred to by the 1047 * {@code URL}. 1048 * 1049 * <P>A new instance of {@linkplain java.net.URLConnection URLConnection} is 1050 * created every time when invoking the 1051 * {@linkplain java.net.URLStreamHandler#openConnection(URL) 1052 * URLStreamHandler.openConnection(URL)} method of the protocol handler for 1053 * this URL.</P> 1054 * 1055 * <P>It should be noted that a URLConnection instance does not establish 1056 * the actual network connection on creation. This will happen only when 1057 * calling {@linkplain java.net.URLConnection#connect() URLConnection.connect()}.</P> 1058 * 1059 * <P>If for the URL's protocol (such as HTTP or JAR), there 1060 * exists a public, specialized URLConnection subclass belonging 1061 * to one of the following packages or one of their subpackages: 1062 * java.lang, java.io, java.util, java.net, the connection 1063 * returned will be of that subclass. For example, for HTTP an 1064 * HttpURLConnection will be returned, and for JAR a 1065 * JarURLConnection will be returned.</P> 1066 * 1067 * @return a {@link java.net.URLConnection URLConnection} linking 1068 * to the URL. 1069 * @exception IOException if an I/O exception occurs. 1070 * @see java.net.URL#URL(java.lang.String, java.lang.String, 1071 * int, java.lang.String) 1072 */ 1073 public URLConnection openConnection() throws java.io.IOException { 1074 return handler.openConnection(this); 1075 } 1076 1077 /** 1078 * Same as {@link #openConnection()}, except that the connection will be 1079 * made through the specified proxy; Protocol handlers that do not 1080 * support proxying will ignore the proxy parameter and make a 1081 * normal connection. 1082 * 1083 * Invoking this method preempts the system's default 1084 * {@link java.net.ProxySelector ProxySelector} settings. 1085 * 1086 * @param proxy the Proxy through which this connection 1087 * will be made. If direct connection is desired, 1088 * Proxy.NO_PROXY should be specified. 1089 * @return a {@code URLConnection} to the URL. 1090 * @exception IOException if an I/O exception occurs. 1091 * @exception SecurityException if a security manager is present 1092 * and the caller doesn't have permission to connect 1093 * to the proxy. 1094 * @exception IllegalArgumentException will be thrown if proxy is null, 1095 * or proxy has the wrong type 1096 * @exception UnsupportedOperationException if the subclass that 1097 * implements the protocol handler doesn't support 1098 * this method. 1099 * @see java.net.URL#URL(java.lang.String, java.lang.String, 1100 * int, java.lang.String) 1101 * @see java.net.URLConnection 1102 * @see java.net.URLStreamHandler#openConnection(java.net.URL, 1103 * java.net.Proxy) 1104 * @since 1.5 1105 */ 1106 public URLConnection openConnection(Proxy proxy) 1107 throws java.io.IOException { 1108 if (proxy == null) { 1109 throw new IllegalArgumentException("proxy can not be null"); 1110 } 1111 1112 // Create a copy of Proxy as a security measure 1113 Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy); 1114 SecurityManager sm = System.getSecurityManager(); 1115 if (p.type() != Proxy.Type.DIRECT && sm != null) { 1116 InetSocketAddress epoint = (InetSocketAddress) p.address(); 1117 if (epoint.isUnresolved()) 1118 sm.checkConnect(epoint.getHostName(), epoint.getPort()); 1119 else 1120 sm.checkConnect(epoint.getAddress().getHostAddress(), 1121 epoint.getPort()); 1122 } 1123 return handler.openConnection(this, p); 1124 } 1125 1126 /** 1127 * Opens a connection to this {@code URL} and returns an 1128 * {@code InputStream} for reading from that connection. This 1129 * method is a shorthand for: 1130 * <blockquote><pre> 1131 * openConnection().getInputStream() 1132 * </pre></blockquote> 1133 * 1134 * @return an input stream for reading from the URL connection. 1135 * @exception IOException if an I/O exception occurs. 1136 * @see java.net.URL#openConnection() 1137 * @see java.net.URLConnection#getInputStream() 1138 */ 1139 public final InputStream openStream() throws java.io.IOException { 1140 return openConnection().getInputStream(); 1141 } 1142 1143 /** 1144 * Gets the contents of this URL. This method is a shorthand for: 1145 * <blockquote><pre> 1146 * openConnection().getContent() 1147 * </pre></blockquote> 1148 * 1149 * @return the contents of this URL. 1150 * @exception IOException if an I/O exception occurs. 1151 * @see java.net.URLConnection#getContent() 1152 */ 1153 public final Object getContent() throws java.io.IOException { 1154 return openConnection().getContent(); 1155 } 1156 1157 /** 1158 * Gets the contents of this URL. This method is a shorthand for: 1159 * <blockquote><pre> 1160 * openConnection().getContent(classes) 1161 * </pre></blockquote> 1162 * 1163 * @param classes an array of Java types 1164 * @return the content object of this URL that is the first match of 1165 * the types specified in the classes array. 1166 * null if none of the requested types are supported. 1167 * @exception IOException if an I/O exception occurs. 1168 * @see java.net.URLConnection#getContent(Class[]) 1169 * @since 1.3 1170 */ 1171 public final Object getContent(Class<?>[] classes) 1172 throws java.io.IOException { 1173 return openConnection().getContent(classes); 1174 } 1175 1176 /** 1177 * The URLStreamHandler factory. 1178 */ 1179 private static volatile URLStreamHandlerFactory factory; 1180 1181 /** 1182 * Sets an application's {@code URLStreamHandlerFactory}. 1183 * This method can be called at most once in a given Java Virtual 1184 * Machine. 1185 * 1186 *<p> The {@code URLStreamHandlerFactory} instance is used to 1187 *construct a stream protocol handler from a protocol name. 1188 * 1189 * <p> If there is a security manager, this method first calls 1190 * the security manager's {@code checkSetFactory} method 1191 * to ensure the operation is allowed. 1192 * This could result in a SecurityException. 1193 * 1194 * @param fac the desired factory. 1195 * @exception Error if the application has already set a factory. 1196 * @exception SecurityException if a security manager exists and its 1197 * {@code checkSetFactory} method doesn't allow 1198 * the operation. 1199 * @see java.net.URL#URL(java.lang.String, java.lang.String, 1200 * int, java.lang.String) 1201 * @see java.net.URLStreamHandlerFactory 1202 * @see SecurityManager#checkSetFactory 1203 */ 1204 public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) { 1205 synchronized (streamHandlerLock) { 1206 if (factory != null) { 1207 throw new Error("factory already defined"); 1208 } 1209 SecurityManager security = System.getSecurityManager(); 1210 if (security != null) { 1211 security.checkSetFactory(); 1212 } 1213 handlers.clear(); 1214 1215 // safe publication of URLStreamHandlerFactory with volatile write 1216 factory = fac; 1217 } 1218 } 1219 1220 private static final URLStreamHandlerFactory defaultFactory = new DefaultFactory(); 1221 1222 private static class DefaultFactory implements URLStreamHandlerFactory { 1223 private static String PREFIX = "sun.net.www.protocol."; 1224 1225 public URLStreamHandler createURLStreamHandler(String protocol) { 1226 // Avoid using reflection during bootstrap 1227 switch (protocol) { 1228 case "file": 1229 return new sun.net.www.protocol.file.Handler(); 1230 case "jar": 1231 return new sun.net.www.protocol.jar.Handler(); 1232 case "jrt": 1233 return new sun.net.www.protocol.jrt.Handler(); 1234 } 1235 String name = PREFIX + protocol + ".Handler"; 1236 try { 1237 Object o = Class.forName(name).getDeclaredConstructor().newInstance(); 1238 return (URLStreamHandler)o; 1239 } catch (Exception e) { 1240 // For compatibility, all Exceptions are ignored. 1241 // any number of exceptions can get thrown here 1242 } 1243 return null; 1244 } 1245 } 1246 1247 private static URLStreamHandler lookupViaProperty(String protocol) { 1248 String packagePrefixList = 1249 GetPropertyAction.privilegedGetProperty(protocolPathProp); 1250 if (packagePrefixList == null) { 1251 // not set 1252 return null; 1253 } 1254 1255 String[] packagePrefixes = packagePrefixList.split("\\|"); 1256 URLStreamHandler handler = null; 1257 for (int i=0; handler == null && i<packagePrefixes.length; i++) { 1258 String packagePrefix = packagePrefixes[i].trim(); 1259 try { 1260 String clsName = packagePrefix + "." + protocol + ".Handler"; 1261 Class<?> cls = null; 1262 try { 1263 cls = Class.forName(clsName); 1264 } catch (ClassNotFoundException e) { 1265 ClassLoader cl = ClassLoader.getSystemClassLoader(); 1266 if (cl != null) { 1267 cls = cl.loadClass(clsName); 1268 } 1269 } 1270 if (cls != null) { 1271 @SuppressWarnings("deprecation") 1272 Object tmp = cls.newInstance(); 1273 handler = (URLStreamHandler)tmp; 1274 } 1275 } catch (Exception e) { 1276 // any number of exceptions can get thrown here 1277 } 1278 } 1279 return handler; 1280 } 1281 1282 private static Iterator<URLStreamHandlerProvider> providers() { 1283 return new Iterator<>() { 1284 1285 ClassLoader cl = ClassLoader.getSystemClassLoader(); 1286 ServiceLoader<URLStreamHandlerProvider> sl = 1287 ServiceLoader.load(URLStreamHandlerProvider.class, cl); 1288 Iterator<URLStreamHandlerProvider> i = sl.iterator(); 1289 1290 URLStreamHandlerProvider next = null; 1291 1292 private boolean getNext() { 1293 while (next == null) { 1294 try { 1295 if (!i.hasNext()) 1296 return false; 1297 next = i.next(); 1298 } catch (ServiceConfigurationError sce) { 1299 if (sce.getCause() instanceof SecurityException) { 1300 // Ignore security exceptions 1301 continue; 1302 } 1303 throw sce; 1304 } 1305 } 1306 return true; 1307 } 1308 1309 public boolean hasNext() { 1310 return getNext(); 1311 } 1312 1313 public URLStreamHandlerProvider next() { 1314 if (!getNext()) 1315 throw new NoSuchElementException(); 1316 URLStreamHandlerProvider n = next; 1317 next = null; 1318 return n; 1319 } 1320 }; 1321 } 1322 1323 // Thread-local gate to prevent recursive provider lookups 1324 private static ThreadLocal<Object> gate = new ThreadLocal<>(); 1325 1326 private static URLStreamHandler lookupViaProviders(final String protocol) { 1327 if (gate.get() != null) 1328 throw new Error("Circular loading of URL stream handler providers detected"); 1329 1330 gate.set(gate); 1331 try { 1332 return AccessController.doPrivileged( 1333 new PrivilegedAction<>() { 1334 public URLStreamHandler run() { 1335 Iterator<URLStreamHandlerProvider> itr = providers(); 1336 while (itr.hasNext()) { 1337 URLStreamHandlerProvider f = itr.next(); 1338 URLStreamHandler h = f.createURLStreamHandler(protocol); 1339 if (h != null) 1340 return h; 1341 } 1342 return null; 1343 } 1344 }); 1345 } finally { 1346 gate.set(null); 1347 } 1348 } 1349 1350 /** 1351 * Returns the protocol in lower case. Special cases known protocols 1352 * to avoid loading locale classes during startup. 1353 */ 1354 static String toLowerCase(String protocol) { 1355 if (protocol.equals("jrt") || protocol.equals("file") || protocol.equals("jar")) { 1356 return protocol; 1357 } else { 1358 return protocol.toLowerCase(Locale.ROOT); 1359 } 1360 } 1361 1362 /** 1363 * Non-overrideable protocols: "jrt" and "file" 1364 * 1365 * Character-based comparison for performance reasons; also ensures 1366 * case-insensitive comparison in a locale-independent fashion. 1367 */ 1368 static boolean isOverrideable(String protocol) { 1369 if (protocol.length() == 3) { 1370 if ((Character.toLowerCase(protocol.charAt(0)) == 'j') && 1371 (Character.toLowerCase(protocol.charAt(1)) == 'r') && 1372 (Character.toLowerCase(protocol.charAt(2)) == 't')) { 1373 return false; 1374 } 1375 } else if (protocol.length() == 4) { 1376 if ((Character.toLowerCase(protocol.charAt(0)) == 'f') && 1377 (Character.toLowerCase(protocol.charAt(1)) == 'i') && 1378 (Character.toLowerCase(protocol.charAt(2)) == 'l') && 1379 (Character.toLowerCase(protocol.charAt(3)) == 'e')) { 1380 return false; 1381 } 1382 } 1383 return true; 1384 } 1385 1386 /** 1387 * A table of protocol handlers. 1388 */ 1389 static Hashtable<String,URLStreamHandler> handlers = new Hashtable<>(); 1390 private static final Object streamHandlerLock = new Object(); 1391 1392 /** 1393 * Returns the Stream Handler. 1394 * @param protocol the protocol to use 1395 */ 1396 static URLStreamHandler getURLStreamHandler(String protocol) { 1397 1398 URLStreamHandler handler = handlers.get(protocol); 1399 1400 if (handler != null) { 1401 return handler; 1402 } 1403 1404 URLStreamHandlerFactory fac; 1405 boolean checkedWithFactory = false; 1406 1407 if (isOverrideable(protocol) && jdk.internal.misc.VM.isBooted()) { 1408 // Use the factory (if any). Volatile read makes 1409 // URLStreamHandlerFactory appear fully initialized to current thread. 1410 fac = factory; 1411 if (fac != null) { 1412 handler = fac.createURLStreamHandler(protocol); 1413 checkedWithFactory = true; 1414 } 1415 1416 if (handler == null && !protocol.equalsIgnoreCase("jar")) { 1417 handler = lookupViaProviders(protocol); 1418 } 1419 1420 if (handler == null) { 1421 handler = lookupViaProperty(protocol); 1422 } 1423 } 1424 1425 if (handler == null) { 1426 // Try the built-in protocol handler 1427 handler = defaultFactory.createURLStreamHandler(protocol); 1428 } 1429 1430 synchronized (streamHandlerLock) { 1431 URLStreamHandler handler2 = null; 1432 1433 // Check again with hashtable just in case another 1434 // thread created a handler since we last checked 1435 handler2 = handlers.get(protocol); 1436 1437 if (handler2 != null) { 1438 return handler2; 1439 } 1440 1441 // Check with factory if another thread set a 1442 // factory since our last check 1443 if (!checkedWithFactory && (fac = factory) != null) { 1444 handler2 = fac.createURLStreamHandler(protocol); 1445 } 1446 1447 if (handler2 != null) { 1448 // The handler from the factory must be given more 1449 // importance. Discard the default handler that 1450 // this thread created. 1451 handler = handler2; 1452 } 1453 1454 // Insert this handler into the hashtable 1455 if (handler != null) { 1456 handlers.put(protocol, handler); 1457 } 1458 } 1459 return handler; 1460 } 1461 1462 /** 1463 * @serialField protocol String 1464 * 1465 * @serialField host String 1466 * 1467 * @serialField port int 1468 * 1469 * @serialField authority String 1470 * 1471 * @serialField file String 1472 * 1473 * @serialField ref String 1474 * 1475 * @serialField hashCode int 1476 * 1477 */ 1478 private static final ObjectStreamField[] serialPersistentFields = { 1479 new ObjectStreamField("protocol", String.class), 1480 new ObjectStreamField("host", String.class), 1481 new ObjectStreamField("port", int.class), 1482 new ObjectStreamField("authority", String.class), 1483 new ObjectStreamField("file", String.class), 1484 new ObjectStreamField("ref", String.class), 1485 new ObjectStreamField("hashCode", int.class), }; 1486 1487 /** 1488 * WriteObject is called to save the state of the URL to an 1489 * ObjectOutputStream. The handler is not saved since it is 1490 * specific to this system. 1491 * 1492 * @serialData the default write object value. When read back in, 1493 * the reader must ensure that calling getURLStreamHandler with 1494 * the protocol variable returns a valid URLStreamHandler and 1495 * throw an IOException if it does not. 1496 */ 1497 private synchronized void writeObject(java.io.ObjectOutputStream s) 1498 throws IOException 1499 { 1500 s.defaultWriteObject(); // write the fields 1501 } 1502 1503 /** 1504 * readObject is called to restore the state of the URL from the 1505 * stream. It reads the components of the URL and finds the local 1506 * stream handler. 1507 */ 1508 private synchronized void readObject(java.io.ObjectInputStream s) 1509 throws IOException, ClassNotFoundException { 1510 GetField gf = s.readFields(); 1511 String protocol = (String)gf.get("protocol", null); 1512 if (getURLStreamHandler(protocol) == null) { 1513 throw new IOException("unknown protocol: " + protocol); 1514 } 1515 String host = (String)gf.get("host", null); 1516 int port = gf.get("port", -1); 1517 String authority = (String)gf.get("authority", null); 1518 String file = (String)gf.get("file", null); 1519 String ref = (String)gf.get("ref", null); 1520 int hashCode = gf.get("hashCode", -1); 1521 if (authority == null 1522 && ((host != null && !host.isEmpty()) || port != -1)) { 1523 if (host == null) 1524 host = ""; 1525 authority = (port == -1) ? host : host + ":" + port; 1526 } 1527 tempState = new UrlDeserializedState(protocol, host, port, authority, 1528 file, ref, hashCode); 1529 } 1530 1531 /** 1532 * Replaces the de-serialized object with an URL object. 1533 * 1534 * @return a newly created object from deserialized data 1535 * 1536 * @throws ObjectStreamException if a new object replacing this 1537 * object could not be created 1538 */ 1539 1540 private Object readResolve() throws ObjectStreamException { 1541 1542 URLStreamHandler handler = null; 1543 // already been checked in readObject 1544 handler = getURLStreamHandler(tempState.getProtocol()); 1545 1546 URL replacementURL = null; 1547 if (isBuiltinStreamHandler(handler.getClass().getName())) { 1548 replacementURL = fabricateNewURL(); 1549 } else { 1550 replacementURL = setDeserializedFields(handler); 1551 } 1552 return replacementURL; 1553 } 1554 1555 private URL setDeserializedFields(URLStreamHandler handler) { 1556 URL replacementURL; 1557 String userInfo = null; 1558 String protocol = tempState.getProtocol(); 1559 String host = tempState.getHost(); 1560 int port = tempState.getPort(); 1561 String authority = tempState.getAuthority(); 1562 String file = tempState.getFile(); 1563 String ref = tempState.getRef(); 1564 int hashCode = tempState.getHashCode(); 1565 1566 1567 // Construct authority part 1568 if (authority == null 1569 && ((host != null && !host.isEmpty()) || port != -1)) { 1570 if (host == null) 1571 host = ""; 1572 authority = (port == -1) ? host : host + ":" + port; 1573 1574 // Handle hosts with userInfo in them 1575 int at = host.lastIndexOf('@'); 1576 if (at != -1) { 1577 userInfo = host.substring(0, at); 1578 host = host.substring(at+1); 1579 } 1580 } else if (authority != null) { 1581 // Construct user info part 1582 int ind = authority.indexOf('@'); 1583 if (ind != -1) 1584 userInfo = authority.substring(0, ind); 1585 } 1586 1587 // Construct path and query part 1588 String path = null; 1589 String query = null; 1590 if (file != null) { 1591 // Fix: only do this if hierarchical? 1592 int q = file.lastIndexOf('?'); 1593 if (q != -1) { 1594 query = file.substring(q+1); 1595 path = file.substring(0, q); 1596 } else 1597 path = file; 1598 } 1599 1600 // Set the object fields. 1601 this.protocol = protocol; 1602 this.host = host; 1603 this.port = port; 1604 this.file = file; 1605 this.authority = authority; 1606 this.ref = ref; 1607 this.hashCode = hashCode; 1608 this.handler = handler; 1609 this.query = query; 1610 this.path = path; 1611 this.userInfo = userInfo; 1612 replacementURL = this; 1613 return replacementURL; 1614 } 1615 1616 private URL fabricateNewURL() 1617 throws InvalidObjectException { 1618 // create URL string from deserialized object 1619 URL replacementURL = null; 1620 String urlString = tempState.reconstituteUrlString(); 1621 1622 try { 1623 replacementURL = new URL(urlString); 1624 } catch (MalformedURLException mEx) { 1625 resetState(); 1626 InvalidObjectException invoEx = new InvalidObjectException( 1627 "Malformed URL: " + urlString); 1628 invoEx.initCause(mEx); 1629 throw invoEx; 1630 } 1631 replacementURL.setSerializedHashCode(tempState.getHashCode()); 1632 resetState(); 1633 return replacementURL; 1634 } 1635 1636 private boolean isBuiltinStreamHandler(String handlerClassName) { 1637 return (handlerClassName.startsWith(BUILTIN_HANDLERS_PREFIX)); 1638 } 1639 1640 private void resetState() { 1641 this.protocol = null; 1642 this.host = null; 1643 this.port = -1; 1644 this.file = null; 1645 this.authority = null; 1646 this.ref = null; 1647 this.hashCode = -1; 1648 this.handler = null; 1649 this.query = null; 1650 this.path = null; 1651 this.userInfo = null; 1652 this.tempState = null; 1653 } 1654 1655 private void setSerializedHashCode(int hc) { 1656 this.hashCode = hc; 1657 } 1658 1659 static { 1660 SharedSecrets.setJavaNetURLAccess( 1661 new JavaNetURLAccess() { 1662 @Override 1663 public URLStreamHandler getHandler(URL u) { 1664 return u.handler; 1665 } 1666 } 1667 ); 1668 } 1669 } 1670 1671 final class UrlDeserializedState { 1672 private final String protocol; 1673 private final String host; 1674 private final int port; 1675 private final String authority; 1676 private final String file; 1677 private final String ref; 1678 private final int hashCode; 1679 1680 public UrlDeserializedState(String protocol, 1681 String host, int port, 1682 String authority, String file, 1683 String ref, int hashCode) { 1684 this.protocol = protocol; 1685 this.host = host; 1686 this.port = port; 1687 this.authority = authority; 1688 this.file = file; 1689 this.ref = ref; 1690 this.hashCode = hashCode; 1691 } 1692 1693 String getProtocol() { 1694 return protocol; 1695 } 1696 1697 String getHost() { 1698 return host; 1699 } 1700 1701 String getAuthority () { 1702 return authority; 1703 } 1704 1705 int getPort() { 1706 return port; 1707 } 1708 1709 String getFile () { 1710 return file; 1711 } 1712 1713 String getRef () { 1714 return ref; 1715 } 1716 1717 int getHashCode () { 1718 return hashCode; 1719 } 1720 1721 String reconstituteUrlString() { 1722 1723 // pre-compute length of StringBuffer 1724 int len = protocol.length() + 1; 1725 if (authority != null && !authority.isEmpty()) 1726 len += 2 + authority.length(); 1727 if (file != null) { 1728 len += file.length(); 1729 } 1730 if (ref != null) 1731 len += 1 + ref.length(); 1732 StringBuilder result = new StringBuilder(len); 1733 result.append(protocol); 1734 result.append(":"); 1735 if (authority != null && !authority.isEmpty()) { 1736 result.append("//"); 1737 result.append(authority); 1738 } 1739 if (file != null) { 1740 result.append(file); 1741 } 1742 if (ref != null) { 1743 result.append("#"); 1744 result.append(ref); 1745 } 1746 return result.toString(); 1747 } 1748 }