Search in sources :

Example 6 with LifecycleException

use of org.apache.catalina.LifecycleException in project Payara by payara.

the class RealmAdapter method validate.

private boolean validate(HttpRequest request, HttpResponse response, LoginConfig config, Authenticator authenticator, boolean calledFromAuthenticate) throws IOException {
    HttpServletRequest servletRequest = (HttpServletRequest) request.getRequest();
    HttpServletResponse servletResponse = (HttpServletResponse) response.getResponse();
    Subject subject = new Subject();
    MessageInfo messageInfo = new HttpMessageInfo(servletRequest, servletResponse);
    boolean isValidateSuccess = false;
    boolean isMandatory = true;
    try {
        isMandatory = !getWebSecurityManager(true).permitAll(servletRequest);
        // Issue - 9578 - produce user challenge if call originates from HttpServletRequest.authenticate
        if (isMandatory || calledFromAuthenticate) {
            setMandatory(messageInfo);
        }
        ServerAuthContext authContext = getServerAuthContext(messageInfo);
        // Call the JASPIC ServerAuthContext which should eventually call the ServerAuthModule (SAM)
        // Notice a null is passed in as the service subject
        // Additionally notice we only care about SUCCESS being returned or not and ignore
        // all other JASPIC AuthStatus values.
        isValidateSuccess = SUCCESS.equals(authContext.validateRequest(messageInfo, subject, null));
        if (isValidateSuccess) {
            // store it only if validateRequest = true
            storeInRequest(servletRequest, messageInfo, authContext);
        }
    } catch (AuthException ae) {
        logger.log(WARNING, "JMAC: http msg authentication fail", ae);
        servletResponse.setStatus(SC_INTERNAL_SERVER_ERROR);
    } catch (RuntimeException e) {
        logger.log(WARNING, "JMAC: Exception during validateRequest", e);
        servletResponse.sendError(SC_INTERNAL_SERVER_ERROR);
    }
    if (isValidateSuccess) {
        Set<Principal> principalSet = subject.getPrincipals();
        // Must be at least one new principal to establish non-default security context
        if (hasNewPrincipal(principalSet)) {
            SecurityContext securityContext = new SecurityContext(subject);
            // Assuming no null principal here
            Principal callerPrincipal = securityContext.getCallerPrincipal();
            WebPrincipal webPrincipal = new WebPrincipal(callerPrincipal, securityContext);
            // TODO: check Java SE SecurityManager access
            SecurityContext.setCurrent(securityContext);
            try {
                String authType = getAuthType(messageInfo, config);
                if (shouldRegisterSession(messageInfo)) {
                    new AuthenticatorProxy(authenticator, webPrincipal, authType).authenticate(request, response, config);
                } else {
                    request.setAuthType(authType == null ? PROXY_AUTH_TYPE : authType);
                    request.setUserPrincipal(webPrincipal);
                }
            } catch (LifecycleException le) {
                logger.log(SEVERE, "[Web-Security] unable to register session", le);
            }
        } else {
            // GLASSFISH-20930. Set null for the case when SAM does not indicate that it needs the session
            if (hasRequestPrincipal(messageInfo)) {
                request.setUserPrincipal(null);
                request.setAuthType(null);
            }
            // If authentication is mandatory, we must have a non-anonymous principal
            if (isMandatory) {
                isValidateSuccess = false;
            }
        }
        if (isValidateSuccess) {
            // Check if the SAM instructed us to wrap the request and response
            HttpServletRequest wrappedServletRequest = (HttpServletRequest) messageInfo.getRequestMessage();
            if (wrappedServletRequest != servletRequest) {
                request.setNote(WRAPPED_REQUEST, new HttpRequestWrapper(request, wrappedServletRequest));
            }
            HttpServletResponse wrappedServletResponse = (HttpServletResponse) messageInfo.getResponseMessage();
            if (wrappedServletResponse != servletResponse) {
                request.setNote(WRAPPED_RESPONSE, new HttpResponseWrapper(response, wrappedServletResponse));
            }
        }
    }
    return isValidateSuccess;
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) Subject(javax.security.auth.Subject) MessageInfo(javax.security.auth.message.MessageInfo) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(com.sun.enterprise.security.SecurityContext) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) Principal(java.security.Principal)

Example 7 with LifecycleException

use of org.apache.catalina.LifecycleException in project pwm by pwm-project.

the class TomcatOneJarMain method startTomcat.

