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