1 /*
   2  * Copyright (c) 1996, 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.rmi.server;
  27 
  28 import java.io.File;
  29 import java.io.FilePermission;
  30 import java.io.IOException;
  31 import java.lang.ref.ReferenceQueue;
  32 import java.lang.ref.SoftReference;
  33 import java.lang.ref.WeakReference;
  34 import java.lang.reflect.Modifier;
  35 import java.lang.reflect.Proxy;
  36 import java.net.JarURLConnection;
  37 import java.net.MalformedURLException;
  38 import java.net.SocketPermission;
  39 import java.net.URL;
  40 import java.net.URLClassLoader;
  41 import java.net.URLConnection;
  42 import java.security.AccessControlContext;
  43 import java.security.CodeSource;
  44 import java.security.Permission;
  45 import java.security.Permissions;
  46 import java.security.PermissionCollection;
  47 import java.security.Policy;
  48 import java.security.ProtectionDomain;
  49 import java.rmi.server.LogStream;
  50 import java.util.Arrays;
  51 import java.util.Collections;
  52 import java.util.Enumeration;
  53 import java.util.HashMap;
  54 import java.util.IdentityHashMap;
  55 import java.util.Map;
  56 import java.util.StringTokenizer;
  57 import java.util.WeakHashMap;
  58 import sun.rmi.runtime.Log;
  59 import sun.security.action.GetPropertyAction;
  60 
  61 /**
  62  * <code>LoaderHandler</code> provides the implementation of the static
  63  * methods of the <code>java.rmi.server.RMIClassLoader</code> class.
  64  *
  65  * @author      Ann Wollrath
  66  * @author      Peter Jones
  67  * @author      Laird Dornin
  68  */
  69 public final class LoaderHandler {
  70 
  71     /** RMI class loader log level */
  72     static final int logLevel = LogStream.parseLevel(
  73         java.security.AccessController.doPrivileged(
  74             new GetPropertyAction("sun.rmi.loader.logLevel")));
  75 
  76     /* loader system log */
  77     static final Log loaderLog =
  78         Log.getLog("sun.rmi.loader", "loader", LoaderHandler.logLevel);
  79 
  80     /**
  81      * value of "java.rmi.server.codebase" property, as cached at class
  82      * initialization time.  It may contain malformed URLs.
  83      */
  84     private static String codebaseProperty = null;
  85     static {
  86         String prop = java.security.AccessController.doPrivileged(
  87             new GetPropertyAction("java.rmi.server.codebase"));
  88         if (prop != null && prop.trim().length() > 0) {
  89             codebaseProperty = prop;
  90         }
  91     }
  92 
  93     /** list of URLs represented by the codebase property, if valid */
  94     private static URL[] codebaseURLs = null;
  95 
  96     /** table of class loaders that use codebase property for annotation */
  97     private static final Map<ClassLoader, Void> codebaseLoaders =
  98         Collections.synchronizedMap(new IdentityHashMap<ClassLoader, Void>(5));
  99     static {
 100         for (ClassLoader codebaseLoader = ClassLoader.getSystemClassLoader();
 101              codebaseLoader != null;
 102              codebaseLoader = codebaseLoader.getParent())
 103         {
 104             codebaseLoaders.put(codebaseLoader, null);
 105         }
 106     }
 107 
 108     /**
 109      * table mapping codebase URL path and context class loader pairs
 110      * to class loader instances.  Entries hold class loaders with weak
 111      * references, so this table does not prevent loaders from being
 112      * garbage collected.
 113      */
 114     private static final HashMap<LoaderKey, LoaderEntry> loaderTable
 115         = new HashMap<>(5);
 116 
 117     /** reference queue for cleared class loader entries */
 118     private static final ReferenceQueue<Loader> refQueue
 119         = new ReferenceQueue<>();
 120 
 121     /*
 122      * Disallow anyone from creating one of these.
 123      */
 124     private LoaderHandler() {}
 125 
 126     /**
 127      * Returns an array of URLs initialized with the value of the
 128      * java.rmi.server.codebase property as the URL path.
 129      */
 130     private static synchronized URL[] getDefaultCodebaseURLs()
 131         throws MalformedURLException
 132     {
 133         /*
 134          * If it hasn't already been done, convert the codebase property
 135          * into an array of URLs; this may throw a MalformedURLException.
 136          */
 137         if (codebaseURLs == null) {
 138             if (codebaseProperty != null) {
 139                 codebaseURLs = pathToURLs(codebaseProperty);
 140             } else {
 141                 codebaseURLs = new URL[0];
 142             }
 143         }
 144         return codebaseURLs;
 145     }
 146 
 147     /**
 148      * Load a class from a network location (one or more URLs),
 149      * but first try to resolve the named class through the given
 150      * "default loader".
 151      */
 152     public static Class<?> loadClass(String codebase, String name,
 153                                      ClassLoader defaultLoader)
 154         throws MalformedURLException, ClassNotFoundException
 155     {
 156         if (loaderLog.isLoggable(Log.BRIEF)) {
 157             loaderLog.log(Log.BRIEF,
 158                 "name = \"" + name + "\", " +
 159                 "codebase = \"" + (codebase != null ? codebase : "") + "\"" +
 160                 (defaultLoader != null ?
 161                  ", defaultLoader = " + defaultLoader : ""));
 162         }
 163 
 164         URL[] urls;
 165         if (codebase != null) {
 166             urls = pathToURLs(codebase);
 167         } else {
 168             urls = getDefaultCodebaseURLs();
 169         }
 170 
 171         if (defaultLoader != null) {
 172             try {
 173                 Class<?> c = Class.forName(name, false, defaultLoader);
 174                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 175                     loaderLog.log(Log.VERBOSE,
 176                         "class \"" + name + "\" found via defaultLoader, " +
 177                         "defined by " + c.getClassLoader());
 178                 }
 179                 return c;
 180             } catch (ClassNotFoundException e) {
 181             }
 182         }
 183 
 184         return loadClass(urls, name);
 185     }
 186 
 187     /**
 188      * Returns the class annotation (representing the location for
 189      * a class) that RMI will use to annotate the call stream when
 190      * marshalling objects of the given class.
 191      */
 192     public static String getClassAnnotation(Class<?> cl) {
 193         String name = cl.getName();
 194 
 195         /*
 196          * Class objects for arrays of primitive types never need an
 197          * annotation, because they never need to be (or can be) downloaded.
 198          *
 199          * REMIND: should we (not) be annotating classes that are in
 200          * "java.*" packages?
 201          */
 202         int nameLength = name.length();
 203         if (nameLength > 0 && name.charAt(0) == '[') {
 204             // skip past all '[' characters (see bugid 4211906)
 205             int i = 1;
 206             while (nameLength > i && name.charAt(i) == '[') {
 207                 i++;
 208             }
 209             if (nameLength > i && name.charAt(i) != 'L') {
 210                 return null;
 211             }
 212         }
 213 
 214         /*
 215          * Get the class's class loader.  If it is null, the system class
 216          * loader, an ancestor of the base class loader (such as the loader
 217          * for installed extensions), return the value of the
 218          * "java.rmi.server.codebase" property.
 219          */
 220         ClassLoader loader = cl.getClassLoader();
 221         if (loader == null || codebaseLoaders.containsKey(loader)) {
 222             return codebaseProperty;
 223         }
 224 
 225         /*
 226          * Get the codebase URL path for the class loader, if it supports
 227          * such a notion (i.e., if it is a URLClassLoader or subclass).
 228          */
 229         String annotation = null;
 230         if (loader instanceof Loader) {
 231             /*
 232              * If the class loader is one of our RMI class loaders, we have
 233              * already computed the class annotation string, and no
 234              * permissions are required to know the URLs.
 235              */
 236             annotation = ((Loader) loader).getClassAnnotation();
 237 
 238         } else if (loader instanceof URLClassLoader) {
 239             try {
 240                 URL[] urls = ((URLClassLoader) loader).getURLs();
 241                 if (urls != null) {
 242                     /*
 243                      * If the class loader is not one of our RMI class loaders,
 244                      * we must verify that the current access control context
 245                      * has permission to know all of these URLs.
 246                      */
 247                     SecurityManager sm = System.getSecurityManager();
 248                     if (sm != null) {
 249                         Permissions perms = new Permissions();
 250                         for (int i = 0; i < urls.length; i++) {
 251                             Permission p =
 252                                 urls[i].openConnection().getPermission();
 253                             if (p != null) {
 254                                 if (!perms.implies(p)) {
 255                                     sm.checkPermission(p);
 256                                     perms.add(p);
 257                                 }
 258                             }
 259                         }
 260                     }
 261 
 262                     annotation = urlsToPath(urls);
 263                 }
 264             } catch (SecurityException | IOException e) {
 265                 /*
 266                  * SecurityException: If access was denied to the knowledge of 
 267                  * the class loader's URLs, fall back to the default behavior.
 268                  *
 269                  * IOException: This shouldn't happen, although it is declared
 270                  * to be thrown by openConnection() and getPermission().  If it
 271                  * does happen, forget about this class loader's URLs and
 272                  * fall back to the default behavior.
 273                  */
 274             }
 275         }
 276 
 277         if (annotation != null) {
 278             return annotation;
 279         } else {
 280             return codebaseProperty;    // REMIND: does this make sense??
 281         }
 282     }
 283 
 284     /**
 285      * Returns a classloader that loads classes from the given codebase URL
 286      * path.  The parent classloader of the returned classloader is the
 287      * context class loader.
 288      */
 289     public static ClassLoader getClassLoader(String codebase)
 290         throws MalformedURLException
 291     {
 292         ClassLoader parent = getRMIContextClassLoader();
 293 
 294         URL[] urls;
 295         if (codebase != null) {
 296             urls = pathToURLs(codebase);
 297         } else {
 298             urls = getDefaultCodebaseURLs();
 299         }
 300 
 301         /*
 302          * If there is a security manager, the current access control
 303          * context must have the "getClassLoader" RuntimePermission.
 304          */
 305         SecurityManager sm = System.getSecurityManager();
 306         if (sm != null) {
 307             sm.checkPermission(new RuntimePermission("getClassLoader"));
 308         } else {
 309             /*
 310              * But if no security manager is set, disable access to
 311              * RMI class loaders and simply return the parent loader.
 312              */
 313             return parent;
 314         }
 315 
 316         Loader loader = lookupLoader(urls, parent);
 317 
 318         /*
 319          * Verify that the caller has permission to access this loader.
 320          */
 321         if (loader != null) {
 322             loader.checkPermissions();
 323         }
 324 
 325         return loader;
 326     }
 327 
 328     /**
 329      * Return the security context of the given class loader.
 330      */
 331     public static Object getSecurityContext(ClassLoader loader) {
 332         /*
 333          * REMIND: This is a bogus JDK1.1-compatible implementation.
 334          * This method should never be called by application code anyway
 335          * (hence the deprecation), but should it do something different
 336          * and perhaps more useful, like return a String or a URL[]?
 337          */
 338         if (loader instanceof Loader) {
 339             URL[] urls = ((Loader) loader).getURLs();
 340             if (urls.length > 0) {
 341                 return urls[0];
 342             }
 343         }
 344         return null;
 345     }
 346 
 347     /**
 348      * Register a class loader as one whose classes should always be
 349      * annotated with the value of the "java.rmi.server.codebase" property.
 350      */
 351     public static void registerCodebaseLoader(ClassLoader loader) {
 352         codebaseLoaders.put(loader, null);
 353     }
 354 
 355     /**
 356      * Load a class from the RMI class loader corresponding to the given
 357      * codebase URL path in the current execution context.
 358      */
 359     private static Class<?> loadClass(URL[] urls, String name)
 360         throws ClassNotFoundException
 361     {
 362         ClassLoader parent = getRMIContextClassLoader();
 363         if (loaderLog.isLoggable(Log.VERBOSE)) {
 364             loaderLog.log(Log.VERBOSE,
 365                 "(thread context class loader: " + parent + ")");
 366         }
 367 
 368         /*
 369          * If no security manager is set, disable access to RMI class
 370          * loaders and simply delegate request to the parent loader
 371          * (see bugid 4140511).
 372          */
 373         SecurityManager sm = System.getSecurityManager();
 374         if (sm == null) {
 375             try {
 376                 Class<?> c = Class.forName(name, false, parent);
 377                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 378                     loaderLog.log(Log.VERBOSE,
 379                         "class \"" + name + "\" found via " +
 380                         "thread context class loader " +
 381                         "(no security manager: codebase disabled), " +
 382                         "defined by " + c.getClassLoader());
 383                 }
 384                 return c;
 385             } catch (ClassNotFoundException e) {
 386                 if (loaderLog.isLoggable(Log.BRIEF)) {
 387                     loaderLog.log(Log.BRIEF,
 388                         "class \"" + name + "\" not found via " +
 389                         "thread context class loader " +
 390                         "(no security manager: codebase disabled)", e);
 391                 }
 392                 throw new ClassNotFoundException(e.getMessage() +
 393                     " (no security manager: RMI class loader disabled)",
 394                     e.getException());
 395             }
 396         }
 397 
 398         /*
 399          * Get or create the RMI class loader for this codebase URL path
 400          * and parent class loader pair.
 401          */
 402         Loader loader = lookupLoader(urls, parent);
 403 
 404         try {
 405             if (loader != null) {
 406                 /*
 407                  * Verify that the caller has permission to access this loader.
 408                  */
 409                 loader.checkPermissions();
 410             }
 411         } catch (SecurityException e) {
 412             /*
 413              * If the current access control context does not have permission
 414              * to access all of the URLs in the codebase path, wrap the
 415              * resulting security exception in a ClassNotFoundException, so
 416              * the caller can handle this outcome just like any other class
 417              * loading failure (see bugid 4146529).
 418              */
 419             try {
 420                 /*
 421                  * But first, check to see if the named class could have been
 422                  * resolved without the security-offending codebase anyway;
 423                  * if so, return successfully (see bugids 4191926 & 4349670).
 424                  */
 425                 Class<?> c = Class.forName(name, false, parent);
 426                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 427                     loaderLog.log(Log.VERBOSE,
 428                         "class \"" + name + "\" found via " +
 429                         "thread context class loader " +
 430                         "(access to codebase denied), " +
 431                         "defined by " + c.getClassLoader());
 432                 }
 433                 return c;
 434             } catch (ClassNotFoundException unimportant) {
 435                 /*
 436                  * Presumably the security exception is the more important
 437                  * exception to report in this case.
 438                  */
 439                 if (loaderLog.isLoggable(Log.BRIEF)) {
 440                     loaderLog.log(Log.BRIEF,
 441                         "class \"" + name + "\" not found via " +
 442                         "thread context class loader " +
 443                         "(access to codebase denied)", e);
 444                 }
 445                 throw new ClassNotFoundException(
 446                     "access to class loader denied", e);
 447             }
 448         }
 449 
 450         try {
 451             Class<?> c = Class.forName(name, false, loader);
 452             if (loaderLog.isLoggable(Log.VERBOSE)) {
 453                 loaderLog.log(Log.VERBOSE,
 454                     "class \"" + name + "\" " + "found via codebase, " +
 455                     "defined by " + c.getClassLoader());
 456             }
 457             return c;
 458         } catch (ClassNotFoundException e) {
 459             if (loaderLog.isLoggable(Log.BRIEF)) {
 460                 loaderLog.log(Log.BRIEF,
 461                     "class \"" + name + "\" not found via codebase", e);
 462             }
 463             throw e;
 464         }
 465     }
 466 
 467     /**
 468      * Define and return a dynamic proxy class in a class loader with
 469      * URLs supplied in the given location.  The proxy class will
 470      * implement interface classes named by the given array of
 471      * interface names.
 472      */
 473     public static Class<?> loadProxyClass(String codebase, String[] interfaces,
 474                                           ClassLoader defaultLoader)
 475         throws MalformedURLException, ClassNotFoundException
 476     {
 477         if (loaderLog.isLoggable(Log.BRIEF)) {
 478             loaderLog.log(Log.BRIEF,
 479                 "interfaces = " + Arrays.asList(interfaces) + ", " +
 480                 "codebase = \"" + (codebase != null ? codebase : "") + "\"" +
 481                 (defaultLoader != null ?
 482                  ", defaultLoader = " + defaultLoader : ""));
 483         }
 484 
 485         /*
 486          * This method uses a fairly complex algorithm to load the
 487          * proxy class and its interface classes in order to maximize
 488          * the likelihood that the proxy's codebase annotation will be
 489          * preserved.  The algorithm is (assuming that all of the
 490          * proxy interface classes are public):
 491          *
 492          * If the default loader is not null, try to load the proxy
 493          * interfaces through that loader. If the interfaces can be
 494          * loaded in that loader, try to define the proxy class in an
 495          * RMI class loader (child of the context class loader) before
 496          * trying to define the proxy in the default loader.  If the
 497          * attempt to define the proxy class succeeds, the codebase
 498          * annotation is preserved.  If the attempt fails, try to
 499          * define the proxy class in the default loader.
 500          *
 501          * If the interface classes can not be loaded from the default
 502          * loader or the default loader is null, try to load them from
 503          * the RMI class loader.  Then try to define the proxy class
 504          * in the RMI class loader.
 505          *
 506          * Additionally, if any of the proxy interface classes are not
 507          * public, all of the non-public interfaces must reside in the
 508          * same class loader or it will be impossible to define the
 509          * proxy class (an IllegalAccessError will be thrown).  An
 510          * attempt to load the interfaces from the default loader is
 511          * made.  If the attempt fails, a second attempt will be made
 512          * to load the interfaces from the RMI loader. If all of the
 513          * non-public interfaces classes do reside in the same class
 514          * loader, then we attempt to define the proxy class in the
 515          * class loader of the non-public interfaces.  No other
 516          * attempt to define the proxy class will be made.
 517          */
 518         ClassLoader parent = getRMIContextClassLoader();
 519         if (loaderLog.isLoggable(Log.VERBOSE)) {
 520             loaderLog.log(Log.VERBOSE,
 521                 "(thread context class loader: " + parent + ")");
 522         }
 523 
 524         URL[] urls;
 525         if (codebase != null) {
 526             urls = pathToURLs(codebase);
 527         } else {
 528             urls = getDefaultCodebaseURLs();
 529         }
 530 
 531         /*
 532          * If no security manager is set, disable access to RMI class
 533          * loaders and use the would-de parent instead.
 534          */
 535         SecurityManager sm = System.getSecurityManager();
 536         if (sm == null) {
 537             try {
 538                 Class<?> c = loadProxyClass(interfaces, defaultLoader, parent,
 539                                          false);
 540                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 541                     loaderLog.log(Log.VERBOSE,
 542                         "(no security manager: codebase disabled) " +
 543                         "proxy class defined by " + c.getClassLoader());
 544                 }
 545                 return c;
 546             } catch (ClassNotFoundException e) {
 547                 if (loaderLog.isLoggable(Log.BRIEF)) {
 548                     loaderLog.log(Log.BRIEF,
 549                         "(no security manager: codebase disabled) " +
 550                         "proxy class resolution failed", e);
 551                 }
 552                 throw new ClassNotFoundException(e.getMessage() +
 553                     " (no security manager: RMI class loader disabled)",
 554                     e.getException());
 555             }
 556         }
 557 
 558         /*
 559          * Get or create the RMI class loader for this codebase URL path
 560          * and parent class loader pair.
 561          */
 562         Loader loader = lookupLoader(urls, parent);
 563 
 564         try {
 565             if (loader != null) {
 566                 /*
 567                  * Verify that the caller has permission to access this loader.
 568                  */
 569                 loader.checkPermissions();
 570             }
 571         } catch (SecurityException e) {
 572             /*
 573              * If the current access control context does not have permission
 574              * to access all of the URLs in the codebase path, wrap the
 575              * resulting security exception in a ClassNotFoundException, so
 576              * the caller can handle this outcome just like any other class
 577              * loading failure (see bugid 4146529).
 578              */
 579             try {
 580                 /*
 581                  * But first, check to see if the proxy class could have been
 582                  * resolved without the security-offending codebase anyway;
 583                  * if so, return successfully (see bugids 4191926 & 4349670).
 584                  */
 585                 Class<?> c = loadProxyClass(interfaces, defaultLoader, parent,
 586                                             false);
 587                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 588                     loaderLog.log(Log.VERBOSE,
 589                         "(access to codebase denied) " +
 590                         "proxy class defined by " + c.getClassLoader());
 591                 }
 592                 return c;
 593             } catch (ClassNotFoundException unimportant) {
 594                 /*
 595                  * Presumably the security exception is the more important
 596                  * exception to report in this case.
 597                  */
 598                 if (loaderLog.isLoggable(Log.BRIEF)) {
 599                     loaderLog.log(Log.BRIEF,
 600                         "(access to codebase denied) " +
 601                         "proxy class resolution failed", e);
 602                 }
 603                 throw new ClassNotFoundException(
 604                     "access to class loader denied", e);
 605             }
 606         }
 607 
 608         try {
 609             Class<?> c = loadProxyClass(interfaces, defaultLoader, loader, true);
 610             if (loaderLog.isLoggable(Log.VERBOSE)) {
 611                 loaderLog.log(Log.VERBOSE,
 612                               "proxy class defined by " + c.getClassLoader());
 613             }
 614             return c;
 615         } catch (ClassNotFoundException e) {
 616             if (loaderLog.isLoggable(Log.BRIEF)) {
 617                 loaderLog.log(Log.BRIEF,
 618                               "proxy class resolution failed", e);
 619             }
 620             throw e;
 621         }
 622     }
 623 
 624     /**
 625      * Define a proxy class in the default loader if appropriate.
 626      * Define the class in an RMI class loader otherwise.  The proxy
 627      * class will implement classes which are named in the supplied
 628      * interfaceNames.
 629      */
 630     private static Class<?> loadProxyClass(String[] interfaceNames,
 631                                            ClassLoader defaultLoader,
 632                                            ClassLoader codebaseLoader,
 633                                            boolean preferCodebase)
 634         throws ClassNotFoundException
 635     {
 636         ClassLoader proxyLoader = null;
 637         Class<?>[] classObjs = new Class<?>[interfaceNames.length];
 638         boolean[] nonpublic = { false };
 639 
 640       defaultLoaderCase:
 641         if (defaultLoader != null) {
 642             try {
 643                 proxyLoader =
 644                     loadProxyInterfaces(interfaceNames, defaultLoader,
 645                                         classObjs, nonpublic);
 646                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 647                     ClassLoader[] definingLoaders =
 648                         new ClassLoader[classObjs.length];
 649                     for (int i = 0; i < definingLoaders.length; i++) {
 650                         definingLoaders[i] = classObjs[i].getClassLoader();
 651                     }
 652                     loaderLog.log(Log.VERBOSE,
 653                         "proxy interfaces found via defaultLoader, " +
 654                         "defined by " + Arrays.asList(definingLoaders));
 655                 }
 656             } catch (ClassNotFoundException e) {
 657                 break defaultLoaderCase;
 658             }
 659             if (!nonpublic[0]) {
 660                 if (preferCodebase) {
 661                     try {
 662                         return Proxy.getProxyClass(codebaseLoader, classObjs);
 663                     } catch (IllegalArgumentException e) {
 664                     }
 665                 }
 666                 proxyLoader = defaultLoader;
 667             }
 668             return loadProxyClass(proxyLoader, classObjs);
 669         }
 670 
 671         nonpublic[0] = false;
 672         proxyLoader = loadProxyInterfaces(interfaceNames, codebaseLoader,
 673                                           classObjs, nonpublic);
 674         if (loaderLog.isLoggable(Log.VERBOSE)) {
 675             ClassLoader[] definingLoaders = new ClassLoader[classObjs.length];
 676             for (int i = 0; i < definingLoaders.length; i++) {
 677                 definingLoaders[i] = classObjs[i].getClassLoader();
 678             }
 679             loaderLog.log(Log.VERBOSE,
 680                 "proxy interfaces found via codebase, " +
 681                 "defined by " + Arrays.asList(definingLoaders));
 682         }
 683         if (!nonpublic[0]) {
 684             proxyLoader = codebaseLoader;
 685         }
 686         return loadProxyClass(proxyLoader, classObjs);
 687     }
 688 
 689     /**
 690      * Define a proxy class in the given class loader.  The proxy
 691      * class will implement the given interfaces Classes.
 692      */
 693     private static Class<?> loadProxyClass(ClassLoader loader, Class[] interfaces)
 694         throws ClassNotFoundException
 695     {
 696         try {
 697             return Proxy.getProxyClass(loader, interfaces);
 698         } catch (IllegalArgumentException e) {
 699             throw new ClassNotFoundException(
 700                 "error creating dynamic proxy class", e);
 701         }
 702     }
 703 
 704     /*
 705      * Load Class objects for the names in the interfaces array fron
 706      * the given class loader.
 707      *
 708      * We pass classObjs and nonpublic arrays to avoid needing a
 709      * multi-element return value.  nonpublic is an array to enable
 710      * the method to take a boolean argument by reference.
 711      *
 712      * nonpublic array is needed to signal when the return value of
 713      * this method should be used as the proxy class loader.  Because
 714      * null represents a valid class loader, that value is
 715      * insufficient to signal that the return value should not be used
 716      * as the proxy class loader.
 717      */
 718     private static ClassLoader loadProxyInterfaces(String[] interfaces,
 719                                                    ClassLoader loader,
 720                                                    Class[] classObjs,
 721                                                    boolean[] nonpublic)
 722         throws ClassNotFoundException
 723     {
 724         /* loader of a non-public interface class */
 725         ClassLoader nonpublicLoader = null;
 726 
 727         for (int i = 0; i < interfaces.length; i++) {
 728             Class<?> cl =
 729                 (classObjs[i] = Class.forName(interfaces[i], false, loader));
 730 
 731             if (!Modifier.isPublic(cl.getModifiers())) {
 732                 ClassLoader current = cl.getClassLoader();
 733                 if (loaderLog.isLoggable(Log.VERBOSE)) {
 734                     loaderLog.log(Log.VERBOSE,
 735                         "non-public interface \"" + interfaces[i] +
 736                         "\" defined by " + current);
 737                 }
 738                 if (!nonpublic[0]) {
 739                     nonpublicLoader = current;
 740                     nonpublic[0] = true;
 741                 } else if (current != nonpublicLoader) {
 742                     throw new IllegalAccessError(
 743                         "non-public interfaces defined in different " +
 744                         "class loaders");
 745                 }
 746             }
 747         }
 748         return nonpublicLoader;
 749     }
 750 
 751     /**
 752      * Convert a string containing a space-separated list of URLs into a
 753      * corresponding array of URL objects, throwing a MalformedURLException
 754      * if any of the URLs are invalid.
 755      */
 756     private static URL[] pathToURLs(String path)
 757         throws MalformedURLException
 758     {
 759         synchronized (pathToURLsCache) {
 760             Object[] v = pathToURLsCache.get(path);
 761             if (v != null) {
 762                 return ((URL[])v[0]);
 763             }
 764         }
 765         StringTokenizer st = new StringTokenizer(path); // divide by spaces
 766         URL[] urls = new URL[st.countTokens()];
 767         for (int i = 0; st.hasMoreTokens(); i++) {
 768             urls[i] = new URL(st.nextToken());
 769         }
 770         synchronized (pathToURLsCache) {
 771             pathToURLsCache.put(path,
 772                                 new Object[] {urls, new SoftReference<String>(path)});
 773         }
 774         return urls;
 775     }
 776 
 777     /** map from weak(key=string) to [URL[], soft(key)] */
 778     private static final Map<String, Object[]> pathToURLsCache
 779         = new WeakHashMap<>(5);
 780 
 781     /**
 782      * Convert an array of URL objects into a corresponding string
 783      * containing a space-separated list of URLs.
 784      *
 785      * Note that if the array has zero elements, the return value is
 786      * null, not the empty string.
 787      */
 788     private static String urlsToPath(URL[] urls) {
 789         if (urls.length == 0) {
 790             return null;
 791         } else if (urls.length == 1) {
 792             return urls[0].toExternalForm();
 793         } else {
 794             StringBuffer path = new StringBuffer(urls[0].toExternalForm());
 795             for (int i = 1; i < urls.length; i++) {
 796                 path.append(' ');
 797                 path.append(urls[i].toExternalForm());
 798             }
 799             return path.toString();
 800         }
 801     }
 802 
 803     /**
 804      * Return the class loader to be used as the parent for an RMI class
 805      * loader used in the current execution context.
 806      */
 807     private static ClassLoader getRMIContextClassLoader() {
 808         /*
 809          * The current implementation simply uses the current thread's
 810          * context class loader.
 811          */
 812         return Thread.currentThread().getContextClassLoader();
 813     }
 814 
 815     /**
 816      * Look up the RMI class loader for the given codebase URL path
 817      * and the given parent class loader.  A new class loader instance
 818      * will be created and returned if no match is found.
 819      */
 820     private static Loader lookupLoader(final URL[] urls,
 821                                        final ClassLoader parent)
 822     {
 823         /*
 824          * If the requested codebase URL path is empty, the supplied
 825          * parent class loader will be sufficient.
 826          *
 827          * REMIND: To be conservative, this optimization is commented out
 828          * for now so that it does not open a security hole in the future
 829          * by providing untrusted code with direct access to the public
 830          * loadClass() method of a class loader instance that it cannot
 831          * get a reference to.  (It's an unlikely optimization anyway.)
 832          *
 833          * if (urls.length == 0) {
 834          *     return parent;
 835          * }
 836          */
 837 
 838         LoaderEntry entry;
 839         Loader loader;
 840 
 841         synchronized (LoaderHandler.class) {
 842             /*
 843              * Take this opportunity to remove from the table entries
 844              * whose weak references have been cleared.
 845              */
 846             while ((entry = (LoaderEntry) refQueue.poll()) != null) {
 847                 if (!entry.removed) {   // ignore entries removed below
 848                     loaderTable.remove(entry.key);
 849                 }
 850             }
 851 
 852             /*
 853              * Look up the codebase URL path and parent class loader pair
 854              * in the table of RMI class loaders.
 855              */
 856             LoaderKey key = new LoaderKey(urls, parent);
 857             entry = loaderTable.get(key);
 858 
 859             if (entry == null || (loader = entry.get()) == null) {
 860                 /*
 861                  * If entry was in table but it's weak reference was cleared,
 862                  * remove it from the table and mark it as explicitly cleared,
 863                  * so that new matching entry that we put in the table will
 864                  * not be erroneously removed when this entry is processed
 865                  * from the weak reference queue.
 866                  */
 867                 if (entry != null) {
 868                     loaderTable.remove(key);
 869                     entry.removed = true;
 870                 }
 871 
 872                 /*
 873                  * A matching loader was not found, so create a new class
 874                  * loader instance for the requested codebase URL path and
 875                  * parent class loader.  The instance is created within an
 876                  * access control context retricted to the permissions
 877                  * necessary to load classes from its codebase URL path.
 878                  */
 879                 AccessControlContext acc = getLoaderAccessControlContext(urls);
 880                 loader = java.security.AccessController.doPrivileged(
 881                     new java.security.PrivilegedAction<Loader>() {
 882                         public Loader run() {
 883                             return new Loader(urls, parent);
 884                         }
 885                     }, acc);
 886 
 887                 /*
 888                  * Finally, create an entry to hold the new loader with a
 889                  * weak reference and store it in the table with the key.
 890                  */
 891                 entry = new LoaderEntry(key, loader);
 892                 loaderTable.put(key, entry);
 893             }
 894         }
 895 
 896         return loader;
 897     }
 898 
 899     /**
 900      * LoaderKey holds a codebase URL path and parent class loader pair
 901      * used to look up RMI class loader instances in its class loader cache.
 902      */
 903     private static class LoaderKey {
 904 
 905         private URL[] urls;
 906 
 907         private ClassLoader parent;
 908 
 909         private int hashValue;
 910 
 911         public LoaderKey(URL[] urls, ClassLoader parent) {
 912             this.urls = urls;
 913             this.parent = parent;
 914 
 915             if (parent != null) {
 916                 hashValue = parent.hashCode();
 917             }
 918             for (int i = 0; i < urls.length; i++) {
 919                 hashValue ^= urls[i].hashCode();
 920             }
 921         }
 922 
 923         public int hashCode() {
 924             return hashValue;
 925         }
 926 
 927         public boolean equals(Object obj) {
 928             if (obj instanceof LoaderKey) {
 929                 LoaderKey other = (LoaderKey) obj;
 930                 if (parent != other.parent) {
 931                     return false;
 932                 }
 933                 if (urls == other.urls) {
 934                     return true;
 935                 }
 936                 if (urls.length != other.urls.length) {
 937                     return false;
 938                 }
 939                 for (int i = 0; i < urls.length; i++) {
 940                     if (!urls[i].equals(other.urls[i])) {
 941                         return false;
 942                     }
 943                 }
 944                 return true;
 945             } else {
 946                 return false;
 947             }
 948         }
 949     }
 950 
 951     /**
 952      * LoaderEntry contains a weak reference to an RMIClassLoader.  The
 953      * weak reference is registered with the private static "refQueue"
 954      * queue.  The entry contains the codebase URL path and parent class
 955      * loader key for the loader so that the mapping can be removed from
 956      * the table efficiently when the weak reference is cleared.
 957      */
 958     private static class LoaderEntry extends WeakReference<Loader> {
 959 
 960         public LoaderKey key;
 961 
 962         /**
 963          * set to true if the entry has been removed from the table
 964          * because it has been replaced, so it should not be attempted
 965          * to be removed again
 966          */
 967         public boolean removed = false;
 968 
 969         public LoaderEntry(LoaderKey key, Loader loader) {
 970             super(loader, refQueue);
 971             this.key = key;
 972         }
 973     }
 974 
 975     /**
 976      * Return the access control context that a loader for the given
 977      * codebase URL path should execute with.
 978      */
 979     private static AccessControlContext getLoaderAccessControlContext(
 980         URL[] urls)
 981     {
 982         /*
 983          * The approach used here is taken from the similar method
 984          * getAccessControlContext() in the sun.applet.AppletPanel class.
 985          */
 986         // begin with permissions granted to all code in current policy
 987         PermissionCollection perms =
 988             java.security.AccessController.doPrivileged(
 989                 new java.security.PrivilegedAction<PermissionCollection>() {
 990                 public PermissionCollection run() {
 991                     CodeSource codesource = new CodeSource(null,
 992                         (java.security.cert.Certificate[]) null);
 993                     Policy p = java.security.Policy.getPolicy();
 994                     if (p != null) {
 995                         return p.getPermissions(codesource);
 996                     } else {
 997                         return new Permissions();
 998                     }
 999                 }
1000             });
1001 
1002         // createClassLoader permission needed to create loader in context
1003         perms.add(new RuntimePermission("createClassLoader"));
1004 
1005         // add permissions to read any "java.*" property
1006         perms.add(new java.util.PropertyPermission("java.*","read"));
1007 
1008         // add permissions reuiqred to load from codebase URL path
1009         addPermissionsForURLs(urls, perms, true);
1010 
1011         /*
1012          * Create an AccessControlContext that consists of a single
1013          * protection domain with only the permissions calculated above.
1014          */
1015         ProtectionDomain pd = new ProtectionDomain(
1016             new CodeSource((urls.length > 0 ? urls[0] : null),
1017                 (java.security.cert.Certificate[]) null),
1018             perms);
1019         return new AccessControlContext(new ProtectionDomain[] { pd });
1020     }
1021 
1022     /**
1023      * Adds to the specified permission collection the permissions
1024      * necessary to load classes from a loader with the specified URL
1025      * path; if "forLoader" is true, also adds URL-specific
1026      * permissions necessary for the security context that such a
1027      * loader operates within, such as permissions necessary for
1028      * granting automatic permissions to classes defined by the
1029      * loader.  A given permission is only added to the collection if
1030      * it is not already implied by the collection.
1031      */
1032     private static void addPermissionsForURLs(URL[] urls,
1033                                              PermissionCollection perms,
1034                                              boolean forLoader)
1035     {
1036         for (int i = 0; i < urls.length; i++) {
1037             URL url = urls[i];
1038             try {
1039                 URLConnection urlConnection = url.openConnection();
1040                 Permission p = urlConnection.getPermission();
1041                 if (p != null) {
1042                     if (p instanceof FilePermission) {
1043                         /*
1044                          * If the codebase is a file, the permission required
1045                          * to actually read classes from the codebase URL is
1046                          * the permission to read all files beneath the last
1047                          * directory in the file path, either because JAR
1048                          * files can refer to other JAR files in the same
1049                          * directory, or because permission to read a
1050                          * directory is not implied by permission to read the
1051                          * contents of a directory, which all that might be
1052                          * granted.
1053                          */
1054                         String path = p.getName();
1055                         int endIndex = path.lastIndexOf(File.separatorChar);
1056                         if (endIndex != -1) {
1057                             path = path.substring(0, endIndex+1);
1058                             if (path.endsWith(File.separator)) {
1059                                 path += "-";
1060                             }
1061                             Permission p2 = new FilePermission(path, "read");
1062                             if (!perms.implies(p2)) {
1063                                 perms.add(p2);
1064                             }
1065                             perms.add(new FilePermission(path, "read"));
1066                         } else {
1067                             /*
1068                              * No directory separator: use permission to
1069                              * read the file.
1070                              */
1071                             if (!perms.implies(p)) {
1072                                 perms.add(p);
1073                             }
1074                         }
1075                     } else {
1076                         if (!perms.implies(p)) {
1077                             perms.add(p);
1078                         }
1079 
1080                         /*
1081                          * If the purpose of these permissions is to grant
1082                          * them to an instance of a URLClassLoader subclass,
1083                          * we must add permission to connect to and accept
1084                          * from the host of non-"file:" URLs, otherwise the
1085                          * getPermissions() method of URLClassLoader will
1086                          * throw a security exception.
1087                          */
1088                         if (forLoader) {
1089                             // get URL with meaningful host component
1090                             URL hostURL = url;
1091                             for (URLConnection conn = urlConnection;
1092                                  conn instanceof JarURLConnection;)
1093                             {
1094                                 hostURL =
1095                                     ((JarURLConnection) conn).getJarFileURL();
1096                                 conn = hostURL.openConnection();
1097                             }
1098                             String host = hostURL.getHost();
1099                             if (host != null &&
1100                                 p.implies(new SocketPermission(host,
1101                                                                "resolve")))
1102                             {
1103                                 Permission p2 =
1104                                     new SocketPermission(host,
1105                                                          "connect,accept");
1106                                 if (!perms.implies(p2)) {
1107                                     perms.add(p2);
1108                                 }
1109                             }
1110                         }
1111                     }
1112                 }
1113             } catch (IOException e) {
1114                 /*
1115                  * This shouldn't happen, although it is declared to be
1116                  * thrown by openConnection() and getPermission().  If it
1117                  * does, don't bother granting or requiring any permissions
1118                  * for this URL.
1119                  */
1120             }
1121         }
1122     }
1123 
1124     /**
1125      * Loader is the actual class of the RMI class loaders created
1126      * by the RMIClassLoader static methods.
1127      */
1128     private static class Loader extends URLClassLoader {
1129 
1130         /** parent class loader, kept here as an optimization */
1131         private ClassLoader parent;
1132 
1133         /** string form of loader's codebase URL path, also an optimization */
1134         private String annotation;
1135 
1136         /** permissions required to access loader through public API */
1137         private Permissions permissions;
1138 
1139         private Loader(URL[] urls, ClassLoader parent) {
1140             super(urls, parent);
1141             this.parent = parent;
1142 
1143             /*
1144              * Precompute the permissions required to access the loader.
1145              */
1146             permissions = new Permissions();
1147             addPermissionsForURLs(urls, permissions, false);
1148 
1149             /*
1150              * Caching the value of class annotation string here assumes
1151              * that the protected method addURL() is never called on this
1152              * class loader.
1153              */
1154             annotation = urlsToPath(urls);
1155         }
1156 
1157         /**
1158          * Return the string to be annotated with all classes loaded from
1159          * this class loader.
1160          */
1161         public String getClassAnnotation() {
1162             return annotation;
1163         }
1164 
1165         /**
1166          * Check that the current access control context has all of the
1167          * permissions necessary to load classes from this loader.
1168          */
1169         private void checkPermissions() {
1170             SecurityManager sm = System.getSecurityManager();
1171             if (sm != null) {           // should never be null?
1172                 Enumeration<Permission> enum_ = permissions.elements();
1173                 while (enum_.hasMoreElements()) {
1174                     sm.checkPermission(enum_.nextElement());
1175                 }
1176             }
1177         }
1178 
1179         /**
1180          * Return the permissions to be granted to code loaded from the
1181          * given code source.
1182          */
1183         protected PermissionCollection getPermissions(CodeSource codesource) {
1184             PermissionCollection perms = super.getPermissions(codesource);
1185             /*
1186              * Grant the same permissions that URLClassLoader would grant.
1187              */
1188             return perms;
1189         }
1190 
1191         /**
1192          * Return a string representation of this loader (useful for
1193          * debugging).
1194          */
1195         public String toString() {
1196             return super.toString() + "[\"" + annotation + "\"]";
1197         }
1198     }
1199 }