Search in sources :

Example 76 with PrivilegedAction

use of java.security.PrivilegedAction in project tomee by apache.

the class BasicURLClassPath method getUcpField.

private Field getUcpField() throws Exception {
    if (ucpField == null) {
        ucpField = AccessController.doPrivileged(new PrivilegedAction<Field>() {

            @Override
            public Field run() {
                try {
                    final Field ucp = URLClassLoader.class.getDeclaredField("ucp");
                    ucp.setAccessible(true);
                    return ucp;
                } catch (final Exception e2) {
                    if (!ucpFieldErrorLogged) {
                        System.err.println("Can't get ucp field of URLClassLoader");
                        ucpFieldErrorLogged = true;
                    }
                }
                return null;
            }
        });
    }
    return ucpField;
}
Also used : Field(java.lang.reflect.Field) PrivilegedAction(java.security.PrivilegedAction) IOException(java.io.IOException)

Example 77 with PrivilegedAction

use of java.security.PrivilegedAction in project rt.equinox.framework by eclipse.

the class ServiceFactoryUse method factoryGetService.

/**
 *  Call the service factory to get the service.
 *
 * @return The service returned by the factory or null if there was an error.
 */
/* @GuardedBy("this") */
S factoryGetService() {
    final S service;
    try {
        service = AccessController.doPrivileged(new PrivilegedAction<S>() {

            public S run() {
                return factory.getService(context.getBundleImpl(), registration);
            }
        });
    } catch (Throwable t) {
        if (debug.DEBUG_SERVICES) {
            // $NON-NLS-1$
            Debug.println(factory + ".getService() exception: " + t.getMessage());
            Debug.printStackTrace(t);
        }
        // allow the adaptor to handle this unexpected error
        context.getContainer().handleRuntimeError(t);
        // $NON-NLS-1$
        ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_EXCEPTION, t);
        context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
        return null;
    }
    if (service == null) {
        if (debug.DEBUG_SERVICES) {
            // $NON-NLS-1$
            Debug.println(factory + ".getService() returned null.");
        }
        ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_OBJECT_NULL_EXCEPTION, factory.getClass().getName()), ServiceException.FACTORY_ERROR);
        context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se);
        return null;
    }
    String[] clazzes = registration.getClasses();
    String invalidService = ServiceRegistry.checkServiceClass(clazzes, service);
    if (invalidService != null) {
        if (debug.DEBUG_SERVICES) {
            // $NON-NLS-1$
            Debug.println("Service object is not an instanceof " + invalidService);
        }
        ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_NOT_INSTANCEOF_CLASS_EXCEPTION, factory.getClass().getName(), invalidService), ServiceException.FACTORY_ERROR);
        context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
        return null;
    }
    return service;
}
Also used : NLS(org.eclipse.osgi.util.NLS) PrivilegedAction(java.security.PrivilegedAction)

Example 78 with PrivilegedAction

use of java.security.PrivilegedAction in project Payara by payara.

the class EarHandler method getClassLoader.