private static void startTomcat(final TomcatConfig tomcatConfig) throws ServletException, IOException, TomcatOneJarException {
    final Instant startTime = Instant.now();
    purgeDirectory(tomcatConfig.getWorkingPath().toPath());
    explodeWar(tomcatConfig);
    out("deployed war");
    try {
        generatePwmKeystore(tomcatConfig);
        out("keystore generated");
    } catch (Exception e) {
        throw new TomcatOneJarException("error generating keystore: " + e.getMessage());
    }
    outputPwmAppProperties(tomcatConfig);
    setupEnv(tomcatConfig);
    final Tomcat tomcat = new Tomcat();
    {
        final File basePath = new File(tomcatConfig.getWorkingPath().getPath() + File.separator + "b");
        basePath.mkdir();
        tomcat.setBaseDir(basePath.getAbsolutePath());
    }
    {
        final File basePath = new File(tomcatConfig.getWorkingPath().getPath() + File.separator + "a");
        basePath.mkdir();
        tomcat.getServer().setCatalinaBase(basePath);
        tomcat.getServer().setCatalinaHome(basePath);
    }
    {
        final File workPath = new File(tomcatConfig.getWorkingPath().getPath() + File.separator + "w");
        workPath.mkdir();
        tomcat.getHost().setAppBase(workPath.getAbsolutePath());
    }
    tomcat.getHost().setAutoDeploy(false);
    tomcat.getHost().setDeployOnStartup(false);
    final String warPath = getWarFolder(tomcatConfig).getAbsolutePath();
    tomcat.addWebapp("/" + tomcatConfig.getContext(), warPath);
    try {
        tomcat.start();
        tomcat.setConnector(makeConnector(tomcatConfig));
        out("tomcat started in " + Duration.between(Instant.now(), startTime).toString());
    } catch (LifecycleException e) {
        throw new TomcatOneJarException("unable to start tomcat: " + e.getMessage());
    }
    tomcat.getServer().await();
    System.out.println("\n");
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) LifecycleException(org.apache.catalina.LifecycleException) Instant(java.time.Instant) File(java.io.File) ServletException(javax.servlet.ServletException) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 8 with LifecycleException

use of org.apache.catalina.LifecycleException in project tomcat70 by apache.

the class WebappLoader method startInternal.

