URLClassPath.java 51.0 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27
 */

package sun.misc;

28
import java.util.*;
D
duke 已提交
29 30 31 32 33 34 35 36 37 38 39
import java.util.jar.JarFile;
import sun.misc.JarIndex;
import sun.misc.InvalidJarIndexException;
import sun.net.www.ParseUtil;
import java.util.zip.ZipEntry;
import java.util.jar.JarEntry;
import java.util.jar.Manifest;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
40
import java.net.URI;
D
duke 已提交
41
import java.net.URL;
42
import java.net.URLClassLoader;
D
duke 已提交
43 44 45 46
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
47
import java.io.*;
R
robm 已提交
48
import java.security.AccessControlContext;
D
duke 已提交
49 50 51 52 53 54 55 56
import java.security.AccessController;
import java.security.AccessControlException;
import java.security.CodeSigner;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.cert.Certificate;
import sun.misc.FileURLMapper;
57
import sun.net.util.URLUtil;
58
import sun.security.action.GetPropertyAction;
D
duke 已提交
59 60 61 62 63 64 65 66 67 68 69

/**
 * This class is used to maintain a search path of URLs for loading classes
 * and resources from both JAR files and directories.
 *
 * @author  David Connelly
 */
public class URLClassPath {
    final static String USER_AGENT_JAVA_VERSION = "UA-Java-Version";
    final static String JAVA_VERSION;
    private static final boolean DEBUG;
70
    private static final boolean DEBUG_LOOKUP_CACHE;
71
    private static final boolean DISABLE_JAR_CHECKING;
R
robm 已提交
72
    private static final boolean DISABLE_ACC_CHECKING;
73 74
    private static final boolean DISABLE_CP_URL_CHECK;
    private static final boolean DEBUG_CP_URL_CHECK;
D
duke 已提交
75 76 77

    static {
        JAVA_VERSION = java.security.AccessController.doPrivileged(
78
            new GetPropertyAction("java.version"));
D
duke 已提交
79
        DEBUG        = (java.security.AccessController.doPrivileged(
80 81 82
            new GetPropertyAction("sun.misc.URLClassPath.debug")) != null);
        DEBUG_LOOKUP_CACHE = (java.security.AccessController.doPrivileged(
            new GetPropertyAction("sun.misc.URLClassPath.debugLookupCache")) != null);
83
        String p = java.security.AccessController.doPrivileged(
84
            new GetPropertyAction("sun.misc.URLClassPath.disableJarChecking"));
85
        DISABLE_JAR_CHECKING = p != null ? p.equals("true") || p.equals("") : false;
R
robm 已提交
86 87 88 89

        p = AccessController.doPrivileged(
            new GetPropertyAction("jdk.net.URLClassPath.disableRestrictedPermissions"));
        DISABLE_ACC_CHECKING = p != null ? p.equals("true") || p.equals("") : false;
90 91 92

        // This property will be removed in a later release
        p = AccessController.doPrivileged(
93
            new GetPropertyAction("jdk.net.URLClassPath.disableClassPathURLCheck", "true"));
94 95 96

        DISABLE_CP_URL_CHECK = p != null ? p.equals("true") || p.isEmpty() : false;
        DEBUG_CP_URL_CHECK = "debug".equals(p);
D
duke 已提交
97 98 99
    }

    /* The original search path of URLs. */
100
    private ArrayList<URL> path = new ArrayList<URL>();
D
duke 已提交
101 102

    /* The stack of unopened URLs */
103
    Stack<URL> urls = new Stack<URL>();
D
duke 已提交
104 105

    /* The resulting search path of Loaders */
106
    ArrayList<Loader> loaders = new ArrayList<Loader>();
D
duke 已提交
107 108

    /* Map of each URL opened to its corresponding Loader */
109
    HashMap<String, Loader> lmap = new HashMap<String, Loader>();
D
duke 已提交
110 111 112 113

    /* The jar protocol handler to use when creating new URLs */
    private URLStreamHandler jarHandler;

114 115 116
    /* Whether this URLClassLoader has been closed yet */
    private boolean closed = false;

R
robm 已提交
117 118 119 120 121
    /* The context to be used when loading classes and resources.  If non-null
     * this is the context that was captured during the creation of the
     * URLClassLoader. null implies no additional security restrictions. */
    private final AccessControlContext acc;

D
duke 已提交
122 123 124 125 126 127 128 129 130
    /**
     * Creates a new URLClassPath for the given URLs. The URLs will be
     * searched in the order specified for classes and resources. A URL
     * ending with a '/' is assumed to refer to a directory. Otherwise,
     * the URL is assumed to refer to a JAR file.
     *
     * @param urls the directory and JAR file URLs to search for classes
     *        and resources
     * @param factory the URLStreamHandlerFactory to use when creating new URLs
R
robm 已提交
131 132
     * @param acc the context to be used when loading classes and resources, may
     *            be null
D
duke 已提交
133
     */
R
robm 已提交
134 135 136
    public URLClassPath(URL[] urls,
                        URLStreamHandlerFactory factory,
                        AccessControlContext acc) {
D
duke 已提交
137 138 139 140 141 142 143
        for (int i = 0; i < urls.length; i++) {
            path.add(urls[i]);
        }
        push(urls);
        if (factory != null) {
            jarHandler = factory.createURLStreamHandler("jar");
        }
R
robm 已提交
144 145 146 147
        if (DISABLE_ACC_CHECKING)
            this.acc = null;
        else
            this.acc = acc;
D
duke 已提交
148 149
    }

R
robm 已提交
150 151 152 153
    /**
     * Constructs a URLClassPath with no additional security restrictions.
     * Used by code that implements the class path.
     */
D
duke 已提交
154
    public URLClassPath(URL[] urls) {
R
robm 已提交
155 156 157 158 159
        this(urls, null, null);
    }