public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext context) {
    final ReadableArchive archive = context.getSource();
    final ApplicationHolder holder = getApplicationHolder(archive, context, true);
    // the ear classloader hierachy will be
    // ear lib classloader <- embedded rar classloader <-
    // ear classloader <- various module classloaders
    final DelegatingClassLoader embeddedConnCl;
    final EarClassLoader cl;
    // add the libraries packaged in the application library directory
    try {
        String compatProp = context.getAppProps().getProperty(DeploymentProperties.COMPATIBILITY);
        // let's see if it's defined in glassfish-application.xml
        if (compatProp == null) {
            GFApplicationXmlParser gfApplicationXmlParser = new GFApplicationXmlParser(context.getSource());
            compatProp = gfApplicationXmlParser.getCompatibilityValue();
            if (compatProp != null) {
                context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp);
            }
        }
        // let's see if it's defined in sun-application.xml
        if (compatProp == null) {
            SunApplicationXmlParser sunApplicationXmlParser = new SunApplicationXmlParser(context.getSourceDir());
            compatProp = sunApplicationXmlParser.getCompatibilityValue();
            if (compatProp != null) {
                context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp);
            }
        }
        if (System.getSecurityManager() != null) {
            // procee declared permissions
            earDeclaredPC = PermsArchiveDelegate.getDeclaredPermissions(SMGlobalPolicyUtil.CommponentType.ear, context);
            // process ee permissions
            processEEPermissions(context);
        }
        final URL[] earLibURLs = ASClassLoaderUtil.getAppLibDirLibraries(context.getSourceDir(), holder.app.getLibraryDirectory(), compatProp);
        final EarLibClassLoader earLibCl = AccessController.doPrivileged(new PrivilegedAction<EarLibClassLoader>() {

            @Override
            public EarLibClassLoader run() {
                return new EarLibClassLoader(earLibURLs, parent);
            }
        });
        String clDelegate = holder.app.getClassLoadingDelegate();
        // default to true if null
        if (Boolean.parseBoolean(clDelegate == null ? "true" : clDelegate) == false) {
            earLibCl.enableCurrentBeforeParentUnconditional();
        } else if (clDelegate != null) {
            // otherwise clDelegate == true
            earLibCl.disableCurrentBeforeParent();
        }
        if (System.getSecurityManager() != null) {
            addEEOrDeclaredPermissions(earLibCl, earDeclaredPC, false);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("added declaredPermissions to earlib: " + earDeclaredPC);
            addEEOrDeclaredPermissions(earLibCl, eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ear), true);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("added all ee permissions to earlib: " + eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ear));
        }
        embeddedConnCl = AccessController.doPrivileged(new PrivilegedAction<DelegatingClassLoader>() {

            @Override
            public DelegatingClassLoader run() {
                return new DelegatingClassLoader(earLibCl);
            }
        });
        cl = AccessController.doPrivileged(new PrivilegedAction<EarClassLoader>() {

            @Override
            public EarClassLoader run() {
                return new EarClassLoader(embeddedConnCl, holder.app);
            }
        });
        // add ear lib to module classloader list so we can
        // clean it up later
        cl.addModuleClassLoader(EAR_LIB, earLibCl);
        if (System.getSecurityManager() != null) {
            // push declared permissions to ear classloader
            addEEOrDeclaredPermissions(cl, earDeclaredPC, false);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("declaredPermissions added: " + earDeclaredPC);
            // push ejb permissions to ear classloader
            addEEOrDeclaredPermissions(cl, eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ejb), true);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("ee permissions added: " + eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ejb));
        }
    } catch (Exception e) {
        _logger.log(Level.SEVERE, strings.get("errAddLibs"), e);
        throw new RuntimeException(e);
    }
    for (ModuleDescriptor md : holder.app.getModules()) {
        ReadableArchive sub = null;
        String moduleUri = md.getArchiveUri();
        try {
            sub = archive.getSubArchive(moduleUri);
            if (sub instanceof InputJarArchive) {
                throw new IllegalArgumentException(strings.get("wrongArchType", moduleUri));
            }
        } catch (IOException e) {
            _logger.log(Level.FINE, "Sub archive " + moduleUri + " seems unreadable", e);
        }
        if (sub != null) {
            try {
                ArchiveHandler handler = context.getModuleArchiveHandlers().get(moduleUri);
                if (handler == null) {
                    handler = getArchiveHandlerFromModuleType(md.getModuleType());
                    if (handler == null) {
                        handler = deployment.getArchiveHandler(sub);
                    }
                    context.getModuleArchiveHandlers().put(moduleUri, handler);
                }
                if (handler != null) {
                    ActionReport subReport = context.getActionReport().addSubActionsReport();
                    // todo : this is a hack, once again,
                    // the handler is assuming a file:// url
                    ExtendedDeploymentContext subContext = new DeploymentContextImpl(subReport, sub, context.getCommandParameters(DeployCommandParameters.class), env) {

                        @Override
                        public File getScratchDir(String subDirName) {
                            String modulePortion = Util.getURIName(getSource().getURI());
                            return (new File(super.getScratchDir(subDirName), modulePortion));
                        }
                    };
                    // sub context will store the root archive handler also
                    // so we can figure out the enclosing archive type
                    subContext.setArchiveHandler(context.getArchiveHandler());
                    subContext.setParentContext((ExtendedDeploymentContext) context);
                    sub.setParentArchive(context.getSource());
                    ClassLoader subCl = handler.getClassLoader(cl, subContext);
                    if ((System.getSecurityManager() != null) && (subCl instanceof DDPermissionsLoader)) {
                        addEEOrDeclaredPermissions(subCl, earDeclaredPC, false);
                        if (_logger.isLoggable(Level.FINE))
                            _logger.fine("added declared permissions to sub module of " + subCl);
                    }
                    if (md.getModuleType().equals(DOLUtils.ejbType())) {
                        // for ejb module, we just add the ejb urls
                        // to EarClassLoader and use that to load
                        // ejb module
                        URL[] moduleURLs = ((URLClassLoader) subCl).getURLs();
                        for (URL moduleURL : moduleURLs) {
                            cl.addURL(moduleURL);
                        }
                        cl.addModuleClassLoader(moduleUri, cl);
                        PreDestroy.class.cast(subCl).preDestroy();
                    } else if (md.getModuleType().equals(DOLUtils.rarType())) {
                        embeddedConnCl.addDelegate((DelegatingClassLoader.ClassFinder) subCl);
                        cl.addModuleClassLoader(moduleUri, subCl);
                    } else {
                        Boolean isTempClassLoader = context.getTransientAppMetaData(ExtendedDeploymentContext.IS_TEMP_CLASSLOADER, Boolean.class);
                        if (subCl instanceof URLClassLoader && (isTempClassLoader != null) && isTempClassLoader) {
                            // for temp classloader, we add all the module
                            // urls to the top level EarClassLoader
                            URL[] moduleURLs = ((URLClassLoader) subCl).getURLs();
                            for (URL moduleURL : moduleURLs) {
                                cl.addURL(moduleURL);
                            }
                        }
                        cl.addModuleClassLoader(moduleUri, subCl);
                    }
                }
            } catch (IOException e) {
                _logger.log(Level.SEVERE, strings.get("noClassLoader", moduleUri), e);
            }
        }
    }
    return cl;
}
Also used : AbstractArchiveHandler(com.sun.enterprise.deploy.shared.AbstractArchiveHandler) ActionReport(org.glassfish.api.ActionReport) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) URL(java.net.URL) ApplicationHolder(org.glassfish.javaee.core.deployment.ApplicationHolder) PrivilegedAction(java.security.PrivilegedAction) DDPermissionsLoader(com.sun.enterprise.security.integration.DDPermissionsLoader) URLClassLoader(java.net.URLClassLoader) DelegatingClassLoader(org.glassfish.internal.api.DelegatingClassLoader) InputJarArchive(com.sun.enterprise.deployment.deploy.shared.InputJarArchive) DelegatingClassLoader(org.glassfish.internal.api.DelegatingClassLoader) XMLStreamException(javax.xml.stream.XMLStreamException) PrivilegedActionException(java.security.PrivilegedActionException) SAXParseException(org.xml.sax.SAXParseException) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) URLClassLoader(java.net.URLClassLoader) PreDestroy(org.glassfish.hk2.api.PreDestroy)

