Skip to content

Fix StatementCache regression with drivers that report statements as not poolable - #5

Closed
rvullriede wants to merge 63 commits into
mainfrom
fix/statementcache-poolable
Closed

rvullriede wants to merge 63 commits into
mainfrom
fix/statementcache-poolable

Conversation

@rvullriede

@rvullriede rvullriede commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

Bugzilla: to follow

bb64a05 made StatementCache cache a statement only when the driver's isPoolable() returns true. H2 and MariaDB Connector/J always return false and ignore setPoolable(), so nothing is cached. The H2-backed TestStatementCache in org.apache.tomcat.jdbc.test has failed since that commit (3 of 8 tests).

Track the application's setPoolable() calls on the cached statement proxy instead. The Statement.setPoolable() Javadoc says prepared and callable statements are poolable when created, so a statement is cached unless the application opted out.

SimpleInstanceManager.newInstance(String) dereferenced the thread
context class loader without a null check. Thread.getContextClassLoader()
is documented to return null in some cases and NullPointerException is not
part of the InstanceManager.newInstance(String) contract, so a raw NPE
could escape to callers.

Fall back to the class loader of SimpleInstanceManager when the thread
context class loader is null, matching the established pattern used by
JspRuntimeContext and Registry. This turns the previous undeclared NPE
into the contract-declared ClassNotFoundException when the class cannot
be resolved, and has no effect on the normal case where the thread
context class loader is set.
In setProperty(), the loop that matches single-argument setters
initialised the success flag to true and only cleared it for the
supported parameter types (int/Integer/long/Long/boolean/Boolean/
InetAddress) when value conversion or host resolution failed. For a
setter whose parameter type was not one of those, the default branch
merely logged a trace message, leaving the flag set, so the code
invoked the method reflectively with a null argument and returned true.
Callers such as SetPropertiesRule, Connector.setAttribute,
AbstractEndpoint, WebdavServlet.init and FilterBase therefore skipped
their error paths and a misconfiguration went unnoticed, with the
targeted property silently set to null.

Mark unsupported parameter types as not ok so the setter is not invoked.
The property now falls back to the generic setProperty(name, value)
handler when the target provides one and invokeSetProperty is true, or
the method returns false so the caller can report the failure. As a
side benefit, an unsupported overload can no longer shadow a supported
overload of the same setter, and digester generated code no longer
emits an empty statement for such properties.

Adds regression tests covering both the no-fallback and the
setProperty-fallback cases.
findDeadlock() called ThreadMXBean.findDeadlockedThreads() twice,
using the first result only for a null check and passing the second,
independent snapshot to getThreadInfo(). If the deadlock was resolved
between the two calls the second call returned null and getThreadInfo()
threw a NullPointerException. Reuse the ids from the first snapshot so
there is no time-of-check/time-of-use window between the calls.

In addition, ThreadMXBean.getThreadInfo(long[], boolean, boolean) is
documented to return null array elements for thread ids that are no
longer alive, for example threads that died after the deadlock
snapshot. getThreadDump(ThreadInfo[]) passed those elements straight
to getThreadDump(ThreadInfo) which dereferences getThreadName(), also
throwing a NullPointerException. Skip null entries. Since the deadlock
genuinely existed at snapshot time, the deadlock message is still
reported; in the extreme case where all threads died the message is
followed by an empty dump rather than crashing.

findDeadlock() runs on every Manager /threaddump request via
Diagnostics.getThreadDump(). The dumpAllThreads() path used by the
same method never returns null elements, so the new guard is a no-op
there. Verified with TestManagerWebapp which requests
/manager/text/threaddump.
The byte emission loop right-shifted the value on each iteration while
also shifting by 8 * (valueSize - 1) of the already shifted value, so
every content byte received a copy of the most significant byte:
writeInteger(0x1234) produced 02 02 12 12 instead of 02 02 12 34 and
writeInteger(256) produced 02 02 01 01 instead of 02 02 01 00. Only
single byte values and values whose bytes are all equal were encoded
correctly. Emit the bytes by shifting the unmodified value.

Also add the leading zero byte that DER (X.6.90) requires for positive
INTEGER values whose most significant content bit is set. Without it,
writeInteger(128) produced 02 01 80 which decodes as -128.

While testing the fix, two related infinite loops were found and
fixed. The value size calculation loops in both writeInteger() and
writeTag() test (value >> (size * 8)) > 0 without an upper bound.
Since the Java shift distance is evaluated modulo 32, once the size
counter reaches 4 the shift distance wraps back to 0 and the loop
never terminates: writeInteger() spun forever for values >= 0x1000000
and writeTag() for data lengths >= 0x1000000. The size counters are
now bounded (4 bytes is the maximum for any non-negative int value or
any Java array length) and the shifts are unsigned.

Adds TestAsn1Writer with explicit expected encodings, an exhaustive
round-trip of the values 0 to 65535 plus transition boundaries and
fixed-seed random values, comparing the content octets against
BigInteger.toByteArray() (canonical minimal DER) and decoding the
result with Asn1Parser, and a regression test for the 16 MiB length
case in writeTag(). Output for the only in-repo callers, PEMFile with
values 0 and 1, is byte-identical to before; TestPEMFile passes.
When a custom WAR separator is configured via the
org.apache.tomcat.util.buf.UriUtil.WAR_SEPARATOR system property,
PATTERN_CUSTOM matches the full separator (custom + "/") but
REPLACE_CUSTOM percent-encoded only the custom part. The replaceAll in
makeSafeForJarUrl therefore deleted the trailing '/' of the separator,
silently rewriting any file path containing the separator sequence to a
different, non-existent path and producing a broken jar:file: URL.