    public URLClassPath(URL[] urls, AccessControlContext acc) {
        this(urls, null, acc);
D
duke 已提交
160 161
    }

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    public synchronized List<IOException> closeLoaders() {
        if (closed) {
            return Collections.emptyList();
        }
        List<IOException> result = new LinkedList<IOException>();
        for (Loader loader : loaders) {
            try {
                loader.close();
            } catch (IOException e) {
                result.add (e);
            }
        }
        closed = true;
        return result;
    }

D
duke 已提交
178 179 180 181 182 183 184
    /**
     * Appends the specified URL to the search path of directory and JAR
     * file URLs from which to load classes and resources.
     * <p>
     * If the URL specified is null or is already in the list of
     * URLs, then invoking this method has no effect.
     */
185 186 187
    public synchronized void addURL(URL url) {
        if (closed)
            return;
D
duke 已提交
188 189 190 191 192 193
        synchronized (urls) {
            if (url == null || path.contains(url))
                return;

            urls.add(0, url);
            path.add(url);
194 195 196 197 198 199

            if (lookupCacheURLs != null) {
                // The lookup cache is no longer valid, since getLookupCache()
                // does not consider the newly added url.
                disableAllLookupCaches();
            }
D
duke 已提交
200 201 202 203 204 205 206 207
        }
    }

    /**
     * Returns the original search path of URLs.
     */
    public URL[] getURLs() {
        synchronized (urls) {
208
            return path.toArray(new URL[path.size()]);
D
duke 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222
        }
    }

    /**
     * Finds the resource with the specified name on the URL search path
     * or null if not found or security check fails.
     *
     * @param name      the name of the resource
     * @param check     whether to perform a security check
     * @return a <code>URL</code> for the resource, or <code>null</code>
     * if the resource could not be found.
     */
    public URL findResource(String name, boolean check) {
        Loader loader;
223 224
        int[] cache = getLookupCache(name);
        for (int i = 0; (loader = getNextLoader(cache, i)) != null; i++) {
D
duke 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            URL url = loader.findResource(name, check);
            if (url != null) {
                return url;
            }
        }
        return null;
    }

