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