You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by re...@apache.org on 2026/10/07 12:19:09 UTC
(tomcat) branch 11.0.x updated (593bffc6cd -> 0e86835b51)
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a change to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
from 593bffc6cd Fix import order
new 17c52f2447 Fix NPE in WebappClassLoaderBase.getResources() for leading-slash names
new de42994355 Fix session histogram unlimited time bucket in the Manager
new ab9b5cc7d2 Avoid ConcurrentModificationException rendering the status page
new 8f70906d73 Allow re-adding a host that was previously removed with manager.xml
new 6f077bb20a Stop rendering the host list page twice in the HTML host manager
new 3b08f70fe0 Make guessLocaleFromSession null tolerant in SessionUtils
new d941978970 Report unlimited TTL for sessions that never time out in the Manager
new 64f38a7651 Treat unknown session times as invalidated in the Manager SessionUtils
new df42109be8 Pass the normalized default host name to the mapper in StandardEngine
new b27b47cf0d Reset the default host when it is removed from the mapper
new 0fb0d1f23a Keep naming resource entries consistent when updated through JMX
new da57e5a98e Avoid null valve MBean names in ContainerMBean and MBeanFactory
new cbf31c3ce8 Match the declared signature of the findErrorPage JMX operation
new 5e5e940ac9 Report failed property updates of the connector MBean
new 387bcfb6b2 Quote the user database id when embedding it in MBean names
new 6b16330900 Report when a naming entry was not actually added through JMX
new 0e86835b51 Resolve the modeler type of model MBeans in the MBeanDumper
The 17 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
java/org/apache/catalina/core/StandardEngine.java | 2 +-
.../catalina/loader/WebappClassLoaderBase.java | 4 +
java/org/apache/catalina/manager/JspHelper.java | 8 +-
.../apache/catalina/manager/ManagerServlet.java | 16 ++--
.../catalina/manager/StatusManagerServlet.java | 18 +++-
.../manager/host/HTMLHostManagerServlet.java | 5 +-
.../catalina/manager/host/HostManagerServlet.java | 6 +-
.../apache/catalina/manager/util/SessionUtils.java | 30 ++++++-
java/org/apache/catalina/mapper/Mapper.java | 9 ++
.../org/apache/catalina/mbeans/ConnectorMBean.java | 29 ++++++-
.../org/apache/catalina/mbeans/ContainerMBean.java | 28 ++++++-
.../catalina/mbeans/ContextEnvironmentMBean.java | 41 +++++++++-
java/org/apache/catalina/mbeans/ContextMBean.java | 17 ++--
.../catalina/mbeans/ContextResourceMBean.java | 15 +++-
.../apache/catalina/mbeans/LocalStrings.properties | 1 +
java/org/apache/catalina/mbeans/MBeanDumper.java | 11 ++-
java/org/apache/catalina/mbeans/MBeanFactory.java | 29 +++++--
java/org/apache/catalina/mbeans/MBeanUtils.java | 22 ++---
.../catalina/mbeans/NamingResourcesMBean.java | 20 ++++-
.../catalina/mbeans/SparseUserDatabaseMBean.java | 8 +-
.../catalina/loader/TestWebappClassLoader.java | 28 +++++++
.../catalina/manager/TestHostManagerWebapp.java | 95 ++++++++++++++++++++++
.../apache/catalina/manager/TestManagerWebapp.java | 87 ++++++++++++++++++++
test/org/apache/catalina/mapper/TestMapper.java | 49 +++++++++++
.../apache/catalina/mbeans/TestConnectorMBean.java | 85 +++++++++++++++++++
.../apache/catalina/mbeans/TestContextMBean.java | 75 +++++++++++++++++
.../TestMBeanDumper.java} | 36 ++++----
27 files changed, 698 insertions(+), 76 deletions(-)
create mode 100644 test/org/apache/catalina/mbeans/TestConnectorMBean.java
create mode 100644 test/org/apache/catalina/mbeans/TestContextMBean.java
copy test/org/apache/catalina/{webresources/war/TestHandlerIntegration.java => mbeans/TestMBeanDumper.java} (57%)
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 14/17: Report failed property updates of the connector MBean
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 5e5e940ac923e9ce322dd3673e3d5436be725bfb
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 12:50:11 2026 +0200
Report failed property updates of the connector MBean
The connector MBean read and wrote its properties through
IntrospectionUtils but ignored the outcome. An update of an unknown
property, or of a known property with a value that could not be
converted, for example a port that is not a number, was reported to the
JMX client as a successful change that did nothing, and reading an
unknown attribute returned null instead of the required attribute not
found error.
Fail the update when the value could not be applied, and report an
unknown attribute on read. An unset property keeps returning null, so
the property is only rejected when no getter exists on the connector or
on its protocol handler. Attribute dumps log the error for attributes
that only exist for another protocol at debug level.
---
.../org/apache/catalina/mbeans/ConnectorMBean.java | 29 +++++++-
.../apache/catalina/mbeans/LocalStrings.properties | 1 +
java/org/apache/catalina/mbeans/MBeanDumper.java | 9 +++
.../apache/catalina/mbeans/TestConnectorMBean.java | 85 ++++++++++++++++++++++
4 files changed, 121 insertions(+), 3 deletions(-)
diff --git a/java/org/apache/catalina/mbeans/ConnectorMBean.java b/java/org/apache/catalina/mbeans/ConnectorMBean.java
index 1bdd2a8473..6205bd8148 100644
--- a/java/org/apache/catalina/mbeans/ConnectorMBean.java
+++ b/java/org/apache/catalina/mbeans/ConnectorMBean.java
@@ -51,7 +51,26 @@ public class ConnectorMBean extends ClassNameMBean<Connector> {
}
Connector connector = doGetManagedResource();
- return IntrospectionUtils.getProperty(connector, name);
+ Object value = IntrospectionUtils.getProperty(connector, name);
+ if (value == null) {
+ // An unset property has a null value, an unknown attribute has no
+ // getter. Only report an error for the latter. Protocol handler
+ // properties are read through the connector's getProperty.
+ String capitalized = IntrospectionUtils.capitalize(name);
+ if (!hasGetter(connector.getClass(), capitalized)) {
+ Object handler = connector.getProtocolHandler();
+ if (handler == null || !hasGetter(handler.getClass(), capitalized)) {
+ throw new AttributeNotFoundException(sm.getString("mBean.attributeNotFound", name));
+ }
+ }
+ }
+ return value;
+ }
+
+
+ private static boolean hasGetter(Class<?> clazz, String capitalizedProperty) {
+ return IntrospectionUtils.findMethod(clazz, "get" + capitalizedProperty, null) != null ||
+ IntrospectionUtils.findMethod(clazz, "is" + capitalizedProperty, null) != null;
}
@@ -72,10 +91,14 @@ public class ConnectorMBean extends ClassNameMBean<Connector> {
}
Connector connector = doGetManagedResource();
+ boolean set;
if (value == null) {
- IntrospectionUtils.setProperty(connector, name, null);
+ set = IntrospectionUtils.setProperty(connector, name, null);
} else {
- IntrospectionUtils.setProperty(connector, name, String.valueOf(value));
+ set = IntrospectionUtils.setProperty(connector, name, String.valueOf(value));
+ }
+ if (!set) {
+ throw new MBeanException(new IllegalArgumentException(sm.getString("mBean.setAttributeFail", name)));
}
}
}
diff --git a/java/org/apache/catalina/mbeans/LocalStrings.properties b/java/org/apache/catalina/mbeans/LocalStrings.properties
index 5dc6a1311f..73107d3412 100644
--- a/java/org/apache/catalina/mbeans/LocalStrings.properties
+++ b/java/org/apache/catalina/mbeans/LocalStrings.properties
@@ -38,6 +38,7 @@ mBean.attributeNotFound=Cannot find attribute [{0}]
mBean.nameChange=Cannot update name property
mBean.nullAttribute=Attribute is null
mBean.nullName=Attribute name is null
+mBean.setAttributeFail=Cannot set attribute [{0}]
mBeanDumper.getAttributeError=Error getting attribute [{0}] for object name [{1}]
diff --git a/java/org/apache/catalina/mbeans/MBeanDumper.java b/java/org/apache/catalina/mbeans/MBeanDumper.java
index 83d53e8b10..5812f9f16c 100644
--- a/java/org/apache/catalina/mbeans/MBeanDumper.java
+++ b/java/org/apache/catalina/mbeans/MBeanDumper.java
@@ -20,6 +20,7 @@ import java.lang.reflect.Array;
import java.util.Set;
import java.util.StringJoiner;
+import javax.management.AttributeNotFoundException;
import javax.management.JMRuntimeException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
@@ -113,6 +114,14 @@ public class MBeanDumper {
log.error(sm.getString("mBeanDumper.getAttributeError", attName, oname), rme);
}
continue;
+ } catch (AttributeNotFoundException e) {
+ // Attributes that are advertised in the descriptor for
+ // every protocol but handled by a single protocol do
+ // not exist on the other protocols
+ if (log.isDebugEnabled()) {
+ log.debug(sm.getString("mBeanDumper.getAttributeError", attName, oname), e);
+ }
+ continue;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("mBeanDumper.getAttributeError", attName, oname), t);
diff --git a/test/org/apache/catalina/mbeans/TestConnectorMBean.java b/test/org/apache/catalina/mbeans/TestConnectorMBean.java
new file mode 100644
index 0000000000..d846466970
--- /dev/null
+++ b/test/org/apache/catalina/mbeans/TestConnectorMBean.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.catalina.mbeans;
+
+import java.util.Set;
+
+import javax.management.Attribute;
+import javax.management.AttributeNotFoundException;
+import javax.management.MBeanException;
+import javax.management.MBeanServer;
+import javax.management.ObjectInstance;
+import javax.management.ObjectName;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.tomcat.util.modeler.Registry;
+
+public class TestConnectorMBean extends TomcatBaseTest {
+
+ @Test
+ public void testAttributeFailuresAreReported() throws Exception {
+ Tomcat tomcat = getTomcatInstance();
+ tomcat.start();
+
+ MBeanServer server = Registry.getRegistry(null).getMBeanServer();
+
+ Set<ObjectInstance> connectors = server.queryMBeans(new ObjectName("*:type=Connector,*"), null);
+ Assert.assertEquals(1, connectors.size());
+ ObjectName oname = connectors.iterator().next().getObjectName();
+
+ // A value that cannot be converted. This used to be reported as a
+ // successful update that did nothing.
+ Object port = server.getAttribute(oname, "port");
+
+ try {
+ server.setAttribute(oname, new Attribute("port", "not-a-number"));
+ Assert.fail("Setting an invalid port value must fail");
+ } catch (MBeanException e) {
+ Assert.assertTrue(String.valueOf(e.getCause()), e.getCause() instanceof IllegalArgumentException);
+ }
+
+ // The failed update must not have changed the value
+ Assert.assertEquals(port, server.getAttribute(oname, "port"));
+
+ // An unknown attribute. Reading used to return null and writing used
+ // to do nothing, both without an error.
+ try {
+ server.getAttribute(oname, "notAnAttribute");
+ Assert.fail("Reading an unknown attribute must fail");
+ } catch (AttributeNotFoundException e) {
+ // Expected
+ }
+
+ try {
+ server.setAttribute(oname, new Attribute("notAnAttribute", "x"));
+ Assert.fail("Writing an unknown attribute must fail");
+ } catch (MBeanException e) {
+ // Expected
+ }
+
+ // A protocol handler property that is simply unset reads as null
+ Assert.assertNull(server.getAttribute(oname, "relaxedPathChars"));
+
+ // A valid property can still be written and read
+ server.setAttribute(oname, new Attribute("useBodyEncodingForURI", "true"));
+ Assert.assertEquals(Boolean.TRUE, server.getAttribute(oname, "useBodyEncodingForURI"));
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 17/17: Resolve the modeler type of model MBeans in the MBeanDumper
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 0e86835b5153a129ae11274a4a28c884f5d5c847
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 14:09:02 2026 +0200
Resolve the modeler type of model MBeans in the MBeanDumper
The check that replaces the class name of a model MBean with the type of
its managed resource compared the class name against the class name of
the commons modeler BaseModelMBean, which has not been the base class in
this codebase since the modeler was forked. The branch therefore never
executed and every MBean whose descriptor omits an explicit className,
such as the MBeanFactory registered by the Server, was dumped with
modelerType set to the base class name instead of the actual managed
resource class. Compare against the current base class
org.apache.tomcat.util.modeler.BaseModelMBean so the modelerType
attribute is used as intended. Add a test that starts embedded Tomcat
and checks the dumped modelerType of the MBeanFactory MBean.
---
java/org/apache/catalina/mbeans/MBeanDumper.java | 2 +-
.../apache/catalina/mbeans/TestMBeanDumper.java | 48 ++++++++++++++++++++++
2 files changed, 49 insertions(+), 1 deletion(-)
diff --git a/java/org/apache/catalina/mbeans/MBeanDumper.java b/java/org/apache/catalina/mbeans/MBeanDumper.java
index 5812f9f16c..3230afffd9 100644
--- a/java/org/apache/catalina/mbeans/MBeanDumper.java
+++ b/java/org/apache/catalina/mbeans/MBeanDumper.java
@@ -76,7 +76,7 @@ public class MBeanDumper {
MBeanInfo minfo = mbeanServer.getMBeanInfo(oname);
// can't be null - I think
String code = minfo.getClassName();
- if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
+ if ("org.apache.tomcat.util.modeler.BaseModelMBean".equals(code)) {
code = (String) mbeanServer.getAttribute(oname, "modelerType");
}
buf.append("modelerType: ");
diff --git a/test/org/apache/catalina/mbeans/TestMBeanDumper.java b/test/org/apache/catalina/mbeans/TestMBeanDumper.java
new file mode 100644
index 0000000000..8a08161621
--- /dev/null
+++ b/test/org/apache/catalina/mbeans/TestMBeanDumper.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.catalina.mbeans;
+
+import java.util.Collections;
+import java.util.Set;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.tomcat.util.modeler.Registry;
+
+public class TestMBeanDumper extends TomcatBaseTest {
+
+ @Test
+ public void testDumpResolvesDefaultModelerType() throws Exception {
+ Tomcat tomcat = getTomcatInstance();
+ tomcat.start();
+
+ MBeanServer server = Registry.getRegistry(null).getMBeanServer();
+ ObjectName oname = new ObjectName("Tomcat:type=MBeanFactory");
+ Set<ObjectName> names = Collections.singleton(oname);
+ Assert.assertTrue(server.isRegistered(oname));
+
+ String dump = MBeanDumper.dumpBeans(server, names);
+
+ Assert.assertTrue(dump.contains("modelerType: org.apache.catalina.mbeans.MBeanFactory"));
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 08/17: Treat unknown session times as invalidated in the Manager SessionUtils
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 64f38a765196fdf73ba321e2edd3a4723c2712fd
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:55:04 2026 +0200
Treat unknown session times as invalidated in the Manager SessionUtils
DummyProxySession, which the HTML Manager uses to represent sessions
held on other cluster nodes, returns zero from its time getters. The
time methods in SessionUtils turned those zeros into values of about
the current epoch time, which the UsedTime, InactiveTime and TTL sort
comparators used as ordering keys.
Return the -1 sentinel, documented for invalidated sessions, when the
creation time is not positive, so proxy sessions sort consistently with
unknown values instead of ±epoch magnitudes, and so their zero max
inactive interval is not mistaken for the never-times-out case.
---
.../apache/catalina/manager/util/SessionUtils.java | 19 ++++++++++++++++---
1 file changed, 16 insertions(+), 3 deletions(-)
diff --git a/java/org/apache/catalina/manager/util/SessionUtils.java b/java/org/apache/catalina/manager/util/SessionUtils.java
index 855477b8d9..5fa21e8d28 100644
--- a/java/org/apache/catalina/manager/util/SessionUtils.java
+++ b/java/org/apache/catalina/manager/util/SessionUtils.java
@@ -238,10 +238,14 @@ public class SessionUtils {
*
* @param in_session The session
* @return the time in milliseconds between session creation and the last access, or -1 if the session is
- * invalidated
+ * invalidated or its times are unknown (proxy sessions of a cluster member)
*/
public static long getUsedTimeForSession(Session in_session) {
try {
+ if (in_session.getCreationTime() <= 0) {
+ // Unknown times, e.g. a proxy session of a cluster member
+ return -1;
+ }
return in_session.getThisAccessedTime() - in_session.getCreationTime();
} catch (IllegalStateException ise) {
// ignore: invalidated session
@@ -254,10 +258,14 @@ public class SessionUtils {
*
* @param in_session The session
* @return the remaining TTL in milliseconds, {@link Long#MAX_VALUE} if the session never times out, or -1 if the
- * session is invalidated
+ * session is invalidated or its times are unknown (proxy sessions of a cluster member)
*/
public static long getTTLForSession(Session in_session) {
try {
+ if (in_session.getCreationTime() <= 0) {
+ // Unknown times, e.g. a proxy session of a cluster member
+ return -1;
+ }
int maxInactiveInterval = in_session.getMaxInactiveInterval();
if (maxInactiveInterval <= 0) {
// A non-positive interval means the session never times out
@@ -275,10 +283,15 @@ public class SessionUtils {
* Returns the time in milliseconds since the session was last accessed.
*
* @param in_session The session
- * @return the inactive time in milliseconds, or -1 if the session is invalidated
+ * @return the inactive time in milliseconds, or -1 if the session is invalidated or its times are unknown (proxy
+ * sessions of a cluster member)
*/
public static long getInactiveTimeForSession(Session in_session) {
try {
+ if (in_session.getCreationTime() <= 0) {
+ // Unknown times, e.g. a proxy session of a cluster member
+ return -1;
+ }
return System.currentTimeMillis() - in_session.getThisAccessedTime();
} catch (IllegalStateException ise) {
// ignore: invalidated session
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 07/17: Report unlimited TTL for sessions that never time out in the Manager
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit d941978970bcd4e5206a63ad87b5e37ba85c657a
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:52:43 2026 +0200
Report unlimited TTL for sessions that never time out in the Manager
SessionUtils.getTTLForSession assumed a positive max inactive interval.
A non-positive interval is a supported configuration that means the
session never times out (a context session timeout of zero is stored as
-1 minutes and reaches the session as a negative number of seconds), so
the method returned a negative value whose magnitude grew with the idle
time. The HTML Manager TTL column rendered it as a growing negative
duration and sorting by TTL used a meaningless negative key.
Return Long.MAX_VALUE from getTTLForSession for a non-positive interval,
and display it as "Unlimited" in JspHelper, matching the label used for
these sessions by the text interface session histogram.
---
java/org/apache/catalina/manager/JspHelper.java | 8 ++++++--
java/org/apache/catalina/manager/util/SessionUtils.java | 10 ++++++++--
2 files changed, 14 insertions(+), 4 deletions(-)
diff --git a/java/org/apache/catalina/manager/JspHelper.java b/java/org/apache/catalina/manager/JspHelper.java
index 7c4bdb1937..e1241815d3 100644
--- a/java/org/apache/catalina/manager/JspHelper.java
+++ b/java/org/apache/catalina/manager/JspHelper.java
@@ -136,7 +136,7 @@ public class JspHelper {
* Returns the formatted time-to-live for the given session.
*
* @param in_session the session
- * @return the formatted TTL string
+ * @return the formatted TTL string, or "Unlimited" for sessions that never time out
*/
public static String getDisplayTTLForSession(Session in_session) {
try {
@@ -147,7 +147,11 @@ public class JspHelper {
// ignore: invalidated session
return "";
}
- return secondsToTimeString(SessionUtils.getTTLForSession(in_session) / 1000);
+ long ttl = SessionUtils.getTTLForSession(in_session);
+ if (ttl == Long.MAX_VALUE) {
+ return "Unlimited";
+ }
+ return secondsToTimeString(ttl / 1000);
}
/**
diff --git a/java/org/apache/catalina/manager/util/SessionUtils.java b/java/org/apache/catalina/manager/util/SessionUtils.java
index a4caac73cb..855477b8d9 100644
--- a/java/org/apache/catalina/manager/util/SessionUtils.java
+++ b/java/org/apache/catalina/manager/util/SessionUtils.java
@@ -253,11 +253,17 @@ public class SessionUtils {
* Returns the remaining time-to-live for the session in milliseconds.
*
* @param in_session The session
- * @return the remaining TTL in milliseconds, or -1 if the session is invalidated
+ * @return the remaining TTL in milliseconds, {@link Long#MAX_VALUE} if the session never times out, or -1 if the
+ * session is invalidated
*/
public static long getTTLForSession(Session in_session) {
try {
- return 1000L * in_session.getMaxInactiveInterval() -
+ int maxInactiveInterval = in_session.getMaxInactiveInterval();
+ if (maxInactiveInterval <= 0) {
+ // A non-positive interval means the session never times out
+ return Long.MAX_VALUE;
+ }
+ return 1000L * maxInactiveInterval -
(System.currentTimeMillis() - in_session.getThisAccessedTime());
} catch (IllegalStateException ise) {
// ignore: invalidated session
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 04/17: Allow re-adding a host that was previously removed with manager.xml
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 8f70906d736f721b05679c740e732f7506bd6486
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:31:59 2026 +0200
Allow re-adding a host that was previously removed with manager.xml
Removing a host does not physically remove the host configuration
directory. When the removed host had been created with the manager
attribute, the manager.xml copy installed in the configuration
directory for that host remained behind. Adding a host again with the
same name and manager=true then failed with "Couldn't install
manager.xml" because Files.copy() refuses to replace an existing
target, so the host was never created. This is a common flow since the
HTML add form checks the manager option by default.
Copy manager.xml with StandardCopyOption.REPLACE_EXISTING so the
template shipped with the running host manager application overwrites
the leftover file, matching the behaviour of a fresh add.
Add a test covering add, remove and re-add with manager=true.
---
.../catalina/manager/host/HostManagerServlet.java | 6 +-
.../catalina/manager/TestHostManagerWebapp.java | 95 ++++++++++++++++++++++
2 files changed, 100 insertions(+), 1 deletion(-)
diff --git a/java/org/apache/catalina/manager/host/HostManagerServlet.java b/java/org/apache/catalina/manager/host/HostManagerServlet.java
index 4111306215..d1d0de5c04 100644
--- a/java/org/apache/catalina/manager/host/HostManagerServlet.java
+++ b/java/org/apache/catalina/manager/host/HostManagerServlet.java
@@ -24,6 +24,7 @@ import java.io.Serial;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
import java.util.StringTokenizer;
import javax.management.InstanceNotFoundException;
@@ -388,7 +389,10 @@ public class HostManagerServlet extends HttpServlet implements ContainerServlet
return;
}
Path dest = new File(configBaseFile, "manager.xml").toPath();
- Files.copy(is, dest);
+ // Replace any manager.xml left behind by a previous host
+ // with the same name. Removing a host does not delete the
+ // configuration directory.
+ Files.copy(is, dest, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
writer.println(smClient.getString("hostManagerServlet.managerXml"));
return;
diff --git a/test/org/apache/catalina/manager/TestHostManagerWebapp.java b/test/org/apache/catalina/manager/TestHostManagerWebapp.java
index e2af5fca9a..9330254a2d 100644
--- a/test/org/apache/catalina/manager/TestHostManagerWebapp.java
+++ b/test/org/apache/catalina/manager/TestHostManagerWebapp.java
@@ -297,4 +297,99 @@ public class TestHostManagerWebapp extends TomcatBaseTest {
tomcat.stop();
}
+
+
+ /*
+ * Removing a host leaves the configuration directory in place. Re-adding
+ * a host with the same name using manager=true must then replace the
+ * leftover manager.xml rather than failing to install it.
+ */
+ @Test
+ public void testAddRemoveReAddWithManager() throws Exception {
+ System.setProperty("catalina.home", getBuildDirectory().getAbsolutePath());
+ Tomcat tomcat = getTomcatInstance();
+ tomcat.setAddDefaultWebXmlToWebapp(false);
+
+ File configFile = new File(getTemporaryDirectory(), "tomcat-users-host-manager-readd.xml");
+ try (PrintWriter writer = new PrintWriter(configFile)) {
+ writer.write(TestManagerWebapp.CONFIG);
+ }
+ addDeleteOnTearDown(configFile);
+
+ MemoryRealm memoryRealm = new MemoryRealm();
+ memoryRealm.setCredentialHandler(new MessageDigestCredentialHandler());
+ memoryRealm.setPathname(configFile.getAbsolutePath());
+ tomcat.getEngine().setRealm(memoryRealm);
+
+ File confFolder = new File(getTemporaryDirectory(), "conf");
+ confFolder.mkdirs();
+ File webappDir = new File(getBuildDirectory(), "webapps");
+
+ File appDir = new File(webappDir, "host-manager");
+ tomcat.addWebapp(null, "/host-manager", appDir.getAbsolutePath());
+
+ getProgrammaticRootContext();
+
+ tomcat.start();
+
+ SimpleHttpClient client = new SimpleHttpClient() {
+ @Override
+ public boolean isResponseBodyOK() {
+ return true;
+ }
+ };
+ client.setPort(getPort());
+ String basicHeader = (new BasicAuthHeader("Basic", "admin", "sekr3t")).getHeader().toString();
+
+ // @formatter:off
+ client.setRequest(new String[] {
+ "GET /host-manager/text/add?name=rehost&manager=true HTTP/1.1" + CRLF +
+ "Host: localhost" + CRLF +
+ "Authorization: " + basicHeader + CRLF +
+ "Connection: Close" + CRLF +
+ CRLF
+ });
+ // @formatter:on
+ client.connect();
+ client.processRequest(true);
+ Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode());
+ Assert.assertTrue(client.getResponseBody(),
+ client.getResponseBody().contains("OK - Host [rehost] added"));
+ File managerXml = new File(confFolder, tomcat.getEngine().getName() + "/rehost/manager.xml");
+ Assert.assertTrue(managerXml.getAbsolutePath(), managerXml.isFile());
+
+ // @formatter:off
+ client.setRequest(new String[] {
+ "GET /host-manager/text/remove?name=rehost HTTP/1.1" + CRLF +
+ "Host: localhost" + CRLF +
+ "Authorization: " + basicHeader + CRLF +
+ "Connection: Close" + CRLF +
+ CRLF
+ });
+ // @formatter:on
+ client.connect();
+ client.processRequest(true);
+ Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode());
+ Assert.assertTrue(client.getResponseBody(),
+ client.getResponseBody().contains("OK - Removed host [rehost]"));
+ // The configuration directory is intentionally left in place
+ Assert.assertTrue(managerXml.getAbsolutePath(), managerXml.isFile());
+
+ // @formatter:off
+ client.setRequest(new String[] {
+ "GET /host-manager/text/add?name=rehost&manager=true HTTP/1.1" + CRLF +
+ "Host: localhost" + CRLF +
+ "Authorization: " + basicHeader + CRLF +
+ "Connection: Close" + CRLF +
+ CRLF
+ });
+ // @formatter:on
+ client.connect();
+ client.processRequest(true);
+ Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode());
+ Assert.assertTrue(client.getResponseBody(),
+ client.getResponseBody().contains("OK - Host [rehost] added"));
+
+ tomcat.stop();
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 13/17: Match the declared signature of the findErrorPage JMX operation
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit cbf31c3ce8fc17ce866e3a9f03d24fcf43bc10a6
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 12:36:22 2026 +0200
Match the declared signature of the findErrorPage JMX operation
The descriptor of StandardContext declares the findErrorPage operation
with a java.lang.String parameter, but the MBean only provided
overloads for an HTTP error code and a Throwable. The modeler reflects
with exactly the declared parameter types, so every invocation of the
operation failed with a ReflectionException, and the Throwable variant
was never reachable through JMX.
Implement the operation with the declared String signature, resolving
the error page by the exact configured exception type name.
---
java/org/apache/catalina/mbeans/ContextMBean.java | 17 +++--
.../apache/catalina/mbeans/TestContextMBean.java | 75 ++++++++++++++++++++++
2 files changed, 85 insertions(+), 7 deletions(-)
diff --git a/java/org/apache/catalina/mbeans/ContextMBean.java b/java/org/apache/catalina/mbeans/ContextMBean.java
index 23c27e1437..980793ab73 100644
--- a/java/org/apache/catalina/mbeans/ContextMBean.java
+++ b/java/org/apache/catalina/mbeans/ContextMBean.java
@@ -102,20 +102,23 @@ public class ContextMBean extends BaseCatalinaMBean<Context> {
/**
* Return the error page entry for the specified Java exception type, if any; otherwise return <code>null</code>.
*
- * @param exceptionType Exception type to look up
+ * @param exceptionType Fully qualified class name of the exception type to look up
*
* @return a string representation of the error page
*
* @throws MBeanException propagated from the managed resource access
*/
- public String findErrorPage(Throwable exceptionType) throws MBeanException {
- Context context = doGetManagedResource();
- ErrorPage errorPage = context.findErrorPage(exceptionType);
- if (errorPage != null) {
- return errorPage.toString();
- } else {
+ public String findErrorPage(String exceptionType) throws MBeanException {
+ if (exceptionType == null) {
return null;
}
+ Context context = doGetManagedResource();
+ for (ErrorPage errorPage : context.findErrorPages()) {
+ if (exceptionType.equals(errorPage.getExceptionType())) {
+ return errorPage.toString();
+ }
+ }
+ return null;
}
diff --git a/test/org/apache/catalina/mbeans/TestContextMBean.java b/test/org/apache/catalina/mbeans/TestContextMBean.java
new file mode 100644
index 0000000000..cbe3005e1e
--- /dev/null
+++ b/test/org/apache/catalina/mbeans/TestContextMBean.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.catalina.mbeans;
+
+import java.io.File;
+import java.util.Set;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectInstance;
+import javax.management.ObjectName;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.core.StandardContext;
+import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.tomcat.util.descriptor.web.ErrorPage;
+import org.apache.tomcat.util.modeler.Registry;
+
+public class TestContextMBean extends TomcatBaseTest {
+
+ @Test
+ public void testFindErrorPageByExceptionType() throws Exception {
+ Tomcat tomcat = getTomcatInstance();
+
+ File appDir = new File(getTemporaryDirectory(), "ctxmbean");
+ Assert.assertTrue(appDir.mkdirs());
+ Context context = tomcat.addContext("", appDir.getAbsolutePath());
+
+ ErrorPage errorPage = new ErrorPage();
+ errorPage.setExceptionType("java.lang.RuntimeException");
+ errorPage.setLocation("/error");
+ ((StandardContext) context).addErrorPage(errorPage);
+
+ tomcat.start();
+
+ MBeanServer server = Registry.getRegistry(null).getMBeanServer();
+
+ Set<ObjectInstance> objectInstances =
+ server.queryMBeans(new ObjectName("*:j2eeType=WebModule,*"), null);
+ ObjectName oname = null;
+ for (ObjectInstance objectInstance : objectInstances) {
+ if ("//localhost/".equals(objectInstance.getObjectName().getKeyProperty("name"))) {
+ oname = objectInstance.getObjectName();
+ }
+ }
+ Assert.assertNotNull(oname);
+
+ Object result = server.invoke(oname, "findErrorPage", new Object[] { "java.lang.RuntimeException" },
+ new String[] { "java.lang.String" });
+
+ Assert.assertNotNull(result);
+ Assert.assertTrue(result.toString(), result.toString().contains("/error"));
+
+ // Exception types are matched by exact name, not by assignability
+ Assert.assertNull(server.invoke(oname, "findErrorPage", new Object[] { "java.lang.Error" },
+ new String[] { "java.lang.String" }));
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 06/17: Make guessLocaleFromSession null tolerant in SessionUtils
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 3b08f70fe0ba12b48dd9756b3eb7f506b83210e6
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:48:13 2026 +0200
Make guessLocaleFromSession null tolerant in SessionUtils
The org.apache.catalina.Session overload dereferenced its argument
immediately, throwing a NullPointerException for a null argument even
though its documented return contract covers the undeterminable case
and the parallel guessUserFromSession(Session) method returns null for
a null argument.
Return null for a null argument, consistent with the sibling method.
The defect is not reachable from the current callers in the Manager
web application; this aligns the public utility behaviour.
---
java/org/apache/catalina/manager/util/SessionUtils.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/java/org/apache/catalina/manager/util/SessionUtils.java b/java/org/apache/catalina/manager/util/SessionUtils.java
index a0b01eea5d..a4caac73cb 100644
--- a/java/org/apache/catalina/manager/util/SessionUtils.java
+++ b/java/org/apache/catalina/manager/util/SessionUtils.java
@@ -68,6 +68,9 @@ public class SessionUtils {
* @return the locale, or {@code null} if it cannot be determined
*/
public static Locale guessLocaleFromSession(final Session in_session) {
+ if (null == in_session) {
+ return null;
+ }
return guessLocaleFromSession(in_session.getSession());
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 02/17: Fix session histogram unlimited time bucket in the Manager
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit de42994355e733f9e97bf2216533f6b087576835
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:17:26 2026 +0200
Fix session histogram unlimited time bucket in the Manager
The Manager text interface session histogram counted sessions with an
unlimited timeout in a bucket selected by testing for a negative idle
time. Idle time is never negative, so the branch was dead, the
"Unlimited time" line was never displayed and sessions which never
time out were silently miscounted into ordinary idle-time buckets.
Count sessions with a negative max inactive interval explicitly as
unlimited. A negative interval is the sentinel for "never times
out"; note that a context session timeout of zero is stored as -1
minutes which becomes -60 seconds on sessions created for that
context. The existing idle-based expiry behaviour triggered by the
idle parameter is unchanged.
Clamp a negative idle time - possible only if the system clock moves
backwards - into the first bucket instead of letting it index the
histogram array out of bounds, as the removed branch incidentally
used to do.
Add a test covering sessions with a max inactive interval of -1 and
sessions created for a context with a session timeout of zero.
---
.../apache/catalina/manager/ManagerServlet.java | 16 ++--
.../apache/catalina/manager/TestManagerWebapp.java | 87 ++++++++++++++++++++++
2 files changed, 98 insertions(+), 5 deletions(-)
diff --git a/java/org/apache/catalina/manager/ManagerServlet.java b/java/org/apache/catalina/manager/ManagerServlet.java
index 0c55535fa4..14801d9dea 100644
--- a/java/org/apache/catalina/manager/ManagerServlet.java
+++ b/java/org/apache/catalina/manager/ManagerServlet.java
@@ -1292,13 +1292,19 @@ public class ManagerServlet extends HttpServlet implements ContainerServlet {
session.expire();
expired++;
}
- time = time / 60 / histoInterval;
- if (time < 0) {
+ // Negative interval: session never times out (a context
+ // session timeout of zero is stored as -1 minutes which
+ // becomes -60 seconds on the session)
+ if (session.getMaxInactiveInterval() < 0) {
notimeout++;
- } else if (time >= maxCount) {
- timeout[maxCount]++;
} else {
- timeout[time]++;
+ // Clamp negative idle time (system clock went backwards)
+ time = Math.max(time, 0) / 60 / histoInterval;
+ if (time >= maxCount) {
+ timeout[maxCount]++;
+ } else {
+ timeout[time]++;
+ }
}
}
if (timeout[0] > 0) {
diff --git a/test/org/apache/catalina/manager/TestManagerWebapp.java b/test/org/apache/catalina/manager/TestManagerWebapp.java
index 18bc35dd44..890d831f94 100644
--- a/test/org/apache/catalina/manager/TestManagerWebapp.java
+++ b/test/org/apache/catalina/manager/TestManagerWebapp.java
@@ -35,10 +35,12 @@ import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
+import org.apache.catalina.Session;
import org.apache.catalina.authenticator.TestBasicAuthParser.BasicAuthHeader;
import org.apache.catalina.filters.Constants;
import org.apache.catalina.realm.MemoryRealm;
import org.apache.catalina.realm.MessageDigestCredentialHandler;
+import org.apache.catalina.session.ManagerBase;
import org.apache.catalina.startup.Catalina;
import org.apache.catalina.startup.HostConfig;
import org.apache.catalina.startup.SimpleHttpClient;
@@ -617,6 +619,91 @@ public class TestManagerWebapp extends TomcatBaseTest {
}
}
+ /*
+ * A session with an unlimited timeout (maxInactiveInterval == -1) must
+ * be counted in the "Unlimited time" bucket of the text interface
+ * session histogram rather than in an idle-time bucket.
+ */
+ @Test
+ public void testSessionsUnlimitedTimeout() throws Exception {
+ ignoreTearDown = true;
+ Tomcat tomcat = getTomcatInstance();
+ tomcat.setAddDefaultWebXmlToWebapp(false);
+ tomcat.addUser("admin", "sekr3t");
+ tomcat.addRole("admin", "manager-script");
+
+ File webappDir = new File(getBuildDirectory(), "webapps");
+ File appDir = new File(webappDir, "manager");
+ tomcat.addWebapp(null, "/manager", appDir.getAbsolutePath());
+
+ Context ctx = tomcat.addContext("/testsession", null);
+ // A session timeout of zero means sessions never time out. It is
+ // stored as -1 minutes which becomes -60 seconds on the session.
+ Context zeroCtx = tomcat.addContext("/testsession0", null);
+ zeroCtx.setSessionTimeout(0);
+
+ tomcat.start();
+
+ ManagerBase manager = (ManagerBase) ctx.getManager();
+ Session unlimited = manager.createSession(null);
+ unlimited.setMaxInactiveInterval(-1);
+ manager.add(unlimited);
+
+ Session limited = manager.createSession(null);
+ manager.add(limited);
+
+ ManagerBase zeroManager = (ManagerBase) zeroCtx.getManager();
+ Session zeroTimeout = zeroManager.createSession(null);
+ Assert.assertEquals(-60, zeroTimeout.getMaxInactiveInterval());
+ zeroManager.add(zeroTimeout);
+
+ SimpleHttpClient client = new SimpleHttpClient() {
+ @Override
+ public boolean isResponseBodyOK() {
+ return true;
+ }
+ };
+ client.setPort(getPort());
+ String basicHeader =
+ (new BasicAuthHeader("Basic", "admin", "sekr3t")).getHeader().toString();
+
+ // @formatter:off
+ client.setRequest(new String[] {
+ "GET /manager/text/sessions?path=/testsession HTTP/1.1" + CRLF +
+ "Host: localhost" + CRLF +
+ "Authorization: " + basicHeader + CRLF +
+ "Connection: Close" + CRLF +
+ CRLF
+ });
+ // @formatter:on
+ client.connect();
+ client.processRequest(true);
+ Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode());
+ Assert.assertTrue(client.getResponseBody(),
+ client.getResponseBody().contains("Unlimited time: [1] sessions"));
+ // The unlimited session must not also appear in an idle bucket
+ Assert.assertTrue(client.getResponseBody(),
+ client.getResponseBody().contains("Inactive for [<1] minutes: [1] sessions"));
+
+ // @formatter:off
+ client.setRequest(new String[] {
+ "GET /manager/text/sessions?path=/testsession0 HTTP/1.1" + CRLF +
+ "Host: localhost" + CRLF +
+ "Authorization: " + basicHeader + CRLF +
+ "Connection: Close" + CRLF +
+ CRLF
+ });
+ // @formatter:on
+ client.connect();
+ client.processRequest(true);
+ Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode());
+ Assert.assertTrue(client.getResponseBody(),
+ client.getResponseBody().contains("Unlimited time: [1] sessions"));
+
+ tomcat.stop();
+ }
+
+
/*
* Verify that manager JSPs compile and render correctly.
*/
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 10/17: Reset the default host when it is removed from the mapper
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit b27b47cf0d411733bea5112caeacc5406e78fa0a
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 12:18:21 2026 +0200
Reset the default host when it is removed from the mapper
Neither removeHost() nor removeHostAlias() updated the default host
reference when the removed entry was the one the default host name had
resolved to, including alias entries. Mapping then kept handing the
removed Host object to requests whose host name matched nothing, and
when the contexts of the removed host were still registered, those
requests were dispatched into the contexts of the removed host instead
of failing with a clean 404.
Clear the default host reference in both removal methods when they
remove the host or alias it points at. The configured default host name
is kept, so re-registering the host resolves the default again. Add unit
tests for both removal paths.
---
java/org/apache/catalina/mapper/Mapper.java | 9 +++++
test/org/apache/catalina/mapper/TestMapper.java | 49 +++++++++++++++++++++++++
2 files changed, 58 insertions(+)
diff --git a/java/org/apache/catalina/mapper/Mapper.java b/java/org/apache/catalina/mapper/Mapper.java
index d240ab14ef..76dbe45391 100644
--- a/java/org/apache/catalina/mapper/Mapper.java
+++ b/java/org/apache/catalina/mapper/Mapper.java
@@ -166,6 +166,12 @@ public final class Mapper {
if (host == null || host.isAlias()) {
return;
}
+ // Requests must not keep going to a removed host, even if it was the
+ // default host. A new default host is resolved again if the
+ // configuration still refers to a host that exists.
+ if (defaultHost != null && defaultHost.getRealHost() == host) {
+ defaultHost = null;
+ }
MappedHost[] newHosts = hosts.clone();
// Remove real host and all its aliases
int j = 0;
@@ -241,6 +247,9 @@ public final class Mapper {
if (removeMap(hosts, newHosts, alias)) {
hosts = newHosts;
hostMapping.getRealHost().removeAlias(hostMapping);
+ if (defaultHost == hostMapping) {
+ defaultHost = null;
+ }
}
}
diff --git a/test/org/apache/catalina/mapper/TestMapper.java b/test/org/apache/catalina/mapper/TestMapper.java
index 589110e255..3fbba1aeab 100644
--- a/test/org/apache/catalina/mapper/TestMapper.java
+++ b/test/org/apache/catalina/mapper/TestMapper.java
@@ -216,6 +216,55 @@ public class TestMapper extends LoggingBaseTest {
}
}
+ @Test
+ public void testRemoveDefaultHost() throws Exception {
+ Mapper defaultHostMapper = new Mapper();
+
+ Host host = createHost("defaulthostobject");
+ defaultHostMapper.addHost("defaulthost", new String[0], host);
+ defaultHostMapper.addContextVersion("defaulthost", host, "", "0", createContext("defaulthostcontext"),
+ new String[0], null, null);
+ defaultHostMapper.setDefaultHostName("defaulthost");
+
+ defaultHostMapper.removeHost("defaulthost");
+
+ MappingData mappingData = new MappingData();
+ MessageBytes hostMB = MessageBytes.newInstance();
+ hostMB.setString("unknown.example");
+ MessageBytes uriMB = MessageBytes.newInstance();
+ char[] uri = "/index.html".toCharArray();
+ uriMB.setChars(uri, 0, uri.length);
+
+ defaultHostMapper.map(hostMB, uriMB, null, mappingData);
+
+ Assert.assertNull(mappingData.host);
+ }
+
+ @Test
+ public void testRemoveDefaultHostAlias() throws Exception {
+ Mapper defaultHostMapper = new Mapper();
+
+ Host host = createHost("aliasdefaulthostobject");
+ defaultHostMapper.addHost("hostname", new String[0], host);
+ defaultHostMapper.addHostAlias("hostname", "aliasname");
+ defaultHostMapper.addContextVersion("hostname", host, "", "0", createContext("aliasdefaulthostcontext"),
+ new String[0], null, null);
+ defaultHostMapper.setDefaultHostName("aliasname");
+
+ defaultHostMapper.removeHostAlias("aliasname");
+
+ MappingData mappingData = new MappingData();
+ MessageBytes hostMB = MessageBytes.newInstance();
+ hostMB.setString("unknown.example");
+ MessageBytes uriMB = MessageBytes.newInstance();
+ char[] uri = "/index.html".toCharArray();
+ uriMB.setChars(uri, 0, uri.length);
+
+ defaultHostMapper.map(hostMB, uriMB, null, mappingData);
+
+ Assert.assertNull(mappingData.host);
+ }
+
@Test
public void testMap() throws Exception {
MappingData mappingData = new MappingData();
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 05/17: Stop rendering the host list page twice in the HTML host manager
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 6f077bb20a95447cab06e37ab895cea5f725c115
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:39:55 2026 +0200
Stop rendering the host list page twice in the HTML host manager
For a POST request with an unknown command, doPost handed the request
off to doGet - which renders the full page and closes the response
writer - and then rendered the list page a second time. The second
document was written to the closed output buffer and silently
discarded.
Return after delegating to doGet, matching the long-standing pattern in
the sibling HTMLManagerServlet, so nothing is rendered after the
delegated GET handling.
---
java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java b/java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
index 41debd06e2..3db1272af8 100644
--- a/java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
+++ b/java/org/apache/catalina/manager/host/HTMLHostManagerServlet.java
@@ -122,8 +122,11 @@ public class HTMLHostManagerServlet extends HostManagerServlet {
} else if (command.equals("/persist")) {
message = persist(smClient);
} else {
- // Try GET
+ // Try GET. The GET handling renders the response in full, so
+ // nothing must be rendered afterwards to avoid writing a second
+ // document on the closed writer.
doGet(request, response);
+ return;
}
list(request, response, message, smClient);
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 15/17: Quote the user database id when embedding it in MBean names
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 387bcfb6b219826638270ad9431249cb23ac4ab2
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 13:38:36 2026 +0200
Quote the user database id when embedding it in MBean names
The createObjectName methods in MBeanUtils already quoted the username,
groupname and rolename when constructing the ObjectName for a User,
Group or Role MBean, but the user database id was appended unquoted. An
id containing characters special to ObjectNames (for example a colon)
therefore produced a malformed ObjectName, throwing
MalformedObjectNameException on registration, while destroy and the
sparse save path could fail to find MBeans registered under a name whose
properties had been re-parsed. Apply ObjectName.quote() to the id in all
four createObjectName methods and, to keep the creation and destruction
sides consistent, apply the same quoting in destroyMBeanUserDatabase()
and in the queries executed by SparseUserDatabaseMBean.save(). Note that
ObjectName.quote() always returns the double-quoted form, so plain ids
now appear as database="UserDatabase" in registered names, matching the
treatment usernames and role/group names already receive.
---
java/org/apache/catalina/mbeans/MBeanUtils.java | 22 ++++++++++++----------
.../catalina/mbeans/SparseUserDatabaseMBean.java | 8 +++++---
2 files changed, 17 insertions(+), 13 deletions(-)
diff --git a/java/org/apache/catalina/mbeans/MBeanUtils.java b/java/org/apache/catalina/mbeans/MBeanUtils.java
index 4b20476a3d..9ef621e758 100644
--- a/java/org/apache/catalina/mbeans/MBeanUtils.java
+++ b/java/org/apache/catalina/mbeans/MBeanUtils.java
@@ -454,7 +454,7 @@ public class MBeanUtils {
static ObjectName createObjectName(String domain, Group group) throws MalformedObjectNameException {
return new ObjectName(domain + ":type=Group,groupname=" + ObjectName.quote(group.getGroupname()) +
- ",database=" + group.getUserDatabase().getId());
+ ",database=" + ObjectName.quote(group.getUserDatabase().getId()));
}
@@ -472,7 +472,7 @@ public class MBeanUtils {
static ObjectName createObjectName(String domain, Role role) throws MalformedObjectNameException {
return new ObjectName(domain + ":type=Role,rolename=" + ObjectName.quote(role.getRolename()) + ",database=" +
- role.getUserDatabase().getId());
+ ObjectName.quote(role.getUserDatabase().getId()));
}
@@ -489,8 +489,8 @@ public class MBeanUtils {
*/
static ObjectName createObjectName(String domain, User user) throws MalformedObjectNameException {
- return new ObjectName(domain + ":type=User,username=" + ObjectName.quote(user.getUsername()) + ",database=" +
- user.getUserDatabase().getId());
+ return new ObjectName(domain + ":type=User,username=" + ObjectName.quote(user.getUsername()) +
+ ",database=" + ObjectName.quote(user.getUserDatabase().getId()));
}
@@ -506,7 +506,7 @@ public class MBeanUtils {
*/
static ObjectName createObjectName(String domain, UserDatabase userDatabase) throws MalformedObjectNameException {
- return new ObjectName(domain + ":type=UserDatabase,database=" + userDatabase.getId());
+ return new ObjectName(domain + ":type=UserDatabase,database=" + ObjectName.quote(userDatabase.getId()));
}
@@ -726,36 +726,38 @@ public class MBeanUtils {
// FIXME: UserDatabase MBean management could be improved
+ String quotedDatabase = ObjectName.quote(userDatabase);
+
ObjectName query;
Set<ObjectName> results;
// Groups
- query = new ObjectName("Users:type=Group,database=" + userDatabase + ",*");
+ query = new ObjectName("Users:type=Group,database=" + quotedDatabase + ",*");
results = mserver.queryNames(query, null);
for (ObjectName result : results) {
mserver.unregisterMBean(result);
}
// Roles
- query = new ObjectName("Users:type=Role,database=" + userDatabase + ",*");
+ query = new ObjectName("Users:type=Role,database=" + quotedDatabase + ",*");
results = mserver.queryNames(query, null);
for (ObjectName result : results) {
mserver.unregisterMBean(result);
}
// Users
- query = new ObjectName("Users:type=User,database=" + userDatabase + ",*");
+ query = new ObjectName("Users:type=User,database=" + quotedDatabase + ",*");
results = mserver.queryNames(query, null);
for (ObjectName result : results) {
mserver.unregisterMBean(result);
}
// The database itself
- ObjectName db = new ObjectName("Users:type=UserDatabase,database=" + userDatabase);
+ ObjectName db = new ObjectName("Users:type=UserDatabase,database=" + quotedDatabase);
if (mserver.isRegistered(db)) {
mserver.unregisterMBean(db);
}
- db = new ObjectName("Catalina:type=UserDatabase,database=" + userDatabase);
+ db = new ObjectName("Catalina:type=UserDatabase,database=" + quotedDatabase);
if (mserver.isRegistered(db)) {
mserver.unregisterMBean(db);
}
diff --git a/java/org/apache/catalina/mbeans/SparseUserDatabaseMBean.java b/java/org/apache/catalina/mbeans/SparseUserDatabaseMBean.java
index 50bff322b2..0a183dd034 100644
--- a/java/org/apache/catalina/mbeans/SparseUserDatabaseMBean.java
+++ b/java/org/apache/catalina/mbeans/SparseUserDatabaseMBean.java
@@ -358,25 +358,27 @@ public class SparseUserDatabaseMBean extends BaseModelMBean {
try {
UserDatabase database = (UserDatabase) this.resource;
if (database.isSparse()) {
+ String quotedDatabase = ObjectName.quote(database.getId());
+
ObjectName query;
Set<ObjectName> results;
// Groups
- query = new ObjectName("Users:type=Group,database=" + database.getId() + ",*");
+ query = new ObjectName("Users:type=Group,database=" + quotedDatabase + ",*");
results = mserver.queryNames(query, null);
for (ObjectName result : results) {
mserver.unregisterMBean(result);
}
// Roles
- query = new ObjectName("Users:type=Role,database=" + database.getId() + ",*");
+ query = new ObjectName("Users:type=Role,database=" + quotedDatabase + ",*");
results = mserver.queryNames(query, null);
for (ObjectName result : results) {
mserver.unregisterMBean(result);
}
// Users
- query = new ObjectName("Users:type=User,database=" + database.getId() + ",*");
+ query = new ObjectName("Users:type=User,database=" + quotedDatabase + ",*");
results = mserver.queryNames(query, null);
for (ObjectName result : results) {
mserver.unregisterMBean(result);
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 03/17: Avoid ConcurrentModificationException rendering the status page
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit ab9b5cc7d26ab89692ffbef25aff013a65f20e55
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 11:24:55 2026 +0200
Avoid ConcurrentModificationException rendering the status page
The object name lists used to render connector status are
Collections.synchronizedList instances which handleNotification()
modifies concurrently when connector MBeans are registered or
unregistered at runtime. StatusTransformer iterates them with plain
for-each loops without holding the list monitor, which the
synchronizedList contract does not cover, so a connector change
during rendering could fail the whole status page with a
ConcurrentModificationException wrapped in a ServletException.
Pass snapshots of the three lists, taken while holding each list's
own monitor, to StatusTransformer.writeConnectorsState() at its
single call site rather than the live lists.
---
.../apache/catalina/manager/StatusManagerServlet.java | 18 ++++++++++++++++--
1 file changed, 16 insertions(+), 2 deletions(-)
diff --git a/java/org/apache/catalina/manager/StatusManagerServlet.java b/java/org/apache/catalina/manager/StatusManagerServlet.java
index 93b8945b88..ae5147a765 100644
--- a/java/org/apache/catalina/manager/StatusManagerServlet.java
+++ b/java/org/apache/catalina/manager/StatusManagerServlet.java
@@ -286,8 +286,12 @@ public class StatusManagerServlet extends HttpServlet implements NotificationLis
args[16] = smClient.getString("htmlManagerServlet.connectorStateTableTitleVHost");
args[17] = smClient.getString("htmlManagerServlet.connectorStateTableTitleRequest");
args[18] = smClient.getString("htmlManagerServlet.connectorStateHint");
- StatusTransformer.writeConnectorsState(writer, mBeanServer, threadPools, globalRequestProcessors,
- requestProcessors, mode, args);
+ // Take snapshots of the lists. They may be modified concurrently
+ // by handleNotification() when connectors are registered or
+ // unregistered and StatusTransformer iterates them without
+ // holding the lists' monitor.
+ StatusTransformer.writeConnectorsState(writer, mBeanServer, copyOf(threadPools),
+ copyOf(globalRequestProcessors), copyOf(requestProcessors), mode, args);
if (request.getPathInfo() != null && request.getPathInfo().equals("/all")) {
// Note: Retrieving the full status is much slower
@@ -304,6 +308,16 @@ public class StatusManagerServlet extends HttpServlet implements NotificationLis
}
+ // Takes a snapshot of a list created with Collections.synchronizedList().
+ // The wrapper instance is its own lock, which is also acquired by the
+ // add() and remove() calls in handleNotification().
+ private static <T> List<T> copyOf(List<T> list) {
+ synchronized (list) {
+ return new ArrayList<>(list);
+ }
+ }
+
+
// ------------------------------------------- NotificationListener Methods
@Override
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 12/17: Avoid null valve MBean names in ContainerMBean and MBeanFactory
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit da57e5a98e3ee4ace576737f9cc7ec48942226e8
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 12:30:11 2026 +0200
Avoid null valve MBean names in ContainerMBean and MBeanFactory
Adding a valve to a container that is not running links the valve into
the pipeline but does not initialize it, so it has no MBean name. The
valve creation operations dereferenced the missing name and threw an
uncaught NullPointerException, and the valve was left without a name
that removeValve could later match against, which made any subsequent
removeValve call fail on that valve as well. When the pipeline was
running but starting the new valve failed, the pipeline cleaned the
valve up without adding it, yet the creation operations still returned
the name of the discarded valve.
Only report a name for a valve that was actually added, tolerate valves
without a name when comparing, and apply the same handling to the
equivalent operations of the valve factory.
---
.../org/apache/catalina/mbeans/ContainerMBean.java | 28 ++++++++++++++++++---
java/org/apache/catalina/mbeans/MBeanFactory.java | 29 ++++++++++++++++++----
2 files changed, 48 insertions(+), 9 deletions(-)
diff --git a/java/org/apache/catalina/mbeans/ContainerMBean.java b/java/org/apache/catalina/mbeans/ContainerMBean.java
index d64b4b9f64..3466bb0a7e 100644
--- a/java/org/apache/catalina/mbeans/ContainerMBean.java
+++ b/java/org/apache/catalina/mbeans/ContainerMBean.java
@@ -28,6 +28,7 @@ import org.apache.catalina.ContainerListener;
import org.apache.catalina.JmxEnabled;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
+import org.apache.catalina.Pipeline;
import org.apache.catalina.Valve;
import org.apache.catalina.core.ContainerBase;
import org.apache.catalina.core.StandardContext;
@@ -114,7 +115,8 @@ public class ContainerMBean extends BaseCatalinaMBean<ContainerBase> {
*
* @param valveType ClassName of the valve to be added
*
- * @return the MBean name of the new valve
+ * @return the MBean name of the new valve, or null if the valve was not
+ * added or has no registered MBean
*
* @throws MBeanException if adding the valve failed
*/
@@ -122,10 +124,27 @@ public class ContainerMBean extends BaseCatalinaMBean<ContainerBase> {
Valve valve = (Valve) newInstance(valveType);
Container container = doGetManagedResource();
- container.getPipeline().addValve(valve);
+ Pipeline pipeline = container.getPipeline();
+ pipeline.addValve(valve);
+
+ // If the pipeline is running and starting the valve fails, the valve
+ // is cleaned up and not added. The pipeline logs the failure.
+ boolean added = false;
+ for (Valve pipelineValve : pipeline.getValves()) {
+ if (pipelineValve == valve) {
+ added = true;
+ break;
+ }
+ }
+ if (!added) {
+ return null;
+ }
if (valve instanceof JmxEnabled) {
- return ((JmxEnabled) valve).getObjectName().toString();
+ // A container that is not running does not initialize the valve,
+ // so no MBean name is available
+ ObjectName oname = ((JmxEnabled) valve).getObjectName();
+ return oname == null ? null : oname.toString();
} else {
return null;
}
@@ -154,7 +173,8 @@ public class ContainerMBean extends BaseCatalinaMBean<ContainerBase> {
for (Valve valve : valves) {
if (valve instanceof JmxEnabled) {
ObjectName voname = ((JmxEnabled) valve).getObjectName();
- if (voname.equals(oname)) {
+ // A valve that has not been initialized has no name
+ if (oname.equals(voname)) {
container.getPipeline().removeValve(valve);
}
}
diff --git a/java/org/apache/catalina/mbeans/MBeanFactory.java b/java/org/apache/catalina/mbeans/MBeanFactory.java
index 9e5a5bcf12..af17824355 100644
--- a/java/org/apache/catalina/mbeans/MBeanFactory.java
+++ b/java/org/apache/catalina/mbeans/MBeanFactory.java
@@ -27,6 +27,7 @@ import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.JmxEnabled;
+import org.apache.catalina.Pipeline;
import org.apache.catalina.Realm;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
@@ -585,8 +586,8 @@ public class MBeanFactory {
* @param className The fully qualified class name of the {@link Valve} to create
* @param parent The MBean name of the associated parent {@link Container}.
*
- * @return The MBean name of the {@link Valve} that was created or <code>null</code> if the {@link Valve} does not
- * implement {@link JmxEnabled}.
+ * @return The MBean name of the {@link Valve} that was created or <code>null</code> if the {@link Valve} was not
+ * added, does not implement {@link JmxEnabled} or has no registered MBean.
*
* @exception Exception if an MBean cannot be created or registered
*/
@@ -602,10 +603,27 @@ public class MBeanFactory {
Valve valve = (Valve) Class.forName(className).getConstructor().newInstance();
- container.getPipeline().addValve(valve);
+ Pipeline pipeline = container.getPipeline();
+ pipeline.addValve(valve);
+
+ // If the pipeline is running and starting the valve fails, the valve
+ // is cleaned up and not added. The pipeline logs the failure.
+ boolean added = false;
+ for (Valve pipelineValve : pipeline.getValves()) {
+ if (pipelineValve == valve) {
+ added = true;
+ break;
+ }
+ }
+ if (!added) {
+ return null;
+ }
if (valve instanceof JmxEnabled) {
- return ((JmxEnabled) valve).getObjectName().toString();
+ // A container that is not running does not initialize the valve,
+ // so no MBean name is available
+ ObjectName oname = ((JmxEnabled) valve).getObjectName();
+ return oname == null ? null : oname.toString();
} else {
return null;
}
@@ -855,7 +873,8 @@ public class MBeanFactory {
for (Valve valve : valves) {
if (valve instanceof JmxEnabled) {
ObjectName voname = ((JmxEnabled) valve).getObjectName();
- if (voname.equals(oname)) {
+ // A valve that has not been initialized has no name
+ if (oname.equals(voname)) {
container.getPipeline().removeValve(valve);
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 11/17: Keep naming resource entries consistent when updated through JMX
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 0fb0d1f23ae7b623ebd8b6390b51a83bb57c0557
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 12:27:12 2026 +0200
Keep naming resource entries consistent when updated through JMX
ContextEnvironmentMBean passed a changed name attribute to the resource
before removing the entry under its new name, so a rename through JMX
left the old entry registered, the old JNDI binding in place and a
second MBean for the same object under the new name. Refuse the name
change, as the sibling resource MBeans do.
Both the environment and the resource MBean updated an entry by
removing it and adding it back. When the add then rejected the new
state, for example a resource type that is incompatible with the
injection targets of the entry, the entry had already been dropped from
the naming resources, its JNDI binding removed and its MBean
unregistered, losing the entry entirely. Restore the previous values
and add the entry back before reporting the failure to the caller.
---
.../catalina/mbeans/ContextEnvironmentMBean.java | 41 ++++++++++++++++++++--
.../catalina/mbeans/ContextResourceMBean.java | 15 ++++++--
2 files changed, 51 insertions(+), 5 deletions(-)
diff --git a/java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java b/java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
index 973029c9cd..02387a43dc 100644
--- a/java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
+++ b/java/org/apache/catalina/mbeans/ContextEnvironmentMBean.java
@@ -20,9 +20,13 @@ import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
+import javax.management.RuntimeOperationsException;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.descriptor.web.ContextEnvironment;
import org.apache.tomcat.util.descriptor.web.NamingResources;
+import org.apache.tomcat.util.res.StringManager;
/**
* A <strong>ModelMBean</strong> implementation for the
@@ -36,20 +40,51 @@ public class ContextEnvironmentMBean extends BaseCatalinaMBean<ContextEnvironmen
public ContextEnvironmentMBean() {
}
+ private static final Log log = LogFactory.getLog(ContextEnvironmentMBean.class);
+ private static final StringManager sm = StringManager.getManager(ContextEnvironmentMBean.class);
+
@Override
public void setAttribute(Attribute attribute)
throws AttributeNotFoundException, MBeanException, ReflectionException {
- super.setAttribute(attribute);
+ if (attribute == null) {
+ throw new RuntimeOperationsException(new IllegalArgumentException(sm.getString("mBean.nullAttribute")),
+ sm.getString("mBean.nullAttribute"));
+ }
ContextEnvironment ce = doGetManagedResource();
+ if ("name".equals(attribute.getName())) {
+ // Updating the name actually needs removing and adding back the
+ // component under the new name. Ignore the change, as the other
+ // naming resource MBeans do.
+ log.info(sm.getString("mBean.nameChange"));
+ return;
+ }
+
+ String oldType = ce.getType();
+ String oldValue = ce.getValue();
+ String oldLookup = ce.getLookupName();
+
+ super.setAttribute(attribute);
+
// cannot use side effects. It's removed and added back each time
// there is a modification in a resource.
NamingResources nr = ce.getNamingResources();
if (nr != null) {
- nr.removeEnvironment(ce.getName());
- nr.addEnvironment(ce);
+ try {
+ nr.removeEnvironment(ce.getName());
+ nr.addEnvironment(ce);
+ } catch (IllegalArgumentException iae) {
+ // The change is not acceptable. Restore the previous state
+ // before passing the failure to the caller, so the entry is
+ // not lost.
+ ce.setType(oldType);
+ ce.setValue(oldValue);
+ ce.setLookupName(oldLookup);
+ nr.addEnvironment(ce);
+ throw iae;
+ }
}
}
}
diff --git a/java/org/apache/catalina/mbeans/ContextResourceMBean.java b/java/org/apache/catalina/mbeans/ContextResourceMBean.java
index f485dd0e51..669bc7726e 100644
--- a/java/org/apache/catalina/mbeans/ContextResourceMBean.java
+++ b/java/org/apache/catalina/mbeans/ContextResourceMBean.java
@@ -96,6 +96,8 @@ public class ContextResourceMBean extends BaseCatalinaMBean<ContextResource> {
ContextResource cr = doGetManagedResource();
+ String oldType = cr.getType();
+
switch (name) {
case "auth" -> cr.setAuth((String) value);
case "description" -> cr.setDescription((String) value);
@@ -110,8 +112,17 @@ public class ContextResourceMBean extends BaseCatalinaMBean<ContextResource> {
// there is a modification in a resource.
NamingResources nr = cr.getNamingResources();
if (nr != null) {
- nr.removeResource(cr.getName());
- nr.addResource(cr);
+ try {
+ nr.removeResource(cr.getName());
+ nr.addResource(cr);
+ } catch (IllegalArgumentException iae) {
+ // The change is not acceptable. Restore the previous type
+ // before passing the failure to the caller, so the entry is
+ // not lost.
+ cr.setType(oldType);
+ nr.addResource(cr);
+ throw iae;
+ }
}
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 16/17: Report when a naming entry was not actually added through JMX
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 6b16330900ca6ee63253455a310d8c60d0c2eba0
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 13:42:44 2026 +0200
Report when a naming entry was not actually added through JMX
NamingResourcesImpl uses a single set of names shared by every naming
entry type, so adding an environment, resource or resource link through
this MBean silently does nothing when the requested name is already
claimed by an entry of a different type, while the add* operations still
computed and returned the ObjectName of an MBean that was never
registered. Re-check the entry with the corresponding find method after
the add call and throw IllegalArgumentException when nothing was added.
Also remove the ObjectName.unquote() calls in removeResource() and
removeResourceLink(). JMX operation parameters arrive as plain strings,
not as ObjectName key property values, so unquoting mangled names that
legitimately begin or end with a quote character and allowed removal of
an entry whose actual name differed from the one supplied.
---
.../apache/catalina/mbeans/NamingResourcesMBean.java | 20 ++++++++++++++++++--
1 file changed, 18 insertions(+), 2 deletions(-)
diff --git a/java/org/apache/catalina/mbeans/NamingResourcesMBean.java b/java/org/apache/catalina/mbeans/NamingResourcesMBean.java
index 0fcf1ca09e..2cf577b11c 100644
--- a/java/org/apache/catalina/mbeans/NamingResourcesMBean.java
+++ b/java/org/apache/catalina/mbeans/NamingResourcesMBean.java
@@ -153,6 +153,12 @@ public class NamingResourcesMBean extends BaseModelMBean {
env.setType(type);
env.setValue(value);
nresources.addEnvironment(env);
+ if (nresources.findEnvironment(envName) == null) {
+ // The name is already claimed by another entry type and the entry
+ // was not added
+ throw new IllegalArgumentException(
+ sm.getString("namingResourcesMBean.addAlreadyExists.environment", envName));
+ }
// Return the corresponding MBean name
ManagedBean managed = registry.findManagedBean("ContextEnvironment");
@@ -186,6 +192,12 @@ public class NamingResourcesMBean extends BaseModelMBean {
resource.setName(resourceName);
resource.setType(type);
nresources.addResource(resource);
+ if (nresources.findResource(resourceName) == null) {
+ // The name is already claimed by another entry type and the entry
+ // was not added
+ throw new IllegalArgumentException(
+ sm.getString("namingResourcesMBean.addAlreadyExists.resource", resourceName));
+ }
// Return the corresponding MBean name
ManagedBean managed = registry.findManagedBean("ContextResource");
@@ -219,6 +231,12 @@ public class NamingResourcesMBean extends BaseModelMBean {
resourceLink.setName(resourceLinkName);
resourceLink.setType(type);
nresources.addResourceLink(resourceLink);
+ if (nresources.findResourceLink(resourceLinkName) == null) {
+ // The name is already claimed by another entry type and the entry
+ // was not added
+ throw new IllegalArgumentException(
+ sm.getString("namingResourcesMBean.addAlreadyExists.resourceLink", resourceLinkName));
+ }
// Return the corresponding MBean name
ManagedBean managed = registry.findManagedBean("ContextResourceLink");
@@ -252,7 +270,6 @@ public class NamingResourcesMBean extends BaseModelMBean {
* @param resourceName Name of the resource reference to remove
*/
public void removeResource(String resourceName) {
- resourceName = ObjectName.unquote(resourceName);
NamingResourcesImpl nresources = (NamingResourcesImpl) this.resource;
if (nresources == null) {
return;
@@ -272,7 +289,6 @@ public class NamingResourcesMBean extends BaseModelMBean {
* @param resourceLinkName Name of the resource link reference to remove
*/
public void removeResourceLink(String resourceLinkName) {
- resourceLinkName = ObjectName.unquote(resourceLinkName);
NamingResourcesImpl nresources = (NamingResourcesImpl) this.resource;
if (nresources == null) {
return;
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 01/17: Fix NPE in WebappClassLoaderBase.getResources() for leading-slash names
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 17c52f24472333a341703d7018b8bf4baeb28cda
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 10:49:43 2026 +0200
Fix NPE in WebappClassLoaderBase.getResources() for leading-slash names
The resource name rework in eb91c3e64b made findResources() return null
when the name was null or started with '/'. This broke the Enumeration
contract of ClassLoader.findResources() and caused getResources() to
throw a NullPointerException from CombinedEnumeration.inc() on the
first hasMoreElements()/nextElement() call, since getResources()
passes the findResources() result directly into CombinedEnumeration.
Return an empty enumeration instead, matching the JDK behaviour where
findResources() returns an empty (not null) enumeration for names that
cannot be found, including leading-slash names. The other lookups
(findResource(), getResource(), getResourceAsStream()) already return
null consistently for these names.
Add regression tests for findResources() and getResources() with
leading-slash names.
---
.../catalina/loader/WebappClassLoaderBase.java | 4 ++++
.../catalina/loader/TestWebappClassLoader.java | 28 ++++++++++++++++++++++
2 files changed, 32 insertions(+)
diff --git a/java/org/apache/catalina/loader/WebappClassLoaderBase.java b/java/org/apache/catalina/loader/WebappClassLoaderBase.java
index 4a29e31e53..c76853d889 100644
--- a/java/org/apache/catalina/loader/WebappClassLoaderBase.java
+++ b/java/org/apache/catalina/loader/WebappClassLoaderBase.java
@@ -881,6 +881,10 @@ public abstract class WebappClassLoaderBase extends URLClassLoader
checkStateForResourceLoading(name);
+ if (name == null || name.startsWith("/")) {
+ return Collections.emptyEnumeration();
+ }
+
String path = nameToPath(name);
WebResource[] webResources;
diff --git a/test/org/apache/catalina/loader/TestWebappClassLoader.java b/test/org/apache/catalina/loader/TestWebappClassLoader.java
index 2850f27b20..bcde963fbb 100644
--- a/test/org/apache/catalina/loader/TestWebappClassLoader.java
+++ b/test/org/apache/catalina/loader/TestWebappClassLoader.java
@@ -244,4 +244,32 @@ public class TestWebappClassLoader extends TomcatBaseTest {
Assert.assertFalse(urls.hasMoreElements());
}
+
+
+ @Test
+ public void testFindResourcesLeadingSlash() throws Exception {
+ Tomcat tomcat = getTomcatInstanceTestWebapp(false, true);
+
+ Context c = (Context) tomcat.getHost().findChildren()[0];
+ WebappClassLoaderBase cl = (WebappClassLoaderBase) c.getLoader().getClassLoader();
+
+ Enumeration<URL> urls = cl.findResources("/org/apache/tomcat/Bug58096.java");
+ Assert.assertNotNull(urls);
+
+ Assert.assertFalse(urls.hasMoreElements());
+ }
+
+
+ @Test
+ public void testGetResourcesLeadingSlash() throws Exception {
+ Tomcat tomcat = getTomcatInstanceTestWebapp(false, true);
+
+ Context c = (Context) tomcat.getHost().findChildren()[0];
+ WebappClassLoaderBase cl = (WebappClassLoaderBase) c.getLoader().getClassLoader();
+
+ Enumeration<URL> urls = cl.getResources("/org/apache/tomcat/Bug58096.java");
+ Assert.assertNotNull(urls);
+
+ Assert.assertFalse(urls.hasMoreElements());
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
(tomcat) 09/17: Pass the normalized default host name to the mapper in StandardEngine
Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit df42109be8ecbf96339f985d7bf193a524bf05ec
Author: opencode <re...@apache.org>
AuthorDate: Wed Oct 7 12:14:13 2026 +0200
Pass the normalized default host name to the mapper in StandardEngine
setDefaultHost() stored a lower-cased copy of its argument in the
engine field but handed the raw argument to the mapper when the engine
was already running. The mapper resolves the default host name
case-sensitively, while StandardHost lower-cases all host names and
aliases it registers, so a runtime update with a differently cased
name, for example through JMX, resolved to no host and silently
dropped the default host fallback until the next restart.
Pass the stored, normalized value, so the runtime update behaves like
the start-up lookup in MapperListener, which reads the same field.
---
java/org/apache/catalina/core/StandardEngine.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/java/org/apache/catalina/core/StandardEngine.java b/java/org/apache/catalina/core/StandardEngine.java
index 506e4e0386..a4b63a745a 100644
--- a/java/org/apache/catalina/core/StandardEngine.java
+++ b/java/org/apache/catalina/core/StandardEngine.java
@@ -117,7 +117,7 @@ public class StandardEngine extends ContainerBase implements Engine {
this.defaultHost = host.toLowerCase(Locale.ENGLISH);
}
if (getState().isAvailable()) {
- service.getMapper().setDefaultHostName(host);
+ service.getMapper().setDefaultHostName(this.defaultHost);
}
support.firePropertyChange("defaultHost", oldDefaultHost, this.defaultHost);
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org