diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/ACCClassLoader.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/ACCClassLoader.java index 21f949c5dae..2f9462116ec 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/ACCClassLoader.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/ACCClassLoader.java @@ -18,17 +18,16 @@ package org.glassfish.appclient.client.acc; +import static java.security.AccessController.doPrivileged; + import com.sun.enterprise.loader.ResourceLocator; import com.sun.enterprise.util.io.FileUtils; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.net.URL; -import java.security.CodeSource; -import java.security.PermissionCollection; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.ArrayList; @@ -36,13 +35,9 @@ import java.util.Enumeration; import java.util.List; import java.util.function.Consumer; - import org.glassfish.appclient.common.ClassPathUtils; -import org.glassfish.appclient.common.ClientClassLoaderDelegate; import org.glassfish.common.util.GlassfishUrlClassLoader; -import static java.security.AccessController.doPrivileged; - /** * Application client classloader * @@ -58,8 +53,6 @@ public class ACCClassLoader extends GlassfishUrlClassLoader { private final List transformers = Collections.synchronizedList(new ArrayList()); - private ClientClassLoaderDelegate clientCLDelegate; - public static synchronized ACCClassLoader newInstance(ClassLoader parent, boolean shouldTransform) { if (instance != null) { throw new IllegalStateException("already set"); @@ -110,12 +103,10 @@ private static void adjustACCAgentClassLoaderParent(ACCClassLoader instance) thr public ACCClassLoader(ClassLoader parent, final boolean shouldTransform) { super(new URL[0], parent); this.shouldTransform = shouldTransform; - clientCLDelegate = new ClientClassLoaderDelegate(this); } public ACCClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); - clientCLDelegate = new ClientClassLoaderDelegate(this); } private ACCClassLoader(URL[] urls, ClassLoader parent, boolean shouldTransform) { @@ -193,26 +184,6 @@ private byte[] readByteCode(final String className) throws ClassNotFoundExceptio } } - @Override - protected PermissionCollection getPermissions(CodeSource codesource) { - if (System.getSecurityManager() == null) { - return super.getPermissions(codesource); - } - - // When security manager is enabled, find the declared permissions - if (clientCLDelegate.getCachedPerms(codesource) != null) { - return clientCLDelegate.getCachedPerms(codesource); - } - - return clientCLDelegate.getPermissions(codesource, super.getPermissions(codesource)); - } - - public void processDeclaredPermissions() throws IOException { - if (clientCLDelegate == null) { - clientCLDelegate = new ClientClassLoaderDelegate(this); - } - } - @Override public Enumeration getResources(String name) throws IOException { final ResourceLocator locator = new ResourceLocator(this, getParentClassLoader(), true); diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java index 4a28a5aee36..d0fd733b393 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java @@ -262,13 +262,6 @@ void setClient(final Launchable client) throws ClassNotFoundException { } - void processPermissions() throws IOException { - // need to process the permissions files - if (classLoader instanceof ACCClassLoader) { - ((ACCClassLoader) classLoader).processDeclaredPermissions(); - } - } - protected Class loadClass(final String className) throws ClassNotFoundException { return Class.forName(className, true, classLoader); } diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerBuilder.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerBuilder.java index 63e9b668f7d..729d1421a65 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerBuilder.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerBuilder.java @@ -17,17 +17,18 @@ package org.glassfish.appclient.client.acc; -import com.sun.enterprise.container.common.spi.util.InjectionException; -import com.sun.enterprise.module.bootstrap.BootException; -import com.sun.enterprise.util.LocalStringManager; -import com.sun.enterprise.util.LocalStringManagerImpl; - +import static com.sun.enterprise.util.Utility.isEmpty; import static java.util.logging.Level.CONFIG; import static org.glassfish.internal.api.ORBLocator.OMG_ORB_INIT_HOST_PROPERTY; import static org.glassfish.internal.api.ORBLocator.OMG_ORB_INIT_PORT_PROPERTY; import static org.glassfish.internal.api.ORBLocator.ORB_SSL_CLIENT_REQUIRED; +import com.sun.enterprise.container.common.spi.util.InjectionException; +import com.sun.enterprise.module.bootstrap.BootException; +import com.sun.enterprise.util.LocalStringManager; +import com.sun.enterprise.util.LocalStringManagerImpl; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLClassLoader; @@ -35,9 +36,7 @@ import java.util.List; import java.util.Properties; import java.util.logging.Logger; - import javax.security.auth.callback.CallbackHandler; - import org.glassfish.appclient.client.acc.config.AuthRealm; import org.glassfish.appclient.client.acc.config.ClientCredential; import org.glassfish.appclient.client.acc.config.MessageSecurityConfig; @@ -159,8 +158,6 @@ private AppClientContainer createContainer(final Launchable client, final Callba AppClientContainer container = ACCModulesManager.getService(AppClientContainer.class); - // process the packaged permissions.xml - container.processPermissions(); container.setClient(client); container.setBuilder(this); CallbackHandler callbackHandler = (callerSuppliedCallbackHandler != null ? callerSuppliedCallbackHandler @@ -171,11 +168,12 @@ private AppClientContainer createContainer(final Launchable client, final Callba return container; } - private CallbackHandler getCallbackHandlerFromDescriptor(final String callbackHandlerName) - throws ClassNotFoundException, InstantiationException, IllegalAccessException { - if (callbackHandlerName != null && !callbackHandlerName.equals("")) { - Class callbackHandlerClass = (Class) Class.forName(callbackHandlerName, true, classLoader); - return callbackHandlerClass.newInstance(); + private CallbackHandler getCallbackHandlerFromDescriptor(final String callbackHandlerName) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + if (!isEmpty(callbackHandlerName)) { + return (CallbackHandler) + Class.forName(callbackHandlerName, true, classLoader) + .getDeclaredConstructor() + .newInstance(); } return null; diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/JWSACCClassLoader.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/JWSACCClassLoader.java deleted file mode 100644 index ff5f2f07e2e..00000000000 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/JWSACCClassLoader.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2023 Contributors to the Eclipse Foundation - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.appclient.client.acc; - -import java.net.URL; -import java.security.CodeSource; -import java.security.PermissionCollection; - -import org.glassfish.appclient.common.ClientClassLoaderDelegate; -import org.glassfish.common.util.GlassfishUrlClassLoader; - -public class JWSACCClassLoader extends GlassfishUrlClassLoader { - - private final ClientClassLoaderDelegate clientCLDelegate; - - public JWSACCClassLoader(URL[] urls, ClassLoader parent) { - super(urls, parent); - - clientCLDelegate = new ClientClassLoaderDelegate(this); - } - - - @Override - protected PermissionCollection getPermissions(CodeSource codesource) { - if (System.getSecurityManager() == null) { - return super.getPermissions(codesource); - } - - // when security manager is enabled, find the declared permissions - if (clientCLDelegate.getCachedPerms(codesource) != null) { - return clientCLDelegate.getCachedPerms(codesource); - } - - return clientCLDelegate.getPermissions(codesource, super.getPermissions(codesource)); - } - -} diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java index 9a73e1c9a56..0774f227bba 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java @@ -36,11 +36,9 @@ import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.Vector; - import javax.swing.SwingUtilities; - import org.glassfish.appclient.client.acc.AppClientContainer; -import org.glassfish.appclient.client.acc.JWSACCClassLoader; +import org.glassfish.common.util.GlassfishUrlClassLoader; /** * Alternate main class for ACC, used when launched by Java Web Start. @@ -394,8 +392,7 @@ private static File writeTextToTempFile(String content, String prefix, String su *@return the class loader */ private static ClassLoader prepareClassLoader(File downloadedAppclientJarFile) throws IOException, URISyntaxException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - ClassLoader ldr = new JWSACCClassLoader(downloadedJarURLs, classPathManager.getParentClassLoader()); - return ldr; + return new GlassfishUrlClassLoader(downloadedJarURLs, classPathManager.getParentClassLoader()); } /* diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/ClientClassLoaderDelegate.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/ClientClassLoaderDelegate.java deleted file mode 100644 index adbcb3146f1..00000000000 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/ClientClassLoaderDelegate.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ -package org.glassfish.appclient.common; - -import java.io.IOException; -import java.security.CodeSource; -import java.security.PermissionCollection; -import java.net.URLClassLoader; -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil; -import com.sun.enterprise.security.integration.PermsHolder; - -public class ClientClassLoaderDelegate { - - protected static final String PERMISSIONS_XML = "META-INF/permissions.xml"; - - private URLClassLoader cl; - - private PermsHolder permHolder; - - public ClientClassLoaderDelegate(URLClassLoader cl) { - this.cl = cl; - loadPemissions(); - } - - private void loadPemissions() { - try { - processDeclaredPermissions(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private void processDeclaredPermissions() throws IOException { - if (System.getSecurityManager() == null) { - return; - } - - PermissionCollection declaredPermissionCollection = PermissionsUtil.getClientDeclaredPermissions(cl); - - PermissionCollection eePc = PermissionsUtil.getClientEEPolicy(cl); - PermissionCollection eeRestriction = PermissionsUtil.getClientRestrictPolicy(cl); - - SMGlobalPolicyUtil.checkRestriction(eePc, eeRestriction); - SMGlobalPolicyUtil.checkRestriction(declaredPermissionCollection, eeRestriction); - - permHolder = new PermsHolder(eePc, declaredPermissionCollection, eeRestriction); - } - - public PermissionCollection getCachedPerms(CodeSource codesource) { - return permHolder.getCachedPerms(codesource); - } - - public PermissionCollection getPermissions(CodeSource codesource, PermissionCollection parentPC) { - return permHolder.getPermissions(codesource, parentPC); - } - -} diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/PermissionsUtil.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/PermissionsUtil.java index 84be1380df2..fe0702473b2 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/PermissionsUtil.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/PermissionsUtil.java @@ -15,24 +15,10 @@ */ package org.glassfish.appclient.common; -import static com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil.CLIENT_TYPE_CODESOURCE; -import static com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil.CommponentType.car; -import com.sun.enterprise.security.ee.perms.XMLPermissionsHandler; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.CodeSource; -import java.security.NoSuchAlgorithmException; import java.security.PermissionCollection; -import java.security.Policy; -import java.security.URIParameter; -import java.security.cert.Certificate; - -import javax.xml.stream.XMLStreamException; public class PermissionsUtil { @@ -48,18 +34,7 @@ public class PermissionsUtil { // or in the client's module jar if standalone // result could be null public static PermissionCollection getClientDeclaredPermissions(ClassLoader classLoader) throws IOException { - URL permUrl = classLoader.getResource(PERMISSIONS_XML); - if (permUrl == null) { - return null; - } - - try { - return new - XMLPermissionsHandler(null, permUrl.openStream(), car) - .getAppDeclaredPermissions(); - } catch (XMLStreamException | FileNotFoundException e) { - throw new IOException(e); - } + return null; } // get the permissions configured inside the javaee.client.policy, @@ -79,40 +54,10 @@ public static PermissionCollection getClientRestrictPolicy(ClassLoader classLoad } private static PermissionCollection getClientPolicy(ClassLoader classLoader, String pkgedFile, String policyFileName) throws IOException { - - // 1st try to find from the packaged client jar - URL eeClientUrl = classLoader.getResource(pkgedFile); - if (eeClientUrl != null) - return getEEPolicyPermissions(eeClientUrl); - - // 2nd try to find from client's installation at lib/appclient folder - String clientPolicyClocation = getClientInstalledPath(); - if (clientPolicyClocation != null) { - return getPolicyPermissions(clientPolicyClocation + policyFileName); - } - return null; } - private static PermissionCollection getPolicyPermissions(String policyFilename) throws IOException { - if (!new File(policyFilename).exists()) { - return null; - } - - return getEEPolicyPermissions(new URL("file:" + policyFilename)); - } - - private static PermissionCollection getEEPolicyPermissions(URL fileUrl) throws IOException { - try { - return - Policy.getInstance("JavaPolicy", new URIParameter(fileUrl.toURI())) - .getPermissions(new CodeSource(new URL(CLIENT_TYPE_CODESOURCE), (Certificate[]) null)); - } catch (NoSuchAlgorithmException | MalformedURLException | URISyntaxException e) { - throw new IllegalStateException(e); - } - } - private static String getClientInstalledPath() { String policyPath = System.getProperty("java.security.policy"); if (policyPath == null) { diff --git a/appserver/appclient/server/core/src/main/java/org/glassfish/appclient/server/core/CarHandler.java b/appserver/appclient/server/core/src/main/java/org/glassfish/appclient/server/core/CarHandler.java index e37b492cfa1..8c2ed3632ab 100644 --- a/appserver/appclient/server/core/src/main/java/org/glassfish/appclient/server/core/CarHandler.java +++ b/appserver/appclient/server/core/src/main/java/org/glassfish/appclient/server/core/CarHandler.java @@ -17,26 +17,22 @@ package org.glassfish.appclient.server.core; +import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + import com.sun.enterprise.deploy.shared.AbstractArchiveHandler; import com.sun.enterprise.loader.ASURLClassLoader; -import com.sun.enterprise.security.ee.perms.PermsArchiveDelegate; -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil; import jakarta.inject.Inject; import jakarta.inject.Named; - import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; import java.util.logging.Level; import java.util.logging.Logger; - import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; - import org.glassfish.api.deployment.DeploymentContext; import org.glassfish.api.deployment.archive.ArchiveDetector; import org.glassfish.api.deployment.archive.CarArchiveType; @@ -44,22 +40,20 @@ import org.glassfish.appclient.server.core.jws.JavaWebStartInfo; import org.jvnet.hk2.annotations.Service; -import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; -import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; -import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; - /** * @author sanjeeb.sahoo@oracle.com */ @Service(name = CarArchiveType.ARCHIVE_TYPE) public class CarHandler extends AbstractArchiveHandler { + private static final Logger LOG = Logger.getLogger(JavaWebStartInfo.APPCLIENT_SERVER_MAIN_LOGGER, + JavaWebStartInfo.APPCLIENT_SERVER_LOGMESSAGE_RESOURCE); + @Inject @Named(CarArchiveType.ARCHIVE_TYPE) private ArchiveDetector detector; - private static final Logger LOG = Logger.getLogger(JavaWebStartInfo.APPCLIENT_SERVER_MAIN_LOGGER, - JavaWebStartInfo.APPCLIENT_SERVER_LOGMESSAGE_RESOURCE); + @Override public String getArchiveType() { @@ -88,30 +82,18 @@ public boolean handles(ReadableArchive archive) throws IOException { @Override public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext context) { - PrivilegedAction action = () -> new ASURLClassLoader(parent); - ASURLClassLoader cloader = AccessController.doPrivileged(action); + ASURLClassLoader cloader = new ASURLClassLoader(parent); try { cloader.addURL(context.getSource().getURI().toURL()); - // add libraries referenced from manifest + + // Add libraries referenced from manifest for (URL url : getManifestLibraries(context)) { cloader.addURL(url); } - - try { - final DeploymentContext dc = context; - final ClassLoader cl = cloader; - - AccessController.doPrivileged( - new PermsArchiveDelegate.SetPermissionsAction( - SMGlobalPolicyUtil.CommponentType.car, dc, cl)); - } catch (PrivilegedActionException e) { - throw new SecurityException(e.getException()); - } - - } catch (MalformedURLException e) { throw new RuntimeException(e); } + return cloader; } diff --git a/appserver/batch/glassfish-batch-connector/src/main/java/org/glassfish/batch/spi/impl/BatchRuntimeHelper.java b/appserver/batch/glassfish-batch-connector/src/main/java/org/glassfish/batch/spi/impl/BatchRuntimeHelper.java index 4bfe708ad2e..8929fe33dd4 100644 --- a/appserver/batch/glassfish-batch-connector/src/main/java/org/glassfish/batch/spi/impl/BatchRuntimeHelper.java +++ b/appserver/batch/glassfish-batch-connector/src/main/java/org/glassfish/batch/spi/impl/BatchRuntimeHelper.java @@ -240,18 +240,7 @@ public ExecutorService getExecutorService() { if (executorService == null) { synchronized (this) { if (executorService == null) { - if (System.getSecurityManager() == null) - executorService = lookupExecutorService(); - else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public java.lang.Object run() { - executorService = lookupExecutorService(); - return null; - } - } - ); - } + executorService = lookupExecutorService(); } } } diff --git a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java index 03a9d528447..47e63cb283c 100644 --- a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java +++ b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java @@ -481,35 +481,25 @@ private void _inject(final Class clazz, final Object instance, String compone } if (target.isFieldInjectable()) { - final Field f = getField(target, clazz); - if (Modifier.isStatic(f.getModifiers()) && instance != null) { + final Field injectableField = getField(target, clazz); + if (Modifier.isStatic(injectableField.getModifiers()) && instance != null) { throw new InjectionException( "Illegal use of static field on class that only supports instance-based injection: " - + f); + + injectableField); } - if (instance == null && !Modifier.isStatic(f.getModifiers())) { + if (instance == null && !Modifier.isStatic(injectableField.getModifiers())) { throw new InjectionException(MessageFormat.format( - "Injected field: {0} on Application Client class: {1} must be declared static", f, + "Injected field: {0} on Application Client class: {1} must be declared static", injectableField, clazz)); } LOG.log(DEBUG, "Injecting dependency with logical name: {0} into field: {1} on class: {2}", - next.getComponentEnvName(), f, clazz); + next.getComponentEnvName(), injectableField, clazz); // Wrap actual value insertion in doPrivileged to // allow for private/protected field access. - if (System.getSecurityManager() != null) { - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - f.set(instance, value); - return null; - } - }); - } else { - f.set(instance, value); - } + injectableField.set(instance, value); } else if (target.isMethodInjectable()) { final Method method = getMethod(next, target, clazz); diff --git a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/spi/util/JavaEEObjectStreamFactory.java b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/spi/util/JavaEEObjectStreamFactory.java deleted file mode 100644 index 25d85a7a81d..00000000000 --- a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/spi/util/JavaEEObjectStreamFactory.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2022 Contributors to the Eclipse Foundation - * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.container.common.spi.util; - -import com.sun.logging.LogDomains; - -import jakarta.inject.Inject; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.glassfish.hk2.api.ServiceLocator; -import org.jvnet.hk2.annotations.Service; - -/** - * A Factory class for creating EJBObject input/output Stream - * - * @author Mahesh Kannan - */ -// FIXME: Seems dead, unused. -@Service -public class JavaEEObjectStreamFactory { - - @Inject - ServiceLocator habitat; - - public static final Logger _logger = LogDomains.getLogger( - JavaEEObjectStreamFactory.class, LogDomains.UTIL_LOGGER); - - private static Collection _empty - = new ArrayList<>(); - /** - * - * Obtain an ObjectOutputStream that allows serialization - * of a graph of objects. The objects can be plain Serializable objects - * or can be converted into Serializable objects using - * the handler - * - *@throws java.io.IOException when the serialziation fails - *@return an ObjectOutputStream that can be used to serialize objects - */ - public ObjectOutputStream createObjectOutputStream( - final OutputStream os, - final boolean replaceObject) - throws IOException - { - // Need privileged block here because EJBObjectOutputStream - // does enableReplaceObject - ObjectOutputStream oos = null; - - final Collection handlers = replaceObject - ? habitat.getAllServices(JavaEEObjectStreamHandler.class) : _empty; - - if(System.getSecurityManager() == null) { - oos = new JavaEEObjectOutputStream(os, replaceObject, handlers); - } else { - try { - oos = (ObjectOutputStream) AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public java.lang.Object run() - throws Exception { - return new JavaEEObjectOutputStream(os, replaceObject, handlers); - } - }); - } catch ( PrivilegedActionException ex ) { - throw (IOException) ex.getException(); - } - } - return oos; - } - - /** - * - * Obtain an ObjectInputStream that allows de-serialization - * of a graph of objects. - * - *@throws java.io.IOException when the de-serialziation fails - *@return an ObjectInputStream that can be used to deserialize objects - */ - public ObjectInputStream createObjectInputStream( - final InputStream is, - final boolean resolveObject, - final ClassLoader loader) - throws Exception - { - ObjectInputStream ois = null; - if ( loader != null ) { - - final Collection handlers = resolveObject - ? habitat.getAllServices(JavaEEObjectStreamHandler.class) : _empty; - - // Need privileged block here because EJBObjectInputStream - // does enableResolveObject - if(System.getSecurityManager() == null) { - ois = new JavaEEObjectInputStream(is, loader, resolveObject, handlers); - } else { - try { - ois = (ObjectInputStream)AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public java.lang.Object run() - throws Exception { - return new JavaEEObjectInputStream( - is, loader, resolveObject, handlers); - } - }); - } catch ( PrivilegedActionException ex ) { - throw (IOException) ex.getException(); - } - } - } else { - ois = new ObjectInputStream(is); - } - - return ois; - } - - public final byte[] serializeObject(Object obj, boolean replaceObject) - throws java.io.IOException - { - byte[] data = null; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = null; - try { - oos = this.createObjectOutputStream( - bos, replaceObject); - - oos.writeObject(obj); - oos.flush(); - data = bos.toByteArray(); - } catch (java.io.NotSerializableException notSerEx) { - throw notSerEx; - } catch (Exception th) { - IOException ioEx = new IOException(th.toString()); - ioEx.initCause(th); - throw ioEx; - } finally { - if (oos != null) { - try { - oos.close(); - } catch (Exception ex) { - } - } - try { - bos.close(); - } catch (Exception ex) { - } - } - - return data; - } - - public final Object deserializeObject(byte[] data, boolean resolveObject, - ClassLoader classLoader) - throws Exception - { - Object obj = null; - ByteArrayInputStream bis = null; - ObjectInputStream ois = null; - try { - bis = new ByteArrayInputStream(data); - ois = this.createObjectInputStream(bis, resolveObject, - classLoader); - obj = ois.readObject(); - } catch (Exception ex) { - _logger.log(Level.FINE, "Error during deserialization", ex); - throw ex; - } finally { - try { - ois.close(); - } catch (Exception ex) { - _logger.log(Level.FINEST, "Error during ois.close()", ex); - } - try { - bis.close(); - } catch (Exception ex) { - _logger.log(Level.FINEST, "Error during bis.close()", ex); - } - } - return obj; - } - - -} diff --git a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/module/RarHandler.java b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/module/RarHandler.java index d5ab44a7bdd..a0ecab2198b 100644 --- a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/module/RarHandler.java +++ b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/module/RarHandler.java @@ -17,32 +17,27 @@ package com.sun.enterprise.connectors.module; +import static java.util.logging.Level.FINEST; +import static org.glassfish.loader.util.ASClassLoaderUtil.getLibDirectoryJarURIs; + import com.sun.appserv.connectors.internal.api.ConnectorRuntimeException; import com.sun.appserv.connectors.internal.api.ConnectorsClassLoaderUtil; import com.sun.appserv.connectors.internal.api.ConnectorsUtil; import com.sun.enterprise.deploy.shared.AbstractArchiveHandler; -import com.sun.enterprise.security.ee.perms.PermsArchiveDelegate; -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil; import com.sun.logging.LogDomains; - import jakarta.inject.Inject; import jakarta.inject.Named; - import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.security.AccessController; -import java.security.PrivilegedActionException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; - import org.glassfish.api.deployment.DeploymentContext; import org.glassfish.api.deployment.archive.ArchiveDetector; import org.glassfish.api.deployment.archive.RarArchiveType; import org.glassfish.api.deployment.archive.ReadableArchive; -import org.glassfish.loader.util.ASClassLoaderUtil; import org.jvnet.hk2.annotations.Service; /** @@ -55,6 +50,8 @@ public class RarHandler extends AbstractArchiveHandler { // This class should be moved to connector runtime along with ConnectorClassLoaderUtil. // We should also consider merging connectors-connector with connectors-internal-api + private final Logger _logger = LogDomains.getLogger(RarHandler.class, LogDomains.RSR_LOGGER); + @Inject private ConnectorsClassLoaderUtil loader; @@ -62,27 +59,16 @@ public class RarHandler extends AbstractArchiveHandler { @Named(RarArchiveType.ARCHIVE_TYPE) private ArchiveDetector detector; - private final Logger _logger = LogDomains.getLogger(RarHandler.class, LogDomains.RSR_LOGGER); - - /** - * {@inheritDoc} - */ @Override public String getArchiveType() { return RarArchiveType.ARCHIVE_TYPE; } - /** - * {@inheritDoc} - */ @Override public boolean handles(ReadableArchive archive) throws IOException { return detector.handles(archive); } - /** - * {@inheritDoc} - */ @Override public ClassLoader getClassLoader(ClassLoader parent, DeploymentContext context) { try { @@ -92,8 +78,8 @@ public ClassLoader getClassLoader(ClassLoader parent, DeploymentContext context) List appLibs = null; try { appLibs = context.getAppLibs(); - if(_logger.isLoggable(Level.FINEST)){ - _logger.log(Level.FINEST, "installed libraries (--applibs and EXTENSTION_LIST) for rar " + + if(_logger.isLoggable(FINEST)){ + _logger.log(FINEST, "installed libraries (--applibs and EXTENSTION_LIST) for rar " + "[ "+moduleName+" ] : " + appLibs); } } catch (URISyntaxException e) { @@ -113,16 +99,6 @@ public ClassLoader getClassLoader(ClassLoader parent, DeploymentContext context) carCL = loader.createRARClassLoader(moduleDir, null, moduleName, appLibs); } - try { - final DeploymentContext dc = context; - final ClassLoader cl = carCL; - - AccessController.doPrivileged( - new PermsArchiveDelegate.SetPermissionsAction(SMGlobalPolicyUtil.CommponentType.rar, dc, cl)); - } catch (PrivilegedActionException e) { - throw new SecurityException(e.getException()); - } - return carCL; } catch (ConnectorRuntimeException e) { @@ -137,7 +113,7 @@ public ClassLoader getClassLoader(ClassLoader parent, DeploymentContext context) */ private boolean isEmbedded(DeploymentContext context) { ReadableArchive archive = context.getSource(); - return (archive != null && archive.getParentArchive() != null); + return archive != null && archive.getParentArchive() != null; } /** @@ -153,11 +129,12 @@ public List getClassPathURIs(ReadableArchive archive) { File archiveFile = new File(archive.getURI()); if (archiveFile.exists() && archiveFile.isDirectory()) { // add top level jars - uris.addAll(ASClassLoaderUtil.getLibDirectoryJarURIs(archiveFile)); + uris.addAll(getLibDirectoryJarURIs(archiveFile)); } } catch (Exception e) { _logger.log(Level.WARNING, e.getMessage(), e); } + return uris; } } diff --git a/appserver/deployment/jakartaee-full/src/main/java/org/glassfish/javaee/full/deployment/EarHandler.java b/appserver/deployment/jakartaee-full/src/main/java/org/glassfish/javaee/full/deployment/EarHandler.java index c33634579c0..8317721c67c 100644 --- a/appserver/deployment/jakartaee-full/src/main/java/org/glassfish/javaee/full/deployment/EarHandler.java +++ b/appserver/deployment/jakartaee-full/src/main/java/org/glassfish/javaee/full/deployment/EarHandler.java @@ -17,8 +17,13 @@ package org.glassfish.javaee.full.deployment; +import static java.util.logging.Level.SEVERE; +import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; +import static org.glassfish.loader.util.ASClassLoaderUtil.getAppLibDirLibraries; + import com.sun.enterprise.config.serverbeans.DasConfig; -import com.sun.enterprise.connectors.connector.module.RarType; import com.sun.enterprise.deploy.shared.AbstractArchiveHandler; import com.sun.enterprise.deploy.shared.ArchiveFactory; import com.sun.enterprise.deploy.shared.FileArchive; @@ -29,17 +34,11 @@ import com.sun.enterprise.deployment.deploy.shared.Util; import com.sun.enterprise.deployment.io.DescriptorConstants; import com.sun.enterprise.deployment.util.DOLUtils; -import com.sun.enterprise.security.ee.perms.EarEEPermissionsProcessor; -import com.sun.enterprise.security.ee.perms.PermsArchiveDelegate; -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil; -import com.sun.enterprise.security.integration.DDPermissionsLoader; import com.sun.enterprise.universal.i18n.LocalStringsImpl; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; - import jakarta.inject.Inject; import jakarta.inject.Named; - import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -48,19 +47,12 @@ import java.net.URI; import java.net.URL; import java.net.URLClassLoader; -import java.security.AccessController; import java.security.PermissionCollection; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.text.MessageFormat; -import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; - import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; - import org.glassfish.api.ActionReport; import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.api.deployment.DeployCommandParameters; @@ -76,25 +68,17 @@ import org.glassfish.api.deployment.archive.ReadableArchive; import org.glassfish.api.deployment.archive.WarArchiveType; import org.glassfish.api.deployment.archive.WritableArchive; -import org.glassfish.appclient.server.connector.CarType; import org.glassfish.deployment.common.DeploymentContextImpl; import org.glassfish.deployment.common.DeploymentProperties; import org.glassfish.deployment.common.ModuleDescriptor; -import org.glassfish.ejb.deployment.archive.EjbType; import org.glassfish.hk2.api.PreDestroy; import org.glassfish.internal.api.DelegatingClassLoader; import org.glassfish.internal.deployment.Deployment; import org.glassfish.internal.deployment.ExtendedDeploymentContext; import org.glassfish.javaee.core.deployment.ApplicationHolder; -import org.glassfish.loader.util.ASClassLoaderUtil; -import org.glassfish.web.WarType; import org.jvnet.hk2.annotations.Service; import org.xml.sax.SAXException; -import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; -import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; -import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; - @Service(name = EarDetector.ARCHIVE_TYPE) public class EarHandler extends AbstractArchiveHandler implements CompositeHandler { @@ -124,9 +108,6 @@ public class EarHandler extends AbstractArchiveHandler implements CompositeHandl // declaredPermission protected PermissionCollection earDeclaredPC; - // ee permissions for all types - private Map eeGarntsMap; - @Override public String getArchiveType() { return EarDetector.ARCHIVE_TYPE; @@ -136,13 +117,11 @@ public String getArchiveType() { public String getVersionIdentifier(ReadableArchive archive) { String versionIdentifier = null; try { - GFApplicationXmlParser gfApplicationXMLParser = new GFApplicationXmlParser(archive); - versionIdentifier = gfApplicationXMLParser.extractVersionIdentifierValue(archive); - } catch (XMLStreamException e) { - _logger.log(Level.SEVERE, e.getMessage()); - } catch (IOException e) { - _logger.log(Level.SEVERE, e.getMessage()); + versionIdentifier = new GFApplicationXmlParser(archive).extractVersionIdentifierValue(archive); + } catch (XMLStreamException | IOException e) { + _logger.log(SEVERE, e.getMessage()); } + return versionIdentifier; } @@ -209,7 +188,7 @@ public void expand(ReadableArchive source, WritableArchive target, DeploymentCon throw new RuntimeException(msg); } } -// Keep the original submodule file because the app client deployer needs it. + // Keep the original submodule file because the app client deployer needs it. /* * // delete the original module file File origSubArchiveFile = new File( target.getURI().getSchemeSpecificPart(), * moduleUri); origSubArchiveFile.delete(); @@ -287,11 +266,13 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co // 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 + final EarClassLoader earClassLoader; + + // Add the libraries packaged in the application library directory try { String compatProp = context.getAppProps().getProperty(DeploymentProperties.COMPATIBILITY); - // if user does not specify the compatibility property + + // If user does not specify the compatibility property // let's see if it's defined in glassfish-application.xml if (compatProp == null) { GFApplicationXmlParser gfApplicationXmlParser = new GFApplicationXmlParser(context.getSource()); @@ -300,7 +281,8 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp); } } - // if user does not specify the compatibility property + + // If user does not specify the compatibility property // let's see if it's defined in sun-application.xml if (compatProp == null) { SunApplicationXmlParser sunApplicationXmlParser = new SunApplicationXmlParser(context.getSourceDir()); @@ -310,72 +292,24 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co } } - 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(), + final URL[] earLibURLs = getAppLibDirLibraries(context.getSourceDir(), holder.app.getLibraryDirectory(), compatProp); - final EarLibClassLoader earLibCl = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public EarLibClassLoader run() { - return new EarLibClassLoader(earLibURLs, parent); - } - }); - 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)); - } - } + final EarLibClassLoader earLibClassLoader = new EarLibClassLoader(earLibURLs, parent); - embeddedConnCl = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public DelegatingClassLoader run() { - return new DelegatingClassLoader(earLibCl); - } - }); - - cl = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public EarClassLoader run() { - return new EarClassLoader(embeddedConnCl); - } - }); + embeddedConnCl = new DelegatingClassLoader(earLibClassLoader); + earClassLoader = new EarClassLoader(embeddedConnCl); // 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)); - } - } - + earClassLoader.addModuleClassLoader(EAR_LIB, earLibClassLoader); } catch (Exception e) { - _logger.log(Level.SEVERE, strings.get("errAddLibs"), e); + _logger.log(SEVERE, strings.get("errAddLibs"), e); throw new RuntimeException(e); } - for (ModuleDescriptor md : holder.app.getModules()) { - String moduleUri = md.getArchiveUri(); + for (ModuleDescriptor moduleDescriptor : holder.app.getModules()) { + String moduleUri = moduleDescriptor.getArchiveUri(); try (ReadableArchive sub = archive.getSubArchive(moduleUri)) { if (sub == null) { throw new IllegalArgumentException(strings.get("noSubModuleArchiveFound", moduleUri)); @@ -385,7 +319,7 @@ public EarClassLoader run() { } ArchiveHandler handler = context.getModuleArchiveHandlers().get(moduleUri); if (handler == null) { - handler = getArchiveHandlerFromModuleType(md.getModuleType()); + handler = getArchiveHandlerFromModuleType(moduleDescriptor.getModuleType()); if (handler == null) { handler = deployment.getArchiveHandler(sub); } @@ -411,27 +345,21 @@ public File getScratchDir(String subDirName) { 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); - } - } + ClassLoader subCl = handler.getClassLoader(earClassLoader, subContext); - if (md.getModuleType().equals(DOLUtils.ejbType())) { + if (moduleDescriptor.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); + earClassLoader.addURL(moduleURL); } - cl.addModuleClassLoader(moduleUri, cl); + earClassLoader.addModuleClassLoader(moduleUri, earClassLoader); PreDestroy.class.cast(subCl).preDestroy(); - } else if (md.getModuleType().equals(DOLUtils.rarType())) { + } else if (moduleDescriptor.getModuleType().equals(DOLUtils.rarType())) { embeddedConnCl.addDelegate((DelegatingClassLoader.ClassFinder) subCl); - cl.addModuleClassLoader(moduleUri, subCl); + earClassLoader.addModuleClassLoader(moduleUri, subCl); } else { Boolean isTempClassLoader = context.getTransientAppMetaData(ExtendedDeploymentContext.IS_TEMP_CLASSLOADER, Boolean.class); @@ -440,58 +368,28 @@ public File getScratchDir(String subDirName) { // urls to the top level EarClassLoader URL[] moduleURLs = ((URLClassLoader) subCl).getURLs(); for (URL moduleURL : moduleURLs) { - cl.addURL(moduleURL); + earClassLoader.addURL(moduleURL); } } - cl.addModuleClassLoader(moduleUri, subCl); + earClassLoader.addModuleClassLoader(moduleUri, subCl); } } } catch (IOException e) { - _logger.log(Level.SEVERE, strings.get("noClassLoader", moduleUri), e); + _logger.log(SEVERE, strings.get("noClassLoader", moduleUri), e); } } - return cl; - } - - protected void processEEPermissions(DeploymentContext dc) { - EarEEPermissionsProcessor eePp = new EarEEPermissionsProcessor(dc); - eeGarntsMap = eePp.getAllAdjustedEEPermission(); - } - - // set ee or declared permissions - private void addEEOrDeclaredPermissions(ClassLoader cloader, final PermissionCollection pc, final boolean isEEPermission) { - - if (!(cloader instanceof DDPermissionsLoader)) { - return; - } - - final DDPermissionsLoader ddpl = (DDPermissionsLoader) cloader; - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws SecurityException { - if (isEEPermission) { - ddpl.addEEPermissions(pc); - } else { - ddpl.addDeclaredPermissions(pc); - } - return null; - } - }); - } catch (PrivilegedActionException e) { - throw new SecurityException(e.getException()); - } + return earClassLoader; } @Override public boolean accept(ReadableArchive source, String entryName) { - // I am hiding everything but the metadata. + // Hide everything but the metadata. return entryName.startsWith("META-INF"); } - // do any necessary meta data initialization for composite handler + // Do any necessary meta data initialization for composite handler @Override public void initCompositeMetaData(DeploymentContext context) { // populate ear level metadata @@ -529,6 +427,7 @@ private ApplicationHolder getApplicationHolder(ReadableArchive source, Deploymen if (holder.app == null) { throw new RuntimeException(strings.get("errReadMetadata")); } + return holder; } @@ -538,15 +437,21 @@ private ApplicationHolder getApplicationHolder(ReadableArchive source, Deploymen private ArchiveHandler getArchiveHandlerFromModuleType(ArchiveType type) { if (type.equals(DOLUtils.warType())) { return habitat.getService(ArchiveHandler.class, WarArchiveType.ARCHIVE_TYPE); - } else if (type.equals(DOLUtils.rarType())) { + } + + if (type.equals(DOLUtils.rarType())) { return habitat.getService(ArchiveHandler.class, RarArchiveType.ARCHIVE_TYPE); - } else if (type.equals(DOLUtils.ejbType())) { + } + + if (type.equals(DOLUtils.ejbType())) { return habitat.getService(ArchiveHandler.class, EjbArchiveType.ARCHIVE_TYPE); - } else if (type.equals(DOLUtils.carType())) { + } + + if (type.equals(DOLUtils.carType())) { return habitat.getService(ArchiveHandler.class, CarArchiveType.ARCHIVE_TYPE); - } else { - return null; } + + return null; } private static class GFApplicationXmlParser { @@ -589,7 +494,6 @@ private static class GFApplicationXmlParser { } protected String extractVersionIdentifierValue(ReadableArchive archive) throws XMLStreamException, IOException { - InputStream input = null; String versionIdentifierValue = null; diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/codegen/ClassGenerator.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/codegen/ClassGenerator.java index e43b78254b2..55d4b78a37d 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/codegen/ClassGenerator.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/codegen/ClassGenerator.java @@ -16,8 +16,9 @@ package com.sun.ejb.codegen; -import com.sun.enterprise.loader.ASURLClassLoader; +import static java.util.logging.Level.CONFIG; +import com.sun.enterprise.loader.ASURLClassLoader; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Method; @@ -29,8 +30,6 @@ import java.util.Objects; import java.util.logging.Logger; -import static java.util.logging.Level.CONFIG; - /** * This class serves to generate classes, because ... *

@@ -92,11 +91,9 @@ public static Class defineClass(final ClassLoader loader, final Class anch final String targetPackageName, final String className, final byte[] classData) { if (useMethodHandles(loader, anchorClass, targetPackageName)) { return defineClass(anchorClass, className, classData); - } else if (System.getSecurityManager() == null) { - return defineClass(loader, className, classData, anchorClass.getProtectionDomain()); - } else { - return defineClass(loader, className, classData); } + + return defineClass(loader, className, classData, anchorClass.getProtectionDomain()); } diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/interceptors/InterceptorManager.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/interceptors/InterceptorManager.java index 6f1e2ad7468..4bc9e46bbb7 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/interceptors/InterceptorManager.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/interceptors/InterceptorManager.java @@ -17,6 +17,12 @@ package com.sun.ejb.containers.interceptors; +import static com.sun.ejb.EJBUtils.loadGeneratedSerializableClass; +import static com.sun.enterprise.deployment.LifecycleCallbackDescriptor.CallbackType.POST_ACTIVATE; +import static com.sun.enterprise.deployment.LifecycleCallbackDescriptor.CallbackType.PRE_PASSIVATE; +import static java.util.logging.Level.CONFIG; +import static java.util.logging.Level.FINE; + import com.sun.ejb.containers.BaseContainer; import com.sun.ejb.containers.EJBContextImpl; import com.sun.enterprise.container.common.spi.util.InterceptorInfo; @@ -25,14 +31,14 @@ import com.sun.enterprise.deployment.LifecycleCallbackDescriptor; import com.sun.enterprise.deployment.LifecycleCallbackDescriptor.CallbackType; import com.sun.enterprise.deployment.MethodDescriptor; - import jakarta.annotation.PostConstruct; import jakarta.ejb.EJBException; import jakarta.interceptor.InvocationContext; - import java.io.Serializable; import java.lang.reflect.InaccessibleObjectException; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.security.PrivilegedActionException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -42,16 +48,9 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; - import org.glassfish.ejb.deployment.descriptor.EjbDescriptor; import org.glassfish.ejb.deployment.descriptor.EjbSessionDescriptor; -import static com.sun.ejb.EJBUtils.loadGeneratedSerializableClass; -import static com.sun.enterprise.deployment.LifecycleCallbackDescriptor.CallbackType.POST_ACTIVATE; -import static com.sun.enterprise.deployment.LifecycleCallbackDescriptor.CallbackType.PRE_PASSIVATE; -import static java.util.logging.Level.CONFIG; -import static java.util.logging.Level.FINE; - /** * UserInterceptorsManager manages UserInterceptors. There is one instance of InterceptorManager per container. * @@ -727,20 +726,8 @@ class AroundInvokeInterceptor { try { final Method finalM = method; - if (System.getSecurityManager() == null) { - if (!finalM.trySetAccessible()) { - throw new InaccessibleObjectException("Unable to make accessible: "+ finalM); - } - } else { - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - if (!finalM.trySetAccessible()) { - throw new InaccessibleObjectException("Unable to make accessible: " + finalM); - } - return null; - } - }); + if (!finalM.trySetAccessible()) { + throw new InaccessibleObjectException("Unable to make accessible: "+ finalM); } } catch (Exception e) { throw new EJBException(e); @@ -750,30 +737,9 @@ public java.lang.Object run() throws Exception { Object intercept(final InterceptorManager.AroundInvokeContext invCtx) throws Throwable { try { - final Object[] interceptors = invCtx.getInterceptorInstances(); - - if (System.getSecurityManager() != null) { - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - return method.invoke(interceptors[index], invCtx); - } - }); - } else { - - return method.invoke(interceptors[index], invCtx); - - } - } catch (java.lang.reflect.InvocationTargetException invEx) { + return method.invoke(invCtx.getInterceptorInstances()[index], invCtx); + } catch (InvocationTargetException invEx) { throw invEx.getCause(); - } catch (java.security.PrivilegedActionException paEx) { - Throwable th = paEx.getCause(); - if (th.getCause() != null) { - throw th.getCause(); - } - throw th; } } @@ -794,27 +760,9 @@ class BeanAroundInvokeInterceptor extends AroundInvokeInterceptor { @Override Object intercept(final InterceptorManager.AroundInvokeContext invCtx) throws Throwable { try { - - if (System.getSecurityManager() != null) { - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - return method.invoke(invCtx.getTarget(), invCtx); - } - }); - } else { - return method.invoke(invCtx.getTarget(), invCtx); - } - } catch (java.lang.reflect.InvocationTargetException invEx) { + return method.invoke(invCtx.getTarget(), invCtx); + } catch (InvocationTargetException invEx) { throw invEx.getCause(); - } catch (java.security.PrivilegedActionException paEx) { - Throwable th = paEx.getCause(); - if (th.getCause() != null) { - throw th.getCause(); - } - throw th; } } } @@ -828,21 +776,8 @@ class CallbackInterceptor { this.method = method; try { - final Method finalM = method; - if (System.getSecurityManager() == null) { - if (!finalM.trySetAccessible()) { - throw new InaccessibleObjectException("Unable to make accessible: " + finalM); - } - } else { - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - if (!finalM.trySetAccessible()) { - throw new InaccessibleObjectException("Unable to make accessible: " + finalM); - } - return null; - } - }); + if (!method.trySetAccessible()) { + throw new InaccessibleObjectException("Unable to make accessible: " + method); } } catch (Exception e) { throw new EJBException(e); @@ -852,30 +787,9 @@ public java.lang.Object run() throws Exception { Object intercept(final CallbackInvocationContext invContext) throws Throwable { try { - - final Object[] interceptors = invContext.getInterceptorInstances(); - - if (System.getSecurityManager() != null) { - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - return method.invoke(interceptors[index], invContext); - } - }); - } else { - return method.invoke(interceptors[index], invContext); - - } + return method.invoke(invContext.getInterceptorInstances()[index], invContext); } catch (java.lang.reflect.InvocationTargetException invEx) { throw invEx.getCause(); - } catch (java.security.PrivilegedActionException paEx) { - Throwable th = paEx.getCause(); - if (th.getCause() != null) { - throw th.getCause(); - } - throw th; } } @@ -899,28 +813,11 @@ class BeanCallbackInterceptor extends CallbackInterceptor { @Override Object intercept(final CallbackInvocationContext invContext) throws Throwable { try { - - if (System.getSecurityManager() != null) { - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - - method.invoke(invContext.getTarget(), NULL_ARGS); - return null; - - } - }); - } else { - method.invoke(invContext.getTarget(), NULL_ARGS); - } - + method.invoke(invContext.getTarget(), NULL_ARGS); return invContext.proceed(); - - } catch (java.lang.reflect.InvocationTargetException invEx) { + } catch (InvocationTargetException invEx) { throw invEx.getCause(); - } catch (java.security.PrivilegedActionException paEx) { + } catch (PrivilegedActionException paEx) { Throwable th = paEx.getCause(); if (th.getCause() != null) { throw th.getCause(); diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/AbstractPool.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/AbstractPool.java index f1f0215d39c..f2ab5fb1dbb 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/AbstractPool.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/AbstractPool.java @@ -24,18 +24,15 @@ package com.sun.ejb.containers.util.pool; import static com.sun.enterprise.util.Utility.setContextClassLoader; -import static java.security.AccessController.doPrivileged; import static java.util.logging.Level.FINE; import static java.util.logging.Level.WARNING; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - import com.sun.ejb.containers.EjbContainerUtilImpl; import com.sun.ejb.monitoring.probes.EjbPoolProbeProvider; import com.sun.ejb.monitoring.stats.EjbMonitoringUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; /** *

@@ -346,17 +343,7 @@ public void run() { final ClassLoader previousClassLoader = currentThread.getContextClassLoader(); try { - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(containerClassLoader); - } else { - doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - currentThread.setContextClassLoader(containerClassLoader); - return null; - } - }); - } + currentThread.setContextClassLoader(containerClassLoader); try { if (pooledObjects.size() > steadyPoolSize) { @@ -368,17 +355,7 @@ public Object run() { // removeIdleObjects would have logged the error } - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(previousClassLoader); - } else { - doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - currentThread.setContextClassLoader(previousClassLoader); - return null; - } - }); - } + currentThread.setContextClassLoader(previousClassLoader); } catch (Throwable th) { _logger.log(FINE, "Exception in run()", th); } diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/NonBlockingPool.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/NonBlockingPool.java index 5bec771845f..566b620384c 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/NonBlockingPool.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/util/pool/NonBlockingPool.java @@ -23,19 +23,16 @@ package com.sun.ejb.containers.util.pool; import static com.sun.enterprise.util.Utility.setContextClassLoader; -import static java.security.AccessController.doPrivileged; import static java.util.logging.Level.FINE; import static java.util.logging.Level.WARNING; -import java.security.PrivilegedAction; +import com.sun.ejb.containers.EJBContextImpl; +import com.sun.ejb.containers.EjbContainerUtilImpl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimerTask; -import com.sun.ejb.containers.EJBContextImpl; -import com.sun.ejb.containers.EjbContainerUtilImpl; - /** *

* NonBlockingPool pool provides the basic implementation of an object pool. @@ -406,17 +403,7 @@ protected void doResize() { long startTime = 0; boolean enteredResizeBlock = false; try { - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(containerClassLoader); - } else { - doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - currentThread.setContextClassLoader(containerClassLoader); - return null; - } - }); - } + currentThread.setContextClassLoader(containerClassLoader); _logger.log(FINE, () -> "[Pool-" + poolName + "]: Resize started at: " + (new Date()) + " steadyPoolSize ::" + steadyPoolSize + " resizeQuantity ::" + resizeQuantity + " maxPoolSize ::" + maxPoolSize); @@ -510,17 +497,7 @@ public Object run() { } } - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(previousClassLoader); - } else { - doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - currentThread.setContextClassLoader(previousClassLoader); - return null; - } - }); - } + currentThread.setContextClassLoader(previousClassLoader); } long endTime = System.currentTimeMillis(); diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/deployment/EjbJarHandler.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/deployment/EjbJarHandler.java index 79790d7bdb4..74c456b5e0d 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/deployment/EjbJarHandler.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/deployment/EjbJarHandler.java @@ -17,33 +17,28 @@ package org.glassfish.ejb.deployment; +import static java.util.logging.Level.SEVERE; +import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + import com.sun.enterprise.deploy.shared.AbstractArchiveHandler; import com.sun.enterprise.deployment.io.DescriptorConstants; import com.sun.enterprise.deployment.util.DOLUtils; import com.sun.enterprise.loader.ASURLClassLoader; -import com.sun.enterprise.security.ee.perms.PermsArchiveDelegate; -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil; import com.sun.enterprise.util.LocalStringManagerImpl; - import jakarta.inject.Inject; import jakarta.inject.Named; - import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; import java.util.List; -import java.util.logging.Level; import java.util.logging.Logger; - import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; - import org.glassfish.api.deployment.DeploymentContext; import org.glassfish.api.deployment.archive.ArchiveDetector; import org.glassfish.api.deployment.archive.EjbArchiveType; @@ -53,10 +48,6 @@ import org.glassfish.loader.util.ASClassLoaderUtil; import org.jvnet.hk2.annotations.Service; -import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; -import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; -import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; - /** * @author sanjeeb.sahoo@oracle.com @@ -88,25 +79,22 @@ public boolean handles(ReadableArchive archive) throws IOException { public String getVersionIdentifier(ReadableArchive archive) { String versionIdentifier = null; try { - GFEjbJarXMLParser gfXMLParser = new GFEjbJarXMLParser(archive); - versionIdentifier = gfXMLParser.extractVersionIdentifierValue(archive); - } catch (XMLStreamException e) { - LOG.log(Level.SEVERE, e.getMessage()); - } catch (IOException e) { - LOG.log(Level.SEVERE, e.getMessage()); + versionIdentifier = new GFEjbJarXMLParser(archive).extractVersionIdentifierValue(archive); + } catch (XMLStreamException | IOException e) { + LOG.log(SEVERE, e.getMessage()); } + return versionIdentifier; } @Override public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext context) { - PrivilegedAction action = () -> new ASURLClassLoader(parent); - ASURLClassLoader cloader = AccessController.doPrivileged(action); + ASURLClassLoader cloader = new ASURLClassLoader(parent); try { String compatProp = context.getAppProps().getProperty(DeploymentProperties.COMPATIBILITY); - // if user does not specify the compatibility property + // If user does not specify the compatibility property // let's see if it's defined in glassfish-ejb-jar.xml if (compatProp == null) { GFEjbJarXMLParser gfEjbJarXMLParser = new GFEjbJarXMLParser(context.getSource()); @@ -116,7 +104,7 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co } } - // if user does not specify the compatibility property + // If user does not specify the compatibility property // let's see if it's defined in sun-ejb-jar.xml if (compatProp == null) { SunEjbJarXMLParser sunEjbJarXMLParser = new SunEjbJarXMLParser(context.getSourceDir()); @@ -126,7 +114,7 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co } } - // if the compatibility property is set to "v2", we should add + // If the compatibility property is set to "v2", we should add // all the jars under the ejb module root to maintain backward // compatibility of v2 jar visibility if (compatProp != null && compatProp.equals("v2")) { @@ -139,25 +127,15 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co cloader.addURL(context.getSource().getURI().toURL()); cloader.addURL(context.getScratchDir("ejb").toURI().toURL()); - // add libraries referenced from manifest + // Add libraries referenced from manifest for (URL url : getManifestLibraries(context)) { cloader.addURL(url); } - - try { - final DeploymentContext dc = context; - final ClassLoader cl = cloader; - - AccessController.doPrivileged( - new PermsArchiveDelegate.SetPermissionsAction(SMGlobalPolicyUtil.CommponentType.ejb, dc, cl)); - } catch (PrivilegedActionException e) { - throw new SecurityException(e.getException()); - } - } catch (Exception e) { - LOG.log(Level.SEVERE, e.getMessage()); + LOG.log(SEVERE, e.getMessage()); throw new RuntimeException(e); } + return cloader; } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/distributed/DistributedReadOnlyBeanServiceImpl.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/distributed/DistributedReadOnlyBeanServiceImpl.java index 755b9d9b07f..3e8a9fd1651 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/distributed/DistributedReadOnlyBeanServiceImpl.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/distributed/DistributedReadOnlyBeanServiceImpl.java @@ -128,17 +128,7 @@ private void refreshRequestReceived(boolean refreshAll, final ClassLoader prevClassLoader = currentThread.getContextClassLoader(); try { - if(System.getSecurityManager() == null) { - currentThread.setContextClassLoader(info.loader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public java.lang.Object run() { - currentThread.setContextClassLoader(info.loader); - return null; - } - }); - } + currentThread.setContextClassLoader(info.loader); if (! refreshAll) { ByteArrayInputStream bis = null; diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java index 8bb7e382bf6..e244c0fce94 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java @@ -29,7 +29,6 @@ import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.common.SecurityConstants; import com.sun.enterprise.security.common.Util; -import com.sun.enterprise.security.ee.J2EESecurityManager; import com.sun.enterprise.security.integration.AppClientSSL; import com.sun.enterprise.security.ssl.SSLUtils; import jakarta.inject.Inject; @@ -87,13 +86,6 @@ public void initializeSecurity(List tServers, List() { - @Override - public java.lang.Boolean run() { - // if realm is null, LCD will log into the default realm - if (SecurityServicesUtil.getInstance() != null && SecurityServicesUtil.getInstance().isServer() - || Util.isEmbeddedServer()) { - LoginContextDriver.login(user, password, realm); - } else { - int type = SecurityConstants.USERNAME_PASSWORD; - - // should not set realm here - // Bugfix# 6387278. The UsernamePasswordStore - // abstracts the thread-local/global details - UsernamePasswordStore.set(user, password); - - try { - LoginContextDriver.doClientLogin(type, handler); - } finally { - // For security, if thread-local no need to - // save the username/password state - UsernamePasswordStore.resetThreadLocalOnly(); - } - } - return true; + // try to login. + // if realm is null, LCD will log into the default realm + if (SecurityServicesUtil.getInstance() != null && SecurityServicesUtil.getInstance().isServer() || isEmbeddedServer()) { + LoginContextDriver.login(user, password, realm); + } else { + int type = SecurityConstants.USERNAME_PASSWORD; + + // should not set realm here + // Bugfix# 6387278. The UsernamePasswordStore + // abstracts the thread-local/global details + UsernamePasswordStore.set(user, password); + + try { + LoginContextDriver.doClientLogin(type, handler); + } finally { + // For security, if thread-local no need to + // save the username/password state + UsernamePasswordStore.resetThreadLocalOnly(); } - }); + } + + authenticated = true; } catch (Exception e) { logger.log(Level.SEVERE, "prog.login.failed", e); if (errors == true) { // propagate the exception ahead @@ -161,13 +133,13 @@ public java.lang.Boolean run() { } authenticated = false; } + return authenticated; } /* * Use of the char[] as password is encouraged */ - @Deprecated public Boolean login(final String user, final String password) { return login(user, password.toCharArray()); } @@ -206,7 +178,6 @@ public Boolean login(final String user, final char[] password) { /* * Use of the char[] as password is encouraged */ - @Deprecated public Boolean login(final String user, final String password, final String realm, final HttpServletRequest request, final HttpServletResponse response, boolean errors) throws Exception { return login(user, password.toCharArray(), realm, request, response, errors); @@ -234,32 +205,23 @@ public Boolean login(final String user, final char[] password, final String real final HttpServletResponse response, boolean errors) throws Exception { Boolean authenticated = null; try { - // check permission to login - checkLoginPermission(user); - // try to login. doPrivileged is used since application code does - // not have permissions to process the jaas login. - authenticated = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - return webProgrammaticLogin.login(user, password, realm, request, response); - } - }); + // try to login. + authenticated = webProgrammaticLogin.login(user, password, realm, request, response); } catch (Exception e) { if (errors == true) { throw e; } authenticated = false; } + return authenticated; } /* * Use of char[] as password is encouraged */ - @Deprecated public Boolean login(final String user, final String password, final HttpServletRequest request, final HttpServletResponse response) { return login(user, password.toCharArray(), request, response); - } /** @@ -286,6 +248,7 @@ public Boolean login(final String user, final char[] password, final HttpServlet // sanity check will never come here authenticated = false; } + return authenticated; } @@ -317,27 +280,20 @@ public Boolean logout() { */ public Boolean logout(boolean errors) throws Exception { Boolean loggedout = null; - // check logout permission try { - checkLogoutPermission(); - AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public java.lang.Object run() { - // V3:Commentedif (isServer) { - if (SecurityServicesUtil.getInstance() != null && SecurityServicesUtil.getInstance().isServer()) { - LoginContextDriver.logout(); - } else { - // Reset the username/password state on logout - UsernamePasswordStore.reset(); - - LoginContextDriver.doClientLogout(); - // If user try to access a protected resource after here - // then it will prompt for password in appclient or - // just fail in standalone client. - } - return null; - } - }); + if (SecurityServicesUtil.getInstance() != null && SecurityServicesUtil.getInstance().isServer()) { + LoginContextDriver.logout(); + } else { + // Reset the username/password state on logout + UsernamePasswordStore.reset(); + + LoginContextDriver.doClientLogout(); + + // If user try to access a protected resource after here + // then it will prompt for password in appclient or + // just fail in standalone client. + } + loggedout = true; } catch (Exception e) { logger.log(Level.WARNING, "prog.logout.failed", e); @@ -346,6 +302,7 @@ public java.lang.Object run() { } loggedout = false; } + return loggedout; } @@ -360,7 +317,7 @@ public Boolean logout(final HttpServletRequest request, final HttpServletRespons try { loggedout = logout(request, response, false); } catch (Exception e) { - // sanity check, will never come here + // Sanity check, will never come here loggedout = false; } return loggedout; @@ -376,68 +333,24 @@ public Boolean logout(final HttpServletRequest request, final HttpServletRespons * @throws Exception, exception encountered while logging out and if errors == true */ public Boolean logout(final HttpServletRequest request, final HttpServletResponse response, boolean errors) throws Exception { - // check logout permission Boolean loggedout = null; try { - checkLogoutPermission(); - loggedout = AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Boolean run() throws Exception { - return webProgrammaticLogin.logout(request, response); - } - }); + loggedout = webProgrammaticLogin.logout(request, response); } catch (Exception e) { if (errors) { throw e; } loggedout = false; } - return loggedout; - } - - /** - * Check whether caller has login permission. - * - */ - private void checkLoginPermission(String user) throws Exception { - try { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "ProgrammaticLogin.login() called for user: " + user); - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(plLogin); - } - - } catch (Exception e) { - logger.warning("proglogin.noperm"); - throw e; - } - } - - /** - * Check if caller has logout permission. - * - */ - private void checkLogoutPermission() throws Exception { - try { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "ProgrammaticLogin.logout() called."); - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(plLogout); - } - } catch (Exception e) { - logger.warning("prologout.noperm"); - throw e; - } + return loggedout; } private void resolveWebProgrammaticLogin() { - ServiceLocator habitat = SecurityServicesUtil.getInstance().getHabitat(); - this.webProgrammaticLogin = habitat.getService(WebProgrammaticLogin.class); + this.webProgrammaticLogin = + SecurityServicesUtil.getInstance() + .getServiceLocator() + .getService(WebProgrammaticLogin.class); } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/cache/PermissionCacheFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/cache/PermissionCacheFactory.java index 1ec0feb3c98..c27df411528 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/cache/PermissionCacheFactory.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/cache/PermissionCacheFactory.java @@ -16,7 +16,6 @@ package com.sun.enterprise.security.ee.authorize.cache; -import com.sun.enterprise.security.ee.J2EESecurityManager; import java.security.CodeSource; import java.security.Permission; import java.util.Hashtable; @@ -144,13 +143,6 @@ public static synchronized PermissionCache removePermissionCache(PermissionCache public static synchronized void resetCaches() { supportsReuse = true; - java.lang.SecurityManager sm = System.getSecurityManager(); - if (sm != null && sm instanceof J2EESecurityManager) { - if (!((J2EESecurityManager) sm).cacheEnabled()) { - ((J2EESecurityManager) sm).enablePermissionCache(securityManagerCache); - } - } - Iterator iter = cacheMap.values().iterator(); while (iter.hasNext()) { Object cache = iter.next(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/DeclaredPermissionsProcessor.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/DeclaredPermissionsProcessor.java deleted file mode 100644 index 096881a7bf0..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/DeclaredPermissionsProcessor.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import java.net.MalformedURLException; -import java.security.PermissionCollection; - -import org.glassfish.api.deployment.DeploymentContext; - -public class DeclaredPermissionsProcessor extends PermissionsProcessor { - - private PermissionCollection orginalDeclaredPc; - private PermissionCollection declaredPc; - - public DeclaredPermissionsProcessor(SMGlobalPolicyUtil.CommponentType type, DeploymentContext dc, PermissionCollection declPc) - throws SecurityException { - super(type, dc); - orginalDeclaredPc = declPc; - convertPathDeclaredPerms(); - } - - /** - * get the declared permissions which have the file path adjusted for the right module - * - * @return adjusted declared permissions - */ - public PermissionCollection getAdjustedDeclaredPermissions() { - return declaredPc; - } - - // conver the path for permissions - private void convertPathDeclaredPerms() throws SecurityException { - - // revise the filepermission's path - try { - declaredPc = processPermisssonsForPath(orginalDeclaredPc, context); - } catch (MalformedURLException e) { - throw new SecurityException(e); - } - - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/EarEEPermissionsProcessor.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/EarEEPermissionsProcessor.java deleted file mode 100644 index aea2ab4cf32..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/EarEEPermissionsProcessor.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2022 Contributors to the Eclipse Foundation - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil.CommponentType; -import java.net.MalformedURLException; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Permissions; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; - -import org.glassfish.api.deployment.DeploymentContext; - -public class EarEEPermissionsProcessor extends PermissionsProcessor { - - // map recording the 'Jakarta EE component type' to its EE adjusted granted permissions - private static final Map compTypeToEEGarntsMap = new HashMap<>(); - - public EarEEPermissionsProcessor(DeploymentContext dc) throws SecurityException { - - super(SMGlobalPolicyUtil.CommponentType.ear, dc); - - try { - convertEEPermissionPaths(CommponentType.ejb); - convertEEPermissionPaths(CommponentType.war); - convertEEPermissionPaths(CommponentType.rar); - convertEEPermissionPaths(CommponentType.car); - - // combine all ee permissions then assign to ear - combineAllEEPermisssonsForEar(); - - } catch (MalformedURLException e) { - throw new SecurityException(e); - } - - } - - /** - * get the EE permissions which have the file path adjusted for the right module - * - * @return adjusted EE permissions - */ - public PermissionCollection getAdjustedEEPermission(CommponentType type) { - return compTypeToEEGarntsMap.get(type); - } - - public Map getAllAdjustedEEPermission() { - return compTypeToEEGarntsMap; - } - - // conver the path for permissions - private void convertEEPermissionPaths(CommponentType cmpType) throws MalformedURLException { - // get server suppled default policy - PermissionCollection defWarPc = SMGlobalPolicyUtil.getEECompGrantededPerms(cmpType); - - // revise the filepermission's path - PermissionCollection eePc = processPermisssonsForPath(defWarPc, context); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Revised permissions = " + eePc); - } - - compTypeToEEGarntsMap.put(cmpType, eePc); - } - - private PermissionCollection combineAllEEPermisssonsForEar() { - - if (compTypeToEEGarntsMap == null) { - return null; - } - - Permissions allEEPerms = new Permissions(); - - addPermissions(allEEPerms, getAdjustedEEPermission(CommponentType.war)); - addPermissions(allEEPerms, getAdjustedEEPermission(CommponentType.ejb)); - addPermissions(allEEPerms, getAdjustedEEPermission(CommponentType.rar)); - // addPermissions(allEEPerms, getAdjustedEEPermission(CommponentType.car)); - - compTypeToEEGarntsMap.put(CommponentType.ear, allEEPerms); - - return allEEPerms; - } - - private void addPermissions(Permissions combined, PermissionCollection toAdd) { - - if (toAdd == null) { - return; - } - - Enumeration enumAdd = toAdd.elements(); - while (enumAdd.hasMoreElements()) { - Permission p = enumAdd.nextElement(); - combined.add(p); - } - - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/ModuleEEPermissionsProcessor.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/ModuleEEPermissionsProcessor.java deleted file mode 100644 index 3941393ee1f..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/ModuleEEPermissionsProcessor.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import java.net.MalformedURLException; -import java.security.PermissionCollection; -import java.util.logging.Level; - -import org.glassfish.api.deployment.DeploymentContext; - -public class ModuleEEPermissionsProcessor extends PermissionsProcessor { - - private PermissionCollection eePc; - - public ModuleEEPermissionsProcessor(SMGlobalPolicyUtil.CommponentType type, DeploymentContext dc) throws SecurityException { - super(type, dc); - - try { - convertEEPermissionPaths(); - } catch (MalformedURLException e) { - throw new SecurityException(e); - } - } - - /** - * get the EE permissions which have the file path adjusted for the right module - * - * @return adjusted EE permissions - */ - public PermissionCollection getAdjustedEEPermission() { - return eePc; - } - - // conver the path for permissions - private void convertEEPermissionPaths() throws MalformedURLException { - // get server suppled default policy - PermissionCollection defWarPc = SMGlobalPolicyUtil.getEECompGrantededPerms(type); - - // revise the filepermission's path - eePc = processPermisssonsForPath(defWarPc, context); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Revised permissions = " + eePc); - } - - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermissionXMLParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermissionXMLParser.java deleted file mode 100644 index 1a5604ea567..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermissionXMLParser.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2022, 2023 Contributors to the Eclipse Foundation - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import com.sun.enterprise.security.integration.PermissionCreator; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Permissions; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLResolver; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; -import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; -import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; - -/** - * Paser to parse permissions.xml packaged in a ear or in a standalone module - */ -public class PermissionXMLParser { - - private static XMLInputFactory xmlInputFactory; - static { - xmlInputFactory = XMLInputFactory.newFactory(); - xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true); - - // set an zero-byte XMLResolver as IBM JDK does not take SUPPORT_DTD=false - // unless there is a jvm option com.ibm.xml.xlxp.support.dtd.compat.mode=false - xmlInputFactory.setXMLResolver(new XMLResolver() { - @Override - public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { - - return new ByteArrayInputStream(new byte[0]); - } - }); - } - - private XMLStreamReader parser; - private final PermissionCollection pc = new Permissions(); - private final PermissionCollection permissionCollectionToBeRestricted; - - - public PermissionXMLParser(InputStream input, PermissionCollection permissionCollectionToBeRestricted) - throws XMLStreamException { - this.permissionCollectionToBeRestricted = permissionCollectionToBeRestricted; - init(input); - } - - - protected static XMLInputFactory getXMLInputFactory() { - return xmlInputFactory; - } - - /** - * This method will parse the input stream and set the XMLStreamReader object for latter use. - * - * @param input InputStream - * @throws XMLStreamException; - */ - protected void read(InputStream input) throws XMLStreamException { - parser = getXMLInputFactory().createXMLStreamReader(input); - - int event = 0; - String classname = null; - String target = null; - String actions = null; - while (parser.hasNext() && (event = parser.next()) != END_DOCUMENT) { - if (event == START_ELEMENT) { - String name = parser.getLocalName(); - if ("permission".equals(name)) { - classname = null; - target = null; - actions = null; - } else if ("class-name".equals(name)) { - classname = parser.getElementText(); - } else if ("name".equals(name)) { - target = parser.getElementText(); - } else if ("actions".equals(name)) { - actions = parser.getElementText(); - } else if ("permissions".equals(name)) { - // continue trough subtree - } else { - skipSubTree(name); - } - } else if (event == END_ELEMENT) { - String name = parser.getLocalName(); - if ("permission".equals(name)) { - if (classname != null && !classname.isEmpty()) { - addPermission(classname, target, actions); - } - } - } - } - } - - protected void init(InputStream input) throws XMLStreamException { - - try { - read(input); - } finally { - if (parser != null) { - try { - parser.close(); - } catch (Exception ex) { - // ignore - } - } - } - } - - protected void skipRoot(String name) throws XMLStreamException { - while (true) { - int event = parser.next(); - if (event == START_ELEMENT) { - String localName = parser.getLocalName(); - if (!name.equals(localName)) { - // String msg = rb.getString(UNEXPECTED_ELEMENT_IN_XML); - // msg = MessageFormat.format(msg, new Object[] { name, - // localName }); - // throw new XMLStreamException(msg); - throw new XMLStreamException("Unexpected element with name " + name); - } - return; - } - } - } - - protected void skipSubTree(String name) throws XMLStreamException { - while (true) { - int event = parser.next(); - if (event == END_DOCUMENT) { - throw new XMLStreamException("Unexpected element with name " + name); - } - if (event == END_ELEMENT && name.equals(parser.getLocalName())) { - return; - } - } - } - - private void addPermission(String classname, String target, String actions) { - try { - Permission pm = PermissionCreator.getInstance(classname, target, actions); - if (pm != null) { - if (permissionCollectionToBeRestricted != null && permissionCollectionToBeRestricted.implies(pm)) { - throw new SecurityException("Restricted Permission Declared - fail deployment!"); - } - pc.add(pm); - } - } catch (ReflectiveOperationException e) { - throw new SecurityException(e); - } - } - - protected PermissionCollection getPermissions() { - return pc; - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermissionsProcessor.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermissionsProcessor.java deleted file mode 100644 index 4b44e017369..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermissionsProcessor.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import java.io.File; -import java.io.FilePermission; -import java.net.MalformedURLException; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Permissions; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.glassfish.api.deployment.DeploymentContext; - -import com.sun.logging.LogDomains; - -public class PermissionsProcessor { - - public static final String CURRENT_FOLDER = "*"; - - public static final String TEMP_FOLDER = "SERVLET-CONTEXT-TEMPDIR"; - - protected DeploymentContext context; - protected SMGlobalPolicyUtil.CommponentType type; - - protected static final Logger logger = Logger.getLogger(LogDomains.SECURITY_LOGGER); - - public PermissionsProcessor(SMGlobalPolicyUtil.CommponentType type, DeploymentContext dc) throws SecurityException { - - this.type = type; - this.context = dc; - - } - - protected static PermissionCollection processPermisssonsForPath(PermissionCollection originalPC, DeploymentContext dc) - throws MalformedURLException { - - if (originalPC == null) { - return originalPC; - } - - Permissions revisedPC = new Permissions(); - - Enumeration pcEnum = originalPC.elements(); - while (pcEnum.hasMoreElements()) { - Permission perm = pcEnum.nextElement(); - if (perm instanceof FilePermission) { - processFilePermission(revisedPC, dc, (FilePermission) perm); - } else { - revisedPC.add(perm); - } - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Revised permissions = " + revisedPC); - } - - return revisedPC; - } - - // for file permission, make the necessary path change, then add permssion to classloader - protected static void processFilePermission(PermissionCollection revisedPC, DeploymentContext dc, FilePermission fp) - throws MalformedURLException { - - if (isFilePermforCurrentDir(fp)) { - addFilePermissionsForCurrentDir(revisedPC, dc, fp); - } else if (isFilePermforTempDir(fp)) { - convertTempDirPermission(revisedPC, dc, fp); - } else { - revisedPC.add(fp); - } - } - - // check if a FilePermssion with target path as the "current" - protected static boolean isFilePermforCurrentDir(FilePermission fp) { - - if (fp == null) { - return false; - } - - String name = fp.getName(); - if (!CURRENT_FOLDER.equals(name)) { - return false; - } - - return true; - } - - // check if a FilePermssion with target path as the "servlet temp dir" - protected static boolean isFilePermforTempDir(FilePermission fp) { - - if (fp == null) { - return false; - } - - String name = fp.getName(); - if (!TEMP_FOLDER.equals(name)) { - return false; - } - - return true; - } - - // add the current folder for the file permission - protected static void addFilePermissionsForCurrentDir(PermissionCollection revisedPC, DeploymentContext context, FilePermission perm) - throws MalformedURLException { - - if (!isFilePermforCurrentDir(perm)) { - // not recognized, add it as is - revisedPC.add(perm); - return; - } - - String actions = perm.getActions(); - - String rootDir = context.getSource().getURI().toURL().toString(); - Permission rootDirPerm = new FilePermission(rootDir, actions); - revisedPC.add(rootDirPerm); - Permission rootPerm = new FilePermission(rootDir + File.separator + "-", actions); - revisedPC.add(rootPerm); - - if (context.getScratchDir("ejb") != null) { - String ejbTmpDir = context.getScratchDir("ejb").toURI().toURL().toString(); - Permission ejbDirPerm = new FilePermission(ejbTmpDir, actions); - revisedPC.add(ejbDirPerm); - Permission ejbPerm = new FilePermission(ejbTmpDir + File.separator + "-", actions); - revisedPC.add(ejbPerm); - } - - if (context.getScratchDir("jsp") != null) { - String jspdir = context.getScratchDir("jsp").toURI().toURL().toString(); - Permission jpsDirPerm = new FilePermission(jspdir, actions); - revisedPC.add(jpsDirPerm); - Permission jpsPerm = new FilePermission(jspdir + File.separator + "-", actions); - revisedPC.add(jpsPerm); - } - } - - // convert 'temp' dir to the absolute path for permission of 'temp' path - protected static Permission convertTempDirPermission(PermissionCollection revisedPC, DeploymentContext context, FilePermission perm) - throws MalformedURLException { - - if (!isFilePermforTempDir(perm)) { - return perm; - } - - String actions = perm.getActions(); - - if (context.getScratchDir("jsp") != null) { - String jspdir = context.getScratchDir("jsp").toURI().toURL().toString(); - Permission jspDirPerm = new FilePermission(jspdir, actions); - revisedPC.add(jspDirPerm); - Permission jspPerm = new FilePermission(jspdir + File.separator + "-", actions); - revisedPC.add(jspPerm); - return jspPerm; - } - - return perm; - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermsArchiveDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermsArchiveDelegate.java deleted file mode 100644 index 0c40bcaea43..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/PermsArchiveDelegate.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import java.io.File; -import java.io.FileNotFoundException; -import java.security.PermissionCollection; -import java.security.PrivilegedExceptionAction; - -import javax.xml.stream.XMLStreamException; - -import org.glassfish.api.deployment.DeploymentContext; -import org.glassfish.internal.deployment.ExtendedDeploymentContext; - -import com.sun.enterprise.security.integration.DDPermissionsLoader; - -public class PermsArchiveDelegate { - - /** - * Get the application or module packaged permissions - * - * @param type the type of the module, this is used to check the configured restriction for the type - * @param context the deployment context - * @return the module or app declared permissions - * @throws SecurityException if permissions.xml has syntax failure, or failed for restriction check - */ - public static PermissionCollection getDeclaredPermissions(SMGlobalPolicyUtil.CommponentType type, DeploymentContext context) - throws SecurityException { - - try { - File base = new File(context.getSource().getURI()); - - XMLPermissionsHandler pHdlr = new XMLPermissionsHandler(base, type); - - PermissionCollection declaredPerms = pHdlr.getAppDeclaredPermissions(); - - // further process the permissions for file path adjustment - DeclaredPermissionsProcessor dpp = new DeclaredPermissionsProcessor(type, context, declaredPerms); - - PermissionCollection revisedWarDeclaredPerms = dpp.getAdjustedDeclaredPermissions(); - - return revisedWarDeclaredPerms; - } catch (XMLStreamException | SecurityException | FileNotFoundException e) { - throw new SecurityException(e); - } - - } - - /** - * Get the EE permissions for the spcified module type - * - * @param type module type - * @param dc the deployment context - * @return the ee permissions - */ - public static PermissionCollection processEEPermissions(SMGlobalPolicyUtil.CommponentType type, DeploymentContext dc) { - - ModuleEEPermissionsProcessor eePp = new ModuleEEPermissionsProcessor(type, dc); - - PermissionCollection eePc = eePp.getAdjustedEEPermission(); - - return eePc; - } - - /** - * Get the declared permissions and EE permissions, then add them to the classloader - * - * @param type module type - * @param context deployment context - * @param classloader throws AccessControlException if caller has no privilege - */ - public static void processModuleDeclaredAndEEPemirssions(SMGlobalPolicyUtil.CommponentType type, DeploymentContext context, - ClassLoader classloader) throws SecurityException { - - if (System.getSecurityManager() != null) { - - if (!(classloader instanceof DDPermissionsLoader)) { - return; - } - - if (!(context instanceof ExtendedDeploymentContext)) { - return; - } - - DDPermissionsLoader ddcl = (DDPermissionsLoader) classloader; - - if (((ExtendedDeploymentContext) context).getParentContext() == null) { - - PermissionCollection declPc = getDeclaredPermissions(type, context); - ddcl.addDeclaredPermissions(declPc); - } - - PermissionCollection eePc = processEEPermissions(type, context); - - ddcl.addEEPermissions(eePc); - } - } - - public static class SetPermissionsAction implements PrivilegedExceptionAction { - - private SMGlobalPolicyUtil.CommponentType type; - private DeploymentContext context; - private ClassLoader cloader; - - public SetPermissionsAction(SMGlobalPolicyUtil.CommponentType type, DeploymentContext dc, ClassLoader cl) { - this.type = type; - this.context = dc; - this.cloader = cl; - } - - @Override - public Object run() throws SecurityException { - - processModuleDeclaredAndEEPemirssions(type, context, cloader); - return null; - } - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/SMGlobalPolicyUtil.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/SMGlobalPolicyUtil.java deleted file mode 100644 index b61fb46c877..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/SMGlobalPolicyUtil.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation - * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.AllPermission; -import java.security.CodeSource; -import java.security.NoSuchAlgorithmException; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Policy; -import java.security.URIParameter; -import java.security.cert.Certificate; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.sun.logging.LogDomains; - -/** - * Utility class to load the EE permissions, EE restrictions, and check restrictions for a given permission set - */ -public class SMGlobalPolicyUtil { - - static Logger logger = Logger.getLogger(LogDomains.SECURITY_LOGGER); - - /** - * Jakarta EE Component type supporting the use of declared permissions - */ - public enum CommponentType { - ear, ejb, war, rar, car - } - - private enum PolicyType { - /** - * Configured EE permissions in the domain - */ - EEGranted, - - /** - * Configured EE restriction list in the domain - */ - EERestricted, - - /** - * Configured domain allowed list - */ - ServerAllowed - } - - /** - * This is the file storing the default permissions granted to each component type - */ - public static final String EE_GRANT_FILE = "javaee.server.policy"; - - /** - * This is the file storing the restricted permissions for each component type; Any permissions declared in this list - * can not be used by the application - */ - public static final String EE_RESTRICTED_FILE = "restrict.server.policy"; - - /** - * This is the file storing the allowed permissions for each component type A permission listed in this file may not be - * used but the application, but any application declared permission must exist in this list; - */ - public static final String SERVER_ALLOWED_FILE = "restrict.server.policy"; - - protected static final String SYS_PROP_JAVA_SEC_POLICY = "java.security.policy"; - - /** - * Code source URL representing Ejb type - */ - public static final String EJB_TYPE_CODESOURCE = "file:/module/Ejb"; - /** - * Code source URL representing Web type - */ - public static final String WEB_TYPE_CODESOURCE = "file:/module/Web"; - /** - * Code source URL representing Rar type - */ - public static final String RAR_TYPE_CODESOURCE = "file:/module/Rar"; - /** - * Code source URL representing App client type - */ - public static final String CLIENT_TYPE_CODESOURCE = "file:/module/Car"; - - /** - * Code source URL representing Ear type - */ - public static final String EAR_TYPE_CODESOURCE = "file:/module/Ear"; - - public static final String EAR_CLASS_LOADER = "org.glassfish.javaee.full.deployment.EarClassLoader"; - - // map recording the 'Jakarta EE component type' to its EE granted permissions - private static final Map compTypeToEEGarntsMap = new HashMap<>(); - - // map recording the 'Jakarta EE component type' to its EE restricted permissions - private static final Map compTypeToEERestrictedMap = new HashMap<>(); - - // map recording the 'Jakarta EE component type' to its allowed permissions - private static final Map compTypeToServAllowedMap = new HashMap<>(); - - private static boolean eeGrantedPolicyInitDone = false; - - protected static final String domainCfgFolder = getJavaPolicyFolder() + File.separator; - - private static final AllPermission ALL_PERM = new AllPermission(); - - // JDK-8173082: JDK required permissions needed by applications using java.desktop module - private static final List JDK_REQUIRED_PERMISSIONS = Stream.of("accessClassInPackage.com.sun.beans", - "accessClassInPackage.com.sun.beans.*", "accessClassInPackage.com.sun.java.swing.plaf.*", "accessClassInPackage.com.apple.*") - .collect(Collectors.toList()); - - // convert a string type to the CommponentType - public static CommponentType convertComponentType(String type) { - - return Enum.valueOf(CommponentType.class, type); - } - - /** - * Get the default granted permissions of a specified component type - * - * @param type Jakarta EE component type - * @return the permission set granted to the specified component - */ - public static PermissionCollection getEECompGrantededPerms(CommponentType type) { - initDefPolicy(); - return compTypeToEEGarntsMap.get(type); - } - - /** - * Get the default granted permissions of a specified component type - * - * @param type Jakarta EE component type such as ejb, war, rar, car, ear - * @return - */ - public static PermissionCollection getEECompGrantededPerms(String type) { - CommponentType compType = convertComponentType(type); - return getEECompGrantededPerms(compType); - } - - /** - * Get the restricted permission set of a specified component type on the server - * - * @param type Jakarta EE component type - * @return the restricted permission set of the specified component type on the server - */ - public static PermissionCollection getCompRestrictedPerms(CommponentType type) { - initDefPolicy(); - return compTypeToEERestrictedMap.get(type); - } - - public static PermissionCollection getCompRestrictedPerms(String type) { - CommponentType compType = convertComponentType(type); - return getCompRestrictedPerms(compType); - } - - private synchronized static void initDefPolicy() { - - try { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("defGrantedPolicyInitDone= " + eeGrantedPolicyInitDone); - } - - if (eeGrantedPolicyInitDone) { - return; - } - - eeGrantedPolicyInitDone = true; - - loadServerPolicy(PolicyType.EEGranted); - - loadServerPolicy(PolicyType.EERestricted); - - loadServerPolicy(PolicyType.ServerAllowed); - - checkDomainRestrictionsForDefaultPermissions(); - - } catch (FileNotFoundException e) { - // ignore: the permissions files not exist - } catch (IOException | NoSuchAlgorithmException | URISyntaxException e) { - logger.warning(e.getMessage()); - throw new RuntimeException(e); - } - } - - private static String getJavaPolicyFolder() { - - String policyPath = System.getProperty(SYS_PROP_JAVA_SEC_POLICY); - - if (policyPath == null) { - return null; - } - - File pf = new File(policyPath); - - return pf.getParent(); - } - - private static void loadServerPolicy(PolicyType policyType) throws IOException, NoSuchAlgorithmException, URISyntaxException { - if (policyType == null) { - return; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("PolicyType= " + policyType); - } - - String policyFilename = null; - Map policyMap = null; - - switch (policyType) { - case EEGranted: - policyFilename = domainCfgFolder + EE_GRANT_FILE; - policyMap = compTypeToEEGarntsMap; - break; - case EERestricted: - policyFilename = domainCfgFolder + EE_RESTRICTED_FILE; - policyMap = compTypeToEERestrictedMap; - break; - case ServerAllowed: - policyFilename = domainCfgFolder + SERVER_ALLOWED_FILE; - policyMap = compTypeToServAllowedMap; - break; - } - - if (policyFilename == null || policyMap == null) { - throw new IllegalArgumentException("Unrecognized policy type: " + policyType); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("policyFilename= " + policyFilename); - } - - if (!new File(policyFilename).exists()) { - return; - } - - URL furl = new URL("file:" + policyFilename); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loading policy from " + furl); - } - - Policy pf = Policy.getInstance("JavaPolicy", new URIParameter(furl.toURI())); - - CodeSource cs = new CodeSource(new URL(EJB_TYPE_CODESOURCE), (Certificate[]) null); - PermissionCollection pc = pf.getPermissions(cs); - policyMap.put(CommponentType.ejb, pc); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loaded EJB policy = " + pc); - } - - cs = new CodeSource(new URL(WEB_TYPE_CODESOURCE), (Certificate[]) null); - pc = pf.getPermissions(cs); - policyMap.put(CommponentType.war, pc); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loaded WEB policy =" + pc); - } - - cs = new CodeSource(new URL(RAR_TYPE_CODESOURCE), (Certificate[]) null); - pc = pf.getPermissions(cs); - policyMap.put(CommponentType.rar, pc); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loaded rar policy =" + pc); - } - - cs = new CodeSource(new URL(CLIENT_TYPE_CODESOURCE), (Certificate[]) null); - pc = pf.getPermissions(cs); - policyMap.put(CommponentType.car, pc); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loaded car policy =" + pc); - } - - cs = new CodeSource(new URL(EAR_TYPE_CODESOURCE), (Certificate[]) null); - pc = pf.getPermissions(cs); - policyMap.put(CommponentType.ear, pc); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loaded ear policy =" + pc); - } - - } - - // this checks default permissions against restrictions - private static void checkDomainRestrictionsForDefaultPermissions() throws SecurityException { - - checkEETypePermsAgainstServerRestiction(CommponentType.ejb); - checkEETypePermsAgainstServerRestiction(CommponentType.war); - checkEETypePermsAgainstServerRestiction(CommponentType.rar); - checkEETypePermsAgainstServerRestiction(CommponentType.car); - checkEETypePermsAgainstServerRestiction(CommponentType.ear); - } - - private static void checkEETypePermsAgainstServerRestiction(CommponentType type) throws SecurityException { - - checkRestriction(compTypeToEEGarntsMap.get(type), compTypeToEERestrictedMap.get(type)); - } - - public static void checkRestriction(CommponentType type, PermissionCollection declaredPC) throws SecurityException { - - checkRestriction(declaredPC, getCompRestrictedPerms(type)); - } - - /** - * Checks a permissions set against a restriction set - * - * @param declaredPC - * @param restrictedPC - * @return true for passed - * @throws SecurityException is thrown if violation detected - */ - public static void checkRestriction(PermissionCollection declaredPC, PermissionCollection restrictedPC) throws SecurityException { - - if (restrictedPC == null || declaredPC == null) { - return; - } - - // check declared does not contain restricted - checkContains(declaredPC, restrictedPC); - - // check restricted does not contain declared - checkContains(restrictedPC, declaredPC); - - } - - // check if permissionCollection toBeCheckedPC is contained/implied by containPC - private static void checkContains(PermissionCollection containPC, PermissionCollection toBeCheckedPC) throws SecurityException { - - if (containPC == null || toBeCheckedPC == null) { - return; - } - - Enumeration checkEnum = toBeCheckedPC.elements(); - while (checkEnum.hasMoreElements()) { - Permission p = checkEnum.nextElement(); - if (!JDK_REQUIRED_PERMISSIONS.contains(p.getName()) && containPC.implies(p)) { - throw new SecurityException("Restricted permission " + p + " is declared or implied in the " + containPC); - } - } - } - - /** - * Check a permission set against a restriction of a component type - * - * @param declaredPC - * @param type - * @return - * @throws SecurityException - */ - public static void checkRestrictionOfComponentType(PermissionCollection declaredPC, CommponentType type) throws SecurityException { - - if (CommponentType.ear == type) { - checkRestrictionOfEar(declaredPC); - } - - PermissionCollection restrictedPC = compTypeToEERestrictedMap.get(type); - - checkRestriction(declaredPC, restrictedPC); - } - - // for ear type, check evrything - public static void checkRestrictionOfEar(PermissionCollection declaredPC) throws SecurityException { - - PermissionCollection pc = compTypeToEERestrictedMap.get(CommponentType.ejb); - if (pc != null) { - SMGlobalPolicyUtil.checkRestriction(declaredPC, pc); - } - - pc = compTypeToEERestrictedMap.get(CommponentType.war); - if (pc != null) { - SMGlobalPolicyUtil.checkRestriction(declaredPC, pc); - } - - pc = compTypeToEERestrictedMap.get(CommponentType.rar); - if (pc != null) { - SMGlobalPolicyUtil.checkRestriction(declaredPC, pc); - } - - pc = compTypeToEERestrictedMap.get(CommponentType.car); - if (pc != null) { - SMGlobalPolicyUtil.checkRestriction(declaredPC, pc); - } - - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/VoidPermission.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/VoidPermission.java deleted file mode 100644 index 649920cddc6..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/VoidPermission.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import java.security.BasicPermission; -import java.security.Permission; - -/** - * a class used on permission restriction list to imply "No 'AllPermission' allowed" in permissions.xml. - * - * This permission can not imply any other permission - */ -public class VoidPermission extends BasicPermission { - - private static final long serialVersionUID = 5535516010244462567L; - - public VoidPermission() { - this("VoidPermmission"); - } - - public VoidPermission(String name) { - super(name); - - } - - public VoidPermission(String name, String actions) { - super(name, actions); - } - - @Override - public boolean implies(Permission permission) { - // always return false - return false; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/XMLPermissionsHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/XMLPermissionsHandler.java deleted file mode 100644 index 886bd50a9e2..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/perms/XMLPermissionsHandler.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2022 Contributors to the Eclipse Foundation - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import com.sun.enterprise.config.serverbeans.DasConfig; -import com.sun.enterprise.deployment.PermissionsDescriptor; -import com.sun.enterprise.deployment.io.PermissionsDeploymentDescriptorFile; -import com.sun.logging.LogDomains; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.security.PermissionCollection; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.xml.stream.XMLStreamException; - -import org.glassfish.hk2.api.ServiceLocator; -import org.glassfish.internal.api.Globals; -import org.xml.sax.SAXException; - -/** - * Utility class to get declared permissions - */ -public class XMLPermissionsHandler { - - private static final Logger LOG = Logger.getLogger(LogDomains.SECURITY_LOGGER); - private static final String PERMISSIONS_XML = "META-INF/permissions.xml"; - - private static ServiceLocator serviceLocator = Globals.getDefaultBaseServiceLocator(); - - private DasConfig dasConfig; - private PermissionCollection declaredPermXml; - private final SMGlobalPolicyUtil.CommponentType compType; - - public XMLPermissionsHandler(File base, SMGlobalPolicyUtil.CommponentType type) - throws XMLStreamException, FileNotFoundException { - this.compType = type; - - configureAppDeclaredPermissions(base); - checkServerRestrictedPermissions(); - } - - - public XMLPermissionsHandler(InputStream restrictPermInput, InputStream allowedPermInput, - SMGlobalPolicyUtil.CommponentType type) throws XMLStreamException, FileNotFoundException { - this.compType = type; - - configureAppDeclaredPermissions(allowedPermInput); - checkServerRestrictedPermissions(); - } - - - public PermissionCollection getAppDeclaredPermissions() { - return declaredPermXml; - } - - - private void configureAppDeclaredPermissions(File base) { - - File permissionsXml = new File(base.getAbsolutePath(), PERMISSIONS_XML); - - if (permissionsXml.exists()) { - FileInputStream fi = null; - try { - // this one uses the Node approach - PermissionsDeploymentDescriptorFile pddf = new PermissionsDeploymentDescriptorFile(); - - if (serviceLocator != null) { - dasConfig = serviceLocator.getService(DasConfig.class); - if (dasConfig != null) { - String xmlValidationLevel = dasConfig.getDeployXmlValidation(); - if (xmlValidationLevel.equals("none")) { - pddf.setXMLValidation(false); - } else { - pddf.setXMLValidation(true); - } - pddf.setXMLValidationLevel(xmlValidationLevel); - } - } - - fi = new FileInputStream(permissionsXml); - PermissionsDescriptor pd = (PermissionsDescriptor) pddf.read(fi); - - declaredPermXml = pd.getDeclaredPermissions(); - LOG.log(Level.FINE, "App declared permission = {0}", declaredPermXml); - - } catch (SAXException | IOException e) { - throw new SecurityException(e); - } finally { - if (fi != null) { - try { - fi.close(); - } catch (IOException e) { - } - } - } - } - } - - private void configureAppDeclaredPermissions(InputStream permInput) throws XMLStreamException, FileNotFoundException { - if (permInput != null) { - // this one has no shchema check (for client) - PermissionXMLParser parser = new PermissionXMLParser(permInput, null); - this.declaredPermXml = parser.getPermissions(); - LOG.log(Level.FINE, "App declared permission = {0}", declaredPermXml); - } - } - - // check the app declared permissions against server restricted policy - private void checkServerRestrictedPermissions() { - - if (this.declaredPermXml == null) { - return; - } - - if (compType == null) { - return; - } - - SMGlobalPolicyUtil.checkRestrictionOfComponentType(declaredPermXml, this.compType); - } - -} diff --git a/appserver/security/core-ee/src/test/java/com/sun/enterprise/security/ee/perms/SMGlobalPolicyUtilTest.java b/appserver/security/core-ee/src/test/java/com/sun/enterprise/security/ee/perms/SMGlobalPolicyUtilTest.java deleted file mode 100644 index a7f200f531b..00000000000 --- a/appserver/security/core-ee/src/test/java/com/sun/enterprise/security/ee/perms/SMGlobalPolicyUtilTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2021 Contributors to the Eclipse Foundation - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FilePermission; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Paths; -import java.security.CodeSource; -import java.security.NoSuchAlgorithmException; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Policy; -import java.security.URIParameter; -import java.security.cert.Certificate; -import java.util.Enumeration; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -public class SMGlobalPolicyUtilTest { - - private static final String plfile = "server.policy"; - - @BeforeAll - public static void setUpBeforeClass() throws Exception { - String absolutePath = getFile(plfile).getAbsolutePath(); - System.out.println("policy path = " + absolutePath); - System.setProperty(SMGlobalPolicyUtil.SYS_PROP_JAVA_SEC_POLICY, absolutePath); - } - - private static File getFile(final String fileName) throws URISyntaxException { - final URL url = SMGlobalPolicyUtilTest.class.getResource(fileName); - assertNotNull(url, "url"); - assertEquals("file", url.getProtocol(), "url.protocol"); - final File file = Paths.get(url.toURI()).toFile(); - assertTrue(file.exists(), "File doesn't exist: " + file); - return file; - } - - @Test - public void testSystemPolicyPath() { - System.out.println("path= " + SMGlobalPolicyUtil.domainCfgFolder); - - assertNotNull(SMGlobalPolicyUtil.domainCfgFolder); - } - - @Test - public void testTYpeConvert() { - SMGlobalPolicyUtil.CommponentType componentType = SMGlobalPolicyUtil.convertComponentType("ejb"); - System.out.println("Converted type = " + componentType); - assertEquals(SMGlobalPolicyUtil.CommponentType.ejb, componentType, "Converted type should be Ejb"); - - componentType = SMGlobalPolicyUtil.convertComponentType("ear"); - System.out.println("Converted type = " + componentType); - assertEquals(SMGlobalPolicyUtil.CommponentType.ear, componentType, "Converted type should be ear"); - - componentType = SMGlobalPolicyUtil.convertComponentType("war"); - System.out.println("Converted type = " + componentType); - assertEquals(SMGlobalPolicyUtil.CommponentType.war, componentType, "Converted type should be web"); - - componentType = SMGlobalPolicyUtil.convertComponentType("rar"); - System.out.println("Converted type = " + componentType); - assertEquals(SMGlobalPolicyUtil.CommponentType.rar, componentType, "Converted type should be rar"); - - componentType = SMGlobalPolicyUtil.convertComponentType("car"); - System.out.println("Converted type = " + componentType); - assertEquals(SMGlobalPolicyUtil.CommponentType.car, componentType, "Converted type should be car"); - - assertThrows(IllegalArgumentException.class, () -> SMGlobalPolicyUtil.convertComponentType("")); - assertThrows(IllegalArgumentException.class, () -> SMGlobalPolicyUtil.convertComponentType("bla")); - assertThrows(NullPointerException.class, () -> SMGlobalPolicyUtil.convertComponentType(null)); - } - - - @Test - public void testPolicyLoading() throws NoSuchAlgorithmException, MalformedURLException, URISyntaxException { - System.out.println("Starting testDefPolicy loading - ee"); - - PermissionCollection defaultPC = Policy.getInstance("JavaPolicy", - new URIParameter(SMGlobalPolicyUtilTest.class.getResource("nobody.policy").toURI())) - .getPermissions(new CodeSource(new URL("file:/module/ALL"), (Certificate[]) null)); - - int defaultCount = dumpPermissions("Grant", "ALL", defaultPC); - assertEquals(4, defaultCount); - PermissionCollection defEjbGrantededPC - = SMGlobalPolicyUtil.getEECompGrantededPerms(SMGlobalPolicyUtil.CommponentType.ejb); - int count = dumpPermissions("Grant", "Ejb", defEjbGrantededPC); - assertEquals(5, count - defaultCount); - - PermissionCollection defWebGrantededPC - = SMGlobalPolicyUtil.getEECompGrantededPerms(SMGlobalPolicyUtil.CommponentType.war); - count = dumpPermissions("Grant", "Web", defWebGrantededPC); - assertEquals(6, count - defaultCount); - - PermissionCollection defRarGrantededPC - = SMGlobalPolicyUtil.getEECompGrantededPerms(SMGlobalPolicyUtil.CommponentType.rar); - count = dumpPermissions("Grant", "Rar", defRarGrantededPC); - assertEquals(5, count - defaultCount); - - PermissionCollection defClientGrantededPC - = SMGlobalPolicyUtil.getEECompGrantededPerms(SMGlobalPolicyUtil.CommponentType.car); - count = dumpPermissions("Grant", "Client", defClientGrantededPC); - assertEquals(10, count - defaultCount); - - System.out.println("Starting testDefPolicy loading - ee restrict"); - - PermissionCollection defEjbRestrictedPC - = SMGlobalPolicyUtil.getCompRestrictedPerms(SMGlobalPolicyUtil.CommponentType.ejb); - count = dumpPermissions("Restricted", "Ejb", defEjbRestrictedPC); - assertEquals(2, count - defaultCount); - - PermissionCollection defWebRestrictedPC - = SMGlobalPolicyUtil.getCompRestrictedPerms(SMGlobalPolicyUtil.CommponentType.war); - count = dumpPermissions("Restricted", "Web", defWebRestrictedPC); - assertEquals(2, count - defaultCount); - - PermissionCollection defRarRestrictedPC - = SMGlobalPolicyUtil.getCompRestrictedPerms(SMGlobalPolicyUtil.CommponentType.rar); - count = dumpPermissions("Restricted", "Rar", defRarRestrictedPC); - assertEquals(1, count - defaultCount); - - PermissionCollection defClientRestrictedPC - = SMGlobalPolicyUtil.getCompRestrictedPerms(SMGlobalPolicyUtil.CommponentType.car); - count = dumpPermissions("Restricted", "Client", defClientRestrictedPC); - assertEquals(2, count - defaultCount); - - } - - - @Test - public void testFilePermission() { - System.out.println("Starting testFilePermission"); - - FilePermission fp1 = new FilePermission("-", "delete"); - FilePermission fp2 = new FilePermission("a/file.txt", "delete"); - - assertTrue(fp1.implies(fp2)); - - FilePermission fp3 = new FilePermission("*", "delete"); - FilePermission fp4 = new FilePermission("file.txt", "delete"); - - assertTrue(fp3.implies(fp4)); - - - FilePermission fp5 = new FilePermission("/scratch/xyz/*", "delete"); - FilePermission fp6 = new FilePermission("/scratch/xyz/deleteit.txt", "delete"); - - assertTrue(fp5.implies(fp6)); - - - FilePermission fp7 = new FilePermission("/scratch/xyz/", "delete"); - FilePermission fp8 = new FilePermission("/scratch/xyz", "delete"); - - assertTrue(fp7.implies(fp8)); - - - Permission fp9 = new java.security.UnresolvedPermission("VoidPermission", "", "", null); - Permission fp10 = new java.security.AllPermission(); - - assertTrue(fp10.implies(fp9)); - assertTrue(!fp9.implies(fp10)); - } - - private int dumpPermissions(String type, String component, PermissionCollection permissionCollection) { - int count = 0; - - if (permissionCollection == null) { - System.out.println("Type= " + type + ", compnent= " + component + ", Permission is empty "); - return count; - } - - Enumeration permissions = permissionCollection.elements(); - while (permissions.hasMoreElements()) { - Permission permission = permissions.nextElement(); - System.out.println("Type= " + type + ", compnent= " + component + ", Permission p= " + permission); - count += 1; - } - - return count; - } - -} diff --git a/appserver/security/core-ee/src/test/java/com/sun/enterprise/security/ee/perms/VoidPermissionTest.java b/appserver/security/core-ee/src/test/java/com/sun/enterprise/security/ee/perms/VoidPermissionTest.java deleted file mode 100644 index 4440323d0cb..00000000000 --- a/appserver/security/core-ee/src/test/java/com/sun/enterprise/security/ee/perms/VoidPermissionTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2021 Contributors to the Eclipse Foundation - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.ee.perms; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.FilePermission; -import java.security.AllPermission; -import java.security.Permission; -import org.junit.jupiter.api.Test; - -public class VoidPermissionTest { - - @Test - public void testImpliedByAllPermission() { - Permission allPerm = new AllPermission(); - VoidPermission vPerm = new VoidPermission(); - - assertTrue(allPerm.implies(vPerm)); - assertFalse(vPerm.implies(allPerm)); - } - - @Test - public void testNotImplied() { - VoidPermission vPerm = new VoidPermission(); - FilePermission fPerm = new FilePermission("/scratch/test/*", "read"); - - assertFalse(vPerm.implies(fPerm)); - assertFalse(fPerm.implies(vPerm)); - } - - @Test - public void testNoImplySelf() { - VoidPermission vPerm1 = new VoidPermission(); - VoidPermission vPerm2 = new VoidPermission(); - - assertFalse(vPerm1.implies(vPerm2)); - assertFalse(vPerm2.implies(vPerm1)); - assertFalse(vPerm1.implies(vPerm1)); - } -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/server/ServerSecurityPipe.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/server/ServerSecurityPipe.java index 31ee7a47de1..2c8329d36da 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/server/ServerSecurityPipe.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/server/ServerSecurityPipe.java @@ -171,29 +171,12 @@ private Packet processRequest(Packet request) throws Exception { } if (authorized) { - // only do doAdPriv if SecurityManager is in effect - if (System.getSecurityManager() == null) { - try { - // proceed to invoke the endpoint - response = next.process(validatedRequest); - } catch (Exception e) { - _logger.log(SEVERE, LogUtils.NEXT_PIPE, e); - response = authenticationService.getFaultResponse(validatedRequest, info.getResponsePacket(), e); - } - } else { - try { - response = Subject.doAsPrivileged(clientSubject, new PrivilegedExceptionAction() { - @Override - public Packet run() throws Exception { - // proceed to invoke the endpoint - return next.process(validatedRequest); - } - }, null); - } catch (PrivilegedActionException pae) { - Throwable cause = pae.getCause(); - _logger.log(SEVERE, LogUtils.NEXT_PIPE, cause); - response = authenticationService.getFaultResponse(validatedRequest, info.getResponsePacket(), cause); - } + try { + // proceed to invoke the endpoint + response = next.process(validatedRequest); + } catch (Exception e) { + _logger.log(SEVERE, LogUtils.NEXT_PIPE, e); + response = authenticationService.getFaultResponse(validatedRequest, info.getResponsePacket(), e); } } diff --git a/appserver/web/war-util/src/main/java/com/sun/enterprise/glassfish/web/WarHandler.java b/appserver/web/war-util/src/main/java/com/sun/enterprise/glassfish/web/WarHandler.java index 07e41f15b55..1badcb4072a 100644 --- a/appserver/web/war-util/src/main/java/com/sun/enterprise/glassfish/web/WarHandler.java +++ b/appserver/web/war-util/src/main/java/com/sun/enterprise/glassfish/web/WarHandler.java @@ -17,17 +17,19 @@ package com.sun.enterprise.glassfish.web; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.SEVERE; +import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + import com.sun.enterprise.config.serverbeans.Config; import com.sun.enterprise.config.serverbeans.HttpService; import com.sun.enterprise.config.serverbeans.VirtualServer; import com.sun.enterprise.deploy.shared.AbstractArchiveHandler; -import com.sun.enterprise.security.ee.perms.PermsArchiveDelegate; -import com.sun.enterprise.security.ee.perms.SMGlobalPolicyUtil; import com.sun.enterprise.util.StringUtils; - import jakarta.inject.Inject; import jakarta.inject.Named; - import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; @@ -36,19 +38,14 @@ import java.net.MalformedURLException; import java.net.URI; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; - import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; - import org.apache.naming.resources.WebDirContext; import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.api.deployment.DeployCommandParameters; @@ -63,10 +60,6 @@ import org.jvnet.hk2.annotations.Service; import org.jvnet.hk2.config.types.Property; -import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; -import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; -import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; - /** * Implementation of the ArchiveHandler for war files. * @@ -75,15 +68,15 @@ @Service(name = WarArchiveType.ARCHIVE_TYPE) public class WarHandler extends AbstractArchiveHandler { + private static final Logger LOG = LogFacade.getLogger(); + private static final ResourceBundle I18N = LOG.getResourceBundle(); + private static final String GLASSFISH_WEB_XML = "WEB-INF/glassfish-web.xml"; private static final String SUN_WEB_XML = "WEB-INF/sun-web.xml"; private static final String WEBLOGIC_XML = "WEB-INF/weblogic.xml"; private static final String WAR_CONTEXT_XML = "META-INF/context.xml"; private static final String DEFAULT_CONTEXT_XML = "config/context.xml"; - private static final Logger LOG = LogFacade.getLogger(); - private static final ResourceBundle I18N = LOG.getResourceBundle(); - // the following two system properties need to be in sync with DOLUtils private static final boolean gfDDOverWLSDD = Boolean.valueOf(System.getProperty("gfdd.over.wlsdd")); private static final boolean ignoreWLSDD = Boolean.valueOf(System.getProperty("ignore.wlsdd")); @@ -108,13 +101,11 @@ public String getArchiveType() { @Override public String getVersionIdentifier(ReadableArchive archive) { try { - WebXmlParser webXmlParser = getWebXmlParser(archive); - return webXmlParser.getVersionIdentifier(); - } catch (XMLStreamException e) { - LOG.log(Level.SEVERE, e.getMessage()); - } catch (IOException e) { - LOG.log(Level.SEVERE, e.getMessage()); + return getWebXmlParser(archive).getVersionIdentifier(); + } catch (XMLStreamException | IOException e) { + LOG.log(SEVERE, e.getMessage()); } + return null; } @@ -125,8 +116,7 @@ public boolean handles(ReadableArchive archive) throws IOException { @Override public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext context) { - PrivilegedAction action = () -> new WebappClassLoader(parent); - WebappClassLoader cloader = AccessController.doPrivileged(action); + WebappClassLoader cloader = new WebappClassLoader(parent); try { WebDirContext webDirContext = new WebDirContext(); File base = new File(context.getSource().getURI()); @@ -141,7 +131,7 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co cloader.setWorkDir(context.getScratchDir("jsp")); } - // add libraries referenced from manifest + // Add libraries referenced from manifest for (URL url : getManifestLibraries(context)) { cloader.addRepository(url.toString()); } @@ -150,20 +140,10 @@ public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext co configureLoaderAttributes(cloader, webXmlParser, base); configureLoaderProperties(cloader, webXmlParser, base); configureContextXmlAttribute(cloader, base, context); - try { - final DeploymentContext dc = context; - final ClassLoader cl = cloader; - AccessController.doPrivileged( - new PermsArchiveDelegate.SetPermissionsAction(SMGlobalPolicyUtil.CommponentType.war, dc, cl)); - } catch (PrivilegedActionException e) { - throw new SecurityException(e.getException()); - } - - } catch(XMLStreamException xse) { - LOG.log(Level.SEVERE, xse.getMessage(), xse); - } catch(IOException ioe) { - LOG.log(Level.SEVERE, ioe.getMessage(), ioe); + } catch(XMLStreamException | IOException xse) { + LOG.log(SEVERE, xse.getMessage(), xse); } + cloader.start(); return cloader; } @@ -197,7 +177,7 @@ protected WebXmlParser getWebXmlParser(ReadableArchive archive) throws XMLStream protected void configureLoaderAttributes(WebappClassLoader cloader, WebXmlParser webXmlParser, File base) { final boolean delegate = webXmlParser.isDelegate(); cloader.setDelegate(delegate); - if (LOG.isLoggable(Level.FINE)) { + if (LOG.isLoggable(FINE)) { LOG.fine("WebModule[" + base + "]: Setting delegate to " + delegate); } @@ -211,7 +191,7 @@ protected void configureLoaderAttributes(WebappClassLoader cloader, WebXmlParser String[] pathElements = extraClassPath.split(";|((? action = () -> { - acessible.setAccessible(true); - return null; - }; - AccessController.doPrivileged(action); - } + private static void setAccessible(final AccessibleObject accessible) { + accessible.setAccessible(true); } diff --git a/appserver/web/war-util/src/main/java/org/glassfish/web/loader/WebappClassLoader.java b/appserver/web/war-util/src/main/java/org/glassfish/web/loader/WebappClassLoader.java index 80cca426864..1bc94b8b1b2 100644 --- a/appserver/web/war-util/src/main/java/org/glassfish/web/loader/WebappClassLoader.java +++ b/appserver/web/war-util/src/main/java/org/glassfish/web/loader/WebappClassLoader.java @@ -18,15 +18,20 @@ package org.glassfish.web.loader; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.ERROR; +import static java.lang.System.Logger.Level.INFO; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; +import static org.glassfish.web.loader.LogFacade.UNABLE_TO_LOAD_CLASS; +import static org.glassfish.web.loader.LogFacade.UNSUPPORTED_VERSION; +import static org.glassfish.web.loader.LogFacade.getString; + import com.sun.appserv.BytecodePreprocessor; import com.sun.enterprise.loader.ResourceLocator; -import com.sun.enterprise.security.integration.DDPermissionsLoader; -import com.sun.enterprise.security.integration.PermsHolder; import com.sun.enterprise.util.io.FileUtils; - import java.io.ByteArrayInputStream; import java.io.File; -import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.System.Logger; @@ -35,13 +40,11 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import java.security.AccessControlException; import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; -import java.security.Policy; import java.security.PrivilegedAction; import java.time.Instant; import java.util.ArrayList; @@ -53,19 +56,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Function; -import java.util.jar.Attributes; -import java.util.jar.Attributes.Name; import java.util.jar.JarFile; -import java.util.jar.Manifest; import java.util.stream.Collectors; - import javax.naming.Binding; import javax.naming.NameClassPair; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; - -import org.apache.naming.JndiPermission; import org.apache.naming.resources.DirContextURLStreamHandler; import org.apache.naming.resources.JarFileResourcesProvider; import org.apache.naming.resources.ProxyDirContext; @@ -77,15 +74,6 @@ import org.glassfish.hk2.api.PreDestroy; import org.glassfish.web.loader.RepositoryManager.RepositoryResource; -import static java.lang.System.Logger.Level.DEBUG; -import static java.lang.System.Logger.Level.ERROR; -import static java.lang.System.Logger.Level.INFO; -import static java.lang.System.Logger.Level.TRACE; -import static java.lang.System.Logger.Level.WARNING; -import static org.glassfish.web.loader.LogFacade.UNABLE_TO_LOAD_CLASS; -import static org.glassfish.web.loader.LogFacade.UNSUPPORTED_VERSION; -import static org.glassfish.web.loader.LogFacade.getString; - /** * Specialized web application class loader. *

@@ -123,8 +111,7 @@ * @author Craig R. McClanahan * @since 2007/08/17 15:46:27 $ */ -public final class WebappClassLoader extends GlassfishUrlClassLoader - implements Reloader, InstrumentableClassLoader, DDPermissionsLoader, JarFileResourcesProvider, PreDestroy { +public final class WebappClassLoader extends GlassfishUrlClassLoader implements Reloader, InstrumentableClassLoader, JarFileResourcesProvider, PreDestroy { static { registerAsParallelCapable(); @@ -156,9 +143,6 @@ public final class WebappClassLoader extends GlassfishUrlClassLoader private static final Set DELEGATED_RESOURCE_PATHS = DELEGATED_PACKAGES.stream() .map(PACKAGE_TO_PATH).collect(Collectors.toUnmodifiableSet()); - /** Instance of the SecurityManager installed. */ - private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager(); - private final ReferenceCleaner cleaner; /** The cache of ResourceEntry for classes and resources we have loaded, keyed by resource name. */ @@ -203,17 +187,12 @@ public final class WebappClassLoader extends GlassfishUrlClassLoader */ private List jarNames = new ArrayList<>(); - private boolean packageDefinitionSecurityEnabled; - /** * A list of read File and Jndi Permission's required if this loader * is for a web application context. */ private final ConcurrentLinkedQueue permissionList = new ConcurrentLinkedQueue<>(); - /** holder for declared and ee permissions */ - private PermsHolder permissionsHolder; - /** Path where resources loaded from JARs will be extracted. */ private File loaderDir; @@ -271,10 +250,6 @@ public WebappClassLoader(ClassLoader parent) { super(new URL[0], parent); this.cleaner = new ReferenceCleaner(this); this.system = WebappClassLoader.class.getClassLoader(); - if (SECURITY_MANAGER != null) { - refreshPolicy(); - } - this.permissionsHolder = new PermsHolder(); } @@ -332,95 +307,6 @@ public void setAntiJARLocking(boolean enable) { } - /** - * Enables checks for the package definition permissions. - * - * @param enable - */ - public void setPackageDefinitionSecurityEnabled(boolean enable) { - if (enable && SECURITY_MANAGER == null) { - throw new IllegalArgumentException("The Security Manager is disabled."); - } - LOG.log(DEBUG, "setPackageDefinitionSecurityEnabled(enable={0})", enable); - this.packageDefinitionSecurityEnabled = enable; - } - - - /** - * If there is a Java SecurityManager create a read FilePermission - * or JndiPermission for URL. - * - * @param url URL for a file or directory on local system - */ - public void addPermission(URL url) { - checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING); - if (url != null) { - addPermission(url.toString()); - } - } - - - /** - * If there is a Java SecurityManager create a read FilePermission - * or JndiPermission for the file directory path. - * - * @param path file directory path - */ - public void addPermission(final String path) { - checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING); - if (path == null || SECURITY_MANAGER == null) { - return; - } - SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY); - if (path.startsWith("jndi:") || path.startsWith("jar:jndi:")) { - final String jndiPath = path.endsWith("/") ? path : path + "/"; - permissionList.add(new JndiPermission(jndiPath + "*")); - } else { - final String filePath; - if (path.endsWith(File.separator)) { - filePath = path; - } else { - permissionList.add(new FilePermission(path, "read")); - filePath = path + File.separator; - } - permissionList.add(new FilePermission(filePath + "-", "read")); - } - } - - - /** - * If there is a Java SecurityManager create a Permission. - * - * @param permission permission to add - */ - public void addPermission(Permission permission) { - checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING); - if (SECURITY_MANAGER != null && permission != null) { - SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY); - permissionList.add(permission); - } - } - - - @Override - public void addDeclaredPermissions(PermissionCollection declaredPc) throws SecurityException { - checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING); - if (SECURITY_MANAGER != null) { - SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY); - permissionsHolder.setDeclaredPermissions(declaredPc); - } - } - - @Override - public void addEEPermissions(PermissionCollection eePc) throws SecurityException { - checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING); - if (SECURITY_MANAGER != null) { - SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY); - permissionsHolder.setEEPermissions(eePc); - } - } - - /** * @return {@value #WEB_INF_LIB} */ @@ -553,18 +439,6 @@ protected Class findClass(String name) throws ClassNotFoundException { LOG.log(DEBUG, "findClass(name={0})", name); checkStatus(LifeCycleStatus.RUNNING); - // (1) Permission to define this class when using a SecurityManager - if (packageDefinitionSecurityEnabled) { - int i = name.lastIndexOf('.'); - if (i >= 0) { - try { - SECURITY_MANAGER.checkPackageDefinition(name.substring(0, i)); - } catch (Exception se) { - throw new ClassNotFoundException(name, se); - } - } - } - // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class clazz = null; @@ -601,8 +475,6 @@ protected Class findClass(String name) throws ClassNotFoundException { } } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError(getString(UNSUPPORTED_VERSION, name, getJavaVersion())); - } catch (AccessControlException ace) { - throw new ClassNotFoundException(name, ace); } catch (RuntimeException | Error e) { throw e; } catch (Throwable t) { @@ -611,8 +483,6 @@ protected Class findClass(String name) throws ClassNotFoundException { if (clazz == null && hasExternalRepositories) { try { clazz = super.findClass(name); - } catch (AccessControlException ace) { - throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { throw e; } @@ -886,20 +756,6 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE return resolveIfRequired(resolve, clazz); } - // (0.5) Permission to access this class when using a SecurityManager - if (packageDefinitionSecurityEnabled) { - int i = name.lastIndexOf('.'); - if (i >= 0) { - try { - SECURITY_MANAGER.checkPackageAccess(name.substring(0, i)); - } catch (SecurityException se) { - String error = getString(LogFacade.SECURITY_EXCEPTION, name); - LOG.log(INFO, error, se); - throw new ClassNotFoundException(error, se); - } - } - } - final ClassLoader delegateLoader = getDelegateClassLoader(); boolean delegateLoad = isDelegateFirstClass(name); @@ -981,15 +837,6 @@ protected PermissionCollection getPermissions(CodeSource codeSource) { pc.add(p); } - // get the declared and EE perms - PermissionCollection pc1 = permissionsHolder.getPermissions(codeSource, null); - if (pc1 != null) { - Enumeration dperms = pc1.elements(); - while (dperms.hasMoreElements()) { - Permission p = dperms.nextElement(); - pc.add(p); - } - } PermissionCollection tmpPc = loaderPC.putIfAbsent(codeUrl, pc); return tmpPc == null ? pc : tmpPc; } @@ -1146,7 +993,6 @@ public void close() throws IOException { repositoryManager.close(); permissionList.clear(); - permissionsHolder = null; loaderPC.clear(); jarFiles.close(); @@ -1169,8 +1015,6 @@ public String toString() { sb.append(", context=").append(contextName); sb.append(", status=").append(status); sb.append(", antiJARLocking=").append(antiJARLocking); - sb.append(", securityManager=").append(SECURITY_MANAGER != null); - sb.append(", packageDefinitionSecurityEnabled=").append(packageDefinitionSecurityEnabled); sb.append(", repositories=").append(repositoryManager); sb.append(", notFound.size=").append(notFoundResources.size()); sb.append(", pathTimestamps.size=").append(pathTimestamps.size()); @@ -1180,6 +1024,7 @@ public String toString() { } + @Override public void preDestroy() { LOG.log(TRACE, "preDestroy()"); try { @@ -1248,21 +1093,6 @@ private ResourceEntry findClassInternal(String name) throws ClassNotFoundExcepti } } - if (SECURITY_MANAGER != null) { - // Checking sealing - if (pkg != null) { - final boolean sealCheck; - if (pkg.isSealed()) { - sealCheck = pkg.isSealed(entry.codeBase); - } else { - sealCheck = entry.manifest == null || !isPackageSealed(packageName, entry.manifest); - } - if (!sealCheck) { - throw new SecurityException( - "Sealing violation loading " + name + ": Package " + packageName + " is sealed."); - } - } - } return entry; } } @@ -1355,13 +1185,7 @@ private ResourceEntry toResourceEntry(String name, RepositoryResource repoResour private ResourceEntry toResourceEntry(String name, RepositoryResource repoResource, ResourceAttributes attributes) { - final ResourceEntry entry; - if (SECURITY_MANAGER == null) { - entry = new ResourceEntry(toURL(repoResource.file)); - } else { - PrivilegedAction action = () -> new ResourceEntry(toURL(repoResource.file)); - entry = AccessController.doPrivileged(action); - } + final ResourceEntry entry = new ResourceEntry(toURL(repoResource.file)); entry.lastModified = attributes.getLastModified(); pathTimestamps.add(new PathTimestamp(repoResource.name, entry.lastModified)); return entry; @@ -1373,26 +1197,6 @@ private ResourceAttributes getResourceAttributes(String fullPath) throws NamingE } - /** - * @return true if the specified package name is sealed according to the given manifest. - */ - private boolean isPackageSealed(String name, Manifest man) { - String path = name.replace('.', '/') + '/'; - Attributes attr = man.getAttributes(path); - String sealed = null; - if (attr != null) { - sealed = attr.getValue(Name.SEALED); - } - if (sealed == null) { - attr = man.getMainAttributes(); - if (attr != null) { - sealed = attr.getValue(Name.SEALED); - } - } - return "true".equalsIgnoreCase(sealed); - } - - /** * Finds the resource with the given name if it has previously been * loaded and cached by this class loader, and return an input stream @@ -1408,6 +1212,7 @@ private InputStream findLoadedResource(String name) { return new ByteArrayInputStream(entry.binaryContent); } } + return null; } @@ -1427,25 +1232,6 @@ private Class findLoadedClass0(String name) { return null; } - - /** - * Refresh the system policy file, to pick up eventual changes. - */ - private void refreshPolicy() { - try { - // The policy file may have been modified to adjust - // permissions, so we're reloading it when loading or - // reloading a Context - Policy policy = Policy.getPolicy(); - policy.refresh(); - } catch (AccessControlException e) { - // Some policy files may restrict this, even for the core, - // so this exception is ignored - LOG.log(TRACE, "The policy refresh failed.", e); - } - } - - /** * Validate a classname. As per SRV.9.7.2, we must restrict loading of * classes from J2SE (java.*) and classes of the servlet API @@ -1511,11 +1297,7 @@ private static void deleteDir(File dir) { private String getJavaVersion() { - if (SECURITY_MANAGER == null) { - return System.getProperty("java.version"); - } - PrivilegedAction action = () -> System.getProperty("java.version"); - return AccessController.doPrivileged(action); + return System.getProperty("java.version"); } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/Globals.java b/appserver/web/web-core/src/main/java/org/apache/catalina/Globals.java index 4faed1ba333..964def049aa 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/Globals.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/Globals.java @@ -17,9 +17,7 @@ package org.apache.catalina; -// START SJSAS import org.apache.catalina.servlets.DefaultServlet; -// END SJSAS /** * Global constants that are applicable to multiple packages within Catalina. @@ -27,23 +25,18 @@ * @author Craig R. McClanahan * @version $Revision: 1.12 $ $Date: 2007/06/18 23:14:22 $ */ - public final class Globals { /** - * The servlet context attribute under which we store the alternate - * deployment descriptor for this web application + * The servlet context attribute under which we store the alternate deployment descriptor for this web application */ - public static final String ALT_DD_ATTR = - "org.apache.catalina.deploy.alt_dd"; + public static final String ALT_DD_ATTR = "org.apache.catalina.deploy.alt_dd"; /** - * The request attribute under which we store the array of X509Certificate - * objects representing the certificate chain presented by our client, - * if any. + * The request attribute under which we store the array of X509Certificate objects representing the certificate chain + * presented by our client, if any. */ - public static final String CERTIFICATES_ATTR = - "jakarta.servlet.request.X509Certificate"; + public static final String CERTIFICATES_ATTR = "jakarta.servlet.request.X509Certificate"; /** * SSL Certificate Request Attributite. @@ -51,222 +44,134 @@ public final class Globals { public static final String SSL_CERTIFICATE_ATTR = "org.apache.coyote.request.X509Certificate"; /** - * The request attribute under which we store the name of the cipher suite - * being used on an SSL connection (as an object of type - * java.lang.String). + * The request attribute under which we store the name of the cipher suite being used on an SSL connection (as an object + * of type java.lang.String). */ - public static final String CIPHER_SUITE_ATTR = - "jakarta.servlet.request.cipher_suite"; - + public static final String CIPHER_SUITE_ATTR = "jakarta.servlet.request.cipher_suite"; /** - * The servlet context attribute under which we store the class loader - * used for loading servlets (as an object of type java.lang.ClassLoader). + * The servlet context attribute under which we store the class loader used for loading servlets (as an object of type + * java.lang.ClassLoader). */ - public static final String CLASS_LOADER_ATTR = - "org.apache.catalina.classloader"; + public static final String CLASS_LOADER_ATTR = "org.apache.catalina.classloader"; /** * Request dispatcher state. */ - public static final String DISPATCHER_TYPE_ATTR = - "org.apache.catalina.core.DISPATCHER_TYPE"; + public static final String DISPATCHER_TYPE_ATTR = "org.apache.catalina.core.DISPATCHER_TYPE"; /** * Request dispatcher path. */ - public static final String DISPATCHER_REQUEST_PATH_ATTR = - "org.apache.catalina.core.DISPATCHER_REQUEST_PATH"; + public static final String DISPATCHER_REQUEST_PATH_ATTR = "org.apache.catalina.core.DISPATCHER_REQUEST_PATH"; /** - * The JNDI directory context which is associated with the context. This - * context can be used to manipulate static files. + * The JNDI directory context which is associated with the context. This context can be used to manipulate static files. */ - public static final String RESOURCES_ATTR = - "org.apache.catalina.resources"; - public static final String ALTERNATE_RESOURCES_ATTR = - "org.apache.catalina.alternateResources"; - + public static final String RESOURCES_ATTR = "org.apache.catalina.resources"; + public static final String ALTERNATE_RESOURCES_ATTR = "org.apache.catalina.alternateResources"; /** - * The servlet context attribute under which we store the class path - * for our application class loader (as an object of type String), - * delimited with the appropriate path delimiter for this platform. + * The servlet context attribute under which we store the class path for our application class loader (as an object of + * type String), delimited with the appropriate path delimiter for this platform. */ - public static final String CLASS_PATH_ATTR = - "org.apache.catalina.jsp_classpath"; - + public static final String CLASS_PATH_ATTR = "org.apache.catalina.jsp_classpath"; /** - * The request attribute under which the Invoker servlet will store - * the invoking servlet path, if it was used to execute a servlet - * indirectly instead of through a servlet mapping. + * The request attribute under which the Invoker servlet will store the invoking servlet path, if it was used to execute + * a servlet indirectly instead of through a servlet mapping. */ - public static final String INVOKED_ATTR = - "org.apache.catalina.INVOKED"; - + public static final String INVOKED_ATTR = "org.apache.catalina.INVOKED"; /** - * The request attribute under which we expose the value of the - * <jsp-file> value associated with this servlet, - * if any. + * The request attribute under which we expose the value of the <jsp-file> value associated with this + * servlet, if any. */ - public static final String JSP_FILE_ATTR = - "org.apache.catalina.jsp_file"; - + public static final String JSP_FILE_ATTR = "org.apache.catalina.jsp_file"; /** - * The request attribute under which we store the key size being used for - * this SSL connection (as an object of type java.lang.Integer). + * The request attribute under which we store the key size being used for this SSL connection (as an object of type + * java.lang.Integer). */ - public static final String KEY_SIZE_ATTR = - "jakarta.servlet.request.key_size"; - + public static final String KEY_SIZE_ATTR = "jakarta.servlet.request.key_size"; /** - * The request attribute under which we store the session id being used - * for this SSL connection (as an object of type java.lang.String). + * The request attribute under which we store the session id being used for this SSL connection (as an object of type + * java.lang.String). */ - public static final String SSL_SESSION_ID_ATTR = - "jakarta.servlet.request.ssl_session_id"; - + public static final String SSL_SESSION_ID_ATTR = "jakarta.servlet.request.ssl_session_id"; /** - * The servlet context attribute under which the managed bean Registry - * will be stored for privileged contexts (if enabled). + * The servlet context attribute under which the managed bean Registry will be stored for privileged contexts (if + * enabled). */ - public static final String MBEAN_REGISTRY_ATTR = - "org.apache.catalina.Registry"; - + public static final String MBEAN_REGISTRY_ATTR = "org.apache.catalina.Registry"; /** - * The servlet context attribute under which the MBeanServer will be stored - * for privileged contexts (if enabled). + * The servlet context attribute under which the MBeanServer will be stored for privileged contexts (if enabled). */ - public static final String MBEAN_SERVER_ATTR = - "org.apache.catalina.MBeanServer"; - + public static final String MBEAN_SERVER_ATTR = "org.apache.catalina.MBeanServer"; /** - * The request attribute under which we store the servlet name on a - * named dispatcher request. + * The request attribute under which we store the servlet name on a named dispatcher request. */ - public static final String NAMED_DISPATCHER_ATTR = - "org.apache.catalina.NAMED"; - + public static final String NAMED_DISPATCHER_ATTR = "org.apache.catalina.NAMED"; /** - * The name of the cookie used to pass the session identifier back - * and forth with the client. + * The name of the cookie used to pass the session identifier back and forth with the client. */ public static final String SESSION_COOKIE_NAME = "JSESSIONID"; - /** - * The name of the path parameter used to pass the session identifier - * back and forth with the client. + * The name of the path parameter used to pass the session identifier back and forth with the client. */ public static final String SESSION_PARAMETER_NAME = "jsessionid"; - /** * The subject under which the AccessControlContext is running. */ - public static final String SUBJECT_ATTR = - "javax.security.auth.subject"; + public static final String SUBJECT_ATTR = "javax.security.auth.subject"; - - // START SJSAS /** * The class name of the default servlet */ - public static final String DEFAULT_SERVLET_CLASS_NAME = - DefaultServlet.class.getName(); - // END SJSAS - - - /** - * Has security been turned on? - */ - public static final boolean IS_SECURITY_ENABLED = - (System.getSecurityManager() != null); - - - // START GlassFish 740 - public static final String JSP_PROPERTY_GROUPS_CONTEXT_ATTRIBUTE = - "com.sun.jsp.propertyGroups"; - - public static final String WEB_XML_VERSION_CONTEXT_ATTRIBUTE = - "com.sun.servlet.webxml.version"; - // END GlassFish 740 - - // START GlassFish 747 - public static final String JSP_TLD_URI_TO_LOCATION_MAP = - "com.sun.jsp.tldUriToLocationMap"; - // END GlassFish 747 - - // START GlassFish 896 - public static final String SESSION_TRACKER = - "com.sun.enterprise.http.sessionTracker"; - // END GlassFish 896 - - public static final String REQUEST_FACADE_HELPER = - "org.glassfish.web.RequestFacadeHelper"; + public static final String DEFAULT_SERVLET_CLASS_NAME = DefaultServlet.class.getName(); + public static final String JSP_PROPERTY_GROUPS_CONTEXT_ATTRIBUTE = "com.sun.jsp.propertyGroups"; + public static final String WEB_XML_VERSION_CONTEXT_ATTRIBUTE = "com.sun.servlet.webxml.version"; + public static final String JSP_TLD_URI_TO_LOCATION_MAP = "com.sun.jsp.tldUriToLocationMap"; + public static final String SESSION_TRACKER = "com.sun.enterprise.http.sessionTracker"; + public static final String REQUEST_FACADE_HELPER = "org.glassfish.web.RequestFacadeHelper"; /** * The name of the cookie used to carry a session's version info */ - public static final String SESSION_VERSION_COOKIE_NAME = - "JSESSIONIDVERSION"; + public static final String SESSION_VERSION_COOKIE_NAME = "JSESSIONIDVERSION"; /** * The name of the path parameter used to carry a session's version info */ - public static final String SESSION_VERSION_PARAMETER_NAME = - "jsessionidversion"; - - public static final String SESSION_VERSION_PARAMETER = - ";" + SESSION_VERSION_PARAMETER_NAME + "="; - - public static final String SESSION_VERSIONS_REQUEST_ATTRIBUTE = - "com.sun.enterprise.http.sessionVersions"; - + public static final String SESSION_VERSION_PARAMETER_NAME = "jsessionidversion"; + public static final String SESSION_VERSION_PARAMETER = ";" + SESSION_VERSION_PARAMETER_NAME + "="; + public static final String SESSION_VERSIONS_REQUEST_ATTRIBUTE = "com.sun.enterprise.http.sessionVersions"; public static final String JREPLICA_COOKIE_NAME = "JREPLICA"; - public static final String JREPLICA_PARAMETER_NAME = "jreplica"; - - public static final String JREPLICA_PARAMETER = - ";" + JREPLICA_PARAMETER_NAME + "="; - - public static final String JREPLICA_SESSION_NOTE = - "com.sun.enterprise.http.jreplicaLocation"; - - public static final String WRAPPED_REQUEST = - "__jakarta.security.auth.message.request"; - - public static final String WRAPPED_RESPONSE = - "__jakarta.security.auth.message.response"; - + public static final String JREPLICA_PARAMETER = ";" + JREPLICA_PARAMETER_NAME + "="; + public static final String JREPLICA_SESSION_NOTE = "com.sun.enterprise.http.jreplicaLocation"; + public static final String WRAPPED_REQUEST = "__jakarta.security.auth.message.request"; + public static final String WRAPPED_RESPONSE = "__jakarta.security.auth.message.response"; /** - * The servlet context attribute under which we store a flag used - * to mark this request as having been processed by the SSIServlet. - * We do this because of the pathInfo mangling happening when using - * the CGIServlet in conjunction with the SSI servlet. (value stored - * as an object of type String) + * The servlet context attribute under which we store a flag used to mark this request as having been processed by the + * SSIServlet. We do this because of the pathInfo mangling happening when using the CGIServlet in conjunction with the + * SSI servlet. (value stored as an object of type String) */ - public static final String SSI_FLAG_ATTR = - "org.apache.catalina.ssi.SSIServlet"; + public static final String SSI_FLAG_ATTR = "org.apache.catalina.ssi.SSIServlet"; /** * Request path. */ - public static final String CONSTRAINT_URI = - "org.apache.catalina.CONSTRAINT_URI"; - + public static final String CONSTRAINT_URI = "org.apache.catalina.CONSTRAINT_URI"; public static final String META_INF_RESOURCES = "META-INF/resources"; - public static final String ISO_8859_1_ENCODING = "ISO-8859-1"; - public static final String FACES_INITIALIZER = "com.sun.faces.config.FacesInitializer"; } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/AsyncContextImpl.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/AsyncContextImpl.java index d9f8ee8cdee..2b86d21eb6d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/AsyncContextImpl.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/AsyncContextImpl.java @@ -30,7 +30,6 @@ import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import java.security.AccessController; import java.security.PrivilegedAction; import java.util.EventListener; @@ -46,7 +45,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; - import org.apache.catalina.ContainerEvent; import org.apache.catalina.Globals; import org.apache.catalina.LogFacade; @@ -301,31 +299,15 @@ void onExitService() { @Override public void start(Runnable run) { - ClassLoader oldCL = null; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { ClassLoader newCL = origRequest.getContext().getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); pool.execute(run); } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } @@ -503,22 +485,11 @@ public void run() { origRequest.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ASYNC); origRequest.setAsyncStarted(false); int startAsyncCurrent = asyncContext.startAsyncCounter.get(); - ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { ClassLoader newCL = origRequest.getContext().getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); asyncContext.setDelayAsyncDispatchAndComplete(true); dispatcher.dispatch(asyncContext.getRequest(), asyncContext.getResponse(), DispatcherType.ASYNC); @@ -545,12 +516,7 @@ public void run() { origRequest.errorDispatchAndComplete(t); } finally { asyncContext.isStartAsyncInScope.set(Boolean.FALSE); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } } @@ -574,22 +540,11 @@ void notifyAsyncListeners(AsyncEventType asyncEventType, Throwable t) { } } - final ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + final ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { final ClassLoader newCL = origRequest.getContext().getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); ServletRequestListener weldListener = getWeldListener(); if (weldListener != null) { @@ -641,12 +596,7 @@ void notifyAsyncListeners(AsyncEventType asyncEventType, Throwable t) { } } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction action = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(action); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteInputStream.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteInputStream.java index 5a9b6167519..3db5428b5ec 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteInputStream.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteInputStream.java @@ -17,17 +17,11 @@ package org.apache.catalina.connector; -import org.apache.catalina.LogFacade; -import org.apache.catalina.security.SecurityUtil; - import jakarta.servlet.ReadListener; import jakarta.servlet.ServletInputStream; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ResourceBundle; - +import org.apache.catalina.LogFacade; /** * This class handles reading bytes. @@ -35,40 +29,32 @@ * @author Remy Maucherat * @author Jean-Francois Arcand */ -public class CoyoteInputStream - extends ServletInputStream { +public class CoyoteInputStream extends ServletInputStream { private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); // ----------------------------------------------------- Instance Variables - protected InputBuffer ib; - // ----------------------------------------------------------- Constructors - public CoyoteInputStream(InputBuffer ib) { this.ib = ib; } - // --------------------------------------------------------- Public Methods - /** - * Prevent cloning the facade. - */ - protected Object clone() - throws CloneNotSupportedException { + * Prevent cloning the facade. + */ + @Override + protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } - // -------------------------------------------------------- Package Methods - /** * Clear facade. */ @@ -76,148 +62,50 @@ void clear() { ib = null; } - // --------------------------------------------- ServletInputStream Methods - - public int read() - throws IOException { - + @Override + public int read() throws IOException { // Disallow operation if the object has gone out of scope if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); } - if (SecurityUtil.isPackageProtectionEnabled()){ - - try{ - Integer result = - AccessController.doPrivileged( - new PrivilegedExceptionAction(){ - - public Integer run() throws IOException{ - Integer integer = Integer.valueOf(ib.readByte()); - return integer; - } - - }); - return result.intValue(); - } catch(PrivilegedActionException pae){ - Exception e = pae.getException(); - if (e instanceof IOException){ - throw (IOException)e; - } else { - throw new RuntimeException(e.getMessage()); - } - } - } else { - return ib.readByte(); - } + return ib.readByte(); } + @Override public int available() throws IOException { // Disallow operation if the object has gone out of scope if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); } - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - Integer result = - AccessController.doPrivileged( - new PrivilegedExceptionAction(){ - - public Integer run() throws IOException{ - Integer integer = Integer.valueOf(ib.available()); - return integer; - } - - }); - return result.intValue(); - } catch(PrivilegedActionException pae){ - Exception e = pae.getException(); - if (e instanceof IOException){ - throw (IOException)e; - } else { - throw new RuntimeException(e.getMessage()); - } - } - } else { - return ib.available(); - } + return ib.available(); } + @Override public int read(final byte[] b) throws IOException { // Disallow operation if the object has gone out of scope if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); } - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - Integer result = - AccessController.doPrivileged( - new PrivilegedExceptionAction(){ - - public Integer run() throws IOException{ - Integer integer = - Integer.valueOf(ib.read(b, 0, b.length)); - return integer; - } - - }); - return result.intValue(); - } catch(PrivilegedActionException pae){ - Exception e = pae.getException(); - if (e instanceof IOException){ - throw (IOException)e; - } else { - throw new RuntimeException(e.getMessage()); - } - } - } else { - return ib.read(b, 0, b.length); - } + return ib.read(b, 0, b.length); } - - public int read(final byte[] b, final int off, final int len) - throws IOException { - + @Override + public int read(final byte[] b, final int off, final int len) throws IOException { // Disallow operation if the object has gone out of scope if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); } - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - Integer result = - AccessController.doPrivileged( - new PrivilegedExceptionAction(){ - - public Integer run() throws IOException{ - Integer integer = - Integer.valueOf(ib.read(b, off, len)); - return integer; - } - - }); - return result.intValue(); - } catch(PrivilegedActionException pae){ - Exception e = pae.getException(); - if (e instanceof IOException){ - throw (IOException)e; - } else { - throw new RuntimeException(e.getMessage()); - } - } - } else { - return ib.read(b, off, len); - } + return ib.read(b, off, len); } - + @Override public int readLine(byte[] b, int off, int len) throws IOException { // Disallow operation if the object has gone out of scope if (ib == null) { @@ -227,7 +115,7 @@ public int readLine(byte[] b, int off, int len) throws IOException { return super.readLine(b, off, len); } - + @Override public boolean isFinished() { if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); @@ -236,7 +124,7 @@ public boolean isFinished() { return ib.isFinished(); } - + @Override public boolean isReady() { if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); @@ -245,7 +133,7 @@ public boolean isReady() { return ib.isReady(); } - + @Override public void setReadListener(ReadListener readListener) { if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); @@ -258,39 +146,16 @@ public void setReadListener(ReadListener readListener) { ib.setReadListener(readListener); } - /** - * Close the stream - * Since we re-cycle, we can't allow the call to super.close() - * which would permanently disable us. + * Close the stream Since we re-cycle, we can't allow the call to super.close() which would permanently disable us. */ + @Override public void close() throws IOException { // Disallow operation if the object has gone out of scope if (ib == null) { throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); } - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - AccessController.doPrivileged( - new PrivilegedExceptionAction(){ - - public Void run() throws IOException{ - ib.close(); - return null; - } - - }); - } catch(PrivilegedActionException pae){ - Exception e = pae.getException(); - if (e instanceof IOException){ - throw (IOException)e; - } else { - throw new RuntimeException(e.getMessage()); - } - } - } else { - ib.close(); - } + ib.close(); } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/InputBuffer.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/InputBuffer.java index b566723500b..88e67b00f5f 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/InputBuffer.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/InputBuffer.java @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.Reader; import java.nio.channels.InterruptedByTimeoutException; -import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ResourceBundle; import java.util.logging.Level; @@ -39,29 +38,23 @@ import org.glassfish.grizzly.http.util.CharChunk; /** - * The buffer used by Tomcat request. This is a derivative of the Tomcat 3.3 - * OutputBuffer, adapted to handle input instead of output. This allows - * complete recycling of the facade objects (the ServletInputStream and the + * The buffer used by Tomcat request. This is a derivative of the Tomcat 3.3 OutputBuffer, adapted to handle input + * instead of output. This allows complete recycling of the facade objects (the ServletInputStream and the * BufferedReader). * * @author Remy Maucherat */ -public class InputBuffer extends Reader - implements ByteInputChannel, CharChunk.CharInputChannel, - CharChunk.CharOutputChannel { +public class InputBuffer extends Reader implements ByteInputChannel, CharChunk.CharInputChannel, CharChunk.CharOutputChannel { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); // -------------------------------------------------------------- Constants - - public static final int DEFAULT_BUFFER_SIZE = 8*1024; - + public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; // ----------------------------------------------------- Instance Variables - /** * Associated Grizzly request. */ @@ -77,17 +70,13 @@ public class InputBuffer extends Reader // ----------------------------------------------------------- Constructors - /** * Default constructor. Allocate the buffer with the default buffer size. */ public InputBuffer() { - this(DEFAULT_BUFFER_SIZE); - } - /** * Alternate constructor which allows specifying the initial buffer size. * @@ -103,7 +92,6 @@ public InputBuffer(int size) { // ------------------------------------------------------------- Properties - /** * Associated Grizzly request. * @@ -114,12 +102,10 @@ public void setRequest(Request grizzlyRequest) { this.grizzlyInputBuffer = grizzlyRequest.getInputBuffer(); } - public void setRequest(org.apache.catalina.connector.Request request) { this.request = request; } - /** * Get associated Grizzly request. * @@ -129,15 +115,12 @@ public Request getRequest() { return this.grizzlyRequest; } - // --------------------------------------------------------- Public Methods - /** * Recycle the output buffer. */ public void recycle() { - if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "recycle()"); @@ -148,27 +131,22 @@ public void recycle() { } - /** * Close the input buffer. * * @throws IOException An underlying IOException occurred */ - public void close() - throws IOException { + @Override + public void close() throws IOException { grizzlyInputBuffer.close(); } - - public int available() - throws IOException { + public int available() throws IOException { return grizzlyInputBuffer.readyData(); } - // ------------------------------------------------- Bytes Handling Methods - /** * Reads new bytes in the byte chunk. * @@ -178,35 +156,29 @@ public int available() * * @throws IOException An underlying IOException occurred */ - public int realReadBytes(byte cbuf[], int off, int len) - throws IOException { + @Override + public int realReadBytes(byte cbuf[], int off, int len) throws IOException { return grizzlyInputBuffer.read(cbuf, off, len); } - - public int readByte() - throws IOException { + public int readByte() throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); return grizzlyInputBuffer.readByte(); } - - public int read(final byte[] b, final int off, final int len) - throws IOException { + public int read(final byte[] b, final int off, final int len) throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); return grizzlyInputBuffer.read(b, off, len); } - public boolean isFinished() { return grizzlyInputBuffer.isFinished(); } - public boolean isReady() { if (!prevIsReady) { return false; @@ -224,14 +196,13 @@ public boolean isReady() { } } else { - prevIsReady = true; // Allow next .isReady() call to check underlying inputStream + prevIsReady = true; // Allow next .isReady() call to check underlying inputStream } } return result; } - public void setReadListener(ReadListener readListener) { if (readHandler != null) { throw new IllegalStateException(rb.getString(LogFacade.ALREADY_SET_READ_LISTENER)); @@ -246,7 +217,7 @@ public void setReadListener(ReadListener readListener) { if (isReady()) { try { readHandler.onDataAvailable(); - } catch(Throwable t) { + } catch (Throwable t) { log.log(Level.WARNING, LogFacade.READ_LISTENER_ON_DATA_AVAILABLE_ERROR, t); } } @@ -254,7 +225,7 @@ public void setReadListener(ReadListener readListener) { void disableReadHandler() { if (readHandler != null) { - synchronized(readHandler) { + synchronized (readHandler) { readHandler.onError(new InterruptedByTimeoutException()); } } @@ -262,65 +233,52 @@ void disableReadHandler() { // ------------------------------------------------- Chars Handling Methods - /** - * Since the converter will use append, it is possible to get chars to - * be removed from the buffer for "writing". Since the chars have already - * been read before, they are ignored. If a mark was set, then the - * mark is lost. + * Since the converter will use append, it is possible to get chars to be removed from the buffer for "writing". Since + * the chars have already been read before, they are ignored. If a mark was set, then the mark is lost. */ - public void realWriteChars(char c[], int off, int len) - throws IOException { + @Override + public void realWriteChars(char c[], int off, int len) throws IOException { // START OF SJSAS 6231069 // initChar(); // END OF SJSAS 6231069 // markPos = -1; } - public void setEncoding(final String encoding) { grizzlyInputBuffer.setDefaultEncoding(encoding); } - - public int realReadChars(final char cbuf[], final int off, final int len) - throws IOException { + @Override + public int realReadChars(final char cbuf[], final int off, final int len) throws IOException { return grizzlyInputBuffer.read(cbuf, off, len); } - - public int read() - throws IOException { - + @Override + public int read() throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); return grizzlyInputBuffer.readChar(); } - - public int read(char[] cbuf) - throws IOException { - + @Override + public int read(char[] cbuf) throws IOException { return read(cbuf, 0, cbuf.length); } - - public int read(char[] cbuf, int off, int len) - throws IOException { - + @Override + public int read(char[] cbuf, int off, int len) throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); return grizzlyInputBuffer.read(cbuf, off, len); } - - public long skip(long n) - throws IOException { - + @Override + public long skip(long n) throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); @@ -331,45 +289,35 @@ public long skip(long n) } - - public boolean ready() - throws IOException { - + @Override + public boolean ready() throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); return grizzlyInputBuffer.ready(); } - + @Override public boolean markSupported() { return true; } - - public void mark(int readAheadLimit) - throws IOException { + @Override + public void mark(int readAheadLimit) throws IOException { grizzlyInputBuffer.mark(readAheadLimit); } - - public void reset() - throws IOException { - + @Override + public void reset() throws IOException { if (grizzlyInputBuffer.isClosed()) throw new IOException(rb.getString(LogFacade.STREAM_CLOSED)); grizzlyInputBuffer.reset(); } - - public void checkConverter() - throws IOException { - + public void checkConverter() throws IOException { grizzlyInputBuffer.processingChars(); - } - class ReadHandlerImpl implements ReadHandler { private ReadListener readListener = null; private volatile boolean disable = false; @@ -396,45 +344,27 @@ public void run() { } private void processDataAvailable() { - ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { Context context = request.getContext(); ClassLoader newCL = context.getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); - synchronized(this) { + synchronized (this) { prevIsReady = true; try { - context.fireContainerEvent( - ContainerEvent.BEFORE_READ_LISTENER_ON_DATA_AVAILABLE, readListener); + context.fireContainerEvent(ContainerEvent.BEFORE_READ_LISTENER_ON_DATA_AVAILABLE, readListener); readListener.onDataAvailable(); - } catch(Throwable t) { + } catch (Throwable t) { disable = true; readListener.onError(t); } finally { - context.fireContainerEvent( - ContainerEvent.AFTER_READ_LISTENER_ON_DATA_AVAILABLE, readListener); + context.fireContainerEvent(ContainerEvent.AFTER_READ_LISTENER_ON_DATA_AVAILABLE, readListener); } } } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } @@ -456,45 +386,27 @@ public void run() { } private void processAllDataRead() { - ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { Context context = request.getContext(); ClassLoader newCL = context.getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); - synchronized(this) { + synchronized (this) { prevIsReady = true; try { - context.fireContainerEvent( - ContainerEvent.BEFORE_READ_LISTENER_ON_ALL_DATA_READ, readListener); + context.fireContainerEvent(ContainerEvent.BEFORE_READ_LISTENER_ON_ALL_DATA_READ, readListener); readListener.onAllDataRead(); - } catch(Throwable t) { + } catch (Throwable t) { disable = true; readListener.onError(t); } finally { - context.fireContainerEvent( - ContainerEvent.AFTER_READ_LISTENER_ON_ALL_DATA_READ, readListener); + context.fireContainerEvent(ContainerEvent.AFTER_READ_LISTENER_ON_ALL_DATA_READ, readListener); } } } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } @@ -518,33 +430,21 @@ public void run() { } private void processError(final Throwable t) { - ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { Context context = request.getContext(); ClassLoader newCL = context.getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); - synchronized(this) { + synchronized (this) { // Get isUpgrade and WebConnection before calling onError // Just in case onError will complete the async processing. final boolean isUpgrade = request.isUpgrade(); final WebConnection wc = request.getWebConnection(); try { - context.fireContainerEvent( - ContainerEvent.BEFORE_READ_LISTENER_ON_ERROR, readListener); + context.fireContainerEvent(ContainerEvent.BEFORE_READ_LISTENER_ON_ERROR, readListener); readListener.onError(t); } finally { if (isUpgrade && wc != null) { @@ -553,43 +453,13 @@ private void processError(final Throwable t) { } catch (Exception ignored) { } } - context.fireContainerEvent( - ContainerEvent.AFTER_READ_LISTENER_ON_ERROR, readListener); + context.fireContainerEvent(ContainerEvent.AFTER_READ_LISTENER_ON_ERROR, readListener); } } } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } } - - private static class PrivilegedSetTccl implements PrivilegedAction { - - private ClassLoader cl; - - PrivilegedSetTccl(ClassLoader cl) { - this.cl = cl; - } - - @Override - public Void run() { - Thread.currentThread().setContextClassLoader(cl); - return null; - } - } - - private static class PrivilegedGetTccl - implements PrivilegedAction { - - @Override - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/OutputBuffer.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/OutputBuffer.java index 1d48f7147d0..0f65243e61d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/OutputBuffer.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/OutputBuffer.java @@ -17,19 +17,18 @@ package org.apache.catalina.connector; +import static java.util.logging.Level.FINE; + +import jakarta.servlet.WriteListener; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.Writer; import java.nio.channels.InterruptedByTimeoutException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Map; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; -import jakarta.servlet.WriteListener; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; - import org.apache.catalina.ContainerEvent; import org.apache.catalina.Context; import org.apache.catalina.Globals; @@ -43,15 +42,13 @@ import org.glassfish.grizzly.http.util.ByteChunk; /** - * The buffer used by Tomcat response. This is a derivative of the Tomcat 3.3 - * OutputBuffer, with the removal of some of the state handling (which in - * Coyote is mostly the Processor's responsibility). + * The buffer used by Tomcat response. This is a derivative of the Tomcat 3.3 OutputBuffer, with the removal of some of + * the state handling (which in Coyote is mostly the Processor's responsibility). * * @author Costin Manolache * @author Remy Maucherat */ -public class OutputBuffer extends Writer - implements ByteChunk.ByteOutputChannel { +public class OutputBuffer extends Writer implements ByteChunk.ByteOutputChannel { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); @@ -59,26 +56,22 @@ public class OutputBuffer extends Writer // -------------------------------------------------------------- Constants private static final String SET_COOKIE_HEADER = "Set-Cookie"; - public static final String DEFAULT_ENCODING = - org.glassfish.grizzly.http.util.Constants.DEFAULT_HTTP_CHARACTER_ENCODING; - public static final int DEFAULT_BUFFER_SIZE = 8*1024; + public static final String DEFAULT_ENCODING = org.glassfish.grizzly.http.util.Constants.DEFAULT_HTTP_CHARACTER_ENCODING; + public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; static final int debug = 0; // ----------------------------------------------------- Instance Variables - /** * Number of bytes written. */ private int bytesWritten = 0; - /** * Number of chars written. */ private int charsWritten = 0; - /** * Associated Coyote response. */ @@ -98,44 +91,27 @@ public class OutputBuffer extends Writer private int size; - private org.glassfish.grizzly.http.io.OutputBuffer.LifeCycleListener sessionCookieChecker = - new SessionCookieChecker(); + private org.glassfish.grizzly.http.io.OutputBuffer.LifeCycleListener sessionCookieChecker = new SessionCookieChecker(); // ----------------------------------------------------------- Constructors - /** * Default constructor. Allocate the buffer with the default buffer size. */ public OutputBuffer() { - this(DEFAULT_BUFFER_SIZE); - } - /** * Alternate constructor which allows specifying the initial buffer size. * * @param size Buffer size to use */ public OutputBuffer(int size) { - // START S1AS8 4861933 - /* - bb = new ByteChunk(size); - bb.setLimit(size); - bb.setByteOutputChannel(this); - cb = new CharChunk(size); - cb.setCharOutputChannel(this); - cb.setLimit(size); - */ this.size = size; - // END S1AS8 4861933 } - // ------------------------------------------------------------- Properties - public void setCoyoteResponse(Response coyoteResponse) { this.response = coyoteResponse; this.grizzlyResponse = coyoteResponse.getCoyoteResponse(); @@ -154,7 +130,6 @@ public boolean isSuspended() { return this.suspended; } - /** * Set the suspended flag. * @@ -164,17 +139,13 @@ public void setSuspended(boolean suspended) { this.suspended = suspended; } - // --------------------------------------------------------- Public Methods - /** * Recycle the output buffer. */ public void recycle() { - - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, "recycle()"); + log.log(FINE, "recycle()"); bytesWritten = 0; charsWritten = 0; @@ -185,19 +156,15 @@ public void recycle() { writeHandler = null; prevIsReady = true; response = null; - } - /** - * Close the output buffer. This tries to calculate the response size if - * the response has not been committed yet. + * Close the output buffer. This tries to calculate the response size if the response has not been committed yet. * * @throws IOException An underlying IOException occurred */ - public void close() - throws IOException { - + @Override + public void close() throws IOException { if (suspended) return; @@ -205,26 +172,22 @@ public void close() } - /** * Flush bytes or chars contained in the buffer. * * @throws IOException An underlying IOException occurred */ - public void flush() - throws IOException { + @Override + public void flush() throws IOException { doFlush(true); } - /** * Flush bytes or chars contained in the buffer. * * @throws IOException An underlying IOException occurred */ - protected void doFlush(boolean realFlush) - throws IOException { - + protected void doFlush(boolean realFlush) throws IOException { if (suspended) return; @@ -234,13 +197,10 @@ protected void doFlush(boolean realFlush) } - // ------------------------------------------------- Bytes Handling Methods - /** - * Sends the buffer data to the client output, checking the - * state of Response and calling the right interceptors. + * Sends the buffer data to the client output, checking the state of Response and calling the right interceptors. * * @param buf Byte buffer to be written to the response * @param off Offset @@ -248,11 +208,10 @@ protected void doFlush(boolean realFlush) * * @throws IOException An underlying IOException occurred */ - public void realWriteBytes(byte buf[], int off, int cnt) - throws IOException { - - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, "realWrite(b, " + off + ", " + cnt + ") " + grizzlyResponse); + @Override + public void realWriteBytes(byte buf[], int off, int cnt) throws IOException { + if (log.isLoggable(FINE)) + log.log(FINE, "realWrite(b, " + off + ", " + cnt + ") " + grizzlyResponse); if (grizzlyResponse == null) return; @@ -266,7 +225,7 @@ public void realWriteBytes(byte buf[], int off, int cnt) grizzlyOutputBuffer.write(buf, off, cnt); } catch (IOException e) { // An IOException on a write is almost always due to - // the remote client aborting the request. Wrap this + // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); } @@ -274,9 +233,7 @@ public void realWriteBytes(byte buf[], int off, int cnt) } - public void write(byte b[], int off, int len) throws IOException { - if (suspended) return; @@ -284,25 +241,19 @@ public void write(byte b[], int off, int len) throws IOException { } - - private void writeBytes(byte b[], int off, int len) - throws IOException { - + private void writeBytes(byte b[], int off, int len) throws IOException { if (grizzlyOutputBuffer.isClosed()) return; - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, "write(b,off,len)"); + + log.log(FINE, "write(b,off,len)"); grizzlyOutputBuffer.write(b, off, len); bytesWritten += len; } - // XXX Char or byte ? - public void writeByte(int b) - throws IOException { - + public void writeByte(int b) throws IOException { if (suspended) return; @@ -310,13 +261,10 @@ public void writeByte(int b) bytesWritten++; } - // ------------------------------------------------- Chars Handling Methods - - public void write(int c) - throws IOException { - + @Override + public void write(int c) throws IOException { if (suspended) return; @@ -325,9 +273,8 @@ public void write(int c) } - - public void write(char c[]) - throws IOException { + @Override + public void write(char c[]) throws IOException { if (suspended) return; @@ -336,9 +283,8 @@ public void write(char c[]) } - - public void write(char c[], int off, int len) - throws IOException { + @Override + public void write(char c[], int off, int len) throws IOException { if (suspended) return; @@ -347,26 +293,22 @@ public void write(char c[], int off, int len) charsWritten += len; } - /** * Append a string to the buffer */ - public void write(String s, int off, int len) - throws IOException { - + @Override + public void write(String s, int off, int len) throws IOException { if (suspended) return; charsWritten += len; - if (s==null) - s="null"; + if (s == null) + s = "null"; grizzlyOutputBuffer.write(s, off, len); } - - public void write(String s) - throws IOException { - + @Override + public void write(String s) throws IOException { if (suspended) return; @@ -375,74 +317,56 @@ public void write(String s) grizzlyOutputBuffer.write(s); } - - public void checkConverter() - throws IOException { + public void checkConverter() throws IOException { grizzlyOutputBuffer.prepareCharacterEncoder(); } - - // -------------------- BufferedOutputStream compatibility - + // -------------------- BufferedOutputStream compatibility /** * Real write - this buffer will be sent to the client */ - public void flushBytes() - throws IOException { - + public void flushBytes() throws IOException { grizzlyOutputBuffer.flush(); - } - public int getBytesWritten() { return bytesWritten; } - public int getCharsWritten() { return charsWritten; } - public int getContentWritten() { return bytesWritten + charsWritten; } - /** - * True if this buffer hasn't been used ( since recycle() ) - - * i.e. no chars or bytes have been added to the buffer. + * True if this buffer hasn't been used ( since recycle() ) - i.e. no chars or bytes have been added to the buffer. */ public boolean isNew() { return (bytesWritten == 0) && (charsWritten == 0); } - public void setBufferSize(int size) { if (size > grizzlyOutputBuffer.getBufferSize()) { grizzlyOutputBuffer.setBufferSize(size); } } - public void reset() { - grizzlyOutputBuffer.reset(); bytesWritten = 0; charsWritten = 0; - } - public int getBufferSize() { return grizzlyOutputBuffer.getBufferSize(); } - public boolean isReady() { if (!prevIsReady) { return false; @@ -460,7 +384,7 @@ public boolean isReady() { } } else { - prevIsReady = true; // Allow next .isReady() call to check underlying outputStream + prevIsReady = true; // Allow next .isReady() call to check underlying outputStream } } @@ -472,7 +396,7 @@ public void setWriteListener(WriteListener writeListener) { throw new IllegalStateException(rb.getString(LogFacade.WRITE_LISTENER_BEEN_SET)); } - Request req = (Request)response.getRequest(); + Request req = (Request) response.getRequest(); if (!(req.isAsyncStarted() || req.isUpgrade())) { throw new IllegalStateException(rb.getString(LogFacade.NON_ASYNC_UPGRADE_WRITER_EXCEPTION)); } @@ -482,7 +406,7 @@ public void setWriteListener(WriteListener writeListener) { if (isReady()) { try { writeHandler.onWritePossible(); - } catch(Throwable t) { + } catch (Throwable t) { log.log(Level.WARNING, LogFacade.WRITE_LISTENER_ON_WRITE_POSSIBLE_ERROR, t); } } @@ -490,13 +414,12 @@ public void setWriteListener(WriteListener writeListener) { void disableWriteHandler() { if (writeHandler != null) { - synchronized(writeHandler) { + synchronized (writeHandler) { writeHandler.onError(new InterruptedByTimeoutException()); } } } - private void addSessionCookies() throws IOException { Request req = (Request) response.getRequest(); if (req.isRequestedSessionIdFromURL()) { @@ -523,46 +446,34 @@ private void addSessionCookies() throws IOException { /** * Adds a session version cookie to the response if necessary. */ - private void addSessionVersionCookie(Request request, - StandardContext context) { - Map sessionVersions = - request.getSessionVersionsRequestAttribute(); + private void addSessionVersionCookie(Request request, StandardContext context) { + Map sessionVersions = request.getSessionVersionsRequestAttribute(); if (sessionVersions != null) { - Cookie cookie = new Cookie( - Globals.SESSION_VERSION_COOKIE_NAME, - RequestUtil.createSessionVersionString(sessionVersions)); + Cookie cookie = new Cookie(Globals.SESSION_VERSION_COOKIE_NAME, RequestUtil.createSessionVersionString(sessionVersions)); request.configureSessionCookie(cookie); if (request.isRequestedSessionIdFromCookie()) { /* - * Have the JSESSIONIDVERSION cookie inherit the - * security setting of the JSESSIONID cookie to avoid - * session loss when switching from HTTPS to HTTP, - * see IT 7414 + * Have the JSESSIONIDVERSION cookie inherit the security setting of the JSESSIONID cookie to avoid session loss when + * switching from HTTPS to HTTP, see IT 7414 */ - cookie.setSecure( - request.isRequestedSessionIdFromSecureCookie()); + cookie.setSecure(request.isRequestedSessionIdFromSecureCookie()); } - grizzlyResponse.addHeader(SET_COOKIE_HEADER, - response.getCookieString(cookie)); + grizzlyResponse.addHeader(SET_COOKIE_HEADER, response.getCookieString(cookie)); } } /** * Adds JSESSIONID cookie whose value includes jvmRoute if necessary. */ - private void addSessionCookieWithJvmRoute(Request request, StandardContext ctx, - Session sess) { - + private void addSessionCookieWithJvmRoute(Request request, StandardContext ctx, Session sess) { if (ctx.getJvmRoute() == null || sess == null) { return; } // Create JSESSIONID cookie that includes jvmRoute - Cookie cookie = getSafeCookie(ctx.getSessionCookieName(), - sess.getIdInternal() + "." + ctx.getJvmRoute()); + Cookie cookie = getSafeCookie(ctx.getSessionCookieName(), sess.getIdInternal() + "." + ctx.getJvmRoute()); request.configureSessionCookie(cookie); - grizzlyResponse.addHeader(SET_COOKIE_HEADER, - response.getCookieString(cookie)); + grizzlyResponse.addHeader(SET_COOKIE_HEADER, response.getCookieString(cookie)); } private Cookie getSafeCookie(String name, String value) { @@ -584,13 +495,11 @@ private Cookie getSafeCookie(String name, String value) { /** * Adds JSESSIONID cookie whose value includes jvmRoute if necessary. */ - private void addSessionCookieWithJReplica(Request request, StandardContext ctx, - Session sess) { - + private void addSessionCookieWithJReplica(Request request, StandardContext ctx, Session sess) { String replicaLocation = null; if (sess != null) { - replicaLocation = (String)sess.getNote(Globals.JREPLICA_SESSION_NOTE); + replicaLocation = (String) sess.getNote(Globals.JREPLICA_SESSION_NOTE); sess.removeNote(Globals.JREPLICA_SESSION_NOTE); } @@ -598,11 +507,9 @@ private void addSessionCookieWithJReplica(Request request, StandardContext ctx, Cookie cookie = getSafeCookie(Globals.JREPLICA_COOKIE_NAME, replicaLocation); request.configureSessionCookie(cookie); if (request.isRequestedSessionIdFromCookie()) { - cookie.setSecure( - request.isRequestedSessionIdFromSecureCookie()); + cookie.setSecure(request.isRequestedSessionIdFromSecureCookie()); } - grizzlyResponse.addHeader(SET_COOKIE_HEADER, - response.getCookieString(cookie)); + grizzlyResponse.addHeader(SET_COOKIE_HEADER, response.getCookieString(cookie)); } } @@ -611,18 +518,13 @@ private void addSessionCookieWithJReplica(Request request, StandardContext ctx, * Adds JSESSIONSSOVERSION cookie */ private void addSsoVersionCookie(Request request, StandardContext ctx) { - - Long ssoVersion = (Long)request.getNote( - org.apache.catalina.authenticator.Constants.REQ_SSO_VERSION_NOTE); + Long ssoVersion = (Long) request.getNote(org.apache.catalina.authenticator.Constants.REQ_SSO_VERSION_NOTE); if (ssoVersion != null) { - Cookie cookie = new Cookie( - org.apache.catalina.authenticator.Constants.SINGLE_SIGN_ON_VERSION_COOKIE, - ssoVersion.toString()); + Cookie cookie = new Cookie(org.apache.catalina.authenticator.Constants.SINGLE_SIGN_ON_VERSION_COOKIE, ssoVersion.toString()); cookie.setMaxAge(-1); cookie.setPath("/"); StandardHost host = (StandardHost) ctx.getParent(); - HttpServletRequest hreq = - (HttpServletRequest)request.getRequest(); + HttpServletRequest hreq = request.getRequest(); if (host != null) { host.configureSingleSignOnCookieSecure(cookie, hreq); host.configureSingleSignOnCookieHttpOnly(cookie); @@ -630,28 +532,22 @@ private void addSsoVersionCookie(Request request, StandardContext ctx) { cookie.setSecure(hreq.isSecure()); } - grizzlyResponse.addHeader(SET_COOKIE_HEADER, - response.getCookieString(cookie)); + grizzlyResponse.addHeader(SET_COOKIE_HEADER, response.getCookieString(cookie)); } } - private void addPersistedSessionCookie(Request request, StandardContext ctx, - Session sess) throws IOException { - + private void addPersistedSessionCookie(Request request, StandardContext ctx, Session sess) throws IOException { if (sess == null) { return; } Cookie cookie = ctx.getManager().toCookie(sess); if (cookie != null) { request.configureSessionCookie(cookie); - grizzlyResponse.addHeader(SET_COOKIE_HEADER, - response.getCookieString(cookie)); + grizzlyResponse.addHeader(SET_COOKIE_HEADER, response.getCookieString(cookie)); } } - private void addJrouteCookie(Request request, StandardContext ctx, - Session sess) { - + private void addJrouteCookie(Request request, StandardContext ctx, Session sess) { String jrouteId = request.getHeader(Constants.PROXY_JROUTE); if (jrouteId == null) { @@ -664,37 +560,28 @@ private void addJrouteCookie(Request request, StandardContext ctx, return; } - if (request.getJrouteId() == null - || !request.getJrouteId().equals(jrouteId)) { + if (request.getJrouteId() == null || !request.getJrouteId().equals(jrouteId)) { // Initial request or failover Cookie cookie = getSafeCookie(Constants.JROUTE_COOKIE, jrouteId); request.configureSessionCookie(cookie); if (request.isRequestedSessionIdFromCookie()) { /* - * Have the JSESSIONIDVERSION cookie inherit the - * security setting of the JSESSIONID cookie to avoid - * session loss when switching from HTTPS to HTTP, - * see IT 7414 + * Have the JSESSIONIDVERSION cookie inherit the security setting of the JSESSIONID cookie to avoid session loss when + * switching from HTTPS to HTTP, see IT 7414 */ - cookie.setSecure( - request.isRequestedSessionIdFromSecureCookie()); + cookie.setSecure(request.isRequestedSessionIdFromSecureCookie()); } - grizzlyResponse.addHeader(SET_COOKIE_HEADER, - response.getCookieString(cookie)); + grizzlyResponse.addHeader(SET_COOKIE_HEADER, response.getCookieString(cookie)); } } - // START PWC 6512276 /** * Are there any pending writes waiting to be flushed? */ public boolean hasData() { - - return !suspended && (!grizzlyResponse.isCommitted() || - grizzlyOutputBuffer.getBufferedDataSize() > 0); + return !suspended && (!grizzlyResponse.isCommitted() || grizzlyOutputBuffer.getBufferedDataSize() > 0); } - // END PWC 6512276 private class SessionCookieChecker implements org.glassfish.grizzly.http.io.OutputBuffer.LifeCycleListener { @@ -713,6 +600,7 @@ private WriteHandlerImpl(WriteListener listener) { writeListener = listener; } + @Override public void onWritePossible() { if (disable) { return; @@ -730,48 +618,31 @@ public void run() { } private void processWritePossible() { - ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { Context context = response.getContext(); ClassLoader newCL = context.getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); - synchronized(this) { + synchronized (this) { prevIsReady = true; try { - context.fireContainerEvent( - ContainerEvent.BEFORE_WRITE_LISTENER_ON_WRITE_POSSIBLE, writeListener); + context.fireContainerEvent(ContainerEvent.BEFORE_WRITE_LISTENER_ON_WRITE_POSSIBLE, writeListener); writeListener.onWritePossible(); - } catch(Throwable t) { + } catch (Throwable t) { disable = true; writeListener.onError(t); } finally { - context.fireContainerEvent( - ContainerEvent.AFTER_WRITE_LISTENER_ON_WRITE_POSSIBLE, writeListener); + context.fireContainerEvent(ContainerEvent.AFTER_WRITE_LISTENER_ON_WRITE_POSSIBLE, writeListener); } } } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } + @Override public void onError(final Throwable t) { if (disable) { return; @@ -791,66 +662,24 @@ public void run() { } private void processError(final Throwable t) { - ClassLoader oldCL; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedGetTccl(); - oldCL = AccessController.doPrivileged(pa); - } else { - oldCL = Thread.currentThread().getContextClassLoader(); - } + ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); try { Context context = response.getContext(); ClassLoader newCL = context.getLoader().getClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(newCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(newCL); - } + Thread.currentThread().setContextClassLoader(newCL); - synchronized(this) { + synchronized (this) { try { - context.fireContainerEvent( - ContainerEvent.BEFORE_WRITE_LISTENER_ON_ERROR, writeListener); + context.fireContainerEvent(ContainerEvent.BEFORE_WRITE_LISTENER_ON_ERROR, writeListener); writeListener.onError(t); } finally { - context.fireContainerEvent( - ContainerEvent.AFTER_WRITE_LISTENER_ON_ERROR, writeListener); + context.fireContainerEvent(ContainerEvent.AFTER_WRITE_LISTENER_ON_ERROR, writeListener); } } } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl(oldCL); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldCL); - } + Thread.currentThread().setContextClassLoader(oldCL); } } } - - private static class PrivilegedSetTccl implements PrivilegedAction { - - private ClassLoader cl; - - PrivilegedSetTccl(ClassLoader cl) { - this.cl = cl; - } - - @Override - public Void run() { - Thread.currentThread().setContextClassLoader(cl); - return null; - } - } - - private static class PrivilegedGetTccl - implements PrivilegedAction { - - @Override - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java index 108ca4b9684..88bb8935c78 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java @@ -65,9 +65,31 @@ import static org.apache.catalina.connector.Constants.AUTHORIZATION_HEADER; import static org.apache.catalina.connector.Constants.JROUTE_COOKIE; +import com.sun.appserv.ProxyHandler; +import jakarta.servlet.AsyncContext; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.FilterChain; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletConnection; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletRequestAttributeEvent; +import jakarta.servlet.ServletRequestAttributeListener; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.SessionCookieConfig; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletMapping; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpUpgradeHandler; +import jakarta.servlet.http.Part; +import jakarta.servlet.http.PushBuilder; +import jakarta.servlet.http.WebConnection; import java.io.BufferedReader; import java.io.CharConversionException; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; @@ -76,11 +98,7 @@ import java.net.URLDecoder; import java.net.UnknownHostException; import java.nio.charset.UnsupportedCharsetException; -import java.security.AccessController; import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -97,9 +115,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; - import javax.security.auth.Subject; - import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; @@ -118,7 +134,6 @@ import org.apache.catalina.core.StandardHost; import org.apache.catalina.core.StandardWrapper; import org.apache.catalina.fileupload.Multipart; -import org.apache.catalina.security.SecurityUtil; import org.apache.catalina.session.PersistentManagerBase; import org.apache.catalina.session.StandardSession; import org.apache.catalina.util.Enumerator; @@ -143,31 +158,6 @@ import org.glassfish.grizzly.utils.Charsets; import org.glassfish.web.valve.GlassFishValve; -import com.sun.appserv.ProxyHandler; -import com.sun.enterprise.util.Utility; -import jakarta.servlet.AsyncContext; -import jakarta.servlet.DispatcherType; -import jakarta.servlet.FilterChain; -import jakarta.servlet.RequestDispatcher; -import jakarta.servlet.ServletConnection; -import jakarta.servlet.ServletContext; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletInputStream; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletRequestAttributeEvent; -import jakarta.servlet.ServletRequestAttributeListener; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.SessionCookieConfig; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletMapping; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpSession; -import jakarta.servlet.http.HttpUpgradeHandler; -import jakarta.servlet.http.Part; -import jakarta.servlet.http.PushBuilder; -import jakarta.servlet.http.WebConnection; - /** * Wrapper object for the Coyote request. * @@ -1695,25 +1685,6 @@ public void setAttribute(String name, Object value) { boolean replaced = false; - // Do the security check before any updates are made - if (Globals.IS_SECURITY_ENABLED && name.equals("org.apache.tomcat.sendfile.filename")) { - // Use the canonical file name to avoid any possible symlink and - // relative path issues - String canonicalPath; - try { - canonicalPath = new File(value.toString()).getCanonicalPath(); - } catch (IOException e) { - String msg = MessageFormat.format(rb.getString(LogFacade.UNABLE_DETERMINE_CANONICAL_NAME), value); - throw new SecurityException(msg, e); - } - // Sendfile is performed in Tomcat's security context so need to - // check if the web app is permitted to access the file while still - // in the web app's security context - System.getSecurityManager().checkRead(canonicalPath); - // Update the value so the canonical path is used - value = canonicalPath; - } - Object oldValue = attributes.put(name, value); if (oldValue != null) { replaced = true; @@ -1782,23 +1753,7 @@ public void setCharacterEncoding(String enc) throws UnsupportedEncodingException byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; - final byte[] finalBuffer = buffer; - final String finalEnc = enc; - if (Globals.IS_SECURITY_ENABLED) { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public String run() throws UnsupportedEncodingException { - return new String(finalBuffer, RequestUtil.lookupCharset(finalEnc)); - } - }); - } catch (PrivilegedActionException pae) { - throw (UnsupportedEncodingException) pae.getCause(); - } - } else { - new String(buffer, RequestUtil.lookupCharset(enc)); - } + new String(buffer, RequestUtil.lookupCharset(enc)); // Save the validated encoding grizzlyRequest.setCharacterEncoding(enc); @@ -1837,6 +1792,7 @@ public boolean isMaxDispatchDepthReached() { } // ---------------------------------------------------- HttpRequest Methods + @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (context == null) { @@ -1868,23 +1824,9 @@ public boolean authenticate(HttpServletResponse response) throws IOException, Se if (realm == null) { throw new ServletException("Internal error: realm null"); } + try { - if (Globals.IS_SECURITY_ENABLED) { - Boolean ret = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - try { - return Boolean.valueOf( - realm.invokeAuthenticateDelegate(req, (HttpResponse) getResponse(), context, authBase, true)); - } catch (IOException ex) { - throw new RuntimeException("Exception thrown while attempting to authenticate", ex); - } - } - }); - return ret.booleanValue(); - } else { - return realm.invokeAuthenticateDelegate(req, (HttpResponse) getResponse(), context, authBase, true); - } + return realm.invokeAuthenticateDelegate(req, (HttpResponse) getResponse(), context, authBase, true); } catch (Exception ex) { throw new ServletException("Exception thrown while attempting to authenticate", ex); @@ -2193,19 +2135,6 @@ public void setServletPath(String servletPath) { */ @Override public void setUserPrincipal(Principal principal) { - if (SecurityUtil.isPackageProtectionEnabled()) { - HttpSession session = getSession(false); - if (subject != null && !subject.getPrincipals().contains(principal)) { - subject.getPrincipals().add(principal); - } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) { - subject = new Subject(); - subject.getPrincipals().add(principal); - } - if (session != null) { - session.setAttribute(Globals.SUBJECT_ATTR, subject); - } - } - this.userPrincipal = principal; } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java index 02fd421fec2..e15bdc3dab0 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java @@ -18,25 +18,8 @@ package org.apache.catalina.connector; -import static org.apache.catalina.Globals.IS_SECURITY_ENABLED; -import static org.apache.catalina.security.SecurityUtil.isPackageProtectionEnabled; import com.sun.enterprise.security.ee.web.integration.WebPrincipal; -import java.io.BufferedReader; -import java.io.IOException; -import java.security.AccessControlException; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.SecurityPermission; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; - -import org.apache.catalina.LogFacade; -import org.apache.catalina.core.RequestFacadeHelper; import jakarta.servlet.AsyncContext; import jakarta.servlet.DispatcherType; import jakarta.servlet.RequestDispatcher; @@ -54,6 +37,17 @@ import jakarta.servlet.http.HttpUpgradeHandler; import jakarta.servlet.http.Part; import jakarta.servlet.http.PushBuilder; +import java.io.BufferedReader; +import java.io.IOException; +import java.security.Principal; +import java.security.SecurityPermission; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import org.apache.catalina.LogFacade; +import org.apache.catalina.core.RequestFacadeHelper; /** * Facade class that wraps a Catalina connector request object. All methods are delegated to the wrapped request. @@ -150,10 +144,6 @@ public Object getAttribute(String name) { public Enumeration getAttributeNames() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetAttributePrivilegedAction()); - } - return catalinaConnectorReqest.getAttributeNames(); } @@ -161,10 +151,6 @@ public Enumeration getAttributeNames() { public String getCharacterEncoding() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetCharacterEncodingPrivilegedAction()); - } - return catalinaConnectorReqest.getCharacterEncoding(); } @@ -214,10 +200,6 @@ public HttpServletMapping getHttpServletMapping() { public String getParameter(String name) { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetParameterPrivilegedAction(name)); - } - return catalinaConnectorReqest.getParameter(name); } @@ -225,10 +207,6 @@ public String getParameter(String name) { public Enumeration getParameterNames() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetParameterNamesPrivilegedAction()); - } - return catalinaConnectorReqest.getParameterNames(); } @@ -236,32 +214,13 @@ public Enumeration getParameterNames() { public String[] getParameterValues(String name) { checkRequestNull(); - String[] ret = null; - - /* - * Clone the returned array only if there is a security manager in place, so that performance won't suffer in the - * non-secure case - */ - if (isPackageProtectionEnabled()) { - ret = AccessController.doPrivileged(new GetParameterValuePrivilegedAction(name)); - if (ret != null) { - ret = ret.clone(); - } - } else { - ret = catalinaConnectorReqest.getParameterValues(name); - } - - return ret; + return catalinaConnectorReqest.getParameterValues(name); } @Override public Map getParameterMap() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetParameterMapPrivilegedAction()); - } - return catalinaConnectorReqest.getParameterMap(); } @@ -332,10 +291,6 @@ public void removeAttribute(String name) { public Locale getLocale() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetLocalePrivilegedAction()); - } - return catalinaConnectorReqest.getLocale(); } @@ -343,11 +298,7 @@ public Locale getLocale() { public Enumeration getLocales() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetLocalesPrivilegedAction()); - } else { - return catalinaConnectorReqest.getLocales(); - } + return catalinaConnectorReqest.getLocales(); } @Override @@ -361,10 +312,6 @@ public boolean isSecure() { public RequestDispatcher getRequestDispatcher(String path) { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetRequestDispatcherPrivilegedAction(path)); - } - return catalinaConnectorReqest.getRequestDispatcher(path); } @@ -379,22 +326,7 @@ public String getAuthType() { public Cookie[] getCookies() { checkRequestNull(); - Cookie[] ret = null; - - /* - * Clone the returned array only if there is a security manager in place, so that performance won't suffer in the - * non-secure case - */ - if (isPackageProtectionEnabled()) { - ret = AccessController.doPrivileged(new GetCookiesPrivilegedAction()); - if (ret != null) { - ret = ret.clone(); - } - } else { - ret = catalinaConnectorReqest.getCookies(); - } - - return ret; + return catalinaConnectorReqest.getCookies(); } @Override @@ -415,10 +347,6 @@ public String getHeader(String name) { public Enumeration getHeaders(String name) { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetHeadersPrivilegedAction(name)); - } - return catalinaConnectorReqest.getHeaders(name); } @@ -426,10 +354,6 @@ public Enumeration getHeaders(String name) { public Enumeration getHeaderNames() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetHeaderNamesPrivilegedAction()); - } - return catalinaConnectorReqest.getHeaderNames(); } @@ -573,10 +497,6 @@ public String getServletPath() { public HttpSession getSession(boolean create) { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new GetSessionPrivilegedAction(create)); - } - return catalinaConnectorReqest.getSession(create); } @@ -591,10 +511,6 @@ public HttpSession getSession() { public String changeSessionId() { checkRequestNull(); - if (isPackageProtectionEnabled()) { - return AccessController.doPrivileged(new ChangeSessionIdPrivilegedAction()); - } - return catalinaConnectorReqest.changeSessionId(); } @@ -754,13 +670,7 @@ public PushBuilder newPushBuilder() { /** * Return the original CoyoteRequest object. */ - public Request getUnwrappedCoyoteRequest() throws AccessControlException { - // Tomcat does not have any Permission types so instead of - // creating a TomcatPermission for this, use SecurityPermission. - if (IS_SECURITY_ENABLED) { - AccessController.checkPermission(GET_UNWRAPPED_COYOTE_REQUEST_PERMISSION); - } - + public Request getUnwrappedCoyoteRequest() { return catalinaConnectorReqest; } @@ -791,147 +701,4 @@ private void checkRequestNull() { } } - // ----------------------------------------------------------- DoPrivileged - - private final class GetAttributePrivilegedAction implements PrivilegedAction> { - - @Override - public Enumeration run() { - return catalinaConnectorReqest.getAttributeNames(); - } - } - - private final class GetParameterMapPrivilegedAction implements PrivilegedAction> { - - @Override - public Map run() { - return catalinaConnectorReqest.getParameterMap(); - } - } - - private final class GetRequestDispatcherPrivilegedAction implements PrivilegedAction { - - private String path; - - public GetRequestDispatcherPrivilegedAction(String path) { - this.path = path; - } - - @Override - public RequestDispatcher run() { - return catalinaConnectorReqest.getRequestDispatcher(path); - } - } - - private final class GetParameterPrivilegedAction implements PrivilegedAction { - - public String name; - - public GetParameterPrivilegedAction(String name) { - this.name = name; - } - - @Override - public String run() { - return catalinaConnectorReqest.getParameter(name); - } - } - - private final class GetParameterNamesPrivilegedAction implements PrivilegedAction> { - - @Override - public Enumeration run() { - return catalinaConnectorReqest.getParameterNames(); - } - } - - private final class GetParameterValuePrivilegedAction implements PrivilegedAction { - - public String name; - - public GetParameterValuePrivilegedAction(String name) { - this.name = name; - } - - @Override - public String[] run() { - return catalinaConnectorReqest.getParameterValues(name); - } - } - - private final class GetCookiesPrivilegedAction implements PrivilegedAction { - - @Override - public Cookie[] run() { - return catalinaConnectorReqest.getCookies(); - } - } - - private final class GetCharacterEncodingPrivilegedAction implements PrivilegedAction { - - @Override - public String run() { - return catalinaConnectorReqest.getCharacterEncoding(); - } - } - - private final class GetHeadersPrivilegedAction implements PrivilegedAction> { - - private String name; - - public GetHeadersPrivilegedAction(String name) { - this.name = name; - } - - @Override - public Enumeration run() { - return catalinaConnectorReqest.getHeaders(name); - } - } - - private final class GetHeaderNamesPrivilegedAction implements PrivilegedAction> { - - @Override - public Enumeration run() { - return catalinaConnectorReqest.getHeaderNames(); - } - } - - private final class GetLocalePrivilegedAction implements PrivilegedAction { - - @Override - public Locale run() { - return catalinaConnectorReqest.getLocale(); - } - } - - private final class GetLocalesPrivilegedAction implements PrivilegedAction> { - - @Override - public Enumeration run() { - return catalinaConnectorReqest.getLocales(); - } - } - - private final class GetSessionPrivilegedAction implements PrivilegedAction { - - private boolean create; - - public GetSessionPrivilegedAction(boolean create) { - this.create = create; - } - - @Override - public HttpSession run() { - return catalinaConnectorReqest.getSession(create); - } - } - - private final class ChangeSessionIdPrivilegedAction implements PrivilegedAction { - - @Override - public String run() { - return catalinaConnectorReqest.changeSessionId(); - } - } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java index 465a5f9b7a1..490cd45744a 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java @@ -33,15 +33,15 @@ import static org.glassfish.common.util.InputValidationUtil.getSafeHeaderValue; import static org.glassfish.web.util.HtmlEntityEncoder.encodeXSS; +import com.sun.appserv.ProxyHandler; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; @@ -53,14 +53,12 @@ import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; - import org.apache.catalina.Connector; import org.apache.catalina.Context; import org.apache.catalina.HttpResponse; import org.apache.catalina.LogFacade; import org.apache.catalina.Session; import org.apache.catalina.core.StandardContext; -import org.apache.catalina.security.SecurityUtil; import org.apache.catalina.util.RequestUtil; import org.glassfish.grizzly.http.util.CharChunk; import org.glassfish.grizzly.http.util.CookieHeaderGenerator; @@ -68,14 +66,6 @@ import org.glassfish.grizzly.http.util.MimeHeaders; import org.glassfish.grizzly.http.util.UEncoder; -import com.sun.appserv.ProxyHandler; - -import jakarta.servlet.ServletOutputStream; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletResponse; - -// END S1AS 6170450 - /** * Wrapper object for the Coyote response. * @@ -796,15 +786,9 @@ public void setContentType(String type) { while (index < len && Character.isWhitespace(type.charAt(index))) { index++; } - if (index + 7 < len && - type.charAt(index) == 'c' && - type.charAt(index + 1) == 'h' && - type.charAt(index + 2) == 'a' && - type.charAt(index + 3) == 'r' && - type.charAt(index + 4) == 's' && - type.charAt(index + 5) == 'e' && - type.charAt(index + 6) == 't' && - type.charAt(index + 7) == '=') { + if (index + 7 < len && type.charAt(index) == 'c' && type.charAt(index + 1) == 'h' && type.charAt(index + 2) == 'a' + && type.charAt(index + 3) == 'r' && type.charAt(index + 4) == 's' && type.charAt(index + 5) == 'e' + && type.charAt(index + 6) == 't' && type.charAt(index + 7) == '=') { isCharacterEncodingSet = true; } } @@ -1285,9 +1269,7 @@ public void setHeader(String name, String value) { } try { - grizzlyResponse.setHeader( - getSafeHeaderName(name), - getSafeHeaderValue(value)); + grizzlyResponse.setHeader(getSafeHeaderName(name), getSafeHeaderValue(value)); } catch (Exception e) { try { grizzlyResponse.sendError(403, "Forbidden"); @@ -1376,16 +1358,7 @@ protected boolean isEncodeable(final String location) { return false; } - if (SecurityUtil.isPackageProtectionEnabled()) { - return (AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - return Boolean.valueOf(doIsEncodeable(connectorRequest, session, location)); - } - })).booleanValue(); - } else { - return doIsEncodeable(connectorRequest, session, location); - } + return doIsEncodeable(connectorRequest, session, location); } private boolean doIsEncodeable(Request hreq, Session session, String location) { @@ -1499,25 +1472,7 @@ protected String toAbsolute(String location) { String relativePath = connectorRequest.getDecodedRequestURI(); relativePath = relativePath.substring(0, relativePath.lastIndexOf('/')); - String encodedURI = null; - final String frelativePath = relativePath; - - if (SecurityUtil.isPackageProtectionEnabled()) { - try { - encodedURI = AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public String run() throws IOException { - return urlEncoder.encodeURL(frelativePath); - } - }); - } catch (PrivilegedActionException pae) { - IllegalArgumentException iae = new IllegalArgumentException(location); - iae.initCause(pae.getCause()); - throw iae; - } - } else { - encodedURI = urlEncoder.encodeURL(relativePath); - } + String encodedURI = urlEncoder.encodeURL(relativePath); redirectURLCharChunk.append(encodedURI, 0, encodedURI.length()); redirectURLCharChunk.append('/'); @@ -1640,37 +1595,9 @@ protected CoyoteWriter createWriter(OutputBuffer outbuf) { * @return The cookie's string representation */ protected String getCookieString(final Cookie cookie) { - String cookieValue = null; - - if (SecurityUtil.isPackageProtectionEnabled()) { - cookieValue = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public String run() { - return CookieHeaderGenerator.generateHeader( - cookie.getName(), - cookie.getValue(), - cookie.getMaxAge(), - cookie.getDomain(), - cookie.getPath(), - cookie.getSecure(), - cookie.isHttpOnly(), - cookie.getAttributes()); - } - }); - } else { - cookieValue = - CookieHeaderGenerator.generateHeader( - cookie.getName(), - cookie.getValue(), - cookie.getMaxAge(), - cookie.getDomain(), - cookie.getPath(), - cookie.getSecure(), - cookie.isHttpOnly(), - cookie.getAttributes()); - } - - return cookieValue; + return CookieHeaderGenerator.generateHeader( + cookie.getName(), cookie.getValue(), cookie.getMaxAge(), cookie.getDomain(), + cookie.getPath(), cookie.getSecure(), cookie.isHttpOnly(), cookie.getAttributes()); } /** diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java index 82466c2de7b..c47d6febe8d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java @@ -20,26 +20,20 @@ import static org.apache.catalina.LogFacade.NULL_RESPONSE_OBJECT; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.UnsupportedCharsetException; -import java.security.AccessController; import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; - import org.apache.catalina.LogFacade; -import org.apache.catalina.security.SecurityUtil; - -import jakarta.servlet.ServletOutputStream; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletResponse; /** * Facade class that wraps a Coyote response object. All methods are delegated to the wrapped response. @@ -186,11 +180,7 @@ public void setContentType(String type) { return; } - if (SecurityUtil.isPackageProtectionEnabled()) { - AccessController.doPrivileged(new SetContentTypePrivilegedAction(type)); - } else { - response.setContentType(type); - } + response.setContentType(type); } @Override @@ -216,28 +206,8 @@ public void flushBuffer() throws IOException { return; } - if (SecurityUtil.isPackageProtectionEnabled()) { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public Void run() throws IOException { - response.setAppCommitted(true); - - response.flushBuffer(); - return null; - } - }); - } catch (PrivilegedActionException e) { - Exception ex = e.getException(); - if (ex instanceof IOException) { - throw (IOException) ex; - } - } - } else { - response.setAppCommitted(true); - response.flushBuffer(); - } + response.setAppCommitted(true); + response.flushBuffer(); } @Override diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContextFacade.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContextFacade.java index 6cb4193af02..3c382f454ed 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContextFacade.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContextFacade.java @@ -18,7 +18,6 @@ package org.apache.catalina.core; -import jakarta.servlet.DispatcherType; import jakarta.servlet.Filter; import jakarta.servlet.FilterRegistration; import jakarta.servlet.RequestDispatcher; @@ -29,22 +28,16 @@ import jakarta.servlet.SessionCookieConfig; import jakarta.servlet.SessionTrackingMode; import jakarta.servlet.descriptor.JspConfigDescriptor; - import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.Collection; -import java.util.EnumSet; import java.util.Enumeration; import java.util.EventListener; import java.util.Map; import java.util.Set; -import static org.apache.catalina.Globals.IS_SECURITY_ENABLED; /** * Facade object which masks the internal ApplicationContext @@ -72,26 +65,17 @@ public ApplicationContextFacade(ApplicationContext context) { @Override public String getContextPath() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getContextPath; - return AccessController.doPrivileged(action); - } return context.getContextPath(); } @Override public ServletContext getContext(String uripath) { - final ServletContext theContext; - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getContext(uripath); - theContext = AccessController.doPrivileged(action); - } else { - theContext = context.getContext(uripath); - } + final ServletContext theContext = context.getContext(uripath); if (theContext instanceof ApplicationContext) { return ((ApplicationContext) theContext).getFacade(); } + return theContext; } @@ -122,285 +106,154 @@ public int getEffectiveMinorVersion() { @Override public String getMimeType(String file) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getMimeType(file); - return AccessController.doPrivileged(action); - } return context.getMimeType(file); } @Override public Set getResourcePaths(String path) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = () -> context.getResourcePaths(path); - return AccessController.doPrivileged(action); - } return context.getResourcePaths(path); } @Override public URL getResource(String path) throws MalformedURLException { - if (IS_SECURITY_ENABLED) { - PrivilegedExceptionAction action = () -> context.getResource(path); - try { - return AccessController.doPrivileged(action); - } catch (PrivilegedActionException e) { - throw (MalformedURLException) e.getCause(); - } - } return context.getResource(path); } @Override public InputStream getResourceAsStream(String path) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getResourceAsStream(path); - return AccessController.doPrivileged(action); - } return context.getResourceAsStream(path); } @Override public RequestDispatcher getRequestDispatcher(final String path) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getRequestDispatcher(path); - return AccessController.doPrivileged(action); - } return context.getRequestDispatcher(path); } @Override public RequestDispatcher getNamedDispatcher(String name) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getNamedDispatcher(name); - return AccessController.doPrivileged(action); - } return context.getNamedDispatcher(name); } @Override public void log(String msg) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.log(msg); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.log(msg); - } + context.log(msg); } @Override public void log(String message, Throwable throwable) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.log(message, throwable); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.log(message, throwable); - } + context.log(message, throwable); } @Override public String getRealPath(String path) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getRealPath(path); - return AccessController.doPrivileged(action); - } return context.getRealPath(path); } @Override public String getServerInfo() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getServerInfo; - return AccessController.doPrivileged(action); - } return context.getServerInfo(); } @Override public String getInitParameter(String name) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getInitParameter(name); - return AccessController.doPrivileged(action); - } return context.getInitParameter(name); } @Override public Enumeration getInitParameterNames() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = context::getInitParameterNames; - return AccessController.doPrivileged(action); - } return context.getInitParameterNames(); } @Override public boolean setInitParameter(String name, String value) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.setInitParameter(name, value); - return null; - }; - AccessController.doPrivileged(action); - } return context.setInitParameter(name, value); } @Override public Object getAttribute(String name) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getAttribute(name); - return AccessController.doPrivileged(action); - } return context.getAttribute(name); } @Override public Enumeration getAttributeNames() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = context::getAttributeNames; - return AccessController.doPrivileged(action); - } return context.getAttributeNames(); } @Override public void setAttribute(String name, Object object) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.setAttribute(name, object); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.setAttribute(name, object); - } + context.setAttribute(name, object); } @Override public void removeAttribute(String name) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.removeAttribute(name); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.removeAttribute(name); - } + context.removeAttribute(name); } @Override public String getServletContextName() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getServletContextName; - return AccessController.doPrivileged(action); - } return context.getServletContextName(); } @Override public ServletRegistration.Dynamic addServlet(String servletName, String className) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addServlet(servletName, className); - return AccessController.doPrivileged(action); - } return context.addServlet(servletName, className); } @Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addServlet(servletName, servlet); - return AccessController.doPrivileged(action); - } return context.addServlet(servletName, servlet); } @Override public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addServlet(servletName, servletClass); - return AccessController.doPrivileged(action); - } return context.addServlet(servletName, servletClass); } @Override public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addJspFile(servletName, jspFile); - return AccessController.doPrivileged(action); - } return context.addJspFile(servletName, jspFile); } @Override public T createServlet(Class clazz) throws ServletException { - if (IS_SECURITY_ENABLED) { - PrivilegedExceptionAction action = () -> context.createServlet(clazz); - try { - return AccessController.doPrivileged(action); - } catch (PrivilegedActionException e) { - throw (ServletException) e.getCause(); - } - } return context.createServlet(clazz); } @Override public ServletRegistration getServletRegistration(String servletName) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getServletRegistration(servletName); - return AccessController.doPrivileged(action); - } return context.getServletRegistration(servletName); } @Override public Map getServletRegistrations() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = context::getServletRegistrations; - return AccessController.doPrivileged(action); - } return context.getServletRegistrations(); } @Override public FilterRegistration.Dynamic addFilter(String filterName, String className) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addFilter(filterName, className); - return AccessController.doPrivileged(action); - } return context.addFilter(filterName, className); } @@ -418,11 +271,6 @@ public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) { wrappedFilter = filter; } - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addFilter(filterName, wrappedFilter); - return AccessController.doPrivileged(action); - } - FilterRegistration.Dynamic registration = context.addFilter(filterName, wrappedFilter); if (registration == null && "WebSocket filter".equals(filterName)) { @@ -438,254 +286,126 @@ public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) { @Override public FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.addFilter(filterName, filterClass); - return AccessController.doPrivileged(action); - } return context.addFilter(filterName, filterClass); } @Override public T createFilter(Class clazz) throws ServletException { - if (IS_SECURITY_ENABLED) { - PrivilegedExceptionAction action = () -> context.createFilter(clazz); - try { - return AccessController.doPrivileged(action); - } catch (PrivilegedActionException e) { - throw (ServletException) e.getCause(); - } - } return context.createFilter(clazz); } @Override public FilterRegistration getFilterRegistration(String filterName) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> context.getFilterRegistration(filterName); - return AccessController.doPrivileged(action); - } return context.getFilterRegistration(filterName); } @Override public Map getFilterRegistrations() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = context::getFilterRegistrations; - return AccessController.doPrivileged(action); - } return context.getFilterRegistrations(); } @Override public SessionCookieConfig getSessionCookieConfig() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getSessionCookieConfig; - return AccessController.doPrivileged(action); - } return context.getSessionCookieConfig(); } @Override public void setSessionTrackingModes(Set sessionTrackingModes) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.setSessionTrackingModes(sessionTrackingModes); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.setSessionTrackingModes(sessionTrackingModes); - } + context.setSessionTrackingModes(sessionTrackingModes); } @Override public Set getDefaultSessionTrackingModes() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = context::getDefaultSessionTrackingModes; - return AccessController.doPrivileged(action); - } return context.getDefaultSessionTrackingModes(); } @Override public Set getEffectiveSessionTrackingModes() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction> action = context::getEffectiveSessionTrackingModes; - return AccessController.doPrivileged(action); - } return context.getEffectiveSessionTrackingModes(); } @Override public void addListener(String className) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.addListener(className); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.addListener(className); - } + context.addListener(className); } @Override public void addListener(T listener) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.addListener(listener); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.addListener(listener); - } + context.addListener(listener); } @Override public void addListener(Class listenerClass) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.addListener(listenerClass); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.addListener(listenerClass); - } + context.addListener(listenerClass); } @Override public T createListener(Class clazz) throws ServletException { - if (IS_SECURITY_ENABLED) { - PrivilegedExceptionAction action = () -> context.createListener(clazz); - try { - return AccessController.doPrivileged(action); - } catch (PrivilegedActionException e) { - throw (ServletException) e.getCause(); - } - } return context.createListener(clazz); } @Override public JspConfigDescriptor getJspConfigDescriptor() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getJspConfigDescriptor; - return AccessController.doPrivileged(action); - } return context.getJspConfigDescriptor(); } @Override public ClassLoader getClassLoader() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getClassLoader; - return AccessController.doPrivileged(action); - } return context.getClassLoader(); } @Override public void declareRoles(String... roleNames) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.declareRoles(roleNames); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.declareRoles(roleNames); - } + context.declareRoles(roleNames); } @Override public String getVirtualServerName() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getVirtualServerName; - return AccessController.doPrivileged(action); - } return context.getVirtualServerName(); } @Override public int getSessionTimeout() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getSessionTimeout; - return AccessController.doPrivileged(action); - } return context.getSessionTimeout(); } @Override public void setSessionTimeout(int sessionTimeout) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.setSessionTimeout(sessionTimeout); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.setSessionTimeout(sessionTimeout); - } + context.setSessionTimeout(sessionTimeout); } @Override public String getRequestCharacterEncoding() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getRequestCharacterEncoding; - return AccessController.doPrivileged(action); - } return context.getRequestCharacterEncoding(); } @Override public void setRequestCharacterEncoding(String encoding) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.setRequestCharacterEncoding(encoding); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.setRequestCharacterEncoding(encoding); - } + context.setRequestCharacterEncoding(encoding); } @Override public String getResponseCharacterEncoding() { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = context::getResponseCharacterEncoding; - return AccessController.doPrivileged(action); - } return context.getResponseCharacterEncoding(); } @Override public void setResponseCharacterEncoding(String encoding) { - if (IS_SECURITY_ENABLED) { - PrivilegedAction action = () -> { - context.setResponseCharacterEncoding(encoding); - return null; - }; - AccessController.doPrivileged(action); - } else { - context.setResponseCharacterEncoding(encoding); - } + context.setResponseCharacterEncoding(encoding); } @Override diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java index cff441a383a..1f3af30d222 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java @@ -18,6 +18,12 @@ package org.apache.catalina.core; import static com.sun.logging.LogCleanerUtil.neutralizeForLog; +import static jakarta.servlet.DispatcherType.ASYNC; +import static jakarta.servlet.DispatcherType.ERROR; +import static jakarta.servlet.DispatcherType.FORWARD; +import static jakarta.servlet.DispatcherType.INCLUDE; +import static java.util.logging.Level.FINE; + import org.apache.catalina.*; import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.Request; @@ -29,7 +35,6 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ResourceBundle; @@ -38,7 +43,6 @@ import java.text.MessageFormat; import jakarta.servlet.http.HttpServletMapping; - import static org.apache.catalina.InstanceEvent.EventType.AFTER_DISPATCH_EVENT; import org.apache.catalina.connector.MappingImpl; import org.glassfish.grizzly.http.server.util.Mapper; @@ -47,29 +51,23 @@ import org.glassfish.grizzly.http.util.MessageBytes; /** - * Standard implementation of RequestDispatcher that allows a - * request to be forwarded to a different resource to create the ultimate - * response, or to include the output of another resource in the response - * from this resource. This implementation allows application level servlets - * to wrap the request and/or response objects that are passed on to the - * called resource, as long as the wrapping classes extend - * jakarta.servlet.ServletRequestWrapper and - * jakarta.servlet.ServletResponseWrapper. + * Standard implementation of RequestDispatcher that allows a request to be forwarded to a different + * resource to create the ultimate response, or to include the output of another resource in the response from this + * resource. This implementation allows application level servlets to wrap the request and/or response objects that are + * passed on to the called resource, as long as the wrapping classes extend + * jakarta.servlet.ServletRequestWrapper and jakarta.servlet.ServletResponseWrapper. * * @author Craig R. McClanahan * @version $Revision: 1.16 $ $Date: 2007/02/26 22:57:08 $ */ - -public final class ApplicationDispatcher - implements RequestDispatcher { +public final class ApplicationDispatcher implements RequestDispatcher { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); // This attribute corresponds to a String[] which acts like a stack // containing the last two pushed elements - public static final String LAST_DISPATCH_REQUEST_PATH_ATTR = - "org.apache.catalina.core.ApplicationDispatcher.lastDispatchRequestPathAttr"; + public static final String LAST_DISPATCH_REQUEST_PATH_ATTR = "org.apache.catalina.core.ApplicationDispatcher.lastDispatchRequestPathAttr"; protected class PrivilegedDispatch implements PrivilegedExceptionAction { @@ -77,13 +75,13 @@ protected class PrivilegedDispatch implements PrivilegedExceptionAction { private ServletResponse response; private DispatcherType dispatcherType; - PrivilegedDispatch(ServletRequest request, ServletResponse response, - DispatcherType dispatcherType) { + PrivilegedDispatch(ServletRequest request, ServletResponse response, DispatcherType dispatcherType) { this.request = request; this.response = response; this.dispatcherType = dispatcherType; } + @Override public Void run() throws java.lang.Exception { doDispatch(request, response, dispatcherType); return null; @@ -100,38 +98,38 @@ protected class PrivilegedInclude implements PrivilegedExceptionAction { this.response = response; } + @Override public Void run() throws ServletException, IOException { - doInclude(request,response); + doInclude(request, response); return null; } } /** - * Used to pass state when the request dispatcher is used. Using instance - * variables causes threading issues and state is too complex to pass and - * return single ServletRequest or ServletResponse objects. + * Used to pass state when the request dispatcher is used. Using instance variables causes threading issues and state is + * too complex to pass and return single ServletRequest or ServletResponse objects. */ private static class State { /** * Outermost request that will be passed on to the invoked servlet */ - ServletRequest outerRequest = null; + ServletRequest outerRequest; /** * Outermost response that will be passed on to the invoked servlet. */ - ServletResponse outerResponse = null; + ServletResponse outerResponse; /** * Request wrapper we have created and installed (if any). */ - ServletRequest wrapRequest = null; + ServletRequest wrapRequest; /** * Response wrapper we have created and installed (if any). */ - ServletResponse wrapResponse = null; + ServletResponse wrapResponse; /** * The type of dispatch we are performing @@ -141,15 +139,14 @@ private static class State { /** * Outermost HttpServletRequest in the chain */ - HttpServletRequest hrequest = null; + HttpServletRequest hrequest; /** * Outermost HttpServletResponse in the chain */ - HttpServletResponse hresponse = null; + HttpServletResponse hresponse; - State(ServletRequest request, ServletResponse response, - DispatcherType dispatcherType) { + State(ServletRequest request, ServletResponse response, DispatcherType dispatcherType) { this.outerRequest = request; this.outerResponse = response; this.dispatcherType = dispatcherType; @@ -158,28 +155,21 @@ private static class State { // ----------------------------------------------------------- Constructors - /** - * Construct a new instance of this class, configured according to the - * specified parameters. If both servletPath and pathInfo are - * null, it will be assumed that this RequestDispatcher - * was acquired by name, rather than by path. + * Construct a new instance of this class, configured according to the specified parameters. If both servletPath and + * pathInfo are null, it will be assumed that this RequestDispatcher was acquired by name, rather than by + * path. * - * @param wrapper The Wrapper associated with the resource that will - * be forwarded to or included (required) + * @param wrapper The Wrapper associated with the resource that will be forwarded to or included (required) * @param mappingForDispatch the mapping for this dispatch * @param requestURI The request URI to this resource (if any) * @param servletPath The revised servlet path to this resource (if any) - * @param pathInfo The revised extra path information to this resource - * (if any) - * @param queryString Query string parameters included with this request - * (if any) - * @param name Servlet name (if a named dispatcher was created) - * else null + * @param pathInfo The revised extra path information to this resource (if any) + * @param queryString Query string parameters included with this request (if any) + * @param name Servlet name (if a named dispatcher was created) else null */ - public ApplicationDispatcher - (Wrapper wrapper, HttpServletMapping mappingForDispatch, String requestURI, String servletPath, - String pathInfo, String queryString, String name) { + public ApplicationDispatcher(Wrapper wrapper, HttpServletMapping mappingForDispatch, String requestURI, String servletPath, + String pathInfo, String queryString, String name) { super(); // Save all of our configuration parameters @@ -192,84 +182,76 @@ private static class State { this.queryString = queryString; this.name = name; - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, "servletPath= " + neutralizeForLog(this.servletPath) + ", pathInfo= " - + neutralizeForLog(this.pathInfo) + ", queryString= " + neutralizeForLog(queryString) + ", name= " - + neutralizeForLog(this.name)); + if (log.isLoggable(FINE)) + log.log(FINE, "servletPath= " + neutralizeForLog(this.servletPath) + ", pathInfo= " + neutralizeForLog(this.pathInfo) + + ", queryString= " + neutralizeForLog(queryString) + ", name= " + neutralizeForLog(this.name)); } // ----------------------------------------------------- Instance Variables - //START OF 6364900 /** * is this dispatch cross context */ - private Boolean crossContextFlag = null; - //END OF 6364900 + private Boolean crossContextFlag; /** * The Context this RequestDispatcher is associated with. */ - private Context context = null; + private Context context; /** * Descriptive information about this implementation. */ - private static final String info = - "org.apache.catalina.core.ApplicationDispatcher/1.0"; + private static final String info = "org.apache.catalina.core.ApplicationDispatcher/1.0"; /** * The servlet name for a named dispatcher. */ - private String name = null; + private String name; /** * The extra path information for this RequestDispatcher. */ - private String pathInfo = null; + private String pathInfo; /** * The query string parameters for this RequestDispatcher. */ - private String queryString = null; + private String queryString; /** * The request URI for this RequestDispatcher. */ - private String requestURI = null; + private String requestURI; /** * The servlet path for this RequestDispatcher. */ - private String servletPath = null; + private String servletPath; /** - * The Wrapper associated with the resource that will be forwarded to - * or included. + * The Wrapper associated with the resource that will be forwarded to or included. */ - private Wrapper wrapper = null; + private Wrapper wrapper; private HttpServletMapping mappingForDispatch; // ------------------------------------------------------------- Properties - /** * Return the descriptive information about this implementation. */ public String getInfo() { - return (this.info); + return info; } - // --------------------------------------------------------- Public Methods /** - * Forwards the given request and response to the resource - * for which this dispatcher was acquired. + * Forwards the given request and response to the resource for which this dispatcher was acquired. * - *

Any runtime exceptions, IOException, or ServletException thrown - * by the target will be propagated to the caller. + *

+ * Any runtime exceptions, IOException, or ServletException thrown by the target will be propagated to the caller. * * @param request The request to be forwarded * @param response The response to be forwarded @@ -277,17 +259,16 @@ public String getInfo() { * @throws IOException if an input/output error occurs * @throws ServletException if a servlet exception occurs */ - public void forward(ServletRequest request, ServletResponse response) - throws ServletException, IOException { - dispatch(request, response, DispatcherType.FORWARD); + @Override + public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { + dispatch(request, response, FORWARD); } /** - * Dispatches the given request and response to the resource - * for which this dispatcher was acquired. + * Dispatches the given request and response to the resource for which this dispatcher was acquired. * - *

Any runtime exceptions, IOException, or ServletException thrown - * by the target will be propagated to the caller. + *

+ * Any runtime exceptions, IOException, or ServletException thrown by the target will be propagated to the caller. * * @param request The request to be forwarded * @param response The response to be forwarded @@ -295,78 +276,43 @@ public void forward(ServletRequest request, ServletResponse response) * * @throws IOException if an input/output error occurs * @throws ServletException if a servlet exception occurs - * @throws IllegalArgumentException if the dispatcher type is different - * from FORWARD, ERROR, and ASYNC + * @throws IllegalArgumentException if the dispatcher type is different from FORWARD, ERROR, and ASYNC */ - public void dispatch(ServletRequest request, ServletResponse response, - DispatcherType dispatcherType) - throws ServletException, IOException { + public void dispatch(ServletRequest request, ServletResponse response, DispatcherType dispatcherType) throws ServletException, IOException { - if (DispatcherType.FORWARD != dispatcherType && - DispatcherType.ERROR != dispatcherType && - DispatcherType.ASYNC != dispatcherType) { + if (FORWARD != dispatcherType && ERROR != dispatcherType && ASYNC != dispatcherType) { throw new IllegalArgumentException("Illegal dispatcher type"); } - boolean isCommit = (DispatcherType.FORWARD == dispatcherType || - DispatcherType.ERROR == dispatcherType); + boolean isCommit = FORWARD == dispatcherType || ERROR == dispatcherType; - if (Globals.IS_SECURITY_ENABLED) { - try { - PrivilegedDispatch dp = new PrivilegedDispatch( - request, response, dispatcherType); - AccessController.doPrivileged(dp); - // START SJSAS 6374990 - if (isCommit && !request.isAsyncStarted()) { - ApplicationDispatcherForward.commit(request, response, - context, wrapper); - } - // END SJSAS 6374990 - } catch (PrivilegedActionException pe) { - Exception e = pe.getException(); - if (e instanceof ServletException) - throw (ServletException) e; - throw (IOException) e; - } - } else { - doDispatch(request, response, dispatcherType); - // START SJSAS 6374990 - if (isCommit && !request.isAsyncStarted()) { - ApplicationDispatcherForward.commit(request, response, - context, wrapper); - } - // END SJSAS 6374990 + doDispatch(request, response, dispatcherType); + if (isCommit && !request.isAsyncStarted()) { + ApplicationDispatcherForward.commit(request, response, context, wrapper); } } - private void doDispatch(ServletRequest request, ServletResponse response, - DispatcherType dispatcherType) - throws ServletException, IOException { + private void doDispatch(ServletRequest request, ServletResponse response, DispatcherType dispatcherType) throws ServletException, IOException { - if (DispatcherType.ASYNC != dispatcherType) { + if (ASYNC != dispatcherType) { // Reset any output that has been buffered, but keep // headers/cookies if (response.isCommitted()) { - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, "Forward on committed response --> ISE"); - throw new IllegalStateException - (rb.getString(LogFacade.ILLEGAL_STATE_EXCEPTION)); + log.log(FINE, "Forward on committed response --> ISE"); + throw new IllegalStateException(rb.getString(LogFacade.ILLEGAL_STATE_EXCEPTION)); } try { response.resetBuffer(); } catch (IllegalStateException e) { - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, - "Forward resetBuffer() returned ISE: " + e.toString(), e); + if (log.isLoggable(FINE)) + log.log(FINE, "Forward resetBuffer() returned ISE: " + e.toString(), e); throw e; } } - if (DispatcherType.INCLUDE != dispatcherType) { - DispatchTargetsInfo dtInfo = - (DispatchTargetsInfo)request.getAttribute( - LAST_DISPATCH_REQUEST_PATH_ATTR); + if (INCLUDE != dispatcherType) { + DispatchTargetsInfo dtInfo = (DispatchTargetsInfo) request.getAttribute(LAST_DISPATCH_REQUEST_PATH_ATTR); if (dtInfo == null) { dtInfo = new DispatchTargetsInfo(); request.setAttribute(LAST_DISPATCH_REQUEST_PATH_ATTR, dtInfo); @@ -395,7 +341,7 @@ private void doDispatch(ServletRequest request, ServletResponse response, processRequest(request, response, state); } else if ((servletPath == null) && (pathInfo == null)) { // Handle an HTTP named dispatcher forward - ApplicationHttpRequest wrequest = (ApplicationHttpRequest)sr; + ApplicationHttpRequest wrequest = (ApplicationHttpRequest) sr; wrequest.setRequestURI(hrequest.getRequestURI()); wrequest.setContextPath(hrequest.getContextPath()); wrequest.setServletPath(hrequest.getServletPath()); @@ -406,26 +352,18 @@ private void doDispatch(ServletRequest request, ServletResponse response, } else { // Handle an HTTP path-based forward - ApplicationHttpRequest wrequest = (ApplicationHttpRequest)sr; + ApplicationHttpRequest wrequest = (ApplicationHttpRequest) sr; // If the request is being FORWARD- or ASYNC-dispatched for // the first time, initialize it with the required request // attributes - if ((DispatcherType.FORWARD == dispatcherType && - hrequest.getAttribute( - RequestDispatcher.FORWARD_REQUEST_URI) == null) || - (DispatcherType.ASYNC == dispatcherType && - hrequest.getAttribute( - AsyncContext.ASYNC_REQUEST_URI) == null)) { - wrequest.initSpecialAttributes(hrequest.getRequestURI(), - hrequest.getContextPath(), - hrequest.getServletPath(), - hrequest.getPathInfo(), - hrequest.getQueryString()); + if ((FORWARD == dispatcherType && hrequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI) == null) + || (ASYNC == dispatcherType && hrequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI) == null)) { + wrequest.initSpecialAttributes(hrequest.getRequestURI(), hrequest.getContextPath(), hrequest.getServletPath(), + hrequest.getPathInfo(), hrequest.getQueryString()); } String targetContextPath = context.getPath(); - // START IT 10395 RequestFacadeHelper reqFacHelper = RequestFacadeHelper.getInstance(wrequest); String originContextPath = null; if (reqFacHelper != null) { @@ -433,11 +371,10 @@ private void doDispatch(ServletRequest request, ServletResponse response, } else { originContextPath = wrequest.getContextPath(); } - if (originContextPath != null && - originContextPath.equals(targetContextPath)) { + if (originContextPath != null && originContextPath.equals(targetContextPath)) { targetContextPath = hrequest.getContextPath(); } - // END IT 10395 + wrequest.setContextPath(targetContextPath); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); @@ -448,7 +385,6 @@ private void doDispatch(ServletRequest request, ServletResponse response, } processRequest(request, response, state); - } recycleRequestWrapper(state); @@ -456,7 +392,6 @@ private void doDispatch(ServletRequest request, ServletResponse response, unwrapResponse(state); } - /** * Prepare the request based on the filter configuration. * @@ -466,16 +401,11 @@ private void doDispatch(ServletRequest request, ServletResponse response, * @throws IOException if an input/output error occurs * @throws ServletException if a servlet error occurs */ - private void processRequest(ServletRequest request, - ServletResponse response, - State state) - throws IOException, ServletException { + private void processRequest(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { if (request != null) { - if (state.dispatcherType != DispatcherType.ERROR) { - state.outerRequest.setAttribute( - Globals.DISPATCHER_REQUEST_PATH_ATTR, - getCombinedPath()); + if (state.dispatcherType != ERROR) { + state.outerRequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); invoke(state.outerRequest, response, state); } else { invoke(state.outerRequest, response, state); @@ -486,8 +416,8 @@ private void processRequest(ServletRequest request, /** * Combines the servletPath and the pathInfo. * - * If pathInfo is null, it is ignored. If servletPath - * is null, then null is returned. + * If pathInfo is null, it is ignored. If servletPath is null, then null is + * returned. * * @return The combined path with pathInfo appended to servletInfo */ @@ -501,11 +431,9 @@ private String getCombinedPath() { return servletPath + pathInfo; } - /** - * Include the response from another resource in the current response. - * Any runtime exception, IOException, or ServletException thrown by the - * called servlet will be propagated to the caller. + * Include the response from another resource in the current response. Any runtime exception, IOException, or + * ServletException thrown by the called servlet will be propagated to the caller. * * @param request The servlet request that is including this one * @param response The servlet response to be appended to @@ -513,68 +441,28 @@ private String getCombinedPath() { * @throws IOException if an input/output error occurs * @throws ServletException if a servlet exception occurs */ - public void include(ServletRequest request, ServletResponse response) - throws ServletException, IOException - { - if (Globals.IS_SECURITY_ENABLED) { - try { - PrivilegedInclude dp = new PrivilegedInclude(request,response); - AccessController.doPrivileged(dp); - } catch (PrivilegedActionException pe) { - Exception e = pe.getException(); - if (e instanceof ServletException) - throw (ServletException) e; - throw (IOException) e; - } - } else { - doInclude(request,response); - } + @Override + public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { + doInclude(request, response); } - - private void doInclude(ServletRequest request, ServletResponse response) - throws ServletException, IOException - { + private void doInclude(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Set up to handle the specified request and response - State state = new State(request, response, DispatcherType.INCLUDE); + State state = new State(request, response, INCLUDE); // Create a wrapped response to use for this request wrapResponse(state); // Handle a non-HTTP include - /* GlassFish 6386229 - if (!(request instanceof HttpServletRequest) || - !(response instanceof HttpServletResponse)) { - - if ( log.isDebugEnabled() ) - log.debug(" Non-HTTP Include"); - request.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, - Integer.valueOf(ApplicationFilterFactory.INCLUDE)); - request.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, - //origServletPath); - servletPath); - try{ - invoke(request, state.outerResponse, state); - } finally { - unwrapResponse(state); - } - } - - // Handle an HTTP named dispatcher include - else if (name != null) { - */ - // START GlassFish 6386229 // Handle an HTTP named dispatcher include if (name != null) { - // END GlassFish 6386229 - ApplicationHttpRequest wrequest = (ApplicationHttpRequest)wrapRequest(state); + ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name); if (servletPath != null) wrequest.setServletPath(servletPath); - wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, - getCombinedPath()); - try{ + wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); + try { invoke(state.outerRequest, state.outerResponse, state); } finally { recycleRequestWrapper(state); @@ -586,37 +474,28 @@ else if (name != null) { // Handle an HTTP path based include else { - ApplicationHttpRequest wrequest = (ApplicationHttpRequest)wrapRequest(state); - wrequest.initSpecialAttributes(requestURI, - context.getPath(), - servletPath, - pathInfo, - queryString); + ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); + wrequest.initSpecialAttributes(requestURI, context.getPath(), servletPath, pathInfo, queryString); wrequest.setQueryParams(queryString); - wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, - getCombinedPath()); - try{ + wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); + try { invoke(state.outerRequest, state.outerResponse, state); } finally { recycleRequestWrapper(state); unwrapRequest(state); unwrapResponse(state); - } + } } } - // -------------------------------------------------------- Private Methods - /** - * Ask the resource represented by this RequestDispatcher to process - * the associated request, and create (or append to) the associated - * response. + * Ask the resource represented by this RequestDispatcher to process the associated request, and create (or append to) + * the associated response. *

- * IMPLEMENTATION NOTE: This implementation assumes - * that no filters are applied to a forwarded or included resource, - * because they were already done for the original request. + * IMPLEMENTATION NOTE: This implementation assumes that no filters are applied to a forwarded or + * included resource, because they were already done for the original request. * * @param request The servlet request we are processing * @param response The servlet response we are creating @@ -624,10 +503,7 @@ else if (name != null) { * @throws IOException if an input/output error occurs * @throws ServletException if a servlet error occurs */ - private void invoke(ServletRequest request, ServletResponse response, - State state) - throws IOException, ServletException { - //START OF 6364900 original invoke has been renamed to doInvoke + private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException { boolean crossContext = false; if (crossContextFlag != null && crossContextFlag.booleanValue()) { crossContext = true; @@ -637,13 +513,11 @@ private void invoke(ServletRequest request, ServletResponse response, } try { if (crossContext) { - context.getManager().preRequestDispatcherProcess(request, - response); + context.getManager().preRequestDispatcherProcess(request, response); } doInvoke(request, response, crossContext, state); if (crossContext) { - context.getManager().postRequestDispatcherProcess(request, - response); + context.getManager().postRequestDispatcherProcess(request, response); } } finally { if (crossContext) { @@ -651,30 +525,24 @@ private void invoke(ServletRequest request, ServletResponse response, } crossContextFlag = null; } - //END OF 6364900 } - /** - * Ask the resource represented by this RequestDispatcher to process - * the associated request, and create (or append to) the associated - * response. + * Ask the resource represented by this RequestDispatcher to process the associated request, and create (or append to) + * the associated response. *

- * IMPLEMENTATION NOTE: This implementation assumes - * that no filters are applied to a forwarded or included resource, - * because they were already done for the original request. + * IMPLEMENTATION NOTE: This implementation assumes that no filters are applied to a forwarded or + * included resource, because they were already done for the original request. * * @param request The servlet request we are processing * @param response The servlet response we are creating - * @param crossContext true if the request dispatch is crossing context - * boundaries, false otherwise + * @param crossContext true if the request dispatch is crossing context boundaries, false otherwise * @param state the state of this ApplicationDispatcher * * @throws IOException if an input/output error occurs * @throws ServletException if a servlet error occurs */ - private void doInvoke(ServletRequest request, ServletResponse response, - boolean crossContext, State state) + private void doInvoke(ServletRequest request, ServletResponse response, boolean crossContext, State state) throws IOException, ServletException { // Checking to see if the context classloader is the current context @@ -694,35 +562,29 @@ private void doInvoke(ServletRequest request, ServletResponse response, RuntimeException runtimeException = null; boolean unavailable = false; - // Check for the servlet being marked unavailable if (wrapper.isUnavailable()) { - String msg = MessageFormat.format(rb.getString(LogFacade.UNAVAILABLE_SERVLET), - wrapper.getName()); + String msg = MessageFormat.format(rb.getString(LogFacade.UNAVAILABLE_SERVLET), wrapper.getName()); log.log(Level.WARNING, msg); if (hresponse == null) { - ; // NOTE - Not much we can do generically + ; // NOTE - Not much we can do generically } else { long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) hresponse.setDateHeader("Retry-After", available); - hresponse.sendError - (HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg); + hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg); } unavailable = true; } // Allocate a servlet instance to process this request - String allocateServletMsg = - MessageFormat.format(rb.getString(LogFacade.ALLOCATE_SERVLET_EXCEPTION), - wrapper.getName()); + String allocateServletMsg = MessageFormat.format(rb.getString(LogFacade.ALLOCATE_SERVLET_EXCEPTION), wrapper.getName()); try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (ServletException e) { - log.log(Level.SEVERE, allocateServletMsg, - StandardWrapper.getRootCause(e)); + log.log(Level.SEVERE, allocateServletMsg, StandardWrapper.getRootCause(e)); servletException = e; servlet = null; } catch (Throwable e) { @@ -733,91 +595,66 @@ private void doInvoke(ServletRequest request, ServletResponse response, // Get the FilterChain Here ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); - ApplicationFilterChain filterChain = factory.createFilterChain( - request, wrapper, servlet); + ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet); InstanceSupport support = ((StandardWrapper) wrapper).getInstanceSupport(); // Call the service() method for the allocated servlet instance - String servletServiceExceptionMsg = - MessageFormat.format(rb.getString(LogFacade.SERVLET_SERVICE_EXCEPTION), - wrapper.getName()); + String servletServiceExceptionMsg = MessageFormat.format(rb.getString(LogFacade.SERVLET_SERVICE_EXCEPTION), wrapper.getName()); RequestFacadeHelper reqFacHelper = RequestFacadeHelper.getInstance(request); try { String jspFile = wrapper.getJspFile(); if (jspFile != null) { request.setAttribute(Globals.JSP_FILE_ATTR, jspFile); } - support.fireInstanceEvent( - InstanceEvent.EventType.BEFORE_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(InstanceEvent.EventType.BEFORE_DISPATCH_EVENT, servlet, request, response); // for includes/forwards - /* IASRI 4665318 - if ((servlet != null) && (filterChain != null)) { - */ - // START IASRI 4665318 if (servlet != null) { - // END IASRI 4665318 - // START OF S1AS 4703023 if (reqFacHelper != null) { reqFacHelper.incrementDispatchDepth(); if (reqFacHelper.isMaxDispatchDepthReached()) { String msg = MessageFormat.format(rb.getString(LogFacade.MAX_DISPATCH_DEPTH_REACHED), - new Object[]{Integer.valueOf(Request.getMaxDispatchDepth())}); + new Object[] { Integer.valueOf(Request.getMaxDispatchDepth()) }); throw new ServletException(msg); } } - // END OF S1AS 4703023 - /* IASRI 4665318 - filterChain.doFilter(request, response); - */ - // START IASRI 4665318 + if (filterChain != null) { - filterChain.setWrapper((StandardWrapper)wrapper); + filterChain.setWrapper((StandardWrapper) wrapper); filterChain.doFilter(request, response); } else { - ((StandardWrapper)wrapper).service( - request, response, servlet); + ((StandardWrapper) wrapper).service(request, response, servlet); } - // END IASRI 4665318 } // Servlet Service Method is called by the FilterChain - support.fireInstanceEvent(AFTER_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(AFTER_DISPATCH_EVENT, servlet, request, response); } catch (ClientAbortException e) { - support.fireInstanceEvent(AFTER_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(AFTER_DISPATCH_EVENT, servlet, request, response); ioException = e; } catch (IOException e) { - support.fireInstanceEvent(AFTER_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(AFTER_DISPATCH_EVENT, servlet, request, response); log.log(Level.WARNING, servletServiceExceptionMsg, e); ioException = e; } catch (UnavailableException e) { - support.fireInstanceEvent(AFTER_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(AFTER_DISPATCH_EVENT, servlet, request, response); log.log(Level.WARNING, servletServiceExceptionMsg, e); servletException = e; wrapper.unavailable(e); } catch (ServletException e) { - support.fireInstanceEvent(AFTER_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(AFTER_DISPATCH_EVENT, servlet, request, response); Throwable rootCause = StandardWrapper.getRootCause(e); if (!(rootCause instanceof ClientAbortException)) { log.log(Level.WARNING, servletServiceExceptionMsg, rootCause); } servletException = e; } catch (RuntimeException e) { - support.fireInstanceEvent(AFTER_DISPATCH_EVENT, - servlet, request, response); + support.fireInstanceEvent(AFTER_DISPATCH_EVENT, servlet, request, response); log.log(Level.WARNING, servletServiceExceptionMsg, e); runtimeException = e; - // START OF S1AS 4703023 } finally { if (reqFacHelper != null) { reqFacHelper.decrementDispatchDepth(); } - // END OF S1AS 4703023 } // Release the filter chain (if any) for this request @@ -825,17 +662,14 @@ private void doInvoke(ServletRequest request, ServletResponse response, if (filterChain != null) filterChain.release(); } catch (Throwable e) { - String msg = MessageFormat.format(rb.getString(LogFacade.RELEASE_FILTERS_EXCEPTION_SEVERE), - wrapper.getName()); + String msg = MessageFormat.format(rb.getString(LogFacade.RELEASE_FILTERS_EXCEPTION_SEVERE), wrapper.getName()); log.log(Level.SEVERE, msg, e); // FIXME Exception handling needs to be simpiler to what is // in the StandardWrapperValue } // Deallocate the allocated servlet instance - String deallocateServletExceptionMsg = - MessageFormat.format(rb.getString(LogFacade.ALLOCATE_SERVLET_EXCEPTION), - wrapper.getName()); + String deallocateServletExceptionMsg = MessageFormat.format(rb.getString(LogFacade.ALLOCATE_SERVLET_EXCEPTION), wrapper.getName()); try { if (servlet != null) { wrapper.deallocate(servlet); @@ -861,46 +695,6 @@ private void doInvoke(ServletRequest request, ServletResponse response, throw runtimeException; } - - /** - * Log a message on the Logger associated with our Context (if any) - * - * @param message Message to be logged - * - private void log(String message) { - org.apache.catalina.Logger logger = context.getLogger(); - if (logger != null) { - logger.log("ApplicationDispatcher[" + context.getPath() + - "]: " + message); - } else { - if (log.isLoggable(Level.INFO)) { - String msg = MessageFormat.format(rb.getString(LogFacade.APPLICATION_DISPATCHER_INFO), - context.getPath(), message); - log.log(Level.INFO, msg); - } - } - } - - - /** - * Log a message on the Logger associated with our Container (if any) - * - * @param message Message to be logged - * @param t Associated exception - * - private void log(String message, Throwable t) { - org.apache.catalina.Logger logger = context.getLogger(); - if (logger != null) { - logger.log("ApplicationDispatcher[" + context.getPath() + - "] " + message, t, org.apache.catalina.Logger.WARNING); - } else { - String msg = MessageFormat.format(rb.getString(LogFacade.APPLICATION_DISPATCHER_WARNING), - context.getPath(), message); - log.log(Level.WARNING, msg, t); - } - } */ - - /** * Unwrap the request if we have wrapped it. */ @@ -915,14 +709,12 @@ private void unwrapRequest(State state) { while (current != null) { // If we run into the container request we are done - if ((current instanceof org.apache.catalina.Request) - || (current instanceof RequestFacade)) + if ((current instanceof org.apache.catalina.Request) || (current instanceof RequestFacade)) break; // Remove the current request if it is our wrapper if (current == state.wrapRequest) { - ServletRequest next = - ((ServletRequestWrapper) current).getRequest(); + ServletRequest next = ((ServletRequestWrapper) current).getRequest(); if (previous == null) state.outerRequest = next; else @@ -936,12 +728,10 @@ private void unwrapRequest(State state) { } } - /** * Unwrap the response if we have wrapped it. */ private void unwrapResponse(State state) { - if (state.wrapResponse == null) return; @@ -951,14 +741,12 @@ private void unwrapResponse(State state) { while (current != null) { // If we run into the container response we are done - if ((current instanceof org.apache.catalina.Response) || - (current instanceof ResponseFacade)) + if ((current instanceof org.apache.catalina.Response) || (current instanceof ResponseFacade)) break; // Remove the current response if it is our wrapper if (current == state.wrapResponse) { - ServletResponse next = - ((ServletResponseWrapper) current).getResponse(); + ServletResponse next = ((ServletResponseWrapper) current).getResponse(); if (previous == null) state.outerResponse = next; else @@ -972,10 +760,8 @@ private void unwrapResponse(State state) { } } - /** - * Create and return a request wrapper that has been inserted in the - * appropriate spot in the request chain. + * Create and return a request wrapper that has been inserted in the appropriate spot in the request chain. */ private ServletRequest wrapRequest(State state) { @@ -985,10 +771,9 @@ private ServletRequest wrapRequest(State state) { while (current != null) { if (state.hrequest == null && (current instanceof HttpServletRequest)) { - state.hrequest = (HttpServletRequest)current; + state.hrequest = (HttpServletRequest) current; } - if ("org.apache.catalina.servlets.InvokerHttpRequest". - equals(current.getClass().getName())) { + if ("org.apache.catalina.servlets.InvokerHttpRequest".equals(current.getClass().getName())) { break; // KLUDGE - Make nested RD.forward() using invoker work } if (!(current instanceof ServletRequestWrapper)) { @@ -1007,37 +792,27 @@ private ServletRequest wrapRequest(State state) { // Instantiate a new wrapper at this point and insert it in the chain ServletRequest wrapper = null; - if ((current instanceof ApplicationHttpRequest) || - (current instanceof Request) || - (current instanceof HttpServletRequest)) { + if ((current instanceof ApplicationHttpRequest) || (current instanceof Request) || (current instanceof HttpServletRequest)) { // Compute a crossContext flag HttpServletRequest hcurrent = (HttpServletRequest) current; boolean crossContext = false; - if ((state.outerRequest instanceof ApplicationHttpRequest) || - (state.outerRequest instanceof Request) || - (state.outerRequest instanceof HttpServletRequest)) { - HttpServletRequest houterRequest = - (HttpServletRequest) state.outerRequest; - Object contextPath = houterRequest.getAttribute( - RequestDispatcher.INCLUDE_CONTEXT_PATH); + if ((state.outerRequest instanceof ApplicationHttpRequest) || (state.outerRequest instanceof Request) + || (state.outerRequest instanceof HttpServletRequest)) { + HttpServletRequest houterRequest = (HttpServletRequest) state.outerRequest; + Object contextPath = houterRequest.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH); if (contextPath == null) { // Forward contextPath = houterRequest.getContextPath(); } crossContext = !(context.getPath().equals(contextPath)); } - //START OF 6364900 crossContextFlag = Boolean.valueOf(crossContext); - //END OF 6364900 - //START OF github/javaee/glassfish/issues/21846 if (this.name != null) { this.mappingForDispatch = computeNamedDispatchHttpServletMapping(context, hcurrent); } - //END OF github/javaee/glassfish/issues/21846 - wrapper = new ApplicationHttpRequest - (hcurrent, context, crossContext, mappingForDispatch, state.dispatcherType); + wrapper = new ApplicationHttpRequest(hcurrent, context, crossContext, mappingForDispatch, state.dispatcherType); } else { wrapper = new ApplicationRequest(current); } @@ -1079,8 +854,7 @@ private HttpServletMapping computeNamedDispatchHttpServletMapping(Context contex } /** - * Create and return a response wrapper that has been inserted in the - * appropriate spot in the response chain. + * Create and return a response wrapper that has been inserted in the appropriate spot in the response chain. */ private ServletResponse wrapResponse(State state) { @@ -1089,9 +863,9 @@ private ServletResponse wrapResponse(State state) { ServletResponse current = state.outerResponse; while (current != null) { - if(state.hresponse == null && (current instanceof HttpServletResponse)) { - state.hresponse = (HttpServletResponse)current; - if (DispatcherType.INCLUDE != state.dispatcherType) // Forward only needs hresponse + if (state.hresponse == null && (current instanceof HttpServletResponse)) { + state.hresponse = (HttpServletResponse) current; + if (INCLUDE != state.dispatcherType) // Forward only needs hresponse return null; } @@ -1107,15 +881,10 @@ private ServletResponse wrapResponse(State state) { // Instantiate a new wrapper at this point and insert it in the chain ServletResponse wrapper = null; - if ((current instanceof ApplicationHttpResponse) || - (current instanceof HttpResponse) || - (current instanceof HttpServletResponse)) - wrapper = - new ApplicationHttpResponse((HttpServletResponse) current, - DispatcherType.INCLUDE == state.dispatcherType); + if ((current instanceof ApplicationHttpResponse) || (current instanceof HttpResponse) || (current instanceof HttpServletResponse)) + wrapper = new ApplicationHttpResponse((HttpServletResponse) current, INCLUDE == state.dispatcherType); else - wrapper = new ApplicationResponse(current, - DispatcherType.INCLUDE == state.dispatcherType); + wrapper = new ApplicationResponse(current, INCLUDE == state.dispatcherType); if (previous == null) state.outerResponse = wrapper; else diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java index 471fdb074bd..02f7acfaf7e 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java @@ -17,30 +17,25 @@ package org.apache.catalina.core; +import static org.apache.catalina.InstanceEvent.EventType.AFTER_FILTER_EVENT; +import static org.apache.catalina.InstanceEvent.EventType.BEFORE_FILTER_EVENT; -import org.apache.catalina.Globals; -import org.apache.catalina.LogFacade; -import org.apache.catalina.security.SecurityUtil; -import org.apache.catalina.util.InstanceSupport; - -import jakarta.servlet.*; -import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.Servlet; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import java.io.IOException; -import java.security.Principal; -import java.security.PrivilegedActionException; import java.util.ResourceBundle; import java.util.logging.Logger; - - -import static org.apache.catalina.InstanceEvent.EventType.AFTER_FILTER_EVENT; -import static org.apache.catalina.InstanceEvent.EventType.BEFORE_FILTER_EVENT; +import org.apache.catalina.LogFacade; +import org.apache.catalina.util.InstanceSupport; /** - * Implementation of jakarta.servlet.FilterChain used to manage - * the execution of a set of filters for a particular request. When the - * set of defined filters has all been executed, the next call to - * doFilter() will execute the servlet's service() - * method itself. + * Implementation of jakarta.servlet.FilterChain used to manage the execution of a set of filters for a + * particular request. When the set of defined filters has all been executed, the next call to doFilter() + * will execute the servlet's service() method itself. * * @author Craig R. McClanahan * @version $Revision: 1.6 $ $Date: 2006/11/21 17:39:39 $ @@ -51,16 +46,12 @@ final class ApplicationFilterChain implements FilterChain { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); - // -------------------------------------------------------------- Constants - public static final int INCREMENT = 10; - // ----------------------------------------------------------- Constructors - /** * Construct a new chain instance with no defined filters. */ @@ -68,67 +59,44 @@ public ApplicationFilterChain() { super(); } - // ----------------------------------------------------- Instance Variables - /** * Filters. */ - private ApplicationFilterConfig[] filters = - new ApplicationFilterConfig[0]; - + private ApplicationFilterConfig[] filters = new ApplicationFilterConfig[0]; /** - * The int which is used to maintain the current position - * in the filter chain. + * The int which is used to maintain the current position in the filter chain. */ private int pos = 0; - /** * The int which gives the current number of filters in the chain. */ private int n = 0; - /** * The servlet instance to be executed by this chain. */ - private Servlet servlet = null; - + private Servlet servlet; /** * The wrapper around the servlet instance to be executed by this chain. */ - private StandardWrapper wrapper = null; - + private StandardWrapper wrapper; /** - * Static class array used when the SecurityManager is turned on and - * doFilterdoFilter[] classType = new Class[]{ServletRequest.class, - ServletResponse.class, - FilterChain.class}; + private static Class[] classType = new Class[] { ServletRequest.class, ServletResponse.class, FilterChain.class }; - /** - * Static class array used when the SecurityManager is turned on and - * service[] classTypeUsedInService = new Class[]{ - ServletRequest.class, - ServletResponse.class}; - */ // ---------------------------------------------------- FilterChain Methods - /** - * Invoke the next filter in this chain, passing the specified request - * and response. If there are no more filters in this chain, invoke - * the service() method of the servlet itself. + * Invoke the next filter in this chain, passing the specified request and response. If there are no more filters in + * this chain, invoke the service() method of the servlet itself. * * @param request The servlet request we are processing * @param response The servlet response we are creating @@ -136,42 +104,12 @@ public ApplicationFilterChain() { * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - - if (Globals.IS_SECURITY_ENABLED) { - final ServletRequest req = request; - final ServletResponse res = response; - try { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public Void run() - throws ServletException, IOException { - internalDoFilter(req,res); - return null; - } - } - ); - } catch( PrivilegedActionException pe) { - Exception e = pe.getException(); - if (e instanceof ServletException) - throw (ServletException) e; - else if (e instanceof IOException) - throw (IOException) e; - else if (e instanceof RuntimeException) - throw (RuntimeException) e; - else - throw new ServletException(e.getMessage(), e); - } - } else { - internalDoFilter(request,response); - } + @Override + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + internalDoFilter(request, response); } - private void internalDoFilter(ServletRequest request, - ServletResponse response) - throws IOException, ServletException { - + private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (wrapper == null) { throw new IllegalStateException("Missing wrapper"); } @@ -190,119 +128,31 @@ private void internalDoFilter(ServletRequest request, Filter filter = null; try { filter = filterConfig.getFilter(); - support.fireInstanceEvent(BEFORE_FILTER_EVENT, - filter, request, response); - - if( SecurityUtil.isPackageProtectionEnabled() ) { - final ServletRequest req = request; - final ServletResponse res = response; - Principal principal = - ((HttpServletRequest) req).getUserPrincipal(); - Object[] filterType = new Object[3]; - - filterType[0] = req; - filterType[1] = res; - filterType[2] = this; - SecurityUtil.doAsPrivilege - ("doFilter", filter, classType, filterType, principal); - } else { - filter.doFilter(request, response, this); - } + support.fireInstanceEvent(BEFORE_FILTER_EVENT, filter, request, response); - support.fireInstanceEvent(AFTER_FILTER_EVENT, - filter, request, response); - } catch (IOException e) { - if (filter != null) - support.fireInstanceEvent(AFTER_FILTER_EVENT, - filter, request, response, e); - throw e; - } catch (ServletException e) { - if (filter != null) - support.fireInstanceEvent(AFTER_FILTER_EVENT, - filter, request, response, e); - throw e; - } catch (RuntimeException e) { + filter.doFilter(request, response, this); + + support.fireInstanceEvent(AFTER_FILTER_EVENT, filter, request, response); + } catch (IOException | ServletException | RuntimeException e) { if (filter != null) - support.fireInstanceEvent(AFTER_FILTER_EVENT, - filter, request, response, e); + support.fireInstanceEvent(AFTER_FILTER_EVENT, filter, request, response, e); throw e; } catch (Throwable e) { if (filter != null) - support.fireInstanceEvent(AFTER_FILTER_EVENT, - filter, request, response, e); - throw new ServletException - (rb.getString(LogFacade.FILTER_EXECUTION_EXCEPTION), e); + support.fireInstanceEvent(AFTER_FILTER_EVENT, filter, request, response, e); + + throw new ServletException(rb.getString(LogFacade.FILTER_EXECUTION_EXCEPTION), e); } return; } // We fell off the end of the chain -- call the servlet instance - /* IASRI 4665318 - try { - support.fireInstanceEvent(InstanceEvent.BEFORE_SERVICE_EVENT, - servlet, request, response); - if ((request instanceof HttpServletRequest) && - (response instanceof HttpServletResponse)) { - - // START SJS WS 7.0 6236329 - //if( System.getSecurityManager() != null) { - if ( SecurityUtil.executeUnderSubjectDoAs() ){ - // END OF SJS WS 7.0 6236329 - final ServletRequest req = request; - final ServletResponse res = response; - Principal principal = - ((HttpServletRequest) req).getUserPrincipal(); - - Object[] serviceType = new Object[2]; - serviceType[0] = req; - serviceType[1] = res; - - SecurityUtil.doAsPrivilege("service", - servlet, - classTypeUsedInService, - serviceType, - principal); - serviceType = null; - } else { - servlet.service((HttpServletRequest) request, - (HttpServletResponse) response); - } - } else { - servlet.service(request, response); - } - support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, - servlet, request, response); - } catch (IOException e) { - support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, - servlet, request, response, e); - throw e; - } catch (ServletException e) { - support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, - servlet, request, response, e); - throw e; - } catch (RuntimeException e) { - support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, - servlet, request, response, e); - throw e; - } catch (Throwable e) { - support.fireInstanceEvent(InstanceEvent.AFTER_SERVICE_EVENT, - servlet, request, response, e); - throw new ServletException - (sm.getString("filterChain.servlet"), e); - //filterChain.servlet=PWC1244: Servlet execution threw an exception - } - */ - // START IASRI 4665318 wrapper.service(request, response, servlet); - // END IASRI 4665318 } - // -------------------------------------------------------- Package Methods - - /** * Add a filter to the set of filters that will be executed in this chain. * @@ -310,15 +160,13 @@ private void internalDoFilter(ServletRequest request, */ void addFilter(ApplicationFilterConfig filterConfig) { if (n == filters.length) { - ApplicationFilterConfig[] newFilters = - new ApplicationFilterConfig[n + INCREMENT]; + ApplicationFilterConfig[] newFilters = new ApplicationFilterConfig[n + INCREMENT]; System.arraycopy(filters, 0, newFilters, 0, n); filters = newFilters; } filters[n++] = filterConfig; } - /** * Release references to the filters and wrapper executed by this chain. */ @@ -329,25 +177,19 @@ void release() { wrapper = null; } - /** - * Sets the Servlet instance that will be executed at the end of this - * Filter chain. + * Sets the Servlet instance that will be executed at the end of this Filter chain. * - * @param servlet the Servlet instance that will be executed at the end - * of this Filter chain. + * @param servlet the Servlet instance that will be executed at the end of this Filter chain. */ void setServlet(Servlet servlet) { this.servlet = servlet; } - /** - * Sets the wrapper of the Servlet that will be executed at the end of - * this Filter chain. + * Sets the wrapper of the Servlet that will be executed at the end of this Filter chain. * - * @param wrapper the wrapper of the Servlet that will be executed at - * the end of this Filter chain. + * @param wrapper the wrapper of the Servlet that will be executed at the end of this Filter chain. */ void setWrapper(StandardWrapper wrapper) { this.wrapper = wrapper; diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterConfig.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterConfig.java index 840d235b2ab..2270fe4f1d2 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterConfig.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterConfig.java @@ -17,28 +17,18 @@ package org.apache.catalina.core; - -import org.apache.catalina.ContainerEvent; -import org.apache.catalina.LogFacade; -import org.apache.catalina.deploy.FilterDef; -import org.apache.catalina.security.SecurityUtil; - import jakarta.servlet.Filter; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import java.io.Serializable; import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ResourceBundle; - - +import org.apache.catalina.ContainerEvent; +import org.apache.catalina.deploy.FilterDef; /** - * Implementation of a jakarta.servlet.FilterConfig useful in - * managing the filter instances instantiated when a web application - * is first started. + * Implementation of a jakarta.servlet.FilterConfig useful in managing the filter instances instantiated + * when a web application is first started. * * @author Craig R. McClanahan * @version $Revision: 1.6 $ $Date: 2007/03/22 18:04:04 $ @@ -46,132 +36,112 @@ final class ApplicationFilterConfig implements FilterConfig, Serializable { - private static final Logger log = LogFacade.getLogger(); - private static final ResourceBundle rb = log.getResourceBundle(); + private static final long serialVersionUID = 1L; // ----------------------------------------------------------- Constructors - /** - * Construct a new ApplicationFilterConfig for the specified filter - * definition. + * Construct a new ApplicationFilterConfig for the specified filter definition. * * @param context The context with which we are associated - * @param filterDef Filter definition for which a FilterConfig is to be - * constructed + * @param filterDef Filter definition for which a FilterConfig is to be constructed * - * @exception ClassCastException if the specified class does not implement - * the jakarta.servlet.Filter interface + * @exception ClassCastException if the specified class does not implement the jakarta.servlet.Filter + * interface * @exception ClassNotFoundException if the filter class cannot be found - * @exception IllegalAccessException if the filter class cannot be - * publicly instantiated - * @exception InstantiationException if an exception occurs while - * instantiating the filter object + * @exception IllegalAccessException if the filter class cannot be publicly instantiated + * @exception InstantiationException if an exception occurs while instantiating the filter object * @exception ServletException if thrown by the filter's init() method */ - public ApplicationFilterConfig(StandardContext context, - FilterDef filterDef) - throws ClassCastException, ClassNotFoundException, - IllegalAccessException, InstantiationException, - ServletException { + public ApplicationFilterConfig(StandardContext context, FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException { super(); this.context = context; setFilterDef(filterDef); // init the filter try { getFilter(); - } catch(InstantiationException iex) { + } catch (InstantiationException iex) { throw iex; - } catch(Exception ex) { + } catch (Exception ex) { InstantiationException iex = new InstantiationException(); iex.initCause(ex); throw iex; } } - // ----------------------------------------------------- Instance Variables - /** * The Context with which we are associated. */ private transient StandardContext context = null; - /** * The application Filter we are configured for. */ private transient Filter filter = null; - /** * The FilterDef that defines our associated Filter. */ private FilterDef filterDef = null; - /** * Does the filter instance need to be initialized? */ private boolean needInitialize = true; - // --------------------------------------------------- FilterConfig Methods - /** * Return the name of the filter we are configuring. */ + @Override public String getFilterName() { return (filterDef.getFilterName()); } - /** - * Checks if this filter has been annotated or flagged in the deployment - * descriptor as being able to support asynchronous operations. + * Checks if this filter has been annotated or flagged in the deployment descriptor as being able to support + * asynchronous operations. * - * @return true if this filter supports async operations, and false - * otherwise + * @return true if this filter supports async operations, and false otherwise */ public boolean isAsyncSupported() { return filterDef.isAsyncSupported(); } - /** - * Return a String containing the value of the named - * initialization parameter, or null if the parameter - * does not exist. + * Return a String containing the value of the named initialization parameter, or null if the + * parameter does not exist. * * @param name Name of the requested initialization parameter */ + @Override public String getInitParameter(String name) { return filterDef.getInitParameter(name); } - /** - * Return an Enumeration of the names of the initialization - * parameters for this Filter. + * Return an Enumeration of the names of the initialization parameters for this Filter. */ + @Override public Enumeration getInitParameterNames() { return filterDef.getInitParameterNames(); } - /** * Return the ServletContext of our associated web application. */ + @Override public ServletContext getServletContext() { return (this.context.getServletContext()); } - /** * Return a String representation of this object. */ + @Override public String toString() { StringBuilder sb = new StringBuilder("ApplicationFilterConfig["); sb.append("name="); @@ -182,10 +152,8 @@ public String toString() { return (sb.toString()); } - // -------------------------------------------------------- Package Methods - /** * Return the application Filter we are configured for. */ @@ -215,34 +183,24 @@ synchronized Filter getFilter() throws Exception { this.filter = context.createFilterInstance(clazz); } - // START PWC 1.2 if (context != null) { - context.fireContainerEvent( - ContainerEvent.BEFORE_FILTER_INITIALIZED, - filter); + context.fireContainerEvent(ContainerEvent.BEFORE_FILTER_INITIALIZED, filter); } - // END PWC 1.2 filter.init(this); needInitialize = false; - // START PWC 1.2 if (context != null) { - context.fireContainerEvent(ContainerEvent.AFTER_FILTER_INITIALIZED, - filter); + context.fireContainerEvent(ContainerEvent.AFTER_FILTER_INITIALIZED, filter); } - // END PWC 1.2 - return (this.filter); } @SuppressWarnings("unchecked") - private Class loadFilterClass(ClassLoader classLoader, - String filterClassName) throws ClassNotFoundException { - return (Class)classLoader.loadClass(filterClassName); + private Class loadFilterClass(ClassLoader classLoader, String filterClassName) throws ClassNotFoundException { + return (Class) classLoader.loadClass(filterClassName); } - /** * Return the filter definition we are configured for. */ @@ -250,41 +208,20 @@ FilterDef getFilterDef() { return (this.filterDef); } - /** - * Release the Filter instance associated with this FilterConfig, - * if there is one. + * Release the Filter instance associated with this FilterConfig, if there is one. */ void release() { - - if (this.filter != null){ + if (this.filter != null) { if (context != null) { - context.fireContainerEvent( - ContainerEvent.BEFORE_FILTER_DESTROYED, - filter); + context.fireContainerEvent(ContainerEvent.BEFORE_FILTER_DESTROYED, filter); } - // START SJS WS 7.0 6236329 - //if( System.getSecurityManager() != null) { - if ( SecurityUtil.executeUnderSubjectDoAs() ){ - // END OF SJS WS 7.0 6236329 - try{ - SecurityUtil.doAsPrivilege("destroy", - filter); - SecurityUtil.remove(filter); - } catch(java.lang.Exception ex){ - String msg = rb.getString(LogFacade.DO_AS_PRIVILEGE); - log.log(Level.SEVERE, msg, ex); - } - } else { - filter.destroy(); - } + filter.destroy(); if (context != null) { - context.fireContainerEvent( - ContainerEvent.AFTER_FILTER_DESTROYED, - filter); + context.fireContainerEvent(ContainerEvent.AFTER_FILTER_DESTROYED, filter); // See GlassFish IT 7071 context = null; } @@ -293,51 +230,30 @@ void release() { this.filter = null; needInitialize = true; - } - + } /** - * Set the filter definition we are configured for. This has the side - * effect of instantiating an instance of the corresponding filter class. + * Set the filter definition we are configured for. This has the side effect of instantiating an instance of the + * corresponding filter class. * * @param filterDef The new filter definition * - * @exception ClassCastException if the specified class does not implement - * the jakarta.servlet.Filter interface + * @exception ClassCastException if the specified class does not implement the jakarta.servlet.Filter + * interface * @exception ClassNotFoundException if the filter class cannot be found - * @exception IllegalAccessException if the filter class cannot be - * publicly instantiated - * @exception InstantiationException if an exception occurs while - * instantiating the filter object + * @exception IllegalAccessException if the filter class cannot be publicly instantiated + * @exception InstantiationException if an exception occurs while instantiating the filter object * @exception ServletException if thrown by the filter's init() method */ - void setFilterDef(FilterDef filterDef) - throws ClassCastException, ClassNotFoundException, - IllegalAccessException, InstantiationException, - ServletException { - + void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException, IllegalAccessException, InstantiationException, ServletException { this.filterDef = filterDef; - if (filterDef == null) { + if (filterDef == null) { // Release any previously allocated filter instance - if (this.filter != null){ - // START SJS WS 7.0 6236329 - //if( System.getSecurityManager() != null) { - if ( SecurityUtil.executeUnderSubjectDoAs() ){ - // END OF SJS WS 7.0 6236329 - try{ - SecurityUtil.doAsPrivilege("destroy", - filter); - SecurityUtil.remove(filter); - } catch(java.lang.Exception ex){ - String msg = rb.getString(LogFacade.DO_AS_PRIVILEGE); - log.log(Level.SEVERE, msg, ex); - } - } else { - filter.destroy(); - } + if (filter != null) { + filter.destroy(); } - this.filter = null; + filter = null; } else { filter = filterDef.getFilter(); diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterFactory.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterFactory.java index a0ed5bd761e..6c91d7ae7fa 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterFactory.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterFactory.java @@ -30,8 +30,7 @@ import java.util.Locale; /** - * Factory for the creation and caching of Filters and creation - * of Filter Chains. + * Factory for the creation and caching of Filters and creation of Filter Chains. * * @author Greg Murray * @author Remy Maucherat @@ -40,25 +39,20 @@ public final class ApplicationFilterFactory { - // -------------------------------------------------------------- Constants private static ApplicationFilterFactory factory = new ApplicationFilterFactory(); - // ----------------------------------------------------------- Constructors - /* * Prevent instantiation outside of the getInstanceMethod(). */ private ApplicationFilterFactory() { } - // --------------------------------------------------------- Public Methods - /** * Return the factory instance. */ @@ -66,42 +60,20 @@ public static ApplicationFilterFactory getInstance() { return factory; } - /** - * Construct and return a FilterChain implementation that will wrap the - * execution of the specified servlet instance. If we should not execute - * a filter chain at all, return null. + * Construct and return a FilterChain implementation that will wrap the execution of the specified servlet instance. If + * we should not execute a filter chain at all, return null. * * @param request The servlet request we are processing * @param servlet The servlet instance to be wrapped */ - public ApplicationFilterChain createFilterChain - (ServletRequest request, Wrapper wrapper, Servlet servlet) { - + public ApplicationFilterChain createFilterChain(ServletRequest request, Wrapper wrapper, Servlet servlet) { // If there is no servlet to execute, return null if (servlet == null) - return (null); + return null; // Create and initialize a filter chain object ApplicationFilterChain filterChain = null; - /** IASRI 4665318 - if ((securityManager == null) && (request instanceof Request)) { - Request req = (Request) request; - filterChain = (ApplicationFilterChain) req.getFilterChain(); - if (filterChain == null) { - filterChain = new ApplicationFilterChain(); - req.setFilterChain(filterChain); - } - } else { - // Security: Do not recycle - filterChain = new ApplicationFilterChain(); - } - - filterChain.setServlet(servlet); - - filterChain.setSupport - (((StandardWrapper)wrapper).getInstanceSupport()); - */ // Acquire the filter mappings for this Context StandardContext context = (StandardContext) wrapper.getParent(); @@ -115,9 +87,8 @@ public static ApplicationFilterFactory getInstance() { // get the dispatcher type DispatcherType dispatcher = request.getDispatcherType(); String requestPath = null; - Object attribute = request.getAttribute( - Globals.DISPATCHER_REQUEST_PATH_ATTR); - if (attribute != null){ + Object attribute = request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR); + if (attribute != null) { requestPath = attribute.toString(); } @@ -133,17 +104,14 @@ public static ApplicationFilterFactory getInstance() { if (!filterMap.getDispatcherTypes().contains(dispatcher)) { continue; } - /* SJSWS 6324431 - if (!matchFiltersURL(filterMaps[i], requestPath)) - continue; - */ + /* + * SJSWS 6324431 if (!matchFiltersURL(filterMaps[i], requestPath)) continue; + */ // START SJSWS 6324431 - if (!matchFiltersURL(filterMap, requestPath, - context.isCaseSensitiveMapping())) + if (!matchFiltersURL(filterMap, requestPath, context.isCaseSensitiveMapping())) continue; // END SJSWS 6324431 - ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) - context.findFilterConfig(filterMap.getFilterName()); + ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) context.findFilterConfig(filterMap.getFilterName()); if (filterConfig == null) { // FIXME - log configuration problem continue; @@ -151,8 +119,7 @@ public static ApplicationFilterFactory getInstance() { // START IASRI 4665318 // Create a filter chain only when there are filters to add if (filterChain == null) - filterChain = internalCreateFilterChain(request, wrapper, - servlet); + filterChain = internalCreateFilterChain(request, wrapper, servlet); // END IASRI 4665318 filterChain.addFilter(filterConfig); n++; @@ -167,8 +134,7 @@ public static ApplicationFilterFactory getInstance() { } if (!matchFiltersServlet(filterMap, servletName)) continue; - ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) - context.findFilterConfig(filterMap.getFilterName()); + ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) context.findFilterConfig(filterMap.getFilterName()); if (filterConfig == null) { // FIXME - log configuration problem continue; @@ -176,8 +142,7 @@ public static ApplicationFilterFactory getInstance() { // START IASRI 4665318 // Create a filter chain only when there are filters to add if (filterChain == null) - filterChain = internalCreateFilterChain(request, wrapper, - servlet); + filterChain = internalCreateFilterChain(request, wrapper, servlet); // END IASRI 4665318 filterChain.addFilter(filterConfig); n++; @@ -188,25 +153,21 @@ public static ApplicationFilterFactory getInstance() { } - // -------------------------------------------------------- Private Methods - /** - * Return true if the context-relative request path - * matches the requirements of the specified filter mapping; - * otherwise, return null. + * Return true if the context-relative request path matches the requirements of the specified filter + * mapping; otherwise, return null. * * @param filterMap Filter mapping being checked * @param requestPath Context-relative request path of this request */ - /* SJSWS 6324431 - private boolean matchFiltersURL(FilterMap filterMap, String requestPath) { - */ + /* + * SJSWS 6324431 private boolean matchFiltersURL(FilterMap filterMap, String requestPath) { + */ // START SJSWS 6324431 - private boolean matchFiltersURL(FilterMap filterMap, String requestPath, - boolean caseSensitiveMapping) { - // END SJSWS 6324431 + private boolean matchFiltersURL(FilterMap filterMap, String requestPath, boolean caseSensitiveMapping) { + // END SJSWS 6324431 if (requestPath == null) return (false); @@ -231,8 +192,7 @@ private boolean matchFiltersURL(FilterMap filterMap, String requestPath, if (testPath.equals("/*")) return (true); if (testPath.endsWith("/*")) { - if (testPath.regionMatches(0, requestPath, 0, - testPath.length() - 2)) { + if (testPath.regionMatches(0, requestPath, 0, testPath.length() - 2)) { if (requestPath.length() == (testPath.length() - 2)) { return (true); } else if ('/' == requestPath.charAt(testPath.length() - 2)) { @@ -246,12 +206,9 @@ private boolean matchFiltersURL(FilterMap filterMap, String requestPath, if (testPath.startsWith("*.")) { int slash = requestPath.lastIndexOf('/'); int period = requestPath.lastIndexOf('.'); - if ((slash >= 0) && (period > slash) - && (period != requestPath.length() - 1) - && ((requestPath.length() - period) - == (testPath.length() - 1))) { - return (testPath.regionMatches(2, requestPath, period + 1, - testPath.length() - 2)); + if ((slash >= 0) && (period > slash) && (period != requestPath.length() - 1) + && ((requestPath.length() - period) == (testPath.length() - 1))) { + return (testPath.regionMatches(2, requestPath, period + 1, testPath.length() - 2)); } } @@ -260,36 +217,29 @@ private boolean matchFiltersURL(FilterMap filterMap, String requestPath, } - /** - * Return true if the specified servlet name matches - * the requirements of the specified filter mapping; otherwise - * return false. + * Return true if the specified servlet name matches the requirements of the specified filter mapping; + * otherwise return false. * * @param filterMap Filter mapping being checked * @param servletName Servlet name being checked */ - private boolean matchFiltersServlet(FilterMap filterMap, - String servletName) { + private boolean matchFiltersServlet(FilterMap filterMap, String servletName) { if (servletName == null) { return (false); - } else { - if (servletName.equals(filterMap.getServletName()) - || "*".equals(filterMap.getServletName())) { - return (true); - } else { - return false; - } } + if (servletName.equals(filterMap.getServletName()) || "*".equals(filterMap.getServletName())) { + return true; + } else { + return false; + } } - - // START IASRI 4665318 private ApplicationFilterChain internalCreateFilterChain(ServletRequest request, Wrapper wrapper, Servlet servlet) { ApplicationFilterChain filterChain = null; - if (!Globals.IS_SECURITY_ENABLED && (request instanceof Request)) { + if (request instanceof Request) { Request req = (Request) request; filterChain = (ApplicationFilterChain) req.getFilterChain(); if (filterChain == null) { @@ -302,11 +252,9 @@ private ApplicationFilterChain internalCreateFilterChain(ServletRequest request, } filterChain.setServlet(servlet); - filterChain.setWrapper((StandardWrapper)wrapper); + filterChain.setWrapper((StandardWrapper) wrapper); return filterChain; } - // END IASRI 4665318 - } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ContainerBase.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ContainerBase.java index d94dd6766e6..fee8b351ee6 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ContainerBase.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ContainerBase.java @@ -18,12 +18,12 @@ package org.apache.catalina.core; -import jakarta.servlet.ServletException; +import static com.sun.logging.LogCleanerUtil.neutralizeForLog; +import jakarta.servlet.ServletException; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; -import java.security.AccessController; import java.security.PrivilegedAction; import java.text.MessageFormat; import java.util.ArrayList; @@ -38,16 +38,13 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; - import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.naming.directory.DirContext; - import org.apache.catalina.Container; import org.apache.catalina.ContainerEvent; import org.apache.catalina.ContainerListener; import org.apache.catalina.Context; -import org.apache.catalina.Globals; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; @@ -64,85 +61,71 @@ import org.apache.naming.resources.ProxyDirContext; import org.glassfish.web.valve.GlassFishValve; -import static com.sun.logging.LogCleanerUtil.neutralizeForLog; - - /** - * Abstract implementation of the Container interface, providing common - * functionality required by nearly every implementation. Classes extending - * this base class must implement getInfo(), and may implement - * a replacement for invoke(). + * Abstract implementation of the Container interface, providing common functionality required by nearly every + * implementation. Classes extending this base class must implement getInfo(), and may implement a + * replacement for invoke(). *

- * All subclasses of this abstract base class will include support for a - * Pipeline object that defines the processing to be performed for each request - * received by the invoke() method of this class, utilizing the - * "Chain of Responsibility" design pattern. A subclass should encapsulate its - * own processing functionality as a Valve, and configure this - * Valve into the pipeline by calling setBasic(). + * All subclasses of this abstract base class will include support for a Pipeline object that defines the processing to + * be performed for each request received by the invoke() method of this class, utilizing the "Chain of + * Responsibility" design pattern. A subclass should encapsulate its own processing functionality as a + * Valve, and configure this Valve into the pipeline by calling setBasic(). *

- * This implementation fires property change events, per the JavaBeans design - * pattern, for changes in singleton properties. In addition, it fires the - * following ContainerEvent events to listeners who register + * This implementation fires property change events, per the JavaBeans design pattern, for changes in singleton + * properties. In addition, it fires the following ContainerEvent events to listeners who register * themselves with addContainerListener(): * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * *
TypeDataDescription
addChildContainerChild container added to this Container.
addValveValveValve added to this Container.
removeChildContainerChild container removed from this Container.
removeValveValveValve removed from this Container.
startnullContainer was started.
stopnullContainer was stopped.
TypeDataDescription
addChildContainerChild container added to this Container.
addValveValveValve added to this Container.
removeChildContainerChild container removed from this Container.
removeValveValveValve removed from this Container.
startnullContainer was started.
stopnullContainer was stopped.
- * Subclasses that fire additional events should document them in the - * class comments of the implementation class. + * Subclasses that fire additional events should document them in the class comments of the implementation class. * * @author Craig R. McClanahan */ -public abstract class ContainerBase - implements Container, Lifecycle, Pipeline { +public abstract class ContainerBase implements Container, Lifecycle, Pipeline { protected static final Logger log = LogFacade.getLogger(); protected static final ResourceBundle rb = log.getResourceBundle(); - - /** - * Perform addChild with the permissions of this class. - * addChild can be called with the XML parser on the stack, - * this allows the XML parser to have fewer privileges than - * Tomcat. + * Perform addChild with the permissions of this class. addChild can be called with the XML parser on the stack, this + * allows the XML parser to have fewer privileges than Tomcat. */ - protected class PrivilegedAddChild - implements PrivilegedAction { + protected class PrivilegedAddChild implements PrivilegedAction { private final Container child; @@ -158,54 +141,44 @@ public Void run() { } - // ----------------------------------------------------- Instance Variables - /** * The child Containers belonging to this Container, keyed by name. */ protected Map children = new LinkedHashMap<>(); - /** * The debugging detail level for this component. */ protected int debug = 0; - /** * The processor delay for this component. */ protected int backgroundProcessorDelay = -1; - /** - * Flag indicating whether a check to see if the request is secure is - * required before adding Pragma and Cache-Control headers when proxy - * caching has been disabled + * Flag indicating whether a check to see if the request is secure is required before adding Pragma and Cache-Control + * headers when proxy caching has been disabled */ - protected boolean checkIfRequestIsSecure = false; - + protected boolean checkIfRequestIsSecure; /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); - /** * The container event listeners for this Container. */ - protected ArrayList listeners = - new ArrayList<>(); + protected ArrayList listeners = new ArrayList<>(); private ContainerListener[] listenersArray = new ContainerListener[0]; - /** * The Loader implementation with which this Container is associated. */ - protected Loader loader = null; + protected Loader loader; private final ReadWriteLock lock = new ReentrantReadWriteLock(); protected Lock readLock = lock.readLock(); @@ -214,93 +187,83 @@ public Void run() { /** * The Logger implementation with which this Container is associated. */ - protected org.apache.catalina.Logger logger = null; + protected org.apache.catalina.Logger logger; /** * The Manager implementation with which this Container is associated. */ - protected Manager manager = null; + protected Manager manager; /** * The human-readable name of this Container. */ - protected String name = null; - + protected String name; /** * The parent Container to which this Container is a child. */ - protected Container parent = null; - + protected Container parent; /** * The parent class loader to be configured when we install a Loader. */ - protected ClassLoader parentClassLoader = null; - + protected ClassLoader parentClassLoader; /** * The Pipeline object with which this Container is associated. */ protected Pipeline pipeline = new StandardPipeline(this); - - protected boolean hasCustomPipeline = false; - + protected boolean hasCustomPipeline; /** * The Realm with which this Container is associated. */ - protected Realm realm = null; + protected Realm realm; /** * The resources DirContext object with which this Container is associated. */ - protected DirContext resources = null; + protected DirContext resources; /** * Has this component been started? */ - protected volatile boolean started = false; + protected volatile boolean started; - protected boolean initialized=false; + protected boolean initialized; /** * The property change support for this component. */ protected PropertyChangeSupport support = new PropertyChangeSupport(this); - /** * The background thread. */ - private Thread thread = null; - + private Thread thread; /** * The background thread completion semaphore. */ - private volatile boolean threadDone = false; - + private volatile boolean threadDone; /** - * Indicates whether ContainerListener instances need to be notified - * of a particular configuration event. + * Indicates whether ContainerListener instances need to be notified of a particular configuration event. */ - protected boolean notifyContainerListeners = true; + protected boolean notifyContainerListeners; // ------------------------------------------------------------- Properties /** - * @return true if ContainerListener instances need to be notified - * of a particular configuration event, and false otherwise + * @return true if ContainerListener instances need to be notified of a particular configuration event, and false + * otherwise */ boolean isNotifyContainerListeners() { return notifyContainerListeners; } - /** * Return the debugging detail level for this component. */ @@ -310,7 +273,6 @@ public int getDebug() { } - /** * Set the debugging detail level for this component. * @@ -320,59 +282,46 @@ public void setDebug(int debug) { int oldDebug = this.debug; this.debug = debug; - support.firePropertyChange("debug", Integer.valueOf(oldDebug), - Integer.valueOf(this.debug)); + support.firePropertyChange("debug", Integer.valueOf(oldDebug), Integer.valueOf(this.debug)); } - /** - * Get the delay between the invocation of the backgroundProcess method on - * this container and its children. Child containers will not be invoked - * if their delay value is not negative (which would mean they are using - * their own thread). Setting this to a positive value will cause - * a thread to be spawn. After waiting the specified amount of time, - * the thread will invoke the executePeriodic method on this container - * and all its children. + * Get the delay between the invocation of the backgroundProcess method on this container and its children. Child + * containers will not be invoked if their delay value is not negative (which would mean they are using their own + * thread). Setting this to a positive value will cause a thread to be spawn. After waiting the specified amount of + * time, the thread will invoke the executePeriodic method on this container and all its children. */ @Override public int getBackgroundProcessorDelay() { return backgroundProcessorDelay; } - /** - * Set the delay between the invocation of the execute method on this - * container and its children. + * Set the delay between the invocation of the execute method on this container and its children. * - * @param delay The delay in seconds between the invocation of - * backgroundProcess methods + * @param delay The delay in seconds between the invocation of backgroundProcess methods */ @Override public void setBackgroundProcessorDelay(int delay) { backgroundProcessorDelay = delay; } - /** - * Return descriptive information about this Container implementation and - * the corresponding version number, in the format - * <description>/<version>. + * Return descriptive information about this Container implementation and the corresponding version number, in the + * format <description>/<version>. */ @Override public String getInfo() { return this.getClass().getName(); } - /** - * Return the Loader with which this Container is associated. If there is - * no associated Loader, return the Loader associated with our parent - * Container (if any); otherwise, return null. + * Return the Loader with which this Container is associated. If there is no associated Loader, return the Loader + * associated with our parent Container (if any); otherwise, return null. */ @Override public Loader getLoader() { - try { readLock.lock(); if (loader != null) { @@ -386,10 +335,9 @@ public Loader getLoader() { return (parent.getLoader()); } - return (null); + return null; } - /** * Set the Loader with which this Container is associated. * @@ -411,8 +359,7 @@ public void setLoader(Loader loader) { this.loader = loader; // Stop the old component if necessary - if (started && (oldLoader != null) && - (oldLoader instanceof Lifecycle)) { + if (started && (oldLoader != null) && (oldLoader instanceof Lifecycle)) { try { ((Lifecycle) oldLoader).stop(); } catch (LifecycleException e) { @@ -424,8 +371,7 @@ public void setLoader(Loader loader) { if (loader != null) { loader.setContainer(this); } - if (started && (loader != null) && - (loader instanceof Lifecycle)) { + if (started && (loader != null) && (loader instanceof Lifecycle)) { try { ((Lifecycle) loader).start(); } catch (LifecycleException e) { @@ -441,11 +387,9 @@ public void setLoader(Loader loader) { } - /** - * Return the Logger with which this Container is associated. If there is - * no associated Logger, return the Logger associated with our parent - * Container (if any); otherwise return null. + * Return the Logger with which this Container is associated. If there is no associated Logger, return the Logger + * associated with our parent Container (if any); otherwise return null. */ @Override public org.apache.catalina.Logger getLogger() { @@ -466,7 +410,6 @@ public org.apache.catalina.Logger getLogger() { return (null); } - /** * Set the Logger with which this Container is associated. * @@ -487,8 +430,7 @@ public void setLogger(org.apache.catalina.Logger logger) { this.logger = logger; // Stop the old component if necessary - if (started && (oldLogger != null) && - (oldLogger instanceof Lifecycle)) { + if (started && (oldLogger != null) && (oldLogger instanceof Lifecycle)) { try { ((Lifecycle) oldLogger).stop(); } catch (LifecycleException e) { @@ -496,13 +438,11 @@ public void setLogger(org.apache.catalina.Logger logger) { } } - // Start the new component if necessary if (logger != null) { logger.setContainer(this); } - if (started && (logger != null) && - (logger instanceof Lifecycle)) { + if (started && (logger != null) && (logger instanceof Lifecycle)) { try { ((Lifecycle) logger).start(); } catch (LifecycleException e) { @@ -518,11 +458,9 @@ public void setLogger(org.apache.catalina.Logger logger) { } - /** - * Return the Manager with which this Container is associated. If there is - * no associated Manager, return the Manager associated with our parent - * Container (if any); otherwise return null. + * Return the Manager with which this Container is associated. If there is no associated Manager, return the Manager + * associated with our parent Container (if any); otherwise return null. */ @Override public Manager getManager() { @@ -543,7 +481,6 @@ public Manager getManager() { return (null); } - /** * Set the Manager with which this Container is associated. * @@ -564,8 +501,7 @@ public void setManager(Manager manager) { this.manager = manager; // Stop the old component if necessary - if (started && (oldManager != null) && - (oldManager instanceof Lifecycle)) { + if (started && (oldManager != null) && (oldManager instanceof Lifecycle)) { try { ((Lifecycle) oldManager).stop(); } catch (LifecycleException e) { @@ -577,8 +513,7 @@ public void setManager(Manager manager) { if (manager != null) { manager.setContainer(this); } - if (started && (manager != null) && - (manager instanceof Lifecycle)) { + if (started && (manager != null) && (manager instanceof Lifecycle)) { try { ((Lifecycle) manager).start(); } catch (LifecycleException e) { @@ -593,7 +528,6 @@ public void setManager(Manager manager) { support.firePropertyChange("manager", oldManager, this.manager); } - /** * Return an object which may be utilized for mapping to this component. */ @@ -602,11 +536,9 @@ public Object getMappingObject() { return this; } - /** - * Return a name string (suitable for use by humans) that describes this - * Container. Within the set of child containers belonging to a particular - * parent, Container names must be unique. + * Return a name string (suitable for use by humans) that describes this Container. Within the set of child containers + * belonging to a particular parent, Container names must be unique. */ @Override public String getName() { @@ -614,17 +546,14 @@ public String getName() { return (name); } - /** - * Set a name string (suitable for use by humans) that describes this - * Container. Within the set of child containers belonging to a particular - * parent, Container names must be unique. + * Set a name string (suitable for use by humans) that describes this Container. Within the set of child containers + * belonging to a particular parent, Container names must be unique. * * @param name New name of this container * - * @exception IllegalStateException if this Container has already been - * added to the children of a parent Container (after which the name - * may not be changed) + * @exception IllegalStateException if this Container has already been added to the children of a parent Container + * (after which the name may not be changed) */ @Override public void setName(String name) { @@ -634,10 +563,9 @@ public void setName(String name) { support.firePropertyChange("name", oldName, this.name); } - /** - * Return the Container for which this Container is a child, if there is - * one. If there is no defined parent, return null. + * Return the Container for which this Container is a child, if there is one. If there is no defined parent, return + * null. */ @Override public Container getParent() { @@ -645,17 +573,13 @@ public Container getParent() { return (parent); } - /** - * Set the parent Container to which this Container is being added as a - * child. This Container may refuse to become attached to the specified - * Container by throwing an exception. + * Set the parent Container to which this Container is being added as a child. This Container may refuse to become + * attached to the specified Container by throwing an exception. * - * @param container Container to which this Container is being added - * as a child + * @param container Container to which this Container is being added as a child * - * @exception IllegalArgumentException if this Container refuses to become - * attached to the specified Container + * @exception IllegalArgumentException if this Container refuses to become attached to the specified Container */ @Override public void setParent(Container container) { @@ -665,11 +589,9 @@ public void setParent(Container container) { support.firePropertyChange("parent", oldParent, this.parent); } - /** - * Return the parent class loader (if any) for this web application. - * This call is meaningful only after a Loader has - * been configured. + * Return the parent class loader (if any) for this web application. This call is meaningful only after + * a Loader has been configured. */ @Override public ClassLoader getParentClassLoader() { @@ -682,12 +604,10 @@ public ClassLoader getParentClassLoader() { return (ClassLoader.getSystemClassLoader()); } - /** - * Set the parent class loader (if any) for this web application. - * This call is meaningful only before a Loader has - * been configured, and the specified value (if non-null) should be - * passed as an argument to the class loader constructor. + * Set the parent class loader (if any) for this web application. This call is meaningful only before a + * Loader has been configured, and the specified value (if non-null) should be passed as an argument to the class loader + * constructor. * * * @param parent The new parent class loader @@ -696,35 +616,28 @@ public ClassLoader getParentClassLoader() { public void setParentClassLoader(ClassLoader parent) { ClassLoader oldParentClassLoader = this.parentClassLoader; this.parentClassLoader = parent; - support.firePropertyChange("parentClassLoader", oldParentClassLoader, - this.parentClassLoader); + support.firePropertyChange("parentClassLoader", oldParentClassLoader, this.parentClassLoader); } - /** - * Return the Pipeline object that manages the Valves associated with - * this Container. + * Return the Pipeline object that manages the Valves associated with this Container. */ @Override public Pipeline getPipeline() { return this.pipeline; } - /** - * @return true if this container was configured with a custom pipeline, - * false otherwise + * @return true if this container was configured with a custom pipeline, false otherwise */ @Override public boolean hasCustomPipeline() { return hasCustomPipeline; } - /** - * Indicates whether the request will be checked to see if it is secure - * before adding Pragma and Cache-control headers when proxy caching has - * been disabled. + * Indicates whether the request will be checked to see if it is secure before adding Pragma and Cache-control headers + * when proxy caching has been disabled. * * @return true if the check is required; false otherwise. */ @@ -733,27 +646,22 @@ public boolean isCheckIfRequestIsSecure() { return checkIfRequestIsSecure; } - /** * Sets the checkIfRequestIsSecure property of this Container. * - * Setting this property to true will check if the request is secure - * before adding Pragma and Cache-Control headers when proxy caching has - * been disabled. + * Setting this property to true will check if the request is secure before adding Pragma and Cache-Control headers when + * proxy caching has been disabled. * - * @param checkIfRequestIsSecure true if check is required, false - * otherwise + * @param checkIfRequestIsSecure true if check is required, false otherwise */ @Override public void setCheckIfRequestIsSecure(boolean checkIfRequestIsSecure) { this.checkIfRequestIsSecure = checkIfRequestIsSecure; } - /** - * Return the Realm with which this Container is associated. If there is - * no associated Realm, return the Realm associated with our parent - * Container (if any); otherwise return null. + * Return the Realm with which this Container is associated. If there is no associated Realm, return the Realm + * associated with our parent Container (if any); otherwise return null. */ @Override public Realm getRealm() { @@ -773,7 +681,6 @@ public Realm getRealm() { return (null); } - /** * Set the Realm with which this Container is associated. * @@ -794,8 +701,7 @@ public void setRealm(Realm realm) { this.realm = realm; // Stop the old component if necessary - if (started && (oldRealm != null) && - (oldRealm instanceof Lifecycle)) { + if (started && (oldRealm != null) && (oldRealm instanceof Lifecycle)) { try { ((Lifecycle) oldRealm).stop(); } catch (LifecycleException e) { @@ -807,8 +713,7 @@ public void setRealm(Realm realm) { if (realm != null) { realm.setContainer(this); } - if (started && (realm != null) && - (realm instanceof Lifecycle)) { + if (started && (realm != null) && (realm instanceof Lifecycle)) { try { ((Lifecycle) realm).start(); } catch (LifecycleException e) { @@ -823,12 +728,9 @@ public void setRealm(Realm realm) { support.firePropertyChange("realm", oldRealm, this.realm); } - /** - * Return the resources DirContext object with which this Container is - * associated. If there is no associated resources object, return the - * resources associated with our parent Container (if any); otherwise - * return null. + * Return the resources DirContext object with which this Container is associated. If there is no associated resources + * object, return the resources associated with our parent Container (if any); otherwise return null. */ @Override public DirContext getResources() { @@ -849,18 +751,16 @@ public DirContext getResources() { return (null); } - /** - * Set the resources DirContext object with which this Container is - * associated. + * Set the resources DirContext object with which this Container is associated. * * @param resources The newly associated DirContext */ @Override public void setResources(DirContext resources) throws Exception { // Called from StandardContext.setResources() - // <- StandardContext.start() - // <- ContainerBase.addChildInternal() + // <- StandardContext.start() + // <- ContainerBase.addChildInternal() // Change components if necessary DirContext oldResources; @@ -882,61 +782,47 @@ public void setResources(DirContext resources) throws Exception { writeLock.unlock(); } - support.firePropertyChange("resources", oldResources, - this.resources); + support.firePropertyChange("resources", oldResources, this.resources); } - // ------------------------------------------------------ Container Methods - /** - * Add a new child Container to those associated with this Container, - * if supported. Prior to adding this Container to the set of children, - * the child's setParent() method must be called, with this - * Container as an argument. This method may thrown an - * IllegalArgumentException if this Container chooses not - * to be attached to the specified Container, in which case it is not added + * Add a new child Container to those associated with this Container, if supported. Prior to adding this Container to + * the set of children, the child's setParent() method must be called, with this Container as an argument. + * This method may thrown an IllegalArgumentException if this Container chooses not to be attached to the + * specified Container, in which case it is not added * * @param child New child Container to be added * - * @exception IllegalArgumentException if this exception is thrown by - * the setParent() method of the child Container - * @exception IllegalArgumentException if the new child does not have - * a name unique from that of existing children of this Container - * @exception IllegalStateException if this Container does not support - * child Containers + * @exception IllegalArgumentException if this exception is thrown by the setParent() method of the child + * Container + * @exception IllegalArgumentException if the new child does not have a name unique from that of existing children of + * this Container + * @exception IllegalStateException if this Container does not support child Containers */ @Override public void addChild(Container child) { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction dp = - new PrivilegedAddChild(child); - AccessController.doPrivileged(dp); - } else { - addChildInternal(child); - } + addChildInternal(child); } private void addChildInternal(Container child) { - - if(log.isLoggable(Level.FINEST)) { + if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Add child " + child + " " + this); } - synchronized(children) { + + synchronized (children) { if (children.get(child.getName()) != null) { - String msg = MessageFormat.format(rb.getString(LogFacade.DUPLICATE_CHILD_NAME_EXCEPTION), - child.getName()); - throw new IllegalArgumentException(msg); + String msg = MessageFormat.format(rb.getString(LogFacade.DUPLICATE_CHILD_NAME_EXCEPTION), child.getName()); + throw new IllegalArgumentException(msg); } - child.setParent(this); // May throw IAE + child.setParent(this); // May throw IAE if (started && (child instanceof Lifecycle)) { try { ((Lifecycle) child).start(); } catch (LifecycleException e) { log.log(Level.SEVERE, LogFacade.CONTAINER_BASE_ADD_CHILD_START, e); - throw new IllegalStateException - (rb.getString(LogFacade.CONTAINER_BASE_ADD_CHILD_START) + e); + throw new IllegalStateException(rb.getString(LogFacade.CONTAINER_BASE_ADD_CHILD_START) + e); } } children.put(child.getName(), child); @@ -948,7 +834,6 @@ private void addChildInternal(Container child) { } - /** * Add a container event listener to this component. * @@ -956,16 +841,12 @@ private void addChildInternal(Container child) { */ @Override public void addContainerListener(ContainerListener listener) { - synchronized (listeners) { listeners.add(listener); - listenersArray = listeners.toArray( - new ContainerListener[listeners.size()]); + listenersArray = listeners.toArray(new ContainerListener[listeners.size()]); } - } - /** * Add a property change listener to this component. * @@ -973,85 +854,66 @@ public void addContainerListener(ContainerListener listener) { */ @Override public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - /** - * Return the child Container, associated with this Container, with - * the specified name (if any); otherwise, return null + * Return the child Container, associated with this Container, with the specified name (if any); otherwise, return + * null * * @param name Name of the child Container to be retrieved */ @Override public Container findChild(String name) { - if (name == null) { return (null); } - synchronized (children) { // Required by post-start changes + + synchronized (children) { // Required by post-start changes return children.get(name); } - } - /** - * Return the set of children Containers associated with this Container. - * If this Container has no children, a zero-length array is returned. + * Return the set of children Containers associated with this Container. If this Container has no children, a + * zero-length array is returned. */ @Override public Container[] findChildren() { - synchronized (children) { return children.values().toArray(new Container[children.size()]); } - } - /** - * Return the set of container listeners associated with this Container. - * If this Container has no registered container listeners, a zero-length - * array is returned. + * Return the set of container listeners associated with this Container. If this Container has no registered container + * listeners, a zero-length array is returned. */ @Override public ContainerListener[] findContainerListeners() { - synchronized (listeners) { return listenersArray; } } - /** - * Process the specified Request, to produce the corresponding Response, - * by invoking the first Valve in our pipeline (if any), or the basic - * Valve otherwise. + * Process the specified Request, to produce the corresponding Response, by invoking the first Valve in our pipeline (if + * any), or the basic Valve otherwise. * * @param request Request to be processed * @param response Response to be produced * - * @exception IllegalStateException if neither a pipeline or a basic - * Valve have been configured for this Container - * @exception IOException if an input/output error occurred while - * processing - * @exception ServletException if a ServletException was thrown - * while processing this request + * @exception IllegalStateException if neither a pipeline or a basic Valve have been configured for this Container + * @exception IOException if an input/output error occurred while processing + * @exception ServletException if a ServletException was thrown while processing this request */ @Override - public void invoke(Request request, Response response) - throws IOException, ServletException { - + public void invoke(Request request, Response response) throws IOException, ServletException { pipeline.invoke(request, response); } - /** - * Remove an existing child Container from association with this parent - * Container. + * Remove an existing child Container from association with this parent Container. * * @param child Existing child Container to be removed */ @@ -1061,7 +923,7 @@ public void removeChild(Container child) { return; } - synchronized(children) { + synchronized (children) { if (children.get(child.getName()) == null) { return; } @@ -1070,8 +932,8 @@ public void removeChild(Container child) { if (started && (child instanceof Lifecycle)) { try { - if( child instanceof ContainerBase ) { - if( ((ContainerBase)child).started ) { + if (child instanceof ContainerBase) { + if (((ContainerBase) child).started) { ((Lifecycle) child).stop(); } } else { @@ -1089,7 +951,6 @@ public void removeChild(Container child) { // child.setParent(null); } - /** * Remove a container event listener from this component. * @@ -1097,15 +958,12 @@ public void removeChild(Container child) { */ @Override public void removeContainerListener(ContainerListener listener) { - synchronized (listeners) { listeners.remove(listener); - listenersArray = listeners.toArray( - new ContainerListener[listeners.size()]); + listenersArray = listeners.toArray(new ContainerListener[listeners.size()]); } } - /** * Remove a property change listener from this component. * @@ -1113,14 +971,11 @@ public void removeContainerListener(ContainerListener listener) { */ @Override public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); } - // ------------------------------------------------------ Lifecycle Methods - /** * Add a lifecycle event listener to this component. * @@ -1131,17 +986,14 @@ public void addLifecycleListener(LifecycleListener listener) { lifecycle.addLifecycleListener(listener); } - /** - * Gets the (possibly empty) list of lifecycle listeners associated - * with this Container. + * Gets the (possibly empty) list of lifecycle listeners associated with this Container. */ @Override public List findLifecycleListeners() { return lifecycle.findLifecycleListeners(); } - /** * Removes the given lifecycle event listener from this Container. * @@ -1152,7 +1004,6 @@ public void removeLifecycleListener(LifecycleListener listener) { lifecycle.removeLifecycleListener(listener); } - /** * Removes any lifecycle event listeners from this Container. */ @@ -1160,12 +1011,10 @@ public void removeLifecycleListeners() { lifecycle.removeLifecycleListeners(); } - /** * Prepare for active use of the public methods of this Component. * - * @exception LifecycleException if this component detects a fatal error - * that prevents it from being started + * @exception LifecycleException if this component detects a fatal error that prevents it from being started */ @Override public synchronized void start() throws LifecycleException { @@ -1218,12 +1067,10 @@ public synchronized void start() throws LifecycleException { lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null); } - /** * Gracefully shut down active use of the public methods of this Component. * - * @exception LifecycleException if this component detects a fatal error - * that needs to be reported + * @exception LifecycleException if this component detects a fatal error that needs to be reported */ @Override public synchronized void stop() throws LifecycleException { @@ -1291,19 +1138,17 @@ public synchronized void stop() throws LifecycleException { lifecycle.fireLifecycleEvent(AFTER_STOP_EVENT, null); } - - /** Init method, part of the MBean lifecycle. - * If the container was added via JMX, it'll register itself with the - * parent, using the ObjectName conventions to locate the parent. + /** + * Init method, part of the MBean lifecycle. If the container was added via JMX, it'll register itself with the parent, + * using the ObjectName conventions to locate the parent. * - * If the container was added directly and it doesn't have an ObjectName, - * it'll create a name and register itself with the JMX console. On destroy(), - * the object will unregister. + * If the container was added directly and it doesn't have an ObjectName, it'll create a name and register itself with + * the JMX console. On destroy(), the object will unregister. * * @throws Exception */ public void init() throws Exception { - initialized=true; + initialized = true; } public ObjectName getParentName() throws MalformedObjectNameException { @@ -1311,20 +1156,20 @@ public ObjectName getParentName() throws MalformedObjectNameException { } public void destroy() throws Exception { - if( started ) { + if (started) { stop(); } - initialized=false; + initialized = false; // unregister this component - if( oname != null ) { + if (oname != null) { try { - if( controller == oname ) { + if (controller == oname) { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "unregistering " + oname); } } - } catch( Throwable t ) { + } catch (Throwable t) { log.log(Level.SEVERE, LogFacade.ERROR_UNREGISTERING, t); } } @@ -1335,7 +1180,7 @@ public void destroy() throws Exception { // Stop our child containers, if any Container children[] = findChildren(); - for(Container aChildren : children) { + for (Container aChildren : children) { removeChild(aChildren); } @@ -1349,24 +1194,17 @@ public void destroy() throws Exception { // ------------------------------------------------------- Pipeline Methods - /** - * Add a new Valve to the end of the pipeline associated with this - * Container. Prior to adding the Valve, the Valve's - * setContainer method must be called, with this Container - * as an argument. The method may throw an - * IllegalArgumentException if this Valve chooses not to - * be associated with this Container, or IllegalStateException - * if it is already associated with a different Container. + * Add a new Valve to the end of the pipeline associated with this Container. Prior to adding the Valve, the Valve's + * setContainer method must be called, with this Container as an argument. The method may throw an + * IllegalArgumentException if this Valve chooses not to be associated with this Container, or + * IllegalStateException if it is already associated with a different Container. * * @param valve Valve to be added * - * @exception IllegalArgumentException if this Container refused to - * accept the specified Valve - * @exception IllegalArgumentException if the specified Valve refuses to be - * associated with this Container - * @exception IllegalStateException if the specified Valve is already - * associated with a different Container + * @exception IllegalArgumentException if this Container refused to accept the specified Valve + * @exception IllegalArgumentException if the specified Valve refuses to be associated with this Container + * @exception IllegalStateException if the specified Valve is already associated with a different Container */ @Override public synchronized void addValve(GlassFishValve valve) { @@ -1378,7 +1216,6 @@ public synchronized void addValve(GlassFishValve valve) { } } - /** * Add Tomcat-style valve. */ @@ -1392,45 +1229,38 @@ public synchronized void addValve(Valve valve) { } } - public ObjectName[] getValveObjectNames() { - return ((StandardPipeline)pipeline).getValveObjectNames(); + return ((StandardPipeline) pipeline).getValveObjectNames(); } /** - *

Return the Valve instance that has been distinguished as the basic - * Valve for this Pipeline (if any). + *

+ * Return the Valve instance that has been distinguished as the basic Valve for this Pipeline (if any). */ @Override public GlassFishValve getBasic() { return (pipeline.getBasic()); } - /** - * Return the set of Valves in the pipeline associated with this - * Container, including the basic Valve (if any). If there are no - * such Valves, a zero-length array is returned. + * Return the set of Valves in the pipeline associated with this Container, including the basic Valve (if any). If there + * are no such Valves, a zero-length array is returned. */ @Override public GlassFishValve[] getValves() { return (pipeline.getValves()); } - /** - * @return true if this pipeline has any non basic valves, false - * otherwise + * @return true if this pipeline has any non basic valves, false otherwise */ @Override public boolean hasNonBasicValves() { return pipeline.hasNonBasicValves(); } - /** - * Remove the specified Valve from the pipeline associated with this - * Container, if it is found; otherwise, do nothing. + * Remove the specified Valve from the pipeline associated with this Container, if it is found; otherwise, do nothing. * * @param valve Valve to be removed */ @@ -1444,16 +1274,14 @@ public synchronized void removeValve(GlassFishValve valve) { } } - /** - *

Set the Valve instance that has been distinguished as the basic - * Valve for this Pipeline (if any). Prior to setting the basic Valve, - * the Valve's setContainer() will be called, if it - * implements Contained, with the owning Container as an - * argument. The method may throw an IllegalArgumentException - * if this Valve chooses not to be associated with this Container, or - * IllegalStateException if it is already associated with - * a different Container.

+ *

+ * Set the Valve instance that has been distinguished as the basic Valve for this Pipeline (if any). Prior to setting + * the basic Valve, the Valve's setContainer() will be called, if it implements Contained, + * with the owning Container as an argument. The method may throw an IllegalArgumentException if this Valve + * chooses not to be associated with this Container, or IllegalStateException if it is already associated + * with a different Container. + *

* * @param valve Valve to be distinguished as the basic Valve */ @@ -1464,24 +1292,19 @@ public void setBasic(GlassFishValve valve) { } - /** - * Execute a periodic task, such as reloading, etc. This method will be - * invoked inside the classloading context of this container. Unexpected - * throwables will be caught and logged. + * Execute a periodic task, such as reloading, etc. This method will be invoked inside the classloading context of this + * container. Unexpected throwables will be caught and logged. */ @Override public void backgroundProcess() { } - // ------------------------------------------------------ Protected Methods - /** - * Notify all container event listeners that a particular event has - * occurred for this Container. The default implementation performs - * this notification synchronously using the calling thread. + * Notify all container event listeners that a particular event has occurred for this Container. The default + * implementation performs this notification synchronously using the calling thread. * * @param type Event type * @param data Event data @@ -1504,7 +1327,6 @@ public void fireContainerEvent(String type, Object data) { } } - /** * Starts the children of this container. */ @@ -1528,25 +1350,22 @@ protected void startChildren() { } } - /** * Log the specified message to our current Logger (if any). * * @param message Message to be logged */ protected void log(String message) { - message = neutralizeForLog(message); + message = neutralizeForLog(message); // Logger logger = getLogger(); // if (logger != null) // logger.log(logName() + ": " + message); // else - log.log(Level.INFO, message); + log.log(Level.INFO, message); } - /** - * Log the specified message and exception to our current Logger - * (if any). + * Log the specified message and exception to our current Logger (if any). * * @param message Message to be logged * @param throwable Related exception @@ -1562,7 +1381,6 @@ protected void log(String message, Throwable throwable) { } - /** * Return the abbreviated name of this container for logging messages */ @@ -1577,7 +1395,7 @@ protected String logName() { } - // -------------------- JMX and Registration -------------------- + // -------------------- JMX and Registration -------------------- protected String domain; protected ObjectName oname; protected ObjectName controller; @@ -1597,43 +1415,39 @@ public String getObjectName() { } public String getDomain() { - if( domain==null ) { - Container parent=this; - while( parent != null && - !( parent instanceof StandardEngine) ) { - parent=parent.getParent(); + if (domain == null) { + Container parent = this; + while (parent != null && !(parent instanceof StandardEngine)) { + parent = parent.getParent(); } - if( parent != null ) { + if (parent != null) { // parent will always be an instanceof StandardEngine unless it is null - domain=((StandardEngine)parent).getDomain(); + domain = ((StandardEngine) parent).getDomain(); } } return domain; } public void setDomain(String domain) { - this.domain=domain; + this.domain = domain; } - public ObjectName[] getChildren() { - synchronized(children) { - ObjectName result[]=new ObjectName[children.size()]; - Iterator it=children.values().iterator(); - int i=0; - while( it.hasNext() ) { - Object next=it.next(); - if( next instanceof ContainerBase ) { - result[i++]=((ContainerBase)next).getJmxName(); + synchronized (children) { + ObjectName result[] = new ObjectName[children.size()]; + Iterator it = children.values().iterator(); + int i = 0; + while (it.hasNext()) { + Object next = it.next(); + if (next instanceof ContainerBase) { + result[i++] = ((ContainerBase) next).getJmxName(); } } return result; } } - public ObjectName createObjectName(String domain, ObjectName parent) - throws Exception - { + public ObjectName createObjectName(String domain, ObjectName parent) throws Exception { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, neutralizeForLog("Create ObjectName " + domain + " " + parent)); } @@ -1641,29 +1455,29 @@ public ObjectName createObjectName(String domain, ObjectName parent) } public String getContainerSuffix() { - Container container=this; - Container context=null; - Container host=null; - Container servlet=null; - - StringBuilder suffix=new StringBuilder(); - - if( container instanceof StandardHost ) { - host=container; - } else if( container instanceof StandardContext ) { - host=container.getParent(); - context=container; - } else if( container instanceof StandardWrapper ) { - context=container.getParent(); - host=context.getParent(); - servlet=container; - } - if( context!=null ) { - String path=((StandardContext)context).getEncodedPath(); + Container container = this; + Container context = null; + Container host = null; + Container servlet = null; + + StringBuilder suffix = new StringBuilder(); + + if (container instanceof StandardHost) { + host = container; + } else if (container instanceof StandardContext) { + host = container.getParent(); + context = container; + } else if (container instanceof StandardWrapper) { + context = container.getParent(); + host = context.getParent(); + servlet = container; + } + if (context != null) { + String path = ((StandardContext) context).getEncodedPath(); suffix.append(",path=").append((path.equals("")) ? "/" : path); } - if( host!=null ) { - suffix.append(",host=").append( host.getName() ); + if (host != null) { + suffix.append(",host=").append(host.getName()); } if (servlet != null) { String containerName = container.getName(); @@ -1673,10 +1487,8 @@ public String getContainerSuffix() { return suffix.toString(); } - /** - * Start the background thread that will periodically check for - * session timeouts. + * Start the background thread that will periodically check for session timeouts. */ protected void threadStart() { @@ -1695,10 +1507,8 @@ protected void threadStart() { } - /** - * Stop the background thread that is periodically checking for - * session timeouts. + * Stop the background thread that is periodically checking for session timeouts. */ protected void threadStop() { @@ -1718,13 +1528,10 @@ protected void threadStop() { } - // -------------------------------------- ContainerExecuteDelay Inner Class - /** - * Private thread class to invoke the backgroundProcess method - * of this container and its children after a fixed delay. + * Private thread class to invoke the backgroundProcess method of this container and its children after a fixed delay. */ protected class ContainerBackgroundProcessor implements Runnable { @@ -1738,8 +1545,7 @@ public void run() { } if (!threadDone) { Container parent = (Container) getMappingObject(); - ClassLoader cl = - Thread.currentThread().getContextClassLoader(); + ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (parent.getLoader() != null) { cl = parent.getLoader().getClassLoader(); } @@ -1751,8 +1557,7 @@ public void run() { protected void processChildren(Container container, ClassLoader cl) { try { if (container.getLoader() != null) { - Thread.currentThread().setContextClassLoader - (container.getLoader().getClassLoader()); + Thread.currentThread().setContextClassLoader(container.getLoader().getClassLoader()); } container.backgroundProcess(); } catch (Throwable t) { diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardContext.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardContext.java index 3cda27d1917..369bd75f48b 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardContext.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardContext.java @@ -18,6 +18,84 @@ package org.apache.catalina.core; +import static com.sun.enterprise.util.Utility.isAllNull; +import static com.sun.enterprise.util.Utility.isEmpty; +import static com.sun.logging.LogCleanerUtil.neutralizeForLog; +import static jakarta.servlet.RequestDispatcher.ERROR_EXCEPTION; +import static java.text.MessageFormat.format; +import static java.util.Collections.synchronizedList; +import static java.util.Collections.unmodifiableMap; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.FINEST; +import static java.util.logging.Level.INFO; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; +import static org.apache.catalina.ContainerEvent.AFTER_CONTEXT_DESTROYED; +import static org.apache.catalina.ContainerEvent.AFTER_CONTEXT_INITIALIZED; +import static org.apache.catalina.ContainerEvent.AFTER_CONTEXT_INITIALIZER_ON_STARTUP; +import static org.apache.catalina.ContainerEvent.AFTER_REQUEST_DESTROYED; +import static org.apache.catalina.ContainerEvent.AFTER_REQUEST_INITIALIZED; +import static org.apache.catalina.ContainerEvent.BEFORE_CONTEXT_DESTROYED; +import static org.apache.catalina.ContainerEvent.BEFORE_CONTEXT_INITIALIZED; +import static org.apache.catalina.ContainerEvent.BEFORE_CONTEXT_INITIALIZER_ON_STARTUP; +import static org.apache.catalina.ContainerEvent.BEFORE_REQUEST_DESTROYED; +import static org.apache.catalina.ContainerEvent.BEFORE_REQUEST_INITIALIZED; +import static org.apache.catalina.ContainerEvent.PRE_DESTROY; +import static org.apache.catalina.Globals.ALTERNATE_RESOURCES_ATTR; +import static org.apache.catalina.Globals.ALT_DD_ATTR; +import static org.apache.catalina.Globals.FACES_INITIALIZER; +import static org.apache.catalina.Globals.META_INF_RESOURCES; +import static org.apache.catalina.Globals.RESOURCES_ATTR; +import static org.apache.catalina.LogFacade.BIND_THREAD_EXCEPTION; +import static org.apache.catalina.LogFacade.CONTAINER_ALREADY_STARTED_EXCEPTION; +import static org.apache.catalina.LogFacade.CONTAINER_NOT_STARTED_EXCEPTION; +import static org.apache.catalina.LogFacade.DEPENDENCY_CHECK_EXCEPTION; +import static org.apache.catalina.LogFacade.DUPLICATE_SERVLET_MAPPING_EXCEPTION; +import static org.apache.catalina.LogFacade.ERROR_PAGE_LOCATION_EXCEPTION; +import static org.apache.catalina.LogFacade.ERROR_PAGE_REQUIRED_EXCEPTION; +import static org.apache.catalina.LogFacade.FILTER_MAPPING_INVALID_URL_EXCEPTION; +import static org.apache.catalina.LogFacade.FILTER_MAPPING_NAME_EXCEPTION; +import static org.apache.catalina.LogFacade.FILTER_WITHOUT_ANY_CLASS; +import static org.apache.catalina.LogFacade.INIT_RESOURCES_EXCEPTION; +import static org.apache.catalina.LogFacade.INVALID_ERROR_PAGE_CODE_EXCEPTION; +import static org.apache.catalina.LogFacade.INVOKING_SERVLET_CONTAINER_INIT_EXCEPTION; +import static org.apache.catalina.LogFacade.JSP_FILE_FINE; +import static org.apache.catalina.LogFacade.LISTENER_STOP_EXCEPTION; +import static org.apache.catalina.LogFacade.LOGIN_CONFIG_ERROR_PAGE_EXCEPTION; +import static org.apache.catalina.LogFacade.LOGIN_CONFIG_LOGIN_PAGE_EXCEPTION; +import static org.apache.catalina.LogFacade.LOGIN_CONFIG_REQUIRED_EXCEPTION; +import static org.apache.catalina.LogFacade.MISS_PATH_OR_URL_PATTERN_EXCEPTION; +import static org.apache.catalina.LogFacade.NO_WRAPPER_EXCEPTION; +import static org.apache.catalina.LogFacade.NULL_EMPTY_FILTER_NAME_EXCEPTION; +import static org.apache.catalina.LogFacade.NULL_EMPTY_SERVLET_NAME_EXCEPTION; +import static org.apache.catalina.LogFacade.NULL_FILTER_INSTANCE_EXCEPTION; +import static org.apache.catalina.LogFacade.NULL_SERVLET_INSTANCE_EXCEPTION; +import static org.apache.catalina.LogFacade.RELOADING_STARTED; +import static org.apache.catalina.LogFacade.REQUEST_DESTROY_EXCEPTION; +import static org.apache.catalina.LogFacade.REQUEST_INIT_EXCEPTION; +import static org.apache.catalina.LogFacade.RESETTING_CONTEXT_EXCEPTION; +import static org.apache.catalina.LogFacade.RESOURCES_STARTED; +import static org.apache.catalina.LogFacade.SECURITY_CONSTRAINT_PATTERN_EXCEPTION; +import static org.apache.catalina.LogFacade.SERVLET_CONTEXT_ALREADY_INIT_EXCEPTION; +import static org.apache.catalina.LogFacade.SERVLET_LOAD_EXCEPTION; +import static org.apache.catalina.LogFacade.SERVLET_MAPPING_INVALID_URL_EXCEPTION; +import static org.apache.catalina.LogFacade.SERVLET_MAPPING_UNKNOWN_NAME_EXCEPTION; +import static org.apache.catalina.LogFacade.STARTING_CONTEXT_EXCEPTION; +import static org.apache.catalina.LogFacade.STARTING_RESOURCES_EXCEPTION; +import static org.apache.catalina.LogFacade.STARTING_RESOURCE_EXCEPTION_MESSAGE; +import static org.apache.catalina.LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION; +import static org.apache.catalina.LogFacade.STOPPING_CONTEXT_EXCEPTION; +import static org.apache.catalina.LogFacade.STOPPING_RESOURCES_EXCEPTION; +import static org.apache.catalina.LogFacade.WRAPPER_ERROR_EXCEPTION; +import static org.apache.catalina.core.Constants.DEFAULT_SERVLET_NAME; +import static org.apache.catalina.core.Constants.JSP_SERVLET_NAME; +import static org.apache.catalina.startup.Constants.WebDtdPublicId_22; +import static org.apache.catalina.util.RequestUtil.urlDecode; +import static org.apache.naming.resources.ProxyDirContext.CONTEXT; +import static org.apache.naming.resources.ProxyDirContext.HOST; +import static org.glassfish.web.loader.ServletContainerInitializerUtil.getInitializerList; +import static org.glassfish.web.loader.ServletContainerInitializerUtil.getInterestList; + import jakarta.servlet.Filter; import jakarta.servlet.FilterConfig; import jakarta.servlet.FilterRegistration; @@ -43,7 +121,6 @@ import jakarta.servlet.http.HttpSessionIdListener; import jakarta.servlet.http.HttpSessionListener; import jakarta.servlet.http.HttpUpgradeHandler; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -54,7 +131,6 @@ import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; -import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; @@ -78,7 +154,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; - import javax.management.MBeanRegistrationException; import javax.management.MalformedObjectNameException; import javax.management.Notification; @@ -87,7 +162,6 @@ import javax.naming.Binding; import javax.naming.NamingException; import javax.naming.directory.DirContext; - import org.apache.catalina.Auditor; import org.apache.catalina.Authenticator; import org.apache.catalina.Container; @@ -153,44 +227,6 @@ import org.glassfish.web.loader.WebappClassLoader; import org.glassfish.web.valve.GlassFishValve; -import static com.sun.enterprise.util.Utility.isAllNull; -import static com.sun.enterprise.util.Utility.isEmpty; -import static com.sun.logging.LogCleanerUtil.neutralizeForLog; -import static jakarta.servlet.RequestDispatcher.ERROR_EXCEPTION; -import static java.text.MessageFormat.format; -import static java.util.Collections.synchronizedList; -import static java.util.Collections.unmodifiableMap; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.FINEST; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static org.apache.catalina.ContainerEvent.AFTER_CONTEXT_DESTROYED; -import static org.apache.catalina.ContainerEvent.AFTER_CONTEXT_INITIALIZED; -import static org.apache.catalina.ContainerEvent.AFTER_CONTEXT_INITIALIZER_ON_STARTUP; -import static org.apache.catalina.ContainerEvent.AFTER_REQUEST_DESTROYED; -import static org.apache.catalina.ContainerEvent.AFTER_REQUEST_INITIALIZED; -import static org.apache.catalina.ContainerEvent.BEFORE_CONTEXT_DESTROYED; -import static org.apache.catalina.ContainerEvent.BEFORE_CONTEXT_INITIALIZED; -import static org.apache.catalina.ContainerEvent.BEFORE_CONTEXT_INITIALIZER_ON_STARTUP; -import static org.apache.catalina.ContainerEvent.BEFORE_REQUEST_DESTROYED; -import static org.apache.catalina.ContainerEvent.BEFORE_REQUEST_INITIALIZED; -import static org.apache.catalina.ContainerEvent.PRE_DESTROY; -import static org.apache.catalina.Globals.ALTERNATE_RESOURCES_ATTR; -import static org.apache.catalina.Globals.ALT_DD_ATTR; -import static org.apache.catalina.Globals.FACES_INITIALIZER; -import static org.apache.catalina.Globals.META_INF_RESOURCES; -import static org.apache.catalina.Globals.RESOURCES_ATTR; -import static org.apache.catalina.LogFacade.*; -import static org.apache.catalina.core.Constants.DEFAULT_SERVLET_NAME; -import static org.apache.catalina.core.Constants.JSP_SERVLET_NAME; -import static org.apache.catalina.startup.Constants.WebDtdPublicId_22; -import static org.apache.catalina.util.RequestUtil.urlDecode; -import static org.apache.naming.resources.ProxyDirContext.CONTEXT; -import static org.apache.naming.resources.ProxyDirContext.HOST; -import static org.glassfish.web.loader.ServletContainerInitializerUtil.getInitializerList; -import static org.glassfish.web.loader.ServletContainerInitializerUtil.getInterestList; - /** * Standard implementation of the Context interface. Each child container must be a Wrapper implementation to * process the requests directed to a particular servlet. @@ -729,11 +765,6 @@ public class StandardContext extends ContainerBase implements Context, ServletCo */ private boolean isProgrammaticServletContextListenerRegistrationAllowed; - /** - * Security manager responsible for enforcing permission check on ServletContext#getClassLoader - */ - private MySecurityManager mySecurityManager; - /** Iterable over all ServletContainerInitializers that were discovered */ private ServiceLoader servletContainerInitializers; @@ -771,12 +802,8 @@ public Level getNonCriticalClassloadingErrorLogLevel() { public StandardContext() { pipeline.setBasic(new StandardContextValve()); namingResources.setContainer(this); - if (Globals.IS_SECURITY_ENABLED) { - mySecurityManager = AccessController.doPrivileged(new PrivilegedCreateSecurityManager()); - } } - @Override public String getEncodedPath() { return encodedPath; @@ -2490,9 +2517,7 @@ public ClassLoader getClassLoader() { if (webappLoader == null) { return null; } - if (mySecurityManager != null) { - mySecurityManager.checkGetClassLoaderPermission(webappLoader); - } + return webappLoader; } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardWrapper.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardWrapper.java index ad63285fdee..aea04a64da4 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardWrapper.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/StandardWrapper.java @@ -18,6 +18,25 @@ package org.apache.catalina.core; +import static com.sun.logging.LogCleanerUtil.neutralizeForLog; +import static java.text.MessageFormat.format; +import static java.util.Collections.emptySet; +import static java.util.Collections.unmodifiableList; +import static java.util.logging.Level.FINEST; +import static org.apache.catalina.InstanceEvent.EventType.AFTER_DESTROY_EVENT; +import static org.apache.catalina.InstanceEvent.EventType.AFTER_INIT_EVENT; +import static org.apache.catalina.InstanceEvent.EventType.AFTER_SERVICE_EVENT; +import static org.apache.catalina.InstanceEvent.EventType.BEFORE_DESTROY_EVENT; +import static org.apache.catalina.InstanceEvent.EventType.BEFORE_INIT_EVENT; +import static org.apache.catalina.InstanceEvent.EventType.BEFORE_SERVICE_EVENT; +import static org.apache.catalina.LogFacade.CANNOT_ALLOCATE_SERVLET_EXCEPTION; +import static org.apache.catalina.LogFacade.CANNOT_FIND_SERVLET_CLASS_EXCEPTION; +import static org.apache.catalina.LogFacade.ERROR_ALLOCATE_SERVLET_INSTANCE_EXCEPTION; +import static org.apache.catalina.LogFacade.ERROR_LOADING_INFO; +import static org.apache.catalina.LogFacade.PARENT_CONTAINER_MUST_BE_CONTEXT_EXCEPTION; +import static org.apache.catalina.LogFacade.WRAPPER_CONTAINER_NO_CHILD_EXCEPTION; +import static org.apache.catalina.core.Constants.JSP_SERVLET_CLASS; + import jakarta.servlet.Servlet; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletContext; @@ -28,13 +47,8 @@ import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -46,11 +60,9 @@ import java.util.Stack; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; - import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; - import org.apache.catalina.Container; import org.apache.catalina.ContainerServlet; import org.apache.catalina.Context; @@ -59,30 +71,10 @@ import org.apache.catalina.Loader; import org.apache.catalina.LogFacade; import org.apache.catalina.Wrapper; -import org.apache.catalina.security.SecurityUtil; import org.apache.catalina.util.Enumerator; import org.apache.catalina.util.InstanceSupport; import org.glassfish.web.valve.GlassFishValve; -import static com.sun.logging.LogCleanerUtil.neutralizeForLog; -import static java.text.MessageFormat.format; -import static java.util.Collections.emptySet; -import static java.util.Collections.unmodifiableList; -import static java.util.logging.Level.FINEST; -import static org.apache.catalina.InstanceEvent.EventType.AFTER_DESTROY_EVENT; -import static org.apache.catalina.InstanceEvent.EventType.AFTER_INIT_EVENT; -import static org.apache.catalina.InstanceEvent.EventType.AFTER_SERVICE_EVENT; -import static org.apache.catalina.InstanceEvent.EventType.BEFORE_DESTROY_EVENT; -import static org.apache.catalina.InstanceEvent.EventType.BEFORE_INIT_EVENT; -import static org.apache.catalina.InstanceEvent.EventType.BEFORE_SERVICE_EVENT; -import static org.apache.catalina.LogFacade.CANNOT_ALLOCATE_SERVLET_EXCEPTION; -import static org.apache.catalina.LogFacade.CANNOT_FIND_SERVLET_CLASS_EXCEPTION; -import static org.apache.catalina.LogFacade.ERROR_ALLOCATE_SERVLET_INSTANCE_EXCEPTION; -import static org.apache.catalina.LogFacade.ERROR_LOADING_INFO; -import static org.apache.catalina.LogFacade.PARENT_CONTAINER_MUST_BE_CONTEXT_EXCEPTION; -import static org.apache.catalina.LogFacade.WRAPPER_CONTAINER_NO_CHILD_EXCEPTION; -import static org.apache.catalina.core.Constants.JSP_SERVLET_CLASS; - /** * Standard implementation of the Wrapper interface that represents an individual servlet definition. No child * Containers are allowed, and the parent Container must be a Context. @@ -1209,27 +1201,7 @@ private synchronized void loadServletClass() throws ServletException { // Load the specified servlet class from the appropriate class loader Class clazz = null; try { - if (SecurityUtil.isPackageProtectionEnabled()) { - try { - PrivilegedExceptionAction> action = () -> { - if (classLoader == null) { - return Class.forName(actualClassName); - } - return classLoader.loadClass(actualClassName); - }; - clazz = AccessController.doPrivileged(action); - } catch (PrivilegedActionException pax) { - Exception ex = pax.getException(); - if (ex instanceof ClassNotFoundException) { - throw (ClassNotFoundException) ex; - } - - getServletContext() - .log(format(rb.getString(ERROR_LOADING_INFO), new Object[] {classLoader, actualClassName}), ex); - } - } else { - clazz = classLoader == null ? Class.forName(actualClassName) : classLoader.loadClass(actualClassName); - } + clazz = classLoader == null ? Class.forName(actualClassName) : classLoader.loadClass(actualClassName); } catch (ClassNotFoundException e) { unavailable(null); String msgErrorLoadingInfo = format(rb.getString(ERROR_LOADING_INFO), @@ -1251,6 +1223,7 @@ private String resolveServletClassNameAndParameters() { if (servletClassName != null || jspFile == null) { return servletClassName; } + Wrapper jspWrapper = (Wrapper) ((Context) getParent()).findChild(Constants.JSP_SERVLET_NAME); if (jspWrapper == null) { return servletClassName; @@ -1279,14 +1252,7 @@ private void initServlet(Servlet servlet) throws ServletException { try { instanceSupport.fireInstanceEvent(BEFORE_INIT_EVENT, servlet); - if (SecurityUtil.executeUnderSubjectDoAs()) { - Object[] initType = new Object[1]; - initType[0] = facade; - SecurityUtil.doAsPrivilege("init", servlet, classType, initType); - initType = null; - } else { - servlet.init(facade); - } + servlet.init(facade); instanceInitialized = true; @@ -1307,14 +1273,7 @@ private void initServlet(Servlet servlet) throws ServletException { DummyResponse res = new DummyResponse(); - if (SecurityUtil.executeUnderSubjectDoAs()) { - Object[] serviceType = new Object[2]; - serviceType[0] = req; - serviceType[1] = res; - SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, serviceType); - } else { - servlet.service(req, res); - } + servlet.service(req, res); } instanceSupport.fireInstanceEvent(AFTER_INIT_EVENT, servlet); @@ -1339,12 +1298,11 @@ private void initServlet(Servlet servlet) throws ServletException { } } - // START IASRI 4665318 - void service(ServletRequest request, ServletResponse response, Servlet serv) throws IOException, ServletException { + void service(ServletRequest request, ServletResponse response, Servlet servlet) throws IOException, ServletException { InstanceSupport supp = getInstanceSupport(); try { - supp.fireInstanceEvent(BEFORE_SERVICE_EVENT, serv, request, response); + supp.fireInstanceEvent(BEFORE_SERVICE_EVENT, servlet, request, response); if (!isAsyncSupported()) { RequestFacadeHelper reqFacHelper = RequestFacadeHelper.getInstance(request); if (reqFacHelper != null) { @@ -1352,43 +1310,26 @@ void service(ServletRequest request, ServletResponse response, Servlet serv) thr } } - if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { + servlet.service(request, response); - if (SecurityUtil.executeUnderSubjectDoAs()) { - final ServletRequest req = request; - final ServletResponse res = response; - Principal principal = ((HttpServletRequest) req).getUserPrincipal(); - - Object[] serviceType = new Object[2]; - serviceType[0] = req; - serviceType[1] = res; - - SecurityUtil.doAsPrivilege("service", serv, classTypeUsedInService, serviceType, principal); - } else { - serv.service(request, response); - } - } else { - serv.service(request, response); - } - supp.fireInstanceEvent(AFTER_SERVICE_EVENT, serv, request, response); + supp.fireInstanceEvent(AFTER_SERVICE_EVENT, servlet, request, response); } catch (IOException | ServletException | RuntimeException | Error e) { log.log(Level.FINE, "Seen throwable, firing instance event and rethrowing ...", e); // Set response status before firing event, see IT 10022 if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } - supp.fireInstanceEvent(AFTER_SERVICE_EVENT, serv, request, response, e); + supp.fireInstanceEvent(AFTER_SERVICE_EVENT, servlet, request, response, e); throw e; } catch (Throwable e) { log.log(Level.FINE, "Seen throwable, firing instance event and throwing a servlet exception ...", e); // Set response status before firing event, see IT 10022 ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - supp.fireInstanceEvent(AFTER_SERVICE_EVENT, serv, request, response, e); + supp.fireInstanceEvent(AFTER_SERVICE_EVENT, servlet, request, response, e); throw new ServletException(rb.getString(LogFacade.SERVLET_EXECUTION_EXCEPTION), e); } } - // END IASRI 4665318 /** * Remove the specified initialization parameter from this servlet. @@ -1535,12 +1476,7 @@ public synchronized void unload() throws ServletException { instanceSupport.fireInstanceEvent(BEFORE_DESTROY_EVENT, instance); Thread.currentThread().setContextClassLoader(classLoader); - if (SecurityUtil.executeUnderSubjectDoAs()) { - SecurityUtil.doAsPrivilege("destroy", instance); - SecurityUtil.remove(instance); - } else { - instance.destroy(); - } + instance.destroy(); instanceSupport.fireInstanceEvent(AFTER_DESTROY_EVENT, instance); } catch (Throwable t) { @@ -1566,12 +1502,7 @@ public synchronized void unload() throws ServletException { try { Thread.currentThread().setContextClassLoader(classLoader); while (!instancePool.isEmpty()) { - if (SecurityUtil.executeUnderSubjectDoAs()) { - SecurityUtil.doAsPrivilege("destroy", instancePool.pop()); - SecurityUtil.remove(instance); - } else { - instancePool.pop().destroy(); - } + instancePool.pop().destroy(); } } catch (Throwable t) { instancePool = null; diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/loader/WebappLoader.java b/appserver/web/web-core/src/main/java/org/apache/catalina/loader/WebappLoader.java index 609fd4738d6..ca953949cb2 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/loader/WebappLoader.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/loader/WebappLoader.java @@ -18,43 +18,37 @@ package org.apache.catalina.loader; +import static com.sun.logging.LogCleanerUtil.neutralizeForLog; +import static java.util.logging.Level.FINEST; +import static java.util.logging.Level.SEVERE; +import static org.apache.catalina.LogFacade.SET_RELOADABLE_PROPERTY_EXCEPTION; import com.sun.enterprise.loader.ASURLClassLoader; - import jakarta.servlet.ServletContext; - import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.FileOutputStream; -import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; -import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandlerFactory; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.text.MessageFormat; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; - import javax.management.ObjectName; import javax.naming.Binding; import javax.naming.NameClassPair; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; - import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Globals; @@ -64,7 +58,6 @@ import org.apache.catalina.Loader; import org.apache.catalina.LogFacade; import org.apache.catalina.core.StandardContext; -import org.apache.catalina.security.SecurityUtil; import org.apache.catalina.util.LifecycleSupport; import org.apache.catalina.util.StringManager; import org.apache.naming.resources.DirContextURLStreamHandler; @@ -72,53 +65,44 @@ import org.apache.naming.resources.Resource; import org.glassfish.web.loader.WebappClassLoader; -import static com.sun.logging.LogCleanerUtil.neutralizeForLog; -import static org.apache.catalina.LogFacade.SET_RELOADABLE_PROPERTY_EXCEPTION; - /** - * Classloader implementation which is specialized for handling web - * applications in the most efficient way, while being Catalina aware (all - * accesses to resources are made through the DirContext interface). - * This class loader supports detection of modified - * Java classes, which can be used to implement auto-reload support. + * Classloader implementation which is specialized for handling web applications in the most efficient way, while being + * Catalina aware (all accesses to resources are made through the DirContext interface). This class loader supports + * detection of modified Java classes, which can be used to implement auto-reload support. *

- * This class loader is configured by adding the pathnames of directories, - * JAR files, and ZIP files with the addRepository() method, - * prior to calling start(). When a new class is required, - * these repositories will be consulted first to locate the class. If it - * is not present, the system class loader will be used instead. + * This class loader is configured by adding the pathnames of directories, JAR files, and ZIP files with the + * addRepository() method, prior to calling start(). When a new class is required, these + * repositories will be consulted first to locate the class. If it is not present, the system class loader will be used + * instead. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Revision: 1.10 $ $Date: 2007/05/05 05:32:09 $ */ -public class WebappLoader - implements Lifecycle, Loader, PropertyChangeListener { +public class WebappLoader implements Lifecycle, Loader, PropertyChangeListener { + + private static final Logger log = LogFacade.getLogger(); + private static final ResourceBundle rb = log.getResourceBundle(); /** * First load of the class. */ private static boolean first = true; - private static final Logger log = LogFacade.getLogger(); - private static final ResourceBundle rb = log.getResourceBundle(); - - // --------------------------------------------------------- Constructors /** - * Construct a new WebappLoader with no defined parent class loader - * (so that the actual parent will be the system class loader). + * Construct a new WebappLoader with no defined parent class loader (so that the actual parent will be the system class + * loader). */ public WebappLoader() { this(null); } - /** - * Construct a new WebappLoader with the specified class loader - * to be defined as the parent of the ClassLoader we ultimately create. + * Construct a new WebappLoader with the specified class loader to be defined as the parent of the ClassLoader we + * ultimately create. * * @param parent The parent class loader */ @@ -127,7 +111,6 @@ public WebappLoader(ClassLoader parent) { this.parentClassLoader = parent; } - // --------------------------------------------------- Instance Variables private ObjectName oname; @@ -138,43 +121,34 @@ public WebappLoader(ClassLoader parent) { */ private WebappClassLoader classLoader; - /** * The Container with which this Loader has been associated. */ private Container container; - /** * The debugging detail level for this component. */ private int debug; - /** - * The "follow standard delegation model" flag that will be used to - * configure our ClassLoader. + * The "follow standard delegation model" flag that will be used to configure our ClassLoader. */ private boolean delegate = WebappClassLoader.DELEGATE_DEFAULT; - /** * The descriptive information about this Loader implementation. */ - private static final String info = - "org.apache.catalina.loader.WebappLoader/1.0"; - + private static final String info = "org.apache.catalina.loader.WebappLoader/1.0"; /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); - /** - * The Java class name of the ClassLoader implementation to be used. - * This class should extend WebappClassLoader, otherwise, a different - * loader implementation must be used. + * The Java class name of the ClassLoader implementation to be used. This class should extend WebappClassLoader, + * otherwise, a different loader implementation must be used. */ private String loaderClass = WebappClassLoader.class.getName(); @@ -183,19 +157,16 @@ public WebappLoader(ClassLoader parent) { */ private ClassLoader parentClassLoader; - /** * The reloadable flag for this Loader. */ private boolean reloadable; - /** * The set of repositories associated with this class loader. */ private String repositories[] = new String[0]; - /** * The string manager for this package. */ @@ -206,23 +177,19 @@ public WebappLoader(ClassLoader parent) { */ private boolean started; - /** * The property change support for this component. */ protected PropertyChangeSupport support = new PropertyChangeSupport(this); - /** * Classpath set in the loader. */ private String classpath; - /** - * Set of packages that may always be overridden, regardless of whether - * they belong to a protected namespace (i.e., a namespace that may never - * be overridden by a webapp) + * Set of packages that may always be overridden, regardless of whether they belong to a protected namespace (i.e., a + * namespace that may never be overridden by a webapp) */ private Set overridablePackages = Set.of(); @@ -232,7 +199,6 @@ public WebappLoader(ClassLoader parent) { // ------------------------------------------------------------- Properties - /** * Return the Java class loader to be used by this Container. */ @@ -241,7 +207,6 @@ public ClassLoader getClassLoader() { return classLoader; } - /** * Return the Container with which this Logger has been associated. */ @@ -250,7 +215,6 @@ public Container getContainer() { return (container); } - /** * Set the Container with which this Logger has been associated. * @@ -271,20 +235,18 @@ public void setContainer(Container container) { // Register with the new Container (if any) if (this.container instanceof Context) { - setReloadable( ((Context) this.container).getReloadable() ); + setReloadable(((Context) this.container).getReloadable()); ((Context) this.container).addPropertyChangeListener(this); } } - /** * @return the debugging detail level for this component. */ public int getDebug() { - return (this.debug); + return debug; } - /** * Set the debugging detail level for this component. * @@ -296,20 +258,16 @@ public void setDebug(int debug) { support.firePropertyChange("debug", Integer.valueOf(oldDebug), Integer.valueOf(this.debug)); } - /** - * Return the "follow standard delegation model" flag used to configure - * our ClassLoader. + * Return the "follow standard delegation model" flag used to configure our ClassLoader. */ @Override public boolean getDelegate() { return this.delegate; } - /** - * Set the "follow standard delegation model" flag used to configure - * our ClassLoader. + * Set the "follow standard delegation model" flag used to configure our ClassLoader. * * @param delegate The new flag */ @@ -320,26 +278,22 @@ public void setDelegate(boolean delegate) { support.firePropertyChange("delegate", Boolean.valueOf(oldDelegate), Boolean.valueOf(this.delegate)); } - /** - * Return descriptive information about this Loader implementation and - * the corresponding version number, in the format + * Return descriptive information about this Loader implementation and the corresponding version number, in the format * <description>/<version>. */ @Override public String getInfo() { - return (info); + return info; } - /** * Return the ClassLoader class name. */ public String getLoaderClass() { - return (this.loaderClass); + return loaderClass; } - /** * Set the ClassLoader class name. * @@ -349,16 +303,14 @@ public void setLoaderClass(String loaderClass) { this.loaderClass = loaderClass; } - /** * Return the reloadable flag for this Loader. */ @Override public boolean getReloadable() { - return (this.reloadable); + return reloadable; } - /** * Set the reloadable flag for this Loader. * @@ -372,15 +324,12 @@ public void setReloadable(boolean reloadable) { support.firePropertyChange("reloadable", Boolean.valueOf(oldReloadable), Boolean.valueOf(this.reloadable)); } - public void setUseMyFaces(boolean useMyFaces) { this.useMyFaces = useMyFaces; } - // --------------------------------------------------------- Public Methods - /** * Add a property change listener to this component. * @@ -391,7 +340,6 @@ public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } - /** * Add a new repository to the set of repositories for this class loader. * @@ -399,9 +347,8 @@ public void addPropertyChangeListener(PropertyChangeListener listener) { */ @Override public void addRepository(String repository) { - - if (log.isLoggable(Level.FINEST)) { - log.log(Level.FINEST, "Adding repository " + repository); + if (log.isLoggable(FINEST)) { + log.log(FINEST, "Adding repository " + repository); } for (String element : repositories) { @@ -423,12 +370,9 @@ public void addRepository(String repository) { } - /** - * Return the set of repositories defined for this class loader. - * If none are defined, a zero-length array is returned. - * For security reason, returns a clone of the Array (since - * String are immutable). + * Return the set of repositories defined for this class loader. If none are defined, a zero-length array is returned. + * For security reason, returns a clone of the Array (since String are immutable). */ @Override public String[] findRepositories() { @@ -439,10 +383,8 @@ public String[] getRepositories() { return repositories.clone(); } - /** - * Classpath, as set in org.apache.catalina.jsp_classpath context - * property + * Classpath, as set in org.apache.catalina.jsp_classpath context property * * @return The classpath */ @@ -450,17 +392,15 @@ public String getClasspath() { return classpath; } - /** - * Has the internal repository associated with this Loader been modified, - * such that the loaded classes should be reloaded? + * Has the internal repository associated with this Loader been modified, such that the loaded classes should be + * reloaded? */ @Override public boolean modified() { - return (classLoader.modified()); + return classLoader.modified(); } - /** * Used to signal to the classloader to release JAR resources because of reload. */ @@ -470,7 +410,6 @@ public void reload() { } } - /** * Remove a property change listener from this component. * @@ -481,7 +420,6 @@ public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } - /** * Return a String representation of this component. */ @@ -495,10 +433,8 @@ public String toString() { return (sb.toString()); } - // ------------------------------------------------------ Lifecycle Methods - /** * Add a lifecycle event listener to this component. * @@ -509,17 +445,14 @@ public void addLifecycleListener(LifecycleListener listener) { lifecycle.addLifecycleListener(listener); } - /** - * Gets the (possibly empty) list of lifecycle listeners associated - * with this WebappLoader. + * Gets the (possibly empty) list of lifecycle listeners associated with this WebappLoader. */ @Override public List findLifecycleListeners() { return lifecycle.findLifecycleListeners(); } - /** * Remove a lifecycle event listener from this component. * @@ -530,52 +463,41 @@ public void removeLifecycleListener(LifecycleListener listener) { lifecycle.removeLifecycleListener(listener); } - private boolean initialized=false; + private boolean initialized = false; public void init() { - initialized=true; + initialized = true; - if( oname==null ) { + if (oname == null) { // not registered yet - standalone or API - if( container instanceof StandardContext) { + if (container instanceof StandardContext) { // Register ourself. The container must be a webapp try { - StandardContext ctx=(StandardContext)container; + StandardContext ctx = (StandardContext) container; String path = ctx.getEncodedPath(); if (path.equals("")) { path = "/"; } - oname = new ObjectName(ctx.getEngineName() + - ":type=Loader,path=" + - path + ",host=" + - ctx.getParent().getName()); + oname = new ObjectName(ctx.getEngineName() + ":type=Loader,path=" + path + ",host=" + ctx.getParent().getName()); controller = oname; } catch (Exception e) { - log.log(Level.SEVERE, LogFacade.REGISTERING_LOADER_EXCEPTION, e); + log.log(SEVERE, LogFacade.REGISTERING_LOADER_EXCEPTION, e); } } } - - /* - if( container == null ) { - // JMX created the loader - // TODO - } - */ } public void destroy() { - if( controller==oname ) { + if (controller == oname) { oname = null; } - initialized = false; + initialized = false; } private static synchronized void initStreamHandlerFactory() { // Register a stream handler factory for the JNDI protocol - URLStreamHandlerFactory streamHandlerFactory = - new DirContextURLStreamHandlerFactory(); + URLStreamHandlerFactory streamHandlerFactory = new DirContextURLStreamHandlerFactory(); synchronized (WebappLoader.class) { if (first) { @@ -584,12 +506,11 @@ private static synchronized void initStreamHandlerFactory() { URL.setURLStreamHandlerFactory(streamHandlerFactory); } catch (Exception e) { // Log and continue anyway, this is not critical - log.log(Level.SEVERE, LogFacade.REGISTERING_JNDI_STREAM_HANDLER_EXCEPTION, e); + log.log(SEVERE, LogFacade.REGISTERING_JNDI_STREAM_HANDLER_EXCEPTION, e); } catch (Throwable t) { // This is likely a dual registration if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Dual registration of jndi stream handler: " + - t.getMessage()); + log.log(Level.FINE, "Dual registration of jndi stream handler: " + t.getMessage()); } } } @@ -610,7 +531,7 @@ public void start() throws LifecycleException { if (started) { throw new LifecycleException(rb.getString(LogFacade.LOADER_ALREADY_STARTED_EXCEPTION)); } - log.log(Level.FINEST, "Starting {0}", this); + log.log(FINEST, "Starting {0}", this); lifecycle.fireLifecycleEvent(START_EVENT, null); started = true; @@ -628,8 +549,7 @@ public void start() throws LifecycleException { if (cl instanceof WebappClassLoader) { classLoader = (WebappClassLoader) cl; } else { - PrivilegedAction action = () -> new WebappClassLoader(cl); - classLoader = AccessController.doPrivileged(action); + classLoader = new WebappClassLoader(cl); } classLoader.setDelegate(delegate); classLoader.setOverridablePackages(overridablePackages); @@ -638,7 +558,6 @@ public void start() throws LifecycleException { classLoader.addRepository(element); } setRepositories(); - setPermissions(); setClassPath(); startNestedClassLoader(); @@ -646,12 +565,11 @@ public void start() throws LifecycleException { DirContextURLStreamHandler.bind(classLoader, resources); } catch (Throwable t) { - log.log(Level.SEVERE, LogFacade.LIFECYCLE_EXCEPTION, t); + log.log(SEVERE, LogFacade.LIFECYCLE_EXCEPTION, t); throw new LifecycleException("start: ", t); } } - /** * Stop this component, finalizing our associated class loader. * @@ -659,12 +577,11 @@ public void start() throws LifecycleException { */ @Override public void stop() throws LifecycleException { - // Validate and update our current component state if (!started) { throw new LifecycleException(rb.getString(LogFacade.LOADER_NOT_STARTED_EXCEPTION)); } - log.log(Level.FINEST, "Stopping {0}", this); + log.log(FINEST, "Stopping {0}", this); lifecycle.fireLifecycleEvent(STOP_EVENT, null); started = false; @@ -684,7 +601,6 @@ public void stop() throws LifecycleException { destroy(); } - /** * Stops the nested classloader */ @@ -696,10 +612,8 @@ public void stopNestedClassLoader() throws LifecycleException { } } - // ----------------------------------------- PropertyChangeListener Methods - /** * Process property change events from our associated Context. * @@ -707,7 +621,6 @@ public void stopNestedClassLoader() throws LifecycleException { */ @Override public void propertyChange(PropertyChangeEvent event) { - // Validate the source of this event if (!(event.getSource() instanceof Context)) { return; @@ -717,9 +630,9 @@ public void propertyChange(PropertyChangeEvent event) { String propName = event.getPropertyName(); if ("reloadable".equals(propName)) { try { - setReloadable(((Boolean) event.getNewValue()).booleanValue() ); + setReloadable(((Boolean) event.getNewValue()).booleanValue()); } catch (NumberFormatException e) { - log.log(Level.SEVERE, SET_RELOADABLE_PROPERTY_EXCEPTION, neutralizeForLog(event.getNewValue().toString())); + log.log(SEVERE, SET_RELOADABLE_PROPERTY_EXCEPTION, neutralizeForLog(event.getNewValue().toString())); } } else if ("antiJARLocking".equals(propName)) { ClassLoader cloader = Thread.currentThread().getContextClassLoader(); @@ -729,10 +642,8 @@ public void propertyChange(PropertyChangeEvent event) { } } - // ------------------------------------------------------- Private Methods - /** * Create associated classLoader. */ @@ -741,20 +652,16 @@ protected ClassLoader createClassLoader() throws Exception { if (parentClassLoader == null) { parentClassLoader = Thread.currentThread().getContextClassLoader(); } - Constructor constr = clazz.getConstructor(ClassLoader.class ); + Constructor constr = clazz.getConstructor(ClassLoader.class); WebappClassLoader webAppClassLoader = (WebappClassLoader) constr.newInstance(parentClassLoader); webAppClassLoader.setUseMyFaces(useMyFaces); return webAppClassLoader; } - /** - * Start the WebappClassLoader here as opposed to in the course of - * WebappLoader#start, in order to prevent it from being started - * twice (during normal deployment, the WebappClassLoader is created - * by the deployment backend without calling - * WebappLoader#createClassLoader, and will have been started - * by the time WebappLoader#start is called) + * Start the WebappClassLoader here as opposed to in the course of WebappLoader#start, in order to prevent it from being + * started twice (during normal deployment, the WebappClassLoader is created by the deployment backend without calling + * WebappLoader#createClassLoader, and will have been started by the time WebappLoader#start is called) * * @throws LifecycleException */ @@ -766,7 +673,6 @@ protected void startNestedClassLoader() throws LifecycleException { } } - /** * Log a message on the Logger associated with our Container (if any) * @@ -777,158 +683,42 @@ private void log(String message, Throwable t) { org.apache.catalina.Logger logger = null; String containerName = null; - if (container != null) { logger = container.getLogger(); containerName = container.getName(); } if (logger != null) { - String msg = MessageFormat.format(rb.getString(LogFacade.WEB_APP_LOADER_EXCEPTION), - new Object[] {containerName, message}); + String msg = MessageFormat.format(rb.getString(LogFacade.WEB_APP_LOADER_EXCEPTION), new Object[] { containerName, message }); logger.log(neutralizeForLog(msg), t); } else { - String msg = MessageFormat.format(rb.getString(LogFacade.WEB_APP_LOADER_EXCEPTION), - new Object[] {containerName, message}); + String msg = MessageFormat.format(rb.getString(LogFacade.WEB_APP_LOADER_EXCEPTION), new Object[] { containerName, message }); log.log(Level.WARNING, neutralizeForLog(msg), t); } } - /** - * Configure associated class loader permissions. - */ - private void setPermissions() { - - if (!Globals.IS_SECURITY_ENABLED) { - return; - } - if (!(container instanceof Context)) { - return; - } - - try { - PrivilegedExceptionAction action = () -> { - setPermissions_priv(); - return null; - }; - AccessController.doPrivileged(action); - } catch (PrivilegedActionException e) { - throw (SecurityException) e.getException(); - } - } - - - private void setPermissions_priv() { - classLoader.setPackageDefinitionSecurityEnabled(SecurityUtil.isPackageProtectionEnabled()); - - // Tell the class loader the root of the context - ServletContext servletContext = - ((Context) container).getServletContext(); - - // Assigning permissions for the work directory - File workDir = - (File) servletContext.getAttribute(ServletContext.TEMPDIR); - if (workDir != null) { - try { - String workDirPath = workDir.getCanonicalPath(); - classLoader.addPermission - (new FilePermission(workDirPath, "read,write")); - classLoader.addPermission - (new FilePermission(workDirPath + File.separator + "-", - "read,write,delete")); - } catch (IOException e) { - // Ignore - } - } - - try { - - URL rootURL = servletContext.getResource("/"); - classLoader.addPermission(rootURL); - - String contextRoot = servletContext.getRealPath("/"); - if (contextRoot != null) { - try { - contextRoot = (new File(contextRoot)).getCanonicalPath(); - classLoader.addPermission(contextRoot); - } catch (IOException e) { - // Ignore - } - } - - URL classesURL = servletContext.getResource("/WEB-INF/classes/"); - classLoader.addPermission(classesURL); - URL libURL = servletContext.getResource("/WEB-INF/lib/"); - classLoader.addPermission(libURL); - - if (contextRoot != null) { - - if (libURL != null) { - File rootDir = new File(contextRoot); - File libDir = new File(rootDir, "WEB-INF/lib/"); - try { - String path = libDir.getCanonicalPath(); - classLoader.addPermission(path); - } catch (IOException e) { - } - } - - } else { - - if (workDir != null) { - if (libURL != null) { - File libDir = new File(workDir, "WEB-INF/lib/"); - try { - String path = libDir.getCanonicalPath(); - classLoader.addPermission(path); - } catch (IOException e) { - } - } - if (classesURL != null) { - File classesDir = new File(workDir, "WEB-INF/classes/"); - try { - String path = classesDir.getCanonicalPath(); - classLoader.addPermission(path); - } catch (IOException e) { - } - } - } - - } - - } catch (MalformedURLException e) { - } - - } - - - /** - * Configure the repositories for our class loader, based on the - * associated Context. + * Configure the repositories for our class loader, based on the associated Context. */ private void setRepositories() throws IOException { - if (!(container instanceof Context)) { return; } - ServletContext servletContext = - ((Context) container).getServletContext(); + + ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) { return; } // Loading the work directory - File workDir = - (File) servletContext.getAttribute(ServletContext.TEMPDIR); + File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir == null) { if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, LogFacade.NO_WORK_DIR_INFO, servletContext); } } - if (log.isLoggable(Level.FINEST) && workDir != null) { - log.log(Level.FINEST, "Deploying class repositories to work directory" - + workDir.getAbsolutePath()); + if (log.isLoggable(FINEST) && workDir != null) { + log.log(FINEST, "Deploying class repositories to work directory" + workDir.getAbsolutePath()); } DirContext resources = container.getResources(); @@ -943,7 +733,7 @@ private void setRepositories() throws IOException { if (object instanceof DirContext) { classes = (DirContext) object; } - } catch(NamingException e) { + } catch (NamingException e) { // Silent catch: it's valid that no /WEB-INF/classes collection // exists } @@ -952,8 +742,7 @@ private void setRepositories() throws IOException { File classRepository = null; - String absoluteClassesPath = - servletContext.getRealPath(classesPath); + String absoluteClassesPath = servletContext.getRealPath(classesPath); if (absoluteClassesPath != null) { @@ -962,8 +751,7 @@ private void setRepositories() throws IOException { } else { classRepository = new File(workDir, classesPath); - if (!classRepository.mkdirs() && - !classRepository.isDirectory()) { + if (!classRepository.mkdirs() && !classRepository.isDirectory()) { throw new IOException(rb.getString(LogFacade.FAILED_CREATE_DEST_DIR)); } if (!copyDir(classes, classRepository)) { @@ -972,10 +760,8 @@ private void setRepositories() throws IOException { } - if (log.isLoggable(Level.FINEST)) { - log.log(Level.FINEST, "Deploy class files " - +classesPath+" to " - + classRepository.getAbsolutePath()); + if (log.isLoggable(FINEST)) { + log.log(FINEST, "Deploy class files " + classesPath + " to " + classRepository.getAbsolutePath()); } } @@ -1006,7 +792,7 @@ private void setRepositories() throws IOException { copyJars = true; destDir = new File(workDir, libPath); if (!destDir.mkdirs() && !destDir.isDirectory()) { - log.log(Level.SEVERE, LogFacade.FAILED_CREATE_WORK_DIR_EXCEPTION, destDir.getAbsolutePath()); + log.log(SEVERE, LogFacade.FAILED_CREATE_WORK_DIR_EXCEPTION, destDir.getAbsolutePath()); } } @@ -1016,31 +802,23 @@ private void setRepositories() throws IOException { // Looking up directory /WEB-INF/lib in the context try { - NamingEnumeration enumeration = - resources.listBindings(libPath); + NamingEnumeration enumeration = resources.listBindings(libPath); while (enumeration.hasMoreElements()) { Binding binding = enumeration.nextElement(); String filename = libPath + "/" + binding.getName(); - // START OF IASRI 4657979 - if (!filename.endsWith(".jar") && - !filename.endsWith(".zip")) { - // END OF IASRI 4657979 + if (!filename.endsWith(".jar") && !filename.endsWith(".zip")) { continue; } - // START PWC 1.1 6314481 - if (binding.getName() != null - && binding.getName().startsWith(".") - && ignoreHiddenJarFiles) { + if (binding.getName() != null && binding.getName().startsWith(".") && ignoreHiddenJarFiles) { continue; } - // END PWC 1.1 6314481 File destFile = new File(destDir, binding.getName()); - if (log.isLoggable(Level.FINEST)) { - log.log(Level.FINEST, "Deploy JAR "+filename+" to " + destFile.getAbsolutePath()); + if (log.isLoggable(FINEST)) { + log.log(FINEST, "Deploy JAR " + filename + " to " + destFile.getAbsolutePath()); } Object obj = binding.getObject(); @@ -1066,17 +844,15 @@ private void setRepositories() throws IOException { } } - /** - * Set the appropriate context attribute for our class path. This - * is required only because WaSP depends on it. + * Set the appropriate context attribute for our class path. This is required only because WaSP depends on it. */ private void setClassPath() { - // Validate our current state information if (!(container instanceof Context)) { return; } + ServletContext servletContext = ((Context) container).getServletContext(); if (servletContext == null) { return; @@ -1118,8 +894,7 @@ private void setClassPath() { } else if (repository.startsWith("file:")) { repository = repository.substring(5); } else if (repository.startsWith("jndi:")) { - repository = servletContext.getRealPath( - repository.substring(5)); + repository = servletContext.getRealPath(repository.substring(5)); } else { continue; } @@ -1144,12 +919,10 @@ private void setClassPath() { } - /** * Copy directory. */ private boolean copyDir(DirContext srcDir, File destDir) { - try { NamingEnumeration enumeration = srcDir.list(""); while (enumeration.hasMoreElements()) { @@ -1184,16 +957,12 @@ private boolean copyDir(DirContext srcDir, File destDir) { } return true; - } - /** - * Copy a file to the specified temp directory. This is required only - * because WaSP depends on it. + * Copy a file to the specified temp directory. This is required only because WaSP depends on it. */ private boolean copy(InputStream is, OutputStream os) { - try { byte[] buf = new byte[4096]; while (true) { @@ -1231,11 +1000,10 @@ public void setController(ObjectName controller) { } @Override - public void setOverridablePackages(Set packageNames){ + public void setOverridablePackages(Set packageNames) { overridablePackages = packageNames; } - @Override public void setIgnoreHiddenJarFiles(boolean ignoreHiddenJarFiles) { this.ignoreHiddenJarFiles = ignoreHiddenJarFiles; diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/security/SecurityUtil.java b/appserver/web/web-core/src/main/java/org/apache/catalina/security/SecurityUtil.java index 7a659c36c11..d105e76e0b6 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/security/SecurityUtil.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/security/SecurityUtil.java @@ -386,29 +386,4 @@ public static void remove(Object cachedObject){ objectCache.remove(cachedObject); } - - /** - * Return the SecurityManager only if Security is enabled AND - * package protection mechanism is enabled. - */ - public static boolean isPackageProtectionEnabled(){ - if (!Globals.IS_SECURITY_ENABLED) { - return false; - } - PrivilegedAction action = () -> Security.getProperty("package.definition"); - String value = AccessController.doPrivileged(action); - return value != null && !value.isEmpty(); - } - - - /** - * Return true if a SecurityManager is used and is - * isDoAsRequired is required. - */ - public static boolean executeUnderSubjectDoAs(){ - if (executeUnderSubjectDoAs && Globals.IS_SECURITY_ENABLED) { - return true; - } - return false; - } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/servlets/DefaultServlet.java b/appserver/web/web-core/src/main/java/org/apache/catalina/servlets/DefaultServlet.java index 15630947a2d..f38e8b6df44 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/servlets/DefaultServlet.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/servlets/DefaultServlet.java @@ -21,6 +21,8 @@ package org.apache.catalina.servlets; +import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_COMPONENT; + import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletContext; @@ -30,7 +32,6 @@ import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -57,7 +58,6 @@ import java.util.Locale; import java.util.ResourceBundle; import java.util.StringTokenizer; - import javax.naming.InitialContext; import javax.naming.NameClassPair; import javax.naming.NamingException; @@ -71,7 +71,6 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; - import org.apache.catalina.Globals; import org.apache.catalina.LogFacade; import org.apache.catalina.core.ContextsAdapterUtility; @@ -90,26 +89,27 @@ import org.xml.sax.SAXException; import org.xml.sax.ext.EntityResolver2; -import static org.glassfish.api.naming.SimpleJndiName.JNDI_CTX_JAVA_COMPONENT; - /** - *

The default resource-serving servlet for most web applications, - * used to serve static resources such as HTML pages and images. + *

+ * The default resource-serving servlet for most web applications, used to serve static resources such as HTML pages and + * images. *

*

* This servlet is intended to be mapped to / e.g.: *

+ * *
  *   <servlet-mapping>
  *       <servlet-name>default</servlet-name>
  *       <url-pattern>/</url-pattern>
  *   </servlet-mapping>
  * 
- *

It can be mapped to sub-paths, however in all cases resources are served - * from the web appplication resource root using the full path from the root - * of the web application context. - *
e.g. given a web application structure: - *

+ *

+ * It can be mapped to sub-paths, however in all cases resources are served from the web appplication resource root + * using the full path from the root of the web application context.
+ * e.g. given a web application structure: + *

+ * *
  * /context
  *   /images
@@ -121,6 +121,7 @@
  * 

* ... and a servlet mapping that maps only /static/* to the default servlet: *

+ * *
  *   <servlet-mapping>
  *       <servlet-name>default</servlet-name>
@@ -128,16 +129,18 @@
  *   </servlet-mapping>
  * 
*

- * Then a request to /context/static/images/tomcat.jpg will succeed - * while a request to /context/images/tomcat2.jpg will fail. + * Then a request to /context/static/images/tomcat.jpg will succeed while a request to + * /context/images/tomcat2.jpg will fail. *

+ * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Revision: 1.16 $ $Date: 2007/06/06 16:01:12 $ */ -public class DefaultServlet - extends HttpServlet { +public class DefaultServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; protected static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); @@ -147,119 +150,98 @@ public class DefaultServlet // ----------------------------------------------------- Instance Variables - /** * The debugging detail level for this servlet. */ protected int debug = 0; - /** * The input buffer size to use when serving resources. */ protected int input = 2048; - /** * Should we generate directory listings? */ protected volatile boolean listings = false; - /** * The sorting mechanism for directory listings */ protected SortedBy sortedBy = SortedBy.NAME; - /** * Read only flag. By default, it's set to true. */ protected boolean readOnly = true; - /** * The output buffer size to use when serving resources. */ protected int output = 2048; - /** * Array containing the safe characters set. */ protected static final URLEncoder urlEncoder; - /** * Allow customized directory listing per directory. */ - protected String localXsltFile = null; - + protected String localXsltFile = null; /** * Allow customized directory listing per context. */ protected String contextXsltFile = null; - /** * Allow customized directory listing per instance. */ - protected String globalXsltFile = null; - + protected String globalXsltFile = null; /** * Allow a readme file to be included. */ protected String readmeFile = null; - /** * Proxy directory context. */ protected transient ProxyDirContext resources = null; - /** * Alternate doc bases */ protected transient ArrayList alternateDocBases = null; - /** - * File encoding to be used when reading static files. If none is specified - * the platform default is used. + * File encoding to be used when reading static files. If none is specified the platform default is used. */ protected String fileEncoding = null; - /** * Minimum size for sendfile usage in bytes. */ protected int sendfileSize = 48 * 1024; - /** * Should the Accept-Ranges: bytes header be send with static resources? */ protected boolean useAcceptRanges = true; - /** * Full range marker. */ protected static final ArrayList FULL = new ArrayList<>(); /** - * The maximum number of items allowed in Range header. - * -1 means unbounded. + * The maximum number of items allowed in Range header. -1 means unbounded. */ protected int maxHeaderRangeItems = 10; - // ----------------------------------------------------- Static Initializer - /** * GMT timezone - all HTTP dates are on GMT */ @@ -271,39 +253,27 @@ public class DefaultServlet urlEncoder.addSafeCharacter('*'); urlEncoder.addSafeCharacter('/'); - if (Globals.IS_SECURITY_ENABLED) { - factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setValidating(false); - secureEntityResolver = new SecureEntityResolver(); - } else { - factory = null; - secureEntityResolver = null; - } + factory = null; + secureEntityResolver = null; } - /** * MIME multipart separation string */ protected static final String mimeSeparation = "CATALINA_MIME_BOUNDARY"; - /** * JNDI resources name. */ protected static final String RESOURCES_JNDI_NAME = JNDI_CTX_JAVA_COMPONENT + "Resources"; - /** * Size of file transfer buffer in bytes. */ protected static final int BUFFER_SIZE = 4096; - // --------------------------------------------------------- Public Methods - /** * Finalize this servlet. */ @@ -312,7 +282,6 @@ public void destroy() { // NOOP } - /** * Initialize this servlet. */ @@ -343,13 +312,11 @@ public void init() throws ServletException { } if (sc.getInitParameter("sendfileSize") != null) { - sendfileSize = - Integer.parseInt(sc.getInitParameter("sendfileSize")) * 1024; + sendfileSize = Integer.parseInt(sc.getInitParameter("sendfileSize")) * 1024; } if (sc.getInitParameter("maxHeaderRangeItems") != null) { - maxHeaderRangeItems = - Integer.parseInt(sc.getInitParameter("maxHeaderRangeItems")); + maxHeaderRangeItems = Integer.parseInt(sc.getInitParameter("maxHeaderRangeItems")); } fileEncoding = sc.getInitParameter("fileEncoding"); @@ -372,18 +339,14 @@ public void init() throws ServletException { } if (debug > 0) { - log("DefaultServlet.init: input buffer size=" + input + - ", output buffer size=" + output); + log("DefaultServlet.init: input buffer size=" + input + ", output buffer size=" + output); } // Load the proxy dir context. - resources = (ProxyDirContext) getServletContext() - .getAttribute(Globals.RESOURCES_ATTR); + resources = (ProxyDirContext) getServletContext().getAttribute(Globals.RESOURCES_ATTR); if (resources == null) { try { - resources = - (ProxyDirContext) new InitialContext() - .lookup(RESOURCES_JNDI_NAME); + resources = (ProxyDirContext) new InitialContext().lookup(RESOURCES_JNDI_NAME); } catch (NamingException e) { throw new ServletException("No resources", e); } catch (ClassCastException e) { @@ -397,22 +360,18 @@ public void init() throws ServletException { try { alternateDocBases = getAlternateDocBases(); - } catch(ClassCastException e) { + } catch (ClassCastException e) { // Failed : Not the right type } } - @SuppressWarnings("unchecked") private ArrayList getAlternateDocBases() { - return (ArrayList) - getServletContext().getAttribute( - Globals.ALTERNATE_RESOURCES_ATTR); + return (ArrayList) getServletContext().getAttribute(Globals.ALTERNATE_RESOURCES_ATTR); } - /** * Return if directory listings are enabled */ @@ -420,21 +379,17 @@ public boolean isListings() { return this.listings; } - /** * Enables or disables directory listings for this DefaultServlet. * - * @param listings true if directory listings are to be enabled, false - * otherwise + * @param listings true if directory listings are to be enabled, false otherwise */ public void setListings(boolean listings) { this.listings = listings; } - // ------------------------------------------------------ Protected Methods - /** * Return the relative path associated with this servlet. * @@ -449,11 +404,9 @@ protected String getRelativePath(HttpServletRequest request) { // Are we being processed by a RequestDispatcher.include()? if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) { - String result = (String) request.getAttribute( - RequestDispatcher.INCLUDE_PATH_INFO); + String result = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (result == null) { - result = (String) request.getAttribute( - RequestDispatcher.INCLUDE_SERVLET_PATH); + result = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); } if ((result == null) || (result.equals(""))) { result = "/"; @@ -475,7 +428,6 @@ protected String getRelativePath(HttpServletRequest request) { } - /** * Process a GET request for the specified resource. * @@ -486,16 +438,13 @@ protected String getRelativePath(HttpServletRequest request) { * @exception ServletException if a servlet-specified error occurs */ @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, including the data content serveResource(request, response, true); } - /** * Process a HEAD request for the specified resource. * @@ -506,16 +455,13 @@ protected void doGet(HttpServletRequest request, * @exception ServletException if a servlet-specified error occurs */ @Override - protected void doHead(HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { + protected void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Serve the requested resource, without the data content serveResource(request, response, false); } - /** * Process a POST request for the specified resource. * @@ -526,13 +472,10 @@ protected void doHead(HttpServletRequest request, * @exception ServletException if a servlet-specified error occurs */ @Override - protected void doPost(HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } - /** * Process a POST request for the specified resource. * @@ -543,8 +486,7 @@ protected void doPost(HttpServletRequest request, * @exception ServletException if a servlet-specified error occurs */ @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); @@ -588,7 +530,7 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) } else { resources.bind(path, newResource); } - } catch(NamingException e) { + } catch (NamingException e) { result = false; } @@ -604,21 +546,16 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) } - /** - * Handle a partial PUT. New content specified in request is appended to - * existing content in oldRevisionContent (if present). This code does - * not support simultaneous partial updates to the same resource. + * Handle a partial PUT. New content specified in request is appended to existing content in oldRevisionContent (if + * present). This code does not support simultaneous partial updates to the same resource. */ - protected File executePartialPut(HttpServletRequest req, Range range, - String path) - throws IOException { + protected File executePartialPut(HttpServletRequest req, Range range, String path) throws IOException { // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation - File tempDir = (File) getServletContext().getAttribute( - ServletContext.TEMPDIR); + File tempDir = (File) getServletContext().getAttribute(ServletContext.TEMPDIR); // Convert all '/' characters to '.' in resourcePath String convertedResourcePath = path.replace('/', '.'); File contentFile = new File(tempDir, convertedResourcePath); @@ -637,16 +574,13 @@ protected File executePartialPut(HttpServletRequest req, Range range, // Ignore } - RandomAccessFile randAccessContentFile = - new RandomAccessFile(contentFile, "rw"); + RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw"); try { // Copy data in oldRevisionContent to contentFile if (oldResource != null) { BufferedInputStream bufOldRevStream = null; try { - bufOldRevStream = - new BufferedInputStream(oldResource.streamContent(), - BUFFER_SIZE); + bufOldRevStream = new BufferedInputStream(oldResource.streamContent(), BUFFER_SIZE); int numBytesRead; byte[] copyBuffer = new byte[BUFFER_SIZE]; @@ -668,8 +602,7 @@ protected File executePartialPut(HttpServletRequest req, Range range, byte[] transferBuffer = new byte[BUFFER_SIZE]; BufferedInputStream requestBufInStream = null; try { - requestBufInStream = - new BufferedInputStream(req.getInputStream(), BUFFER_SIZE); + requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE); while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) { randAccessContentFile.write(transferBuffer, 0, numBytesRead); @@ -687,7 +620,6 @@ protected File executePartialPut(HttpServletRequest req, Range range, } - /** * Process a POST request for the specified resource. * @@ -698,8 +630,7 @@ protected File executePartialPut(HttpServletRequest req, Range range, * @exception ServletException if a servlet-specified error occurs */ @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); @@ -733,48 +664,39 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) } - /** - * Check if the conditions specified in the optional If headers are - * satisfied. + * Check if the conditions specified in the optional If headers are satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceAttributes The resource information - * @return boolean true if the resource meets all the specified conditions, - * and false if any of the conditions is not satisfied, in which case - * request processing is stopped + * @return boolean true if the resource meets all the specified conditions, and false if any of the conditions is not + * satisfied, in which case request processing is stopped */ - protected boolean checkIfHeaders(HttpServletRequest request, - HttpServletResponse response, - ResourceAttributes resourceAttributes) - throws IOException { + protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) + throws IOException { - return checkIfMatch(request, response, resourceAttributes) - && checkIfModifiedSince(request, response, resourceAttributes) - && checkIfNoneMatch(request, response, resourceAttributes) - && checkIfUnmodifiedSince(request, response, resourceAttributes); + return checkIfMatch(request, response, resourceAttributes) && checkIfModifiedSince(request, response, resourceAttributes) + && checkIfNoneMatch(request, response, resourceAttributes) && checkIfUnmodifiedSince(request, response, resourceAttributes); } - /** * URL rewriter. * * @param path Path which has to be rewritten */ protected String rewriteUrl(String path) { - return urlEncoder.encode( path ); + return urlEncoder.encode(path); } - /** * Display the size of a file. */ protected void displaySize(StringBuilder buf, int filesize) { int leftside = filesize / 1024; - int rightside = (filesize % 1024) / 103; // makes 1 digit + int rightside = (filesize % 1024) / 103; // makes 1 digit // To avoid 0.0 for non-zero file, we bump to 0.1 if (leftside == 0 && rightside == 0 && filesize != 0) { rightside = 1; @@ -784,7 +706,6 @@ protected void displaySize(StringBuilder buf, int filesize) { } - /** * Serve the specified resource, optionally including the data content. * @@ -795,31 +716,25 @@ protected void displaySize(StringBuilder buf, int filesize) { * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ - protected void serveResource(HttpServletRequest request, - HttpServletResponse response, - boolean content) - throws IOException, ServletException { + protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) + throws IOException, ServletException { // Identify the requested resource path String path = getRelativePath(request); if (debug > 0) { if (content) { - log("DefaultServlet.serveResource: Serving resource '" + - path + "' headers and data"); + log("DefaultServlet.serveResource: Serving resource '" + path + "' headers and data"); } else { - log("DefaultServlet.serveResource: Serving resource '" + - path + "' headers only"); + log("DefaultServlet.serveResource: Serving resource '" + path + "' headers only"); } } CacheEntry cacheEntry = null; ProxyDirContext proxyDirContext = resources; - if (alternateDocBases == null - || alternateDocBases.size() == 0) { + if (alternateDocBases == null || alternateDocBases.size() == 0) { cacheEntry = proxyDirContext.lookupCache(path); } else { - AlternateDocBase match = AlternateDocBase.findMatch( - path, alternateDocBases); + AlternateDocBase match = AlternateDocBase.findMatch(path, alternateDocBases); if (match != null) { cacheEntry = ((ProxyDirContext) ContextsAdapterUtility.unwrap(match.getResources())).lookupCache(path); } else { @@ -831,29 +746,22 @@ protected void serveResource(HttpServletRequest request, if (!cacheEntry.exists) { // Check if we're included so we can return the appropriate // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - /* IASRI 4878272 - if (requestUri == null) { - requestUri = request.getRequestURI(); - } else { - */ + String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI); + /* + * IASRI 4878272 if (requestUri == null) { requestUri = request.getRequestURI(); } else { + */ if (requestUri != null) { /* - * We're included, and the response.sendError() below is going - * to be ignored by the including resource (see SRV.8.3, - * "The Include Method"). - * Therefore, the only way we can let the including resource - * know about the missing resource is by throwing an - * exception - */ + * We're included, and the response.sendError() below is going to be ignored by the including resource (see SRV.8.3, + * "The Include Method"). Therefore, the only way we can let the including resource know about the missing resource is + * by throwing an exception + */ throw new FileNotFoundException(requestUri); } - /* IASRI 4878272 - response.sendError(HttpServletResponse.SC_NOT_FOUND, - requestUri); - */ + /* + * IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); + */ // BEGIN IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND); // END IASRI 4878272 @@ -864,17 +772,11 @@ protected void serveResource(HttpServletRequest request, // ends with "/" or "\", return NOT FOUND if (cacheEntry.context == null) { if (path.endsWith("/") || (path.endsWith("\\"))) { - /* IASRI 4878272 - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } - response.sendError(HttpServletResponse.SC_NOT_FOUND, - requestUri); - */ + /* + * IASRI 4878272 // Check if we're included so we can return the appropriate // missing resource name in the error + * String requestUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI); if (requestUri == null) { + * requestUri = request.getRequestURI(); } response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); + */ // BEGIN IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND); // END IASRI 4878272 @@ -887,10 +789,8 @@ protected void serveResource(HttpServletRequest request, if (cacheEntry.context == null) { // Checking If headers - boolean included = - (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); - if (!included - && !checkIfHeaders(request, response, cacheEntry.attributes)) { + boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); + if (!included && !checkIfHeaders(request, response, cacheEntry.attributes)) { return; } @@ -911,10 +811,9 @@ protected void serveResource(HttpServletRequest request, // Skip directory listings if we have been configured to // suppress them if (!listings) { - /* IASRI 4878272 - response.sendError(HttpServletResponse.SC_NOT_FOUND, - request.getRequestURI()); - */ + /* + * IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); + */ // BEGIN IASRI 4878272 response.sendError(HttpServletResponse.SC_NOT_FOUND); // END IASRI 4878272 @@ -935,8 +834,7 @@ protected void serveResource(HttpServletRequest request, response.setHeader("ETag", cacheEntry.attributes.getETag()); // Last-Modified header - response.setHeader("Last-Modified", - cacheEntry.attributes.getLastModifiedHttp()); + response.setHeader("Last-Modified", cacheEntry.attributes.getLastModifiedHttp()); // Get content length contentLength = cacheEntry.attributes.getContentLength(); @@ -960,9 +858,7 @@ protected void serveResource(HttpServletRequest request, } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file - if ( (contentType == null) - || (contentType.startsWith("text")) - || (contentType.startsWith("xml")) ) { + if ((contentType == null) || (contentType.startsWith("text")) || (contentType.startsWith("xml"))) { writer = response.getWriter(); } else { throw e; @@ -971,23 +867,19 @@ protected void serveResource(HttpServletRequest request, } - if ( (cacheEntry.context != null) - || ( ((ranges == null) || (ranges.isEmpty())) - && (request.getHeader("Range") == null) ) - || (ranges == FULL) ) { + if ((cacheEntry.context != null) || (((ranges == null) || (ranges.isEmpty())) && (request.getHeader("Range") == null)) + || (ranges == FULL)) { // Set the appropriate output headers if (contentType != null) { if (debug > 0) { - log("DefaultServlet.serveFile: contentType='" + - contentType + "'"); + log("DefaultServlet.serveFile: contentType='" + contentType + "'"); } response.setContentType(contentType); } if ((cacheEntry.resource != null) && (contentLength >= 0)) { if (debug > 0) { - log("DefaultServlet.serveFile: contentLength=" + - contentLength); + log("DefaultServlet.serveFile: contentLength=" + contentLength); } if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); @@ -1002,8 +894,7 @@ protected void serveResource(HttpServletRequest request, if (content) { // Serve the directory browser - renderResult = - render(request.getContextPath(), cacheEntry, proxyDirContext); + renderResult = render(request.getContextPath(), cacheEntry, proxyDirContext); } } @@ -1042,10 +933,7 @@ protected void serveResource(HttpServletRequest request, if (ranges.size() == 1) { Range range = ranges.get(0); - response.addHeader("Content-Range", "bytes " - + range.start - + "-" + range.end + "/" - + range.length); + response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { response.setContentLength((int) length); @@ -1056,8 +944,7 @@ protected void serveResource(HttpServletRequest request, if (contentType != null) { if (debug > 0) { - log("DefaultServlet.serveFile: contentType='" + - contentType + "'"); + log("DefaultServlet.serveFile: contentType='" + contentType + "'"); } response.setContentType(contentType); } @@ -1079,8 +966,7 @@ protected void serveResource(HttpServletRequest request, } else { - response.setContentType("multipart/byteranges; boundary=" - + mimeSeparation); + response.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (content) { try { @@ -1089,11 +975,9 @@ protected void serveResource(HttpServletRequest request, // Silent catch } if (ostream != null) { - copy(cacheEntry, ostream, ranges.iterator(), - contentType); + copy(cacheEntry, ostream, ranges.iterator(), contentType); } else { - copy(cacheEntry, writer, ranges.iterator(), - contentType); + copy(cacheEntry, writer, ranges.iterator(), contentType); } } @@ -1103,7 +987,6 @@ protected void serveResource(HttpServletRequest request, } - /** * Parse the content-range header. * @@ -1111,9 +994,7 @@ protected void serveResource(HttpServletRequest request, * @param response The servlet response we are creating * @return Range */ - protected Range parseContentRange(HttpServletRequest request, - HttpServletResponse response) - throws IOException { + protected Range parseContentRange(HttpServletRequest request, HttpServletResponse response) throws IOException { // Retrieving the content-range header (if any is specified String rangeHeader = request.getHeader("Content-Range"); @@ -1147,10 +1028,8 @@ protected Range parseContentRange(HttpServletRequest request, try { range.start = Long.parseLong(rangeHeader.substring(0, dashPos)); - range.end = - Long.parseLong(rangeHeader.substring(dashPos + 1, slashPos)); - range.length = Long.parseLong - (rangeHeader.substring(slashPos + 1, rangeHeader.length())); + range.end = Long.parseLong(rangeHeader.substring(dashPos + 1, slashPos)); + range.length = Long.parseLong(rangeHeader.substring(slashPos + 1, rangeHeader.length())); } catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; @@ -1165,7 +1044,6 @@ protected Range parseContentRange(HttpServletRequest request, } - /** * Parse the range header. * @@ -1173,9 +1051,8 @@ protected Range parseContentRange(HttpServletRequest request, * @param response The servlet response we are creating * @return Vector of ranges */ - protected ArrayList parseRange(HttpServletRequest request, - HttpServletResponse response, - ResourceAttributes resourceAttributes) throws IOException { + protected ArrayList parseRange(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) + throws IOException { // Checking If-Range String headerValue = request.getHeader("If-Range"); @@ -1229,8 +1106,7 @@ protected ArrayList parseRange(HttpServletRequest request, // of adding new ones). if (!rangeHeader.startsWith("bytes")) { response.addHeader("Content-Range", "bytes */" + fileLength); - response.sendError - (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); + response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } @@ -1252,8 +1128,7 @@ protected ArrayList parseRange(HttpServletRequest request, if (dashPos == -1) { response.addHeader("Content-Range", "bytes */" + fileLength); - response.sendError - (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); + response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } @@ -1264,32 +1139,23 @@ protected ArrayList parseRange(HttpServletRequest request, currentRange.start = fileLength + offset; currentRange.end = fileLength - 1; } catch (NumberFormatException e) { - response.addHeader("Content-Range", - "bytes */" + fileLength); - response.sendError - (HttpServletResponse - .SC_REQUESTED_RANGE_NOT_SATISFIABLE); + response.addHeader("Content-Range", "bytes */" + fileLength); + response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } else { try { - currentRange.start = Long.parseLong - (rangeDefinition.substring(0, dashPos)); + currentRange.start = Long.parseLong(rangeDefinition.substring(0, dashPos)); if (dashPos < rangeDefinition.length() - 1) { - currentRange.end = Long.parseLong - (rangeDefinition.substring - (dashPos + 1, rangeDefinition.length())); + currentRange.end = Long.parseLong(rangeDefinition.substring(dashPos + 1, rangeDefinition.length())); } else { currentRange.end = fileLength - 1; } } catch (NumberFormatException e) { - response.addHeader("Content-Range", - "bytes */" + fileLength); - response.sendError - (HttpServletResponse - .SC_REQUESTED_RANGE_NOT_SATISFIABLE); + response.addHeader("Content-Range", "bytes */" + fileLength); + response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } @@ -1297,8 +1163,7 @@ protected ArrayList parseRange(HttpServletRequest request, if (!currentRange.validate()) { response.addHeader("Content-Range", "bytes */" + fileLength); - response.sendError - (HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); + response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } @@ -1308,18 +1173,14 @@ protected ArrayList parseRange(HttpServletRequest request, return result; } - - /** - * Decide which way to render. HTML or XML. + * Decide which way to render. HTML or XML. */ - protected InputStream render(String contextPath, CacheEntry cacheEntry) - throws IOException, ServletException { + protected InputStream render(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { return render(contextPath, cacheEntry, resources); } - private InputStream render(String contextPath, CacheEntry cacheEntry, - ProxyDirContext proxyDirContext) + private InputStream render(String contextPath, CacheEntry cacheEntry, ProxyDirContext proxyDirContext) throws IOException, ServletException { Source xsltSource = findXsltInputStream(cacheEntry.context); @@ -1333,23 +1194,15 @@ private InputStream render(String contextPath, CacheEntry cacheEntry, } /** - * Return an InputStream to an HTML representation of the contents - * of this directory. + * Return an InputStream to an HTML representation of the contents of this directory. * - * @param contextPath Context path to which our internal paths are - * relative + * @param contextPath Context path to which our internal paths are relative */ - protected InputStream renderXml(String contextPath, - CacheEntry cacheEntry, - Source xsltSource) - throws IOException, ServletException { + protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, Source xsltSource) throws IOException, ServletException { return renderXml(contextPath, cacheEntry, xsltSource, resources); } - private InputStream renderXml(String contextPath, - CacheEntry cacheEntry, - Source xsltSource, - ProxyDirContext proxyDirContext) + private InputStream renderXml(String contextPath, CacheEntry cacheEntry, Source xsltSource, ProxyDirContext proxyDirContext) throws IOException, ServletException { StringBuilder sb = new StringBuilder(); @@ -1370,35 +1223,29 @@ private InputStream renderXml(String contextPath, try { // Render the directory entries within this directory - Enumeration enumeration = - proxyDirContext.list(cacheEntry.name); + Enumeration enumeration = proxyDirContext.list(cacheEntry.name); if (sortedBy.equals(SortedBy.LAST_MODIFIED)) { - ArrayList list = - Collections.list(enumeration); - Comparator c = new LastModifiedComparator( - proxyDirContext, cacheEntry.name); + ArrayList list = Collections.list(enumeration); + Comparator c = new LastModifiedComparator(proxyDirContext, cacheEntry.name); Collections.sort(list, c); enumeration = Collections.enumeration(list); } else if (sortedBy.equals(SortedBy.SIZE)) { - ArrayList list = - Collections.list(enumeration); - Comparator c = new SizeComparator( - proxyDirContext, cacheEntry.name); + ArrayList list = Collections.list(enumeration); + Comparator c = new SizeComparator(proxyDirContext, cacheEntry.name); Collections.sort(list, c); enumeration = Collections.enumeration(list); } // rewriteUrl(contextPath) is expensive. cache result for later reuse - String rewrittenContextPath = rewriteUrl(contextPath); + String rewrittenContextPath = rewriteUrl(contextPath); while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); - String trimmed = resourceName/*.substring(trim)*/; - if (trimmed.equalsIgnoreCase("WEB-INF") || - trimmed.equalsIgnoreCase("META-INF") || - trimmed.equalsIgnoreCase(localXsltFile)) { + String trimmed = resourceName/* .substring(trim) */; + if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") + || trimmed.equalsIgnoreCase(localXsltFile)) { continue; } @@ -1406,29 +1253,19 @@ private InputStream renderXml(String contextPath, continue; } - CacheEntry childCacheEntry = - proxyDirContext.lookupCache(cacheEntry.name + resourceName); + CacheEntry childCacheEntry = proxyDirContext.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } sb.append(""); sb.append(HtmlEntityEncoder.encodeXSS(trimmed)); @@ -1448,33 +1285,21 @@ private InputStream renderXml(String contextPath, String readme = getReadme(cacheEntry.context); - if (readme!=null) { + if (readme != null) { sb.append(""); } - sb.append(""); // Prevent possible memory leak. Ensure Transformer and // TransformerFactory are not loaded from the web application. - ClassLoader original; - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedGetTccl pa = new PrivilegedGetTccl(); - original = AccessController.doPrivileged(pa); - } else { - original = Thread.currentThread().getContextClassLoader(); - } + ClassLoader original = Thread.currentThread().getContextClassLoader(); + try { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedSetTccl pa = - new PrivilegedSetTccl(DefaultServlet.class.getClassLoader()); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader( - DefaultServlet.class.getClassLoader()); - } + Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader()); + TransformerFactory tFactory = TransformerFactory.newInstance(); Source xmlSource = new StreamSource(new StringReader(sb.toString())); Transformer transformer = tFactory.newTransformer(xsltSource); @@ -1489,40 +1314,27 @@ private InputStream renderXml(String contextPath, log("directory transform failure: " + e.getMessage()); return renderHtml(contextPath, cacheEntry); } finally { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedSetTccl pa = new PrivilegedSetTccl(original); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(original); - } + Thread.currentThread().setContextClassLoader(original); } } /** - * Return an InputStream to an HTML representation of the contents - * of this directory. + * Return an InputStream to an HTML representation of the contents of this directory. * - * @param contextPath Context path to which our internal paths are - * relative + * @param contextPath Context path to which our internal paths are relative */ - protected InputStream renderHtml (String contextPath, CacheEntry cacheEntry) - throws IOException, ServletException { + protected InputStream renderHtml(String contextPath, CacheEntry cacheEntry) throws IOException, ServletException { return renderHtml(contextPath, cacheEntry, resources); } - private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, - ProxyDirContext proxyDirContext) + private InputStream renderHtml(String contextPath, CacheEntry cacheEntry, ProxyDirContext proxyDirContext) throws IOException, ServletException { String name = cacheEntry.name; /* - // Number of characters to trim from the beginnings of filenames - int trim = name.length(); - if (!name.endsWith("/")) - trim += 1; - if (name.equals("/")) - trim = 1; - */ + * // Number of characters to trim from the beginnings of filenames int trim = name.length(); if (!name.endsWith("/")) + * trim += 1; if (name.equals("/")) trim = 1; + */ // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); @@ -1538,7 +1350,7 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, StringBuilder sb = new StringBuilder(); // rewriteUrl(contextPath) is expensive. cache result for later reuse - String rewrittenContextPath = rewriteUrl(contextPath); + String rewrittenContextPath = rewriteUrl(contextPath); String dirTitle = MessageFormat.format(rb.getString(LogFacade.DIR_TITLE_INFO), name); @@ -1560,8 +1372,7 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, String parentDirectory = name; if (parentDirectory.endsWith("/")) { - parentDirectory = - parentDirectory.substring(0, parentDirectory.length() - 1); + parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { @@ -1586,8 +1397,7 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, sb.append(""); sb.append("
"); - sb.append("\r\n"); + sb.append("
\r\n"); // Render the column headings sb.append("\r\n"); @@ -1605,20 +1415,15 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, try { // Render the directory entries within this directory - Enumeration enumeration = - proxyDirContext.list(cacheEntry.name); + Enumeration enumeration = proxyDirContext.list(cacheEntry.name); if (sortedBy.equals(SortedBy.LAST_MODIFIED)) { - ArrayList list = - Collections.list(enumeration); - Comparator c = new LastModifiedComparator( - proxyDirContext, cacheEntry.name); + ArrayList list = Collections.list(enumeration); + Comparator c = new LastModifiedComparator(proxyDirContext, cacheEntry.name); Collections.sort(list, c); enumeration = Collections.enumeration(list); } else if (sortedBy.equals(SortedBy.SIZE)) { - ArrayList list = - Collections.list(enumeration); - Comparator c = new SizeComparator( - proxyDirContext, cacheEntry.name); + ArrayList list = Collections.list(enumeration); + Comparator c = new SizeComparator(proxyDirContext, cacheEntry.name); Collections.sort(list, c); enumeration = Collections.enumeration(list); } @@ -1628,14 +1433,12 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, NameClassPair ncPair = enumeration.nextElement(); String resourceName = ncPair.getName(); - String trimmed = resourceName/*.substring(trim)*/; - if (trimmed.equalsIgnoreCase("WEB-INF") || - trimmed.equalsIgnoreCase("META-INF")) { + String trimmed = resourceName/* .substring(trim) */; + if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) { continue; } - CacheEntry childCacheEntry = - proxyDirContext.lookupCache(cacheEntry.name + resourceName); + CacheEntry childCacheEntry = proxyDirContext.lookupCache(cacheEntry.name + resourceName); if (!childCacheEntry.exists) { continue; } @@ -1688,7 +1491,7 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, sb.append("
"); String readme = getReadme(cacheEntry.context); - if (readme!=null) { + if (readme != null) { sb.append(readme); sb.append("
"); } @@ -1707,7 +1510,6 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, } - /** * Render the specified file size (in bytes). * @@ -1716,7 +1518,7 @@ private InputStream renderHtml (String contextPath, CacheEntry cacheEntry, protected String renderSize(long size) { long leftSide = size / 1024; - long rightSide = (size % 1024) / 103; // Makes 1 digit + long rightSide = (size % 1024) / 103; // Makes 1 digit if ((leftSide == 0) && (rightSide == 0) && (size > 0)) { rightSide = 1; } @@ -1725,79 +1527,64 @@ protected String renderSize(long size) { } - /** * Get the readme file as a string. */ - protected String getReadme(DirContext directory) - throws IOException, ServletException { + protected String getReadme(DirContext directory) throws IOException, ServletException { - if (readmeFile!=null) { + if (readmeFile != null) { try { Object obj = directory.lookup(readmeFile); - if (obj!=null && obj instanceof Resource) { + if (obj != null && obj instanceof Resource) { StringWriter buffer = new StringWriter(); - InputStream is = ((Resource)obj).streamContent(); - copyRange(new InputStreamReader(is), - new PrintWriter(buffer)); + InputStream is = ((Resource) obj).streamContent(); + copyRange(new InputStreamReader(is), new PrintWriter(buffer)); return buffer.toString(); - } - } catch(Throwable e) { - /* Should only be IOException or NamingException - * can be ignored - */ - if (debug > 10) { + } + } catch (Throwable e) { + /* + * Should only be IOException or NamingException can be ignored + */ + if (debug > 10) { log("readme '" + readmeFile + "' not found", e); } - } + } } return null; } - /** * Return a Source for the xsl template (if possible) */ - protected Source findXsltInputStream(DirContext directory) - throws IOException, ServletException { - - if (localXsltFile!=null) { + protected Source findXsltInputStream(DirContext directory) throws IOException, ServletException { + if (localXsltFile != null) { try { Object obj = directory.lookup(localXsltFile); - if (obj!=null && obj instanceof Resource) { - InputStream is = ((Resource)obj).streamContent(); + if (obj != null && obj instanceof Resource) { + InputStream is = ((Resource) obj).streamContent(); if (is != null) { - if (Globals.IS_SECURITY_ENABLED) { - return secureXslt(is); - } else { - return new StreamSource(is); - } + return new StreamSource(is); } } - } catch(Throwable e) { - /* Should only be IOException or NamingException - * can be ignored - */ + } catch (Throwable e) { + /* + * Should only be IOException or NamingException can be ignored + */ if (debug > 10) { log("localXsltFile '" + localXsltFile + "' not found", e); } return null; - } + } } if (contextXsltFile != null) { - InputStream is = - getServletContext().getResourceAsStream(contextXsltFile); + InputStream is = getServletContext().getResourceAsStream(contextXsltFile); if (is != null) { - if (Globals.IS_SECURITY_ENABLED) { - return secureXslt(is); - } else { - return new StreamSource(is); - } + return new StreamSource(is); } if (debug > 10) { @@ -1805,17 +1592,17 @@ protected Source findXsltInputStream(DirContext directory) } } - /* Open and read in file in one fell swoop to reduce chance - * chance of leaving handle open. + /* + * Open and read in file in one fell swoop to reduce chance chance of leaving handle open. */ - if (globalXsltFile!=null) { + if (globalXsltFile != null) { File f = validateGlobalXsltFile(); - if (f != null){ + if (f != null) { FileInputStream fis = null; try { fis = new FileInputStream(f); long len = f.length(); - byte b[] = new byte[(int)len]; /* danger! */ + byte b[] = new byte[(int) len]; /* danger! */ if (len != fis.read(b)) { throw new IOException(MessageFormat.format(rb.getString(LogFacade.READ_FILE_EXCEPTION), f.getAbsolutePath())); } @@ -1859,7 +1646,6 @@ private File validateGlobalXsltFile() { return result; } - private File validateGlobalXsltFile(File base) { File candidate = new File(globalXsltFile); if (!candidate.isAbsolute()) { @@ -1888,7 +1674,6 @@ private File validateGlobalXsltFile(File base) { return candidate; } - private Source secureXslt(InputStream is) { // Need to filter out any external entities Source result = null; @@ -1923,24 +1708,17 @@ private Source secureXslt(InputStream is) { return result; } - // -------------------------------------------------------- protected Methods - /** * Check if sendfile can be used. */ - protected boolean checkSendfile(HttpServletRequest request, - HttpServletResponse response, - CacheEntry entry, - long length, Range range) { - if ((sendfileSize > 0) - && (entry.resource != null) - && ((length > sendfileSize) || (entry.resource.getContent() == null)) - && (entry.attributes.getCanonicalPath() != null) - && (Boolean.TRUE.equals(request.getAttribute("org.apache.tomcat.sendfile.support"))) - && (request.getClass().getName().equals("org.apache.catalina.connector.RequestFacade")) - && (response.getClass().getName().equals("org.apache.catalina.connector.ResponseFacade"))) { + protected boolean checkSendfile(HttpServletRequest request, HttpServletResponse response, CacheEntry entry, long length, Range range) { + if ((sendfileSize > 0) && (entry.resource != null) && ((length > sendfileSize) || (entry.resource.getContent() == null)) + && (entry.attributes.getCanonicalPath() != null) + && (Boolean.TRUE.equals(request.getAttribute("org.apache.tomcat.sendfile.support"))) + && (request.getClass().getName().equals("org.apache.catalina.connector.RequestFacade")) + && (response.getClass().getName().equals("org.apache.catalina.connector.ResponseFacade"))) { request.setAttribute("org.apache.tomcat.sendfile.filename", entry.attributes.getCanonicalPath()); if (range == null) { request.setAttribute("org.apache.tomcat.sendfile.start", Long.valueOf(0L)); @@ -1956,29 +1734,24 @@ protected boolean checkSendfile(HttpServletRequest request, } } - /** * Check if the if-match condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceAttributes File object - * @return boolean true if the resource meets the specified condition, - * and false if the condition is not satisfied, in which case request - * processing is stopped + * @return boolean true if the resource meets the specified condition, and false if the condition is not satisfied, in + * which case request processing is stopped */ - protected boolean checkIfMatch(HttpServletRequest request, - HttpServletResponse response, - ResourceAttributes resourceAttributes) - throws IOException { + protected boolean checkIfMatch(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) + throws IOException { String eTag = resourceAttributes.getETag(); String headerValue = request.getHeader("If-Match"); if (headerValue != null) { if (headerValue.indexOf('*') == -1) { - StringTokenizer commaTokenizer = new StringTokenizer - (headerValue, ","); + StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); boolean conditionSatisfied = false; while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { @@ -1991,8 +1764,7 @@ protected boolean checkIfMatch(HttpServletRequest request, // If none of the given ETags match, 412 Precodition failed is // sent back if (!conditionSatisfied) { - response.sendError - (HttpServletResponse.SC_PRECONDITION_FAILED); + response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } @@ -2002,21 +1774,17 @@ protected boolean checkIfMatch(HttpServletRequest request, } - /** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceAttributes File object - * @return boolean true if the resource meets the specified condition, - * and false if the condition is not satisfied, in which case request - * processing is stopped - */ - protected boolean checkIfModifiedSince(HttpServletRequest request, - HttpServletResponse response, - ResourceAttributes resourceAttributes) - throws IOException { + * @return boolean true if the resource meets the specified condition, and false if the condition is not satisfied, in + * which case request processing is stopped + */ + protected boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) + throws IOException { try { long headerValue = request.getDateHeader("If-Modified-Since"); long lastModified = resourceAttributes.getLastModified(); @@ -2024,8 +1792,7 @@ protected boolean checkIfModifiedSince(HttpServletRequest request, // If an If-None-Match header has been specified, // If-Modified-Since is ignored. - if ((request.getHeader("If-None-Match") == null) - && (lastModified < headerValue + 1000)) { + if ((request.getHeader("If-None-Match") == null) && (lastModified < headerValue + 1000)) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); @@ -2033,28 +1800,24 @@ protected boolean checkIfModifiedSince(HttpServletRequest request, return false; } } - } catch(IllegalArgumentException illegalArgument) { + } catch (IllegalArgumentException illegalArgument) { return true; } return true; } - /** * Check if the if-none-match condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceAttributes File object - * @return boolean true if the resource meets the specified condition, - * and false if the condition is not satisfied, in which case request - * processing is stopped + * @return boolean true if the resource meets the specified condition, and false if the condition is not satisfied, in + * which case request processing is stopped */ - protected boolean checkIfNoneMatch(HttpServletRequest request, - HttpServletResponse response, - ResourceAttributes resourceAttributes) - throws IOException { + protected boolean checkIfNoneMatch(HttpServletRequest request, HttpServletResponse response, ResourceAttributes resourceAttributes) + throws IOException { String eTag = resourceAttributes.getETag(); String headerValue = request.getHeader("If-None-Match"); @@ -2064,8 +1827,7 @@ protected boolean checkIfNoneMatch(HttpServletRequest request, if (!headerValue.equals("*")) { - StringTokenizer commaTokenizer = - new StringTokenizer(headerValue, ","); + StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); @@ -2084,14 +1846,12 @@ protected boolean checkIfNoneMatch(HttpServletRequest request, // 304 Not Modified. // For every other method, 412 Precondition Failed is sent // back. - if ( ("GET".equals(request.getMethod())) - || ("HEAD".equals(request.getMethod())) ) { + if (("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod()))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); return false; } else { - response.sendError - (HttpServletResponse.SC_PRECONDITION_FAILED); + response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } @@ -2100,44 +1860,38 @@ protected boolean checkIfNoneMatch(HttpServletRequest request, } - /** * Check if the if-unmodified-since condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceAttributes File object - * @return boolean true if the resource meets the specified condition, - * and false if the condition is not satisfied, in which case request - * processing is stopped - */ - protected boolean checkIfUnmodifiedSince(HttpServletRequest request, - HttpServletResponse response, - ResourceAttributes resourceAttributes) - throws IOException { + * @return boolean true if the resource meets the specified condition, and false if the condition is not satisfied, in + * which case request processing is stopped + */ + protected boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response, + ResourceAttributes resourceAttributes) throws IOException { try { long lastModified = resourceAttributes.getLastModified(); long headerValue = request.getDateHeader("If-Unmodified-Since"); if (headerValue != -1) { - if ( lastModified >= (headerValue + 1000)) { + if (lastModified >= (headerValue + 1000)) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } - } catch(IllegalArgumentException illegalArgument) { + } catch (IllegalArgumentException illegalArgument) { return true; } return true; } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param cacheEntry The CacheEntry object * @param is The InputStream @@ -2145,9 +1899,7 @@ protected boolean checkIfUnmodifiedSince(HttpServletRequest request, * * @exception IOException if an input/output error occurs */ - protected void copy(CacheEntry cacheEntry, InputStream is, - ServletOutputStream ostream) - throws IOException { + protected void copy(CacheEntry cacheEntry, InputStream is, ServletOutputStream ostream) throws IOException { IOException exception = null; InputStream resourceInputStream = null; @@ -2165,8 +1917,7 @@ protected void copy(CacheEntry cacheEntry, InputStream is, resourceInputStream = is; } - InputStream istream = new BufferedInputStream - (resourceInputStream, input); + InputStream istream = new BufferedInputStream(resourceInputStream, input); try { // Copy the input stream to the output stream @@ -2183,11 +1934,9 @@ protected void copy(CacheEntry cacheEntry, InputStream is, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param cacheEntry The cache entry * @param is The InputStream @@ -2195,9 +1944,7 @@ protected void copy(CacheEntry cacheEntry, InputStream is, * * @exception IOException if an input/output error occurs */ - protected void copy(CacheEntry cacheEntry, InputStream is, - PrintWriter writer) - throws IOException { + protected void copy(CacheEntry cacheEntry, InputStream is, PrintWriter writer) throws IOException { IOException exception = null; @@ -2212,8 +1959,7 @@ protected void copy(CacheEntry cacheEntry, InputStream is, if (fileEncoding == null) { reader = new InputStreamReader(resourceInputStream); } else { - reader = new InputStreamReader(resourceInputStream, - fileEncoding); + reader = new InputStreamReader(resourceInputStream, fileEncoding); } // Copy the input stream to the output stream @@ -2229,26 +1975,21 @@ protected void copy(CacheEntry cacheEntry, InputStream is, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param cacheEntry The CacheEntry object * @param ostream The output stream to write to * @param range Range the client wanted to retrieve * @exception IOException if an input/output error occurs */ - protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, - Range range) - throws IOException { + protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, Range range) throws IOException { IOException exception = null; InputStream resourceInputStream = cacheEntry.resource.streamContent(); - InputStream istream = - new BufferedInputStream(resourceInputStream, input); + InputStream istream = new BufferedInputStream(resourceInputStream, input); try { exception = copyRange(istream, ostream, range.start, range.end); } finally { @@ -2263,20 +2004,16 @@ protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param cacheEntry The CacheEntry object * @param writer The writer to write to * @param range Range the client wanted to retrieve * @exception IOException if an input/output error occurs */ - protected void copy(CacheEntry cacheEntry, PrintWriter writer, - Range range) - throws IOException { + protected void copy(CacheEntry cacheEntry, PrintWriter writer, Range range) throws IOException { IOException exception = null; @@ -2286,8 +2023,7 @@ protected void copy(CacheEntry cacheEntry, PrintWriter writer, if (fileEncoding == null) { reader = new InputStreamReader(resourceInputStream); } else { - reader = new InputStreamReader(resourceInputStream, - fileEncoding); + reader = new InputStreamReader(resourceInputStream, fileEncoding); } exception = copyRange(reader, writer, range.start, range.end); @@ -2302,11 +2038,9 @@ protected void copy(CacheEntry cacheEntry, PrintWriter writer, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param cacheEntry The CacheEntry object * @param ostream The output stream to write to @@ -2314,19 +2048,16 @@ protected void copy(CacheEntry cacheEntry, PrintWriter writer, * @param contentType Content type of the resource * @exception IOException if an input/output error occurs */ - protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, - Iterator ranges, String contentType) - throws IOException { + protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, Iterator ranges, String contentType) throws IOException { IOException exception = null; - while ( (exception == null) && (ranges.hasNext()) ) { + while ((exception == null) && (ranges.hasNext())) { InputStream resourceInputStream = cacheEntry.resource.streamContent(); InputStream istream = null; try { - istream = - new BufferedInputStream(resourceInputStream, input); + istream = new BufferedInputStream(resourceInputStream, input); Range currentRange = ranges.next(); @@ -2336,14 +2067,11 @@ protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, if (contentType != null) { ostream.println("Content-Type: " + contentType); } - ostream.println("Content-Range: bytes " + currentRange.start - + "-" + currentRange.end + "/" - + currentRange.length); + ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length); ostream.println(); // Printing content - exception = copyRange(istream, ostream, currentRange.start, - currentRange.end); + exception = copyRange(istream, ostream, currentRange.start, currentRange.end); } finally { if (istream != null) { @@ -2362,11 +2090,9 @@ protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param cacheEntry The CacheEntry object * @param writer The writer to write to @@ -2374,13 +2100,11 @@ protected void copy(CacheEntry cacheEntry, ServletOutputStream ostream, * @param contentType Content type of the resource * @exception IOException if an input/output error occurs */ - protected void copy(CacheEntry cacheEntry, PrintWriter writer, - Iterator ranges, String contentType) - throws IOException { + protected void copy(CacheEntry cacheEntry, PrintWriter writer, Iterator ranges, String contentType) throws IOException { IOException exception = null; - while ( (exception == null) && (ranges.hasNext()) ) { + while ((exception == null) && (ranges.hasNext())) { InputStream resourceInputStream = cacheEntry.resource.streamContent(); @@ -2388,8 +2112,7 @@ protected void copy(CacheEntry cacheEntry, PrintWriter writer, if (fileEncoding == null) { reader = new InputStreamReader(resourceInputStream); } else { - reader = new InputStreamReader(resourceInputStream, - fileEncoding); + reader = new InputStreamReader(resourceInputStream, fileEncoding); } Range currentRange = ranges.next(); @@ -2400,14 +2123,11 @@ protected void copy(CacheEntry cacheEntry, PrintWriter writer, if (contentType != null) { writer.println("Content-Type: " + contentType); } - writer.println("Content-Range: bytes " + currentRange.start - + "-" + currentRange.end + "/" - + currentRange.length); + writer.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length); writer.println(); // Printing content - exception = copyRange(reader, writer, currentRange.start, - currentRange.end); + exception = copyRange(reader, writer, currentRange.start, currentRange.end); reader.close(); } @@ -2422,18 +2142,15 @@ protected void copy(CacheEntry cacheEntry, PrintWriter writer, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param istream The input stream to read from * @param ostream The output stream to write to * @return Exception which occurred during processing */ - protected IOException copyRange(InputStream istream, - ServletOutputStream ostream) { + protected IOException copyRange(InputStream istream, ServletOutputStream ostream) { // Copy the input stream to the output stream IOException exception = null; byte buffer[] = new byte[input]; @@ -2454,11 +2171,9 @@ protected IOException copyRange(InputStream istream, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param reader The reader to read from * @param writer The writer to write to @@ -2485,11 +2200,9 @@ protected IOException copyRange(Reader reader, PrintWriter writer) { } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param istream The input stream to read from * @param ostream The output stream to write to @@ -2497,9 +2210,7 @@ protected IOException copyRange(Reader reader, PrintWriter writer) { * @param end End of the range which will be copied * @return Exception which occurred during processing */ - protected IOException copyRange(InputStream istream, - ServletOutputStream ostream, - long start, long end) { + protected IOException copyRange(InputStream istream, ServletOutputStream ostream, long start, long end) { if (debug > 10) { log("Serving bytes:" + start + "-" + end); } @@ -2512,8 +2223,7 @@ protected IOException copyRange(InputStream istream, } if (skipped < start) { String msg = MessageFormat.format(rb.getString(LogFacade.SKIP_BYTES_EXCEPTION), - new Object[] {Long.valueOf(skipped), - Long.valueOf(start)}); + new Object[] { Long.valueOf(skipped), Long.valueOf(start) }); return new IOException(msg); } @@ -2522,7 +2232,7 @@ protected IOException copyRange(InputStream istream, byte buffer[] = new byte[input]; int len = buffer.length; - while ( (bytesToRead > 0) && (len >= buffer.length)) { + while ((bytesToRead > 0) && (len >= buffer.length)) { try { len = istream.read(buffer); if (bytesToRead >= len) { @@ -2545,11 +2255,9 @@ protected IOException copyRange(InputStream istream, } - /** - * Copy the contents of the specified input stream to the specified - * output stream, and ensure that both streams are closed before returning - * (even in the face of an exception). + * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are + * closed before returning (even in the face of an exception). * * @param reader The reader to read from * @param writer The writer to write to @@ -2557,8 +2265,7 @@ protected IOException copyRange(InputStream istream, * @param end End of the range which will be copied * @return Exception which occurred during processing */ - protected IOException copyRange(Reader reader, PrintWriter writer, - long start, long end) { + protected IOException copyRange(Reader reader, PrintWriter writer, long start, long end) { long skipped = 0; try { @@ -2568,8 +2275,7 @@ protected IOException copyRange(Reader reader, PrintWriter writer, } if (skipped < start) { String msg = MessageFormat.format(rb.getString(LogFacade.SKIP_BYTES_EXCEPTION), - new Object[] {Long.valueOf(skipped), - Long.valueOf(start)}); + new Object[] { Long.valueOf(skipped), Long.valueOf(start) }); return new IOException(msg); } @@ -2578,7 +2284,7 @@ protected IOException copyRange(Reader reader, PrintWriter writer, char buffer[] = new char[input]; int len = buffer.length; - while ( (bytesToRead > 0) && (len >= buffer.length)) { + while ((bytesToRead > 0) && (len >= buffer.length)) { try { len = reader.read(buffer); if (bytesToRead >= len) { @@ -2601,7 +2307,6 @@ protected IOException copyRange(Reader reader, PrintWriter writer, } - // ------------------------------------------------------ Inner Classes protected static class Range { @@ -2617,8 +2322,7 @@ public boolean validate() { if (end >= length) { end = length - 1; } - return ( (start >= 0) && (end >= 0) && (start <= end) - && (length > 0) ); + return ((start >= 0) && (end >= 0) && (start <= end) && (length > 0)); } } @@ -2626,26 +2330,20 @@ public boolean validate() { * Enumeration of sorting mechanisms for directory listings. */ private enum SortedBy { - NAME, - LAST_MODIFIED, - SIZE + NAME, LAST_MODIFIED, SIZE } /** - * Comparator which sorts directory listings by their creation - * or lastModified date + * Comparator which sorts directory listings by their creation or lastModified date * - * This comparator class cannot be used with TreeSet and TreeMap - * as it is not Serializable. + * This comparator class cannot be used with TreeSet and TreeMap as it is not Serializable. */ - private static class LastModifiedComparator - implements Comparator { + private static class LastModifiedComparator implements Comparator { private final ProxyDirContext resources; private final String dirName; - public LastModifiedComparator(ProxyDirContext resources, - String dirName) { + public LastModifiedComparator(ProxyDirContext resources, String dirName) { this.resources = resources; this.dirName = dirName; } @@ -2653,11 +2351,9 @@ public LastModifiedComparator(ProxyDirContext resources, @Override public int compare(NameClassPair p1, NameClassPair p2) { - CacheEntry ce1 = resources.lookupCache( - dirName + p1.getName()); + CacheEntry ce1 = resources.lookupCache(dirName + p1.getName()); Date date1 = ce1.attributes.getCreationOrLastModifiedDate(); - CacheEntry ce2 = resources.lookupCache( - dirName + p2.getName()); + CacheEntry ce2 = resources.lookupCache(dirName + p2.getName()); Date date2 = ce2.attributes.getCreationOrLastModifiedDate(); if (date1.before(date2)) { return -1; @@ -2672,17 +2368,14 @@ public int compare(NameClassPair p1, NameClassPair p2) { /** * Comparator which sorts directory listings by their file size * - * This comparator class cannot be used with TreeSet and TreeMap - * as it is not Serializable. + * This comparator class cannot be used with TreeSet and TreeMap as it is not Serializable. */ - private static class SizeComparator - implements Comparator { + private static class SizeComparator implements Comparator { private final ProxyDirContext resources; private final String dirName; - public SizeComparator(ProxyDirContext resources, - String dirName) { + public SizeComparator(ProxyDirContext resources, String dirName) { this.resources = resources; this.dirName = dirName; } @@ -2690,11 +2383,9 @@ public SizeComparator(ProxyDirContext resources, @Override public int compare(NameClassPair p1, NameClassPair p2) { - CacheEntry ce1 = resources.lookupCache( - dirName + p1.getName()); + CacheEntry ce1 = resources.lookupCache(dirName + p1.getName()); long size1 = ce1.attributes.getContentLength(); - CacheEntry ce2 = resources.lookupCache( - dirName + p2.getName()); + CacheEntry ce2 = resources.lookupCache(dirName + p2.getName()); long size2 = ce2.attributes.getContentLength(); if (size1 < size2) { return -1; @@ -2707,32 +2398,23 @@ public int compare(NameClassPair p1, NameClassPair p2) { } /** - * This is secure in the sense that any attempt to use an external entity - * will trigger an exception. + * This is secure in the sense that any attempt to use an external entity will trigger an exception. */ - private static class SecureEntityResolver implements EntityResolver2 { + private static class SecureEntityResolver implements EntityResolver2 { @Override - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - throw new SAXException( - MessageFormat.format(rb.getString(LogFacade.BLOCK_EXTERNAL_ENTITY), publicId, systemId)); + public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { + throw new SAXException(MessageFormat.format(rb.getString(LogFacade.BLOCK_EXTERNAL_ENTITY), publicId, systemId)); } @Override - public InputSource getExternalSubset(String name, String baseURI) - throws SAXException, IOException { - throw new SAXException( - MessageFormat.format(rb.getString(LogFacade.BLOCK_EXTERNAL_SUBSET), name, baseURI)); + public InputSource getExternalSubset(String name, String baseURI) throws SAXException, IOException { + throw new SAXException(MessageFormat.format(rb.getString(LogFacade.BLOCK_EXTERNAL_SUBSET), name, baseURI)); } @Override - public InputSource resolveEntity(String name, String publicId, - String baseURI, String systemId) throws SAXException, - IOException { - throw new SAXException( - MessageFormat.format(rb.getString(LogFacade.BLOCK_EXTERNAL_ENTITY2), - name, publicId, baseURI, systemId)); + public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException { + throw new SAXException(MessageFormat.format(rb.getString(LogFacade.BLOCK_EXTERNAL_ENTITY2), name, publicId, baseURI, systemId)); } } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/session/ManagerBase.java b/appserver/web/web-core/src/main/java/org/apache/catalina/session/ManagerBase.java index 6ff3adfad83..28fc735c207 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/session/ManagerBase.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/session/ManagerBase.java @@ -17,37 +17,50 @@ package org.apache.catalina.session; +import static com.sun.logging.LogCleanerUtil.neutralizeForLog; +import static java.util.logging.Level.FINE; + import com.sun.enterprise.util.uuid.UuidGenerator; import com.sun.enterprise.util.uuid.UuidGeneratorImpl; -import org.apache.catalina.*; -import org.apache.catalina.core.StandardContext; -import org.apache.catalina.core.StandardHost; -import static com.sun.logging.LogCleanerUtil.neutralizeForLog; -import javax.management.ObjectName; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.*; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.security.AccessController; import java.security.PrivilegedAction; import java.text.MessageFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; -//end HERCULES:added - +import javax.management.ObjectName; +import org.apache.catalina.Container; +import org.apache.catalina.Engine; +import org.apache.catalina.Globals; +import org.apache.catalina.LogFacade; +import org.apache.catalina.Manager; +import org.apache.catalina.Session; +import org.apache.catalina.SessionLocker; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.core.StandardHost; /** - * Minimal implementation of the Manager interface that supports - * no session persistence or distributable capabilities. This class may - * be subclassed to create more sophisticated Manager implementations. + * Minimal implementation of the Manager interface that supports no session persistence or distributable + * capabilities. This class may be subclassed to create more sophisticated Manager implementations. * * @author Craig R. McClanahan * @version $Revision: 1.23.2.3 $ $Date: 2008/04/17 18:37:20 $ @@ -59,125 +72,103 @@ public abstract class ManagerBase implements Manager { // ----------------------------------------------------- Instance Variables - protected DataInputStream randomIS=null; - protected String devRandomSource="/dev/urandom"; + protected DataInputStream randomIS = null; + protected String devRandomSource = "/dev/urandom"; /** * The Container with which this Manager is associated. */ protected Container container; - /** * The debugging detail level for this component. */ protected int debug = 0; - /** - * The distributable flag for Sessions created by this Manager. If this - * flag is set to true, any user attributes added to a - * session controlled by this Manager must be Serializable. + * The distributable flag for Sessions created by this Manager. If this flag is set to true, any user + * attributes added to a session controlled by this Manager must be Serializable. */ protected boolean distributable; - /** - * A String initialization parameter used to increase the entropy of - * the initialization of our random number generator. + * A String initialization parameter used to increase the entropy of the initialization of our random number generator. */ protected String entropy = null; - //START OF 6364900 + // START OF 6364900 /** - * A SessionLocker used to lock sessions (curently only - * in the request dispatcher forward/include use case) + * A SessionLocker used to lock sessions (curently only in the request dispatcher forward/include use case) */ protected SessionLocker sessionLocker = new BaseSessionLocker(); - //END OF 6364900 + // END OF 6364900 /** * The descriptive information string for this implementation. */ private static final String info = "ManagerBase/1.0"; - /** - * The default maximum inactive interval for Sessions created by - * this Manager. + * The default maximum inactive interval for Sessions created by this Manager. */ protected int maxInactiveInterval = 60; - /** * The session id length of Sessions created by this Manager. */ protected int sessionIdLength = 16; - /** * The descriptive name of this Manager implementation (for logging). */ protected static final String name = "ManagerBase"; - /** * A random number generator to use when generating session identifiers. */ private Random random = null; - /** - * The Uuid Generator to be used - * when generating universally unique session identifiers. - * HERCULES: add + * The Uuid Generator to be used when generating universally unique session identifiers. HERCULES: add */ protected UuidGenerator uuidGenerator = new UuidGeneratorImpl(); - /** - * The Java class name of the random number generator class to be used - * when generating session identifiers. + * The Java class name of the random number generator class to be used when generating session identifiers. */ protected String randomClass = "java.security.SecureRandom"; - /** * The longest time (in seconds) that an expired session had been alive. */ protected int sessionMaxAliveTime; - /** * Average time (in seconds) that expired sessions had been alive. */ protected int sessionAverageAliveTime; - /** * Number of sessions that have expired. */ protected int expiredSessions = 0; - /** - * The set of currently active Sessions for this Manager, keyed by - * session identifier. + * The set of currently active Sessions for this Manager, keyed by session identifier. */ protected Map sessions = new ConcurrentHashMap(); // Number of sessions created by this manager - protected int sessionCounter=0; + protected int sessionCounter = 0; - protected volatile int maxActive=0; + protected volatile int maxActive = 0; protected final Object maxActiveUpdateLock = new Object(); // number of duplicated session ids - anything >0 means we have problems - protected int duplicates=0; - - protected boolean initialized=false; + protected int duplicates = 0; + protected boolean initialized = false; /** * The property change support for this component. @@ -185,81 +176,77 @@ public abstract class ManagerBase implements Manager { protected PropertyChangeSupport support = new PropertyChangeSupport(this); /** - * Number of times a session was not created because the maximum number - * of active sessions had been reached. + * Number of times a session was not created because the maximum number of active sessions had been reached. */ protected int rejectedSessions = 0; - // ------------------------------------------------------- Security classes - private class PrivilegedSetRandomFile implements PrivilegedAction{ + private class PrivilegedSetRandomFile implements PrivilegedAction { - public DataInputStream run(){ + @Override + public DataInputStream run() { FileInputStream fileInputStream = null; try { - File f=new File( devRandomSource ); - if( ! f.exists() ) return null; + File f = new File(devRandomSource); + if (!f.exists()) + return null; fileInputStream = new FileInputStream(f); - randomIS= new DataInputStream( fileInputStream ); + randomIS = new DataInputStream(fileInputStream); randomIS.readLong(); - if( log.isLoggable(Level.FINE)) - log.log(Level.FINE, "Opening " + devRandomSource); + if (log.isLoggable(FINE)) + log.log(FINE, "Opening " + devRandomSource); return randomIS; - } catch (IOException ex){ + } catch (IOException ex) { return null; - } finally{ - try{ - if ( fileInputStream != null ) + } finally { + try { + if (fileInputStream != null) fileInputStream.close(); - } catch (IOException ex){ + } catch (IOException ex) { ; } } } } - // ------------------------------------------------------------- Properties /** - * Return the UuidGenerator for this Manager. - * HERCULES:added + * Return the UuidGenerator for this Manager. HERCULES:added */ public UuidGenerator getUuidGenerator() { return uuidGenerator; } /** - * Set the UuidGenerator for this Manager. - * HERCULES:added + * Set the UuidGenerator for this Manager. HERCULES:added */ public void setUuidGenerator(UuidGenerator aUuidGenerator) { uuidGenerator = aUuidGenerator; } - /** * Return the Container with which this Manager is associated. */ + @Override public Container getContainer() { return container; } - /** * Set the Container with which this Manager is associated. * * @param container The newly associated Container */ + @Override public void setContainer(Container container) { Container oldContainer = this.container; this.container = container; support.firePropertyChange("container", oldContainer, this.container); // TODO: find a good scheme for the log names - //log=LogFactory.getLog("tomcat.manager." + container.getName()); + // log=LogFactory.getLog("tomcat.manager." + container.getName()); } - /** * Return the debugging detail level for this component. */ @@ -267,7 +254,6 @@ public int getDebug() { return debug; } - /** * Set the debugging detail level for this component. * @@ -277,41 +263,36 @@ public void setDebug(int debug) { this.debug = debug; } - /** Returns the name of the implementation class. + /** + * Returns the name of the implementation class. */ public String getClassName() { return this.getClass().getName(); } - /** - * Return the distributable flag for the sessions supported by - * this Manager. + * Return the distributable flag for the sessions supported by this Manager. */ + @Override public boolean getDistributable() { return distributable; } - /** - * Set the distributable flag for the sessions supported by this - * Manager. If this flag is set, all user data objects added to - * sessions associated with this manager must implement Serializable. + * Set the distributable flag for the sessions supported by this Manager. If this flag is set, all user data objects + * added to sessions associated with this manager must implement Serializable. * * @param distributable The new distributable flag */ + @Override public void setDistributable(boolean distributable) { boolean oldDistributable = this.distributable; this.distributable = distributable; - support.firePropertyChange("distributable", - Boolean.valueOf(oldDistributable), - Boolean.valueOf(this.distributable)); + support.firePropertyChange("distributable", Boolean.valueOf(oldDistributable), Boolean.valueOf(this.distributable)); } - /** - * Return the entropy increaser value, or compute a semi-useful value - * if this String has not yet been set. + * Return the entropy increaser value, or compute a semi-useful value if this String has not yet been set. */ public String getEntropy() { // Calculate a semi-useful value if this has not been set @@ -320,7 +301,6 @@ public String getEntropy() { return (this.entropy); } - /** * Set the entropy increaser value. * @@ -332,108 +312,96 @@ public void setEntropy(String entropy) { support.firePropertyChange("entropy", oldEntropy, this.entropy); } - /** - * Return descriptive information about this Manager implementation and - * the corresponding version number, in the format + * Return descriptive information about this Manager implementation and the corresponding version number, in the format * <description>/<version>. */ + @Override public String getInfo() { return info; } - /** * Same as getMaxInactiveIntervalSeconds */ + @Override public int getMaxInactiveInterval() { return getMaxInactiveIntervalSeconds(); } - /** - * Return the default maximum inactive interval (in seconds) - * for Sessions created by this Manager. + * Return the default maximum inactive interval (in seconds) for Sessions created by this Manager. */ + @Override public int getMaxInactiveIntervalSeconds() { return maxInactiveInterval; } - /** * Same as setMaxInactiveIntervalSeconds */ + @Override public void setMaxInactiveInterval(int interval) { setMaxInactiveIntervalSeconds(interval); } - /** - * Set the default maximum inactive interval (in seconds) - * for Sessions created by this Manager. + * Set the default maximum inactive interval (in seconds) for Sessions created by this Manager. * * @param interval The new default value */ + @Override public void setMaxInactiveIntervalSeconds(int interval) { int oldMaxInactiveInterval = this.maxInactiveInterval; this.maxInactiveInterval = interval; - support.firePropertyChange("maxInactiveInterval", - Integer.valueOf(oldMaxInactiveInterval), - Integer.valueOf(this.maxInactiveInterval)); + support.firePropertyChange("maxInactiveInterval", Integer.valueOf(oldMaxInactiveInterval), + Integer.valueOf(this.maxInactiveInterval)); } - /** - * Gets the session id length (in bytes) of Sessions created by - * this Manager. + * Gets the session id length (in bytes) of Sessions created by this Manager. * * @return The session id length */ + @Override public int getSessionIdLength() { return sessionIdLength; } - /** - * Sets the session id length (in bytes) for Sessions created by this - * Manager. + * Sets the session id length (in bytes) for Sessions created by this Manager. * * @param idLength The session id length */ + @Override public void setSessionIdLength(int idLength) { int oldSessionIdLength = this.sessionIdLength; this.sessionIdLength = idLength; - support.firePropertyChange("sessionIdLength", - Integer.valueOf(oldSessionIdLength), - Integer.valueOf(this.sessionIdLength)); + support.firePropertyChange("sessionIdLength", Integer.valueOf(oldSessionIdLength), Integer.valueOf(this.sessionIdLength)); } - /** - * Gets the number of session creations that failed due to - * maxActiveSessions + * Gets the number of session creations that failed due to maxActiveSessions * - * @return number of session creations that failed due to - * maxActiveSessions + * @return number of session creations that failed due to maxActiveSessions */ + @Override public int getRejectedSessions() { return rejectedSessions; } - /** - * Sets the number of sessions that were not created because the maximum - * number of active sessions was reached. + * Sets the number of sessions that were not created because the maximum number of active sessions was reached. * * @param rejectedSessions Number of rejected sessions */ + @Override public void setRejectedSessions(int rejectedSessions) { this.rejectedSessions = rejectedSessions; } - /** * Return the descriptive short name of this Manager implementation. */ @@ -444,44 +412,37 @@ public String getName() { } /** - * Use /dev/random-type special device. This is new code, but may reduce - * the big delay in generating the random. + * Use /dev/random-type special device. This is new code, but may reduce the big delay in generating the random. * - * You must specify a path to a random generator file. Use /dev/urandom - * for linux ( or similar ) systems. Use /dev/random for maximum security - * ( it may block if not enough "random" exist ). You can also use - * a pipe that generates random. + * You must specify a path to a random generator file. Use /dev/urandom for linux ( or similar ) systems. Use + * /dev/random for maximum security ( it may block if not enough "random" exist ). You can also use a pipe that + * generates random. * - * The code will check if the file exists, and default to java Random - * if not found. There is a significant performance difference, very - * visible on the first call to getSession ( like in the first JSP ) - * - so use it if available. - */ - public void setRandomFile( String s ) { - // as a hack, you can use a static file - and genarate the same - // session ids ( good for strange debugging ) - if (Globals.IS_SECURITY_ENABLED){ - randomIS = AccessController.doPrivileged(new PrivilegedSetRandomFile()); - } else { - FileInputStream fileInputStream = null; - try{ - devRandomSource=s; - File f=new File( devRandomSource ); - if( ! f.exists() ) return; - fileInputStream = new FileInputStream(f); - randomIS= new DataInputStream( fileInputStream); - randomIS.readLong(); - if (log.isLoggable(Level.FINE)) - log.log(Level.FINE, "Opening " + devRandomSource ); - } catch( IOException ex ) { - randomIS=null; - } finally { - try{ - if ( fileInputStream != null ) - fileInputStream.close(); - } catch (IOException ex){ - ; - } + * The code will check if the file exists, and default to java Random if not found. There is a significant performance + * difference, very visible on the first call to getSession ( like in the first JSP ) - so use it if available. + */ + public void setRandomFile(String s) { + // as a hack, you can use a static file - and genarate the same + // session ids ( good for strange debugging ) + FileInputStream fileInputStream = null; + try { + devRandomSource = s; + File f = new File(devRandomSource); + if (!f.exists()) + return; + fileInputStream = new FileInputStream(f); + randomIS = new DataInputStream(fileInputStream); + randomIS.readLong(); + if (log.isLoggable(FINE)) + log.log(FINE, "Opening " + devRandomSource); + } catch (IOException ex) { + randomIS = null; + } finally { + try { + if (fileInputStream != null) + fileInputStream.close(); + } catch (IOException ex) { + ; } } } @@ -490,11 +451,9 @@ public String getRandomFile() { return devRandomSource; } - /** - * Return the random number generator instance we should use for - * generating session identifiers. If there is no such generator - * currently defined, construct and seed a new one. + * Return the random number generator instance we should use for generating session identifiers. If there is no such + * generator currently defined, construct and seed a new one. */ public synchronized Random getRandom() { if (this.random == null) { @@ -503,29 +462,27 @@ public synchronized Random getRandom() { long t1 = seed; char entropy[] = getEntropy().toCharArray(); for (int i = 0; i < entropy.length; i++) { - long update = ((byte) entropy[i]) << ((i % 8) * 8); - seed ^= update; + long update = ((byte) entropy[i]) << ((i % 8) * 8); + seed ^= update; } try { - // Construct and seed a new random number generator - Class clazz = Class.forName(randomClass); - this.random = (Random) clazz.newInstance(); - this.random.setSeed(seed); + // Construct and seed a new random number generator + Class clazz = Class.forName(randomClass); + this.random = (Random) clazz.newInstance(); + this.random.setSeed(seed); } catch (Exception e) { - // Fall back to the simple case - String msg = MessageFormat.format(rb.getString(LogFacade.INIT_RANDOM_NUMBER_GENERATOR_EXCEPTION), - randomClass); - log.log(Level.SEVERE, msg, e); - this.random = new java.util.Random(); - this.random.setSeed(seed); + // Fall back to the simple case + String msg = MessageFormat.format(rb.getString(LogFacade.INIT_RANDOM_NUMBER_GENERATOR_EXCEPTION), randomClass); + log.log(Level.SEVERE, msg, e); + this.random = new java.util.Random(); + this.random.setSeed(seed); } - long t2=System.currentTimeMillis(); - if( (t2-t1) > 100 ) - if (log.isLoggable(Level.FINE)) { - String msg = MessageFormat.format(rb.getString(LogFacade.SEEDING_RANDOM_NUMBER_GENERATOR_CLASS), - randomClass); - log.log(Level.FINE, msg + " " + (t2-t1)); - } + long t2 = System.currentTimeMillis(); + if ((t2 - t1) > 100) + if (log.isLoggable(FINE)) { + String msg = MessageFormat.format(rb.getString(LogFacade.SEEDING_RANDOM_NUMBER_GENERATOR_CLASS), randomClass); + log.log(FINE, msg + " " + (t2 - t1)); + } } return (this.random); @@ -538,7 +495,6 @@ protected synchronized void resetRandom() { this.random = null; } - /** * Return the random number generator class name. */ @@ -546,7 +502,6 @@ public String getRandomClass() { return randomClass; } - /** * Set the random number generator class name. * @@ -555,43 +510,41 @@ public String getRandomClass() { public void setRandomClass(String randomClass) { String oldRandomClass = this.randomClass; this.randomClass = randomClass; - support.firePropertyChange("randomClass", oldRandomClass, - this.randomClass); + support.firePropertyChange("randomClass", oldRandomClass, this.randomClass); } - /** * Gets the number of sessions that have expired. * * @return Number of sessions that have expired */ + @Override public int getExpiredSessions() { return expiredSessions; } - /** * Sets the number of sessions that have expired. * * @param expiredSessions Number of sessions that have expired */ + @Override public void setExpiredSessions(int expiredSessions) { this.expiredSessions = expiredSessions; } - //START OF 6364900 + // START OF 6364900 /** - * set the pluggable sessionLocker for this manager - * by default it is pre-set to no-op BaseSessionLocker + * set the pluggable sessionLocker for this manager by default it is pre-set to no-op BaseSessionLocker */ public void setSessionLocker(SessionLocker sessLocker) { sessionLocker = sessLocker; } - //END OF 6364900 + // END OF 6364900 // --------------------------------------------------------- Public Methods public void destroy() { - if (randomIS!=null) { + if (randomIS != null) { try { randomIS.close(); } catch (IOException ioe) { @@ -599,83 +552,79 @@ public void destroy() { log.log(Level.WARNING, LogFacade.FAILED_CLOSE_RANDOMIS_EXCEPTION); } } - randomIS=null; + randomIS = null; } - initialized=false; + initialized = false; oname = null; } public void init() { - if( initialized ) return; - initialized=true; + if (initialized) + return; + initialized = true; - if( oname==null ) { + if (oname == null) { try { - StandardContext ctx=(StandardContext)this.getContainer(); - domain=ctx.getEngineName(); + StandardContext ctx = (StandardContext) this.getContainer(); + domain = ctx.getEngineName(); distributable = ctx.getDistributable(); - StandardHost hst=(StandardHost)ctx.getParent(); + StandardHost hst = (StandardHost) ctx.getParent(); String path = ctx.getEncodedPath(); if (path.equals("")) { path = "/"; } - oname=new ObjectName(domain + ":type=Manager,path=" - + path + ",host=" + hst.getName()); + oname = new ObjectName(domain + ":type=Manager,path=" + path + ",host=" + hst.getName()); } catch (Exception e) { log.log(Level.SEVERE, LogFacade.ERROR_REGISTERING_EXCEPTION_SEVERE, e); } } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Registering " + oname ); + if (log.isLoggable(FINE)) { + log.log(FINE, "Registering " + oname); } } - /** * Add this Session to the set of active Sessions for this Manager. * * @param session Session to be added */ + @Override public void add(Session session) { sessions.put(session.getIdInternal(), session); int size = sessions.size(); if (size > maxActive) { - synchronized(maxActiveUpdateLock) { - if( size > maxActive ) { + synchronized (maxActiveUpdateLock) { + if (size > maxActive) { maxActive = size; } } } } - /** * Add a property change listener to this component. * * @param listener The listener to add */ + @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } - /** - * Construct and return a new session object, based on the default - * settings specified by this Manager's properties. The session - * id will be assigned by this method, and available via the getId() - * method of the returned session. If a new session cannot be created - * for any reason, return null. - * Hercules: modified + * Construct and return a new session object, based on the default settings specified by this Manager's properties. The + * session id will be assigned by this method, and available via the getId() method of the returned session. If a new + * session cannot be created for any reason, return null. Hercules: modified * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * @exception IllegalStateException if a new session cannot be instantiated for any reason */ + @Override public Session createSession() { // Recycle or create a Session instance Session session = null; session = createEmptySession(); - //always lock + // always lock session.lockForeground(); // Initialize the properties of the new session and return it @@ -692,24 +641,20 @@ public Session createSession() { } - // START S1AS8PE 4817642 /** - * Construct and return a new session object, based on the default - * settings specified by this Manager's properties, using the specified - * session id. + * Construct and return a new session object, based on the default settings specified by this Manager's properties, + * using the specified session id. * - * IMPLEMENTATION NOTE: This method must be kept in sync with the - * createSession method that takes no arguments. + * IMPLEMENTATION NOTE: This method must be kept in sync with the createSession method that takes no arguments. * * @param sessionId the session id to assign to the new session * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * @exception IllegalStateException if a new session cannot be instantiated for any reason * - * @return the new session, or null if a session with the - * requested id already exists + * @return the new session, or null if a session with the requested id already exists */ + @Override public Session createSession(String sessionId) { // Recycle or create a Session instance @@ -721,10 +666,10 @@ public Session createSession(String sessionId) { session.setCreationTime(System.currentTimeMillis()); session.setMaxInactiveInterval(this.maxInactiveInterval); - //START OF 6364900 - //always lock + // START OF 6364900 + // always lock session.lockForeground(); - //END OF 6364900 + // END OF 6364900 session.setId(sessionId); sessionCounter++; @@ -734,12 +679,11 @@ public Session createSession(String sessionId) { } // END S1AS8PE 4817642 - /** - * Get a session from the recycled ones or create a new empty one. - * The PersistentManager manager does not need to create session data - * because it reads it from the Store. + * Get a session from the recycled ones or create a new empty one. The PersistentManager manager does not need to create + * session data because it reads it from the Store. */ + @Override public Session createEmptySession() { return (getNewSession()); } @@ -747,22 +691,19 @@ public Session createEmptySession() { @Override public void checkSessionAttribute(String name, Object value) { if (getDistributable() && !StandardSession.isSerializable(value)) { - String msg = MessageFormat.format(rb.getString(LogFacade.NON_SERIALIZABLE_ATTRIBUTE_EXCEPTION), - name); + String msg = MessageFormat.format(rb.getString(LogFacade.NON_SERIALIZABLE_ATTRIBUTE_EXCEPTION), name); throw new IllegalArgumentException(msg); } } /** - * Return the active Session, associated with this Manager, with the - * specified session id (if any); otherwise return null. + * Return the active Session, associated with this Manager, with the specified session id (if any); otherwise return + * null. * * @param id The session id for the session to be returned * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason - * @exception IOException if an input/output error occurs while - * processing this request + * @exception IllegalStateException if a new session cannot be instantiated for any reason + * @exception IOException if an input/output error occurs while processing this request */ @Override public Session findSession(String id) throws IOException { @@ -778,20 +719,16 @@ public Session findSession(String id, HttpServletRequest request) throws IOExcep } /** - * Finds and returns the session with the given id that also satisfies - * the given version requirement. + * Finds and returns the session with the given id that also satisfies the given version requirement. * - * This overloaded version of findSession() will be invoked only if - * isSessionVersioningSupported() returns true. By default, this method - * delegates to the version of findSession() that does not take any - * session version number. + * This overloaded version of findSession() will be invoked only if isSessionVersioningSupported() returns true. By + * default, this method delegates to the version of findSession() that does not take any session version number. * * @param id The session id to match * @param version The session version requirement to satisfy * - * @return The session that matches the given id and also satisfies the - * given version requirement, or null if no such session could be found - * by this session manager + * @return The session that matches the given id and also satisfies the given version requirement, or null if no such + * session could be found by this session manager * * @exception IOException if an IO error occurred */ @@ -801,11 +738,9 @@ public Session findSession(String id, String version) throws IOException { } /** - * Returns true if this session manager supports session versioning, false - * otherwise. + * Returns true if this session manager supports session versioning, false otherwise. * - * @return true if this session manager supports session versioning, false - * otherwise. + * @return true if this session manager supports session versioning, false otherwise. */ @Override public boolean isSessionVersioningSupported() { @@ -813,18 +748,17 @@ public boolean isSessionVersioningSupported() { } /** - * clear out the sessions cache - * HERCULES:added + * clear out the sessions cache HERCULES:added */ public void clearSessions() { sessions.clear(); } - /** - * Return the set of active Sessions associated with this Manager. - * If this Manager has no active Sessions, a zero-length array is returned. + * Return the set of active Sessions associated with this Manager. If this Manager has no active Sessions, a zero-length + * array is returned. */ + @Override public Session[] findSessions() { // take a snapshot Collection sessionsValues = sessions.values(); @@ -835,12 +769,12 @@ public Session[] findSessions() { return list.toArray(new Session[list.size()]); } - /** * Remove this Session from the active Sessions for this Manager. * * @param session Session to be removed */ + @Override public void remove(Session session) { sessions.remove(session.getIdInternal()); } @@ -850,31 +784,28 @@ public Cookie toCookie(Session session) throws IOException { return null; } - /** * Remove a property change listener from this component. * * @param listener The listener to remove */ + @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } - /** - * Change the session ID of the current session to a new randomly generated - * session ID. + * Change the session ID of the current session to a new randomly generated session ID. * - * @param session The session to change the session ID for + * @param session The session to change the session ID for */ + @Override public void changeSessionId(Session session) { session.setId(generateSessionId()); } - // ------------------------------------------------------ Protected Methods - /** * Get new session class to be used in the doLoad() method. */ @@ -882,50 +813,44 @@ protected StandardSession getNewSession() { return new StandardSession(this); } - - protected void getRandomBytes( byte bytes[] ) { + protected void getRandomBytes(byte bytes[]) { // Generate a byte array containing a session identifier - if( devRandomSource!=null && randomIS==null ) { - setRandomFile( devRandomSource ); + if (devRandomSource != null && randomIS == null) { + setRandomFile(devRandomSource); } - if(randomIS!=null ) { + if (randomIS != null) { try { - int len=randomIS.read( bytes ); - if( len==bytes.length ) { + int len = randomIS.read(bytes); + if (len == bytes.length) { return; } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Got " + len + " " + bytes.length); + if (log.isLoggable(FINE)) { + log.log(FINE, "Got " + len + " " + bytes.length); } - } catch( Exception ex ) { + } catch (Exception ex) { } - devRandomSource=null; - randomIS=null; + devRandomSource = null; + randomIS = null; } getRandom().nextBytes(bytes); } - /** - * Generate and return a new session identifier. - * Hercules:added + * Generate and return a new session identifier. Hercules:added */ protected synchronized String generateSessionId(Object obj) { return uuidGenerator.generateUuid(obj); } /** - * Generate and return a new session identifier. - * Hercules:modified + * Generate and return a new session identifier. Hercules:modified */ protected synchronized String generateSessionId() { return generateSessionId(new Object()); } - // ------------------------------------------------------ Protected Methods - /** * Retrieve the enclosing Engine for this Manager. * @@ -933,17 +858,17 @@ protected synchronized String generateSessionId() { */ public Engine getEngine() { Engine e = null; - for (Container c = getContainer(); e == null && c != null ; c = c.getParent()) { + for (Container c = getContainer(); e == null && c != null; c = c.getParent()) { if (c instanceof Engine) { - e = (Engine)c; + e = (Engine) c; } } return e; } - /** * Retrieve the JvmRoute for the enclosing Engine. + * * @return the JvmRoute or null. */ public String getJvmRoute() { @@ -951,21 +876,19 @@ public String getJvmRoute() { return e == null ? null : e.getJvmRoute(); } - // -------------------------------------------------------- Package Methods - /** * Log a message on the Logger associated with our Container (if any). * * @param message Message to be logged * @deprecated */ + @Deprecated protected void log(String message) { log.log(Level.INFO, neutralizeForLog(message)); } - /** * Log a message on the Logger associated with our Container (if any). * @@ -973,45 +896,44 @@ protected void log(String message) { * @param throwable Associated exception * @deprecated */ + @Deprecated protected void log(String message, Throwable throwable) { log.log(Level.INFO, neutralizeForLog(message), throwable); } - /** * Same as setSessionCount */ + @Override public void setSessionCounter(int sessionCounter) { setSessionCount(sessionCounter); } - + @Override public void setSessionCount(int sessionCounter) { this.sessionCounter = sessionCounter; } - /** * Same as getSessionCount */ + @Override public int getSessionCounter() { return getSessionCount(); } - /** * Total sessions created by this manager. * * @return sessions created */ + @Override public int getSessionCount() { return sessionCounter; } - /** - * Number of duplicated session IDs generated by the random source. - * Anything bigger than 0 means problems. + * Number of duplicated session IDs generated by the random source. Anything bigger than 0 means problems. * * @return */ @@ -1019,133 +941,122 @@ public int getDuplicates() { return duplicates; } - public void setDuplicates(int duplicates) { this.duplicates = duplicates; } - /** * Returns the number of active sessions * * @return number of sessions active */ + @Override public int getActiveSessions() { return sessions.size(); } - /** * Max number of concurent active sessions * * @return */ + @Override public int getMaxActive() { return maxActive; } - + @Override public void setMaxActive(int maxActive) { synchronized (maxActiveUpdateLock) { this.maxActive = maxActive; } } - /** * Same as getSessionMaxAliveTimeSeconds */ + @Override public int getSessionMaxAliveTime() { return getSessionMaxAliveTimeSeconds(); } - /** - * Gets the longest time (in seconds) that an expired session had been - * alive. + * Gets the longest time (in seconds) that an expired session had been alive. * - * @return Longest time (in seconds) that an expired session had been - * alive. + * @return Longest time (in seconds) that an expired session had been alive. */ + @Override public int getSessionMaxAliveTimeSeconds() { return sessionMaxAliveTime; } - /** * Same as setSessionMaxAliveTimeSeconds */ + @Override public void setSessionMaxAliveTime(int sessionMaxAliveTime) { setSessionMaxAliveTimeSeconds(sessionMaxAliveTime); } - /** - * Sets the longest time (in seconds) that an expired session had been - * alive. + * Sets the longest time (in seconds) that an expired session had been alive. * - * @param sessionMaxAliveTime Longest time (in seconds) that an expired - * session had been alive. + * @param sessionMaxAliveTime Longest time (in seconds) that an expired session had been alive. */ + @Override public void setSessionMaxAliveTimeSeconds(int sessionMaxAliveTime) { this.sessionMaxAliveTime = sessionMaxAliveTime; } - /** * Same as getSessionAverageAliveTimeSeconds */ + @Override public int getSessionAverageAliveTime() { return getSessionAverageAliveTimeSeconds(); } - /** - * Gets the average time (in seconds) that expired sessions had been - * alive. + * Gets the average time (in seconds) that expired sessions had been alive. * - * @return Average time (in seconds) that expired sessions had been - * alive. + * @return Average time (in seconds) that expired sessions had been alive. */ + @Override public int getSessionAverageAliveTimeSeconds() { return sessionAverageAliveTime; } - /** * Same as setSessionAverageAliveTimeSeconds */ + @Override public void setSessionAverageAliveTime(int sessionAverageAliveTime) { setSessionAverageAliveTimeSeconds(sessionAverageAliveTime); } - /** - * Sets the average time (in seconds) that expired sessions had been - * alive. + * Sets the average time (in seconds) that expired sessions had been alive. * - * @param sessionAverageAliveTime Average time (in seconds) that expired - * sessions had been alive. + * @param sessionAverageAliveTime Average time (in seconds) that expired sessions had been alive. */ + @Override public void setSessionAverageAliveTimeSeconds(int sessionAverageAliveTime) { this.sessionAverageAliveTime = sessionAverageAliveTime; } - /** * For debugging: return a list of all session ids currently active * */ public String listSessionIds() { - StringBuilder sb=new StringBuilder(); - Iterator keys=sessions.keySet().iterator(); - while( keys.hasNext() ) { + StringBuilder sb = new StringBuilder(); + Iterator keys = sessions.keySet().iterator(); + while (keys.hasNext()) { sb.append(keys.next()).append(" "); } return sb.toString(); } - /** * For debugging: get a session attribute * @@ -1153,64 +1064,57 @@ public String listSessionIds() { * @param key * @return */ - public String getSessionAttribute( String sessionId, String key ) { + public String getSessionAttribute(String sessionId, String key) { Session s = sessions.get(sessionId); - if( s==null ) { + if (s == null) { /* - Do not log session ID - if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO, LogFacade.SESSION_NOT_FOUND, sessionId); - } - */ + * Do not log session ID if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, LogFacade.SESSION_NOT_FOUND, sessionId); + * } + */ return null; } - Object o=s.getSession().getAttribute(key); - if( o==null ) return null; + Object o = s.getSession().getAttribute(key); + if (o == null) + return null; return o.toString(); } - - public void expireSession( String sessionId ) { - Session s=sessions.get(sessionId); - if( s==null ) { + public void expireSession(String sessionId) { + Session s = sessions.get(sessionId); + if (s == null) { /* - Do not log session ID - if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO, LogFacade.SESSION_NOT_FOUND, sessionId); - } - */ + * Do not log session ID if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, LogFacade.SESSION_NOT_FOUND, sessionId); + * } + */ return; } s.expire(); } - - public String getLastAccessedTimeMillis( String sessionId ) { - Session s=sessions.get(sessionId); - if( s==null ) { + public String getLastAccessedTimeMillis(String sessionId) { + Session s = sessions.get(sessionId); + if (s == null) { /* - Do not log session ID - if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO, LogFacade.SESSION_NOT_FOUND, sessionId); - } - */ + * Do not log session ID if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, LogFacade.SESSION_NOT_FOUND, sessionId); + * } + */ return ""; } return new Date(s.getLastAccessedTime()).toString(); } - - //PWC Extension - //START OF RIMOD# 4820359 -- Support for iWS6.0 session managers + // PWC Extension + // START OF RIMOD# 4820359 -- Support for iWS6.0 session managers /** * Perform any operations when the request is finished. */ + @Override public void update(HttpSession session) throws Exception { return; } - //END OF RIMOD# 4820359 + // END OF RIMOD# 4820359 - // -------------------- JMX and Registration -------------------- + // -------------------- JMX and Registration -------------------- protected String domain; protected ObjectName oname; @@ -1222,32 +1126,33 @@ public String getDomain() { return domain; } - //START OF 6364900 + @Override public void postRequestDispatcherProcess(ServletRequest request, ServletResponse response) { - //deliberate no-op + // deliberate no-op return; } + @Override public void preRequestDispatcherProcess(ServletRequest request, ServletResponse response) { - //deliberate no-op + // deliberate no-op return; } + @Override public boolean lockSession(ServletRequest request) throws ServletException { boolean result = false; - if(sessionLocker != null) { + if (sessionLocker != null) { result = sessionLocker.lockSession(request); } return result; } + @Override public void unlockSession(ServletRequest request) { - if(sessionLocker != null) { + if (sessionLocker != null) { sessionLocker.unlockSession(request); } } - //END OF 6364900 - /* * Releases any resources held by this session manager. diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/session/PersistentManagerBase.java b/appserver/web/web-core/src/main/java/org/apache/catalina/session/PersistentManagerBase.java index 286c1bf97ae..df10cac35c0 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/session/PersistentManagerBase.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/session/PersistentManagerBase.java @@ -17,57 +17,57 @@ package org.apache.catalina.session; -import org.apache.catalina.*; -import org.apache.catalina.core.StandardContext; -import org.apache.catalina.security.SecurityUtil; -import org.apache.catalina.util.LifecycleSupport; +import static java.util.logging.Level.SEVERE; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.text.MessageFormat; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; +import org.apache.catalina.Container; +import org.apache.catalina.Context; +import org.apache.catalina.Lifecycle; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.LifecycleListener; +import org.apache.catalina.LogFacade; +import org.apache.catalina.Session; +import org.apache.catalina.Store; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.util.LifecycleSupport; /** - * Extends the ManagerBase class to implement most of the - * functionality required by a Manager which supports any kind of - * persistence, even if only for restarts. + * Extends the ManagerBase class to implement most of the functionality required by a Manager which supports any + * kind of persistence, even if only for restarts. *

- * IMPLEMENTATION NOTE: Correct behavior of session storing and - * reloading depends upon external calls to the start() and - * stop() methods of this class at the correct times. + * IMPLEMENTATION NOTE: Correct behavior of session storing and reloading depends upon external calls to the + * start() and stop() methods of this class at the correct times. * * @author Craig R. McClanahan * @author Jean-Francois Arcand * @version $Revision: 1.16 $ $Date: 2007/05/05 05:32:19 $ */ -public abstract class PersistentManagerBase - extends ManagerBase - implements Lifecycle, PropertyChangeListener { +public abstract class PersistentManagerBase extends ManagerBase implements Lifecycle, PropertyChangeListener { // ---------------------------------------------------- Security Classes - private class PrivilegedStoreClear - implements PrivilegedExceptionAction { + private class PrivilegedStoreClear implements PrivilegedExceptionAction { PrivilegedStoreClear() { // NOOP } - public Void run() throws Exception{ - store.clear(); - return null; + @Override + public Void run() throws Exception { + store.clear(); + return null; } } - private class PrivilegedStoreRemove - implements PrivilegedExceptionAction { + private class PrivilegedStoreRemove implements PrivilegedExceptionAction { private String id; @@ -75,14 +75,14 @@ private class PrivilegedStoreRemove this.id = id; } - public Void run() throws Exception{ - store.remove(id); - return null; + @Override + public Void run() throws Exception { + store.remove(id); + return null; } } - private class PrivilegedStoreLoad - implements PrivilegedExceptionAction { + private class PrivilegedStoreLoad implements PrivilegedExceptionAction { private String id; @@ -90,13 +90,13 @@ private class PrivilegedStoreLoad this.id = id; } - public Session run() throws Exception{ - return store.load(id); + @Override + public Session run() throws Exception { + return store.load(id); } } - private class PrivilegedStoreSave - implements PrivilegedExceptionAction { + private class PrivilegedStoreSave implements PrivilegedExceptionAction { private Session session; @@ -104,104 +104,88 @@ private class PrivilegedStoreSave this.session = session; } - public Void run() throws Exception{ - store.save(session); - return null; + @Override + public Void run() throws Exception { + store.save(session); + return null; } } - private class PrivilegedStoreKeys - implements PrivilegedExceptionAction { + private class PrivilegedStoreKeys implements PrivilegedExceptionAction { PrivilegedStoreKeys() { // NOOP } - public String[] run() throws Exception{ - return store.keys(); + @Override + public String[] run() throws Exception { + return store.keys(); } } // ----------------------------------------------------- Instance Variables - /** * The descriptive information about this implementation. */ private static final String info = "PersistentManagerBase/1.0"; - /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); - /** * The maximum number of active Sessions allowed, or -1 for no limit. */ private int maxActiveSessions = -1; - /** * The descriptive name of this Manager implementation (for logging). */ protected static final String name = "PersistentManagerBase"; - /** * Has this component been started yet? */ private boolean started = false; - /** * Store object which will manage the Session store. */ private Store store = null; - /** - * Whether to save and reload sessions when the Manager unload - * and load methods are called. + * Whether to save and reload sessions when the Manager unload and load methods are called. */ private boolean saveOnRestart = true; - /** - * How long a session must be idle before it should be backed up. - * -1 means sessions won't be backed up. + * How long a session must be idle before it should be backed up. -1 means sessions won't be backed up. */ private int maxIdleBackup = -1; - /** - * Minimum time a session must be idle before it is swapped to disk. - * This overrides maxActiveSessions, to prevent thrashing if there are lots - * of active sessions. Setting to -1 means it's ignored. + * Minimum time a session must be idle before it is swapped to disk. This overrides maxActiveSessions, to prevent + * thrashing if there are lots of active sessions. Setting to -1 means it's ignored. */ private int minIdleSwap = -1; /** - * The maximum time a session may be idle before it should be swapped - * to file just on general principle. Setting this to -1 means sessions - * should not be forced out. + * The maximum time a session may be idle before it should be swapped to file just on general principle. Setting this to + * -1 means sessions should not be forced out. */ private int maxIdleSwap = -1; - // START SJSAS 6406580 /** - * The set of invalidated Sessions for this Manager, keyed by - * session identifier. + * The set of invalidated Sessions for this Manager, keyed by session identifier. */ - protected ConcurrentHashMap invalidatedSessions - = new ConcurrentHashMap(); + protected ConcurrentHashMap invalidatedSessions = new ConcurrentHashMap(); // Specifies for how long we're going to remember invalidated session ids private long rememberInvalidatedSessionIdMilliSecs = 60000L; // END SJSAS 6406580 - // ------------------------------------------------------------- Properties /** @@ -213,16 +197,14 @@ public void backgroundProcess() { // START SJSAS 6406580 this.processInvalidatedSessions(); // END SJSAS 6406580 - if ((this.getStore() != null) - && (this.getStore() instanceof StoreBase)) { + if ((this.getStore() != null) && (this.getStore() instanceof StoreBase)) { ((StoreBase) this.getStore()).processExpires(); } } /** - * Indicates how many seconds old a session can get, after its last - * use in a request, before it should be backed up to the store. -1 - * means sessions are not backed up. + * Indicates how many seconds old a session can get, after its last use in a request, before it should be backed up to + * the store. -1 means sessions are not backed up. */ public int getMaxIdleBackup() { @@ -230,43 +212,31 @@ public int getMaxIdleBackup() { } - /** - * Sets the option to back sessions up to the Store after they - * are used in a request. Sessions remain available in memory - * after being backed up, so they are not passivated as they are - * when swapped out. The value set indicates how old a session - * may get (since its last use) before it must be backed up: -1 - * means sessions are not backed up. + * Sets the option to back sessions up to the Store after they are used in a request. Sessions remain available in + * memory after being backed up, so they are not passivated as they are when swapped out. The value set indicates how + * old a session may get (since its last use) before it must be backed up: -1 means sessions are not backed up. *

- * Note that this is not a hard limit: sessions are checked - * against this age limit periodically according to checkInterval. - * This value should be considered to indicate when a session is - * ripe for backing up. + * Note that this is not a hard limit: sessions are checked against this age limit periodically according to + * checkInterval. This value should be considered to indicate when a session is ripe for backing up. *

- * So it is possible that a session may be idle for maxIdleBackup + - * checkInterval seconds, plus the time it takes to handle other - * session expiration, swapping, etc. tasks. + * So it is possible that a session may be idle for maxIdleBackup + checkInterval seconds, plus the time it takes to + * handle other session expiration, swapping, etc. tasks. * - * @param backup The number of seconds after their last accessed - * time when they should be written to the Store. + * @param backup The number of seconds after their last accessed time when they should be written to the Store. */ - public void setMaxIdleBackup (int backup) { + public void setMaxIdleBackup(int backup) { if (backup == this.maxIdleBackup) return; int oldBackup = this.maxIdleBackup; this.maxIdleBackup = backup; - support.firePropertyChange("maxIdleBackup", - Integer.valueOf(oldBackup), - Integer.valueOf(this.maxIdleBackup)); + support.firePropertyChange("maxIdleBackup", Integer.valueOf(oldBackup), Integer.valueOf(this.maxIdleBackup)); } - /** - * The time in seconds after which a session should be swapped out of - * memory to disk. + * The time in seconds after which a session should be swapped out of memory to disk. */ public int getMaxIdleSwap() { @@ -274,10 +244,8 @@ public int getMaxIdleSwap() { } - /** - * Sets the time in seconds after which a session should be swapped out of - * memory to disk. + * Sets the time in seconds after which a session should be swapped out of memory to disk. */ public void setMaxIdleSwap(int max) { @@ -285,17 +253,13 @@ public void setMaxIdleSwap(int max) { return; int oldMaxIdleSwap = this.maxIdleSwap; this.maxIdleSwap = max; - support.firePropertyChange("maxIdleSwap", - Integer.valueOf(oldMaxIdleSwap), - Integer.valueOf(this.maxIdleSwap)); + support.firePropertyChange("maxIdleSwap", Integer.valueOf(oldMaxIdleSwap), Integer.valueOf(this.maxIdleSwap)); } - /** - * The minimum time in seconds that a session must be idle before - * it can be swapped out of memory, or -1 if it can be swapped out - * at any time. + * The minimum time in seconds that a session must be idle before it can be swapped out of memory, or -1 if it can be + * swapped out at any time. */ public int getMinIdleSwap() { @@ -303,11 +267,9 @@ public int getMinIdleSwap() { } - /** - * Sets the minimum time in seconds that a session must be idle before - * it can be swapped out of memory due to maxActiveSession. Set it to -1 - * if it can be swapped out at any time. + * Sets the minimum time in seconds that a session must be idle before it can be swapped out of memory due to + * maxActiveSession. Set it to -1 if it can be swapped out at any time. */ public void setMinIdleSwap(int min) { @@ -315,20 +277,17 @@ public void setMinIdleSwap(int min) { return; int oldMinIdleSwap = this.minIdleSwap; this.minIdleSwap = min; - support.firePropertyChange("minIdleSwap", - Integer.valueOf(oldMinIdleSwap), - Integer.valueOf(this.minIdleSwap)); + support.firePropertyChange("minIdleSwap", Integer.valueOf(oldMinIdleSwap), Integer.valueOf(this.minIdleSwap)); } - /** - * Set the Container with which this Manager has been associated. If - * it is a Context (the usual case), listen for changes to the session - * timeout property. + * Set the Container with which this Manager has been associated. If it is a Context (the usual case), listen for + * changes to the session timeout property. * * @param container The associated Container */ + @Override public void setContainer(Container container) { // De-register from the old Container (if any) @@ -340,8 +299,7 @@ public void setContainer(Container container) { // Register with the new Container (if any) if ((this.container != null) && (this.container instanceof Context)) { - setMaxInactiveIntervalSeconds - ( ((Context) this.container).getSessionTimeout()*60 ); + setMaxInactiveIntervalSeconds(((Context) this.container).getSessionTimeout() * 60); ((Context) this.container).addPropertyChangeListener(this); } @@ -352,8 +310,7 @@ public void setContainer(Container container) { StandardContext ctx = (StandardContext) container; int frequency = ctx.getManagerChecksFrequency(); int reapIntervalSeconds = ctx.getBackgroundProcessorDelay(); - rememberInvalidatedSessionIdMilliSecs - = frequency * reapIntervalSeconds * 1000L * 2; + rememberInvalidatedSessionIdMilliSecs = frequency * reapIntervalSeconds * 1000L * 2; if (rememberInvalidatedSessionIdMilliSecs <= 0) { rememberInvalidatedSessionIdMilliSecs = 60000L; } @@ -361,44 +318,37 @@ public void setContainer(Container container) { // END SJSAS 6406580 } - /** - * Return descriptive information about this Manager implementation and - * the corresponding version number, in the format + * Return descriptive information about this Manager implementation and the corresponding version number, in the format * <description>/<version>. */ + @Override public String getInfo() { return (this.info); } - /** - * Return true, if the session id is loaded in memory - * otherwise false is returned + * Return true, if the session id is loaded in memory otherwise false is returned * * @param id The session id for the session to be searched for * - * @exception IOException if an input/output error occurs while - * processing this request + * @exception IOException if an input/output error occurs while processing this request */ - public boolean isLoaded( String id ){ + public boolean isLoaded(String id) { try { - if ( super.findSession(id) != null ) + if (super.findSession(id) != null) return true; } catch (IOException e) { - String msg = MessageFormat.format(rb.getString(LogFacade.CHECKING_IS_LOADED_EXCEPTION), - new Object[] {id, e.getMessage()}); - log.log(Level.SEVERE, msg, e); + String msg = MessageFormat.format(rb.getString(LogFacade.CHECKING_IS_LOADED_EXCEPTION), new Object[] { id, e.getMessage() }); + log.log(SEVERE, msg, e); } return false; } - /** - * Return the maximum number of active Sessions allowed, or -1 for - * no limit. + * Return the maximum number of active Sessions allowed, or -1 for no limit. */ public int getMaxActiveSessions() { @@ -406,10 +356,8 @@ public int getMaxActiveSessions() { } - /** - * Set the maximum number of active Sessions allowed, or -1 for - * no limit. + * Set the maximum number of active Sessions allowed, or -1 for no limit. * * @param max The new maximum number of sessions */ @@ -417,20 +365,17 @@ public void setMaxActiveSessions(int max) { int oldMaxActiveSessions = this.maxActiveSessions; this.maxActiveSessions = max; - support.firePropertyChange("maxActiveSessions", - Integer.valueOf(oldMaxActiveSessions), - Integer.valueOf(this.maxActiveSessions)); + support.firePropertyChange("maxActiveSessions", Integer.valueOf(oldMaxActiveSessions), Integer.valueOf(this.maxActiveSessions)); } - /** * Return the descriptive short name of this Manager implementation. */ + @Override public String getName() { return (name); } - /** * Get the started status. */ @@ -438,7 +383,6 @@ protected boolean isStarted() { return started; } - /** * Set the started flag */ @@ -446,10 +390,8 @@ protected void setStarted(boolean started) { this.started = started; } - /** - * Set the Store object which will manage persistent Session - * storage for this Manager. + * Set the Store object which will manage persistent Session storage for this Manager. * * @param store the associated Store */ @@ -458,10 +400,8 @@ public void setStore(Store store) { store.setManager(this); } - /** - * Return the Store object which manages persistent Session - * storage for this Manager. + * Return the Store object which manages persistent Session storage for this Manager. */ public Store getStore() { @@ -469,11 +409,9 @@ public Store getStore() { } - - /** - * Indicates whether sessions are saved when the Manager is shut down - * properly. This requires the unload() method to be called. + * Indicates whether sessions are saved when the Manager is shut down properly. This requires the unload() method to be + * called. */ public boolean getSaveOnRestart() { @@ -481,15 +419,11 @@ public boolean getSaveOnRestart() { } - /** - * Set the option to save sessions to the Store when the Manager is - * shut down, then loaded when the Manager starts again. If set to - * false, any sessions found in the Store may still be picked up when - * the Manager is started again. + * Set the option to save sessions to the Store when the Manager is shut down, then loaded when the Manager starts + * again. If set to false, any sessions found in the Store may still be picked up when the Manager is started again. * - * @param saveOnRestart true if sessions should be saved on restart, false if - * they should be ignored. + * @param saveOnRestart true if sessions should be saved on restart, false if they should be ignored. */ public void setSaveOnRestart(boolean saveOnRestart) { @@ -498,57 +432,40 @@ public void setSaveOnRestart(boolean saveOnRestart) { boolean oldSaveOnRestart = this.saveOnRestart; this.saveOnRestart = saveOnRestart; - support.firePropertyChange("saveOnRestart", - Boolean.valueOf(oldSaveOnRestart), - Boolean.valueOf(this.saveOnRestart)); + support.firePropertyChange("saveOnRestart", Boolean.valueOf(oldSaveOnRestart), Boolean.valueOf(this.saveOnRestart)); } - // --------------------------------------------------------- Public Methods - /* * Releases any resources held by this session manager. */ + @Override public void release() { super.release(); clearStore(); } - /** * Clear all sessions from the Store. */ public void clearStore() { - if (store == null) return; try { - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - AccessController.doPrivileged(new PrivilegedStoreClear()); - }catch(PrivilegedActionException ex){ - Exception exception = ex.getException(); - log.log(Level.SEVERE, LogFacade.CLEARING_STORE_EXCEPTION, exception); - } - } else { - store.clear(); - } + store.clear(); } catch (IOException e) { - log.log(Level.SEVERE, LogFacade.CLEARING_STORE_EXCEPTION, e); + log.log(SEVERE, LogFacade.CLEARING_STORE_EXCEPTION, e); } } - /** - * Invalidate all sessions that have expired. - * Hercules: modified method + * Invalidate all sessions that have expired. Hercules: modified method */ protected void processExpires() { - if (!started) return; @@ -556,41 +473,32 @@ protected void processExpires() { for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; - /* START CR 6363689 - if (!session.isValid()) { - */ - // START CR 6363689 - if(!session.getIsValid() || session.hasExpired()) { - // END CR 6363689 - if(session.lockBackground()) { + if (!session.getIsValid() || session.hasExpired()) { + if (session.lockBackground()) { try { session.expire(); } finally { session.unlockBackground(); } } - } + } } } - /** - * Called by the background thread after active sessions have - * been checked for expiration, to allow sessions to be + * Called by the background thread after active sessions have been checked for expiration, to allow sessions to be * swapped out, backed up, etc. */ public void processPersistenceChecks() { - processMaxIdleSwaps(); - processMaxActiveSwaps(); - processMaxIdleBackups(); + processMaxIdleSwaps(); + processMaxActiveSwaps(); + processMaxIdleBackups(); } - /** - * Purges those session ids from the map of invalidated session ids whose - * time has come up + * Purges those session ids from the map of invalidated session ids whose time has come up */ protected void processInvalidatedSessions() { @@ -602,85 +510,70 @@ protected void processInvalidatedSessions() { for (Map.Entry e : invalidatedSessions.entrySet()) { String id = e.getKey(); Long timeAdded = e.getValue(); - if ((timeAdded == null) - || (timeNow - timeAdded.longValue() > - rememberInvalidatedSessionIdMilliSecs)) { + if ((timeAdded == null) || (timeNow - timeAdded.longValue() > rememberInvalidatedSessionIdMilliSecs)) { removeFromInvalidatedSessions(id); } } } - /** - * Return a new session object as long as the number of active - * sessions does not exceed maxActiveSessions. If there - * aren't too many active sessions, or if there is no limit, - * a session is created or retrieved from the recycled pool. + * Return a new session object as long as the number of active sessions does not exceed maxActiveSessions. If + * there aren't too many active sessions, or if there is no limit, a session is created or retrieved from the recycled + * pool. * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * @exception IllegalStateException if a new session cannot be instantiated for any reason */ + @Override public Session createSession() { - if ((maxActiveSessions >= 0) && - (sessions.size() >= maxActiveSessions)) - throw new IllegalStateException - (rb.getString(LogFacade.CREATE_SESSION_EXCEPTION)); + if ((maxActiveSessions >= 0) && (sessions.size() >= maxActiveSessions)) + throw new IllegalStateException(rb.getString(LogFacade.CREATE_SESSION_EXCEPTION)); return (super.createSession()); } - // START S1AS8PE 4817642 /** - * Construct and return a new session object, based on the default - * settings specified by this Manager's properties, using the specified - * session id. + * Construct and return a new session object, based on the default settings specified by this Manager's properties, + * using the specified session id. * - * IMPLEMENTATION NOTE: This method must be kept in sync with the - * createSession method that takes no arguments. + * IMPLEMENTATION NOTE: This method must be kept in sync with the createSession method that takes no arguments. * * @param sessionId the session id to assign to the new session * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * @exception IllegalStateException if a new session cannot be instantiated for any reason * - * @return the new session, or null if a session with the - * requested id already exists + * @return the new session, or null if a session with the requested id already exists */ + @Override public Session createSession(String sessionId) { - if ((maxActiveSessions >= 0) && - (sessions.size() >= maxActiveSessions)) - throw new IllegalStateException - (rb.getString(LogFacade.CREATE_SESSION_EXCEPTION)); + if ((maxActiveSessions >= 0) && (sessions.size() >= maxActiveSessions)) + throw new IllegalStateException(rb.getString(LogFacade.CREATE_SESSION_EXCEPTION)); return (super.createSession(sessionId)); } // END S1AS8PE 4817642 - /** - * Return the active Session, associated with this Manager, with the - * specified session id (if any); otherwise return null. - * This method checks the persistence store if persistence is enabled, - * otherwise just uses the functionality from ManagerBase. + * Return the active Session, associated with this Manager, with the specified session id (if any); otherwise return + * null. This method checks the persistence store if persistence is enabled, otherwise just uses the + * functionality from ManagerBase. * * @param id The session id for the session to be returned * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason - * @exception IOException if an input/output error occurs while - * processing this request + * @exception IllegalStateException if a new session cannot be instantiated for any reason + * @exception IOException if an input/output error occurs while processing this request */ + @Override public Session findSession(String id) throws IOException { - //6406580 START - if(!this.isSessionIdValid(id)) { + // 6406580 START + if (!this.isSessionIdValid(id)) { return null; } - //6406580 END + // 6406580 END Session session = super.findSession(id); if (session != null) @@ -693,30 +586,25 @@ public Session findSession(String id) throws IOException { } /** - * Return the active Session, associated with this Manager, with the - * specified session id (if any); otherwise return null. - * This method first removes the cached copy if removeCachedCopy = true. - * Then this method checks the persistence store if persistence is enabled, - * otherwise just uses the functionality from ManagerBase. + * Return the active Session, associated with this Manager, with the specified session id (if any); otherwise return + * null. This method first removes the cached copy if removeCachedCopy = true. Then this method checks the + * persistence store if persistence is enabled, otherwise just uses the functionality from ManagerBase. * * @param id The session id for the session to be returned * @param removeCachedCopy * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason - * @exception IOException if an input/output error occurs while - * processing this request + * @exception IllegalStateException if a new session cannot be instantiated for any reason + * @exception IOException if an input/output error occurs while processing this request */ public Session findSession(String id, boolean removeCachedCopy) throws IOException { Session theSession = super.findSession(id); if (theSession != null) { - if(removeCachedCopy) { - //remove from manager cache + if (removeCachedCopy) { + // remove from manager cache removeSuper(theSession); - //remove from store cache if it exists - if ((this.getStore() != null) - && (this.getStore() instanceof StoreBase)) { + // remove from store cache if it exists + if ((this.getStore() != null) && (this.getStore() instanceof StoreBase)) { ((StoreBase) this.getStore()).removeFromStoreCache(id); } theSession = null; @@ -724,42 +612,37 @@ public Session findSession(String id, boolean removeCachedCopy) throws IOExcepti return (theSession); } } - //now do full findSession + // now do full findSession theSession = findSession(id); return theSession; } /** - * used by subclasses of PersistentManagerBase - * Hercules: added method + * used by subclasses of PersistentManagerBase Hercules: added method */ protected Session superFindSession(String id) throws IOException { return super.findSession(id); } /** - * Remove this Session from the active Sessions for this Manager, - * but not from the Store. (Used by the PersistentValve) + * Remove this Session from the active Sessions for this Manager, but not from the Store. (Used by the PersistentValve) * * @param session Session to be removed */ public void removeSuper(Session session) { - super.remove (session); + super.remove(session); } /** - * Load all sessions found in the persistence mechanism, assuming - * they are marked as valid and have not passed their expiration - * limit. If persistence is not supported, this method returns - * without doing anything. + * Load all sessions found in the persistence mechanism, assuming they are marked as valid and have not passed their + * expiration limit. If persistence is not supported, this method returns without doing anything. *

- * Note that by default, this method is not called by the MiddleManager - * class. In order to use it, a subclass must specifically call it, - * for example in the start() and/or processPersistenceChecks() methods. + * Note that by default, this method is not called by the MiddleManager class. In order to use it, a subclass must + * specifically call it, for example in the start() and/or processPersistenceChecks() methods. */ + @Override public void load() { - // Initialize our internal data structures sessions.clear(); @@ -768,19 +651,9 @@ public void load() { String[] ids = null; try { - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - ids = AccessController.doPrivileged( - new PrivilegedStoreKeys()); - }catch(PrivilegedActionException ex){ - Exception exception = ex.getException(); - log.log(Level.SEVERE, LogFacade.STORE_LOADING_EXCEPTION, exception); - } - } else { - ids = store.keys(); - } + ids = store.keys(); } catch (IOException e) { - log.log(Level.SEVERE, LogFacade.CANNOT_LOAD_SESSION_EXCEPTION, e); + log.log(SEVERE, LogFacade.CANNOT_LOAD_SESSION_EXCEPTION, e); return; } @@ -795,74 +668,58 @@ public void load() { try { swapIn(ids[i]); } catch (IOException e) { - log.log(Level.SEVERE, LogFacade.FAILED_LOAD_SESSION_EXCEPTION, e); + log.log(SEVERE, LogFacade.FAILED_LOAD_SESSION_EXCEPTION, e); } } /** - * Remove this Session from the active Sessions for this Manager, - * and from the Store. + * Remove this Session from the active Sessions for this Manager, and from the Store. * * @param session Session to be removed */ + @Override public void remove(Session session) { remove(session, true); } /** - * Remove this Session from the active Sessions for this Manager, - * and from the Store. + * Remove this Session from the active Sessions for this Manager, and from the Store. * * @param session Session to be removed - * @param persistentRemove - do we remove persistent session too + * @param persistentRemove - do we remove persistent session too */ public void remove(Session session, boolean persistentRemove) { - super.remove (session); + super.remove(session); - if (persistentRemove && store != null){ + if (persistentRemove && store != null) { removeSession(session.getIdInternal()); } } /** - * Remove this Session from the active Sessions for this Manager, - * and from the Store. + * Remove this Session from the active Sessions for this Manager, and from the Store. * * @param id Session's id to be removed */ - private void removeSession(String id){ + private void removeSession(String id) { try { - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - AccessController.doPrivileged(new PrivilegedStoreRemove(id)); - }catch(PrivilegedActionException ex){ - Exception exception = ex.getException(); - log.log(Level.SEVERE, LogFacade.STORE_REMOVE_SESSION_EXCEPTION, exception); - } - } else { - store.remove(id); - } + store.remove(id); } catch (IOException e) { - log.log(Level.SEVERE, LogFacade.REMOVING_SESSION_EXCEPTION, e); + log.log(SEVERE, LogFacade.REMOVING_SESSION_EXCEPTION, e); } } - - // START SJSAS 6406580 /** - * Add this Session id to the set of invalidated Session ids for this - * Manager. + * Add this Session id to the set of invalidated Session ids for this Manager. * * @param sessionId session id to be added */ public void addToInvalidatedSessions(String sessionId) { - invalidatedSessions.put(sessionId, - Long.valueOf(System.currentTimeMillis())); + invalidatedSessions.put(sessionId, Long.valueOf(System.currentTimeMillis())); } - /** * Removes the given session id from the map of invalidated session ids. * @@ -872,28 +729,22 @@ public void removeFromInvalidatedSessions(String sessionId) { invalidatedSessions.remove(sessionId); } - /** - * @return true if the given session id is not contained in the map of - * invalidated session ids, false otherwise + * @return true if the given session id is not contained in the map of invalidated session ids, false otherwise */ public boolean isSessionIdValid(String sessionId) { - return (!invalidatedSessions.containsKey(sessionId)); + return !invalidatedSessions.containsKey(sessionId); } - // END SJSAS 6406580 - /** - * Save all currently active sessions in the appropriate persistence - * mechanism, if any. If persistence is not supported, this method - * returns without doing anything. + * Save all currently active sessions in the appropriate persistence mechanism, if any. If persistence is not supported, + * this method returns without doing anything. *

- * Note that by default, this method is not called by the MiddleManager - * class. In order to use it, a subclass must specifically call it, - * for example in the stop() and/or processPersistenceChecks() methods. + * Note that by default, this method is not called by the MiddleManager class. In order to use it, a subclass must + * specifically call it, for example in the stop() and/or processPersistenceChecks() methods. */ + @Override public void unload() { - if (store == null) return; @@ -914,14 +765,11 @@ public void unload() { } - // ------------------------------------------------------ Protected Methods /** - * Look for a session in the Store and, if found, restore - * it in the Manager's list of active sessions if appropriate. - * The session will be removed from the Store after swapping - * in, but will not be added to the active session list if it + * Look for a session in the Store and, if found, restore it in the Manager's list of active sessions if appropriate. + * The session will be removed from the Store after swapping in, but will not be added to the active session list if it * is invalid or past its expiration. */ protected Session swapIn(String id) throws IOException { @@ -929,10 +777,8 @@ protected Session swapIn(String id) throws IOException { } /** - * Look for a session in the Store and, if found, restore - * it in the Manager's list of active sessions if appropriate. - * The session will be removed from the Store after swapping - * in, but will not be added to the active session list if it + * Look for a session in the Store and, if found, restore it in the Manager's list of active sessions if appropriate. + * The session will be removed from the Store after swapping in, but will not be added to the active session list if it * is invalid or past its expiration. * * @param id The session id @@ -943,8 +789,7 @@ protected Session swapIn(String id, String version) throws IOException { ClassLoader webappCl = null; ClassLoader curCl = null; - if (getContainer() != null - && getContainer().getLoader() != null) { + if (getContainer() != null && getContainer().getLoader() != null) { webappCl = getContainer().getLoader().getClassLoader(); curCl = Thread.currentThread().getContextClassLoader(); } @@ -966,43 +811,24 @@ && getContainer().getLoader() != null) { } /** - * Look for a session in the Store and, if found, restore - * it in the Manager's list of active sessions if appropriate. - * The session will be removed from the Store after swapping - * in, but will not be added to the active session list if it + * Look for a session in the Store and, if found, restore it in the Manager's list of active sessions if appropriate. + * The session will be removed from the Store after swapping in, but will not be added to the active session list if it * is invalid or past its expiration. */ private Session doSwapIn(String id, String version) throws IOException { - if (store == null) return null; Session session = null; try { - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - session = AccessController.doPrivileged( - new PrivilegedStoreLoad(id)); - }catch(PrivilegedActionException ex){ - Exception exception = ex.getException(); - log.log(Level.SEVERE, LogFacade.STORE_SWAP_IN_EXCEPTION, exception); - if (exception instanceof IOException){ - throw (IOException)exception; - } else if (exception instanceof ClassNotFoundException) { - throw (ClassNotFoundException)exception; - } - } + if (version != null) { + session = ((StoreBase) store).load(id, version); } else { - if (version != null) { - session = ((StoreBase) store).load(id, version); - } else { - session = store.load(id); - } + session = store.load(id); } } catch (ClassNotFoundException e) { - String msg = MessageFormat.format(rb.getString(LogFacade.DESERILIZING_SESSION_EXCEPTION), - new Object[] {id, e}); - log.log(Level.SEVERE, msg); + String msg = MessageFormat.format(rb.getString(LogFacade.DESERILIZING_SESSION_EXCEPTION), new Object[] { id, e }); + log.log(SEVERE, msg); throw new IllegalStateException(msg); } @@ -1010,55 +836,44 @@ private Session doSwapIn(String id, String version) throws IOException { return (null); if (!session.isValid()) { - log.log(Level.SEVERE, LogFacade.INVALID_EXPIRED_SESSION_EXCEPTION); - //6406580 START - /* - these lines are calling remove on store redundantly - session.expire(); - removeSession(id); - */ - //6406580 END + log.log(SEVERE, LogFacade.INVALID_EXPIRED_SESSION_EXCEPTION); return (null); } if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, LogFacade.SWAPPING_SESSION_FROM_STORE, id); } + session.setManager(this); // make sure the listeners know about it. - ((StandardSession)session).tellNew(); + ((StandardSession) session).tellNew(); add(session); - ((StandardSession)session).activate(); + ((StandardSession) session).activate(); return (session); } - /** - * Remove the session from the Manager's list of active - * sessions and write it out to the Store. If the session - * is past its expiration or invalid, this method does - * nothing. + * Remove the session from the Manager's list of active sessions and write it out to the Store. If the session is past + * its expiration or invalid, this method does nothing. * * @param session The Session to write out. */ protected void swapOut(Session session) throws IOException { - if (store == null || !session.isValid()) { return; } - ((StandardSession)session).passivate(); + ((StandardSession) session).passivate(); writeSession(session); super.remove(session); session.recycle(); } - /** - * Write the provided session to the Store without modifying - * the copy in memory or triggering passivation events. Does + * Write the provided session to the Store without modifying the copy in memory or triggering passivation events. Does * nothing if the session is invalid or past its expiration. */ protected void writeSession(Session session) throws IOException { @@ -1066,86 +881,64 @@ protected void writeSession(Session session) throws IOException { return; } - ((StandardContext)getContainer()).sessionPersistedStartEvent( - (StandardSession) session); + ((StandardContext) getContainer()).sessionPersistedStartEvent((StandardSession) session); // If the given session is being persisted after a lock has been // acquired out-of-band, its version needs to be incremented // here (otherwise, it will have already been incremented at the // time the session was acquired via HttpServletRequest.getSession()) - if (isSessionVersioningSupported() - && ((StandardSession) session).hasNonHttpLockOccurred()) { + if (isSessionVersioningSupported() && ((StandardSession) session).hasNonHttpLockOccurred()) { ((StandardSession) session).incrementVersion(); } try { - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - AccessController.doPrivileged(new PrivilegedStoreSave(session)); - } catch(PrivilegedActionException ex){ - Exception exception = ex.getException(); - log.log(Level.SEVERE, LogFacade.STORE_WRITE_SESSION_EXCEPTION, - exception); - } - } else { - store.save(session); - } + store.save(session); } catch (IOException e) { - log.log(Level.SEVERE,LogFacade.SERIALIZING_SESSION_EXCEPTION, new Object[] {session.getIdInternal(), e}); + log.log(SEVERE, LogFacade.SERIALIZING_SESSION_EXCEPTION, new Object[] { session.getIdInternal(), e }); throw e; } finally { - ((StandardContext)getContainer()).sessionPersistedEndEvent( - (StandardSession) session); + ((StandardContext) getContainer()).sessionPersistedEndEvent((StandardSession) session); } } - // -------------------------------------------------- Lifecycle Methods - /** * Add a lifecycle event listener to this component. * * @param listener The listener to add */ + @Override public void addLifecycleListener(LifecycleListener listener) { - lifecycle.addLifecycleListener(listener); - } - /** - * Gets the (possibly empty) list of lifecycle listeners associated - * with this session manager. + * Gets the (possibly empty) list of lifecycle listeners associated with this session manager. */ + @Override public List findLifecycleListeners() { return lifecycle.findLifecycleListeners(); } - /** * Remove a lifecycle event listener from this component. * * @param listener The listener to remove */ + @Override public void removeLifecycleListener(LifecycleListener listener) { - lifecycle.removeLifecycleListener(listener); - } - /** - * Prepare for the beginning of active use of the public methods of this - * component. This method should be called after configure(), - * and before any of the public methods of the component are utilized. + * Prepare for the beginning of active use of the public methods of this component. This method should be called after + * configure(), and before any of the public methods of the component are utilized. * - * @exception LifecycleException if this component detects a fatal error - * that prevents this component from being used + * @exception LifecycleException if this component detects a fatal error that prevents this component from being used */ + @Override public void start() throws LifecycleException { - // Validate and update our current component state if (started) { if (log.isLoggable(Level.INFO)) { @@ -1153,7 +946,7 @@ public void start() throws LifecycleException { } return; } - if( ! initialized ) + if (!initialized) init(); lifecycle.fireLifecycleEvent(START_EVENT, null); @@ -1167,30 +960,27 @@ public void start() throws LifecycleException { log.log(Level.FINEST, "Force random number initialization completed"); if (store == null) - log.log(Level.SEVERE, LogFacade.NO_STORE_CONFIG_EXCEPTION); + log.log(SEVERE, LogFacade.NO_STORE_CONFIG_EXCEPTION); else if (store instanceof Lifecycle) - ((Lifecycle)store).start(); + ((Lifecycle) store).start(); } - /** - * Gracefully terminate the active use of the public methods of this - * component. This method should be the last one called on a given - * instance of this component. + * Gracefully terminate the active use of the public methods of this component. This method should be the last one + * called on a given instance of this component. * - * @exception LifecycleException if this component detects a fatal error - * that needs to be reported + * @exception LifecycleException if this component detects a fatal error that needs to be reported */ - public void stop() throws LifecycleException { - + @Override + public void stop() throws LifecycleException { if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Stopping"); // Validate and update our current component state if (!isStarted()) { if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO,LogFacade. MANAGER_NOT_STARTED_INFO); + log.log(Level.INFO, LogFacade.MANAGER_NOT_STARTED_INFO); } return; } @@ -1212,25 +1002,24 @@ public void stop() throws LifecycleException { } if (getStore() != null && getStore() instanceof Lifecycle) - ((Lifecycle)getStore()).stop(); + ((Lifecycle) getStore()).stop(); // Require a new random number generator if we are restarted resetRandom(); - if( initialized ) + if (initialized) destroy(); } - // ----------------------------------------- PropertyChangeListener Methods - /** * Process property change events from our associated Context. * * @param event The property change event that has occurred */ + @Override public void propertyChange(PropertyChangeEvent event) { // Validate the source of this event @@ -1240,19 +1029,16 @@ public void propertyChange(PropertyChangeEvent event) { // Process a relevant property change if (event.getPropertyName().equals("sessionTimeout")) { try { - setMaxInactiveIntervalSeconds - ( ((Integer) event.getNewValue()).intValue()*60 ); + setMaxInactiveIntervalSeconds(((Integer) event.getNewValue()).intValue() * 60); } catch (NumberFormatException e) { - log.log(Level.SEVERE, LogFacade.INVALID_SESSION_TIMEOUT_SETTING_EXCEPTION, event.getNewValue().toString()); + log.log(SEVERE, LogFacade.INVALID_SESSION_TIMEOUT_SETTING_EXCEPTION, event.getNewValue().toString()); } } } - // -------------------------------------------------------- Private Methods - /** * Swap idle sessions out to Store if they are idle too long. */ @@ -1273,11 +1059,11 @@ protected void processMaxIdleSwaps() { if (!session.isValid()) continue; int timeIdle = // Truncate, do not round up - (int) ((timeNow - session.getLastAccessedTime()) / 1000L); + (int) ((timeNow - session.getLastAccessedTime()) / 1000L); if (timeIdle > maxIdleSwap && timeIdle > minIdleSwap) { if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, LogFacade.SWAPPING_SESSION_TO_STORE, new Object[] {session.getIdInternal(), - Integer.valueOf(timeIdle)}); + log.log(Level.FINE, LogFacade.SWAPPING_SESSION_TO_STORE, + new Object[] { session.getIdInternal(), Integer.valueOf(timeIdle) }); } try { swapOut(session); @@ -1290,10 +1076,8 @@ protected void processMaxIdleSwaps() { } - /** - * Swap idle sessions out to Store if too many are active - * Hercules: modified method + * Swap idle sessions out to Store if too many are active Hercules: modified method */ protected void processMaxActiveSwaps() { @@ -1306,7 +1090,7 @@ protected void processMaxActiveSwaps() { if (getMaxActiveSessions() >= sessions.length) return; - if(log.isLoggable(Level.FINE)) { + if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, LogFacade.TOO_MANY_ACTIVE_SESSION, Integer.valueOf(sessions.length)); } int toswap = sessions.length - getMaxActiveSessions(); @@ -1314,14 +1098,14 @@ protected void processMaxActiveSwaps() { for (int i = 0; i < sessions.length && toswap > 0; i++) { int timeIdle = // Truncate, do not round up - (int) ((timeNow - sessions[i].getLastAccessedTime()) / 1000L); + (int) ((timeNow - sessions[i].getLastAccessedTime()) / 1000L); if (timeIdle > minIdleSwap) { StandardSession session = (StandardSession) sessions[i]; - //skip the session if it cannot be locked - if(session.lockBackground()) { - if(log.isLoggable(Level.FINE)) { - log.log(Level.FINE, LogFacade.SWAP_OUT_SESSION, new Object[] {session.getIdInternal(), - Integer.valueOf(timeIdle)}); + // skip the session if it cannot be locked + if (session.lockBackground()) { + if (log.isLoggable(Level.FINE)) { + log.log(Level.FINE, LogFacade.SWAP_OUT_SESSION, + new Object[] { session.getIdInternal(), Integer.valueOf(timeIdle) }); } try { swapOut(session); @@ -1341,10 +1125,8 @@ protected void processMaxActiveSwaps() { } - /** - * Back up idle sessions. - * Hercules: modified method + * Back up idle sessions. Hercules: modified method */ protected void processMaxIdleBackups() { @@ -1361,13 +1143,13 @@ protected void processMaxIdleBackups() { if (!session.isValid()) continue; int timeIdle = // Truncate, do not round up - (int) ((timeNow - session.getLastAccessedTime()) / 1000L); + (int) ((timeNow - session.getLastAccessedTime()) / 1000L); if (timeIdle > maxIdleBackup) { - //if session cannot be background locked then skip it + // if session cannot be background locked then skip it if (session.lockBackground()) { if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, LogFacade.BACKUP_SESSION_TO_STORE, new Object[] {session.getIdInternal(), - Integer.valueOf(timeIdle)}); + log.log(Level.FINE, LogFacade.BACKUP_SESSION_TO_STORE, + new Object[] { session.getIdInternal(), Integer.valueOf(timeIdle) }); } try { writeSession(session); @@ -1388,9 +1170,8 @@ protected void processMaxIdleBackups() { } public String getMonitorAttributeValues() { - //FIXME if desired for monitoring 'file' + // FIXME if desired for monitoring 'file' return ""; } - } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardManager.java b/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardManager.java index 0e019a44523..97d98bdfe05 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardManager.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardManager.java @@ -20,58 +20,64 @@ package org.apache.catalina.session; -import org.apache.catalina.*; -import org.apache.catalina.core.StandardContext; -import org.apache.catalina.security.SecurityUtil; -import org.apache.catalina.util.LifecycleSupport; - import jakarta.servlet.ServletContext; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -import java.io.*; -import java.security.AccessController; -import java.security.PrivilegedActionException; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; import java.security.PrivilegedExceptionAction; import java.text.MessageFormat; import java.util.List; import java.util.logging.Level; +import org.apache.catalina.Container; +import org.apache.catalina.Context; +import org.apache.catalina.Lifecycle; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.LifecycleListener; +import org.apache.catalina.LogFacade; +import org.apache.catalina.Session; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.util.LifecycleSupport; /** - * Standard implementation of the Manager interface that provides - * simple session persistence across restarts of this component (such as - * when the entire server is shut down and restarted, or when a particular - * web application is reloaded. + * Standard implementation of the Manager interface that provides simple session persistence across restarts of + * this component (such as when the entire server is shut down and restarted, or when a particular web application is + * reloaded. *

- * IMPLEMENTATION NOTE: Correct behavior of session storing and - * reloading depends upon external calls to the start() and - * stop() methods of this class at the correct times. + * IMPLEMENTATION NOTE: Correct behavior of session storing and reloading depends upon external calls to the + * start() and stop() methods of this class at the correct times. * * @author Craig R. McClanahan * @author Jean-Francois Arcand * @version $Revision: 1.14.6.2 $ $Date: 2008/04/17 18:37:20 $ */ -public class StandardManager - extends ManagerBase - implements Lifecycle, PropertyChangeListener { +public class StandardManager extends ManagerBase implements Lifecycle, PropertyChangeListener { // ---------------------------------------------------- Security Classes - private class PrivilegedDoLoadFromFile - implements PrivilegedExceptionAction { + private class PrivilegedDoLoadFromFile implements PrivilegedExceptionAction { PrivilegedDoLoadFromFile() { // NOOP } @Override - public Void run() throws Exception{ - doLoadFromFile(); - return null; + public Void run() throws Exception { + doLoadFromFile(); + return null; } } - private class PrivilegedDoUnload - implements PrivilegedExceptionAction { + private class PrivilegedDoUnload implements PrivilegedExceptionAction { private final boolean expire; private final boolean isShutdown; @@ -82,74 +88,60 @@ private class PrivilegedDoUnload } @Override - public Void run() throws Exception{ + public Void run() throws Exception { doUnload(expire, isShutdown); return null; } } - // ----------------------------------------------------- Instance Variables - /** * The descriptive information about this implementation. */ private static final String info = "StandardManager/1.0"; - /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); - /** * The maximum number of active Sessions allowed, or -1 for no limit. */ private int maxActiveSessions = -1; - /** * The descriptive name of this Manager implementation (for logging). */ protected static final String name = "StandardManager"; - /** - * Path name of the disk file in which active sessions are saved - * when we stop, and from which these sessions are loaded when we start. - * A null value indicates that no persistence is desired. - * If this pathname is relative, it will be resolved against the - * temporary working directory provided by our context, available via - * the jakarta.servlet.context.tempdir context attribute. + * Path name of the disk file in which active sessions are saved when we stop, and from which these sessions are loaded + * when we start. A null value indicates that no persistence is desired. If this pathname is relative, it + * will be resolved against the temporary working directory provided by our context, available via the + * jakarta.servlet.context.tempdir context attribute. */ private String pathname = "SESSIONS.ser"; - /** * Has this component been started yet? */ private boolean started = false; - // START SJSAS 6359401 /* * The absolute path name of the file where sessions are persisted. */ private String absPathName; - // END SJSAS 6359401 - - long processingTime=0; + long processingTime = 0; // ------------------------------------------------------------- Properties - /** - * Set the Container with which this Manager has been associated. If - * it is a Context (the usual case), listen for changes to the session - * timeout property. + * Set the Container with which this Manager has been associated. If it is a Context (the usual case), listen for + * changes to the session timeout property. * * @param container The associated Container */ @@ -166,17 +158,14 @@ public void setContainer(Container container) { // Register with the new Container (if any) if ((this.container != null) && (this.container instanceof Context)) { - setMaxInactiveIntervalSeconds - ( ((Context) this.container).getSessionTimeout()*60 ); + setMaxInactiveIntervalSeconds(((Context) this.container).getSessionTimeout() * 60); ((Context) this.container).addPropertyChangeListener(this); } } - /** - * Return descriptive information about this Manager implementation and - * the corresponding version number, in the format + * Return descriptive information about this Manager implementation and the corresponding version number, in the format * <description>/<version>. */ @Override @@ -184,41 +173,32 @@ public String getInfo() { return info; } - /** - * Return the maximum number of active Sessions allowed, or -1 for - * no limit. + * Return the maximum number of active Sessions allowed, or -1 for no limit. */ public int getMaxActiveSessions() { return maxActiveSessions; } - public long getProcessingTime() { return processingTime; } - public void setProcessingTime(long processingTime) { this.processingTime = processingTime; } - /** - * Set the maximum number of active Sessions allowed, or -1 for - * no limit. + * Set the maximum number of active Sessions allowed, or -1 for no limit. * * @param max The new maximum number of sessions */ public void setMaxActiveSessions(int max) { int oldMaxActiveSessions = this.maxActiveSessions; this.maxActiveSessions = max; - support.firePropertyChange("maxActiveSessions", - Integer.valueOf(oldMaxActiveSessions), - Integer.valueOf(this.maxActiveSessions)); + support.firePropertyChange("maxActiveSessions", Integer.valueOf(oldMaxActiveSessions), Integer.valueOf(this.maxActiveSessions)); } - /** * Return the descriptive short name of this Manager implementation. */ @@ -227,7 +207,6 @@ public String getName() { return name; } - /** * Return the session persistence pathname, if any. */ @@ -235,10 +214,9 @@ public String getPathname() { return pathname; } - /** - * Set the session persistence pathname to the specified value. If no - * persistence support is desired, set the pathname to null. + * Set the session persistence pathname to the specified value. If no persistence support is desired, set the pathname + * to null. * * @param pathname New session persistence pathname */ @@ -248,28 +226,21 @@ public void setPathname(String pathname) { support.firePropertyChange("pathname", oldPathname, this.pathname); } - // --------------------------------------------------------- Public Methods /** - * Construct and return a new session object, based on the default - * settings specified by this Manager's properties. The session - * id will be assigned by this method, and available via the getId() - * method of the returned session. If a new session cannot be created - * for any reason, return null. + * Construct and return a new session object, based on the default settings specified by this Manager's properties. The + * session id will be assigned by this method, and available via the getId() method of the returned session. If a new + * session cannot be created for any reason, return null. * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * @exception IllegalStateException if a new session cannot be instantiated for any reason */ @Override public Session createSession() { - if ((maxActiveSessions >= 0) && - (sessions.size() >= maxActiveSessions)) { + if ((maxActiveSessions >= 0) && (sessions.size() >= maxActiveSessions)) { rejectedSessions++; - ((StandardContext)container).sessionRejectedEvent( - maxActiveSessions); - throw new IllegalStateException - (rb.getString(LogFacade.TOO_MANY_ACTIVE_SESSION_EXCEPTION)); + ((StandardContext) container).sessionRejectedEvent(maxActiveSessions); + throw new IllegalStateException(rb.getString(LogFacade.TOO_MANY_ACTIVE_SESSION_EXCEPTION)); } return (super.createSession()); @@ -277,28 +248,22 @@ public Session createSession() { // START S1AS8PE 4817642 /** - * Construct and return a new session object, based on the default - * settings specified by this Manager's properties, using the specified - * session id. + * Construct and return a new session object, based on the default settings specified by this Manager's properties, + * using the specified session id. * - * IMPLEMENTATION NOTE: This method must be kept in sync with the - * createSession method that takes no arguments. + * IMPLEMENTATION NOTE: This method must be kept in sync with the createSession method that takes no arguments. * * @param sessionId the session id to assign to the new session * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * @exception IllegalStateException if a new session cannot be instantiated for any reason * - * @return the new session, or null if a session with the - * requested id already exists + * @return the new session, or null if a session with the requested id already exists */ @Override public Session createSession(String sessionId) { - if ((maxActiveSessions >= 0) && - (sessions.size() >= maxActiveSessions)) { + if ((maxActiveSessions >= 0) && (sessions.size() >= maxActiveSessions)) { rejectedSessions++; - throw new IllegalStateException - (rb.getString(LogFacade.TOO_MANY_ACTIVE_SESSION_EXCEPTION)); + throw new IllegalStateException(rb.getString(LogFacade.TOO_MANY_ACTIVE_SESSION_EXCEPTION)); } return (super.createSession(sessionId)); @@ -314,7 +279,6 @@ public void release() { clearStore(); } - // START SJSAS 6359401 /* * Deletes the persistent session storage file. @@ -325,47 +289,23 @@ public void clearStore() { deleteFile(file); } } - // END SJSAS 6359401 - /** - * Loads any currently active sessions that were previously unloaded - * to the appropriate persistence mechanism, if any. If persistence is not - * supported, this method returns without doing anything. + * Loads any currently active sessions that were previously unloaded to the appropriate persistence mechanism, if any. + * If persistence is not supported, this method returns without doing anything. * - * @exception ClassNotFoundException if a serialized class cannot be - * found during the reload + * @exception ClassNotFoundException if a serialized class cannot be found during the reload * @exception IOException if a read error occurs */ @Override public void load() throws ClassNotFoundException, IOException { - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - AccessController.doPrivileged(new PrivilegedDoLoadFromFile()); - } catch (PrivilegedActionException ex){ - Exception exception = ex.getException(); - if (exception instanceof ClassNotFoundException){ - throw (ClassNotFoundException)exception; - } else if (exception instanceof IOException) { - throw (IOException)exception; - } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Unreported exception in load() " - + exception); - } - } - } else { - doLoadFromFile(); - } + doLoadFromFile(); } - /** - * Loads any currently active sessions that were previously unloaded - * to file + * Loads any currently active sessions that were previously unloaded to file * - * @exception ClassNotFoundException if a serialized class cannot be - * found during the reload + * @exception ClassNotFoundException if a serialized class cannot be found during the reload * @exception IOException if a read error occurs */ private void doLoadFromFile() throws ClassNotFoundException, IOException { @@ -413,17 +353,15 @@ private void deleteFile(File file) { } /* - * Reads any sessions from the given input stream, and initializes the - * cache of active sessions with them. + * Reads any sessions from the given input stream, and initializes the cache of active sessions with them. * * @param is the input stream from which to read the sessions * - * @exception ClassNotFoundException if a serialized class cannot be - * found during the reload + * @exception ClassNotFoundException if a serialized class cannot be found during the reload + * * @exception IOException if a read error occurs */ - public void readSessions(InputStream is) - throws ClassNotFoundException, IOException { + public void readSessions(InputStream is) throws ClassNotFoundException, IOException { // Initialize our internal data structures sessions.clear(); @@ -432,20 +370,19 @@ public void readSessions(InputStream is) try { BufferedInputStream bis = new BufferedInputStream(is); if (container != null) { - ois = ((StandardContext)container).createObjectInputStream(bis); + ois = ((StandardContext) container).createObjectInputStream(bis); } else { ois = new ObjectInputStream(bis); } } catch (IOException ioe) { - String msg = MessageFormat.format(rb.getString(LogFacade.LOADING_PERSISTED_SESSION_IO_EXCEPTION), - ioe); + String msg = MessageFormat.format(rb.getString(LogFacade.LOADING_PERSISTED_SESSION_IO_EXCEPTION), ioe); log.log(Level.SEVERE, msg, ioe); if (ois != null) { try { ois.close(); } catch (IOException f) { - // Ignore + // Ignore } ois = null; } @@ -460,15 +397,13 @@ public void readSessions(InputStream is) log.log(Level.FINE, "Loading " + n + " persisted sessions"); } for (int i = 0; i < n; i++) { - StandardSession session = - StandardSession.deserialize(ois, this); + StandardSession session = StandardSession.deserialize(ois, this); session.setManager(this); sessions.put(session.getIdInternal(), session); session.activate(); } } catch (ClassNotFoundException e) { - String msg = MessageFormat.format(rb.getString(LogFacade.CLASS_NOT_FOUND_EXCEPTION), - e); + String msg = MessageFormat.format(rb.getString(LogFacade.CLASS_NOT_FOUND_EXCEPTION), e); log.log(Level.SEVERE, msg, e); if (ois != null) { try { @@ -480,9 +415,8 @@ public void readSessions(InputStream is) } throw e; } catch (IOException e) { - String msg = MessageFormat.format(rb.getString(LogFacade.LOADING_PERSISTED_SESSION_IO_EXCEPTION), - e); - log.log(Level.SEVERE, msg, e); + String msg = MessageFormat.format(rb.getString(LogFacade.LOADING_PERSISTED_SESSION_IO_EXCEPTION), e); + log.log(Level.SEVERE, msg, e); if (ois != null) { try { ois.close(); @@ -505,11 +439,9 @@ public void readSessions(InputStream is) } } - /** - * Save any currently active sessions in the appropriate persistence - * mechanism, if any. If persistence is not supported, this method - * returns without doing anything. + * Save any currently active sessions in the appropriate persistence mechanism, if any. If persistence is not supported, + * this method returns without doing anything. * * @exception IOException if an input/output error occurs */ @@ -518,7 +450,6 @@ public void unload() throws IOException { unload(true, false); } - /** * Writes all active sessions to the given output stream. * @@ -530,72 +461,52 @@ public void writeSessions(OutputStream os) throws IOException { writeSessions(os, true); } - /** - * Save any currently active sessions in the appropriate persistence - * mechanism, if any. If persistence is not supported, this method - * returns without doing anything. + * Save any currently active sessions in the appropriate persistence mechanism, if any. If persistence is not supported, + * this method returns without doing anything. * - * @doExpire true if the unloaded sessions are to be expired, false - * otherwise - * @param isShutdown true if this manager is being stopped as part of a - * domain shutdown (as opposed to an undeployment), and false otherwise + * @doExpire true if the unloaded sessions are to be expired, false otherwise + * @param isShutdown true if this manager is being stopped as part of a domain shutdown (as opposed to an undeployment), + * and false otherwise * * @exception IOException if an input/output error occurs */ protected void unload(boolean doExpire, boolean isShutdown) throws IOException { - if (SecurityUtil.isPackageProtectionEnabled()){ - try { - AccessController.doPrivileged( - new PrivilegedDoUnload(doExpire, isShutdown)); - } catch (PrivilegedActionException ex){ - Exception exception = ex.getException(); - if (exception instanceof IOException){ - throw (IOException)exception; - } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Unreported exception in unLoad() " + exception); - } - } - } else { - doUnload(doExpire, isShutdown); - } + doUnload(doExpire, isShutdown); } - /** * Saves any currently active sessions to file. * - * @doExpire true if the unloaded sessions are to be expired, false - * otherwise + * @doExpire true if the unloaded sessions are to be expired, false otherwise * * @exception IOException if an input/output error occurs */ private void doUnload(boolean doExpire, boolean isShutdown) throws IOException { - if(isShutdown) { - if(log.isLoggable(Level.FINE)) { + if (isShutdown) { + if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Unloading persisted sessions"); } // Open an output stream to the specified pathname, if any File file = file(); - if(file == null || !isDirectoryValidFor(file.getAbsolutePath())) { + if (file == null || !isDirectoryValidFor(file.getAbsolutePath())) { return; } - if(log.isLoggable(Level.FINE)) { + if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, LogFacade.SAVING_PERSISTED_SESSION_PATH, pathname); } FileOutputStream fos = null; try { fos = new FileOutputStream(file.getAbsolutePath()); writeSessions(fos, doExpire); - if(log.isLoggable(Level.FINE)) { + if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Unloading complete"); } - } catch(IOException ioe) { - if(fos != null) { + } catch (IOException ioe) { + if (fos != null) { try { fos.close(); - } catch(IOException f) { + } catch (IOException f) { } fos = null; @@ -603,10 +514,10 @@ private void doUnload(boolean doExpire, boolean isShutdown) throws IOException { throw ioe; } finally { try { - if(fos != null) { + if (fos != null) { fos.close(); } - } catch(IOException f) { + } catch (IOException f) { // ignore } } @@ -656,7 +567,6 @@ public void writeSessions(OutputStream os, boolean doExpire) throws IOException } } - private ObjectOutputStream wrapStream(OutputStream os) throws IOException { if (container == null) { return new ObjectOutputStream(new BufferedOutputStream(os)); @@ -665,26 +575,21 @@ private ObjectOutputStream wrapStream(OutputStream os) throws IOException { } } - /** - * Check if the directory for this full qualified file - * exists and is valid - * Hercules: added method + * Check if the directory for this full qualified file exists and is valid Hercules: added method */ private boolean isDirectoryValidFor(String fullPathFileName) { int lastSlashIdx = fullPathFileName.lastIndexOf(File.separator); - if(lastSlashIdx == -1) { + if (lastSlashIdx == -1) { return false; } String result = fullPathFileName.substring(0, lastSlashIdx); - //System.out.println("PATH name = " + result); + // System.out.println("PATH name = " + result); return new File(result).isDirectory(); } - // ------------------------------------------------------ Lifecycle Methods - /** * Add a lifecycle event listener to this component. * @@ -695,17 +600,14 @@ public void addLifecycleListener(LifecycleListener listener) { lifecycle.addLifecycleListener(listener); } - /** - * Gets the (possibly empty) list of lifecycle listeners - * associated with this StandardManager. + * Gets the (possibly empty) list of lifecycle listeners associated with this StandardManager. */ @Override public List findLifecycleListeners() { return lifecycle.findLifecycleListeners(); } - /** * Remove a lifecycle event listener from this component. * @@ -717,17 +619,15 @@ public void removeLifecycleListener(LifecycleListener listener) { } /** - * Prepare for the beginning of active use of the public methods of this - * component. This method should be called after configure(), - * and before any of the public methods of the component are utilized. + * Prepare for the beginning of active use of the public methods of this component. This method should be called after + * configure(), and before any of the public methods of the component are utilized. * - * @exception LifecycleException if this component detects a fatal error - * that prevents this component from being used + * @exception LifecycleException if this component detects a fatal error that prevents this component from being used */ @Override public void start() throws LifecycleException { - if( ! initialized ) { + if (!initialized) { init(); } @@ -754,8 +654,7 @@ public void start() throws LifecycleException { try { load(); } catch (Throwable t) { - log.log(Level.SEVERE, - LogFacade.LOADING_SESSIONS_EXCEPTION, t); + log.log(Level.SEVERE, LogFacade.LOADING_SESSIONS_EXCEPTION, t); } } @@ -767,14 +666,11 @@ public final boolean isStarted() { return started; } - /** - * Gracefully terminate the active use of the public methods of this - * component. This method should be the last one called on a given - * instance of this component. + * Gracefully terminate the active use of the public methods of this component. This method should be the last one + * called on a given instance of this component. * - * @exception LifecycleException if this component detects a fatal error - * that needs to be reported + * @exception LifecycleException if this component detects a fatal error that needs to be reported */ @Override public void stop() throws LifecycleException { @@ -782,15 +678,13 @@ public void stop() throws LifecycleException { } /** - * Gracefully terminate the active use of the public methods of this - * component. This method should be the last one called on a given - * instance of this component. + * Gracefully terminate the active use of the public methods of this component. This method should be the last one + * called on a given instance of this component. * - * @param isShutdown true if this manager is being stopped as part of a - * domain shutdown (as opposed to an undeployment), and false otherwise + * @param isShutdown true if this manager is being stopped as part of a domain shutdown (as opposed to an undeployment), + * and false otherwise * - * @exception LifecycleException if this component detects a fatal error - * that needs to be reported + * @exception LifecycleException if this component detects a fatal error that needs to be reported */ public void stop(boolean isShutdown) throws LifecycleException { @@ -832,15 +726,13 @@ public void stop(boolean isShutdown) throws LifecycleException { // Require a new random number generator if we are restarted resetRandom(); - if( initialized ) { + if (initialized) { destroy(); } } - // ----------------------------------------- PropertyChangeListener Methods - /** * Process property change events from our associated Context. * @@ -857,31 +749,23 @@ public void propertyChange(PropertyChangeEvent event) { // Process a relevant property change if ("sessionTimeout".equals(event.getPropertyName())) { try { - setMaxInactiveIntervalSeconds - ((Integer) event.getNewValue() *60 ); + setMaxInactiveIntervalSeconds((Integer) event.getNewValue() * 60); } catch (NumberFormatException e) { - log.log(Level.SEVERE, LogFacade.INVALID_SESSION_TIMEOUT_SETTING_EXCEPTION, - event.getNewValue().toString()); + log.log(Level.SEVERE, LogFacade.INVALID_SESSION_TIMEOUT_SETTING_EXCEPTION, event.getNewValue().toString()); } } } - // -------------------------------------------------------- Private Methods - /** - * Return a File object representing the pathname to our - * persistence file, if any. + * Return a File object representing the pathname to our persistence file, if any. */ private File file() { - - // START SJSAS 6359401 if (absPathName != null) { return new File(absPathName); } - // END SJSAS 6359401 if ((pathname == null) || (pathname.length() == 0)) { return (null); @@ -889,32 +773,25 @@ private File file() { File file = new File(pathname); if (!file.isAbsolute()) { if (container instanceof Context) { - ServletContext servletContext = - ((Context) container).getServletContext(); - File tempdir = (File) - servletContext.getAttribute(ServletContext.TEMPDIR); + ServletContext servletContext = ((Context) container).getServletContext(); + File tempdir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (tempdir != null) { file = new File(tempdir, pathname); } } } - // START SJSAS 6359401 if (file != null) { absPathName = file.getAbsolutePath(); } - // END SJSAS 6359401 - - return (file); + return file; } - /** * Invalidate all sessions that have expired. */ public void processExpires() { - long timeNow = System.currentTimeMillis(); Session[] sessions = findSessions(); @@ -932,7 +809,7 @@ public void processExpires() { } long timeEnd = System.currentTimeMillis(); - processingTime += ( timeEnd - timeNow ); + processingTime += (timeEnd - timeNow); } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardSession.java b/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardSession.java index ddfee7fcd39..0b564b49e04 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardSession.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/session/StandardSession.java @@ -20,45 +20,60 @@ package org.apache.catalina.session; -import com.sun.enterprise.spi.io.BaseIndirectlySerializable; import static com.sun.logging.LogCleanerUtil.neutralizeForLog; -import org.apache.catalina.*; -import org.apache.catalina.core.StandardContext; -import org.apache.catalina.security.SecurityUtil; -import org.apache.catalina.util.Enumerator; -import org.apache.tomcat.util.security.PrivilegedSetTccl; +import com.sun.enterprise.spi.io.BaseIndirectlySerializable; import jakarta.servlet.ServletContext; -import jakarta.servlet.http.*; -import java.io.*; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSessionActivationListener; +import jakarta.servlet.http.HttpSessionAttributeListener; +import jakarta.servlet.http.HttpSessionBindingEvent; +import jakarta.servlet.http.HttpSessionBindingListener; +import jakarta.servlet.http.HttpSessionEvent; +import jakarta.servlet.http.HttpSessionIdListener; +import jakarta.servlet.http.HttpSessionListener; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; import java.lang.reflect.Method; -import java.security.AccessController; import java.security.Principal; -import java.security.PrivilegedAction; import java.text.MessageFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.EventListener; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; -//end HERCULES:add - - +import org.apache.catalina.ContainerEvent; +import org.apache.catalina.Context; +import org.apache.catalina.Globals; +import org.apache.catalina.LogFacade; +import org.apache.catalina.Manager; +import org.apache.catalina.Session; +import org.apache.catalina.SessionEvent; +import org.apache.catalina.SessionListener; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.util.Enumerator; /** - * Standard implementation of the Session interface. This object is - * serializable, so that it can be stored in persistent storage or transferred - * to a different JVM for distributable session support. + * Standard implementation of the Session interface. This object is serializable, so that it can be stored in + * persistent storage or transferred to a different JVM for distributable session support. *

- * IMPLEMENTATION NOTE: An instance of this class represents both the - * internal (Session) and application level (HttpSession) view of the session. - * However, because the class itself is not declared public, Java logic outside - * of the org.apache.catalina.session package cannot cast an - * HttpSession view of this instance back to a Session view. + * IMPLEMENTATION NOTE: An instance of this class represents both the internal (Session) and application level + * (HttpSession) view of the session. However, because the class itself is not declared public, Java logic outside of + * the org.apache.catalina.session package cannot cast an HttpSession view of this instance back to a + * Session view. *

- * IMPLEMENTATION NOTE: If you add fields to this class, you must - * make sure that you carry them over in the read/writeObject methods so - * that this class is properly serialized. + * IMPLEMENTATION NOTE: If you add fields to this class, you must make sure that you carry them over in the + * read/writeObject methods so that this class is properly serialized. * * @author Craig R. McClanahan * @author Sean Legassick @@ -66,8 +81,7 @@ * @version $Revision: 1.33 $ $Date: 2007/03/12 21:41:52 $ */ -public class StandardSession - implements HttpSession, Session, Serializable { +public class StandardSession implements HttpSession, Session, Serializable { private static final Logger log = LogFacade.getLogger(); @@ -89,35 +103,29 @@ public StandardSession(Manager manager) { } } - // ----------------------------------------------------- Class Variables - /** * Type array. */ protected static final String EMPTY_ARRAY[] = new String[0]; /** - * The dummy attribute value serialized when a NotSerializableException is - * encountered in writeObject(). + * The dummy attribute value serialized when a NotSerializableException is encountered in writeObject(). */ - protected static final String NOT_SERIALIZED = - "___NOT_SERIALIZABLE_EXCEPTION___"; + protected static final String NOT_SERIALIZED = "___NOT_SERIALIZABLE_EXCEPTION___"; - //HERCULES:add + // HERCULES:add /** - * The string used in the name for setAttribute and removeAttribute - * to signify on-demand sync + * The string used in the name for setAttribute and removeAttribute to signify on-demand sync */ protected static final String SYNC_STRING = "com.sun.sync"; - //end HERCULES:add + // end HERCULES:add /** * The method signature for the fireContainerEvent method. */ - static final Class containerEventTypes[] = - { String.class, Object.class }; + static final Class containerEventTypes[] = { String.class, Object.class }; /** * Descriptive information describing this Session implementation. @@ -127,20 +135,16 @@ public StandardSession(Manager manager) { /** * Set of attribute names which are not allowed to be persisted. */ - private static final String[] excludedAttributes = { - Globals.SUBJECT_ATTR - }; + private static final String[] excludedAttributes = { Globals.SUBJECT_ATTR }; /** - * Used for serialized format versioning. - * 1 = first version where this is being tracked. + * Used for serialized format versioning. 1 = first version where this is being tracked. * - * NOTE: You must increment this version whenever any changes are made - * to the serialized representation of this class between releases + * NOTE: You must increment this version whenever any changes are made to the serialized representation of this class + * between releases */ private static final Short SERIALIZED_FORM_VERSION = Short.valueOf("1"); - // ----------------------------------------------------- Instance Variables /** @@ -151,12 +155,12 @@ public StandardSession(Manager manager) { /** * The BEKEY of this session, or null. * - *

The BEKEY is used by the Converged Loadbalancer (CLB) in DCR mode - * for loadbalancing purposes, and supplied to the web container in the - * form of a request header. + *

+ * The BEKEY is used by the Converged Loadbalancer (CLB) in DCR mode for loadbalancing purposes, and supplied to the web + * container in the form of a request header. * - *

See https://sailfin.dev.java.net/issues/show_bug.cgi?id=1647 - * for additional details + *

+ * See https://sailfin.dev.java.net/issues/show_bug.cgi?id=1647 for additional details */ private String beKey; @@ -166,44 +170,38 @@ public StandardSession(Manager manager) { protected Map attributes = new ConcurrentHashMap(); /** - * The authentication type used to authenticate our cached Principal, - * if any. NOTE: This value is not included in the serialized - * version of this object. + * The authentication type used to authenticate our cached Principal, if any. NOTE: This value is not included in the + * serialized version of this object. */ protected transient String authType = null; /** - * The java.lang.Method for the - * fireContainerEvent() method of the - * org.apache.catalina.core.StandardContext method, - * if our Context implementation is of this class. This value is - * computed dynamically the first time it is needed, or after - * a session reload (since it is declared transient). + * The java.lang.Method for the fireContainerEvent() method of the + * org.apache.catalina.core.StandardContext method, if our Context implementation is of this class. This + * value is computed dynamically the first time it is needed, or after a session reload (since it is declared + * transient). */ protected transient Method containerEventMethod = null; /** - * The time this session was created, in milliseconds since midnight, - * January 1, 1970 GMT. + * The time this session was created, in milliseconds since midnight, January 1, 1970 GMT. */ protected long creationTime = 0L; /** - * The debugging detail level for this component. NOTE: This value - * is not included in the serialized version of this object. + * The debugging detail level for this component. NOTE: This value is not included in the serialized version of this + * object. */ protected transient int debug = 0; /** - * We are currently processing a session expiration, so bypass - * certain IllegalStateException tests. NOTE: This value is not - * included in the serialized version of this object. + * We are currently processing a session expiration, so bypass certain IllegalStateException tests. NOTE: This value is + * not included in the serialized version of this object. */ protected transient boolean expiring = false; /** - * The facade associated with this session. NOTE: This value is not - * included in the serialized version of this object. + * The facade associated with this session. NOTE: This value is not included in the serialized version of this object. */ protected transient StandardSessionFacade facade = null; @@ -220,8 +218,7 @@ public StandardSession(Manager manager) { /** * The session event listeners for this Session. */ - protected transient ArrayList listeners = - new ArrayList(); + protected transient ArrayList listeners = new ArrayList(); /** * The Manager with which this Session is associated. @@ -234,9 +231,8 @@ public StandardSession(Manager manager) { protected transient StandardContext context = null; /** - * The maximum time interval, in seconds, between client requests before - * the servlet container may invalidate this session. A negative time - * indicates that the session should never time out. + * The maximum time interval, in seconds, between client requests before the servlet container may invalidate this + * session. A negative time indicates that the session should never time out. */ protected int maxInactiveInterval = -1; @@ -251,18 +247,14 @@ public StandardSession(Manager manager) { protected boolean isValid = false; /** - * Internal notes associated with this session by Catalina components - * and event listeners. IMPLEMENTATION NOTE: This object is - * not saved and restored across session serializations! + * Internal notes associated with this session by Catalina components and event listeners. IMPLEMENTATION NOTE: + * This object is not saved and restored across session serializations! */ protected transient Map notes = new Hashtable(); /** - * The authenticated Principal associated with this session, if any. - // START SJSWS 6371339 - // * IMPLEMENTATION NOTE: This object is not saved and - // * restored across session serializations! - // END SJSWS 6371339 + * The authenticated Principal associated with this session, if any. // START SJSWS 6371339 // * IMPLEMENTATION + * NOTE: This object is not saved and // * restored across session serializations! // END SJSWS 6371339 */ protected transient Principal principal = null; @@ -272,8 +264,7 @@ public StandardSession(Manager manager) { protected long thisAccessedTime = creationTime; /** - * The session version, incremented and used by in-memory-replicating - * session managers + * The session version, incremented and used by in-memory-replicating session managers */ protected AtomicLong version = new AtomicLong(-1); @@ -287,13 +278,10 @@ public StandardSession(Manager manager) { */ protected volatile long ssoVersion = 0L; - // ----------------------------------------------------- Session Properties - /** - * Return the authentication type used to authenticate our cached - * Principal, if any. + * Return the authentication type used to authenticate our cached Principal, if any. */ @Override public String getAuthType() { @@ -302,10 +290,8 @@ public String getAuthType() { } - /** - * Set the authentication type used to authenticate our cached - * Principal, if any. + * Set the authentication type used to authenticate our cached Principal, if any. * * @param authType The new cached authentication type */ @@ -315,10 +301,9 @@ public void setAuthType(String authType) { this.authType = authType; } - /** - * Set the creation time for this session. This method is called by the - * Manager when an existing Session instance is reused. + * Set the creation time for this session. This method is called by the Manager when an existing Session instance is + * reused. * * @param time The new creation time */ @@ -331,7 +316,6 @@ public void setCreationTime(long time) { } - /** * Return the session identifier for this session. */ @@ -342,7 +326,6 @@ public String getId() { } - /** * Return the session identifier for this session. */ @@ -353,7 +336,6 @@ public String getIdInternal() { } - /** * Set the session identifier for this session. * @@ -371,7 +353,6 @@ public void setId(String id) { if (manager != null) manager.add(this); - // Notify interested session event listeners if (oldId == null) { // the session is just created tellNew(); @@ -387,23 +368,17 @@ public void setId(String id) { if (!(eventListener instanceof HttpSessionIdListener)) { continue; } - HttpSessionIdListener listener = (HttpSessionIdListener)eventListener; + HttpSessionIdListener listener = (HttpSessionIdListener) eventListener; try { - fireContainerEvent(context, - "beforeSessionIdChanged", - listener); + fireContainerEvent(context, "beforeSessionIdChanged", listener); if (event == null) { event = new HttpSessionEvent(getSession()); } listener.sessionIdChanged(event, oldId); - fireContainerEvent(context, - "afterSessionIdChanged", - listener); + fireContainerEvent(context, "afterSessionIdChanged", listener); } catch (Throwable t) { try { - fireContainerEvent(context, - "afterSessionIdChanged", - listener); + fireContainerEvent(context, "afterSessionIdChanged", listener); } catch (Exception e) { // Ignore } @@ -413,22 +388,19 @@ public void setId(String id) { } } - -/** + /** * Sets the BEKEY for this session * - *

The BEKEY is used by the Converged Loadbalancer (CLB) in DCR mode - * for loadbalancing purposes, and supplied to the web container in the - * form of a request header. + *

+ * The BEKEY is used by the Converged Loadbalancer (CLB) in DCR mode for loadbalancing purposes, and supplied to the web + * container in the form of a request header. * - * @param beKey the BEKEY for this session, or null if not - * present + * @param beKey the BEKEY for this session, or null if not present */ public void setBeKey(String beKey) { this.beKey = beKey; } - /** * Gets the BEKEY of this session * @@ -438,10 +410,8 @@ public String getBeKey() { return beKey; } - /** - * Sets the id of the SipApplicationSession that is the parent of this - * StandardSession. + * Sets the id of the SipApplicationSession that is the parent of this StandardSession. * * @param id SipApplicationSession id */ @@ -449,19 +419,15 @@ public void setSipApplicationSessionId(String id) { sipAppSessionId = id; } - /** - * Gets the id of the SipApplicationSession that is the parent of this - * StandardSession. + * Gets the id of the SipApplicationSession that is the parent of this StandardSession. * - * @return The SipApplicationSession id, or null if this - * StandardSession does not have any SipApplicationSession parent + * @return The SipApplicationSession id, or null if this StandardSession does not have any SipApplicationSession parent */ public String getSipApplicationSessionId() { return sipAppSessionId; } - /** * Inform the listeners about the new session. * @@ -476,15 +442,12 @@ public void tellNew() { // Notify interested application event listeners for (HttpSessionListener listener : context.getSessionListeners()) { try { - fireContainerEvent(context, "beforeSessionCreated", - listener); + fireContainerEvent(context, "beforeSessionCreated", listener); listener.sessionCreated(event); - fireContainerEvent(context, "afterSessionCreated", - listener); + fireContainerEvent(context, "afterSessionCreated", listener); } catch (Throwable t) { try { - fireContainerEvent(context, "afterSessionCreated", - listener); + fireContainerEvent(context, "afterSessionCreated", listener); } catch (Exception e) { // Ignore } @@ -493,10 +456,8 @@ public void tellNew() { } } - /** - * Return descriptive information about this Session implementation and - * the corresponding version number, in the format + * Return descriptive information about this Session implementation and the corresponding version number, in the format * <description>/<version>. */ @Override @@ -506,48 +467,39 @@ public String getInfo() { } - /** - * Return the last time the client sent a request associated with this - * session, as the number of milliseconds since midnight, January 1, 1970 - * GMT. Actions that your application takes, such as getting or setting - * a value associated with the session, do not affect the access time. + * Return the last time the client sent a request associated with this session, as the number of milliseconds since + * midnight, January 1, 1970 GMT. Actions that your application takes, such as getting or setting a value associated + * with the session, do not affect the access time. */ @Override public long getLastAccessedTime() { - if ( !isValid() ) { - throw new IllegalStateException - ("getLastAccessedTime: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + if (!isValid()) { + throw new IllegalStateException("getLastAccessedTime: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); } return (this.lastAccessedTime); } - // START SJSAS 6470831 /** - * Same as getLastAccessedTime(), except that there is no call to - * isValid(), which may expire the session and cause any subsequent - * session access to throw an IllegalStateException. + * Same as getLastAccessedTime(), except that there is no call to isValid(), which may expire the session and cause any + * subsequent session access to throw an IllegalStateException. */ public long getLastAccessedTimeInternal() { return this.lastAccessedTime; } // END SJSAS 6470831 - /** - * Set the last time the client sent a request associated with this - * session, as the number of milliseconds since midnight, January 1, 1970 - * GMT. Actions that your application takes, such as getting or setting - * a value associated with the session, do not affect the access time. - * HERCULES: added method + * Set the last time the client sent a request associated with this session, as the number of milliseconds since + * midnight, January 1, 1970 GMT. Actions that your application takes, such as getting or setting a value associated + * with the session, do not affect the access time. HERCULES: added method */ public void setLastAccessedTime(long lastAcessedTime) { this.lastAccessedTime = lastAcessedTime; } - /** * Return the Manager within which this Session is valid. */ @@ -558,7 +510,6 @@ public Manager getManager() { } - /** * Set the Manager within which this Session is valid. * @@ -570,11 +521,9 @@ public void setManager(Manager manager) { context = (StandardContext) manager.getContainer(); } - /** - * Return the maximum time interval, in seconds, between client requests - * before the servlet container will invalidate the session. A negative - * time indicates that the session should never time out. + * Return the maximum time interval, in seconds, between client requests before the servlet container will invalidate + * the session. A negative time indicates that the session should never time out. */ @Override public int getMaxInactiveInterval() { @@ -583,11 +532,9 @@ public int getMaxInactiveInterval() { } - /** - * Set the maximum time interval, in seconds, between client requests - * before the servlet container will invalidate the session. A negative - * time indicates that the session should never time out. + * Set the maximum time interval, in seconds, between client requests before the servlet container will invalidate the + * session. A negative time indicates that the session should never time out. * * @param interval The new maximum interval */ @@ -601,7 +548,6 @@ public void setMaxInactiveInterval(int interval) { } - /** * Set the isNew flag for this session. * @@ -614,13 +560,11 @@ public void setNew(boolean isNew) { } - /** - * Return the authenticated Principal that is associated with this Session. - * This provides an Authenticator with a means to cache a - * previously authenticated Principal, and avoid potentially expensive - * Realm.authenticate() calls on every request. If there - * is no current associated Principal, return null. + * Return the authenticated Principal that is associated with this Session. This provides an Authenticator + * with a means to cache a previously authenticated Principal, and avoid potentially expensive + * Realm.authenticate() calls on every request. If there is no current associated Principal, return + * null. */ @Override public Principal getPrincipal() { @@ -629,11 +573,9 @@ public Principal getPrincipal() { } - /** - * Set the authenticated Principal that is associated with this Session. - * This provides an Authenticator with a means to cache a - * previously authenticated Principal, and avoid potentially expensive + * Set the authenticated Principal that is associated with this Session. This provides an Authenticator + * with a means to cache a previously authenticated Principal, and avoid potentially expensive * Realm.authenticate() calls on every request. * * @param principal The new Principal, or null if none @@ -644,44 +586,28 @@ public void setPrincipal(Principal principal) { this.principal = principal; } - /** - * Return the HttpSession for which this object - * is the facade. + * Return the HttpSession for which this object is the facade. */ @Override public HttpSession getSession() { - - if (facade == null){ - if (SecurityUtil.isPackageProtectionEnabled()){ - final StandardSession fsession = this; - facade = AccessController.doPrivileged( - new PrivilegedAction(){ - @Override - public StandardSessionFacade run(){ - return new StandardSessionFacade(fsession); - } - }); - } else { - facade = new StandardSessionFacade(this); - } + if (facade == null) { + facade = new StandardSessionFacade(this); } - return (facade); + return facade; } - /** * Return the isValid flag for this session. */ @Override public boolean isValid() { - - if (this.expiring){ + if (expiring) { return true; } - if (!this.isValid ) { + if (!isValid) { return false; } @@ -689,30 +615,17 @@ public boolean isValid() { return true; } - /* SJSAS 6329289 - if (maxInactiveInterval >= 0) { - long timeNow = System.currentTimeMillis(); - int timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L); - if (timeIdle >= maxInactiveInterval) { - expire(true); - } - } - */ - // START SJSAS 6329289 if (hasExpired()) { expire(true); } - // END SJSAS 6329289 - return (this.isValid); + return isValid; } - // START CR 6363689 @Override public boolean getIsValid() { - return this.isValid; + return isValid; } - // END CR 6363689 /** * Set the isValid flag for this session. @@ -721,23 +634,17 @@ public boolean getIsValid() { */ @Override public void setValid(boolean isValid) { - this.isValid = isValid; - //SJSAS 6406580 START if (!isValid && (getManager() instanceof PersistentManagerBase)) { ((PersistentManagerBase) getManager()).addToInvalidatedSessions(this.id); } - //SJSAS 6406580 END } - // ------------------------------------------------- Session Public Methods - /** - * Update the accessed time information for this session. This method - * should be called by the context when a request comes in for a particular - * session, even if the application does not reference it. + * Update the accessed time information for this session. This method should be called by the context when a request + * comes in for a particular session, even if the application does not reference it. */ @Override public void access() { @@ -747,7 +654,6 @@ public void access() { evaluateIfValid(); } - /** * End the access. */ @@ -756,53 +662,43 @@ public void endAccess() { isNew = false; } - /** * Add a session event listener to this component. */ @Override public void addSessionListener(SessionListener listener) { - synchronized (listeners) { listeners.add(listener); } - } - /** - * Perform the internal processing required to invalidate this session, - * without triggering an exception if the session has already expired. + * Perform the internal processing required to invalidate this session, without triggering an exception if the session + * has already expired. */ @Override public void expire() { - expire(true); - } /** - * Perform the internal processing required to invalidate this session, - * without triggering an exception if the session has already expired. + * Perform the internal processing required to invalidate this session, without triggering an exception if the session + * has already expired. * - * @param notify Should we notify listeners about the demise of - * this session? + * @param notify Should we notify listeners about the demise of this session? */ public void expire(boolean notify) { expire(notify, true); } /** - * Perform the internal processing required to invalidate this session, - * without triggering an exception if the session has already expired. + * Perform the internal processing required to invalidate this session, without triggering an exception if the session + * has already expired. * - * @param notify Should we notify listeners about the demise of - * this session? - * @param persistentRemove should we call store to remove the session - * if available + * @param notify Should we notify listeners about the demise of this session? + * @param persistentRemove should we call store to remove the session if available */ public void expire(boolean notify, boolean persistentRemove) { - // Mark this session as "being expired" if needed if (expiring) return; @@ -821,17 +717,9 @@ public void expire(boolean notify, boolean persistentRemove) { // Make sure the webapp's class loader is set when calling the // listeners ClassLoader oldTccl = null; - if (context.getLoader() != null && - context.getLoader().getClassLoader() != null) { + if (context.getLoader() != null && context.getLoader().getClassLoader() != null) { oldTccl = Thread.currentThread().getContextClassLoader(); - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = new PrivilegedSetTccl( - context.getLoader().getClassLoader()); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader( - context.getLoader().getClassLoader()); - } + Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader()); } try { List listeners = context.getSessionListeners(); @@ -842,18 +730,12 @@ public void expire(boolean notify, boolean persistentRemove) { // Invoke in reverse order of declaration HttpSessionListener listener = listeners.get((len - 1) - i); try { - fireContainerEvent(context, - "beforeSessionDestroyed", - listener); + fireContainerEvent(context, "beforeSessionDestroyed", listener); listener.sessionDestroyed(event); - fireContainerEvent(context, - "afterSessionDestroyed", - listener); + fireContainerEvent(context, "afterSessionDestroyed", listener); } catch (Throwable t) { try { - fireContainerEvent(context, - "afterSessionDestroyed", - listener); + fireContainerEvent(context, "afterSessionDestroyed", listener); } catch (Exception e) { // Ignore } @@ -864,24 +746,17 @@ public void expire(boolean notify, boolean persistentRemove) { } } finally { if (oldTccl != null) { - if (Globals.IS_SECURITY_ENABLED) { - PrivilegedAction pa = - new PrivilegedSetTccl(oldTccl); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(oldTccl); - } + Thread.currentThread().setContextClassLoader(oldTccl); } } setValid(false); /* - * Compute how long this session has been alive, and update - * session manager's related properties accordingly + * Compute how long this session has been alive, and update session manager's related properties accordingly */ long timeNow = System.currentTimeMillis(); - int timeAlive = (int) ((timeNow - creationTime)/1000); + int timeAlive = (int) ((timeNow - creationTime) / 1000); synchronized (manager) { if (timeAlive > manager.getSessionMaxAliveTimeSeconds()) { manager.setSessionMaxAliveTimeSeconds(timeAlive); @@ -890,24 +765,22 @@ public void expire(boolean notify, boolean persistentRemove) { numExpired++; manager.setExpiredSessions(numExpired); int average = manager.getSessionAverageAliveTimeSeconds(); - average = ((average * (numExpired-1)) + timeAlive)/numExpired; + average = ((average * (numExpired - 1)) + timeAlive) / numExpired; manager.setSessionAverageAliveTimeSeconds(average); } // Remove this session from our manager's active sessions - if(persistentRemove) { + if (persistentRemove) { manager.remove(this); } else { - if(manager instanceof PersistentManagerBase) { - ((PersistentManagerBase)manager).remove(this, false); + if (manager instanceof PersistentManagerBase) { + ((PersistentManagerBase) manager).remove(this, false); } } /* - * Mark session as expired *before* removing its attributes, so - * that its HttpSessionBindingListener objects will get an - * IllegalStateException when accessing the session attributes - * from within their valueUnbound() method + * Mark session as expired *before* removing its attributes, so that its HttpSessionBindingListener objects will get an + * IllegalStateException when accessing the session attributes from within their valueUnbound() method */ expiring = false; @@ -927,11 +800,9 @@ public void expire(boolean notify, boolean persistentRemove) { } /** - * Perform the internal processing required to passivate - * this session. + * Perform the internal processing required to passivate this session. */ public void passivate() { - context.sessionPassivatedStartEvent(this); try { @@ -944,7 +815,7 @@ public void passivate() { if (event == null) event = new HttpSessionEvent(getSession()); // FIXME: Should we catch throwables? - ((HttpSessionActivationListener)attribute).sessionWillPassivate(event); + ((HttpSessionActivationListener) attribute).sessionWillPassivate(event); } } } finally { @@ -952,10 +823,8 @@ public void passivate() { } } - /** - * Perform internal processing required to activate this - * session. + * Perform internal processing required to activate this session. */ public void activate() { @@ -971,7 +840,7 @@ public void activate() { if (event == null) event = new HttpSessionEvent(getSession()); // FIXME: Should we catch throwables? - ((HttpSessionActivationListener)attribute).sessionDidActivate(event); + ((HttpSessionActivationListener) attribute).sessionDidActivate(event); } } } finally { @@ -979,10 +848,9 @@ public void activate() { } } - /** - * Return the object bound with the specified name to the internal notes - * for this session, or null if no such binding exists. + * Return the object bound with the specified name to the internal notes for this session, or null if no + * such binding exists. * * @param name Name of the note to be returned */ @@ -991,20 +859,16 @@ public Object getNote(String name) { return (notes.get(name)); } - /** - * Return an Iterator containing the String names of all notes bindings - * that exist for this session. + * Return an Iterator containing the String names of all notes bindings that exist for this session. */ @Override public Iterator getNoteNames() { return (notes.keySet().iterator()); } - /** - * Release all object references, and initialize instance variables, in - * preparation for reuse of this object. + * Release all object references, and initialize instance variables, in preparation for reuse of this object. */ @Override public void recycle() { @@ -1028,10 +892,8 @@ public void recycle() { } - /** - * Remove any object bound to the specified name in the internal notes - * for this session. + * Remove any object bound to the specified name in the internal notes for this session. * * @param name Name of the note to be removed */ @@ -1040,7 +902,6 @@ public void removeNote(String name) { notes.remove(name); } - /** * Remove a session event listener from this component. */ @@ -1053,10 +914,9 @@ public void removeSessionListener(SessionListener listener) { } - /** - * Bind an object to a specified name in the internal notes associated - * with this session, replacing any existing binding for this name. + * Bind an object to a specified name in the internal notes associated with this session, replacing any existing binding + * for this name. * * @param name Name to which the object should be bound * @param value Object to be bound to the specified name @@ -1066,7 +926,6 @@ public void setNote(String name, Object value) { notes.put(name, value); } - // START SJSAS 6329289 /** * Checks whether this Session has expired. @@ -1076,9 +935,7 @@ public void setNote(String name, Object value) { @Override public boolean hasExpired() { - if (maxInactiveInterval >= 0 - && (System.currentTimeMillis() - thisAccessedTime >= - maxInactiveInterval * 1000L)) { + if (maxInactiveInterval >= 0 && (System.currentTimeMillis() - thisAccessedTime >= maxInactiveInterval * 1000L)) { return true; } else { return false; @@ -1086,7 +943,6 @@ public boolean hasExpired() { } // END SJSAS 6329289 - /** * Increments the version number */ @@ -1094,7 +950,6 @@ public long incrementVersion() { return version.incrementAndGet(); } - /** * Gets the version number */ @@ -1103,7 +958,6 @@ public long getVersion() { return version.get(); } - /** * Sets the version number */ @@ -1111,17 +965,14 @@ public void setVersion(long value) { version.set(value); } - /** - * Return the single sign on id. - * It is null if there is no SSO. + * Return the single sign on id. It is null if there is no SSO. */ @Override public String getSsoId() { return ssoId; } - /** * Set the single sign on id. */ @@ -1130,7 +981,6 @@ public void setSsoId(String ssoId) { this.ssoId = ssoId; } - /** * Return the single sign on version. */ @@ -1139,7 +989,6 @@ public long getSsoVersion() { return ssoVersion; } - /** * Set the single sign on version. */ @@ -1148,7 +997,6 @@ public void setSsoVersion(long value) { ssoVersion = value; } - /** * Return a string representation of this object. */ @@ -1157,17 +1005,14 @@ public String toString() { // STARTS S1AS /* - StringBuilder sb = new StringBuilder(); - sb.append("StandardSession["); - sb.append(id); - sb.append("]"); - return (sb.toString()); - */ + * StringBuilder sb = new StringBuilder(); sb.append("StandardSession["); sb.append(id); sb.append("]"); return + * (sb.toString()); + */ // END S1AS // START S1AS StringBuilder sb = null; - if(!this.isValid) { + if (!this.isValid) { sb = new StringBuilder(); } else { sb = new StringBuilder(1000); @@ -1179,7 +1024,7 @@ public String toString() { if (this.isValid) { Enumeration attrNamesEnum = getAttributeNames(); - while(attrNamesEnum.hasMoreElements()) { + while (attrNamesEnum.hasMoreElements()) { String nextAttrName = attrNamesEnum.nextElement(); Object nextAttrValue = getAttribute(nextAttrName); sb.append("\n"); @@ -1192,33 +1037,23 @@ public String toString() { // END S1AS } - // ------------------------------------------------ Session Package Methods - /** - * Creates a StandardSession instance from the given ObjectInputStream, - * and returns it. + * Creates a StandardSession instance from the given ObjectInputStream, and returns it. * - * If ObjectInputStream does not contain a serialized StandardSession - * (or one of its subclasses), this method will create an empty session - * and populate it with the serialized data (this is for backwards - * compatibility). + * If ObjectInputStream does not contain a serialized StandardSession (or one of its subclasses), this method will + * create an empty session and populate it with the serialized data (this is for backwards compatibility). * - * @param ois The ObjectInputStream from which to read the serialized - * session data - * @param manager The session manager from which to create an empty - * session if needed + * @param ois The ObjectInputStream from which to read the serialized session data + * @param manager The session manager from which to create an empty session if needed * * @return The restored session * - * @exception ClassNotFoundException If the class for an object being - * restored cannot be found. + * @exception ClassNotFoundException If the class for an object being restored cannot be found. * @exception IOException if I/O errors occur */ - static StandardSession deserialize(ObjectInputStream ois, - Manager manager) - throws ClassNotFoundException, IOException { + static StandardSession deserialize(ObjectInputStream ois, Manager manager) throws ClassNotFoundException, IOException { StandardSession result = null; @@ -1237,29 +1072,23 @@ static StandardSession deserialize(ObjectInputStream ois, return result; } - // ------------------------------------------------- HttpSession Properties - /** - * Return the time when this session was created, in milliseconds since - * midnight, January 1, 1970 GMT. + * Return the time when this session was created, in milliseconds since midnight, January 1, 1970 GMT. * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session */ @Override public long getCreationTime() { if (!isValid()) - throw new IllegalStateException - ("getCreationTime: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + throw new IllegalStateException("getCreationTime: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); return (this.creationTime); } - /** * Return the ServletContext to which this session belongs. */ @@ -1275,27 +1104,22 @@ public ServletContext getServletContext() { } - - // ----------------------------------------------HttpSession Public Methods - /** - * Return the object bound with the specified name in this session, or - * null if no object is bound with that name. + * Return the object bound with the specified name in this session, or null if no object is bound with that + * name. * - * @param name Name of the attribute to be returned - * * @exception IllegalStateException if this method is called on an - * invalidated session + * @param name Name of the attribute to be returned * @exception IllegalStateException if this method is called on an + * invalidated session */ @Override public Object getAttribute(String name) { - if (!isValid()) - throw new IllegalStateException - ("getAttribute: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + throw new IllegalStateException("getAttribute: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); - if (name == null) return null; + if (name == null) + return null; return (attributes.get(name)); } @@ -1306,108 +1130,87 @@ public Map getAttributes() { } /** - * Return an Enumeration of String objects - * containing the names of the objects bound to this session. + * Return an Enumeration of String objects containing the names of the objects bound to this + * session. * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session */ @Override public Enumeration getAttributeNames() { - if (!isValid()) - throw new IllegalStateException - ("getAttributeNames: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); - + throw new IllegalStateException("getAttributeNames: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); return (new Enumerator(attributes.keySet(), true)); } - /** - * Return the object bound with the specified name in this session, or - * null if no object is bound with that name. + * Return the object bound with the specified name in this session, or null if no object is bound with that + * name. * * @param name Name of the value to be returned * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session * - * @deprecated As of Version 2.2, this method is replaced by - * getAttribute() + * @deprecated As of Version 2.2, this method is replaced by getAttribute() */ @Deprecated public Object getValue(String name) { - - return (getAttribute(name)); - + return getAttribute(name); } - /** - * Return the set of names of objects bound to this session. If there - * are no such objects, a zero-length array is returned. + * Return the set of names of objects bound to this session. If there are no such objects, a zero-length array is + * returned. * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session * - * @deprecated As of Version 2.2, this method is replaced by - * getAttributeNames() + * @deprecated As of Version 2.2, this method is replaced by getAttributeNames() */ @Deprecated public String[] getValueNames() { - if (!isValid()) - throw new IllegalStateException - ("getValueNames: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); - - return (keys()); + throw new IllegalStateException("getValueNames: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + return keys(); } - // ------------------------session locking --HERCULES:add------------------- /** - * get this session locked for foreground - * if the session is found to be presently background - * locked; retry logic in a time-decay polling loop - * waits for background lock to clear - * after 6 attempts (12.6 seconds) it unlocks the - * session and acquires the foreground lock + * get this session locked for foreground if the session is found to be presently background locked; retry logic in a + * time-decay polling loop waits for background lock to clear after 6 attempts (12.6 seconds) it unlocks the session and + * acquires the foreground lock */ protected boolean getSessionLockForForeground() { boolean result = false; StandardSession sess = this; - //now lock the session - //System.out.println("IN LOCK_SESSION_FOR_FOREGROUND: sess =" + sess); + // now lock the session long pollTime = 200L; int tryNumber = 0; int numTries = 7; boolean keepTrying = true; boolean lockResult = false; - //System.out.println("locking session: sess =" + sess); - //try to lock up to numTries (i.e. 7) times - //poll and wait starting with 200 ms - while(keepTrying) { + + // try to lock up to numTries (i.e. 7) times + // poll and wait starting with 200 ms + while (keepTrying) { lockResult = sess.lockForeground(); - if(lockResult) { + if (lockResult) { keepTrying = false; result = true; break; } tryNumber++; - if(tryNumber < (numTries - 1) ) { + if (tryNumber < (numTries - 1)) { pollTime = pollTime * 2L; } else { - //unlock the background so we can take over - //FIXME: need to log warning for this situation + // unlock the background so we can take over + // FIXME: need to log warning for this situation sess.unlockBackground(); } } - //System.out.println("finished locking session: sess =" + sess); - //System.out.println("LOCK = " + sess.getSessionLock()); + return result; } @@ -1415,54 +1218,51 @@ protected boolean getSessionLockForForeground() { * return whether this session is currently foreground locked */ public boolean isForegroundLocked() { - //in this case we are not using locks - //so just return false - if(_sessionLock == null) + // in this case we are not using locks + // so just return false + if (_sessionLock == null) return false; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { return _sessionLock.isForegroundLocked(); } } /** - * lock the session for foreground - * returns true if successful; false if unsuccessful + * lock the session for foreground returns true if successful; false if unsuccessful */ public boolean lockBackground() { - //in this case we are not using locks - //so just return true - if(_sessionLock == null) + // in this case we are not using locks + // so just return true + if (_sessionLock == null) return true; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { return _sessionLock.lockBackground(); } } /** - * lock the session for background - * returns true if successful; false if unsuccessful + * lock the session for background returns true if successful; false if unsuccessful */ @Override public boolean lockForeground() { - //in this case we are not using locks - //so just return true - if(_sessionLock == null) + // in this case we are not using locks + // so just return true + if (_sessionLock == null) return true; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { return _sessionLock.lockForeground(); } } /** - * unlock the session completely - * irregardless of whether it was foreground or background locked + * unlock the session completely irregardless of whether it was foreground or background locked */ public void unlockForegroundCompletely() { - //in this case we are not using locks - //so just return true - if(_sessionLock == null) + // in this case we are not using locks + // so just return true + if (_sessionLock == null) return; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { _sessionLock.unlockForegroundCompletely(); } } @@ -1472,11 +1272,11 @@ public void unlockForegroundCompletely() { */ @Override public void unlockForeground() { - //in this case we are not using locks - //so just return true - if(_sessionLock == null) + // in this case we are not using locks + // so just return true + if (_sessionLock == null) return; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { _sessionLock.unlockForeground(); } } @@ -1485,11 +1285,11 @@ public void unlockForeground() { * unlock the session from background */ public void unlockBackground() { - //in this case we are not using locks - //so just return true - if(_sessionLock == null) + // in this case we are not using locks + // so just return true + if (_sessionLock == null) return; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { _sessionLock.unlockBackground(); } } @@ -1503,6 +1303,7 @@ public SessionLock getSessionLock() { /** * set the Session lock + * * @param sessionLock */ public void setSessionLock(SessionLock sessionLock) { @@ -1510,15 +1311,14 @@ public void setSessionLock(SessionLock sessionLock) { } /** - * @return true if this session has been locked by any - * out-of-band (i.e., non-http) request, false otherwise + * @return true if this session has been locked by any out-of-band (i.e., non-http) request, false otherwise */ public boolean hasNonHttpLockOccurred() { - //in this case we are not using locks - //so just return false - if(_sessionLock == null) + // in this case we are not using locks + // so just return false + if (_sessionLock == null) return false; - synchronized(sessionLockMonitor) { + synchronized (sessionLockMonitor) { return _sessionLock.hasNonHttpLockOccurred(); } } @@ -1529,23 +1329,18 @@ public boolean hasNonHttpLockOccurred() { // ------------------------end session locking ---HERCULES:add-------- - - /** * Invalidates this session and unbinds any objects bound to it. * - * @exception IllegalStateException if this method is called on - * an invalidated session - * HERCULES:modified method + * @exception IllegalStateException if this method is called on an invalidated session HERCULES:modified method */ @Override public void invalidate() { if (!isValid) - throw new IllegalStateException - ("invalidate: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); - //make sure foreground locked first - if(!this.isForegroundLocked()) { + throw new IllegalStateException("invalidate: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + // make sure foreground locked first + if (!this.isForegroundLocked()) { this.getSessionLockForForeground(); } // Cause this session to expire @@ -1557,46 +1352,36 @@ public void invalidate() { } - /** - * Return true if the client does not yet know about the - * session, or if the client chooses not to join the session. For - * example, if the server used only cookie-based sessions, and the client - * has disabled the use of cookies, then a session would be new on each - * request. + * Return true if the client does not yet know about the session, or if the client chooses not to join the + * session. For example, if the server used only cookie-based sessions, and the client has disabled the use of cookies, + * then a session would be new on each request. * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session */ @Override public boolean isNew() { if (!isValid()) - throw new IllegalStateException - ("isNew: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + throw new IllegalStateException("isNew: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); return (this.isNew); } - /** - * Bind an object to this session, using the specified name. If an object - * of the same name is already bound to this session, the object is - * replaced. + * Bind an object to this session, using the specified name. If an object of the same name is already bound to this + * session, the object is replaced. *

- * After this method executes, and if the object implements - * HttpSessionBindingListener, the container calls + * After this method executes, and if the object implements HttpSessionBindingListener, the container calls * valueBound() on the object. * * @param name Name to which the object is bound, cannot be null * @param value Object to be bound, cannot be null * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session * - * @deprecated As of Version 2.2, this method is replaced by - * setAttribute() + * @deprecated As of Version 2.2, this method is replaced by setAttribute() */ @Deprecated public void putValue(String name, Object value) { @@ -1605,20 +1390,16 @@ public void putValue(String name, Object value) { } - /** - * Remove the object bound with the specified name from this session. If - * the session does not have an object bound with this name, this method - * does nothing. + * Remove the object bound with the specified name from this session. If the session does not have an object bound with + * this name, this method does nothing. *

- * After this method executes, and if the object implements - * HttpSessionBindingListener, the container calls + * After this method executes, and if the object implements HttpSessionBindingListener, the container calls * valueUnbound() on the object. * * @param name Name of the object to remove from this session. * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session */ @Override public void removeAttribute(String name) { @@ -1627,34 +1408,26 @@ public void removeAttribute(String name) { } - /** - * Remove the object bound with the specified name from this session. If - * the session does not have an object bound with this name, this method - * does nothing. + * Remove the object bound with the specified name from this session. If the session does not have an object bound with + * this name, this method does nothing. *

- * After this method executes, and if the object implements - * HttpSessionBindingListener, the container calls + * After this method executes, and if the object implements HttpSessionBindingListener, the container calls * valueUnbound() on the object. * * @param name Name of the object to remove from this session. - * @param notify Should we notify interested listeners that this - * attribute is being removed? - * @param checkValid Indicates whether IllegalStateException must be - * thrown if session has already been invalidated + * @param notify Should we notify interested listeners that this attribute is being removed? + * @param checkValid Indicates whether IllegalStateException must be thrown if session has already been invalidated * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session */ - public void removeAttribute(String name, boolean notify, - boolean checkValid) { - - if (name == null) return; + public void removeAttribute(String name, boolean notify, boolean checkValid) { + if (name == null) + return; // Validate our current state if (!isValid() && checkValid) - throw new IllegalStateException - ("removeAttribute: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + throw new IllegalStateException("removeAttribute: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); // Remove this attribute from our collection Object value = attributes.remove(name); @@ -1669,27 +1442,24 @@ public void removeAttribute(String name, boolean notify, if (value instanceof HttpSessionBindingListener) { event = new HttpSessionBindingEvent(getSession(), name, value); try { - context.fireContainerEvent( - ContainerEvent.BEFORE_SESSION_VALUE_UNBOUND, null); + context.fireContainerEvent(ContainerEvent.BEFORE_SESSION_VALUE_UNBOUND, null); ((HttpSessionBindingListener) value).valueUnbound(event); - context.fireContainerEvent( - ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); + context.fireContainerEvent(ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); } catch (Throwable t) { // Log exception - context.fireContainerEvent( - ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); + context.fireContainerEvent(ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); } } // Notify special event listeners on removeAttribute - //HERCULES:add + // HERCULES:add // fire container event context.fireContainerEvent("sessionRemoveAttributeCalled", event); // fire sync container event if name equals SYNC_STRING if (SYNC_STRING.equals(name)) { - context.fireContainerEvent("sessionSync", (new HttpSessionBindingEvent(getSession(), name))); + context.fireContainerEvent("sessionSync", (new HttpSessionBindingEvent(getSession(), name))); } - //END HERCULES:add + // END HERCULES:add // Notify interested application event listeners List listeners = context.getApplicationEventListeners(); @@ -1702,24 +1472,17 @@ public void removeAttribute(String name, boolean notify, if (!(eventListener instanceof HttpSessionAttributeListener)) { continue; } - HttpSessionAttributeListener listener = - (HttpSessionAttributeListener) eventListener; + HttpSessionAttributeListener listener = (HttpSessionAttributeListener) eventListener; try { - fireContainerEvent(context, - "beforeSessionAttributeRemoved", - listener); + fireContainerEvent(context, "beforeSessionAttributeRemoved", listener); if (event == null) { event = new HttpSessionBindingEvent(getSession(), name, value); } listener.attributeRemoved(event); - fireContainerEvent(context, - "afterSessionAttributeRemoved", - listener); + fireContainerEvent(context, "afterSessionAttributeRemoved", listener); } catch (Throwable t) { try { - fireContainerEvent(context, - "afterSessionAttributeRemoved", - listener); + fireContainerEvent(context, "afterSessionAttributeRemoved", listener); } catch (Exception e) { // Ignore } @@ -1729,23 +1492,18 @@ public void removeAttribute(String name, boolean notify, } - /** - * Remove the object bound with the specified name from this session. If - * the session does not have an object bound with this name, this method - * does nothing. + * Remove the object bound with the specified name from this session. If the session does not have an object bound with + * this name, this method does nothing. *

- * After this method executes, and if the object implements - * HttpSessionBindingListener, the container calls + * After this method executes, and if the object implements HttpSessionBindingListener, the container calls * valueUnbound() on the object. * * @param name Name of the object to remove from this session. * - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalStateException if this method is called on an invalidated session * - * @deprecated As of Version 2.2, this method is replaced by - * removeAttribute() + * @deprecated As of Version 2.2, this method is replaced by removeAttribute() */ @Deprecated public void removeValue(String name) { @@ -1754,31 +1512,26 @@ public void removeValue(String name) { } - /** - * Bind an object to this session, using the specified name. If an object - * of the same name is already bound to this session, the object is - * replaced. + * Bind an object to this session, using the specified name. If an object of the same name is already bound to this + * session, the object is replaced. *

- * After this method executes, and if the object implements - * HttpSessionBindingListener, the container calls + * After this method executes, and if the object implements HttpSessionBindingListener, the container calls * valueBound() on the object. * * @param name Name to which the object is bound, cannot be null * @param value Object to be bound, cannot be null * - * @exception IllegalArgumentException if an attempt is made to add a - * non-serializable object in an environment marked distributable. - * @exception IllegalStateException if this method is called on an - * invalidated session + * @exception IllegalArgumentException if an attempt is made to add a non-serializable object in an environment marked + * distributable. + * @exception IllegalStateException if this method is called on an invalidated session */ @Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) - throw new IllegalArgumentException - (rb.getString(LogFacade.NAME_PARAMETER_CANNOT_BE_NULL_EXCEPTION)); + throw new IllegalArgumentException(rb.getString(LogFacade.NAME_PARAMETER_CANNOT_BE_NULL_EXCEPTION)); // Null value is the same as removeAttribute() if (value == null) { @@ -1788,8 +1541,7 @@ public void setAttribute(String name, Object value) { // Validate our current state if (!isValid()) { - throw new IllegalStateException - ("setAttribute: "+ rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); + throw new IllegalStateException("setAttribute: " + rb.getString(LogFacade.SESSION_INVALIDATED_EXCEPTION)); } if (manager != null) { @@ -1804,7 +1556,7 @@ public void setAttribute(String name, Object value) { event = new HttpSessionBindingEvent(getSession(), name, value); try { ((HttpSessionBindingListener) value).valueBound(event); - } catch (Throwable t){ + } catch (Throwable t) { log(rb.getString(LogFacade.SESSION_BINDING_EVENT_LISTENER_EXCEPTION), t); } } @@ -1813,29 +1565,23 @@ public void setAttribute(String name, Object value) { Object unbound = attributes.put(name, value); // Call the valueUnbound() method if necessary - if ((unbound != null) && - (unbound instanceof HttpSessionBindingListener)) { + if ((unbound != null) && (unbound instanceof HttpSessionBindingListener)) { try { - context.fireContainerEvent( - ContainerEvent.BEFORE_SESSION_VALUE_UNBOUND, null); - ((HttpSessionBindingListener) unbound).valueUnbound - (new HttpSessionBindingEvent(getSession(), name)); - context.fireContainerEvent( - ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); + context.fireContainerEvent(ContainerEvent.BEFORE_SESSION_VALUE_UNBOUND, null); + ((HttpSessionBindingListener) unbound).valueUnbound(new HttpSessionBindingEvent(getSession(), name)); + context.fireContainerEvent(ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); } catch (Throwable t) { - context.fireContainerEvent( - ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); + context.fireContainerEvent(ContainerEvent.AFTER_SESSION_VALUE_UNBOUND, null); log(rb.getString(LogFacade.SESSION_BINDING_EVENT_LISTENER_EXCEPTION), t); } } - //HERCULES:add + // HERCULES:add // fire sync container event if name equals SYNC_STRING if (SYNC_STRING.equals(name)) { - context.fireContainerEvent("sessionSync", - new HttpSessionBindingEvent(getSession(), name)); + context.fireContainerEvent("sessionSync", new HttpSessionBindingEvent(getSession(), name)); } - //end HERCULES:add + // end HERCULES:add // Notify interested application event listeners List listeners = context.getApplicationEventListeners(); @@ -1848,44 +1594,29 @@ public void setAttribute(String name, Object value) { if (!(eventListener instanceof HttpSessionAttributeListener)) { continue; } - HttpSessionAttributeListener listener = - (HttpSessionAttributeListener) eventListener; + HttpSessionAttributeListener listener = (HttpSessionAttributeListener) eventListener; try { if (unbound != null) { - fireContainerEvent(context, - "beforeSessionAttributeReplaced", - listener); + fireContainerEvent(context, "beforeSessionAttributeReplaced", listener); if (event == null) { - event = new HttpSessionBindingEvent - (getSession(), name, unbound); + event = new HttpSessionBindingEvent(getSession(), name, unbound); } listener.attributeReplaced(event); - fireContainerEvent(context, - "afterSessionAttributeReplaced", - listener); + fireContainerEvent(context, "afterSessionAttributeReplaced", listener); } else { - fireContainerEvent(context, - "beforeSessionAttributeAdded", - listener); + fireContainerEvent(context, "beforeSessionAttributeAdded", listener); if (event == null) { - event = new HttpSessionBindingEvent( - getSession(), name, value); + event = new HttpSessionBindingEvent(getSession(), name, value); } listener.attributeAdded(event); - fireContainerEvent(context, - "afterSessionAttributeAdded", - listener); + fireContainerEvent(context, "afterSessionAttributeAdded", listener); } } catch (Throwable t) { try { if (unbound != null) { - fireContainerEvent(context, - "afterSessionAttributeReplaced", - listener); + fireContainerEvent(context, "afterSessionAttributeReplaced", listener); } else { - fireContainerEvent(context, - "afterSessionAttributeAdded", - listener); + fireContainerEvent(context, "afterSessionAttributeAdded", listener); } } catch (Exception e) { // Ignore @@ -1896,24 +1627,20 @@ public void setAttribute(String name, Object value) { } - // ------------------------------------------ HttpSession Protected Methods - /** - * Read a serialized version of this session object from the specified - * object input stream. + * Read a serialized version of this session object from the specified object input stream. *

- * IMPLEMENTATION NOTE: The reference to the owning Manager - * is not restored by this method, and must be set explicitly. + * IMPLEMENTATION NOTE: The reference to the owning Manager is not restored by this method, and must be set + * explicitly. * * @param stream The input stream to read from * * @exception ClassNotFoundException if an unknown class is specified * @exception IOException if an input/output error occurs */ - private void readObject(ObjectInputStream stream) - throws ClassNotFoundException, IOException { + private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { if (listeners == null) { listeners = new ArrayList(); @@ -1923,12 +1650,11 @@ private void readObject(ObjectInputStream stream) } // Deserialize the scalar instance variables (except Manager) - authType = null; // Transient only + authType = null; // Transient only /* - * The stream starts with a Long, which indicates the session's - * creation time. This Long may optionally be preceded by a Short, - * which indicates the session's serializedFormVersion. + * The stream starts with a Long, which indicates the session's creation time. This Long may optionally be preceded by a + * Short, which indicates the session's serializedFormVersion. */ Object obj = stream.readObject(); short readSerializedFormVersion = 0; @@ -1936,18 +1662,15 @@ private void readObject(ObjectInputStream stream) readSerializedFormVersion = ((Short) obj).shortValue(); creationTime = ((Long) stream.readObject()).longValue(); } else { - creationTime = ((Long) obj).longValue(); + creationTime = ((Long) obj).longValue(); } readRemainingObject(stream); /* - * Any additional fields that are to be included in the serialized - * representation of this class MUST be written to the end of the - * stream (in writeObject), and must be read back in HERE, i.e., - * AFTER readRemainingObject (which is shared by the code that reads - * in sessions that were serialized using an earlier, proprietary - * format) has returned. + * Any additional fields that are to be included in the serialized representation of this class MUST be written to the + * end of the stream (in writeObject), and must be read back in HERE, i.e., AFTER readRemainingObject (which is shared + * by the code that reads in sessions that were serialized using an earlier, proprietary format) has returned. */ sipAppSessionId = (String) stream.readObject(); @@ -1959,28 +1682,21 @@ private void readObject(ObjectInputStream stream) beKey = (String) stream.readObject(); break; default: - throw new IOException("Unable to deserialize into " - + getClass().getName() - + " due to unknown serializedFormVersion of " + throw new IOException("Unable to deserialize into " + getClass().getName() + " due to unknown serializedFormVersion of " + readSerializedFormVersion); } } - /** - * Reads the serialized session data from the given ObjectInputStream, - * with the assumption that the session's creation time, which appears - * first in the serialized data, has already been consumed. + * Reads the serialized session data from the given ObjectInputStream, with the assumption that the session's creation + * time, which appears first in the serialized data, has already been consumed. * - * @param stream The ObjectInputStream from which to read the serialized - * session data + * @param stream The ObjectInputStream from which to read the serialized session data * - * @exception ClassNotFoundException If the class for an object being - * restored cannot be found. + * @exception ClassNotFoundException If the class for an object being restored cannot be found. * @exception IOException if I/O errors occur */ - private void readRemainingObject(ObjectInputStream stream) - throws ClassNotFoundException, IOException { + private void readRemainingObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { version = new AtomicLong(); @@ -1989,20 +1705,18 @@ private void readRemainingObject(ObjectInputStream stream) isNew = ((Boolean) stream.readObject()).booleanValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); thisAccessedTime = ((Long) stream.readObject()).longValue(); - /* SJSWS 6371339 - principal = null; // Transient only - // setId((String) stream.readObject()); - id = (String) stream.readObject(); - */ + /* + * SJSWS 6371339 principal = null; // Transient only // setId((String) stream.readObject()); id = (String) + * stream.readObject(); + */ // START SJSWS 6371339 // Read the next object, if it is of type Principal, then // store it in the principal variable Object obj = stream.readObject(); if (obj instanceof Principal) { - principal = (Principal)obj; + principal = (Principal) obj; id = (String) stream.readObject(); - } - else { + } else { principal = null; id = (String) obj; } @@ -2024,9 +1738,9 @@ private void readRemainingObject(ObjectInputStream stream) // Deserialize the attribute count and attribute values if (attributes == null) attributes = new ConcurrentHashMap(); - /* PWC 6444754 - int n = ((Integer) stream.readObject()).intValue(); - */ + /* + * PWC 6444754 int n = ((Integer) stream.readObject()).intValue(); + */ boolean isValidSave = isValid; isValid = true; for (int i = 0; i < n; i++) { @@ -2035,28 +1749,21 @@ private void readRemainingObject(ObjectInputStream stream) if ((value instanceof String) && (value.equals(NOT_SERIALIZED))) continue; if (debug >= 2) - log(" loading attribute '" + name + - "' with value '" + value + "'"); + log(" loading attribute '" + name + "' with value '" + value + "'"); attributes.put(name, value); } isValid = isValidSave; } - /** - * Write a serialized version of this session object to the specified - * object output stream. + * Write a serialized version of this session object to the specified object output stream. *

- * IMPLEMENTATION NOTE: The owning Manager will not be stored - * in the serialized representation of this Session. After calling - * readObject(), you must set the associated Manager - * explicitly. + * IMPLEMENTATION NOTE: The owning Manager will not be stored in the serialized representation of this Session. + * After calling readObject(), you must set the associated Manager explicitly. *

- * IMPLEMENTATION NOTE: Any attribute that is not Serializable - * will be unbound from the session, with appropriate actions if it - * implements HttpSessionBindingListener. If you do not want any such - * attributes, be sure the distributable property of the - * associated Manager is set to true. + * IMPLEMENTATION NOTE: Any attribute that is not Serializable will be unbound from the session, with appropriate + * actions if it implements HttpSessionBindingListener. If you do not want any such attributes, be sure the + * distributable property of the associated Manager is set to true. * * @param stream The output stream to write to * @@ -2101,22 +1808,21 @@ private void writeObject(ObjectOutputStream stream) throws IOException { if (value == null) { continue; - //HERCULES:mod - /* original PE code next 4 lines - else if (value instanceof Serializable) { - saveNames.add(keys[i]); - saveValues.add(value); - } - */ - //original Hercules code was next line - //else if (value instanceof Serializable || value instanceof jakarta.ejb.EJBLocalObject || value instanceof javax.naming.Context || value instanceof jakarta.ejb.EJBLocalHome ) { //Bug 4853798 - //FIXME: IndirectlySerializable includes more than 3 classes in Hercules code - //need to explore implications of this + // HERCULES:mod + /* + * original PE code next 4 lines else if (value instanceof Serializable) { saveNames.add(keys[i]); + * saveValues.add(value); } + */ + // original Hercules code was next line + // else if (value instanceof Serializable || value instanceof jakarta.ejb.EJBLocalObject || value instanceof + // javax.naming.Context || value instanceof jakarta.ejb.EJBLocalHome ) { //Bug 4853798 + // FIXME: IndirectlySerializable includes more than 3 classes in Hercules code + // need to explore implications of this } else if (isSerializable(value)) { saveNames.add(keys[i]); saveValues.add(value); - //end HERCULES:mod + // end HERCULES:mod } else { removeAttribute(keys[i], true, true); } @@ -2127,26 +1833,17 @@ else if (value instanceof Serializable) { stream.writeObject(Integer.valueOf(n)); for (int i = 0; i < n; i++) { stream.writeObject(saveNames.get(i)); - //HERCULES:mod - /* orignal PE code - try { - stream.writeObject(saveValues.get(i)); - if (debug >= 2) - log(" storing attribute '" + saveNames.get(i) + - "' with value '" + saveValues.get(i) + "'"); - } catch (NotSerializableException e) { - log(sm.getString("standardSession.notSerializable", - saveNames.get(i), id), e); - //standardSession.notSerializable=PWC2785: Cannot serialize session attribute {0} for session {1} - stream.writeObject(NOT_SERIALIZED); - if (debug >= 2) - log(" storing attribute '" + saveNames.get(i) + - "' with value NOT_SERIALIZED"); - } - *end original PE code + // HERCULES:mod + /* + * orignal PE code try { stream.writeObject(saveValues.get(i)); if (debug >= 2) log(" storing attribute '" + + * saveNames.get(i) + "' with value '" + saveValues.get(i) + "'"); } catch (NotSerializableException e) { + * log(sm.getString("standardSession.notSerializable", saveNames.get(i), id), e); + * //standardSession.notSerializable=PWC2785: Cannot serialize session attribute {0} for session {1} + * stream.writeObject(NOT_SERIALIZED); if (debug >= 2) log(" storing attribute '" + saveNames.get(i) + + * "' with value NOT_SERIALIZED"); } end original PE code */ - //following is replacement code from Hercules + // following is replacement code from Hercules try { stream.writeObject(saveValues.get(i)); if (debug >= 2) { @@ -2154,7 +1851,7 @@ else if (value instanceof Serializable) { } } catch (NotSerializableException e) { String msg = MessageFormat.format(rb.getString(LogFacade.CANNOT_SERIALIZE_SESSION_EXCEPTION), - new Object[] {saveNames.get(i), id}); + new Object[] { saveNames.get(i), id }); log(msg, e); stream.writeObject(NOT_SERIALIZED); if (debug >= 2) { @@ -2163,7 +1860,7 @@ else if (value instanceof Serializable) { } catch (IOException ioe) { if (ioe.getCause() instanceof NotSerializableException) { String msg = MessageFormat.format(rb.getString(LogFacade.CANNOT_SERIALIZE_SESSION_EXCEPTION), - new Object[] {saveNames.get(i), id}); + new Object[] { saveNames.get(i), id }); log(msg, ioe); stream.writeObject(NOT_SERIALIZED); if (debug >= 2) { @@ -2181,13 +1878,12 @@ else if (value instanceof Serializable) { } - - /** * Exclude attribute that cannot be serialized. + * * @param name the attribute's name */ - protected boolean exclude(String name){ + protected boolean exclude(String name) { for (int i = 0; i < excludedAttributes.length; i++) { if (name.equalsIgnoreCase(excludedAttributes[i])) @@ -2197,11 +1893,9 @@ protected boolean exclude(String name){ return false; } - protected void evaluateIfValid() { /* - * If this session has expired or is in the process of expiring or - * will never expire, return + * If this session has expired or is in the process of expiring or will never expire, return */ if (!this.isValid || expiring || maxInactiveInterval < 0) return; @@ -2210,13 +1904,10 @@ protected void evaluateIfValid() { } - // ------------------------------------------------------ Protected Methods - /** - * Fire container events if the Context implementation is the - * org.apache.catalina.core.StandardContext. + * Fire container events if the Context implementation is the org.apache.catalina.core.StandardContext. * * @param context Context for which to fire events * @param type Event type @@ -2224,17 +1915,14 @@ protected void evaluateIfValid() { * * @exception Exception occurred during event firing */ - protected void fireContainerEvent(Context context, String type, Object data) - throws Exception { + protected void fireContainerEvent(Context context, String type, Object data) throws Exception { if (!(context instanceof StandardContext)) { return; // Container events are not supported } - // NOTE: Race condition is harmless, so do not synchronize + // NOTE: Race condition is harmless, so do not synchronize if (containerEventMethod == null) { - containerEventMethod = - context.getClass().getMethod("fireContainerEvent", - containerEventTypes); + containerEventMethod = context.getClass().getMethod("fireContainerEvent", containerEventTypes); } Object containerEventParams[] = new Object[2]; containerEventParams[0] = type; @@ -2243,12 +1931,9 @@ protected void fireContainerEvent(Context context, String type, Object data) } - - /** - * Notify all session event listeners that a particular event has - * occurred for this Session. The default implementation performs - * this notification synchronously using the calling thread. + * Notify all session event listeners that a particular event has occurred for this Session. The default implementation + * performs this notification synchronously using the calling thread. * * @param type Event type * @param data Event data @@ -2258,7 +1943,7 @@ public void fireSessionEvent(String type, Object data) { // Fire monitoring probe if (Session.SESSION_CREATED_EVENT.equals(type)) { context.sessionCreatedEvent(this); - } else { + } else { context.sessionDestroyedEvent(this); } @@ -2270,17 +1955,15 @@ public void fireSessionEvent(String type, Object data) { list = listeners.toArray(list); } - for (int i = 0; i < list.length; i++){ + for (int i = 0; i < list.length; i++) { (list[i]).sessionEvent(event); } } - /** - * Return the names of all currently defined session attributes - * as an array of Strings. If there are no defined attributes, a - * zero-length array is returned. + * Return the names of all currently defined session attributes as an array of Strings. If there are no defined + * attributes, a zero-length array is returned. */ protected String[] keys() { if (attributes.size() > 0) { @@ -2295,7 +1978,6 @@ protected String[] keys() { } } - /** * Return the value of an attribute without a check for validity. */ @@ -2303,7 +1985,6 @@ protected Object getAttributeInternal(String name) { return (attributes.get(name)); } - /** * Log a message on the Logger associated with our Manager (if any). * @@ -2318,7 +1999,6 @@ protected void log(String message) { } } - /** * Log a message on the Logger associated with our Manager (if any). * @@ -2334,25 +2014,19 @@ protected void log(String message, Throwable t) { } } - /** * Returns true if the given value may be serialized, false otherwise. * - * A given value is considered serializable if it is an instance of - * java.io.Serializable or - * com.sun.enterprise.spi.io.BaseIndirectlySerializable, or if special - * serialization logic for it exists. For example, in the case of - * GlassFish, instances of javax.naming.Context are replaced with - * corresponding instances of SerializableJNDIContext during serialization - * (this is done by the specialized object outputstream returned by - * the JavaEEObjectStreamFactory mechanism). + * A given value is considered serializable if it is an instance of java.io.Serializable or + * com.sun.enterprise.spi.io.BaseIndirectlySerializable, or if special serialization logic for it exists. For example, + * in the case of GlassFish, instances of javax.naming.Context are replaced with corresponding instances of + * SerializableJNDIContext during serialization (this is done by the specialized object outputstream returned by the + * JavaEEObjectStreamFactory mechanism). * * @return true if the given value may be serialized, false otherwise */ static boolean isSerializable(Object value) { - if ((value instanceof Serializable) - || (value instanceof BaseIndirectlySerializable) - || (value instanceof javax.naming.Context)) { + if ((value instanceof Serializable) || (value instanceof BaseIndirectlySerializable) || (value instanceof javax.naming.Context)) { return true; } else { return false; @@ -2360,5 +2034,3 @@ static boolean isSerializable(Object value) { } } - - diff --git a/appserver/web/web-glue/src/main/java/com/sun/web/server/EEInstanceListener.java b/appserver/web/web-glue/src/main/java/com/sun/web/server/EEInstanceListener.java index 5772c01a84b..3f0d72d4a89 100644 --- a/appserver/web/web-glue/src/main/java/com/sun/web/server/EEInstanceListener.java +++ b/appserver/web/web-glue/src/main/java/com/sun/web/server/EEInstanceListener.java @@ -171,12 +171,6 @@ private void handleBeforeEvent(InstanceEvent event, InstanceEvent.EventType even if (principal != null && principal == basePrincipal && principal.getClass().getName().equals(WEB_PRINCIPAL_CLASS)) { securityContext.setSecurityContextWithPrincipal(principal); } else if (principal != basePrincipal && principal != getCurrentCallerPrincipal()) { - - // The wrapper has overridden getUserPrincipal - // reject the request if the wrapper does not have - // the necessary permission. - - checkObjectForDoAsPermission(httpServletRequest); securityContext.setSecurityContextWithPrincipal(principal); } } @@ -258,21 +252,6 @@ private Principal getCurrentCallerPrincipal() { return currentSecurityContext.getCallerPrincipal(); } - private static void checkObjectForDoAsPermission(final Object o) throws AccessControlException { - if (System.getSecurityManager() != null) { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - if (!getPolicy().implies(o.getClass().getProtectionDomain(), doAsPrivilegedPerm)) { - throw new AccessControlException("permission required to override getUserPrincipal", doAsPrivilegedPerm); - } - - return null; - } - }); - } - } - private void handleAfterEvent(InstanceEvent event, InstanceEvent.EventType eventType) { Wrapper wrapper = event.getWrapper(); Context context = (Context) wrapper.getParent(); diff --git a/appserver/web/web-naming/src/main/java/org/apache/naming/factory/ResourceLinkFactory.java b/appserver/web/web-naming/src/main/java/org/apache/naming/factory/ResourceLinkFactory.java index 4c1f980b1c1..cadf7d9fd40 100644 --- a/appserver/web/web-naming/src/main/java/org/apache/naming/factory/ResourceLinkFactory.java +++ b/appserver/web/web-naming/src/main/java/org/apache/naming/factory/ResourceLinkFactory.java @@ -28,64 +28,50 @@ import javax.naming.spi.ObjectFactory; import org.apache.naming.ResourceLinkRef; - /** - *

Object factory for resource links.

+ *

+ * Object factory for resource links. + *

* * @author Remy Maucherat * @version $Revision: 1.2 $ $Date: 2005/12/08 01:29:07 $ */ -public class ResourceLinkFactory - implements ObjectFactory { - - - // ----------------------------------------------------------- Constructors - +public class ResourceLinkFactory implements ObjectFactory { // ------------------------------------------------------- Static Variables - /** * Global naming context. */ - private static Context globalContext = null; - + private static Context globalContext; // --------------------------------------------------------- Public Methods - /** * Set the global context (note: can only be used once). * * @param newGlobalContext new global context value */ public static void setGlobalContext(Context newGlobalContext) { - if (globalContext != null) + if (globalContext != null) { return; - SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - securityManager.checkPermission(new RuntimePermission( - ResourceLinkFactory.class.getName() + ".setGlobalContext")); } + globalContext = newGlobalContext; } - // -------------------------------------------------- ObjectFactory Methods - /** * Create a new DataSource instance. * * @param obj The reference object describing the DataSource */ - public Object getObjectInstance(Object obj, Name name, Context nameCtx, - Hashtable environment) - throws NamingException { - - if (!(obj instanceof ResourceLinkRef)) + public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws NamingException { + if (!(obj instanceof ResourceLinkRef)) { return null; + } // Can we process this request? Reference ref = (Reference) obj; @@ -101,10 +87,7 @@ public Object getObjectInstance(Object obj, Name name, Context nameCtx, return result; } - return (null); - - + return null; } - } diff --git a/appserver/web/weld-integration/src/main/java/org/glassfish/weld/ACLSingletonProvider.java b/appserver/web/weld-integration/src/main/java/org/glassfish/weld/ACLSingletonProvider.java index 7f44c1f9b09..80aeebf5236 100644 --- a/appserver/web/weld-integration/src/main/java/org/glassfish/weld/ACLSingletonProvider.java +++ b/appserver/web/weld-integration/src/main/java/org/glassfish/weld/ACLSingletonProvider.java @@ -17,11 +17,10 @@ package org.glassfish.weld; -import java.security.AccessController; -import java.security.PrivilegedAction; +import static java.lang.Thread.currentThread; + import java.util.Hashtable; import java.util.Map; - import org.glassfish.internal.api.ClassLoaderHierarchy; import org.glassfish.internal.api.Globals; import org.glassfish.javaee.full.deployment.EarLibClassLoader; @@ -30,10 +29,6 @@ import org.jboss.weld.bootstrap.api.SingletonProvider; import org.jboss.weld.bootstrap.api.helpers.TCCLSingletonProvider; -import static java.lang.System.getSecurityManager; -import static java.lang.Thread.currentThread; -import static java.security.AccessController.doPrivileged; - /** * Singleton provider that uses Application ClassLoader to differentiate between applications. * @@ -93,12 +88,7 @@ private static class ACLSingleton implements Singleton { private static ClassLoader bootstrapCL; static { - bootstrapCL = getSecurityManager() != null ? AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return Object.class.getClassLoader(); - } - }) : Object.class.getClassLoader(); + bootstrapCL = Object.class.getClassLoader(); } @Override @@ -113,11 +103,11 @@ public T get(String id) { } /** - * This is the most significant method of this class. This is what distingushes it from TCCLSIngleton. + * This is the most significant method of this class. This is what distinguishes it from TCCLSIngleton. * *

* It tries to obtain a class loader that's common to all modules of an application (ear). Since it runs in the context - * of Java EE, it can assume that Thread's context class loader is always set as application class loader. In GlassFish, + * of Jakarta EE, it can assume that Thread's context class loader is always set as application class loader. In GlassFish, * the class loader can vary for each module of an Ear. Thread's context class loader is set depending on which module * is handling the request. * @@ -131,12 +121,7 @@ public T get(String id) { * @return a class loader that's common to all modules of a Jakarta EE application */ private ClassLoader getClassLoader() { - ClassLoader contextClassLoader = getSecurityManager() != null ? doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return currentThread().getContextClassLoader(); - } - }) : currentThread().getContextClassLoader(); + ClassLoader contextClassLoader = currentThread().getContextClassLoader(); if (contextClassLoader == null) { throw new RuntimeException("Thread's context class loader is null"); @@ -168,12 +153,7 @@ public ClassLoader run() { } private ClassLoader getParent(ClassLoader classLoader) { - return getSecurityManager() != null ? doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return classLoader.getParent(); - } - }) : classLoader.getParent(); + return classLoader.getParent(); } @Override diff --git a/appserver/web/weld-integration/src/main/java/org/glassfish/weld/DeploymentImpl.java b/appserver/web/weld-integration/src/main/java/org/glassfish/weld/DeploymentImpl.java index e75b72beb53..138ffb3cb10 100644 --- a/appserver/web/weld-integration/src/main/java/org/glassfish/weld/DeploymentImpl.java +++ b/appserver/web/weld-integration/src/main/java/org/glassfish/weld/DeploymentImpl.java @@ -62,8 +62,6 @@ import static com.sun.enterprise.util.Utility.isAnyEmpty; import static com.sun.enterprise.util.Utility.isAnyNull; import static com.sun.enterprise.util.Utility.isEmpty; -import static java.lang.System.getSecurityManager; -import static java.security.AccessController.doPrivileged; import static java.util.Collections.emptyList; import static java.util.logging.Level.FINE; import static java.util.stream.Collectors.toList; @@ -272,13 +270,7 @@ public Iterable> getExtensions() { if (!buildExtensions.isEmpty()) { try { - LiteExtensionTranslator extension = getSecurityManager() != null ? doPrivileged(new PrivilegedAction() { - @Override - public LiteExtensionTranslator run() { - return new LiteExtensionTranslator(buildExtensions, Thread.currentThread().getContextClassLoader()); - } - }) : new LiteExtensionTranslator(buildExtensions, Thread.currentThread().getContextClassLoader()); - extensionsList.add(new MetadataImpl<>(extension)); + extensionsList.add(new MetadataImpl<>(new LiteExtensionTranslator(buildExtensions, Thread.currentThread().getContextClassLoader()))); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/CompositeUtil.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/CompositeUtil.java index 9cff2b88c22..e0a31fcae14 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/CompositeUtil.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/CompositeUtil.java @@ -17,8 +17,33 @@ package org.glassfish.admin.rest.composite; +import static java.util.Collections.emptySet; +import static org.objectweb.asm.Opcodes.ACC_PRIVATE; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_SUPER; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ARETURN; +import static org.objectweb.asm.Opcodes.DUP; +import static org.objectweb.asm.Opcodes.GETFIELD; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.NEW; +import static org.objectweb.asm.Opcodes.PUTFIELD; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V11; + import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.v3.common.ActionReporter; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorContext; +import jakarta.validation.ValidatorFactory; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -29,11 +54,8 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.text.MessageFormat; import java.util.ArrayList; -import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; @@ -44,18 +66,6 @@ import java.util.Set; import java.util.logging.Level; import javax.security.auth.Subject; - -import jakarta.validation.ConstraintViolation; -import jakarta.validation.Validation; -import jakarta.validation.Validator; -import jakarta.validation.ValidatorContext; -import jakarta.validation.ValidatorFactory; -import jakarta.ws.rs.WebApplicationException; -import jakarta.ws.rs.core.HttpHeaders; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.Response.Status; - import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; @@ -76,8 +86,6 @@ import org.glassfish.hk2.utilities.BuilderHelper; import org.glassfish.internal.api.Globals; import org.glassfish.jersey.media.sse.EventOutput; - -import static org.objectweb.asm.Opcodes.*; import org.jvnet.hk2.config.Attribute; import org.jvnet.hk2.config.MessageInterpolatorImpl; import org.objectweb.asm.AnnotationVisitor; @@ -345,7 +353,7 @@ public Set> validateRestModel(Locale locale, T model) Set> constraintViolations = beanValidator.validate(model); if (constraintViolations == null || constraintViolations.isEmpty()) { - return Collections.EMPTY_SET; + return emptySet(); } return constraintViolations; @@ -821,9 +829,9 @@ private void setDefaultValue(MethodVisitor method, String className, String fiel /** * Add the field to the class, adding the @XmlAttribute annotation for marshalling purposes. */ - private void createField(ClassWriter cw, String name, Class type) { + private void createField(ClassWriter classWriter, String name, Class type) { String internalType = getInternalTypeString(type); - FieldVisitor field = cw.visitField(ACC_PRIVATE, getPropertyName(name), internalType, null, null); + FieldVisitor field = classWriter.visitField(ACC_PRIVATE, getPropertyName(name), internalType, null, null); field.visitAnnotation("Ljakarta/xml/bind/annotation/XmlAttribute;", true).visitEnd(); field.visitEnd(); } @@ -831,19 +839,20 @@ private void createField(ClassWriter cw, String name, Class type) { /** * Create getters and setters for the given field */ - private void createGettersAndSetters(ClassWriter cw, Class c, String className, String name, Map props) { + private void createGettersAndSetters(ClassWriter classWriter, Class clazz, String className, String name, Map props) { Class type = (Class) props.get("type"); String internalType = getInternalTypeString(type); className = getInternalName(className); // Create the getter - MethodVisitor getter = cw.visitMethod(ACC_PUBLIC, "get" + name, "()" + internalType, null, null); + MethodVisitor getter = classWriter.visitMethod(ACC_PUBLIC, "get" + name, "()" + internalType, null, null); getter.visitCode(); getter.visitVarInsn(ALOAD, 0); getter.visitFieldInsn(GETFIELD, className, getPropertyName(name), internalType); getter.visitInsn(type.isPrimitive() ? Primitive.getPrimitive(internalType).getReturnOpcode() : ARETURN); getter.visitMaxs(0, 0); getter.visitEnd(); + Map> annotations = (Map>) props.get("annotations"); if (annotations != null) { for (Map.Entry> entry : annotations.entrySet()) { @@ -866,7 +875,7 @@ private void createGettersAndSetters(ClassWriter cw, Class c, String className, } // Create the setter - MethodVisitor setter = cw.visitMethod(ACC_PUBLIC, "set" + name, "(" + internalType + ")V", null, null); + MethodVisitor setter = classWriter.visitMethod(ACC_PUBLIC, "set" + name, "(" + internalType + ")V", null, null); setter.visitCode(); setter.visitVarInsn(ALOAD, 0); setter.visitVarInsn(type.isPrimitive() ? Primitive.getPrimitive(internalType).getSetOpCode() : ALOAD, 1); @@ -888,6 +897,7 @@ private String getInternalName(String className) { private Class defineClass(Class similarClass, String className, byte[] classBytes) throws Exception { RestLogging.restLogger.log(Level.FINEST, "Loading bytecode for {0}", className); + return MethodHandles.privateLookupIn(similarClass, MethodHandles.lookup()).defineClass(classBytes); } @@ -895,13 +905,8 @@ private static synchronized void initBeanValidator() { if (beanValidator != null) { return; } - ClassLoader cl = System.getSecurityManager() == null ? Thread.currentThread().getContextClassLoader() - : AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - }); + + ClassLoader existingClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(Validation.class.getClassLoader()); ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); @@ -909,7 +914,7 @@ public ClassLoader run() { validatorContext.messageInterpolator(new MessageInterpolatorImpl()); beanValidator = validatorContext.getValidator(); } finally { - Thread.currentThread().setContextClassLoader(cl); + Thread.currentThread().setContextClassLoader(existingClassLoader); } } } diff --git a/nucleus/common/common-util/src/main/java/com/sun/enterprise/loader/ASURLClassLoader.java b/nucleus/common/common-util/src/main/java/com/sun/enterprise/loader/ASURLClassLoader.java index 37d7e7809d1..14acd32884c 100644 --- a/nucleus/common/common-util/src/main/java/com/sun/enterprise/loader/ASURLClassLoader.java +++ b/nucleus/common/common-util/src/main/java/com/sun/enterprise/loader/ASURLClassLoader.java @@ -17,12 +17,12 @@ package com.sun.enterprise.loader; +import static java.util.logging.Level.INFO; + import com.sun.appserv.server.util.PreprocessorUtil; -import com.sun.enterprise.security.integration.DDPermissionsLoader; import com.sun.enterprise.security.integration.PermsHolder; import com.sun.enterprise.util.CULoggerInfo; import com.sun.enterprise.util.i18n.StringManager; - import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -66,13 +66,10 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; - import org.glassfish.api.deployment.InstrumentableClassLoader; import org.glassfish.common.util.GlassfishUrlClassLoader; import org.glassfish.hk2.api.PreDestroy; -import static java.util.logging.Level.INFO; - /** * Class loader used by the ejbs of an application or stand-alone module. * @@ -83,8 +80,7 @@ * @author Sivakumar Thyagarajan * @since JDK 1.4 */ -public class ASURLClassLoader extends GlassfishUrlClassLoader - implements JasperAdapter, InstrumentableClassLoader, PreDestroy, DDPermissionsLoader { +public class ASURLClassLoader extends GlassfishUrlClassLoader implements JasperAdapter, InstrumentableClassLoader, PreDestroy { /** logger for this class */ private static final Logger _logger = CULoggerInfo.getLogger(); @@ -615,27 +611,6 @@ private byte[] loadClassData0(final URLEntry res, final String entryName) { return AccessController.doPrivileged(action); } - - @Override - public void addEEPermissions(PermissionCollection eePc) throws SecurityException { - // sm on - if (System.getSecurityManager() != null) { - System.getSecurityManager().checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY); - - permissionsHolder.setEEPermissions(eePc); - } - } - - - @Override - public void addDeclaredPermissions(PermissionCollection declaredPc) throws SecurityException { - if (System.getSecurityManager() != null) { - System.getSecurityManager().checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY); - permissionsHolder.setDeclaredPermissions(declaredPc); - } - } - - @Override protected PermissionCollection getPermissions(CodeSource codeSource) { PermissionCollection cachedPc = permissionsHolder.getCachedPerms(codeSource); diff --git a/nucleus/common/common-util/src/main/java/com/sun/enterprise/security/integration/DDPermissionsLoader.java b/nucleus/common/common-util/src/main/java/com/sun/enterprise/security/integration/DDPermissionsLoader.java deleted file mode 100644 index ae43af1b28d..00000000000 --- a/nucleus/common/common-util/src/main/java/com/sun/enterprise/security/integration/DDPermissionsLoader.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.enterprise.security.integration; - -import java.security.PermissionCollection; - -public interface DDPermissionsLoader { - - String SET_EE_POLICY = "createPolicy.eepermissions"; - - /** - * Pass the declared permission collection from the module handler to the classloader - * - * @param declaredPc the declared permission collection obtained from permissions.xml file throws AccessControlException if - * caller has no privilege - */ - void addDeclaredPermissions(PermissionCollection declaredPc) throws SecurityException; - - /** - * Pass the EE permission to the classloader - * - * @param eePc EE permissions throws AccessControlException if caller has no privilege - */ - void addEEPermissions(PermissionCollection eePc) throws SecurityException; - -} diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityServicesUtil.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityServicesUtil.java index 232ef545312..ecc90889c58 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityServicesUtil.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityServicesUtil.java @@ -20,10 +20,10 @@ */ package com.sun.enterprise.security; -import java.util.logging.Logger; - +import com.sun.enterprise.security.audit.AuditManager; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; import javax.security.auth.callback.CallbackHandler; - import org.glassfish.api.admin.ProcessEnvironment; import org.glassfish.api.admin.ProcessEnvironment.ProcessType; import org.glassfish.api.admin.ServerEnvironment; @@ -31,12 +31,6 @@ import org.glassfish.internal.api.Globals; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.security.audit.AuditManager; -import com.sun.enterprise.util.LocalStringManagerImpl; - -import jakarta.inject.Inject; -import jakarta.inject.Singleton; - @Service @Singleton public class SecurityServicesUtil { @@ -59,6 +53,10 @@ public ServiceLocator getHabitat() { return serviceLocator; } + public ServiceLocator getServiceLocator() { + return serviceLocator; + } + public AuditManager getAuditManager() { return auditManager; }