Fix this by appending a literal '/' to REPLACE_CUSTOM so the escaped
replacement keeps the separator's trailing slash, consistent with the
default handling where "*/" is replaced with "%2a/". As a side
effect, an empty custom separator now behaves as a no-op instead of
stripping every '/' from the path.

Add a regression test asserting the full expected JAR URL with the '@'
separator, using the String overload of buildJarUrl so the expected
value is independent of platform-specific File.toURI() behaviour.
…oss calls

UEncoder.encodeURL() recycled the internal byte and char chunks but not
the per-instance C2BConverter. C2BConverter retains characters that
could not yet be encoded (such as a high surrogate not followed by a low
surrogate) in a private leftovers buffer. A string ending with such a
character therefore left it in the converter, and the next encodeURL()
call on the same instance silently paired the leftover with the start of
the new, unrelated string, corrupting the result. For example, encoding
"ab\uD800" followed by "\uDC00cd" produced %f0%90%80%80cd
(U+10000) instead of %3fcd.

Fix this by calling c2b.recycle() whenever an existing converter is
reused. C2BConverter.recycle() resets the charset encoder and clears the
leftovers buffer. Add a regression test that compares the second call's
result with that of a fresh encoder.
get() promoted every long-term store hit into eden unconditionally,
while only put() trims eden. A workload with more reads than writes of
distinct keys could therefore grow eden far beyond the size documented
as the maximum size of the eden space, with each entry pinning a
previously weakly-reachable key with a strong reference until the next
put-triggered promotion and clear. For example, with a configured size
of 10, 100 puts followed by 100 gets left eden holding 100 entries.

Fix this by promoting into eden from get() only while eden has room,
i.e. when its size is below the configured size. The check-then-act
race is benign: it is the same pattern already used by put() and any
transient overshoot is bounded by the number of concurrent readers and
is cleared by the next promotion. Entries that are not promoted remain
available through the long-term store, so lookups are unaffected.

Add TestConcurrentCache covering basic operation, promotion to the
long-term store, promotion back into eden while there is room, and the
eden size bound.
setLimit() only stored the limit field while push() consulted the limit
only when the backing array was already full. A stack with the default
capacity of 128 and a newly configured limit of, say, 10 therefore kept
accepting pushes until it held 128 elements, ignoring the limit. For
the HTTP/2 recycled Request/Response pool, whose limit is set from the
connector's maxConnections, this allowed the pool to hold up to 128
entries when maxConnections was configured below 128.

Fix this by shrinking the stack in setLimit() when the new limit is
lower than the current capacity. The most recently pushed elements are
retained and any remaining, older elements are discarded along with the
old backing array, which releases their references.

As follow-up work prompted by review, make expand() able to grow from a
zero capacity array using Math.max(1, size * 2). Shrinking to a limit of
zero and later raising the limit previously produced an
ArrayIndexOutOfBoundsException on the next push, and the same latent
problem existed for a stack constructed with a zero size. Add tests for
shrinking below the capacity and below the element count, for the
unlimited limit and for zero-then-raise. All assertions fail against the
previous implementation where applicable.
The public constructor accepted values it could not handle. A zero
initial size produced a queue whose first offer() threw
ArrayIndexOutOfBoundsException, and a negative value produced
NegativeArraySizeException from the array allocation. Neither state is
usable, and a zero-size queue cannot recover since expand() doubles the
current size.

Reject non-positive values with IllegalArgumentException using a
localized message from a new LocalStrings bundle for the
org.apache.tomcat.util.collections package, following the StringManager
pattern used by other util packages. No in-tree caller is affected; the
only production instantiation uses the default constructor.

Add tests for rejected zero and negative sizes, for the smallest valid
size of one, and add the missing @test annotation to testPollEmpty which
previously prevented it from running.
The class extends AbstractMap and only overrode entrySet(), so keySet()
returned the AbstractMap view whose contains() delegates to the map's
case-insensitive containsKey() while remove(Object) iterates the keys
comparing them with String.equals(). For a stored key "a",
keySet().contains("A") returned true but keySet().remove("A")
returned false and left the entry in place, violating the Set contract
for callers that remove keys via the view with different casing.

Override keySet() with a KeySet view backed by the same live map as the
entry set. Its iterator reports keys in their original case, contains()
and remove() are case-insensitive, removal correctly reports success
even for entries with a null value, null and non-String arguments return
false, and clear() empties the backing map. Non-String and null keys are
never stored since put() rejects null keys and Key.getInstance() returns
null for other types.

Add tests for case-insensitive removal of a set object, rejection of
null and non-String keys, original-case keys from the iterator and
clearing via the view.
The constant concatenated the Java EE 5 namespace and the schema file
name without the '/' separator, producing the malformed URL
http://java.sun.com/xml/ns/javaeejavaee_web_services_1_2.xsd instead of
http://java.sun.com/xml/ns/javaee/javaee_web_services_1_2.xsd used by
the specification and by DigesterFactory when registering the schema.

The constant is currently unreferenced - DigesterFactory registers the
web services schemas via bare file names - so there is no functional
impact today. The correction removes a latent copy-paste defect from
this public constants class and aligns the value with all sibling
constants, which use the namespace plus "/filename".
The parser registers addCallMethod for <tag-plugin> with two parameters
taken from the child element bodies. CallMethodRule always invokes the
method when it expects more than one parameter, passing null for
parameters whose element is absent. As a result, a <tag-plugin> element
that omitted <tag-class> or <plugin-class> stored a map entry with a
null key or value.

The sole consumer, Jasper's TagPluginManager, then either called
loadClass(null), which produced a raw NullPointerException surfaced as
an unhelpful JasperException during JSP translation, or silently stored
an entry under a null key that could never match a tag handler class.

