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


1360         try {
1361             return AccessController.doPrivileged(
1362                 new PrivilegedAction<>() {
1363                     public URLStreamHandler run() {
1364                         Iterator<URLStreamHandlerProvider> itr = providers();
1365                         while (itr.hasNext()) {
1366                             URLStreamHandlerProvider f = itr.next();
1367                             URLStreamHandler h = f.createURLStreamHandler(protocol);
1368                             if (h != null)
1369                                 return h;
1370                         }
1371                         return null;
1372                     }
1373                 });
1374         } finally {
1375             gate().exit();
1376         }
1377     }
1378 
1379     /**
1380      * Returns the protocol in lower case. Special cases known protocols
1381      * to avoid loading locale classes during startup.
1382      */
1383     static String toLowerCase(String protocol) {
1384         if (protocol.equals("jrt") || protocol.equals("file") || protocol.equals("jar")) {
1385             return protocol;
1386         } else {
1387             return protocol.toLowerCase(Locale.ROOT);
1388         }
1389     }
1390 
1391     /**
1392      * Non-overrideable protocols: "jrt" and "file"
1393      *
1394      * Character-based comparison for performance reasons; also ensures
1395      * case-insensitive comparison in a locale-independent fashion.
1396      */
1397     static boolean isOverrideable(String protocol) {
1398         if (protocol.length() == 3) {
1399             if ((Character.toLowerCase(protocol.charAt(0)) == 'j') &&
1400                     (Character.toLowerCase(protocol.charAt(1)) == 'r') &&
1401                     (Character.toLowerCase(protocol.charAt(2)) == 't')) {
1402                 return false;
1403             }
1404         } else if (protocol.length() == 4) {
1405             if ((Character.toLowerCase(protocol.charAt(0)) == 'f') &&
1406                     (Character.toLowerCase(protocol.charAt(1)) == 'i') &&
1407                     (Character.toLowerCase(protocol.charAt(2)) == 'l') &&
1408                     (Character.toLowerCase(protocol.charAt(3)) == 'e')) {
1409                 return false;
1410             }
1411         }
1412         return true;
1413     }
1414 
1415     /**
1416      * A table of protocol handlers.
1417      */
1418     static Hashtable<String,URLStreamHandler> handlers = new Hashtable<>();
1419     private static final Object streamHandlerLock = new Object();
1420 
1421     /**
1422      * Returns the Stream Handler.
1423      * @param protocol the protocol to use
1424      */
1425     static URLStreamHandler getURLStreamHandler(String protocol) {
1426 
1427         URLStreamHandler handler = handlers.get(protocol);
1428 
1429         if (handler != null) {
1430             return handler;
1431         }
1432 
1433         URLStreamHandlerFactory fac;
1434         boolean checkedWithFactory = false;
1435         boolean overrideableProtocol = isOverrideable(protocol);
1436 
1437         if (overrideableProtocol && VM.isBooted()) {
1438             // Use the factory (if any). Volatile read makes
1439             // URLStreamHandlerFactory appear fully initialized to current thread.
1440             fac = factory;
1441             if (fac != null) {
1442                 handler = fac.createURLStreamHandler(protocol);
1443                 checkedWithFactory = true;
1444             }
1445 
1446             if (handler == null && !protocol.equalsIgnoreCase("jar")) {
1447                 handler = lookupViaProviders(protocol);
1448             }
1449 
1450             if (handler == null) {
1451                 handler = lookupViaProperty(protocol);
1452             }
1453         }
1454 
1455         if (handler == null) {
1456             // Try the built-in protocol handler
1457             handler = defaultFactory.createURLStreamHandler(protocol);
1458         }
1459 
1460         synchronized (streamHandlerLock) {
1461             URLStreamHandler handler2 = null;
1462 
1463             // Check again with hashtable just in case another
1464             // thread created a handler since we last checked
1465             handler2 = handlers.get(protocol);
1466 
1467             if (handler2 != null) {
1468                 return handler2;
1469             }
1470 
1471             // Check with factory if another thread set a
1472             // factory since our last check
1473             if (overrideableProtocol && !checkedWithFactory &&
1474                 (fac = factory) != null) {
1475                 handler2 = fac.createURLStreamHandler(protocol);
1476             }
1477 
1478             if (handler2 != null) {
1479                 // The handler from the factory must be given more
1480                 // importance. Discard the default handler that
1481                 // this thread created.
1482                 handler = handler2;
1483             }
1484 
1485             // Insert this handler into the hashtable
1486             if (handler != null) {
1487                 handlers.put(protocol, handler);
1488             }
1489         }
1490         return handler;
1491     }
1492 
1493     /**
1494      * @serialField    protocol String the protocol to use (ftp, http, nntp, ... etc.)
1495      *
1496      * @serialField    host String the host name to connect to
1497      *
1498      * @serialField    port int the protocol port to connect to
1499      *
1500      * @serialField    authority String the authority part of this URL
1501      *
1502      * @serialField    file String the specified file name on that host. {@code file} is
1503      *                 defined as {@code path[?query]}
1504      *
1505      * @serialField    ref String the fragment part of this URL
1506      *
1507      * @serialField    hashCode int the hashCode of this URL
1508      *
1509      */
1510     @java.io.Serial
1511     private static final ObjectStreamField[] serialPersistentFields = {
1512         new ObjectStreamField("protocol", String.class),
1513         new ObjectStreamField("host", String.class),
1514         new ObjectStreamField("port", int.class),
1515         new ObjectStreamField("authority", String.class),
1516         new ObjectStreamField("file", String.class),
1517         new ObjectStreamField("ref", String.class),
1518         new ObjectStreamField("hashCode", int.class), };
1519 
1520     /**
1521      * WriteObject is called to save the state of the URL to an
1522      * ObjectOutputStream. The handler is not saved since it is
1523      * specific to this system.
1524      *
1525      * @serialData the default write object value. When read back in,
1526      * the reader must ensure that calling getURLStreamHandler with
1527      * the protocol variable returns a valid URLStreamHandler and
1528      * throw an IOException if it does not.
1529      *
1530      * @param  s the {@code ObjectOutputStream} to which data is written
1531      * @throws IOException if an I/O error occurs
1532      */
1533     @java.io.Serial
1534     private synchronized void writeObject(java.io.ObjectOutputStream s)
1535         throws IOException
1536     {
1537         s.defaultWriteObject(); // write the fields
1538     }
1539 
1540     /**
1541      * readObject is called to restore the state of the URL from the
1542      * stream.  It reads the components of the URL and finds the local
1543      * stream handler.
1544      *
1545      * @param  s the {@code ObjectInputStream} from which data is read
1546      * @throws IOException if an I/O error occurs
1547      * @throws ClassNotFoundException if a serialized class cannot be loaded
1548      */
1549     @java.io.Serial
1550     private synchronized void readObject(java.io.ObjectInputStream s)
1551             throws IOException, ClassNotFoundException {
1552         GetField gf = s.readFields();
1553         String protocol = (String)gf.get("protocol", null);
1554         if (getURLStreamHandler(protocol) == null) {
1555             throw new IOException("unknown protocol: " + protocol);
1556         }
1557         String host = (String)gf.get("host", null);
1558         int port = gf.get("port", -1);
1559         String authority = (String)gf.get("authority", null);
1560         String file = (String)gf.get("file", null);
1561         String ref = (String)gf.get("ref", null);
1562         int hashCode = gf.get("hashCode", -1);
1563         if (authority == null
1564                 && ((host != null && !host.isEmpty()) || port != -1)) {
1565             if (host == null)
1566                 host = "";
1567             authority = (port == -1) ? host : host + ":" + port;
1568         }
1569         tempState = new UrlDeserializedState(protocol, host, port, authority,
1570                file, ref, hashCode);
1571     }
1572 
1573     /**
1574      * Replaces the de-serialized object with an URL object.
1575      *
1576      * @return a newly created object from deserialized data
1577      *
1578      * @throws ObjectStreamException if a new object replacing this
1579      * object could not be created
1580      */
1581    @java.io.Serial
1582    private Object readResolve() throws ObjectStreamException {
1583 
1584         URLStreamHandler handler = null;
1585         // already been checked in readObject
1586         handler = getURLStreamHandler(tempState.getProtocol());
1587 
1588         URL replacementURL = null;
1589         if (isBuiltinStreamHandler(handler.getClass().getName())) {
1590             replacementURL = fabricateNewURL();
1591         } else {
1592             replacementURL = setDeserializedFields(handler);
1593         }
1594         return replacementURL;
1595     }
1596 
1597     private URL setDeserializedFields(URLStreamHandler handler) {
1598         URL replacementURL;
1599         String userInfo = null;
1600         String protocol = tempState.getProtocol();
1601         String host = tempState.getHost();
1602         int port = tempState.getPort();
1603         String authority = tempState.getAuthority();
1604         String file = tempState.getFile();
1605         String ref = tempState.getRef();
1606         int hashCode = tempState.getHashCode();
1607 
1608 
1609         // Construct authority part
1610         if (authority == null
1611             && ((host != null && !host.isEmpty()) || port != -1)) {
1612             if (host == null)
1613                 host = "";
1614             authority = (port == -1) ? host : host + ":" + port;
1615 
1616             // Handle hosts with userInfo in them
1617             int at = host.lastIndexOf('@');
1618             if (at != -1) {
1619                 userInfo = host.substring(0, at);
1620                 host = host.substring(at+1);
1621             }
1622         } else if (authority != null) {
1623             // Construct user info part
1624             int ind = authority.indexOf('@');
1625             if (ind != -1)
1626                 userInfo = authority.substring(0, ind);
1627         }
1628 
1629         // Construct path and query part
1630         String path = null;
1631         String query = null;
1632         if (file != null) {
1633             // Fix: only do this if hierarchical?
1634             int q = file.lastIndexOf('?');
1635             if (q != -1) {
1636                 query = file.substring(q+1);
1637                 path = file.substring(0, q);
1638             } else
1639                 path = file;
1640         }
1641 
1642         // Set the object fields.
1643         this.protocol = protocol;
1644         this.host = host;
1645         this.port = port;
1646         this.file = file;
1647         this.authority = authority;
1648         this.ref = ref;
1649         this.hashCode = hashCode;
1650         this.handler = handler;
1651         this.query = query;
1652         this.path = path;
1653         this.userInfo = userInfo;
1654         replacementURL = this;
1655         return replacementURL;
1656     }
1657 
1658     private URL fabricateNewURL()
1659                 throws InvalidObjectException {
1660         // create URL string from deserialized object
1661         URL replacementURL = null;
1662         String urlString = tempState.reconstituteUrlString();
1663 
1664         try {
1665             replacementURL = new URL(urlString);
1666         } catch (MalformedURLException mEx) {
1667             resetState();
1668             InvalidObjectException invoEx = new InvalidObjectException(
1669                     "Malformed URL:  " + urlString);
1670             invoEx.initCause(mEx);
1671             throw invoEx;
1672         }
1673         replacementURL.setSerializedHashCode(tempState.getHashCode());
1674         resetState();
1675         return replacementURL;
1676     }
1677 
1678     boolean isBuiltinStreamHandler(URLStreamHandler handler) {
1679        Class<?> handlerClass = handler.getClass();
1680        return isBuiltinStreamHandler(handlerClass.getName())
1681                  || VM.isSystemDomainLoader(handlerClass.getClassLoader());
1682     }
1683 
1684     private boolean isBuiltinStreamHandler(String handlerClassName) {
1685         return (handlerClassName.startsWith(BUILTIN_HANDLERS_PREFIX));
1686     }
1687 
1688     private void resetState() {
1689         this.protocol = null;
1690         this.host = null;
1691         this.port = -1;
1692         this.file = null;
1693         this.authority = null;
1694         this.ref = null;
1695         this.hashCode = -1;
1696         this.handler = null;
1697         this.query = null;
1698         this.path = null;
1699         this.userInfo = null;
1700         this.tempState = null;
1701     }
1702 
1703     private void setSerializedHashCode(int hc) {
1704         this.hashCode = hc;
1705     }
1706 
1707     static {
1708         SharedSecrets.setJavaNetURLAccess(
1709                 new JavaNetURLAccess() {
1710                     @Override
1711                     public URLStreamHandler getHandler(URL u) {
1712                         return u.handler;
1713                     }
1714                 }
1715         );
1716     }
1717 }
1718 
1719 final class UrlDeserializedState {
1720     private final String protocol;
1721     private final String host;
1722     private final int port;
1723     private final String authority;
1724     private final String file;
1725     private final String ref;
1726     private final int hashCode;
1727 
1728     public UrlDeserializedState(String protocol,
1729                                 String host, int port,
1730                                 String authority, String file,
1731                                 String ref, int hashCode) {
1732         this.protocol = protocol;
1733         this.host = host;
1734         this.port = port;
1735         this.authority = authority;
1736         this.file = file;
1737         this.ref = ref;
1738         this.hashCode = hashCode;
1739     }
1740 
1741     String getProtocol() {
1742         return protocol;
1743     }
1744 
1745     String getHost() {
1746         return host;
1747     }
1748 
1749     String getAuthority () {
1750         return authority;
1751     }
1752 
1753     int getPort() {
1754         return port;
1755     }
1756 
1757     String getFile () {
1758         return file;
1759     }
1760 
1761     String getRef () {
1762         return ref;
1763     }
1764 
1765     int getHashCode () {
1766         return hashCode;
1767     }
1768 
1769     String reconstituteUrlString() {
1770 
1771         // pre-compute length of StringBuilder
1772         int len = protocol.length() + 1;
1773         if (authority != null && !authority.isEmpty())
1774             len += 2 + authority.length();
1775         if (file != null) {
1776             len += file.length();
1777         }
1778         if (ref != null)
1779             len += 1 + ref.length();
1780         StringBuilder result = new StringBuilder(len);
1781         result.append(protocol);
1782         result.append(":");
1783         if (authority != null && !authority.isEmpty()) {
1784             result.append("//");
1785             result.append(authority);
1786         }
1787         if (file != null) {
1788             result.append(file);
1789         }
1790         if (ref != null) {
1791             result.append("#");
1792             result.append(ref);
1793         }
1794         return result.toString();
1795     }
1796 }
--- EOF ---