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