Fix this by ignoring entries with a null or empty tag class or plugin
class and logging a localized warning via StringManager, using a new
resource bundle for the org.apache.tomcat.util.descriptor.tagplugin
package. Complete entries in the same descriptor are still registered.
Document the behaviour in the addPlugin() Javadoc. Add tests covering
direct calls with missing values and the parsing of a descriptor
mixing incomplete and complete entries.
TldCache shares a single TldParser, and therefore a single Digester,
across all cached TLDs. Digester is documented as single-threaded but
the re-parse path in getTaglibXml() was only protected by a per-entry
lock. Two threads recompiling JSPs that referenced two different TLDs
whose last modified time had changed since the startup scan could call
tldParser.parse() concurrently on the same Digester. Observed failure
modes included Xerces rejecting the reentrant parse
(FWK005: parse may not be called while parsing) and a NullPointerException
after a concurrent digester.reset() from the finally block of the other
parse, with the corrupted result being cached until the next change.

Fix this by serializing all re-parses on the shared parser's monitor.
The monitor is taken while holding the per-entry lock, and no path
takes the two locks in the opposite order, so no deadlock is possible.
Correct the class Javadoc, which previously claimed the opposite
thread-safety behaviour.
JSP.7.3.2 only permits version information and a short name in an
implicit.tld file. The web application TLD scanner previously parsed
these files with the full TldRuleSet at start-up. That allowed
elements which the specification forbids in an implicit TLD to take
effect: a <uri> element caused the URI to be registered so that the
file could be used for URI based taglib directives, and a <listener>
element caused JasperInitializer to register the listener with the
context, aborting start-up when the class could not be instantiated.

TldScanner now owns a second TldParser built with the existing
ImplicitTldRuleSet - the same rule set already used by
ImplicitTagLibraryInfo when a tag file is translated - and uses it
for resources whose web application path is an implicit.tld below
/WEB-INF/tags. An implicit TLD which is not specification compliant
is now rejected at scan time: the scanner logs a warning naming the
resource and continues, so such a file can no longer register a URI,
cache a tag library or contribute listeners, and cannot prevent the
web application from starting. If the tag library is actually used
via tagdir, the same error is reported at translation time as before.

Explicit taglib mappings in web.xml (scanJspConfig) deliberately keep
using the lenient parser since an explicit mapping is an administrator
decision and <listener> is legitimate in a regular TLD.

Also replace the /WEB-INF/tags/ and /implicit.tld literals in
scanResourcePaths() with the new WEB_INF_TAGS and IMPLICIT_TLD
constants, now used by both code paths.
TldResourcePath accepted a null URL without complaint and then failed
later with a NullPointerException in toExternalForm(), openStream(),
equals() or hashCode() when the value was first used.

One caller made this reachable in normal operation. TldScanner
resolved a TLD listed by ServletContext.getResourcePaths() with
ServletContext.getResource() and passed the result straight to the
constructor. The two calls are not atomic: a TLD removed from an
exploded web application between them resolved to null, the resulting
NullPointerException was thrown out of the scan and, since
JasperInitializer.onStartup() only catches IOException and
SAXException, it aborted context start-up with an opaque error.

Both constructors now throw an IllegalArgumentException with a
readable, localised message when the URL is null, mirroring the
validation style used elsewhere in the utility packages. In addition,
TldScanner.parseTld(String) now checks for the vanished resource and
skips it with a warning, in the same way as scanJspConfig() handles a
taglib-location in web.xml that does not exist, so the race becomes a
startup warning rather than a failure.

Tests: TestTldResourcePath covers the constructor rejection and the
methods the invariant protects; TestTldScanner covers the scan-time
warn-and-skip of a resource that disappeared.
The port-component-ref mappings of a <service-ref> (the Service
Endpoint Interface to port-component-link associations) were stored in
the generic properties map inherited from ResourceBase, via
addPortcomponent() -> setProperty(). The same map also holds the
<mapped-name> value, which MappedNameRule stores under the key
mappedName for every resource that allows that element. Since
getServiceendpoints() simply returned listProperties(), any
<service-ref> that declared a <mapped-name> - which is legal per the
Servlet specification - was reported as having a bogus service endpoint
named mappedName, whose port-component-link was the mapped-name
value.

That bogus endpoint leaked to several consumers:

  * NamingContextListener.addService() bound a
    SERVICEENDPOINTINTERFACE/PORTCOMPONENTLINK pair for mappedName
    into the application's JNDI ServiceRef.
  * WebXml.toXml() serialized an extra
    <port-component-ref><service-endpoint-interface>mappedName
    </service-endpoint-interface>...</port-component-ref> element into
    the effective web.xml.
  * ContextService.toString() printed mappedName as an endpoint, as did
    the storeconfig output for a global ServiceRef.

Port-component mappings now live in a dedicated map, kept separate from
the generic properties, and are included in equals()/hashCode().
WebXml.toXml() reads the port link through getPortlink() rather than by
treating the endpoint name as a property key; the mapped-name element
continues to be read from the mappedName property. As a side effect,
endpoint names are no longer emitted as generic attributes when a global
<ServiceRef> is written by storeconfig.

Tests: TestWebXml now checks that a service-ref with a mapped-name
reports only its real endpoint, retains the mapped-name as a property,
and serializes a single correct port-component-ref in the effective
web.xml.
FilterDef.asyncSupportedBoolean defaulted to true and any value
other than "false"/"no" was parsed as true. The Servlet specification
defaults filters to not supporting async processing.

The web.xml path masked the incorrect default because ContextConfig
normalises a missing async-supported element to "false", but filters
registered dynamically through ServletContext.addFilter() that never
called Dynamic.setAsyncSupported(true) were treated as async supported,
so ApplicationFilterChain applied them to ASYNC and ERROR dispatches
contrary to the specification.

The boolean field could also disagree with the stored string: values
such as "yes" or "1" returned true from getAsyncSupportedBoolean() but
false from the getAsyncSupported().equals("true") checks used elsewhere,
so the same filter was inconsistently treated as async supported and
async unsupported.