Example 79 with PrivilegedAction

use of java.security.PrivilegedAction in project Payara by payara.

the class WebappLoader method start.

/**
 * Start this component, initializing our associated class loader.
 *
 * @exception LifecycleException if a lifecycle error occurs
 */
public void start() throws LifecycleException {
    // Validate and update our current component state
    if (!initialized)
        init();
    if (started)
        throw new LifecycleException(rb.getString(LogFacade.LOADER_ALREADY_STARTED_EXCEPTION));
    if (log.isLoggable(Level.FINEST))
        log.log(Level.FINEST, "Starting this Loader");
    lifecycle.fireLifecycleEvent(START_EVENT, null);
    started = true;
    if (container.getResources() == null) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, LogFacade.NO_RESOURCE_INFO, container);
        }
        return;
    }
    // Register a stream handler factory for the JNDI protocol
    initStreamHandlerFactory();
    // Construct a class loader based on our current repositories list
    try {
        final ClassLoader cl = createClassLoader();
        if (cl instanceof WebappClassLoader) {
            classLoader = (WebappClassLoader) cl;
        } else {
            classLoader = AccessController.doPrivileged(new PrivilegedAction<WebappClassLoader>() {

                @Override
                public WebappClassLoader run() {
                    return new WebappClassLoader(cl, Application.createApplication());
                }
            });
        }
        classLoader.setResources(container.getResources());
        classLoader.setDebug(this.debug);
        classLoader.setDelegate(this.delegate);
        for (int i = 0; i < repositories.length; i++) {
            classLoader.addRepository(repositories[i]);
        }
        // START OF PE 4985680
        if (overridablePackages != null) {
            for (int i = 0; i < overridablePackages.size(); i++) {
                classLoader.addOverridablePackage(overridablePackages.get(i));
            }
            overridablePackages = null;
        }
        // END OF PE 4985680
        // Configure our repositories
        setRepositories();
        setClassPath();
        setPermissions();
        // Binding the Webapp class loader to the directory context
        DirContextURLStreamHandler.bind(classLoader, this.container.getResources());
    } catch (Throwable t) {
        log.log(Level.SEVERE, LogFacade.LIFECYCLE_EXCEPTION, t);
        throw new LifecycleException("start: ", t);
    }
}
Also used : WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) PrivilegedAction(java.security.PrivilegedAction) URLClassLoader(java.net.URLClassLoader) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader)