/**
 * Start associated {@link ClassLoader} and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {
    if (log.isDebugEnabled())
        log.debug(sm.getString("webappLoader.starting"));
    if (container.getResources() == null) {
        log.info("No resources for " + container);
        setState(LifecycleState.STARTING);
        return;
    }
    // Register a stream handler factory for the JNDI protocol
    URLStreamHandlerFactory streamHandlerFactory = DirContextURLStreamHandlerFactory.getInstance();
    if (first) {
        first = false;
        try {
            URL.setURLStreamHandlerFactory(streamHandlerFactory);
        } catch (Exception e) {
            // Log and continue anyway, this is not critical
            log.error("Error registering jndi stream handler", e);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            // This is likely a dual registration
            log.info("Dual registration of jndi stream handler: " + t.getMessage());
        }
    }
    // Construct a class loader based on our current repositories list
    try {
        classLoader = createClassLoader();
        classLoader.setJarOpenInterval(this.jarOpenInterval);
        classLoader.setResources(container.getResources());
        classLoader.setDelegate(this.delegate);
        classLoader.setSearchExternalFirst(searchExternalFirst);
        if (container instanceof StandardContext) {
            classLoader.setAntiJARLocking(((StandardContext) container).getAntiJARLocking());
            classLoader.setClearReferencesRmiTargets(((StandardContext) container).getClearReferencesRmiTargets());
            classLoader.setClearReferencesStatic(((StandardContext) container).getClearReferencesStatic());
            classLoader.setClearReferencesStopThreads(((StandardContext) container).getClearReferencesStopThreads());
            classLoader.setClearReferencesStopTimerThreads(((StandardContext) container).getClearReferencesStopTimerThreads());
            classLoader.setClearReferencesHttpClientKeepAliveThread(((StandardContext) container).getClearReferencesHttpClientKeepAliveThread());
            classLoader.setClearReferencesObjectStreamClassCaches(((StandardContext) container).getClearReferencesObjectStreamClassCaches());
        }
        for (int i = 0; i < repositories.length; i++) {
            classLoader.addRepository(repositories[i]);
        }
        // Configure our repositories
        setRepositories();
        setClassPath();
        setPermissions();
        ((Lifecycle) classLoader).start();
        // Binding the Webapp class loader to the directory context
        DirContextURLStreamHandler.bind(classLoader, this.container.getResources());
        StandardContext ctx = (StandardContext) container;
        String contextName = ctx.getName();
        if (!contextName.startsWith("/")) {
            contextName = "/" + contextName;
        }
        ObjectName cloname = new ObjectName(MBeanUtils.getDomain(ctx) + ":type=WebappClassLoader,context=" + contextName + ",host=" + ctx.getParent().getName());
        Registry.getRegistry(null, null).registerComponent(classLoader, cloname, null);
    } catch (Throwable t) {
        t = ExceptionUtils.unwrapInvocationTargetException(t);
        ExceptionUtils.handleThrowable(t);
        log.error("LifecycleException ", t);
        throw new LifecycleException("start: ", t);
    }
    setState(LifecycleState.STARTING);
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) StandardContext(org.apache.catalina.core.StandardContext) Lifecycle(org.apache.catalina.Lifecycle) URLStreamHandlerFactory(java.net.URLStreamHandlerFactory) DirContextURLStreamHandlerFactory(org.apache.naming.resources.DirContextURLStreamHandlerFactory) NamingException(javax.naming.NamingException) LifecycleException(org.apache.catalina.LifecycleException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ObjectName(javax.management.ObjectName)

Example 9 with LifecycleException

use of org.apache.catalina.LifecycleException in project tomcat70 by apache.

the class WebappLoader method stopInternal.

/**
 * Stop associated {@link ClassLoader} and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void stopInternal() throws LifecycleException {
    if (log.isDebugEnabled())
        log.debug(sm.getString("webappLoader.stopping"));
    setState(LifecycleState.STOPPING);
    // Remove context attributes as appropriate
    if (container instanceof Context) {
        ServletContext servletContext = ((Context) container).getServletContext();
        servletContext.removeAttribute(Globals.CLASS_PATH_ATTR);
    }
    // Throw away our current class loader
    if (classLoader != null) {
        ((Lifecycle) classLoader).stop();
        DirContextURLStreamHandler.unbind(classLoader);
    }
    try {
        StandardContext ctx = (StandardContext) container;
        String contextName = ctx.getName();
        if (!contextName.startsWith("/")) {
            contextName = "/" + contextName;
        }
        ObjectName cloname = new ObjectName(MBeanUtils.getDomain(ctx) + ":type=WebappClassLoader,context=" + contextName + ",host=" + ctx.getParent().getName());
        Registry.getRegistry(null, null).unregisterComponent(cloname);
    } catch (Exception e) {
        log.error("LifecycleException ", e);
    }
    classLoader = null;
}
Also used : DirContext(javax.naming.directory.DirContext) Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) Lifecycle(org.apache.catalina.Lifecycle) StandardContext(org.apache.catalina.core.StandardContext) ServletContext(javax.servlet.ServletContext) NamingException(javax.naming.NamingException) LifecycleException(org.apache.catalina.LifecycleException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ObjectName(javax.management.ObjectName)

Example 10 with LifecycleException

use of org.apache.catalina.LifecycleException in project tomcat70 by apache.

the class SimpleTcpCluster method startInternal.

/**
 * Start Cluster and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {
    if (log.isInfoEnabled())
        log.info("Cluster is about to start");
    try {
        checkDefaults();
        registerClusterValve();
        channel.addMembershipListener(this);
        channel.addChannelListener(this);
        if (channel instanceof GroupChannel)
            ((GroupChannel) channel).setName(getClusterName() + "-Channel");
        channel.start(channelStartOptions);
        if (clusterDeployer != null)
            clusterDeployer.start();
        registerMember(channel.getLocalMember(false));
    } catch (Exception x) {
        log.error("Unable to start cluster.", x);
        throw new LifecycleException(x);
    }
    setState(LifecycleState.STARTING);
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) GroupChannel(org.apache.catalina.tribes.group.GroupChannel) LifecycleException(org.apache.catalina.LifecycleException)

Aggregations

LifecycleException (org.apache.catalina.LifecycleException)128 Lifecycle (org.apache.catalina.Lifecycle)36 IOException (java.io.IOException)29 Container (org.apache.catalina.Container)19 NamingException (javax.naming.NamingException)18 File (java.io.File)17 Realm (org.apache.catalina.Realm)16 MalformedURLException (java.net.MalformedURLException)15 ServletException (javax.servlet.ServletException)12 ArrayList (java.util.ArrayList)9 ReentrantReadWriteLock (java.util.concurrent.locks.ReentrantReadWriteLock)9 Manager (org.apache.catalina.Manager)9 Valve (org.apache.catalina.Valve)9 Tomcat (org.apache.catalina.startup.Tomcat)9 Lock (java.util.concurrent.locks.Lock)8 ReadWriteLock (java.util.concurrent.locks.ReadWriteLock)8 Cluster (org.apache.catalina.Cluster)8 Loader (org.apache.catalina.Loader)8 Server (org.apache.catalina.Server)8 Contained (org.apache.catalina.Contained)7