asyncSupportedBoolean now defaults to false and the setter derives it
with "true".equalsIgnoreCase(), consistent with ServletDef and the
Boolean parsing used by the other descriptor setters. The string value
is stored unchanged so a storeconfig round-trip preserves the original
descriptor value.

This is a user-visible behaviour change: dynamically registered filters
now require an explicit setAsyncSupported(true) to receive async and
error dispatches. Annotation-defined filters and the shipped filter
definitions are unaffected. Adds tests for the default and the full
setter matrix, plus a changelog entry.
SecurityRoleRef.equals(Object) compared getClass() on the argument
without a null check, so equals(null) dereferenced null and threw
NullPointerException, violating the Object.equals contract which
requires false for a null argument.

Replace the getClass() comparison with an instanceof pattern match,
consistent with LoginConfig in the same package, which handles both the
null argument and foreign types by returning false. There are no
subclasses of SecurityRoleRef in the tree, so behaviour is unchanged for
all non-null inputs; hashCode is untouched and remains consistent with
equals. No internal call site passes null (HashSet operations
null-guard the query key), so this is a latent robustness fix.

Adds TestSecurityRoleRef covering the null argument, the field
comparison matrix and equality of instances with null fields.
SessionConfig.setCookieMaxAge(String) stored the raw string and
getCookieMaxAge() parsed it lazily. The value is copied verbatim by
ContextConfig into the runtime SessionCookieConfig, where
ApplicationSessionCookieConfig.getMaxAge() parses it again on every
session cookie creation. Web.xml XSD validation is off by default, so an
invalid value such as "abc" passed parsing and then threw a raw
NumberFormatException on every session creation and session id change
for the application, instead of failing the deployment.

The setter now validates the value with Integer.valueOf() before
storing it, consistently with setSessionTimeout() in the same class. The
digester wraps the resulting NumberFormatException into a SAX parse
error that reports the location in the descriptor and fails the
deployment cleanly. Valid values, including negative ones used to
disable cookie expiry, are stored unchanged.

The generic cookie attribute path (SessionConfig.setCookieAttribute, the
descriptor mirror of SessionCookieConfig.setAttribute) accepts arbitrary
strings and remains unvalidated, which is pre-existing and mirrors the
programmatic API.

Adds TestSessionConfig for the setter and parse level tests in
TestWebXmlParser covering valid, invalid and empty max-age elements.
When getXMLReader().parse() aborted with a fatal SAX error, IOException
or an exception from a rule, endDocument() and with it clear() never ran.
The Digester was left with a partially built match path, entries on the
matches stack, the parameter array pushed by CallMethodRule, objects on
the object stack and a stale root object. A subsequent parse on the same
instance then built its match patterns on top of the stale path, so
rules stopped matching at the path they were registered for or matched
at the wrong depth, and the leftover objects shifted the stack offsets
the rules rely on.

This is reachable in first-party code: ContextConfig.contextConfig()
parses up to three context.xml files with one shared Digester and keeps
using it after processContextConfig() swallows a parse exception, and
StoreLoader.load() re-parses with the same instance after an
IOException.

All parse() overloads now restore a consistent state (clear() plus a
null root) before rethrowing. clear() also clears the matches stack and
the namespace prefix mappings, which leaked on every failed parse even
via reset(); they are empty by the time endDocument() calls clear() on
the success path, so this only removes residue. The code generation
buffer is deliberately left alone because ContextConfig writes the
generated file after processContextConfig() even when the parse failed.

Adds TestDigester covering the residual state after a failed parse and
rule matching on the parse following a failure; both tests fail against
the previous code.
clear() nulled log and saxLog. It runs at the end of every successful
parse via endDocument(), on every failed parse via the reset added in
the previous commit, and via the public reset() method, so afterwards
the loggers stayed null until the next parse re-ran configure().

That left several public methods broken in exactly the empty state
their Javadoc promises a null return or a plain call: peek(), peek(int)
and pop() threw a NullPointerException inside their
catch(EmptyStackException) handler instead of returning null, peekParams
and popParams behaved the same way, popParams(), pushParams() and
register() hit a NullPointerException unconditionally on the trace
enablement check, and createSAXException(String, Exception) did so on
its log.error path when no document locator has been set, for example
after a parse failure on a file that could not be opened.

The nulling also served no purpose. JULI loggers are cached by name by
the logging implementation, so retaining the two handles between parses
costs nothing, and configure() re-assigned equivalent handles on every
subsequent parse anyway. Nothing reads the fields to test for null and
no Digester subclass in the tree overrides configure().

Adds regression tests to TestDigester for the stack and parameter
methods after a successful parse and for createSAXException() in the
no-locator state left by a failed parse; both fail with a
NullPointerException without this change.
ArrayStack.peek(int) computed [size() - n - 1] and threw
EmptyStackException only when that index fell below zero, which covers
indexes beyond the bottom of the stack. A negative index moved the
computed position beyond the end of the backing list instead, so get()
threw an IndexOutOfBoundsException.

That exception escaped Digester.peek(int), which only catches
EmptyStackException, even though the method is documented to return
null for any out of range index. One path where a negative index can be
passed in is CallMethodRule with a negative targetOffset deeper than
the current stack depth, where digester.peek(getCount() + targetOffset)
then reported a wrapped IndexOutOfBoundsException rather than the
intended 'Call target is null' parse error that names the offset and
the stack depth.

Guard both ends of the range instead. For non-negative indexes the
condition is equivalent to the previous one, so no legitimate use
changes, and the outcome for extreme values no longer depends on
integer wrap-around.

