1 /*
   2  * Copyright (c) 1998, 2010, 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.io.File;
  29 import java.io.IOException;
  30 import java.io.FilePermission;
  31 import java.net.URL;
  32 import java.net.URLClassLoader;
  33 import java.net.MalformedURLException;
  34 import java.net.URLStreamHandler;
  35 import java.net.URLStreamHandlerFactory;
  36 import java.util.HashSet;
  37 import java.util.StringTokenizer;
  38 import java.util.Set;
  39 import java.util.Vector;
  40 import java.security.AccessController;
  41 import java.security.AllPermission;
  42 import java.security.PrivilegedAction;
  43 import java.security.PrivilegedExceptionAction;
  44 import java.security.AccessControlContext;
  45 import java.security.PermissionCollection;
  46 import java.security.Permissions;
  47 import java.security.Permission;
  48 import java.security.ProtectionDomain;
  49 import java.security.CodeSource;
  50 import sun.security.util.SecurityConstants;
  51 import sun.net.www.ParseUtil;
  52 
  53 /**
  54  * This class is used by the system to launch the main application.
  55 Launcher */
  56 public class Launcher {
  57     private static URLStreamHandlerFactory factory = new Factory();
  58     private static Launcher launcher = new Launcher();
  59     private static String bootClassPath =
  60         System.getProperty("sun.boot.class.path");
  61 
  62     public static Launcher getLauncher() {
  63         return launcher;
  64     }
  65 
  66     private ClassLoader loader;
  67 
  68     public Launcher() {
  69         // Create the extension class loader
  70         ClassLoader extcl;
  71         try {
  72             extcl = ExtClassLoader.getExtClassLoader();
  73         } catch (IOException e) {
  74             throw new InternalError(
  75                 "Could not create extension class loader");
  76         }
  77 
  78         // Now create the class loader to use to launch the application
  79         try {
  80             loader = AppClassLoader.getAppClassLoader(extcl);
  81         } catch (IOException e) {
  82             throw new InternalError(
  83                 "Could not create application class loader");
  84         }
  85 
  86         // Also set the context class loader for the primordial thread.
  87         Thread.currentThread().setContextClassLoader(loader);
  88 
  89         // Finally, install a security manager if requested
  90         String s = System.getProperty("java.security.manager");
  91         if (s != null) {
  92             SecurityManager sm = null;
  93             if ("".equals(s) || "default".equals(s)) {
  94                 sm = new java.lang.SecurityManager();
  95             } else {
  96                 try {
  97                     sm = (SecurityManager)loader.loadClass(s).newInstance();
  98                 } catch (IllegalAccessException e) {
  99                 } catch (InstantiationException e) {
 100                 } catch (ClassNotFoundException e) {
 101                 } catch (ClassCastException e) {
 102                 }
 103             }
 104             if (sm != null) {
 105                 System.setSecurityManager(sm);
 106             } else {
 107                 throw new InternalError(
 108                     "Could not create SecurityManager: " + s);
 109             }
 110         }
 111     }
 112 
 113     /*
 114      * Returns the class loader used to launch the main application.
 115      */
 116     public ClassLoader getClassLoader() {
 117         return loader;
 118     }
 119 
 120     public static void addURLToAppClassLoader(URL u) {
 121         AccessController.checkPermission(new AllPermission());
 122         ClassLoader loader = Launcher.getLauncher().getClassLoader();
 123         ((Launcher.AppClassLoader) loader).addAppURL(u);
 124     }
 125 
 126     public static void addURLToExtClassLoader(URL u) {
 127         AccessController.checkPermission(new AllPermission());
 128         ClassLoader loader = Launcher.getLauncher().getClassLoader();
 129         ((Launcher.ExtClassLoader) loader.getParent()).addExtURL(u);
 130     }
 131 
 132     /*
 133      * The class loader used for loading installed extensions.
 134      */
 135     static class ExtClassLoader extends URLClassLoader {
 136 
 137         static {
 138             ClassLoader.registerAsParallelCapable();
 139         }
 140 
 141         /**
 142          * create an ExtClassLoader. The ExtClassLoader is created
 143          * within a context that limits which files it can read
 144          */
 145         public static ExtClassLoader getExtClassLoader() throws IOException
 146         {
 147             final File[] dirs = getExtDirs();
 148 
 149             try {
 150                 // Prior implementations of this doPrivileged() block supplied
 151                 // aa synthesized ACC via a call to the private method
 152                 // ExtClassLoader.getContext().
 153 
 154                 return AccessController.doPrivileged(
 155                     new PrivilegedExceptionAction<ExtClassLoader>() {
 156                         public ExtClassLoader run() throws IOException {
 157                             int len = dirs.length;
 158                             for (int i = 0; i < len; i++) {
 159                                 MetaIndex.registerDirectory(dirs[i]);
 160                             }
 161                             return new ExtClassLoader(dirs);
 162                         }
 163                     });
 164             } catch (java.security.PrivilegedActionException e) {
 165                 throw (IOException) e.getException();
 166             }
 167         }
 168 
 169         void addExtURL(URL url) {
 170             super.addURL(url);
 171         }
 172 
 173         /*
 174          * Creates a new ExtClassLoader for the specified directories.
 175          */
 176         public ExtClassLoader(File[] dirs) throws IOException {
 177             super(getExtURLs(dirs), null, factory);
 178         }
 179 
 180         private static File[] getExtDirs() {
 181             String s = System.getProperty("java.ext.dirs");
 182             File[] dirs;
 183             if (s != null) {
 184                 StringTokenizer st =
 185                     new StringTokenizer(s, File.pathSeparator);
 186                 int count = st.countTokens();
 187                 dirs = new File[count];
 188                 for (int i = 0; i < count; i++) {
 189                     dirs[i] = new File(st.nextToken());
 190                 }
 191             } else {
 192                 dirs = new File[0];
 193             }
 194             return dirs;
 195         }
 196 
 197         private static URL[] getExtURLs(File[] dirs) throws IOException {
 198             Vector<URL> urls = new Vector<URL>();
 199             for (int i = 0; i < dirs.length; i++) {
 200                 String[] files = dirs[i].list();
 201                 if (files != null) {
 202                     for (int j = 0; j < files.length; j++) {
 203                         if (!files[j].equals("meta-index")) {
 204                             File f = new File(dirs[i], files[j]);
 205                             urls.add(getFileURL(f));
 206                         }
 207                     }
 208                 }
 209             }
 210             URL[] ua = new URL[urls.size()];
 211             urls.copyInto(ua);
 212             return ua;
 213         }
 214 
 215         /*
 216          * Searches the installed extension directories for the specified
 217          * library name. For each extension directory, we first look for
 218          * the native library in the subdirectory whose name is the value
 219          * of the system property <code>os.arch</code>. Failing that, we
 220          * look in the extension directory itself.
 221          */
 222         public String findLibrary(String name) {
 223             name = System.mapLibraryName(name);
 224             URL[] urls = super.getURLs();
 225             File prevDir = null;
 226             for (int i = 0; i < urls.length; i++) {
 227                 // Get the ext directory from the URL
 228                 File dir = new File(urls[i].getPath()).getParentFile();
 229                 if (dir != null && !dir.equals(prevDir)) {
 230                     // Look in architecture-specific subdirectory first
 231                     // Read from the saved system properties to avoid deadlock
 232                     String arch = VM.getSavedProperty("os.arch");
 233                     if (arch != null) {
 234                         File file = new File(new File(dir, arch), name);
 235                         if (file.exists()) {
 236                             return file.getAbsolutePath();
 237                         }
 238                     }
 239                     // Then check the extension directory
 240                     File file = new File(dir, name);
 241                     if (file.exists()) {
 242                         return file.getAbsolutePath();
 243                     }
 244                 }
 245                 prevDir = dir;
 246             }
 247             return null;
 248         }
 249 
 250         protected Class findClass(String name) throws ClassNotFoundException {
 251             BootClassLoaderHook.preLoadClass(name);
 252             return super.findClass(name);
 253         }
 254 
 255         private static AccessControlContext getContext(File[] dirs)
 256             throws IOException
 257         {
 258             PathPermissions perms =
 259                 new PathPermissions(dirs);
 260 
 261             ProtectionDomain domain = new ProtectionDomain(
 262                 new CodeSource(perms.getCodeBase(),
 263                     (java.security.cert.Certificate[]) null),
 264                 perms);
 265 
 266             AccessControlContext acc =
 267                 new AccessControlContext(new ProtectionDomain[] { domain });
 268 
 269             return acc;
 270         }
 271     }
 272 
 273     /**
 274      * The class loader used for loading from java.class.path.
 275      * runs in a restricted security context.
 276      */
 277     static class AppClassLoader extends URLClassLoader {
 278 
 279         static {
 280             ClassLoader.registerAsParallelCapable();
 281         }
 282 
 283         public static ClassLoader getAppClassLoader(final ClassLoader extcl)
 284             throws IOException
 285         {
 286             final String s = System.getProperty("java.class.path");
 287             final File[] path = (s == null) ? new File[0] : getClassPath(s);
 288 
 289             // Note: on bugid 4256530
 290             // Prior implementations of this doPrivileged() block supplied
 291             // a rather restrictive ACC via a call to the private method
 292             // AppClassLoader.getContext(). This proved overly restrictive
 293             // when loading  classes. Specifically it prevent
 294             // accessClassInPackage.sun.* grants from being honored.
 295             //
 296             return AccessController.doPrivileged(
 297                 new PrivilegedAction<AppClassLoader>() {
 298                     public AppClassLoader run() {
 299                     URL[] urls =
 300                         (s == null) ? new URL[0] : pathToURLs(path);
 301                     return new AppClassLoader(urls, extcl);
 302                 }
 303             });
 304         }
 305 
 306         /*
 307          * Creates a new AppClassLoader
 308          */
 309         AppClassLoader(URL[] urls, ClassLoader parent) {
 310             super(urls, parent, factory);
 311         }
 312 
 313         /**
 314          * Override loadClass so we can checkPackageAccess.
 315          */
 316         public Class loadClass(String name, boolean resolve)
 317             throws ClassNotFoundException
 318         {
 319             BootClassLoaderHook.preLoadClass(name);
 320             int i = name.lastIndexOf('.');
 321             if (i != -1) {
 322                 SecurityManager sm = System.getSecurityManager();
 323                 if (sm != null) {
 324                     sm.checkPackageAccess(name.substring(0, i));
 325                 }
 326             }
 327             return (super.loadClass(name, resolve));
 328         }
 329 
 330         /**
 331          * allow any classes loaded from classpath to exit the VM.
 332          */
 333         protected PermissionCollection getPermissions(CodeSource codesource)
 334         {
 335             PermissionCollection perms = super.getPermissions(codesource);
 336             perms.add(new RuntimePermission("exitVM"));
 337             return perms;
 338         }
 339 
 340         /**
 341          * This class loader supports dynamic additions to the class path
 342          * at runtime.
 343          *
 344          * @see java.lang.instrument.Instrumentation#appendToSystemClassPathSearch
 345          */
 346         private void appendToClassPathForInstrumentation(String path) {
 347             assert(Thread.holdsLock(this));
 348 
 349             // addURL is a no-op if path already contains the URL
 350             super.addURL( getFileURL(new File(path)) );
 351         }
 352 
 353         /**
 354          * create a context that can read any directories (recursively)
 355          * mentioned in the class path. In the case of a jar, it has to
 356          * be the directory containing the jar, not just the jar, as jar
 357          * files might refer to other jar files.
 358          */
 359 
 360         private static AccessControlContext getContext(File[] cp)
 361             throws java.net.MalformedURLException
 362         {
 363             PathPermissions perms =
 364                 new PathPermissions(cp);
 365 
 366             ProtectionDomain domain =
 367                 new ProtectionDomain(new CodeSource(perms.getCodeBase(),
 368                     (java.security.cert.Certificate[]) null),
 369                 perms);
 370 
 371             AccessControlContext acc =
 372                 new AccessControlContext(new ProtectionDomain[] { domain });
 373 
 374             return acc;
 375         }
 376 
 377         void addAppURL(URL url) {
 378             super.addURL(url);
 379         }
 380     }
 381 
 382     private static class BootClassPathHolder {
 383         static final URLClassPath bcp;
 384         static {
 385             URL[] urls;
 386             if (bootClassPath != null) {
 387                 urls = AccessController.doPrivileged(
 388                     new PrivilegedAction<URL[]>() {
 389                         public URL[] run() {
 390                             File[] classPath = getClassPath(bootClassPath);
 391                             int len = classPath.length;
 392                             Set<File> seenDirs = new HashSet<File>();
 393                             for (int i = 0; i < len; i++) {
 394                                 File curEntry = classPath[i];
 395                                 // Negative test used to properly handle
 396                                 // nonexistent jars on boot class path
 397                                 if (!curEntry.isDirectory()) {
 398                                     curEntry = curEntry.getParentFile();
 399                                 }
 400                                 if (curEntry != null && seenDirs.add(curEntry)) {
 401                                     MetaIndex.registerDirectory(curEntry);
 402                                 }
 403                             }
 404                             return pathToURLs(classPath);
 405                         }
 406                     }
 407                 );
 408             } else {
 409                 urls = new URL[0];
 410             }
 411             bcp = new URLClassPath(urls, factory);
 412         }
 413     }
 414 
 415     public static URLClassPath getBootstrapClassPath() {
 416         URLClassPath bcp = BootClassPathHolder.bcp;
 417         // if DownloadManager is installed, return the bootstrap class path
 418         // maintained by the Java kernel
 419         BootClassLoaderHook hook = BootClassLoaderHook.getHook();
 420         return hook == null ? bcp : hook.getBootstrapClassPath(bcp, factory);
 421     }
 422 
 423     private static URL[] pathToURLs(File[] path) {
 424         URL[] urls = new URL[path.length];
 425         for (int i = 0; i < path.length; i++) {
 426             urls[i] = getFileURL(path[i]);
 427         }
 428         // DEBUG
 429         //for (int i = 0; i < urls.length; i++) {
 430         //  System.out.println("urls[" + i + "] = " + '"' + urls[i] + '"');
 431         //}
 432         return urls;
 433     }
 434 
 435     private static File[] getClassPath(String cp) {
 436         File[] path;
 437         if (cp != null) {
 438             int count = 0, maxCount = 1;
 439             int pos = 0, lastPos = 0;
 440             // Count the number of separators first
 441             while ((pos = cp.indexOf(File.pathSeparator, lastPos)) != -1) {
 442                 maxCount++;
 443                 lastPos = pos + 1;
 444             }
 445             path = new File[maxCount];
 446             lastPos = pos = 0;
 447             // Now scan for each path component
 448             while ((pos = cp.indexOf(File.pathSeparator, lastPos)) != -1) {
 449                 if (pos - lastPos > 0) {
 450                     path[count++] = new File(cp.substring(lastPos, pos));
 451                 } else {
 452                     // empty path component translates to "."
 453                     path[count++] = new File(".");
 454                 }
 455                 lastPos = pos + 1;
 456             }
 457             // Make sure we include the last path component
 458             if (lastPos < cp.length()) {
 459                 path[count++] = new File(cp.substring(lastPos));
 460             } else {
 461                 path[count++] = new File(".");
 462             }
 463             // Trim array to correct size
 464             if (count != maxCount) {
 465                 File[] tmp = new File[count];
 466                 System.arraycopy(path, 0, tmp, 0, count);
 467                 path = tmp;
 468             }
 469         } else {
 470             path = new File[0];
 471         }
 472         // DEBUG
 473         //for (int i = 0; i < path.length; i++) {
 474         //  System.out.println("path[" + i + "] = " + '"' + path[i] + '"');
 475         //}
 476         return path;
 477     }
 478 
 479     private static URLStreamHandler fileHandler;
 480 
 481     static URL getFileURL(File file) {
 482         try {
 483             file = file.getCanonicalFile();
 484         } catch (IOException e) {}
 485 
 486         try {
 487             return ParseUtil.fileToEncodedURL(file);
 488         } catch (MalformedURLException e) {
 489             // Should never happen since we specify the protocol...
 490             throw new InternalError();
 491         }
 492     }
 493 
 494     /*
 495      * The stream handler factory for loading system protocol handlers.
 496      */
 497     private static class Factory implements URLStreamHandlerFactory {
 498         private static String PREFIX = "sun.net.www.protocol";
 499 
 500         public URLStreamHandler createURLStreamHandler(String protocol) {
 501             String name = PREFIX + "." + protocol + ".Handler";
 502             try {
 503                 Class c = Class.forName(name);
 504                 return (URLStreamHandler)c.newInstance();
 505             } catch (ClassNotFoundException e) {
 506                 e.printStackTrace();
 507             } catch (InstantiationException e) {
 508                 e.printStackTrace();
 509             } catch (IllegalAccessException e) {
 510                 e.printStackTrace();
 511             }
 512             throw new InternalError("could not load " + protocol +
 513                                     "system protocol handler");
 514         }
 515     }
 516 }
 517 
 518 class PathPermissions extends PermissionCollection {
 519     // use serialVersionUID from JDK 1.2.2 for interoperability
 520     private static final long serialVersionUID = 8133287259134945693L;
 521 
 522     private File path[];
 523     private Permissions perms;
 524 
 525     URL codeBase;
 526 
 527     PathPermissions(File path[])
 528     {
 529         this.path = path;
 530         this.perms = null;
 531         this.codeBase = null;
 532     }
 533 
 534     URL getCodeBase()
 535     {
 536         return codeBase;
 537     }
 538 
 539     public void add(java.security.Permission permission) {
 540         throw new SecurityException("attempt to add a permission");
 541     }
 542 
 543     private synchronized void init()
 544     {
 545         if (perms != null)
 546             return;
 547 
 548         perms = new Permissions();
 549 
 550         // this is needed to be able to create the classloader itself!
 551         perms.add(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);
 552 
 553         // add permission to read any "java.*" property
 554         perms.add(new java.util.PropertyPermission("java.*",
 555             SecurityConstants.PROPERTY_READ_ACTION));
 556 
 557         AccessController.doPrivileged(new PrivilegedAction<Void>() {
 558             public Void run() {
 559                 for (int i=0; i < path.length; i++) {
 560                     File f = path[i];
 561                     String path;
 562                     try {
 563                         path = f.getCanonicalPath();
 564                     } catch (IOException ioe) {
 565                         path = f.getAbsolutePath();
 566                     }
 567                     if (i == 0) {
 568                         codeBase = Launcher.getFileURL(new File(path));
 569                     }
 570                     if (f.isDirectory()) {
 571                         if (path.endsWith(File.separator)) {
 572                             perms.add(new FilePermission(path+"-",
 573                                 SecurityConstants.FILE_READ_ACTION));
 574                         } else {
 575                             perms.add(new FilePermission(
 576                                 path + File.separator+"-",
 577                                 SecurityConstants.FILE_READ_ACTION));
 578                         }
 579                     } else {
 580                         int endIndex = path.lastIndexOf(File.separatorChar);
 581                         if (endIndex != -1) {
 582                             path = path.substring(0, endIndex+1) + "-";
 583                             perms.add(new FilePermission(path,
 584                                 SecurityConstants.FILE_READ_ACTION));
 585                         } else {
 586                             // XXX?
 587                         }
 588                     }
 589                 }
 590                 return null;
 591             }
 592         });
 593     }
 594 
 595     public boolean implies(java.security.Permission permission) {
 596         if (perms == null)
 597             init();
 598         return perms.implies(permission);
 599     }
 600 
 601     public java.util.Enumeration<Permission> elements() {
 602         if (perms == null)
 603             init();
 604         synchronized (perms) {
 605             return perms.elements();
 606         }
 607     }
 608 
 609     public String toString() {
 610         if (perms == null)
 611             init();
 612         return perms.toString();
 613     }
 614 }