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