Adds TestArrayStack covering the top, the bottom, the empty stack and
both out of range directions including Integer.MIN_VALUE and
Integer.MAX_VALUE, plus a TestDigester test for the peek(int) null
contract for negative indexes.
A CallMethodRule collecting two or more parameters passes a parameter
whose nested element is absent to the target method as a null value.
That is documented behaviour, and the method call itself handles it.

The code generation block at the end of end() did not. A null parameter
is not a String, so it was handed to Digester.toVariableName() to name a
variable for it. That method registers the object and then dereferences
it, so the generated code path aborted the parse with a
NullPointerException, wrapped in a SAXException, as soon as a
multi-parameter element omitted one of its parameter children, for
example an init-param without an init-value. This affects the opt-in
-generateCode path used to pre-compile descriptor processing.

Emit the null literal for a null parameter instead. The generated
statement then reflects the call that is actually made. All first-party
targets of these rules declare a single method of that name, so the
generated source resolves to the same method the reflective invocation
selected; a cast is not needed and would require canonicalising type
names for no first-party benefit.
getProperty() decoded the binding file bytes with new String(byte[],int,
int), which uses the JVM default character set. Service binding entries
under SERVICE_BINDING_ROOT are text files that follow the UTF-8
convention (Kubernetes secret projections encode stringData as UTF-8)
and the resolved values flow into configuration such as SSLHostConfig
certificate key passwords, so on a JVM whose default character set is
not UTF-8 every non-ASCII character was replaced with a question mark,
producing a silently wrong credential.

Decode the bytes as UTF-8 explicitly. Since the service binding
specification fixes no encoding, the class Javadoc now states that
entry files are decoded as UTF-8 and that invalid bytes become U+FFFD.

Adds TestServiceBindingPropertySource covering the UTF-8 decoding of
multi-byte characters (with and without the chomp: prefix), the full
chomp matrix and the null results for unknown bindings and malformed
keys. The environment variable cannot be set from the tests, so a
package-private constructor pins the binding root for the test class;
the public no-argument path is unchanged and still reads the
environment on every resolution. Note that the tests pass on the
default-UTF-8 test JVM regardless of the fix; they fail against the
previous code when the default character set is not UTF-8, and they
pin the contract either way.
…names

getURI() is documented to return URIs even for locations where no
resource exists. For a relative name of a file that does not exist, the
DEFAULT implementation ended by resolving the name against the user
directory URI. URI.resolve() parses the reference strictly, so a name
containing characters that are illegal in a URI but valid in a file
name, such as a space, threw an unchecked IllegalArgumentException
instead, contradicting the contract and inconsistent with getResource(),
which wraps the same resolve() call and reports FileNotFoundException.

Catch the IllegalArgumentException in the missing file case and fall
back to the file based URI, which is valid whether or not the file
exists and percent-encodes the name correctly. Resolvable names keep
their existing resolve() result unchanged, including scheme based
names such as classpath: and jar: that UriUtil does not classify as
absolute URIs and which resolve() returns intact.

Adds TestConfigurationSource covering the missing file with a space,
the unchanged results for a missing URI-safe name, an existing file, a
scheme based name and an absolute URI name.
RFC 4918 section 10.4.2 requires a WebDAV If header list to contain at
least one condition (List = "(" 1*Condition ")"). The parser in
WebdavIfHeader previously accepted an empty list, such as "If: ()",
"( )" or a list without any valid entry, and returned a non-null
structure for it. An empty IfList.match() vacuously returned true, so
the header passed the If precondition checks for any token and ETag,
and hasValue() returned true so the strict mode rejection of invalid
If syntax in WebdavServlet.checkIfHeaders() was bypassed.

parseIfList() now returns null when it did not read at least one valid
entry, and parseUntagged() and parseTagged() propagate this so the
whole header value is treated as invalid. This routes processing into
the existing invalid syntax handling: with strictIfProcessing enabled,
the default, requests using such headers now fail the precondition
check; with strictIfProcessing disabled the header is ignored, as for
any other invalid If header syntax, and lock tokens in the raw header
are still evaluated separately by isLocked(). Lenient error recovery
for entries that fail to parse is retained where other valid entries
were read.

Add TestWebdavIfHeader covering the parser behavior and new
TestWebdavServlet cases covering the strict and non-strict servlet
behavior for "If: ()".
The header parser's line folding (obs-fold) handling peeked the first
byte of the continuation line and copied that raw byte into the
compacted header value. Since an obs-fold may start with HTAB, a TAB
could end up in the value, e.g. a header sent as "X: abcd CRLF TAB
efgh" was stored as "abcd\tefgh".

RFC 9112 section 5.2 requires a server that receives an obs-fold to
either reject the message or replace each obs-fold with one or more SP
octets. The parser now always inserts a single space at the fold point
instead of copying the peeked byte. Whitespace beyond the first byte of
the continuation line was and is skipped by the value-start state, so
the stored value for the HTAB case changes from a TAB to a space while
the SP case is unchanged. This also removes a divergence between what
Tomcat sees and what a spec-compliant intermediary would forward for
the same message.

The existing test for folded headers (bz 48839) asserted the legacy
behaviour with a tab in the value and was updated to expect the single
space mandated by the specification. A new test pins the SP
continuation case.
@rvullriede
rvullriede force-pushed the fix/statementcache-poolable branch from 67b2876 to 86e011f Compare October 14, 2026 18:17
…arset

toString() skipped parameters with a null or empty value but
toStringNoCharset() did not, so a media type such as
"text/html;charset=utf-8;foo=" re-serialised by Response with the
literal string "foo=null" (null values occur for unterminated quoted
strings and mid-string empty values) or with an empty "foo=". The
corrupted value was then written to the Content-Type response header.