    /**
     * Finds the first Resource on the URL search path which has the specified
     * name. Returns null if no Resource could be found.
     *
     * @param name the name of the Resource
     * @param check     whether to perform a security check
     * @return the Resource, or null if not found
     */
    public Resource getResource(String name, boolean check) {
        if (DEBUG) {
            System.err.println("URLClassPath.getResource(\"" + name + "\")");
        }

        Loader loader;
247 248
        int[] cache = getLookupCache(name);
        for (int i = 0; (loader = getNextLoader(cache, i)) != null; i++) {
D
duke 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            Resource res = loader.getResource(name, check);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    /**
     * Finds all resources on the URL search path with the given name.
     * Returns an enumeration of the URL objects.
     *
     * @param name the resource name
     * @return an Enumeration of all the urls having the specified name
     */
264
    public Enumeration<URL> findResources(final String name,
D
duke 已提交
265
                                     final boolean check) {
266
        return new Enumeration<URL>() {
D
duke 已提交
267
            private int index = 0;
268
            private int[] cache = getLookupCache(name);
D
duke 已提交
269 270 271 272 273 274 275
            private URL url = null;

            private boolean next() {
                if (url != null) {
                    return true;
                } else {
                    Loader loader;
276
                    while ((loader = getNextLoader(cache, index++)) != null) {
D
duke 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289
                        url = loader.findResource(name, check);
                        if (url != null) {
                            return true;
                        }
                    }
                    return false;
                }
            }

            public boolean hasMoreElements() {
                return next();
            }

290
            public URL nextElement() {
D
duke 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
                if (!next()) {
                    throw new NoSuchElementException();
                }
                URL u = url;
                url = null;
                return u;
            }
        };
    }

    public Resource getResource(String name) {
        return getResource(name, true);
    }

    /**
     * Finds all resources on the URL search path with the given name.
     * Returns an enumeration of the Resource objects.
     *
     * @param name the resource name
     * @return an Enumeration of all the resources having the specified name
     */
312
    public Enumeration<Resource> getResources(final String name,
D
duke 已提交
313
                                    final boolean check) {
314
        return new Enumeration<Resource>() {
D
duke 已提交
315
            private int index = 0;
316
            private int[] cache = getLookupCache(name);
D
duke 已提交
317 318 319 320 321 322 323
            private Resource res = null;

            private boolean next() {
                if (res != null) {
                    return true;
                } else {
                    Loader loader;
324
                    while ((loader = getNextLoader(cache, index++)) != null) {
D
duke 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337
                        res = loader.getResource(name, check);
                        if (res != null) {
                            return true;
                        }
                    }
                    return false;
                }
            }

            public boolean hasMoreElements() {
                return next();
            }

338
            public Resource nextElement() {
D
duke 已提交
339 340 341 342 343 344 345 346 347 348
                if (!next()) {
                    throw new NoSuchElementException();
                }
                Resource r = res;
                res = null;
                return r;
            }
        };
    }

349
    public Enumeration<Resource> getResources(final String name) {
D
duke 已提交
350 351 352
        return getResources(name, true);
    }

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    private static volatile boolean lookupCacheEnabled
        = "true".equals(VM.getSavedProperty("sun.cds.enableSharedLookupCache"));
    private URL[] lookupCacheURLs;
    private ClassLoader lookupCacheLoader;

    synchronized void initLookupCache(ClassLoader loader) {
        if ((lookupCacheURLs = getLookupCacheURLs(loader)) != null) {
            lookupCacheLoader = loader;
        } else {
            // This JVM instance does not support lookup cache.
            disableAllLookupCaches();
        }
    }

    static void disableAllLookupCaches() {
        lookupCacheEnabled = false;
    }

    private static native URL[] getLookupCacheURLs(ClassLoader loader);
    private static native int[] getLookupCacheForClassLoader(ClassLoader loader,
                                                             String name);
    private static native boolean knownToNotExist0(ClassLoader loader,
                                                   String className);

    synchronized boolean knownToNotExist(String className) {
        if (lookupCacheURLs != null && lookupCacheEnabled) {
            return knownToNotExist0(lookupCacheLoader, className);
        }

        // Don't know if this class exists or not -- need to do a full search.
        return false;
    }

    /**
     * Returns an array of the index to lookupCacheURLs that may
     * contain the specified resource. The values in the returned
     * array are in strictly ascending order and must be a valid index
     * to lookupCacheURLs array.
     *
     * This method returns an empty array if the specified resource
     * cannot be found in this URLClassPath. If there is no lookup
     * cache or it's disabled, this method returns null and the lookup
     * should search the entire classpath.
     *
     * Example: if lookupCacheURLs contains {a.jar, b.jar, c.jar, d.jar}
     * and package "foo" only exists in a.jar and c.jar,
     * getLookupCache("foo/Bar.class") will return {0, 2}
     *
     * @param name the resource name
     * @return an array of the index to lookupCacheURLs that may contain the
     *         specified resource; or null if no lookup cache is used.
     */
    private synchronized int[] getLookupCache(String name) {
        if (lookupCacheURLs == null || !lookupCacheEnabled) {
            return null;
        }

        int[] cache = getLookupCacheForClassLoader(lookupCacheLoader, name);
        if (cache != null && cache.length > 0) {
            int maxindex = cache[cache.length - 1]; // cache[] is strictly ascending.
            if (!ensureLoaderOpened(maxindex)) {
                if (DEBUG_LOOKUP_CACHE) {
                    System.out.println("Expanded loaders FAILED " +
                                       loaders.size() + " for maxindex=" + maxindex);
                }
                return null;
            }
        }

        return cache;
    }

    private boolean ensureLoaderOpened(int index) {
        if (loaders.size() <= index) {
            // Open all Loaders up to, and including, index
            if (getLoader(index) == null) {
                return false;
            }
            if (!lookupCacheEnabled) {
                // cache was invalidated as the result of the above call.
                return false;
            }
            if (DEBUG_LOOKUP_CACHE) {
                System.out.println("Expanded loaders " + loaders.size() +
                                   " to index=" + index);
            }
        }
        return true;
    }

    /*
     * The CLASS-PATH attribute was expanded by the VM when building
     * the resource lookup cache in the same order as the getLoader
     * method does. This method validates if the URL from the lookup
     * cache matches the URL of the Loader at the given index;
     * otherwise, this method disables the lookup cache.
     */
    private synchronized void validateLookupCache(int index,
                                                  String urlNoFragString) {
        if (lookupCacheURLs != null && lookupCacheEnabled) {
            if (index < lookupCacheURLs.length &&
                urlNoFragString.equals(
                    URLUtil.urlNoFragString(lookupCacheURLs[index]))) {
                return;
            }
            if (DEBUG || DEBUG_LOOKUP_CACHE) {
                System.out.println("WARNING: resource lookup cache invalidated "
                                   + "for lookupCacheLoader at " + index);
            }
            disableAllLookupCaches();
        }
    }

    /**
     * Returns the next Loader that may contain the resource to
     * lookup. If the given cache is null, return loaders.get(index)
     * that may be lazily created; otherwise, cache[index] is the next
     * Loader that may contain the resource to lookup and so returns
     * loaders.get(cache[index]).
     *
     * If cache is non-null, loaders.get(cache[index]) must be present.
     *
     * @param cache lookup cache. If null, search the entire class path
     * @param index index to the given cache array; or to the loaders list.
     */
    private synchronized Loader getNextLoader(int[] cache, int index) {
        if (closed) {
            return null;
        }
        if (cache != null) {
            if (index < cache.length) {
                Loader loader = loaders.get(cache[index]);
                if (DEBUG_LOOKUP_CACHE) {
                    System.out.println("HASCACHE: Loading from : " + cache[index]
                                       + " = " + loader.getBaseURL());
                }
                return loader;
            } else {
                return null; // finished iterating over cache[]
            }
        } else {
            return getLoader(index);
        }
    }

D
duke 已提交
498 499 500 501 502 503
    /*
     * Returns the Loader at the specified position in the URL search
     * path. The URLs are opened and expanded as needed. Returns null
     * if the specified index is out of range.
     */
     private synchronized Loader getLoader(int index) {
504 505 506
        if (closed) {
            return null;
        }
D
duke 已提交
507 508 509 510 511 512 513 514 515
         // Expand URL search path until the request can be satisfied
         // or the URL stack is empty.
        while (loaders.size() < index + 1) {
            // Pop the next URL from the URL stack
            URL url;
            synchronized (urls) {
                if (urls.empty()) {
                    return null;
                } else {
516
                    url = urls.pop();
D
duke 已提交
517 518 519 520 521
                }
            }
            // Skip this URL if it already has a Loader. (Loader
            // may be null in the case where URL has not been opened
            // but is referenced by a JAR index.)
522 523
            String urlNoFragString = URLUtil.urlNoFragString(url);
            if (lmap.containsKey(urlNoFragString)) {
D
duke 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
                continue;
            }
            // Otherwise, create a new Loader for the URL.
            Loader loader;
            try {
                loader = getLoader(url);
                // If the loader defines a local class path then add the
                // URLs to the list of URLs to be opened.
                URL[] urls = loader.getClassPath();
                if (urls != null) {
                    push(urls);
                }
            } catch (IOException e) {
                // Silently ignore for now...
                continue;
R
robm 已提交
539 540 541 542 543 544 545 546
            } catch (SecurityException se) {
                // Always silently ignore. The context, if there is one, that
                // this URLClassPath was given during construction will never
                // have permission to access the URL.
                if (DEBUG) {
                    System.err.println("Failed to access " + url + ", " + se );
                }
                continue;
D
duke 已提交
547 548
            }
            // Finally, add the Loader to the search path.
549
            validateLookupCache(loaders.size(), urlNoFragString);
D
duke 已提交
550
            loaders.add(loader);
551
            lmap.put(urlNoFragString, loader);
D
duke 已提交
552
        }
553 554 555
        if (DEBUG_LOOKUP_CACHE) {
            System.out.println("NOCACHE: Loading from : " + index );
        }
556
        return loaders.get(index);
D
duke 已提交
557 558 559 560 561 562 563
    }

    /*
     * Returns the Loader for the specified base URL.
     */
    private Loader getLoader(final URL url) throws IOException {
        try {
564 565 566
            return java.security.AccessController.doPrivileged(
                new java.security.PrivilegedExceptionAction<Loader>() {
                public Loader run() throws IOException {
D
duke 已提交
567 568 569 570 571 572 573 574
                    String file = url.getFile();
                    if (file != null && file.endsWith("/")) {
                        if ("file".equals(url.getProtocol())) {
                            return new FileLoader(url);
                        } else {
                            return new Loader(url);
                        }
                    } else {
R
robm 已提交
575
                        return new JarLoader(url, jarHandler, lmap, acc);
D
duke 已提交
576 577
                    }
                }
R
robm 已提交
578
            }, acc);
D
duke 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
        } catch (java.security.PrivilegedActionException pae) {
            throw (IOException)pae.getException();
        }
    }

    /*
     * Pushes the specified URLs onto the list of unopened URLs.
     */
    private void push(URL[] us) {
        synchronized (urls) {
            for (int i = us.length - 1; i >= 0; --i) {
                urls.push(us[i]);
            }
        }
    }

    /**
     * Convert class path specification into an array of file URLs.
     *
     * The path of the file is encoded before conversion into URL
     * form so that reserved characters can safely appear in the path.
     */
    public static URL[] pathToURLs(String path) {
        StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
        URL[] urls = new URL[st.countTokens()];
        int count = 0;
        while (st.hasMoreTokens()) {
            File f = new File(st.nextToken());
            try {
                f = new File(f.getCanonicalPath());
            } catch (IOException x) {
                // use the non-canonicalized filename
            }
            try {
                urls[count++] = ParseUtil.fileToEncodedURL(f);
            } catch (IOException x) { }
        }

        if (urls.length != count) {
            URL[] tmp = new URL[count];
            System.arraycopy(urls, 0, tmp, 0, count);
            urls = tmp;
        }
        return urls;
    }

    /*
     * Check whether the resource URL should be returned.
     * Return null on security check failure.
     * Called by java.net.URLClassLoader.
     */
    public URL checkURL(URL url) {
        try {
            check(url);
        } catch (Exception e) {
            return null;
        }

        return url;
    }

    /*
     * Check whether the resource URL should be returned.
     * Throw exception on failure.
     * Called internally within this file.
     */
    static void check(URL url) throws IOException {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            URLConnection urlConnection = url.openConnection();
            Permission perm = urlConnection.getPermission();
            if (perm != null) {
                try {
                    security.checkPermission(perm);
                } catch (SecurityException se) {
                    // fallback to checkRead/checkConnect for pre 1.2
                    // security managers
                    if ((perm instanceof java.io.FilePermission) &&
                        perm.getActions().indexOf("read") != -1) {
                        security.checkRead(perm.getName());
                    } else if ((perm instanceof
                        java.net.SocketPermission) &&
                        perm.getActions().indexOf("connect") != -1) {
                        URL locUrl = url;
                        if (urlConnection instanceof JarURLConnection) {
                            locUrl = ((JarURLConnection)urlConnection).getJarFileURL();
                        }
                        security.checkConnect(locUrl.getHost(),
                                              locUrl.getPort());
                    } else {
                        throw se;
                    }
                }
            }
        }
    }

    /**
     * Inner class used to represent a loader of resources and classes
     * from a base URL.
     */
680
    private static class Loader implements Closeable {
D
duke 已提交
681
        private final URL base;
682
        private JarFile jarfile; // if this points to a jar file
D
duke 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723

        /*
         * Creates a new Loader for the specified URL.
         */
        Loader(URL url) {
            base = url;
        }

        /*
         * Returns the base URL for this Loader.
         */
        URL getBaseURL() {
            return base;
        }

        URL findResource(final String name, boolean check) {
            URL url;
            try {
                url = new URL(base, ParseUtil.encodePath(name, false));
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("name");
            }

            try {
                if (check) {
                    URLClassPath.check(url);
                }

                /*
                 * For a HTTP connection we use the HEAD method to
                 * check if the resource exists.
                 */
                URLConnection uc = url.openConnection();
                if (uc instanceof HttpURLConnection) {
                    HttpURLConnection hconn = (HttpURLConnection)uc;
                    hconn.setRequestMethod("HEAD");
                    if (hconn.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
                        return null;
                    }
                } else {
                    // our best guess for the other cases
724 725
                    uc.setUseCaches(false);
                    InputStream is = uc.getInputStream();
D
duke 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
                    is.close();
                }
                return url;
            } catch (Exception e) {
                return null;
            }
        }

        Resource getResource(final String name, boolean check) {
            final URL url;
            try {
                url = new URL(base, ParseUtil.encodePath(name, false));
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("name");
            }
            final URLConnection uc;
            try {
                if (check) {
                    URLClassPath.check(url);
                }
                uc = url.openConnection();
                InputStream in = uc.getInputStream();
748
                if (uc instanceof JarURLConnection) {
749
                    /* Need to remember the jar file so it can be closed
750 751 752
                     * in a hurry.
                     */
                    JarURLConnection juc = (JarURLConnection)uc;
753
                    jarfile = JarLoader.checkJar(juc.getJarFile());
754
                }
D
duke 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
            } catch (Exception e) {
                return null;
            }
            return new Resource() {
                public String getName() { return name; }
                public URL getURL() { return url; }
                public URL getCodeSourceURL() { return base; }
                public InputStream getInputStream() throws IOException {
                    return uc.getInputStream();
                }
                public int getContentLength() throws IOException {
                    return uc.getContentLength();
                }
            };
        }

        /*
         * Returns the Resource for the specified name, or null if not
         * found or the caller does not have the permission to get the
         * resource.
         */
        Resource getResource(final String name) {
            return getResource(name, true);
        }

780 781 782 783
        /*
         * close this loader and release all resources
         * method overridden in sub-classes
         */
784 785 786 787 788
        public void close () throws IOException {
            if (jarfile != null) {
                jarfile.close();
            }
        }
789

D
duke 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802
        /*
         * Returns the local class path for this loader, or null if none.
         */
        URL[] getClassPath() throws IOException {
            return null;
        }
    }

    /*
     * Inner class used to represent a Loader of resources from a JAR URL.
     */
    static class JarLoader extends Loader {
        private JarFile jar;
R
robm 已提交
803
        private final URL csu;
D
duke 已提交
804 805 806
        private JarIndex index;
        private MetaIndex metaIndex;
        private URLStreamHandler handler;
R
robm 已提交
807 808
        private final HashMap<String, Loader> lmap;
        private final AccessControlContext acc;
809
        private boolean closed = false;
810 811
        private static final sun.misc.JavaUtilZipFileAccess zipAccess =
                sun.misc.SharedSecrets.getJavaUtilZipFileAccess();
D
duke 已提交
812 813 814 815 816

        /*
         * Creates a new JarLoader for the specified URL referring to
         * a JAR file.
         */
817
        JarLoader(URL url, URLStreamHandler jarHandler,
R
robm 已提交
818 819
                  HashMap<String, Loader> loaderMap,
                  AccessControlContext acc)
D
duke 已提交
820 821 822 823 824 825
            throws IOException
        {
            super(new URL("jar", "", -1, url + "!/", jarHandler));
            csu = url;
            handler = jarHandler;
            lmap = loaderMap;
R
robm 已提交
826
            this.acc = acc;
D
duke 已提交
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

            if (!isOptimizable(url)) {
                ensureOpen();
            } else {
                 String fileName = url.getFile();
                if (fileName != null) {
                    fileName = ParseUtil.decode(fileName);
                    File f = new File(fileName);
                    metaIndex = MetaIndex.forJar(f);
                    // If the meta index is found but the file is not
                    // installed, set metaIndex to null. A typical
                    // senario is charsets.jar which won't be installed
                    // when the user is running in certain locale environment.
                    // The side effect of null metaIndex will cause
                    // ensureOpen get called so that IOException is thrown.
                    if (metaIndex != null && !f.exists()) {
                        metaIndex = null;
                    }
                }

                // metaIndex is null when either there is no such jar file
                // entry recorded in meta-index file or such jar file is
                // missing in JRE. See bug 6340399.
                if (metaIndex == null) {
                    ensureOpen();
                }
            }
        }

856 857 858 859 860 861 862 863 864 865 866
        @Override
        public void close () throws IOException {
            // closing is synchronized at higher level
            if (!closed) {
                closed = true;
                // in case not already open.
                ensureOpen();
                jar.close();
            }
        }

D
duke 已提交
867 868 869 870 871 872 873 874 875 876 877 878
        JarFile getJarFile () {
            return jar;
        }

        private boolean isOptimizable(URL url) {
            return "file".equals(url.getProtocol());
        }

        private void ensureOpen() throws IOException {
            if (jar == null) {
                try {
                    java.security.AccessController.doPrivileged(
879 880
                        new java.security.PrivilegedExceptionAction<Void>() {
                            public Void run() throws IOException {
D
duke 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
                                if (DEBUG) {
                                    System.err.println("Opening " + csu);
                                    Thread.dumpStack();
                                }

                                jar = getJarFile(csu);
                                index = JarIndex.getJarIndex(jar, metaIndex);
                                if (index != null) {
                                    String[] jarfiles = index.getJarFiles();
                                // Add all the dependent URLs to the lmap so that loaders
                                // will not be created for them by URLClassPath.getLoader(int)
                                // if the same URL occurs later on the main class path.  We set
                                // Loader to null here to avoid creating a Loader for each
                                // URL until we actually need to try to load something from them.
                                    for(int i = 0; i < jarfiles.length; i++) {
                                        try {
                                            URL jarURL = new URL(csu, jarfiles[i]);
                                            // If a non-null loader already exists, leave it alone.
899 900 901
                                            String urlNoFragString = URLUtil.urlNoFragString(jarURL);
                                            if (!lmap.containsKey(urlNoFragString)) {
                                                lmap.put(urlNoFragString, null);
D
duke 已提交
902 903 904 905 906 907 908 909
                                            }
                                        } catch (MalformedURLException e) {
                                            continue;
                                        }
                                    }
                                }
                                return null;
                            }
R
robm 已提交
910
                        }, acc);
D
duke 已提交
911 912 913 914 915 916
                } catch (java.security.PrivilegedActionException pae) {
                    throw (IOException)pae.getException();
                }
            }
        }

917 918 919
        /* Throws if the given jar file is does not start with the correct LOC */
        static JarFile checkJar(JarFile jar) throws IOException {
            if (System.getSecurityManager() != null && !DISABLE_JAR_CHECKING
920 921 922 923 924 925 926 927 928 929
                && !zipAccess.startsWithLocHeader(jar)) {
                IOException x = new IOException("Invalid Jar file");
                try {
                    jar.close();
                } catch (IOException ex) {
                    x.addSuppressed(ex);
                }
                throw x;
            }

930 931 932
            return jar;
        }

D
duke 已提交
933 934 935 936 937 938 939
        private JarFile getJarFile(URL url) throws IOException {
            // Optimize case where url refers to a local jar file
            if (isOptimizable(url)) {
                FileURLMapper p = new FileURLMapper (url);
                if (!p.exists()) {
                    throw new FileNotFoundException(p.getPath());
                }
940
                return checkJar(new JarFile(p.getPath()));
D
duke 已提交
941 942 943
            }
            URLConnection uc = getBaseURL().openConnection();
            uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
944 945
            JarFile jarFile = ((JarURLConnection)uc).getJarFile();
            return checkJar(jarFile);
D
duke 已提交
946 947 948 949 950 951 952 953 954
        }

        /*
         * Returns the index of this JarLoader if it exists.
         */
        JarIndex getIndex() {
            try {
                ensureOpen();
            } catch (IOException e) {
955
                throw new InternalError(e);
D
duke 已提交
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
            }
            return index;
        }

        /*
         * Creates the resource and if the check flag is set to true, checks if
         * is its okay to return the resource.
         */
        Resource checkResource(final String name, boolean check,
            final JarEntry entry) {

            final URL url;
            try {
                url = new URL(getBaseURL(), ParseUtil.encodePath(name, false));
                if (check) {
                    URLClassPath.check(url);
                }
            } catch (MalformedURLException e) {
                return null;
                // throw new IllegalArgumentException("name");
            } catch (IOException e) {
                return null;
            } catch (AccessControlException e) {
                return null;
            }

            return new Resource() {
                public String getName() { return name; }
                public URL getURL() { return url; }
                public URL getCodeSourceURL() { return csu; }
                public InputStream getInputStream() throws IOException
                    { return jar.getInputStream(entry); }
                public int getContentLength()
                    { return (int)entry.getSize(); }
990 991 992 993
                public Manifest getManifest() throws IOException {
                    SharedSecrets.javaUtilJarAccess().ensureInitialization(jar);
                    return jar.getManifest();
                }
D
duke 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
                public Certificate[] getCertificates()
                    { return entry.getCertificates(); };
                public CodeSigner[] getCodeSigners()
                    { return entry.getCodeSigners(); };
            };
        }


        /*
         * Returns true iff atleast one resource in the jar file has the same
         * package name as that of the specified resource name.
         */
        boolean validIndex(final String name) {
            String packageName = name;
            int pos;
            if((pos = name.lastIndexOf("/")) != -1) {
                packageName = name.substring(0, pos);
            }

            String entryName;
            ZipEntry entry;
1015
            Enumeration<JarEntry> enum_ = jar.entries();
D
duke 已提交
1016
            while (enum_.hasMoreElements()) {
1017
                entry = enum_.nextElement();
D
duke 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
                entryName = entry.getName();
                if((pos = entryName.lastIndexOf("/")) != -1)
                    entryName = entryName.substring(0, pos);
                if (entryName.equals(packageName)) {
                    return true;
                }
            }
            return false;
        }

        /*
         * Returns the URL for a resource with the specified name
         */
        URL findResource(final String name, boolean check) {
            Resource rsc = getResource(name, check);
            if (rsc != null) {
                return rsc.getURL();
            }
            return null;
        }

        /*
         * Returns the JAR Resource for the specified name.
         */
        Resource getResource(final String name, boolean check) {
            if (metaIndex != null) {
                if (!metaIndex.mayContain(name)) {
                    return null;
                }
            }

            try {
                ensureOpen();
            } catch (IOException e) {
1052
                throw new InternalError(e);
D
duke 已提交
1053 1054 1055 1056 1057 1058 1059 1060
            }
            final JarEntry entry = jar.getJarEntry(name);
            if (entry != null)
                return checkResource(name, check, entry);

            if (index == null)
                return null;

1061
            HashSet<String> visited = new HashSet<String>();
D
duke 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
            return getResource(name, check, visited);
        }

        /*
         * Version of getResource() that tracks the jar files that have been
         * visited by linking through the index files. This helper method uses
         * a HashSet to store the URLs of jar files that have been searched and
         * uses it to avoid going into an infinite loop, looking for a
         * non-existent resource
         */
        Resource getResource(final String name, boolean check,
1073
                             Set<String> visited) {
D
duke 已提交
1074 1075

            Resource res;
1076
            String[] jarFiles;
D
duke 已提交
1077
            int count = 0;
1078
            LinkedList<String> jarFilesList = null;
D
duke 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087

            /* If there no jar files in the index that can potential contain
             * this resource then return immediately.
             */
            if((jarFilesList = index.get(name)) == null)
                return null;

            do {
                int size = jarFilesList.size();
1088
                jarFiles = jarFilesList.toArray(new String[size]);
D
duke 已提交
1089 1090
                /* loop through the mapped jar file list */
                while(count < size) {
1091
                    String jarName = jarFiles[count++];
D
duke 已提交
1092 1093 1094 1095 1096
                    JarLoader newLoader;
                    final URL url;

                    try{
                        url = new URL(csu, jarName);
1097 1098
                        String urlNoFragString = URLUtil.urlNoFragString(url);
                        if ((newLoader = (JarLoader)lmap.get(urlNoFragString)) == null) {
D
duke 已提交
1099 1100 1101
                            /* no loader has been set up for this jar file
                             * before
                             */
1102 1103 1104
                            newLoader = AccessController.doPrivileged(
                                new PrivilegedExceptionAction<JarLoader>() {
                                    public JarLoader run() throws IOException {
D
duke 已提交
1105
                                        return new JarLoader(url, handler,
R
robm 已提交
1106
                                            lmap, acc);
D
duke 已提交
1107
                                    }
R
robm 已提交
1108
                                }, acc);
D
duke 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

                            /* this newly opened jar file has its own index,
                             * merge it into the parent's index, taking into
                             * account the relative path.
                             */
                            JarIndex newIndex = newLoader.getIndex();
                            if(newIndex != null) {
                                int pos = jarName.lastIndexOf("/");
                                newIndex.merge(this.index, (pos == -1 ?
                                    null : jarName.substring(0, pos + 1)));
                            }

                            /* put it in the global hashtable */
1122
                            lmap.put(urlNoFragString, newLoader);
D
duke 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
                        }
                    } catch (java.security.PrivilegedActionException pae) {
                        continue;
                    } catch (MalformedURLException e) {
                        continue;
                    }


                    /* Note that the addition of the url to the list of visited
                     * jars incorporates a check for presence in the hashmap
                     */
1134
                    boolean visitedURL = !visited.add(URLUtil.urlNoFragString(url));
D
duke 已提交
1135 1136 1137 1138
                    if (!visitedURL) {
                        try {
                            newLoader.ensureOpen();
                        } catch (IOException e) {
1139
                            throw new InternalError(e);
D
duke 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
                        }
                        final JarEntry entry = newLoader.jar.getJarEntry(name);
                        if (entry != null) {
                            return newLoader.checkResource(name, check, entry);
                        }

                        /* Verify that at least one other resource with the
                         * same package name as the lookedup resource is
                         * present in the new jar
                         */
                        if (!newLoader.validIndex(name)) {
                            /* the mapping is wrong */
                            throw new InvalidJarIndexException("Invalid index");
                        }
                    }

                    /* If newLoader is the current loader or if it is a
                     * loader that has already been searched or if the new
                     * loader does not have an index then skip it
                     * and move on to the next loader.
                     */
                    if (visitedURL || newLoader == this ||
                            newLoader.getIndex() == null) {
                        continue;
                    }

                    /* Process the index of the new loader
                     */
                    if((res = newLoader.getResource(name, check, visited))
                            != null) {
                        return res;
                    }
                }
                // Get the list of jar files again as the list could have grown
                // due to merging of index files.
                jarFilesList = index.get(name);

            // If the count is unchanged, we are done.
            } while(count < jarFilesList.size());
            return null;
        }


        /*
         * Returns the JAR file local class path, or null if none.
         */
        URL[] getClassPath() throws IOException {
            if (index != null) {
                return null;
            }

            if (metaIndex != null) {
                return null;
            }

            ensureOpen();
            parseExtensionsDependencies();
1197

D
duke 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
            if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
                Manifest man = jar.getManifest();
                if (man != null) {
                    Attributes attr = man.getMainAttributes();
                    if (attr != null) {
                        String value = attr.getValue(Name.CLASS_PATH);
                        if (value != null) {
                            return parseClassPath(csu, value);
                        }
                    }
                }
            }
            return null;
        }

        /*
         * parse the standard extension dependencies
         */
        private void  parseExtensionsDependencies() throws IOException {
            ExtensionDependency.checkExtensionsDependencies(jar);
        }

        /*
         * Parses value of the Class-Path manifest attribute and returns
         * an array of URLs relative to the specified base URL.
         */
        private URL[] parseClassPath(URL base, String value)
            throws MalformedURLException
        {
            StringTokenizer st = new StringTokenizer(value);
            URL[] urls = new URL[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String path = st.nextToken();
1232
                URL url = DISABLE_CP_URL_CHECK ? new URL(base, path) : tryResolve(base, path);
1233 1234 1235
                if (url != null) {
                    urls[i] = url;
                    i++;
1236 1237 1238 1239 1240
                } else {
                    if (DEBUG_CP_URL_CHECK) {
                        System.err.println("Class-Path entry: \"" + path
                                           + "\" ignored in JAR file " + base);
                    }
1241 1242 1243 1244 1245 1246 1247
                }
            }
            if (i == 0) {
                urls = null;
            } else if (i != urls.length) {
                // Truncate nulls from end of array
                urls = Arrays.copyOf(urls, i);
D
duke 已提交
1248 1249 1250
            }
            return urls;
        }
1251

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
        static URL tryResolve(URL base, String input) throws MalformedURLException {
            if ("file".equalsIgnoreCase(base.getProtocol())) {
                return tryResolveFile(base, input);
            } else {
                return tryResolveNonFile(base, input);
            }
        }

        /**
         * Attempt to return a file URL by resolving input against a base file
         * URL. The input is an absolute or relative file URL that encodes a
         * file path.
         *
         * @apiNote Nonsensical input such as a Windows file path with a drive
         * letter cannot be disambiguated from an absolute URL so will be rejected
         * (by returning null) by this method.
         *
         * @return the resolved URL or null if the input is an absolute URL with
         *         a scheme other than file (ignoring case)
         * @throws MalformedURLException
1272
         */
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        static URL tryResolveFile(URL base, String input) throws MalformedURLException {
            int index = input.indexOf(':');
            boolean isFile;
            if (index >= 0) {
                String scheme = input.substring(0, index);
                isFile = "file".equalsIgnoreCase(scheme);
            } else {
                isFile = true;
            }
            return (isFile) ? new URL(base, input) : null;
        }

        /**
         * Attempt to return a URL by resolving input against a base URL. Returns
         * null if the resolved URL is not contained by the base URL.
         *
         * @return the resolved URL or null
         * @throws MalformedURLException
         */
        static URL tryResolveNonFile(URL base, String input) throws MalformedURLException {
            String child = input.replace(File.separatorChar, '/');
            if (isRelative(child)) {
                URL url = new URL(base, child);
                String bp = base.getPath();
                String urlp = url.getPath();
                int pos = bp.lastIndexOf('/');
                if (pos == -1) {
                    pos = bp.length() - 1;
                }
                if (urlp.regionMatches(0, bp, 0, pos + 1)
                        && urlp.indexOf("..", pos) == -1) {
                    return url;
1305 1306 1307 1308
                }
            }
            return null;
        }
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

        /**
         * Returns true if the given input is a relative URI.
         */
        static boolean isRelative(String child) {
            try {
                return !URI.create(child).isAbsolute();
            } catch (IllegalArgumentException e) {
                return false;
            }
        }
D
duke 已提交
1320 1321 1322 1323 1324 1325 1326
    }