Example 80 with PrivilegedAction

use of java.security.PrivilegedAction in project Payara by payara.

the class ACCClassLoader method newInstance.

public static synchronized ACCClassLoader newInstance(ClassLoader parent, final boolean shouldTransform) {
    if (instance != null) {
        throw new IllegalStateException("already set");
    }
    final ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
    final boolean currentCLWasAgentCL = currentCL.getClass().getName().equals(AGENT_LOADER_CLASS_NAME);
    final ClassLoader parentForACCCL = currentCLWasAgentCL ? currentCL.getParent() : currentCL;
    instance = AccessController.doPrivileged(new PrivilegedAction<ACCClassLoader>() {

        @Override
        public ACCClassLoader run() {
            return new ACCClassLoader(userClassPath(), parentForACCCL, shouldTransform);
        }
    });
    if (currentCLWasAgentCL) {
        try {
            adjustACCAgentClassLoaderParent(instance);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    return instance;
}
Also used : PrivilegedAction(java.security.PrivilegedAction) URLClassLoader(java.net.URLClassLoader) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Aggregations

PrivilegedAction (java.security.PrivilegedAction)190 IOException (java.io.IOException)44 Subject (javax.security.auth.Subject)28 File (java.io.File)19 AccessControlContext (java.security.AccessControlContext)18 Method (java.lang.reflect.Method)13 InputStream (java.io.InputStream)12 URL (java.net.URL)11 LoginException (com.sun.enterprise.security.auth.login.common.LoginException)10 Field (java.lang.reflect.Field)10 URLClassLoader (java.net.URLClassLoader)10 Principal (java.security.Principal)10 Set (java.util.Set)9 PrivilegedActionException (java.security.PrivilegedActionException)8 Iterator (java.util.Iterator)8 PasswordCredential (com.sun.enterprise.security.auth.login.common.PasswordCredential)7 InvalidOperationException (com.sun.enterprise.security.auth.realm.InvalidOperationException)7 NoSuchRealmException (com.sun.enterprise.security.auth.realm.NoSuchRealmException)7 NoSuchUserException (com.sun.enterprise.security.auth.realm.NoSuchUserException)7 URISyntaxException (java.net.URISyntaxException)7