toStringNoCharset() now applies the same null/empty value guard as
toString(). Callers (coyote Response.setContentType and
MediaTypeCache used by catalina connector Response) only use the
no-charset serialisation when a charset is present, so this simply
removes the corruption; programmatic access to the parameters via
getParameterValue() is unchanged.
A dangling ';' at the end of a media type is invalid but tolerated by
the parser. Previously it resulted in a phantom parameter with an
empty name and an empty value being added to the parsed MediaType,
inflating getParameterCount() (e.g. "text/html;" reported one
parameter). Trailing ";;" had the same effect, inconsistent with the
handling of a ";;" sequence in the middle of the value where the null
attribute is skipped and no parameter is stored.

readToken() only returns the empty string at end of input, so an empty
attribute can never carry a real name; attributes with an empty name
are now ignored in the same way as null attributes.
rmaucher and others added 28 commits October 15, 2026 10:18
BaseModelMBean.setAttribute() sent every AttributeChangeNotification
with a null old value since the code fetching the previous value had
been commented out (a leftover from the removed attribute cache),
which breaks the AttributeChangeNotification contract for listeners
that rely on the old value.

Retrieve the previous value via getAttribute() before invoking the
setter. Attributes without a getter, or whose getter fails, keep the
unknown old value null so write-only or failing-getter sets behave
exactly as before. As a consequence, a set to null is now reported
(old and new values both null is still treated as no change).

Add a unit test covering the old and new values of the notification
emitted by setAttribute().
BaseModelMBean emitted every JMX notification with the hard-coded
sequence number 1, which prevents listeners that use the sequence
number for ordering or to detect missed or duplicated notifications
from doing so, contrary to the JMX requirements for notification
sources.

Add a per-MBean sequence number counter (AtomicLong since
notifications may be emitted from several admin threads) and use it
at both notification construction sites so attribute change
notifications and generic notifications share one increasing
sequence. Notifications built by callers and passed to the
sendNotification/sendAttributeChangeNotification overloads keep the
sequence number assigned by their constructing sender as per the JMX
contract.

Add a unit test asserting the exact sequence numbers of two attribute
change notifications and a following generic notification.
When JMX support is disabled with --no-jmx, Registry.getMBeanServer()
returns the NoJmxMBeanServer whose methods returned null or silently
did nothing where the MBeanServer contract requires an exception or a
non-null value. Downstream code that trusted the contract then hit
null pointer exceptions, for example Registry.getMethodInfo()
dereferencing the null MBeanInfo returned by getMBeanInfo (reached
through the Manager application JMX proxy) and the boolean unboxing
of the null result of invoke in ManagerServlet.isDeployed() and
tryAddServiced().

Since no MBean can ever be registered with this server, the truthful
contract-compliant answer for any operation referencing an object
name is InstanceNotFoundException, and the count of registered MBeans
is zero. Update all such methods accordingly and return 0 from
getMBeanCount. Methods without an InstanceNotFoundException throws
clause that are unreachable through the overridden no-op Registry
methods keep their previous behavior.

Add a unit test covering the previously failing contract paths.
ManagedBean caches the MBeanInfo it builds and every other mutator
(setName, setClassName, setDescription, setType, addNotification)
nulls the cache under the mBeanInfoLock write lock, but addAttribute
and addOperation did neither. Adding an attribute or operation after
getMBeanInfo() had been called would therefore keep serving a stale
MBeanInfo, and writing the descriptor maps without the lock was also
inconsistent with getMBeanInfo() reading them under the write lock.

Make both methods mirror addNotification: hold the write lock, update
the map, and clear the cached info. Add a unit test that verifies the
MBeanInfo is rebuilt and contains the newly added descriptor.
The descriptors, descriptorsByClass and searchedPaths maps were plain
HashMaps mutated by addManagedBean() and loadDescriptors() and read
by findManagedBean(), registerComponent() and findDescriptor() with no
synchronization, while registerComponent() is invoked concurrently
during parallel web application deployment and from worker threads on
first use of an upgrade protocol. Concurrent access could lose
updates or transiently corrupt the map state, and stop() additionally
reassigned the three non-volatile fields while readers were active.

Make the three maps final ConcurrentHashMaps and have stop() clear
them rather than reassign them. Record the searched package
atomically with putIfAbsent so concurrent first loads of the same
package can not both parse the descriptor file, and skip the
name-keyed entry when a ManagedBean has no name (permitted by the
DTD) since ConcurrentHashMap does not allow null keys, preserving the
previous behavior for such descriptors.
Registry.load() opens an input stream for URL and File sources and
hands it to the modeler source without retaining any reference, so
the stream had to be closed by the source that consumed it.
MbeansDescriptorsDigesterSource.execute() previously cast the source
to InputStream and parsed it without ever closing it, relying on the
underlying SAX parser to release the stream. That left the release of
the resource to unspecified parser behaviour.

Validate the source with an instanceof check instead of a blind cast,
throwing IllegalArgumentException for anything other than an
InputStream, and parse inside a try-with-resources statement so the
stream is closed when the parse completes, when it fails and when an
unchecked error occurs.

Add unit tests that pass a close-tracking input stream through
Registry.load() and assert the stream is closed after both a
successful parse and a parse error, and that a non-InputStream source
is rejected with IllegalArgumentException.
Registry.findManagedBean() is documented to return null when no
metadata can be found for the requested type: the introspection
fallback logs registry.noTypeMetadata and returns null, and the no
descriptor registry always returns null. Registry.registerComponent()
dereferenced that result immediately, so the documented failure
surfaced as a NullPointerException logged under the generic
registry.registerError message instead of the descriptive metadata
message.

Check the result and throw an IllegalStateException carrying the
registry.noTypeMetadata message, still inside the existing try block
so the error is logged with the object name before it is rethrown.
Registry.convertValue() only mapped String, ObjectName, int/Integer,
long/Long and boolean/Boolean type names. Every other type name fell
through and the raw String was returned. Its sole consumer, the JMX
proxy servlet of the Manager application, passes the returned value
directly to MBeanServer.setAttribute() and invoke(), and the modeler
MBeans apply no conversion of their own, so setting an attribute or
invoking an operation with a double, float, short, byte or char
parameter on any modeler MBean always failed with an argument type
mismatch.

