/* this code is workaround for subtle bug/feature in JDK1.3.1 and 1.4, related to loading applets behind proxy */ protected PermissionCollection getPermissions(CodeSource codesource) { PermissionCollection sysPerms = null; Policy policy = (Policy) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return Policy.getPolicy(); } }); if (policy != null) sysPerms = policy.getPermissions(new CodeSource(null, null)); else sysPerms = new Permissions(); final PermissionCollection perms = sysPerms; if (base != null && base.getHost() != null) perms.add(new SocketPermission(base.getHost() + ":1-", "accept,connect,resolve")); URL url = codesource.getLocation(); if (url.getProtocol().equals("file")) { String path = url.getFile().replace('/', File.separatorChar); if (!path.endsWith(File.separator)) { int endIndex = path.lastIndexOf(File.separatorChar); if (endIndex != -1) { path = path.substring(0, endIndex + 1) + "-"; perms.add(new FilePermission(path, "read")); } } perms.add(new SocketPermission("localhost", "connect,accept")); AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { String host = InetAddress.getLocalHost().getHostName(); perms.add(new SocketPermission(host, "connect,accept")); } catch (UnknownHostException uhe) { } return null; } }); if (base.getProtocol().equals("file")) { String bpath = base.getFile().replace('/', File.separatorChar); if (bpath.endsWith(File.separator)) { bpath += "-"; } perms.add(new FilePermission(bpath, "read")); } } // for (Enumeration e=perms.elements();e.hasMoreElements();) // System.err.println("p="+e.nextElement()); return perms; }
protected PermissionCollection getPermissions(CodeSource codeSource) { PermissionCollection perms; try { try { perms = super.getPermissions(codeSource); } catch (SecurityException e) { // We lied about our CodeSource and that makes URLClassLoader unhappy. perms = new Permissions(); } ProtectionDomain myDomain = AccessController.doPrivileged( new PrivilegedAction<ProtectionDomain>() { public ProtectionDomain run() { return getClass().getProtectionDomain(); } }); PermissionCollection myPerms = myDomain.getPermissions(); if (myPerms != null) { for (Enumeration<Permission> elements = myPerms.elements(); elements.hasMoreElements(); ) { perms.add(elements.nextElement()); } } } catch (Throwable e) { // We lied about our CodeSource and that makes URLClassLoader unhappy. perms = new Permissions(); } perms.setReadOnly(); return perms; }
/** * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong * encoding issues. */ public Class parseClass(final InputStream in, final String fileName) throws CompilationFailedException { // For generic input streams, provide a catch-all codebase of GroovyScript // Security for these classes can be administered via policy grants with // a codebase of file:groovy.script GroovyCodeSource gcs = AccessController.doPrivileged( new PrivilegedAction<GroovyCodeSource>() { public GroovyCodeSource run() { try { String scriptText = config.getSourceEncoding() != null ? IOGroovyMethods.getText(in, config.getSourceEncoding()) : IOGroovyMethods.getText(in); return new GroovyCodeSource(scriptText, fileName, "/groovy/script"); } catch (IOException e) { throw new RuntimeException( "Impossible to read the content of the input stream for file named: " + fileName, e); } } }); return parseClass(gcs); }
/** * creates a ClassCollector for a new compilation. * * @param unit the compilationUnit * @param su the SourceUnit * @return the ClassCollector */ protected ClassCollector createCollector(CompilationUnit unit, SourceUnit su) { InnerLoader loader = AccessController.doPrivileged( new PrivilegedAction<InnerLoader>() { public InnerLoader run() { return new InnerLoader(GroovyClassLoader.this); } }); return new ClassCollector(loader, unit, su); }
/** * Parses the given text into a Java class capable of being run * * @param text the text of the script/class to parse * @param fileName the file name to use as the name of the class * @return the main class defined in the given script */ public Class parseClass(final String text, final String fileName) throws CompilationFailedException { GroovyCodeSource gcs = AccessController.doPrivileged( new PrivilegedAction<GroovyCodeSource>() { public GroovyCodeSource run() { return new GroovyCodeSource(text, fileName, "/groovy/script"); } }); gcs.setCachable(false); return parseClass(gcs); }
public static InputStream openStream(final URL url) throws IOException { try { return (InputStream) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException { return url.openStream(); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
public static InputStream getResourceAsStream(final Class c, final String name) throws IOException { try { return (InputStream) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException { return c.getResourceAsStream(name); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
public static ClassLoader getContextClassLoader() { return (ClassLoader) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); } catch (SecurityException ex) { } return cl; } }); }
public URL loadGroovySource(final String filename) throws MalformedURLException { return AccessController.doPrivileged( new PrivilegedAction<URL>() { public URL run() { for (String extension : config.getScriptExtensions()) { try { URL ret = getSourceFile(filename, extension); if (ret != null) return ret; } catch (Throwable t) { // } } return null; } }); }
public static Field makeAccessible(Class<?> target, String fieldName) { try { final Field field = target.getDeclaredField(fieldName); return (Field) AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws IllegalAccessException, InvocationTargetException { if (!field.isAccessible()) field.setAccessible(true); return field; } }); } catch (NoSuchFieldException | PrivilegedActionException e) { System.out.print(""); } // keep quiet IError.printStackTrace(e); } return null; }
/** Invoke a method on an object using reflection. */ public static Object invoke(final Object target, final Method method, final Object... args) { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws IllegalAccessException, InvocationTargetException { if (!method.isAccessible()) method.setAccessible( true); // Say please - else invoke() will fail if method is protected return method.invoke(target, args); } }); } catch (PrivilegedActionException e) { e.printStackTrace(); } return null; }
/** * adds a classpath to this classloader. * * @param path is a jar file or a directory. * @see #addURL(URL) */ public void addClasspath(final String path) { AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { try { // As the java.net.URL Javadoc says, the recommended way to get a URL is via URI. // http://docs.oracle.com/javase/7/docs/api/java/net/URL.html // "Note, the URI class does perform escaping of its component fields in certain // circumstances. // The recommended way to manage the encoding and decoding of URLs is to use URI, and // to convert // between these two classes using toURI() and URI.toURL()." // A possibly better approach here is to construct a URI and then resolve it against // a URI for the current working directory. // But we use this string match for now so everyone can see it doesn't hurt file-only // classpaths. URI newURI; if (!URI_PATTERN.matcher(path).matches()) { newURI = new File(path).toURI(); } else { newURI = new URI(path); } URL[] urls = getURLs(); for (URL url : urls) { // Do not use URL.equals. It uses the network to resolve names and compares ip // addresses! // That is a violation of RFC and just plain evil. // http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html // http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#equals(java.lang.Object) // "Since hosts comparison requires name resolution, this operation is a blocking // operation. // Note: The defined behavior for equals is known to be inconsistent with virtual // hosting in HTTP." if (newURI.equals(url.toURI())) return null; } addURL(newURI.toURL()); } catch (MalformedURLException e) { // TODO: fail through ? } catch (URISyntaxException e) { // Just doing the same thing... } return null; } }); }
/** * UIManager.setLookAndFeel calls this method before the first call (and typically the only call) * to getDefaults(). Subclasses should do any one-time setup they need here, rather than in a * static initializer, because look and feel class uiDefaults may be loaded just to discover that * isSupportedLookAndFeel() returns false. * * @see #uninitialize * @see UIManager#setLookAndFeel */ @Override public void initialize() { // Note: We initialize in a privileged block, because if we are // installed as a Standard Extension in the Java VM, we // are allowed to access our resources (i.e. images), // even then, when the calling application is not allowed // to do so. AccessController.doPrivileged( new PrivilegedAction() { public Object run() { target.initialize(); myDefaults = target.getDefaults(); initResourceBundle(myDefaults); initClassDefaults(myDefaults); initGeneralDefaults(myDefaults); initComponentDefaults(myDefaults); return null; } }); }
public static URL[] getResources(final ClassLoader cl, final String name) { return (URL[]) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { URL[] ret = null; try { List v = new ArrayList(); Enumeration e = cl.getResources(name); while (e != null && e.hasMoreElements()) { URL url = (URL) e.nextElement(); if (url != null) v.add(url); } if (v.size() > 0) { ret = new URL[v.size()]; ret = (URL[]) v.toArray(ret); } } catch (IOException ioex) { } catch (SecurityException ex) { } return ret; } }); }
/** Does install of JRE */ public static void install() { // Hide the JNLP Clients installer window and show own Config.getInstallService().hideStatusWindow(); showInstallerWindow(); // Make sure the destination exists. String path = Config.getInstallService().getInstallPath(); if (Config.isWindowsInstall()) { String defaultLocation = "C:\\Program Files\\Java\\j2re" + Config.getJavaVersion() + "\\"; File defaultDir = new File(defaultLocation); if (!defaultDir.exists()) { defaultDir.mkdirs(); } if (defaultDir.exists() && defaultDir.canWrite()) { path = defaultLocation; // use default if you can } } File installDir = new File(path); if (!installDir.exists()) { installDir.mkdirs(); if (!installDir.exists()) { // The installFailed string is only for debugging. No localization needed installFailed("couldntCreateDirectory", null); return; } } // Show license if neccesary enableStep(STEP_LICENSE); if (!showLicensing()) { // The installFailed string is only for debugging. No localization needed installFailed("Licensing was not accepted", null); } ; // Make sure that the data JAR is downloaded enableStep(STEP_DOWNLOAD); if (!downloadInstallerComponent()) { // The installFailed string is only for debugging. No localization needed installFailed("Unable to download data component", null); } String nativeLibName = Config.getNativeLibName(); File installerFile = null; try { // Load native library into process if found if (nativeLibName != null && !Config.isSolarisInstall()) { System.loadLibrary(nativeLibName); } // Unpack installer enableStep(STEP_UNPACK); String installResource = Config.getInstallerResource(); Config.trace("Installer resource: " + installResource); installerFile = unpackInstaller(installResource); // To clean-up downloaded files Config.trace("Unpacked installer to: " + installerFile); if (installerFile == null) { // The installFailed string is only for debugging. No localization needed installFailed("Could not unpack installer components", null); return; } enableStep(STEP_INSTALL); setStepText(STEP_INSTALL, Config.getWindowStepWait(STEP_INSTALL)); boolean success = false; if (Config.isSolarisInstall()) { success = runSolarisInstaller(path, installerFile); } else { success = runWindowsInstaller(path, installerFile); } if (!success) { // The installFailed string is only for debugging. No localization needed installFailed("Could not run installer", null); return; } } catch (UnsatisfiedLinkError ule) { // The installFailed string is only for debugging. No localization needed installFailed("Unable to load library: " + nativeLibName, null); return; } finally { if (installerFile != null) { installerFile.delete(); } } setStepText(STEP_INSTALL, Config.getWindowStep(STEP_INSTALL)); enableStep(STEP_DONE); String execPath = path + Config.getJavaPath(); Config.trace(execPath); /** Remove installer JAR from cache */ removeInstallerComponent(); // If we're running anything after 1.0.1 or not on Windows, just call // finishedInstall. Otherwise, deny ExitVM permission so that we can // return here and do a reboot. We have to do this because we need to // call ExtensionInstallerService.finishedInstall(), which registers // that our extension (the JRE) is installed. Unfortunately pre-1.2 it // also does not understand that we are requesting a reboot, and calls // System.exit(). So for pre 1.2 we want to deny the permission to // exit the VM so we can return here and perform a reboot. boolean ispre12 = false; String version = Config.getJavaWSVersion(); // get first tuple String v = version.substring(version.indexOf('-') + 1); int i2 = v.indexOf('.'); int v1 = Integer.parseInt(v.substring(0, i2)); // get second tuple v = v.substring(i2 + 1); i2 = v.indexOf('.'); if (i2 == -1) i2 = v.indexOf('-'); if (i2 == -1) i2 = v.indexOf('['); if (i2 == -1) i2 = v.length(); int v2 = Integer.parseInt(v.substring(0, i2)); // are we pre 1.2? if (v1 < 1 || (v1 == 1 && v2 < 2)) ispre12 = true; if (Config.isWindowsInstall() && ispre12 && Config.isHopper()) { // deny ExitVM permission then call finishedInstall ProtectionDomain pd = (new Object()).getClass().getProtectionDomain(); CodeSource cs = pd.getCodeSource(); AllPermissionExceptExitVM perm = new AllPermissionExceptExitVM(); PermissionCollection newpc = perm.newPermissionCollection(); newpc.add(perm); // run finishedInstall within the new context which excluded // just the ExitVM permission ProtectionDomain newpd = new ProtectionDomain(cs, newpc); AccessControlContext newacc = new AccessControlContext(new ProtectionDomain[] {newpd}); final String fExecPath = execPath; try { AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws SecurityException { finishedInstall(fExecPath); return null; } }, newacc); } catch (PrivilegedActionException pae) { // swallow the exception because we want ExitVM to fail silent } catch (SecurityException se) { // swallow the exception because we want ExitVM to fail silent } } else { // just call finished Install finishedInstall(execPath); } if (Config.isWindowsInstall() && WindowsInstaller.IsRebootNecessary()) { // reboot if (!WindowsInstaller.askUserForReboot()) System.exit(0); } else { System.exit(0); } }