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