Convert the missing floating point and narrow integral types using the
wrapper valueOf methods, giving the same decimal range and format
checking the existing integral branches already provide, and convert
the first character of a non-empty string for the character types. A
null or empty string is left unconverted rather than introducing a new
exception path.
The JMX parser rejects unquoted property values containing a double
quote or a line feed, so such values must be passed through
ObjectName.quote() before being concatenated into an ObjectName
string. Util.objectNameValueNeedsQuote() listed only comma, equals,
colon and the wildcards, so servlet, filter and upgrade protocol
names containing a double quote bypassed the quoting and the
subsequent ObjectName construction failed. The call sites catch that
failure and log a warning, silently leaving the component without a
JMX registration.

Add the double quote and the line feed to the character check. A
sweep of the value position of a key property confirms these are the
only characters, besides the ones already listed, that the parser
rejects in an unquoted value.
MbeansDescriptorsIntrospectionSource declares its own StringManager
bound to the org.apache.tomcat.util.modeler.modules resource bundle but
logs with the key modules.readDescriptorsError, which existed only in
the org.apache.tomcat.util.modeler bundle used by the sibling digester
source through the inherited manager. StringManager has no fallback to
a parent package bundle and its single argument getString() returns
null for a key that is missing from its bundle, so a failed descriptor
load logged an error entry without a message.

Add the message to the modules bundle, and add a test asserting that
the keys bound to that bundle resolve from the default locale as well
as from the translated bundles, which fall back to the base bundle for
keys that are not yet translated.
ModelerSource.loadDescriptors() is documented to return a list of
object names, but both sources provided with Tomcat registered the
descriptors they loaded with the given registry and never recorded any
object names, so the private fields backing the return value were dead
and the returned list was always empty. No object name identifying a
loaded descriptor exists in the modeler, so populating the list would
have invented a semantic that no code produces.

Remove the dead fields and return the immutable empty list, following
the precedent already set by the no-descriptor registry, and document
in ModelerSource and Registry.load() that the provided sources
register their descriptors with the registry and do not return object
names. Callers must not assume the returned list is mutable.
When no utility executor was set, AbstractEndpoint.getUtilityExecutor()
created one lazily. The executor was never shut down when the endpoint
was destroyed, so the non-daemon core thread of the scheduled thread
pool it created kept running and prevented JVM shutdown, which is
reachable for embedded users that do not provide the shared executor a
full server installs from StandardServer.

Track an executor created by the endpoint and shut it down in
destroy(). Externally provided executors remain owned by the caller and
are left running. The field is made volatile so the creation is safely
published. Concurrent lazy creation remains an unsynchronised
check-then-act: the executor is only requested from the protocol
lifecycle start and from the scheduled async timeout task, which are
serialised per endpoint, the same tolerated pattern already used for
the connection latch in this class, and a duplicated pool in the
hypothetical concurrent case would at worst match the previous
behaviour since callers schedule tasks on the instance they received.
The executor reference is deliberately not cleared on destroy so a
later call returns the shut-down instance rather than creating a new
pool that would never be destroyed.
Inputs that pass the mayBeIPv6Address() heuristic but contain more than
8 colon-separated groups (e.g. "1:2:3:4:5:6:7:8:9" or forms with more
than two consecutive colons), or groups with more than 4 significant
characters (e.g. "12345::"), indexed the fixed-size group store out of
bounds and threw an undocumented ArrayIndexOutOfBoundsException. With
the non-default access log attribute ipv6Canonical="true", such values
(e.g. from a client-supplied Host header via the %v element) caused
loss of the access log record plus a warning per request. canonize()
now returns such malformed inputs unchanged, consistent with how
non-IPv6 input is already passed through. Add tests for the
pass-through behaviour and for the valid 8-colon forms
("1:2:3:4:5:6:7::") whose canonicalization must be preserved.
…limit

When a ClientHello could not be buffered within sniParseLimit,
processSNI() selected the default SSLHostConfig but then still called
the TLSClientHelloExtractor getters, which throw IllegalStateException
for an incomplete extraction. The documented fallback therefore never
happened: the exception escaped to the socket processor's error
handler, logging an error and aborting the connection. Pass empty
lists for all extractor-derived values (requested ciphers, application
protocols, protocol versions, cipher names, supported groups and
signature schemes) through local variables on the UNDERFLOW path
instead of consulting the extractor, which also prevents NPEs on the
unguarded isEmpty()/contains() usages in createSSLEngine(). Add a test
that sends an oversized ClientHello record and asserts the default-host
fallback is logged without an IllegalStateException.
SSLHostConfig.setCipherSuites() converted each configured name from JSSE
format to OpenSSL format and then discarded the result, appending the
original value instead. Since the value is always stored, and later passed
to OpenSSL, in OpenSSL format, append the converted name. This matches
setCiphers(), which already appended the converted name. There is no
change in behaviour for current configurations because the JSSE and
OpenSSL names for TLS 1.3 cipher suites are currently the same.

Also avoid a NullPointerException when a null value is provided. That
method dereferenced the argument without checking it, unlike setCiphers(),
which stores a null value and resets the values derived from the previous
configuration. Do the same here.

Tests: testCiphersuite04 covers the JSSE format (comma separated) list and
the conversion to the OpenSSL format list. testCiphersuite05 covers the
null value, which previously failed with a NullPointerException.
Put all files into a directory matching the release version number
…ager

