1 /* 2 * Copyright (c) 1997, 2017, 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 jdk.internal.loader; 27 28 import java.io.Closeable; 29 import java.io.File; 30 import java.io.FileInputStream; 31 import java.io.FileNotFoundException; 32 import java.io.IOException; 33 import java.io.InputStream; 34 import java.net.HttpURLConnection; 35 import java.net.JarURLConnection; 36 import java.net.MalformedURLException; 37 import java.net.URL; 38 import java.net.URLConnection; 39 import java.net.URLStreamHandler; 40 import java.net.URLStreamHandlerFactory; 41 import java.security.AccessControlContext; 42 import java.security.AccessControlException; 43 import java.security.AccessController; 44 import java.security.CodeSigner; 45 import java.security.Permission; 46 import java.security.PrivilegedActionException; 47 import java.security.PrivilegedExceptionAction; 48 import java.security.cert.Certificate; 49 import java.util.ArrayList; 50 import java.util.Arrays; 51 import java.util.Collections; 52 import java.util.Enumeration; 53 import java.util.HashMap; 54 import java.util.HashSet; 55 import java.util.LinkedList; 56 import java.util.List; 57 import java.util.NoSuchElementException; 58 import java.util.Properties; 59 import java.util.Set; 60 import java.util.Stack; 61 import java.util.StringTokenizer; 62 import java.util.jar.JarFile; 63 import java.util.zip.ZipEntry; 64 import java.util.jar.JarEntry; 65 import java.util.jar.Manifest; 66 import java.util.jar.Attributes; 67 import java.util.jar.Attributes.Name; 68 import java.util.zip.ZipFile; 69 70 import jdk.internal.misc.JavaNetURLAccess; 71 import jdk.internal.misc.JavaUtilZipFileAccess; 72 import jdk.internal.misc.SharedSecrets; 73 import jdk.internal.util.jar.InvalidJarIndexError; 74 import jdk.internal.util.jar.JarIndex; 75 import sun.net.util.URLUtil; 76 import sun.net.www.ParseUtil; 77 import sun.security.action.GetPropertyAction; 78 79 /** 80 * This class is used to maintain a search path of URLs for loading classes 81 * and resources from both JAR files and directories. 82 * 83 * @author David Connelly 84 */ 85 public class URLClassPath { 86 private static final String USER_AGENT_JAVA_VERSION = "UA-Java-Version"; 87 private static final String JAVA_VERSION; 88 private static final boolean DEBUG; 89 private static final boolean DISABLE_JAR_CHECKING; 90 private static final boolean DISABLE_ACC_CHECKING; 91 92 static { 93 Properties props = GetPropertyAction.privilegedGetProperties(); 94 JAVA_VERSION = props.getProperty("java.version"); 95 DEBUG = (props.getProperty("sun.misc.URLClassPath.debug") != null); 96 String p = props.getProperty("sun.misc.URLClassPath.disableJarChecking"); 97 DISABLE_JAR_CHECKING = p != null ? p.equals("true") || p.equals("") : false; 98 99 p = props.getProperty("jdk.net.URLClassPath.disableRestrictedPermissions"); 100 DISABLE_ACC_CHECKING = p != null ? p.equals("true") || p.equals("") : false; 101 } 102 103 /* The original search path of URLs. */ 104 private final List<URL> path; 105 106 /* The stack of unopened URLs */ 107 private final Stack<URL> unopenedUrls = new Stack<>(); 108 109 /* The resulting search path of Loaders */ 110 private final ArrayList<Loader> loaders = new ArrayList<>(); 111 112 /* Map of each URL opened to its corresponding Loader */ 113 private final HashMap<String, Loader> lmap = new HashMap<>(); 114 115 /* The jar protocol handler to use when creating new URLs */ 116 private final URLStreamHandler jarHandler; 117 118 /* Whether this URLClassLoader has been closed yet */ 119 private boolean closed = false; 120 121 /* The context to be used when loading classes and resources. If non-null 122 * this is the context that was captured during the creation of the 123 * URLClassLoader. null implies no additional security restrictions. */ 124 private final AccessControlContext acc; 125 126 /** 127 * Creates a new URLClassPath for the given URLs. The URLs will be 128 * searched in the order specified for classes and resources. A URL 129 * ending with a '/' is assumed to refer to a directory. Otherwise, 130 * the URL is assumed to refer to a JAR file. 131 * 132 * @param urls the directory and JAR file URLs to search for classes 133 * and resources 134 * @param factory the URLStreamHandlerFactory to use when creating new URLs 135 * @param acc the context to be used when loading classes and resources, may 136 * be null 137 */ 138 public URLClassPath(URL[] urls, 139 URLStreamHandlerFactory factory, 140 AccessControlContext acc) { 141 List<URL> path = new ArrayList<>(urls.length); 142 for (URL url : urls) { 143 path.add(url); 144 } 145 this.path = path; 146 push(urls); 147 if (factory != null) { 148 jarHandler = factory.createURLStreamHandler("jar"); 149 } else { 150 jarHandler = null; 151 } 152 if (DISABLE_ACC_CHECKING) 153 this.acc = null; 154 else 155 this.acc = acc; 156 } 157 158 public URLClassPath(URL[] urls, AccessControlContext acc) { 159 this(urls, null, acc); 160 } 161 162 /** 163 * Constructs a URLClassPath from a class path string. 164 * 165 * @param cp the class path string 166 * @param skipEmptyElements indicates if empty elements are ignored or 167 * treated as the current working directory 168 * 169 * @apiNote Used to create the application class path. 170 */ 171 URLClassPath(String cp, boolean skipEmptyElements) { 172 List<URL> path = new ArrayList<>(); 173 if (cp != null) { 174 // map each element of class path to a file URL 175 int off = 0; 176 int next; 177 while ((next = cp.indexOf(File.pathSeparator, off)) != -1) { 178 String element = cp.substring(off, next); 179 if (element.length() > 0 || !skipEmptyElements) { 180 URL url = toFileURL(element); 181 if (url != null) path.add(url); 182 } 183 off = next + 1; 184 } 185 186 // remaining element 187 String element = cp.substring(off); 188 if (element.length() > 0 || !skipEmptyElements) { 189 URL url = toFileURL(element); 190 if (url != null) path.add(url); 191 } 192 193 // push the URLs 194 for (int i = path.size() - 1; i >= 0; --i) { 195 unopenedUrls.push(path.get(i)); 196 } 197 } 198 199 this.path = path; 200 this.jarHandler = null; 201 this.acc = null; 202 } 203 204 public synchronized List<IOException> closeLoaders() { 205 if (closed) { 206 return Collections.emptyList(); 207 } 208 List<IOException> result = new LinkedList<>(); 209 for (Loader loader : loaders) { 210 try { 211 loader.close(); 212 } catch (IOException e) { 213 result.add(e); 214 } 215 } 216 closed = true; 217 return result; 218 } 219 220 /** 221 * Appends the specified URL to the search path of directory and JAR 222 * file URLs from which to load classes and resources. 223 * <p> 224 * If the URL specified is null or is already in the list of 225 * URLs, then invoking this method has no effect. 226 */ 227 public synchronized void addURL(URL url) { 228 if (closed) 229 return; 230 synchronized (unopenedUrls) { 231 if (url == null || path.contains(url)) 232 return; 233 234 unopenedUrls.add(0, url); 235 path.add(url); 236 } 237 } 238 239 /** 240 * Appends the specified file path as a file URL to the search path. 241 */ 242 public void addFile(String s) { 243 URL url = toFileURL(s); 244 if (url != null) { 245 addURL(url); 246 } 247 } 248 249 /** 250 * Returns a file URL for the given file path. 251 */ 252 private static URL toFileURL(String s) { 253 try { 254 File f = new File(s).getCanonicalFile(); 255 return ParseUtil.fileToEncodedURL(f); 256 } catch (IOException e) { 257 return null; 258 } 259 } 260 261 /** 262 * Returns the original search path of URLs. 263 */ 264 public URL[] getURLs() { 265 synchronized (unopenedUrls) { 266 return path.toArray(new URL[0]); 267 } 268 } 269 270 /** 271 * Finds the resource with the specified name on the URL search path 272 * or null if not found or security check fails. 273 * 274 * @param name the name of the resource 275 * @param check whether to perform a security check 276 * @return a {@code URL} for the resource, or {@code null} 277 * if the resource could not be found. 278 */ 279 public URL findResource(String name, boolean check) { 280 Loader loader; 281 for (int i = 0; (loader = getLoader(i)) != null; i++) { 282 URL url = loader.findResource(name, check); 283 if (url != null) { 284 return url; 285 } 286 } 287 return null; 288 } 289 290 /** 291 * Finds the first Resource on the URL search path which has the specified 292 * name. Returns null if no Resource could be found. 293 * 294 * @param name the name of the Resource 295 * @param check whether to perform a security check 296 * @return the Resource, or null if not found 297 */ 298 public Resource getResource(String name, boolean check) { 299 if (DEBUG) { 300 System.err.println("URLClassPath.getResource(\"" + name + "\")"); 301 } 302 303 Loader loader; 304 for (int i = 0; (loader = getLoader(i)) != null; i++) { 305 Resource res = loader.getResource(name, check); 306 if (res != null) { 307 return res; 308 } 309 } 310 return null; 311 } 312 313 /** 314 * Finds all resources on the URL search path with the given name. 315 * Returns an enumeration of the URL objects. 316 * 317 * @param name the resource name 318 * @return an Enumeration of all the urls having the specified name 319 */ 320 public Enumeration<URL> findResources(final String name, 321 final boolean check) { 322 return new Enumeration<>() { 323 private int index = 0; 324 private URL url = null; 325 326 private boolean next() { 327 if (url != null) { 328 return true; 329 } else { 330 Loader loader; 331 while ((loader = getLoader(index++)) != null) { 332 url = loader.findResource(name, check); 333 if (url != null) { 334 return true; 335 } 336 } 337 return false; 338 } 339 } 340 341 public boolean hasMoreElements() { 342 return next(); 343 } 344 345 public URL nextElement() { 346 if (!next()) { 347 throw new NoSuchElementException(); 348 } 349 URL u = url; 350 url = null; 351 return u; 352 } 353 }; 354 } 355 356 public Resource getResource(String name) { 357 return getResource(name, true); 358 } 359 360 /** 361 * Finds all resources on the URL search path with the given name. 362 * Returns an enumeration of the Resource objects. 363 * 364 * @param name the resource name 365 * @return an Enumeration of all the resources having the specified name 366 */ 367 public Enumeration<Resource> getResources(final String name, 368 final boolean check) { 369 return new Enumeration<>() { 370 private int index = 0; 371 private Resource res = null; 372 373 private boolean next() { 374 if (res != null) { 375 return true; 376 } else { 377 Loader loader; 378 while ((loader = getLoader(index++)) != null) { 379 res = loader.getResource(name, check); 380 if (res != null) { 381 return true; 382 } 383 } 384 return false; 385 } 386 } 387 388 public boolean hasMoreElements() { 389 return next(); 390 } 391 392 public Resource nextElement() { 393 if (!next()) { 394 throw new NoSuchElementException(); 395 } 396 Resource r = res; 397 res = null; 398 return r; 399 } 400 }; 401 } 402 403 public Enumeration<Resource> getResources(final String name) { 404 return getResources(name, true); 405 } 406 407 /* 408 * Returns the Loader at the specified position in the URL search 409 * path. The URLs are opened and expanded as needed. Returns null 410 * if the specified index is out of range. 411 */ 412 private synchronized Loader getLoader(int index) { 413 if (closed) { 414 return null; 415 } 416 // Expand URL search path until the request can be satisfied 417 // or the URL stack is empty. 418 while (loaders.size() < index + 1) { 419 // Pop the next URL from the URL stack 420 URL url; 421 synchronized (unopenedUrls) { 422 if (unopenedUrls.empty()) { 423 return null; 424 } else { 425 url = unopenedUrls.pop(); 426 } 427 } 428 // Skip this URL if it already has a Loader. (Loader 429 // may be null in the case where URL has not been opened 430 // but is referenced by a JAR index.) 431 String urlNoFragString = URLUtil.urlNoFragString(url); 432 if (lmap.containsKey(urlNoFragString)) { 433 continue; 434 } 435 // Otherwise, create a new Loader for the URL. 436 Loader loader; 437 try { 438 loader = getLoader(url); 439 // If the loader defines a local class path then add the 440 // URLs to the list of URLs to be opened. 441 URL[] urls = loader.getClassPath(); 442 if (urls != null) { 443 push(urls); 444 } 445 } catch (IOException e) { 446 // Silently ignore for now... 447 continue; 448 } catch (SecurityException se) { 449 // Always silently ignore. The context, if there is one, that 450 // this URLClassPath was given during construction will never 451 // have permission to access the URL. 452 if (DEBUG) { 453 System.err.println("Failed to access " + url + ", " + se ); 454 } 455 continue; 456 } 457 // Finally, add the Loader to the search path. 458 loaders.add(loader); 459 lmap.put(urlNoFragString, loader); 460 } 461 return loaders.get(index); 462 } 463 464 /* 465 * Returns the Loader for the specified base URL. 466 */ 467 private Loader getLoader(final URL url) throws IOException { 468 try { 469 return AccessController.doPrivileged( 470 new PrivilegedExceptionAction<>() { 471 public Loader run() throws IOException { 472 String protocol = url.getProtocol(); // lower cased in URL 473 String file = url.getFile(); 474 if (file != null && file.endsWith("/")) { 475 if ("file".equals(protocol)) { 476 return new FileLoader(url); 477 } else if ("jar".equals(protocol) && 478 isDefaultJarHandler(url) && 479 file.endsWith("!/")) { 480 // extract the nested URL 481 URL nestedUrl = new URL(file.substring(0, file.length() - 2)); 482 return new JarLoader(nestedUrl, jarHandler, lmap, acc); 483 } else { 484 return new Loader(url); 485 } 486 } else { 487 return new JarLoader(url, jarHandler, lmap, acc); 488 } 489 } 490 }, acc); 491 } catch (PrivilegedActionException pae) { 492 throw (IOException)pae.getException(); 493 } 494 } 495 496 private static final JavaNetURLAccess JNUA 497 = SharedSecrets.getJavaNetURLAccess(); 498 499 private static boolean isDefaultJarHandler(URL u) { 500 URLStreamHandler h = JNUA.getHandler(u); 501 return h instanceof sun.net.www.protocol.jar.Handler; 502 } 503 504 /* 505 * Pushes the specified URLs onto the list of unopened URLs. 506 */ 507 private void push(URL[] urls) { 508 synchronized (unopenedUrls) { 509 for (int i = urls.length - 1; i >= 0; --i) { 510 unopenedUrls.push(urls[i]); 511 } 512 } 513 } 514 515 /* 516 * Checks whether the resource URL should be returned. 517 * Returns null on security check failure. 518 * Called by java.net.URLClassLoader. 519 */ 520 public static URL checkURL(URL url) { 521 if (url != null) { 522 try { 523 check(url); 524 } catch (Exception e) { 525 return null; 526 } 527 } 528 return url; 529 } 530 531 /* 532 * Checks whether the resource URL should be returned. 533 * Throws exception on failure. 534 * Called internally within this file. 535 */ 536 public static void check(URL url) throws IOException { 537 SecurityManager security = System.getSecurityManager(); 538 if (security != null) { 539 URLConnection urlConnection = url.openConnection(); 540 Permission perm = urlConnection.getPermission(); 541 if (perm != null) { 542 try { 543 security.checkPermission(perm); 544 } catch (SecurityException se) { 545 // fallback to checkRead/checkConnect for pre 1.2 546 // security managers 547 if ((perm instanceof java.io.FilePermission) && 548 perm.getActions().indexOf("read") != -1) { 549 security.checkRead(perm.getName()); 550 } else if ((perm instanceof 551 java.net.SocketPermission) && 552 perm.getActions().indexOf("connect") != -1) { 553 URL locUrl = url; 554 if (urlConnection instanceof JarURLConnection) { 555 locUrl = ((JarURLConnection)urlConnection).getJarFileURL(); 556 } 557 security.checkConnect(locUrl.getHost(), 558 locUrl.getPort()); 559 } else { 560 throw se; 561 } 562 } 563 } 564 } 565 } 566 567 /** 568 * Nested class used to represent a loader of resources and classes 569 * from a base URL. 570 */ 571 private static class Loader implements Closeable { 572 private final URL base; 573 private JarFile jarfile; // if this points to a jar file 574 575 /* 576 * Creates a new Loader for the specified URL. 577 */ 578 Loader(URL url) { 579 base = url; 580 } 581 582 /* 583 * Returns the base URL for this Loader. 584 */ 585 URL getBaseURL() { 586 return base; 587 } 588 589 URL findResource(final String name, boolean check) { 590 URL url; 591 try { 592 url = new URL(base, ParseUtil.encodePath(name, false)); 593 } catch (MalformedURLException e) { 594 throw new IllegalArgumentException("name"); 595 } 596 597 try { 598 if (check) { 599 URLClassPath.check(url); 600 } 601 602 /* 603 * For a HTTP connection we use the HEAD method to 604 * check if the resource exists. 605 */ 606 URLConnection uc = url.openConnection(); 607 if (uc instanceof HttpURLConnection) { 608 HttpURLConnection hconn = (HttpURLConnection)uc; 609 hconn.setRequestMethod("HEAD"); 610 if (hconn.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { 611 return null; 612 } 613 } else { 614 // our best guess for the other cases 615 uc.setUseCaches(false); 616 InputStream is = uc.getInputStream(); 617 is.close(); 618 } 619 return url; 620 } catch (Exception e) { 621 return null; 622 } 623 } 624 625 Resource getResource(final String name, boolean check) { 626 final URL url; 627 try { 628 url = new URL(base, ParseUtil.encodePath(name, false)); 629 } catch (MalformedURLException e) { 630 throw new IllegalArgumentException("name"); 631 } 632 final URLConnection uc; 633 try { 634 if (check) { 635 URLClassPath.check(url); 636 } 637 uc = url.openConnection(); 638 InputStream in = uc.getInputStream(); 639 if (uc instanceof JarURLConnection) { 640 /* Need to remember the jar file so it can be closed 641 * in a hurry. 642 */ 643 JarURLConnection juc = (JarURLConnection)uc; 644 jarfile = JarLoader.checkJar(juc.getJarFile()); 645 } 646 } catch (Exception e) { 647 return null; 648 } 649 return new Resource() { 650 public String getName() { return name; } 651 public URL getURL() { return url; } 652 public URL getCodeSourceURL() { return base; } 653 public InputStream getInputStream() throws IOException { 654 return uc.getInputStream(); 655 } 656 public int getContentLength() throws IOException { 657 return uc.getContentLength(); 658 } 659 }; 660 } 661 662 /* 663 * Returns the Resource for the specified name, or null if not 664 * found or the caller does not have the permission to get the 665 * resource. 666 */ 667 Resource getResource(final String name) { 668 return getResource(name, true); 669 } 670 671 /* 672 * Closes this loader and release all resources. 673 * Method overridden in sub-classes. 674 */ 675 @Override 676 public void close() throws IOException { 677 if (jarfile != null) { 678 jarfile.close(); 679 } 680 } 681 682 /* 683 * Returns the local class path for this loader, or null if none. 684 */ 685 URL[] getClassPath() throws IOException { 686 return null; 687 } 688 } 689 690 /* 691 * Nested class used to represent a Loader of resources from a JAR URL. 692 */ 693 static class JarLoader extends Loader { 694 private JarFile jar; 695 private final URL csu; 696 private JarIndex index; 697 private URLStreamHandler handler; 698 private final HashMap<String, Loader> lmap; 699 private final AccessControlContext acc; 700 private boolean closed = false; 701 private static final JavaUtilZipFileAccess zipAccess = 702 SharedSecrets.getJavaUtilZipFileAccess(); 703 704 /* 705 * Creates a new JarLoader for the specified URL referring to 706 * a JAR file. 707 */ 708 JarLoader(URL url, URLStreamHandler jarHandler, 709 HashMap<String, Loader> loaderMap, 710 AccessControlContext acc) 711 throws IOException 712 { 713 super(new URL("jar", "", -1, url + "!/", jarHandler)); 714 csu = url; 715 handler = jarHandler; 716 lmap = loaderMap; 717 this.acc = acc; 718 719 ensureOpen(); 720 } 721 722 @Override 723 public void close () throws IOException { 724 // closing is synchronized at higher level 725 if (!closed) { 726 closed = true; 727 // in case not already open. 728 ensureOpen(); 729 jar.close(); 730 } 731 } 732 733 JarFile getJarFile () { 734 return jar; 735 } 736 737 private boolean isOptimizable(URL url) { 738 return "file".equals(url.getProtocol()); 739 } 740 741 private void ensureOpen() throws IOException { 742 if (jar == null) { 743 try { 744 AccessController.doPrivileged( 745 new PrivilegedExceptionAction<>() { 746 public Void run() throws IOException { 747 if (DEBUG) { 748 System.err.println("Opening " + csu); 749 Thread.dumpStack(); 750 } 751 752 jar = getJarFile(csu); 753 index = JarIndex.getJarIndex(jar); 754 if (index != null) { 755 String[] jarfiles = index.getJarFiles(); 756 // Add all the dependent URLs to the lmap so that loaders 757 // will not be created for them by URLClassPath.getLoader(int) 758 // if the same URL occurs later on the main class path. We set 759 // Loader to null here to avoid creating a Loader for each 760 // URL until we actually need to try to load something from them. 761 for (int i = 0; i < jarfiles.length; i++) { 762 try { 763 URL jarURL = new URL(csu, jarfiles[i]); 764 // If a non-null loader already exists, leave it alone. 765 String urlNoFragString = URLUtil.urlNoFragString(jarURL); 766 if (!lmap.containsKey(urlNoFragString)) { 767 lmap.put(urlNoFragString, null); 768 } 769 } catch (MalformedURLException e) { 770 continue; 771 } 772 } 773 } 774 return null; 775 } 776 }, acc); 777 } catch (PrivilegedActionException pae) { 778 throw (IOException)pae.getException(); 779 } 780 } 781 } 782 783 /* Throws if the given jar file is does not start with the correct LOC */ 784 static JarFile checkJar(JarFile jar) throws IOException { 785 if (System.getSecurityManager() != null && !DISABLE_JAR_CHECKING 786 && !zipAccess.startsWithLocHeader(jar)) { 787 IOException x = new IOException("Invalid Jar file"); 788 try { 789 jar.close(); 790 } catch (IOException ex) { 791 x.addSuppressed(ex); 792 } 793 throw x; 794 } 795 796 return jar; 797 } 798 799 private JarFile getJarFile(URL url) throws IOException { 800 // Optimize case where url refers to a local jar file 801 if (isOptimizable(url)) { 802 FileURLMapper p = new FileURLMapper (url); 803 if (!p.exists()) { 804 throw new FileNotFoundException(p.getPath()); 805 } 806 return checkJar(new JarFile(new File(p.getPath()), true, ZipFile.OPEN_READ, 807 JarFile.runtimeVersion())); 808 } 809 URLConnection uc = (new URL(getBaseURL(), "#runtime")).openConnection(); 810 uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION); 811 JarFile jarFile = ((JarURLConnection)uc).getJarFile(); 812 return checkJar(jarFile); 813 } 814 815 /* 816 * Returns the index of this JarLoader if it exists. 817 */ 818 JarIndex getIndex() { 819 try { 820 ensureOpen(); 821 } catch (IOException e) { 822 throw new InternalError(e); 823 } 824 return index; 825 } 826 827 /* 828 * Creates the resource and if the check flag is set to true, checks if 829 * is its okay to return the resource. 830 */ 831 Resource checkResource(final String name, boolean check, 832 final JarEntry entry) { 833 834 final URL url; 835 try { 836 String nm; 837 if (jar.isMultiRelease()) { 838 nm = entry.getRealName(); 839 } else { 840 nm = name; 841 } 842 url = new URL(getBaseURL(), ParseUtil.encodePath(nm, false)); 843 if (check) { 844 URLClassPath.check(url); 845 } 846 } catch (MalformedURLException e) { 847 return null; 848 // throw new IllegalArgumentException("name"); 849 } catch (IOException e) { 850 return null; 851 } catch (AccessControlException e) { 852 return null; 853 } 854 855 return new Resource() { 856 public String getName() { return name; } 857 public URL getURL() { return url; } 858 public URL getCodeSourceURL() { return csu; } 859 public InputStream getInputStream() throws IOException 860 { return jar.getInputStream(entry); } 861 public int getContentLength() 862 { return (int)entry.getSize(); } 863 public Manifest getManifest() throws IOException 864 { return jar.getManifest(); }; 865 public Certificate[] getCertificates() 866 { return entry.getCertificates(); }; 867 public CodeSigner[] getCodeSigners() 868 { return entry.getCodeSigners(); }; 869 }; 870 } 871 872 873 /* 874 * Returns true iff at least one resource in the jar file has the same 875 * package name as that of the specified resource name. 876 */ 877 boolean validIndex(final String name) { 878 String packageName = name; 879 int pos; 880 if ((pos = name.lastIndexOf('/')) != -1) { 881 packageName = name.substring(0, pos); 882 } 883 884 String entryName; 885 ZipEntry entry; 886 Enumeration<JarEntry> enum_ = jar.entries(); 887 while (enum_.hasMoreElements()) { 888 entry = enum_.nextElement(); 889 entryName = entry.getName(); 890 if ((pos = entryName.lastIndexOf('/')) != -1) 891 entryName = entryName.substring(0, pos); 892 if (entryName.equals(packageName)) { 893 return true; 894 } 895 } 896 return false; 897 } 898 899 /* 900 * Returns the URL for a resource with the specified name 901 */ 902 @Override 903 URL findResource(final String name, boolean check) { 904 Resource rsc = getResource(name, check); 905 if (rsc != null) { 906 return rsc.getURL(); 907 } 908 return null; 909 } 910 911 /* 912 * Returns the JAR Resource for the specified name. 913 */ 914 @Override 915 Resource getResource(final String name, boolean check) { 916 try { 917 ensureOpen(); 918 } catch (IOException e) { 919 throw new InternalError(e); 920 } 921 final JarEntry entry = jar.getJarEntry(name); 922 if (entry != null) 923 return checkResource(name, check, entry); 924 925 if (index == null) 926 return null; 927 928 HashSet<String> visited = new HashSet<>(); 929 return getResource(name, check, visited); 930 } 931 932 /* 933 * Version of getResource() that tracks the jar files that have been 934 * visited by linking through the index files. This helper method uses 935 * a HashSet to store the URLs of jar files that have been searched and 936 * uses it to avoid going into an infinite loop, looking for a 937 * non-existent resource. 938 */ 939 Resource getResource(final String name, boolean check, 940 Set<String> visited) { 941 Resource res; 942 String[] jarFiles; 943 int count = 0; 944 LinkedList<String> jarFilesList = null; 945 946 /* If there no jar files in the index that can potential contain 947 * this resource then return immediately. 948 */ 949 if ((jarFilesList = index.get(name)) == null) 950 return null; 951 952 do { 953 int size = jarFilesList.size(); 954 jarFiles = jarFilesList.toArray(new String[size]); 955 /* loop through the mapped jar file list */ 956 while (count < size) { 957 String jarName = jarFiles[count++]; 958 JarLoader newLoader; 959 final URL url; 960 961 try{ 962 url = new URL(csu, jarName); 963 String urlNoFragString = URLUtil.urlNoFragString(url); 964 if ((newLoader = (JarLoader)lmap.get(urlNoFragString)) == null) { 965 /* no loader has been set up for this jar file 966 * before 967 */ 968 newLoader = AccessController.doPrivileged( 969 new PrivilegedExceptionAction<>() { 970 public JarLoader run() throws IOException { 971 return new JarLoader(url, handler, 972 lmap, acc); 973 } 974 }, acc); 975 976 /* this newly opened jar file has its own index, 977 * merge it into the parent's index, taking into 978 * account the relative path. 979 */ 980 JarIndex newIndex = newLoader.getIndex(); 981 if (newIndex != null) { 982 int pos = jarName.lastIndexOf('/'); 983 newIndex.merge(this.index, (pos == -1 ? 984 null : jarName.substring(0, pos + 1))); 985 } 986 987 /* put it in the global hashtable */ 988 lmap.put(urlNoFragString, newLoader); 989 } 990 } catch (PrivilegedActionException pae) { 991 continue; 992 } catch (MalformedURLException e) { 993 continue; 994 } 995 996 /* Note that the addition of the url to the list of visited 997 * jars incorporates a check for presence in the hashmap 998 */ 999 boolean visitedURL = !visited.add(URLUtil.urlNoFragString(url)); 1000 if (!visitedURL) { 1001 try { 1002 newLoader.ensureOpen(); 1003 } catch (IOException e) { 1004 throw new InternalError(e); 1005 } 1006 final JarEntry entry = newLoader.jar.getJarEntry(name); 1007 if (entry != null) { 1008 return newLoader.checkResource(name, check, entry); 1009 } 1010 1011 /* Verify that at least one other resource with the 1012 * same package name as the lookedup resource is 1013 * present in the new jar 1014 */ 1015 if (!newLoader.validIndex(name)) { 1016 /* the mapping is wrong */ 1017 throw new InvalidJarIndexError("Invalid index"); 1018 } 1019 } 1020 1021 /* If newLoader is the current loader or if it is a 1022 * loader that has already been searched or if the new 1023 * loader does not have an index then skip it 1024 * and move on to the next loader. 1025 */ 1026 if (visitedURL || newLoader == this || 1027 newLoader.getIndex() == null) { 1028 continue; 1029 } 1030 1031 /* Process the index of the new loader 1032 */ 1033 if ((res = newLoader.getResource(name, check, visited)) 1034 != null) { 1035 return res; 1036 } 1037 } 1038 // Get the list of jar files again as the list could have grown 1039 // due to merging of index files. 1040 jarFilesList = index.get(name); 1041 1042 // If the count is unchanged, we are done. 1043 } while (count < jarFilesList.size()); 1044 return null; 1045 } 1046 1047 1048 /* 1049 * Returns the JAR file local class path, or null if none. 1050 */ 1051 @Override 1052 URL[] getClassPath() throws IOException { 1053 if (index != null) { 1054 return null; 1055 } 1056 1057 ensureOpen(); 1058 1059 // Only get manifest when necessary 1060 if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { 1061 Manifest man = jar.getManifest(); 1062 if (man != null) { 1063 Attributes attr = man.getMainAttributes(); 1064 if (attr != null) { 1065 String value = attr.getValue(Name.CLASS_PATH); 1066 if (value != null) { 1067 return parseClassPath(csu, value); 1068 } 1069 } 1070 } 1071 } 1072 return null; 1073 } 1074 1075 /* 1076 * Parses value of the Class-Path manifest attribute and returns 1077 * an array of URLs relative to the specified base URL. 1078 */ 1079 private static URL[] parseClassPath(URL base, String value) 1080 throws MalformedURLException 1081 { 1082 StringTokenizer st = new StringTokenizer(value); 1083 URL[] urls = new URL[st.countTokens()]; 1084 int i = 0; 1085 while (st.hasMoreTokens()) { 1086 String path = st.nextToken(); 1087 urls[i] = new URL(base, path); 1088 i++; 1089 } 1090 return urls; 1091 } 1092 } 1093 1094 /* 1095 * Nested class used to represent a loader of classes and resources 1096 * from a file URL that refers to a directory. 1097 */ 1098 private static class FileLoader extends Loader { 1099 /* Canonicalized File */ 1100 private File dir; 1101 1102 FileLoader(URL url) throws IOException { 1103 super(url); 1104 if (!"file".equals(url.getProtocol())) { 1105 throw new IllegalArgumentException("url"); 1106 } 1107 String path = url.getFile().replace('/', File.separatorChar); 1108 path = ParseUtil.decode(path); 1109 dir = (new File(path)).getCanonicalFile(); 1110 } 1111 1112 /* 1113 * Returns the URL for a resource with the specified name 1114 */ 1115 @Override 1116 URL findResource(final String name, boolean check) { 1117 Resource rsc = getResource(name, check); 1118 if (rsc != null) { 1119 return rsc.getURL(); 1120 } 1121 return null; 1122 } 1123 1124 @Override 1125 Resource getResource(final String name, boolean check) { 1126 final URL url; 1127 try { 1128 URL normalizedBase = new URL(getBaseURL(), "."); 1129 url = new URL(getBaseURL(), ParseUtil.encodePath(name, false)); 1130 1131 if (url.getFile().startsWith(normalizedBase.getFile()) == false) { 1132 // requested resource had ../..'s in path 1133 return null; 1134 } 1135 1136 if (check) 1137 URLClassPath.check(url); 1138 1139 final File file; 1140 if (name.indexOf("..") != -1) { 1141 file = (new File(dir, name.replace('/', File.separatorChar))) 1142 .getCanonicalFile(); 1143 if ( !((file.getPath()).startsWith(dir.getPath())) ) { 1144 /* outside of base dir */ 1145 return null; 1146 } 1147 } else { 1148 file = new File(dir, name.replace('/', File.separatorChar)); 1149 } 1150 1151 if (file.exists()) { 1152 return new Resource() { 1153 public String getName() { return name; }; 1154 public URL getURL() { return url; }; 1155 public URL getCodeSourceURL() { return getBaseURL(); }; 1156 public InputStream getInputStream() throws IOException 1157 { return new FileInputStream(file); }; 1158 public int getContentLength() throws IOException 1159 { return (int)file.length(); }; 1160 }; 1161 } 1162 } catch (Exception e) { 1163 return null; 1164 } 1165 return null; 1166 } 1167 } 1168 }