    /*
     * Inner class used to represent a loader of classes and resources
     * from a file URL that refers to a directory.
     */
    private static class FileLoader extends Loader {
1327
        /* Canonicalized File */
D
duke 已提交
1328 1329 1330 1331 1332 1333 1334 1335 1336
        private File dir;

        FileLoader(URL url) throws IOException {
            super(url);
            if (!"file".equals(url.getProtocol())) {
                throw new IllegalArgumentException("url");
            }
            String path = url.getFile().replace('/', File.separatorChar);
            path = ParseUtil.decode(path);
1337
            dir = (new File(path)).getCanonicalFile();
D
duke 已提交
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
        }

        /*
         * Returns the URL for a resource with the specified name
         */
        URL findResource(final String name, boolean check) {
            Resource rsc = getResource(name, check);
            if (rsc != null) {
                return rsc.getURL();
            }
            return null;
        }

        Resource getResource(final String name, boolean check) {
            final URL url;
            try {
                URL normalizedBase = new URL(getBaseURL(), ".");
                url = new URL(getBaseURL(), ParseUtil.encodePath(name, false));

                if (url.getFile().startsWith(normalizedBase.getFile()) == false) {
                    // requested resource had ../..'s in path
                    return null;
                }

                if (check)
                    URLClassPath.check(url);
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

                final File file;
                if (name.indexOf("..") != -1) {
                    file = (new File(dir, name.replace('/', File.separatorChar)))
                          .getCanonicalFile();
                    if ( !((file.getPath()).startsWith(dir.getPath())) ) {
                        /* outside of base dir */
                        return null;
                    }
                } else {
                    file = new File(dir, name.replace('/', File.separatorChar));
                }

D
duke 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
                if (file.exists()) {
                    return new Resource() {
                        public String getName() { return name; };
                        public URL getURL() { return url; };
                        public URL getCodeSourceURL() { return getBaseURL(); };
                        public InputStream getInputStream() throws IOException
                            { return new FileInputStream(file); };
                        public int getContentLength() throws IOException
                            { return (int)file.length(); };
                    };
                }
            } catch (Exception e) {
                return null;
            }
            return null;
        }
    }
}