When the KeyManagerFactory is provided by a FIPS module, Tomcat passes the
configured key store to the factory directly and skips the manipulation of
key material that FIPS does not allow. PEM format certificates require that
manipulation: the key and certificate chain are read from the PEM files and
imported into an in memory key store.

Previously, the FIPS code path used the configured key store without
checking it. For a PEM based configuration there is no key store, so the
factory was initialised with a null key store. Depending on the
implementation, that either produced a key manager with no keys, allowing
the connector to start but causing every TLS handshake to fail, or an
unrelated error during start up.

Now report the configuration error when no key store is available. The
existing message is used when no certificate has been configured at all, as
for a non-FIPS configuration. Otherwise, explain that PEM format
certificate files require a key store when a FIPS key manager factory is in
use.

Tests: testFipsWithPemConfiguration and testFipsWithoutConfiguration cover
both cases. Both previously failed because no error was reported.
The encoded text was written with the final line of the Base64 data joined
onto the end boundary and without a line separator after the end boundary.
The result was not valid PEM: OpenSSL was unable to decode it
("Could not find or decode certificate") and Tomcat's own PEM parser did not
see any certificate in it, since the end boundary never started a line.

Write each boundary on a line of its own, terminate the encoded text with a
line separator and encode with the line length of 64 characters that RFC
7468 requires. The Base64 line separator is now the same as the one used for
the boundaries, so the output no longer mixes line separators when the JVM
uses a line feed. The output of the method now has the same format as the one
produced by keytool -exportcert -rfc for the same certificate, apart from the
line separator, which on a JVM using a line feed will be that separator
rather than the carriage return line feed used by keytool.

These values are used for the mod_rewrite compatible SSL_SERVER_CERT,
SSL_CLIENT_CERT and CERT_CHAIN variables, which are expected to contain a
full PEM encoded certificate as Apache HTTP Server's mod_ssl provides them.

Tests: testToPem encodes the certificate in the new certificate.pem test
file and checks the resulting structure as well as that the result can be
read back as PEM. It previously failed because the end boundary was not on a
line of its own.
The scanner for the parts of a PEM file silently accepted files with a
malformed structure. A part that was never closed by an end boundary,
either because the file ended or because the next start boundary
appeared, was dropped without any error and the part was simply missing
from the result. An end boundary whose type did not match the type of
the start boundary that opened the part was accepted. An end boundary
that did not follow a start boundary put a null part into the list of
parts, leading to a null pointer exception later on. Boundary lines and
DEK-Info lines were parsed without any checks, leading to an index out
of bounds exception for truncated boundary lines and to a silently
ignored or incorrectly parsed DEK-Info line. For example, a DEK-Info
line with white space after the comma was parsed with the white space
kept as part of the initialisation vector, which only became visible as
a failure to decrypt the key.

Reject all of these with an IOException that describes the problem. This
lets the connector fail at startup with a usable configuration error
instead of silently loading an incomplete file or failing later with an
unrelated exception. White space at the end of a boundary line remains
tolerated, since RFC 7468 allows it there.

Tests: 7 new tests in TestPEMFile for the malformed structures listed
above and for white space at the end of the boundary lines. All 23 PEM
files in the existing test resources parse exactly as before.
The switch on the DEK-Info algorithm of a traditional PEM encrypted
private key only handled DES-CBC, DES-EDE3-CBC and AES-256-CBC. Any
other algorithm, including the AES-128-CBC and AES-192-CBC that OpenSSL
readily produces with openssl rsa -aes128 and -aes192, fell into a
default branch that used the OpenSSL algorithm name directly as the JCE
transformation name. That always failed with a message like Cannot find
any provider supporting AES-128-CBC, which does not say that the
algorithm is simply unsupported.

Add the two missing algorithms, using the same key derivation and the
same warning about the OpenSSL password based key derivation that the
AES-256-CBC case uses, and report any other algorithm as unsupported
with the name of the PEM file and the algorithm instead of attempting to
use the OpenSSL name as a JCE transformation.

Tests: new fixtures key-encrypted-pkcs1-aes128.pem and
key-encrypted-pkcs1-aes192.pem, generated with OpenSSL from the existing
key-pkcs1.pem, cover the new algorithms. A new test checks that an
algorithm outside the supported set is reported as a
NoSuchAlgorithmException that names the algorithm.
Move the certificate and private key loading out of OpenSSLContext into
a new reusable CertificateLoader utility class, to allow reuse (the
QUIC-based HTTP/3 endpoints will need the same logic). PEM (with an
ENGINE fallback for unparseable keys), PKCS#12 and Java key store
sources are supported; PKCS#12 is parsed with the JDK so a wrong
password is detected via the MAC check. The native objects of a loaded
entry (leaf, key, chain) are owned by the configuration snapshot which
loads them, and released with freeCertEntry() when it is discarded.

The Java X.509 chain view used by JMX and the certificate expiry checks
moves as well, and so does the TLS 1.3 pre-shared key find-session
callback: it is now installed on the SSL_CTX and resolves the per-host
selector per connection, since a single listener serves all hosts.

Also:

- Detect OpenSSL 4.x (OpenSSLStatus.isOpenSSL4()) which provides the
  QUIC API, and add the d2i_AutoPrivateKey binding which is used to
  convert Java private keys to native ones.
- Complete and align the panama string bundle: add the FIPS provider
  keys which OpenSSLLibrary and AprLifecycleListener already reference,
  rename opensslconf.unknownCommandType to opensslconf.typeUnknown
  which is the key OpenSSLContext uses, and drop the unused panama
  engine.noSession key.
….3 when rebuilding the list of enabled protocols during initialization.
See the diff for the full explanation. The short version is that this
was an expensive check paid by everyone for a rare bug that should
affect very few - hence the refactoring.
@rvullriede

Copy link
Copy Markdown
Owner Author

Merged upstream as apache#1083.

@rvullriede rvullriede closed this Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants