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/19 21:43:05 UTC

(tomcat) branch 10.1.x updated (05b4e876e4 -> c15a98ec3d)

This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a change to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


    from 05b4e876e4 Clean-up
     new 17234c387e Fix jspc handling of the full stop (--) argument
     new f35f427c80 Fix jspc infinite loop with a trailing -trimSpaces argument
     new b94d6b83e6 Stop the Ant compiler System.err capture when compilation fails unexpectedly
     new 84ec9f7800 Report compilation errors before removing the generated source
     new 46ce2c54d1 Match JSP pages in sub-directories in JspConfig.isJspPage
     new e54527e0d4 Avoid NullPointerException when the JSP source cannot be read for an error detail
     new f2706e6e97 Correct the "unusable error detail" line number in JavacErrorDetail
     new 0ffa6fac2d Fix the jsp:attribute trim loop skipping nodes after removal
     new f9393219de Avoid NullPointerException in include error path for non-JAR pages
     new 947f7f75ca Validate page directive buffer values against the JSP specification
     new bab89e9ac2 Match the JSP namespace exactly when detecting JSP documents
     new f0545bb994 Extract the SMAP from the end of the compiled class file
     new 380eb782f9 Report a translation error for an empty taglib URI
     new 209fa2e3be Report a translation error for an invalid TLD jsp-version
     new 744a6e74c5 Avoid NullPointerException when a cached TLD is removed
     new 22c06ced0d Omit the id from validation messages without one
     new a2e083c5b5 Reject jsp:element with multiple name attributes
     new 48208e0c78 Correct the assignability check for Graal bean property writes
     new 5162412292 Avoid NullPointerException writing a null bean property value
     new 37a1db8eb7 Report bean getter and setter exceptions in GraalVM mode
     new 3428bfa6a4 Keep the wrapped exception in the JSP EL exception cause chain
     new 1a7f7ad2c9 Correct the expression wrapper equals implementation
     new 01817b9e15 Use the canonical enum name in optimized tag setter code generation
     new ac7142b626 Use the canonical enum name in the optimized string interpreter
     new 6fe39d64b6 Avoid NullPointerException releasing a PageContext when the pool size changed
     new 607192fa11 Avoid StringIndexOutOfBoundsException forwarding a relative path from a slash-less servlet path
     new fa2825827f Record JSP usage time on every request, fixing premature idle unload
     new 99083290a8 Avoid registering TLD listeners twice for a duplicate taglib URI
     new dad31835db Resolve JspC resources whose path contains URI-illegal characters
     new 553a8633b8 Avoid StringIndexOutOfBoundsException on an empty content-type parameter
     new 06acd5918f Expose the ForEach tag plugin loop variable as an Integer
     new 9b1f916e3f Validate begin, end and step in the ForEach and ForTokens tag plugins
     new 2a0b5a1cd0 Fall back when c:when or c:otherwise has no choose parent
     new a0de9017ce Compute the ForEach tag plugin's state flags per request
     new 4ea3677f93 Share the Import tag plugin URL with its params via the plugin context
     new d18bcf61d1 Trim and escape the Out tag plugin body fallback
     new 1e88dd946d Store the Set tag plugin deferred value in the variable mapper
     new e48a38e62c Fall back when the Set tag plugin has nowhere to set
     new 437c0be2b6 Strip a trailing slash from the context in resolveUrl
     new 64c4b06524 Share the Url and Redirect tag plugin URLs with their params
     new ab1313f0cc Honour a FastRemovalDequeue maximum size of one
     new bd9e004a37 Avoid NullPointerException rendering a null entry
     new 511586603b Keep UniqueAttributesImpl tracking in step with its attributes
     new d5ea224b93 Build UniqueAttributesImpl.setAttributes() from the incoming set
     new 9e7d4a6a7a Match duplicate page directive attribute names exactly
     new c15a98ec3d Java compatibility

The 46 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/jasper/JspC.java                   |  43 ++--
 java/org/apache/jasper/compiler/AntCompiler.java   | 169 ++++++-------
 java/org/apache/jasper/compiler/JDTCompiler.java   |  12 +-
 java/org/apache/jasper/compiler/JavaCompiler.java  |  12 +-
 .../apache/jasper/compiler/JavacErrorDetail.java   |  14 +-
 java/org/apache/jasper/compiler/JspConfig.java     |   2 +-
 .../apache/jasper/compiler/JspDocumentParser.java  |   3 +
 java/org/apache/jasper/compiler/PageInfo.java      |  10 +
 .../apache/jasper/compiler/ParserController.java   |   9 +-
 java/org/apache/jasper/compiler/SmapUtil.java      |  66 ++---
 .../apache/jasper/compiler/TagLibraryInfoImpl.java |   4 +
 .../apache/jasper/compiler/TagPluginManager.java   |   9 +
 java/org/apache/jasper/compiler/TldCache.java      |   6 +
 java/org/apache/jasper/compiler/Validator.java     |  35 ++-
 .../compiler/tagplugin/TagPluginContext.java       |   5 +-
 java/org/apache/jasper/el/JasperELResolver.java    |  19 +-
 java/org/apache/jasper/el/JspELException.java      |   2 +-
 java/org/apache/jasper/el/JspMethodExpression.java |  10 +-
 .../jasper/el/JspMethodNotFoundException.java      |   2 +-
 .../jasper/el/JspPropertyNotFoundException.java    |   2 +-
 .../jasper/el/JspPropertyNotWritableException.java |   2 +-
 java/org/apache/jasper/el/JspValueExpression.java  |  10 +-
 .../optimizations/ELInterpreterTagSetters.java     |   5 +-
 .../optimizations/StringInterpreterEnum.java       |   5 +-
 .../jasper/resources/LocalStrings.properties       |   4 +
 java/org/apache/jasper/runtime/JspFactoryImpl.java |  11 +-
 .../org/apache/jasper/runtime/PageContextImpl.java |   6 +-
 .../apache/jasper/servlet/JspCServletContext.java  |  37 ++-
 .../apache/jasper/servlet/JspServletWrapper.java   |  11 +-
 java/org/apache/jasper/servlet/TldScanner.java     |  12 +-
 java/org/apache/jasper/tagplugins/jstl/Util.java   |  18 +-
 .../apache/jasper/tagplugins/jstl/core/Choose.java |   4 +
 .../jasper/tagplugins/jstl/core/ForEach.java       |  79 ++++--
 .../jasper/tagplugins/jstl/core/ForTokens.java     |  19 +-
 .../apache/jasper/tagplugins/jstl/core/Import.java |  23 +-
 .../jasper/tagplugins/jstl/core/Otherwise.java     |   9 +
 .../apache/jasper/tagplugins/jstl/core/Out.java    |  24 ++
 .../apache/jasper/tagplugins/jstl/core/Param.java  |  37 ++-
 .../jasper/tagplugins/jstl/core/Redirect.java      |  19 +-
 .../apache/jasper/tagplugins/jstl/core/Set.java    |  37 ++-
 .../apache/jasper/tagplugins/jstl/core/Url.java    |  21 +-
 .../apache/jasper/tagplugins/jstl/core/When.java   |  12 +
 .../org/apache/jasper/util/FastRemovalDequeue.java |  11 +-
 .../apache/jasper/util/UniqueAttributesImpl.java   |  59 ++++-
 .../catalina/core/TestDefaultInstanceManager.java  |   2 +-
 test/org/apache/el/TestELInJsp.java                |   2 +-
 test/org/apache/jasper/TestJspC.java               |  70 ++++++
 .../apache/jasper/compiler/TestAntCompiler.java    |  76 ++++++
 .../apache/jasper/compiler/TestJavaCompiler.java   | 114 +++++++++
 .../jasper/compiler/TestJavacErrorDetail.java      |  52 ++++
 .../jasper/compiler/TestJspDocumentParser.java     |  23 ++
 test/org/apache/jasper/compiler/TestPageInfo.java  |  79 ++++++
 .../jasper/compiler/TestParserController.java      | 110 +++++++++
 test/org/apache/jasper/compiler/TestSmapUtil.java  |  93 +++++++
 .../jasper/compiler/TestTagLibraryInfoImpl.java    |  18 ++
 test/org/apache/jasper/compiler/TestTldCache.java  |  49 ++++
 test/org/apache/jasper/compiler/TestValidator.java |  71 ++++++
 .../org/apache/jasper/el/TestJasperELResolver.java |  64 ++++-
 .../optimizations/TestELInterpreterTagSetters.java |  29 +++
 .../optimizations/TestStringInterpreterEnum.java   |  20 ++
 .../TestStringInterpreterTagSetters.java           |   6 +
 .../apache/jasper/runtime/TestPageContextImpl.java |  62 +++++
 .../jasper/servlet/TestJspCServletContext.java     |  44 ++++
 test/org/apache/jasper/servlet/TestTldScanner.java |  61 +++++
 .../jstl/core/{TestSet.java => TestChoose.java}    |  24 +-
 .../jasper/tagplugins/jstl/core/TestForEach.java   |  54 ++++
 .../jstl/core/{TestOut.java => TestForTokens.java} |  41 ++--
 .../jasper/tagplugins/jstl/core/TestImport.java    |  95 +++++++
 .../jstl/core/{TestSet.java => TestOtherwise.java} |  29 +--
 .../jasper/tagplugins/jstl/core/TestOut.java       |  41 ++++
 .../jasper/tagplugins/jstl/core/TestRedirect.java  |  27 ++
 .../jasper/tagplugins/jstl/core/TestSet.java       |  61 +++++
 .../jasper/tagplugins/jstl/core/TestUrl.java       | 172 +++++++++++++
 .../jstl/core/{TestForEach.java => TestWhen.java}  |  38 ++-
 ...direct-tagPlugins.xml => import-tagPlugins.xml} |   8 +-
 .../tagplugins/jstl/core/redirect-tagPlugins.xml   |   4 +
 ...{redirect-tagPlugins.xml => url-tagPlugins.xml} |  16 +-
 .../apache/jasper/util/TestFastRemovalDequeue.java |  82 +++++++
 .../jasper/util/TestUniqueAttributesImpl.java      | 273 +++++++++++++++++++++
 .../WEB-INF/{bug53545.tld => invalid-version.tld}  |  25 +-
 .../WEB-INF/{bug53545.tld => null-id-tlv.tld}      |  19 +-
 test/webapp/WEB-INF/tag-setters.tld                |  11 +
 ...biginteger.jsp => bug64872-nested-timeunit.jsp} |   8 +-
 ...-timeunit.jsp => bug64872b-nested-timeunit.jsp} |   6 +-
 test/webapp/jsp/document/named-attribute-trim.jspx |  37 +++
 .../pageinfo/buffer-min.jsp}                       |   2 +-
 .../pageinfo/buffer-negative.jsp}                  |   2 +-
 .../pageinfo/buffer-none.jsp}                      |   2 +-
 .../pageinfo/buffer-overflow.jsp}                  |   2 +-
 .../pageinfo/buffer-valid.jsp}                     |   2 +-
 .../pageinfo/buffer-zero.jsp}                      |   2 +-
 .../parsing/element-duplicate-name.jspx}           |   5 +-
 .../parsing/include-invalid-uri.jsp}               |   7 +-
 .../parsing/taglib-empty-uri.jsp}                  |   7 +-
 .../jsp/parsing/taglib-invalid-version.jsp}        |   7 +-
 .../parsing/taglib-null-id-tlv.jsp}                |   8 +-
 .../webapp/jstl/{redirect.jsp => choose-basic.jsp} |  11 +-
 .../foreach-begin-negative.jsp}                    |   6 +-
 .../redirect.tag => jstl/foreach-end-negative.jsp} |   7 +-
 .../redirect.tag => jstl/foreach-numeric-var.jsp}  |   5 +-
 .../redirect.tag => jstl/foreach-step-zero.jsp}    |   6 +-
 .../fortokens-begin-negative.jsp}                  |   6 +-
 .../redirect.tag => jstl/fortokens-step-zero.jsp}  |   6 +-
 .../jstl/{redirect.jsp => import-clobber.jsp}      |  11 +-
 .../jstl/redirect.tag => jstl/import-nested.jsp}   |   8 +-
 .../jstl/redirect.tag => jstl/import-params.jsp}   |   8 +-
 .../jstl/import-target.jsp}                        |   9 +-
 .../otherwise-outside-choose.jsp}                  |   7 +-
 test/webapp/jstl/out-body.jsp                      |  38 +++
 test/webapp/jstl/redirect-params.jsp               |  22 ++
 test/webapp/jstl/set-deferred.jsp                  |  39 +++
 test/webapp/jstl/set-no-var-target.jsp             |  24 ++
 test/webapp/jstl/url-clobber.jsp                   |  23 ++
 test/webapp/jstl/url-context-slash.jsp             |  25 ++
 test/webapp/jstl/url-nested.jsp                    |  20 ++
 test/webapp/jstl/url-param-fallback-nested.jsp     |  22 ++
 test/webapp/jstl/url-param-nested-if.jsp           |  25 ++
 test/webapp/jstl/url-params.jsp                    |  22 ++
 .../redirect.tag => jstl/when-outside-choose.jsp}  |   7 +-
 webapps/docs/changelog.xml                         |  98 ++++++++
 120 files changed, 3089 insertions(+), 437 deletions(-)
 create mode 100644 test/org/apache/jasper/compiler/TestAntCompiler.java
 create mode 100644 test/org/apache/jasper/compiler/TestJavaCompiler.java
 create mode 100644 test/org/apache/jasper/compiler/TestJavacErrorDetail.java
 create mode 100644 test/org/apache/jasper/compiler/TestPageInfo.java
 create mode 100644 test/org/apache/jasper/compiler/TestParserController.java
 create mode 100644 test/org/apache/jasper/compiler/TestSmapUtil.java
 copy test/org/apache/jasper/tagplugins/jstl/core/{TestSet.java => TestChoose.java} (67%)
 copy test/org/apache/jasper/tagplugins/jstl/core/{TestOut.java => TestForTokens.java} (54%)
 create mode 100644 test/org/apache/jasper/tagplugins/jstl/core/TestImport.java
 copy test/org/apache/jasper/tagplugins/jstl/core/{TestSet.java => TestOtherwise.java} (66%)
 create mode 100644 test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java
 copy test/org/apache/jasper/tagplugins/jstl/core/{TestForEach.java => TestWhen.java} (60%)
 copy test/org/apache/jasper/tagplugins/jstl/core/{redirect-tagPlugins.xml => import-tagPlugins.xml} (72%)
 copy test/org/apache/jasper/tagplugins/jstl/core/{redirect-tagPlugins.xml => url-tagPlugins.xml} (55%)
 create mode 100644 test/org/apache/jasper/util/TestUniqueAttributesImpl.java
 copy test/webapp/WEB-INF/{bug53545.tld => invalid-version.tld} (55%)
 copy test/webapp/WEB-INF/{bug53545.tld => null-id-tlv.tld} (68%)
 copy test/webapp/bug6nnnn/{bug64872-biginteger.jsp => bug64872-nested-timeunit.jsp} (81%)
 copy test/webapp/bug6nnnn/{bug64872b-timeunit.jsp => bug64872b-nested-timeunit.jsp} (86%)
 create mode 100644 test/webapp/jsp/document/named-attribute-trim.jspx
 copy test/webapp/{jstl/redirect-target.jsp => jsp/pageinfo/buffer-min.jsp} (96%)
 copy test/webapp/{jstl/redirect-target.jsp => jsp/pageinfo/buffer-negative.jsp} (96%)
 copy test/webapp/{jstl/redirect-target.jsp => jsp/pageinfo/buffer-none.jsp} (96%)
 copy test/webapp/{jstl/redirect-target.jsp => jsp/pageinfo/buffer-overflow.jsp} (96%)
 copy test/webapp/{jstl/redirect-target.jsp => jsp/pageinfo/buffer-valid.jsp} (96%)
 copy test/webapp/{jstl/redirect-target.jsp => jsp/pageinfo/buffer-zero.jsp} (96%)
 copy test/webapp/{WEB-INF/tags/no-jsp-root.tagx => jsp/parsing/element-duplicate-name.jspx} (86%)
 copy test/webapp/{bug49nnn/bug49297MultiplePageEncoding2.jsp => jsp/parsing/include-invalid-uri.jsp} (84%)
 copy test/webapp/{bug49nnn/bug49297MultiplePageEncoding2.jsp => jsp/parsing/taglib-empty-uri.jsp} (84%)
 copy test/{webapp-servletsecurity-b/protected.jsp => webapp/jsp/parsing/taglib-invalid-version.jsp} (78%)
 copy test/webapp/{bug49nnn/bug49297MultiplePageEncoding1.jsp => jsp/parsing/taglib-null-id-tlv.jsp} (81%)
 copy test/webapp/jstl/{redirect.jsp => choose-basic.jsp} (74%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/foreach-begin-negative.jsp} (79%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/foreach-end-negative.jsp} (77%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/foreach-numeric-var.jsp} (80%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/foreach-step-zero.jsp} (78%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/fortokens-begin-negative.jsp} (78%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/fortokens-step-zero.jsp} (78%)
 copy test/webapp/jstl/{redirect.jsp => import-clobber.jsp} (73%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/import-nested.jsp} (76%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/import-params.jsp} (76%)
 copy test/{webapp-2.3/el-as-literal.jsp => webapp/jstl/import-target.jsp} (83%)
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/otherwise-outside-choose.jsp} (78%)
 create mode 100644 test/webapp/jstl/out-body.jsp
 create mode 100644 test/webapp/jstl/redirect-params.jsp
 create mode 100644 test/webapp/jstl/set-deferred.jsp
 create mode 100644 test/webapp/jstl/set-no-var-target.jsp
 create mode 100644 test/webapp/jstl/url-clobber.jsp
 create mode 100644 test/webapp/jstl/url-context-slash.jsp
 create mode 100644 test/webapp/jstl/url-nested.jsp
 create mode 100644 test/webapp/jstl/url-param-fallback-nested.jsp
 create mode 100644 test/webapp/jstl/url-param-nested-if.jsp
 create mode 100644 test/webapp/jstl/url-params.jsp
 copy test/webapp/{WEB-INF/tags/jstl/redirect.tag => jstl/when-outside-choose.jsp} (77%)


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 06/46: Avoid NullPointerException when the JSP source cannot be read for an error detail

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit e54527e0d47da208403e0daa7a568e22ffc3b550
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 21:34:37 2026 +0200

    Avoid NullPointerException when the JSP source cannot be read for an error detail
    
    When a compilation error is reported, JavacErrorDetail reads the JSP
    source to include a fragment of the page in the error report. The JSP
    input stream can legitimately be null, for example when the tag file
    entry is missing from its jar or when the JSP is removed between
    translation and compilation. In that case reading the stream threw a
    NullPointerException, which escaped the error detail construction and
    replaced the compilation error report with an opaque failure.
    
    Fall back to reporting only the error in the generated Java source when
    the JSP source cannot be obtained, as is already done when the error
    cannot be mapped to a JSP line at all.
---
 .../apache/jasper/compiler/JavacErrorDetail.java   |  6 +++
 .../jasper/compiler/TestJavacErrorDetail.java      | 52 ++++++++++++++++++++++
 2 files changed, 58 insertions(+)

diff --git a/java/org/apache/jasper/compiler/JavacErrorDetail.java b/java/org/apache/jasper/compiler/JavacErrorDetail.java
index c8a7c58cd7..eef5f57205 100644
--- a/java/org/apache/jasper/compiler/JavacErrorDetail.java
+++ b/java/org/apache/jasper/compiler/JavacErrorDetail.java
@@ -83,6 +83,12 @@ public class JavacErrorDetail {
                 } else {
                     is = ctxt.getResourceAsStream(jspFileName);
                 }
+                if (is == null) {
+                    // The JSP source is no longer available. Report only the
+                    // details of the error in the generated Java source.
+                    this.jspBeginLineNum = -1;
+                    return;
+                }
                 // Read both files in, so we can inspect them
                 String[] jspLines = readFile(is);
 
diff --git a/test/org/apache/jasper/compiler/TestJavacErrorDetail.java b/test/org/apache/jasper/compiler/TestJavacErrorDetail.java
new file mode 100644
index 0000000000..edc567215b
--- /dev/null
+++ b/test/org/apache/jasper/compiler/TestJavacErrorDetail.java
@@ -0,0 +1,52 @@
+/*
+ * 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.jasper.compiler;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.jasper.JspCompilationContext;
+import org.easymock.EasyMock;
+
+public class TestJavacErrorDetail {
+
+    /*
+     * If the JSP source is no longer available when the error detail is
+     * constructed, such as when the JSP is removed between translation and
+     * compilation, the error detail must fall back to reporting only the
+     * error in the generated Java source, rather than throwing a
+     * NullPointerException.
+     */
+    @Test
+    public void testMissingJspSource() throws Exception {
+        JspCompilationContext ctxt = EasyMock.createMock(
+                JspCompilationContext.class);
+        EasyMock.expect(ctxt.getTagFileJar()).andReturn(null).anyTimes();
+        EasyMock.expect(ctxt.getResourceAsStream("/a.jsp")).andReturn(null)
+                .anyTimes();
+        EasyMock.replay(ctxt);
+
+        JavacErrorDetail detail = new JavacErrorDetail("a_jsp.java", 10,
+                "/a.jsp", 5, new StringBuilder("error message"), ctxt);
+
+        // A negative JSP line number signals that no JSP line is known, in
+        // which case only the Java source error details are reported
+        Assert.assertEquals(-1, detail.getJspBeginLineNumber());
+
+        EasyMock.verify(ctxt);
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 14/46: Report a translation error for an invalid TLD jsp-version

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 209fa2e3be0325ad37f468d74a7bf240707e8ab3
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 09:45:57 2026 +0200

    Report a translation error for an invalid TLD jsp-version
    
    Validator.checkXmlAttributes() parsed the required version of the tag
    library with Double.parseDouble() once per attribute and without any
    exception handling. TLD XML validation is off by default and the parsed
    jsp-version value is only null checked, never format validated, so a
    TLD using a value such as "2.1.1" parsed fine and any page using one
    of the library's tags with attributes failed with a raw
    NumberFormatException rather than a JSP translation error. The same
    value is already handled defensively at the other two places where it
    is parsed: Compiler.generateJava() for tag files and the implicit TLD
    handling in ImplicitTagLibraryInfo.
    
    The required version is constant for the tag so the parse is now
    performed once before the attribute loop instead of for every
    attribute. A value that cannot be parsed is reported as a translation
    error at the tag invocation using a new message.
    
    Note that this also reports the invalid version for a tag invocation
    with no attributes, which previously compiled without any error.
    
    Found by code review.
---
 java/org/apache/jasper/compiler/Validator.java     | 12 ++++++-
 .../jasper/resources/LocalStrings.properties       |  1 +
 test/org/apache/jasper/compiler/TestValidator.java | 18 ++++++++++
 test/webapp/WEB-INF/invalid-version.tld            | 38 ++++++++++++++++++++++
 test/webapp/jsp/parsing/taglib-invalid-version.jsp | 24 ++++++++++++++
 5 files changed, 92 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/compiler/Validator.java b/java/org/apache/jasper/compiler/Validator.java
index 4d9e4deb37..965f46b2b4 100644
--- a/java/org/apache/jasper/compiler/Validator.java
+++ b/java/org/apache/jasper/compiler/Validator.java
@@ -966,6 +966,17 @@ class Validator {
             TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
             Attributes attrs = n.getAttributes();
 
+            // The required version of the tag library is constant for the tag,
+            // so parse it once rather than for every attribute
+            double libraryVersion = 0;
+            try {
+                libraryVersion = Double.parseDouble(tagInfo.getTagLibrary().getRequiredVersion());
+            } catch (NumberFormatException e) {
+                // Never reached: jspError always throws
+                err.jspError(n, "jsp.error.invalid.taglib.version", tagInfo.getTagLibrary().getRequiredVersion(),
+                        n.getQName());
+            }
+
             for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
                 boolean found = false;
 
@@ -973,7 +984,6 @@ class Validator {
                         (!n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("<%=")));
                 boolean elExpression = false;
                 boolean deferred = false;
-                double libraryVersion = Double.parseDouble(tagInfo.getTagLibrary().getRequiredVersion());
                 boolean deferredSyntaxAllowedAsLiteral =
                         pageInfo.isDeferredSyntaxAllowedAsLiteral() || libraryVersion < 2.1;
 
diff --git a/java/org/apache/jasper/resources/LocalStrings.properties b/java/org/apache/jasper/resources/LocalStrings.properties
index d533c92542..bab1da9ea7 100644
--- a/java/org/apache/jasper/resources/LocalStrings.properties
+++ b/java/org/apache/jasper/resources/LocalStrings.properties
@@ -99,6 +99,7 @@ jsp.error.invalid.includeInTagFileJar=The include [{0}] is not valid since it is
 jsp.error.invalid.name=File [{0}] uses name [{1}] in jsp:getProperty for a bean that was not previously introduced as per JSP.5.3
 jsp.error.invalid.scope=Illegal value of ''scope'' attribute: [{0}] (must be one of "page", "request", "session", or "application")
 jsp.error.invalid.tagdir=Tag file directory [{0}] does not start with "/WEB-INF/tags"
+jsp.error.invalid.taglib.version=Invalid JSP version [{0}] defined by the tag library used by tag [{1}]
 jsp.error.invalid.varscope=Invalid variable scope [{0}]
 jsp.error.invalid.version=Invalid JSP version defined for tag file at [{0}]
 jsp.error.ise_on_clear=Illegal to clear() when buffer size == 0
diff --git a/test/org/apache/jasper/compiler/TestValidator.java b/test/org/apache/jasper/compiler/TestValidator.java
index 64ae9b90e0..2e084ab744 100644
--- a/test/org/apache/jasper/compiler/TestValidator.java
+++ b/test/org/apache/jasper/compiler/TestValidator.java
@@ -41,6 +41,24 @@ public class TestValidator extends TomcatBaseTest {
         Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
     }
 
+    @Test
+    public void testInvalidTldVersion() throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/parsing/taglib-invalid-version.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
+
+        // The invalid jsp-version in the TLD must produce a clean translation
+        // error. It previously triggered a raw NumberFormatException at
+        // translation time since the value was parsed without a catch.
+        String result = res.toString();
+        Assert.assertTrue(result, result.contains("Invalid JSP version [2.1.1]"));
+        Assert.assertFalse(result, result.contains("NumberFormatException"));
+    }
+
     @Test
     public void testTldVersions22() throws Exception {
         Tomcat tomcat = getTomcatInstance();
diff --git a/test/webapp/WEB-INF/invalid-version.tld b/test/webapp/WEB-INF/invalid-version.tld
new file mode 100644
index 0000000000..9e0fc0c3cf
--- /dev/null
+++ b/test/webapp/WEB-INF/invalid-version.tld
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<taglib xmlns="http://java.sun.com/xml/ns/javaee"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
+    version="2.1">
+    <tlib-version>1.0</tlib-version>
+    <short-name>iv</short-name>
+    <!-- The jsp-version element is not part of the TLD 2.1 schema. It is
+         accepted here because TLD XML validation is off by default. The value
+         is not a valid version number. -->
+    <jsp-version>2.1.1</jsp-version>
+    <tag>
+      <name>echo</name>
+      <tag-class>org.apache.jasper.compiler.TestValidator$Echo</tag-class>
+      <body-content>empty</body-content>
+      <attribute>
+        <name>echo</name>
+        <required>false</required>
+        <rtexprvalue>false</rtexprvalue>
+      </attribute>
+    </tag>
+</taglib>
diff --git a/test/webapp/jsp/parsing/taglib-invalid-version.jsp b/test/webapp/jsp/parsing/taglib-invalid-version.jsp
new file mode 100644
index 0000000000..47136a9b72
--- /dev/null
+++ b/test/webapp/jsp/parsing/taglib-invalid-version.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page contentType="text/html;charset=UTF-8" %>
+<%@ taglib uri="/WEB-INF/invalid-version.tld" prefix="iv" %>
+<html>
+  <head><title>Taglib with an invalid TLD version test case</title></head>
+  <body>
+    <iv:echo echo="Should not appear"/>
+  </body>
+</html>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 17/46: Reject jsp:element with multiple name attributes

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit a2e083c5b596e044141fefb81caf6819de855f23
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 10:08:16 2026 +0200

    Reject jsp:element with multiple name attributes
    
    The JspAttribute array built for a jsp:element action was sized as the
    number of XML-style attributes minus one plus the number of named
    attributes, which assumes that exactly one XML-style attribute with the
    local name 'name' is present. XML permits two attributes with the same
    local name as long as they use different namespace prefixes, for
    example:
    
        <jsp:element name="e" p:name="f"/>
    
    Both attributes matched the check that excludes the 'name' attribute
    from the array, so the array was over-allocated and the trailing null
    entry was passed on by setJspAttributes() only to trigger a
    NullPointerException later while collecting or generating code.
    
    Count the attributes with the local name 'name' before allocating the
    array and report the use of more than one as a translation error, since
    jsp:element has exactly one 'name' attribute. Pages with a single
    'name' attribute, including those using a prefixed name attribute, are
    handled exactly as before.
    
    Found by code review.
---
 java/org/apache/jasper/compiler/Validator.java       | 17 ++++++++++++++++-
 .../apache/jasper/resources/LocalStrings.properties  |  1 +
 test/org/apache/jasper/compiler/TestValidator.java   | 20 ++++++++++++++++++++
 test/webapp/jsp/parsing/element-duplicate-name.jspx  | 20 ++++++++++++++++++++
 4 files changed, 57 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/compiler/Validator.java b/java/org/apache/jasper/compiler/Validator.java
index dfda3dc112..32ed3cd0e5 100644
--- a/java/org/apache/jasper/compiler/Validator.java
+++ b/java/org/apache/jasper/compiler/Validator.java
@@ -816,9 +816,24 @@ class Validator {
 
             Node.Nodes namedAttrs = n.getNamedAttributeNodes();
 
+            /*
+             * XML allows attributes with the same local name as long as they
+             * use different namespace prefixes so the number of 'name'
+             * attributes must be counted rather than assumed to be one.
+             */
+            int nameAttrCount = 0;
+            for (int i = 0; i < xmlAttrLen; i++) {
+                if ("name".equals(attrs.getLocalName(i))) {
+                    nameAttrCount++;
+                }
+            }
+            if (nameAttrCount > 1) {
+                err.jspError(n, "jsp.error.jspelement.duplicate.name");
+            }
+
             // XML-style 'name' attribute, which is mandatory, must not be
             // included in JspAttribute array
-            int jspAttrSize = xmlAttrLen - 1 + namedAttrs.size();
+            int jspAttrSize = xmlAttrLen - nameAttrCount + namedAttrs.size();
 
             Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize];
             int jspAttrIndex = 0;
diff --git a/java/org/apache/jasper/resources/LocalStrings.properties b/java/org/apache/jasper/resources/LocalStrings.properties
index bab1da9ea7..f82467d793 100644
--- a/java/org/apache/jasper/resources/LocalStrings.properties
+++ b/java/org/apache/jasper/resources/LocalStrings.properties
@@ -112,6 +112,7 @@ jsp.error.jspbody.required=Must use jsp:body to specify tag body for [{0}] if js
 jsp.error.jspc.missingTarget=Missing target: Must specify -webapp or -uriroot, or one or more JSP pages
 jsp.error.jspc.no_uriroot=The uriroot is not specified and cannot be located with the specified JSP file(s)
 jsp.error.jspc.uriroot_not_dir=The -uriroot option must specify a pre-existing directory
+jsp.error.jspelement.duplicate.name=XML-style 'name' attribute appears more than once
 jsp.error.jspelement.missing.name=Mandatory XML-style 'name' attribute missing
 jsp.error.jspoutput.conflict=&lt;jsp:output&gt;: illegal to have multiple occurrences of [{0}] with different values (old: [{1}], new: [{2}])
 jsp.error.jspoutput.doctypenamesystem=&lt;jsp:output&gt;: 'doctype-root-element' and 'doctype-system' attributes must appear together
diff --git a/test/org/apache/jasper/compiler/TestValidator.java b/test/org/apache/jasper/compiler/TestValidator.java
index b2ad3535f7..c37b677756 100644
--- a/test/org/apache/jasper/compiler/TestValidator.java
+++ b/test/org/apache/jasper/compiler/TestValidator.java
@@ -83,6 +83,26 @@ public class TestValidator extends TomcatBaseTest {
         Assert.assertTrue(result, result.contains("123: message with an id"));
     }
 
+    @Test
+    public void testDuplicateJspElementName() throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/parsing/element-duplicate-name.jspx", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
+
+        // XML allows two attributes with the local name 'name' as long as
+        // they use different namespace prefixes. jsp:element must report that
+        // as a translation error. It previously sized the JspAttribute array
+        // for a single 'name' attribute which left a null entry that later
+        // triggered a NullPointerException.
+        String result = res.toString();
+        Assert.assertTrue(result, result.contains("attribute appears more than once"));
+        Assert.assertFalse(result, result.contains("NullPointerException"));
+    }
+
     @Test
     public void testTldVersions22() throws Exception {
         Tomcat tomcat = getTomcatInstance();
diff --git a/test/webapp/jsp/parsing/element-duplicate-name.jspx b/test/webapp/jsp/parsing/element-duplicate-name.jspx
new file mode 100644
index 0000000000..6c0fe404fe
--- /dev/null
+++ b/test/webapp/jsp/parsing/element-duplicate-name.jspx
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:p="urn:test" version="2.0">
+  <jsp:element name="e" p:name="f"/>
+</jsp:root>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 24/46: Use the canonical enum name in the optimized string interpreter

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit ac7142b626edd16ae29839c0319e5b4c783682a9
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 11:15:49 2026 +0200

    Use the canonical enum name in the optimized string interpreter
    
    StringInterpreterEnum converts static (non-EL) tag attribute values
    into enum constant references in generated JSP Java source. It
    referenced the enum type by Class.getName(), which for a nested enum
    returns the binary name with '$' separators, e.g.
    com.example.Tags$Status, so a static attribute value for a setter
    taking a nested enum type made the generated JSP class fail to compile
    on first request.
    
    Use getCanonicalName() instead, matching the dot-separated name the
    DefaultStringInterpreter fallback already uses.
    
    Found by code review.
---
 .../optimizations/StringInterpreterEnum.java       |  5 +++-
 .../optimizations/TestStringInterpreterEnum.java   | 20 +++++++++++++++
 .../TestStringInterpreterTagSetters.java           |  6 +++++
 test/webapp/bug6nnnn/bug64872b-nested-timeunit.jsp | 29 ++++++++++++++++++++++
 4 files changed, 59 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/optimizations/StringInterpreterEnum.java b/java/org/apache/jasper/optimizations/StringInterpreterEnum.java
index ff52b6b1ac..8c21ede54f 100644
--- a/java/org/apache/jasper/optimizations/StringInterpreterEnum.java
+++ b/java/org/apache/jasper/optimizations/StringInterpreterEnum.java
@@ -42,7 +42,10 @@ public class StringInterpreterEnum extends DefaultStringInterpreter {
             try {
                 @SuppressWarnings({ "unchecked", "rawtypes" })
                 Enum<?> enumValue = Enum.valueOf((Class<? extends Enum>) c, s);
-                return c.getName() + "." + enumValue.name();
+                // The canonical name (dot-separated) must be used here. The
+                // binary name returned by getName() contains '$' separators
+                // for nested types and is not valid Java source.
+                return c.getCanonicalName() + "." + enumValue.name();
             } catch (IllegalArgumentException iae) {
                 if (log.isDebugEnabled()) {
                     log.debug(Localizer.getMessage("jsp.error.typeConversion", s, "Enum[" + c.getName() + "]"), iae);
diff --git a/test/org/apache/jasper/optimizations/TestStringInterpreterEnum.java b/test/org/apache/jasper/optimizations/TestStringInterpreterEnum.java
index b22cd36581..459e7c81fe 100644
--- a/test/org/apache/jasper/optimizations/TestStringInterpreterEnum.java
+++ b/test/org/apache/jasper/optimizations/TestStringInterpreterEnum.java
@@ -18,6 +18,7 @@ package org.apache.jasper.optimizations;
 
 import java.util.concurrent.TimeUnit;
 
+import org.junit.Assert;
 import org.junit.Test;
 
 public class TestStringInterpreterEnum {
@@ -30,6 +31,15 @@ public class TestStringInterpreterEnum {
     }
 
 
+    /*
+     * Enum nested in a class so the binary name differs from the canonical
+     * name by a '$' separator.
+     */
+    public enum NestedEnum {
+        VALUE
+    }
+
+
     @Test
     public void testBadTerms() {
         String[] badTerms = new String[] { "", "mis format", "fudge", ";", ".", "\"", " " };
@@ -37,4 +47,14 @@ public class TestStringInterpreterEnum {
             new TestInterpreter().evaluate(TimeUnit.class, badTerm);
         }
     }
+
+
+    @Test
+    public void testNestedEnumUsesCanonicalName() {
+        // The generated code must reference the canonical name (dot
+        // separated). The binary name contains '$' and is not valid Java
+        // source.
+        String result = new TestInterpreter().evaluate(NestedEnum.class, "VALUE");
+        Assert.assertEquals(NestedEnum.class.getCanonicalName() + ".VALUE", result);
+    }
 }
\ No newline at end of file
diff --git a/test/org/apache/jasper/optimizations/TestStringInterpreterTagSetters.java b/test/org/apache/jasper/optimizations/TestStringInterpreterTagSetters.java
index ca6db5864e..fca4d3560f 100644
--- a/test/org/apache/jasper/optimizations/TestStringInterpreterTagSetters.java
+++ b/test/org/apache/jasper/optimizations/TestStringInterpreterTagSetters.java
@@ -73,6 +73,12 @@ public class TestStringInterpreterTagSetters extends TomcatBaseTest {
         String actual = bc.toString();
 
         Assert.assertTrue(actual, actual.contains("01 The value of foo is [SECONDS]"));
+
+        bc = getUrl("http://localhost:" + getPort() + "/test/bug6nnnn/bug64872b-nested-timeunit.jsp");
+
+        actual = bc.toString();
+
+        Assert.assertTrue(actual, actual.contains("01 The value of foo is [SECONDS]"));
     }
 
 
diff --git a/test/webapp/bug6nnnn/bug64872b-nested-timeunit.jsp b/test/webapp/bug6nnnn/bug64872b-nested-timeunit.jsp
new file mode 100644
index 0000000000..3f0bc21baf
--- /dev/null
+++ b/test/webapp/bug6nnnn/bug64872b-nested-timeunit.jsp
@@ -0,0 +1,29 @@
+<%--
+ 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.
+--%>
+<%@ taglib uri="http://tomcat.apache.org/tag-setters" prefix="ts" %>
+<html>
+  <head><title>Bug 64872b nested enum test case</title></head>
+  <body>
+  <%
+  for (int i=0; i < 5000; i++) {
+  %>
+    <p>01 The value of foo is [<ts:tagNestedTimeUnit foo="SECONDS" />]</p>
+  <%
+  }
+  %>
+  </body>
+</html>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 27/46: Record JSP usage time on every request, fixing premature idle unload

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit fa2825827f3d0c630acc361eeb349970820d63a5
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 12:04:57 2026 +0200

    Record JSP usage time on every request, fixing premature idle unload
    
    JspServletWrapper.service() only advanced the wrapper's lastUsageTime
    when it was older than the timestamp of the previous background
    checkUnload() run, a gate introduced to limit jspQueue re-ordering to
    a single move per background cycle. When the jspIdleTimeout feature
    was added it reused the same gate for lastUsageTime, so the timestamp
    of an actively requested JSP advanced at most once per background
    processor cycle (default 10s). With jspIdleTimeout shorter than that
    cycle, JspRuntimeContext.checkUnload() saw continuously used JSPs as
    idle and unloaded them repeatedly, forcing needless recompilation and
    class loader churn; the LRU queue ordering was likewise stale by up to
    one cycle.
    
    Keep the once-per-cycle throttle for the makeYoungest() queue
    re-ordering, which was its original purpose (commit ee86d455a5), but
    record lastUsageTime unconditionally inside the already held wrapper
    lock, so the idle timeout check always sees the true last usage.
    
    Found by code review.
---
 java/org/apache/jasper/servlet/JspServletWrapper.java | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/java/org/apache/jasper/servlet/JspServletWrapper.java b/java/org/apache/jasper/servlet/JspServletWrapper.java
index 90d5cdfdc5..30a3f57d9a 100644
--- a/java/org/apache/jasper/servlet/JspServletWrapper.java
+++ b/java/org/apache/jasper/servlet/JspServletWrapper.java
@@ -483,14 +483,15 @@ public class JspServletWrapper {
                         if (unloadHandle == null) {
                             unloadHandle = ctxt.getRuntimeContext().push(this);
                         } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
+                            // Limit queue re-ordering to a single move per
+                            // background checkUnload() cycle.
                             ctxt.getRuntimeContext().makeYoungest(unloadHandle);
-                            lastUsageTime = System.currentTimeMillis();
-                        }
-                    } else {
-                        if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
-                            lastUsageTime = System.currentTimeMillis();
                         }
                     }
+                    // Always record the usage time, so an actively used JSP is
+                    // never seen as idle by checkUnload(), independent of how
+                    // often the queue order above was updated.
+                    lastUsageTime = System.currentTimeMillis();
                 }
             }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 44/46: Build UniqueAttributesImpl.setAttributes() from the incoming set

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit d5ea224b930f4dfbde012d4102feb163272a791a
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 17:11:12 2026 +0200

    Build UniqueAttributesImpl.setAttributes() from the incoming set
    
    setAttributes() validated the incoming attributes against the store
    they were about to replace and never reset the duplicate tracking set.
    A repeated import on a page directive was merged into an attribute of
    the old store that was immediately discarded, or threw an
    ArrayIndexOutOfBoundsException when that store held no import yet; a
    duplicate tolerated by the page directive rules was copied into the
    store verbatim; and names from the replaced attributes stayed behind in
    the tracking set, where they were later reported as false duplicates.
    
    Build the replacement store and the tracking set from the incoming
    attributes alone, so the duplicate rules act on each other's results,
    and install them only once the whole set validates, leaving the
    instance untouched when a duplicate is rejected. Generalise
    handleDuplicate() to take the store it acts on; the delegating
    overload preserves the behaviour of the addAttribute(), setAttribute()
    and setQName() paths.
    
    Extend TestUniqueAttributesImpl with the replacement cases.
    
    Found by code review.
---
 .../apache/jasper/util/UniqueAttributesImpl.java   |  32 +++--
 .../jasper/util/TestUniqueAttributesImpl.java      | 132 +++++++++++++++++++++
 2 files changed, 157 insertions(+), 7 deletions(-)

diff --git a/java/org/apache/jasper/util/UniqueAttributesImpl.java b/java/org/apache/jasper/util/UniqueAttributesImpl.java
index e36268417d..174a94a819 100644
--- a/java/org/apache/jasper/util/UniqueAttributesImpl.java
+++ b/java/org/apache/jasper/util/UniqueAttributesImpl.java
@@ -59,12 +59,26 @@ public class UniqueAttributesImpl extends AttributesImpl {
 
     @Override
     public void setAttributes(Attributes atts) {
+        // Build the replacement store separately so that the incoming
+        // attributes are validated and merged against each other rather than
+        // against the attributes being replaced, and so that a rejected
+        // duplicate leaves this instance untouched
+        AttributesImpl merged = new AttributesImpl();
+        Set<String> names = new HashSet<>();
         for (int i = 0; i < atts.getLength(); i++) {
-            if (!qNames.add(atts.getQName(i))) {
-                handleDuplicate(atts.getQName(i), atts.getValue(i));
+            String qName = atts.getQName(i);
+            String value = atts.getValue(i);
+            if (names.add(qName)) {
+                merged.addAttribute(atts.getURI(i), atts.getLocalName(i), qName,
+                        atts.getType(i), value);
+            } else {
+                handleDuplicate(qName, value, merged);
             }
         }
-        super.setAttributes(atts);
+
+        super.setAttributes(merged);
+        qNames.clear();
+        qNames.addAll(names);
     }
 
     @Override
@@ -113,12 +127,16 @@ public class UniqueAttributesImpl extends AttributesImpl {
     }
 
     private void handleDuplicate(String qName, String value) {
+        handleDuplicate(qName, value, this);
+    }
+
+    private void handleDuplicate(String qName, String value, AttributesImpl store) {
         if (pageDirective) {
             if (IMPORT.equalsIgnoreCase(qName)) {
                 // Always merge imports
-                int i = super.getIndex(IMPORT);
-                String v = super.getValue(i);
-                super.setValue(i, v + "," + value);
+                int i = store.getIndex(IMPORT);
+                String v = store.getValue(i);
+                store.setValue(i, v + "," + value);
                 return;
             } else if (PAGE_ENCODING.equalsIgnoreCase(qName)) {
                 // Page encoding can only occur once per file so a second
@@ -126,7 +144,7 @@ public class UniqueAttributesImpl extends AttributesImpl {
             } else {
                 // Other attributes can be repeated if and only if the values
                 // are identical
-                String v = super.getValue(qName);
+                String v = store.getValue(qName);
                 if (v.equals(value)) {
                     return;
                 }
diff --git a/test/org/apache/jasper/util/TestUniqueAttributesImpl.java b/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
index 68b2810e2c..ea46f43d1b 100644
--- a/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
+++ b/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
@@ -19,6 +19,9 @@ package org.apache.jasper.util;
 import org.junit.Assert;
 import org.junit.Test;
 
+import org.xml.sax.Attributes;
+import org.xml.sax.helpers.AttributesImpl;
+
 
 public class TestUniqueAttributesImpl {
 
@@ -29,6 +32,15 @@ public class TestUniqueAttributesImpl {
         return attrs;
     }
 
+    private static Attributes attributes(String... nameValuePairs) {
+        AttributesImpl atts = new AttributesImpl();
+        for (int i = 0; i < nameValuePairs.length; i += 2) {
+            atts.addAttribute("", nameValuePairs[i], nameValuePairs[i], "CDATA",
+                    nameValuePairs[i + 1]);
+        }
+        return atts;
+    }
+
 
     /*
      * Renaming an attribute to a new name must register that name, so a
@@ -117,4 +129,124 @@ public class TestUniqueAttributesImpl {
             // expected
         }
     }
+
+
+    /*
+     * Replacing the attributes must reset the duplicate tracking, so names
+     * from the replaced attributes are no longer reported as duplicates and
+     * names of the new attributes are.
+     */
+    @Test
+    public void testSetAttributesResetsTracking() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        attrs.setAttributes(attributes("x", "3", "y", "4"));
+
+        Assert.assertEquals(2, attrs.getLength());
+        Assert.assertEquals("x", attrs.getQName(0));
+
+        // The replaced attributes' names must no longer be tracked
+        attrs.addAttribute("", "a", "a", "CDATA", "5");
+
+        // The new attributes' names must be tracked
+        try {
+            attrs.addAttribute("", "x", "x", "CDATA", "6");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+
+    /*
+     * The incoming set must be validated against itself, not against the
+     * attributes being replaced, so a name held by a replaced attribute may
+     * be reused with any value.
+     */
+    @Test
+    public void testSetAttributesReplacesHeldName() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        attrs.setAttributes(attributes("a", "9"));
+
+        Assert.assertEquals(1, attrs.getLength());
+        Assert.assertEquals("9", attrs.getValue("a"));
+    }
+
+
+    /*
+     * Replacing the attributes with a set containing a rejected duplicate
+     * must leave both the attributes and the tracking untouched.
+     */
+    @Test
+    public void testSetAttributesRejectedDuplicateLeavesStateUntouched() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        try {
+            attrs.setAttributes(attributes("m", "3", "m", "4"));
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+
+        Assert.assertEquals(2, attrs.getLength());
+        Assert.assertEquals("a", attrs.getQName(0));
+
+        // The rejected set's names must not have been left behind in the
+        // tracking either
+        attrs.addAttribute("", "m", "m", "CDATA", "5");
+        Assert.assertEquals(3, attrs.getLength());
+
+        try {
+            attrs.addAttribute("", "a", "a", "CDATA", "6");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+
+    /*
+     * On a page directive, repeated import attributes in the incoming set
+     * must be merged into a single attribute.
+     */
+    @Test
+    public void testSetAttributesMergesImports() throws Exception {
+        UniqueAttributesImpl attrs = new UniqueAttributesImpl(true);
+
+        attrs.setAttributes(attributes("import", "a", "import", "b",
+                "contentType", "text/html"));
+
+        Assert.assertEquals(2, attrs.getLength());
+        Assert.assertEquals("a,b", attrs.getValue("import"));
+
+        // A later import still merges
+        attrs.addAttribute("", "import", "import", "CDATA", "c");
+        Assert.assertEquals("a,b,c", attrs.getValue("import"));
+    }
+
+
+    /*
+     * On a page directive, an attribute in the incoming set repeated with an
+     * identical value must be tolerated without storing the duplicate, while
+     * a repeated pageEncoding must be rejected even with an identical value.
+     */
+    @Test
+    public void testSetAttributesPageDirectiveRules() throws Exception {
+        UniqueAttributesImpl attrs = new UniqueAttributesImpl(true);
+
+        attrs.setAttributes(attributes("foo", "1", "foo", "1"));
+        Assert.assertEquals(1, attrs.getLength());
+
+        try {
+            attrs.setAttributes(attributes("pageEncoding", "UTF-8",
+                    "pageEncoding", "UTF-8"));
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+        // The rejected set left the previous attributes in place
+        Assert.assertEquals(1, attrs.getLength());
+        Assert.assertEquals("1", attrs.getValue("foo"));
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 09/46: Avoid NullPointerException in include error path for non-JAR pages

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit f9393219dec8b639f349d84d0af7dc49ba67aac2
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 22:27:17 2026 +0200

    Avoid NullPointerException in include error path for non-JAR pages
    
    When ParserController.doParse() failed to resolve the name of a file
    included using an include directive, the error handling assumed that the
    page was being read from a JAR. For a page read from the file system the
    "jar" argument is null, so evaluating the error message threw a
    NullPointerException.
    
    That exception was then caught by Parser.processIncludeDirective() which
    re-dispatched its message, so compiling a page such as one containing
    
        <%@ include file="a b.jsp" %>
    
    reported the details of the NullPointerException, or nothing at all on
    older JDKs, instead of a translation error describing the problem with
    the include.
    
    Report the invalid include via a dedicated message that does not depend
    on the page being read from a JAR. This also removes an incorrect
    report of an include escaping /META-INF/tags for any include with an
    invalid URI that did happen to be read from a JAR.
    
    Found by code review.
---
 .../apache/jasper/compiler/ParserController.java   |  3 +-
 .../jasper/resources/LocalStrings.properties       |  1 +
 .../jasper/compiler/TestParserController.java      | 43 ++++++++++++++++++++++
 test/webapp/jsp/parsing/include-invalid-uri.jsp    | 24 ++++++++++++
 4 files changed, 70 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/compiler/ParserController.java b/java/org/apache/jasper/compiler/ParserController.java
index 1629af24f4..7dbe122479 100644
--- a/java/org/apache/jasper/compiler/ParserController.java
+++ b/java/org/apache/jasper/compiler/ParserController.java
@@ -198,7 +198,8 @@ public class ParserController implements TagConstants {
         try {
             absFileName = resolveFileName(inFileName);
         } catch (URISyntaxException e) {
-            err.jspError("jsp.error.invalid.includeInTagFileJar", inFileName, jar.getJarFileURL().toString());
+            // Note: jar may be null here, so avoid referencing it
+            err.jspError("jsp.error.invalid.include", inFileName);
         }
         if (processingTagInJar && !absFileName.startsWith(TAGS_IN_JAR_LOCATION)) {
             /*
diff --git a/java/org/apache/jasper/resources/LocalStrings.properties b/java/org/apache/jasper/resources/LocalStrings.properties
index 4943ca1dfa..d533c92542 100644
--- a/java/org/apache/jasper/resources/LocalStrings.properties
+++ b/java/org/apache/jasper/resources/LocalStrings.properties
@@ -94,6 +94,7 @@ jsp.error.invalid.directive=Invalid directive
 jsp.error.invalid.expression=[{0}] contains invalid expression(s): [{1}]
 jsp.error.invalid.implicit=Invalid implicit TLD for tag file at [{0}]
 jsp.error.invalid.implicit.version=Invalid JSP version defined in implicit TLD for tag file at [{0}]
+jsp.error.invalid.include=The include [{0}] is invalid as it cannot be resolved to a valid URI
 jsp.error.invalid.includeInTagFileJar=The include [{0}] is not valid since it is outside of /META-INF/tags in the current JAR
 jsp.error.invalid.name=File [{0}] uses name [{1}] in jsp:getProperty for a bean that was not previously introduced as per JSP.5.3
 jsp.error.invalid.scope=Illegal value of ''scope'' attribute: [{0}] (must be one of "page", "request", "session", or "application")
diff --git a/test/org/apache/jasper/compiler/TestParserController.java b/test/org/apache/jasper/compiler/TestParserController.java
new file mode 100644
index 0000000000..51594b2512
--- /dev/null
+++ b/test/org/apache/jasper/compiler/TestParserController.java
@@ -0,0 +1,43 @@
+/*
+ * 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.jasper.compiler;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestParserController extends TomcatBaseTest {
+
+    @Test
+    public void testIncludeInvalidUri() throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk res = new ByteChunk();
+        int sc = getUrl("http://localhost:" + getPort() + "/test/jsp/parsing/include-invalid-uri.jsp", res, null);
+
+        Assert.assertEquals(500, sc);
+
+        // The report should include the translation error for the invalid
+        // include. The error handling code previously threw a
+        // NullPointerException itself which was reported instead.
+        String result = res.toString();
+        Assert.assertTrue(result, result.contains("The include [a b.jsp] is invalid"));
+        Assert.assertFalse(result, result.contains("Cannot invoke"));
+    }
+}
diff --git a/test/webapp/jsp/parsing/include-invalid-uri.jsp b/test/webapp/jsp/parsing/include-invalid-uri.jsp
new file mode 100644
index 0000000000..62cb5bf970
--- /dev/null
+++ b/test/webapp/jsp/parsing/include-invalid-uri.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page contentType="text/html;charset=UTF-8" %>
+<%@ include file="a b.jsp" %>
+<html>
+  <head><title>Include with an invalid URI test case</title></head>
+  <body>
+    <p>Should fail</p>
+  </body>
+</html>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 30/46: Avoid StringIndexOutOfBoundsException on an empty content-type parameter

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 553a8633b8ca0d0e67be993776b517538885b59a
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 12:30:48 2026 +0200

    Avoid StringIndexOutOfBoundsException on an empty content-type parameter
    
    getContentTypeAttribute() positioned itself after the '=' of the
    requested attribute, trimmed the remainder and then unconditionally
    tested charAt(0). A parameter value that was empty or contained only
    whitespace, for example the malformed but plausible "Content-Type:
    text/html;charset=" header a remote server could return for a
    <c:import> of an absolute URL, produced an empty string here and the
    charAt(0) call threw a StringIndexOutOfBoundsException that propagated
    out of the generated tag plugin code as a raw runtime exception.
    
    Return null for an empty value instead, matching the existing contract
    for an attribute that is not present, so the callers in the Import tag
    plugin fall back to the default encoding.
    
    Found by code review.
---
 java/org/apache/jasper/tagplugins/jstl/Util.java | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/java/org/apache/jasper/tagplugins/jstl/Util.java b/java/org/apache/jasper/tagplugins/jstl/Util.java
index 9c6faa2e77..a57dfe823e 100644
--- a/java/org/apache/jasper/tagplugins/jstl/Util.java
+++ b/java/org/apache/jasper/tagplugins/jstl/Util.java
@@ -140,6 +140,11 @@ public class Util {
         }
         index += 1; // positioned after the '='
         input = input.substring(index).trim();
+        if (input.isEmpty()) {
+            // Empty or whitespace-only parameter value, e.g. a malformed
+            // "Content-Type: text/html;charset=" header from a remote server.
+            return null;
+        }
 
         if (input.charAt(0) == '"') {
             // attribute value is a quoted string


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 32/46: Validate begin, end and step in the ForEach and ForTokens tag plugins

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 9b1f916e3fcdc66c1491a53c876d97336479b04c
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 13:35:11 2026 +0200

    Validate begin, end and step in the ForEach and ForTokens tag plugins
    
    The reference implementation validates these three attributes in their
    setters, throwing a JspTagException with the message "'begin' < 0",
    "'end' < 0" or "'step' <= 0" when the corresponding attribute is
    specified. The tag plugins generated no validation at all: a numeric
    c:forEach with step="0" generated a for loop with a zero increment,
    hanging the request thread indefinitely, a negative step looped
    forever, negative begin and end values were silently accepted, and
    c:forTokens with step="0" failed mid-loop with an
    ArithmeticException instead of a tag error.
    
    Evaluate the loop control attributes once, as the reference does, and
    emit the equivalent throw checks for the specified attributes. In
    numeric mode this also corrects two related deviations: end and step
    were previously re-evaluated on every iteration, and an unspecified
    begin or end produced uncompilable generated code, since no Java
    source is emitted for an absent attribute. These now default to 0 and
    -1, matching the reference and producing zero iterations when end is
    absent.
    
    Add tests using c:catch to pin the exception type and message of the
    generated checks.
    
    Found by code review.
---
 .../jasper/tagplugins/jstl/core/ForEach.java       | 58 +++++++++++++++++++---
 .../jasper/tagplugins/jstl/core/ForTokens.java     | 19 ++++---
 .../jasper/tagplugins/jstl/core/TestForEach.java   | 37 ++++++++++++++
 .../jasper/tagplugins/jstl/core/TestForTokens.java | 58 ++++++++++++++++++++++
 test/webapp/jstl/foreach-begin-negative.jsp        | 21 ++++++++
 test/webapp/jstl/foreach-end-negative.jsp          | 22 ++++++++
 test/webapp/jstl/foreach-step-zero.jsp             | 21 ++++++++
 test/webapp/jstl/fortokens-begin-negative.jsp      | 21 ++++++++
 test/webapp/jstl/fortokens-step-zero.jsp           | 21 ++++++++
 9 files changed, 262 insertions(+), 16 deletions(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java b/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
index 89a162e340..e69446a0f2 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
@@ -54,18 +54,54 @@ public final class ForEach implements TagPlugin {
             return;
         }
 
-        // We must have a begin and end attributes
+        // We must have begin and end attributes. Evaluate the loop control
+        // attributes once and validate them, as the setters of the reference
+        // implementation LoopTagSupport do.
         index = ctxt.getTemporaryVariableName();
-        ctxt.generateJavaSource("for (int " + index + " = ");
-        ctxt.generateAttribute("begin");
-        ctxt.generateJavaSource("; " + index + " <= ");
-        ctxt.generateAttribute("end");
+
+        String beginName = ctxt.getTemporaryVariableName();
+        ctxt.generateJavaSource("int " + beginName + " = ");
+        if (hasBegin) {
+            ctxt.generateAttribute("begin");
+        } else {
+            ctxt.generateJavaSource("0");
+        }
+        ctxt.generateJavaSource(";");
+        if (hasBegin) {
+            ctxt.generateJavaSource("if (" + beginName + " < 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'begin' < 0\");}");
+        }
+
+        String endName = ctxt.getTemporaryVariableName();
+        ctxt.generateJavaSource("int " + endName + " = ");
+        if (hasEnd) {
+            ctxt.generateAttribute("end");
+        } else {
+            // Same default as the reference implementation, which results in
+            // zero iterations when end is not specified.
+            ctxt.generateJavaSource("-1");
+        }
+        ctxt.generateJavaSource(";");
+        if (hasEnd) {
+            ctxt.generateJavaSource("if (" + endName + " < 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'end' < 0\");}");
+        }
+
+        String stepName = null;
         if (hasStep) {
-            ctxt.generateJavaSource("; " + index + "+=");
+            stepName = ctxt.getTemporaryVariableName();
+            ctxt.generateJavaSource("int " + stepName + " = ");
             ctxt.generateAttribute("step");
-            ctxt.generateJavaSource(") {");
+            ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + stepName + " <= 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'step' <= 0\");}");
+        }
+
+        ctxt.generateJavaSource("for (int " + index + " = " + beginName + "; " + index + " <= " + endName + ";");
+        if (hasStep) {
+            ctxt.generateJavaSource(" " + index + " += " + stepName + ") {");
         } else {
-            ctxt.generateJavaSource("; " + index + "++) {");
+            ctxt.generateJavaSource(" " + index + "++) {");
         }
 
         // If var is specified, sync the var attribute
@@ -98,6 +134,8 @@ public final class ForEach implements TagPlugin {
             ctxt.generateJavaSource("int " + beginV + " = ");
             ctxt.generateAttribute("begin");
             ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + beginV + " < 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'begin' < 0\");}");
         }
         if (hasEnd) {
             indexV = ctxt.getTemporaryVariableName();
@@ -106,12 +144,16 @@ public final class ForEach implements TagPlugin {
             ctxt.generateJavaSource("int " + endV + " = ");
             ctxt.generateAttribute("end");
             ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + endV + " < 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'end' < 0\");}");
         }
         if (hasStep) {
             stepV = ctxt.getTemporaryVariableName();
             ctxt.generateJavaSource("int " + stepV + " = ");
             ctxt.generateAttribute("step");
             ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + stepV + " <= 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'step' <= 0\");}");
         }
 
         String iterV = ctxt.getTemporaryVariableName();
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/ForTokens.java b/java/org/apache/jasper/tagplugins/jstl/core/ForTokens.java
index 8ae2858edb..05cd8f8156 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/ForTokens.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/ForTokens.java
@@ -78,6 +78,8 @@ public class ForTokens implements TagPlugin {
             ctxt.generateJavaSource("int " + beginName + " = ");
             ctxt.generateAttribute("begin");
             ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + beginName + " < 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'begin' < 0\");}");
             ctxt.generateJavaSource("for(int " + index + " = 0; " + index + " < " + beginName + " && " + stName +
                     ".hasMoreTokens(); " + index + "++, " + stName + ".nextToken()){}");
         } else {
@@ -88,15 +90,14 @@ public class ForTokens implements TagPlugin {
         // record the end place as the last index, otherwise, record it as "end";
         // default end place is the last index
         if (hasEnd) {
-            ctxt.generateJavaSource("int " + endName + " = 0;");
-            ctxt.generateJavaSource("if((" + tokensCountName + " - 1) < ");
+            String endSpecifiedName = ctxt.getTemporaryVariableName();
+            ctxt.generateJavaSource("int " + endSpecifiedName + " = ");
             ctxt.generateAttribute("end");
-            ctxt.generateJavaSource("){");
-            ctxt.generateJavaSource("    " + endName + " = " + tokensCountName + " - 1;");
-            ctxt.generateJavaSource("}else{");
-            ctxt.generateJavaSource("    " + endName + " = ");
-            ctxt.generateAttribute("end");
-            ctxt.generateJavaSource(";}");
+            ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + endSpecifiedName + " < 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'end' < 0\");}");
+            ctxt.generateJavaSource("int " + endName + " = (" + tokensCountName + " - 1) < " + endSpecifiedName +
+                    " ? " + tokensCountName + " - 1 : " + endSpecifiedName + ";");
         } else {
             ctxt.generateJavaSource("int " + endName + " = " + tokensCountName + " - 1;");
         }
@@ -107,6 +108,8 @@ public class ForTokens implements TagPlugin {
             ctxt.generateJavaSource("int " + stepName + " = ");
             ctxt.generateAttribute("step");
             ctxt.generateJavaSource(";");
+            ctxt.generateJavaSource("if (" + stepName + " <= 0) {" +
+                    "throw new jakarta.servlet.jsp.JspTagException(\"'step' <= 0\");}");
         } else {
             ctxt.generateJavaSource("int " + stepName + " = 1;");
         }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java b/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
index 869961163b..50905ff2cb 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
@@ -72,4 +72,41 @@ public class TestForEach extends AbstractTestTag {
         Assert.assertEquals(2, body.split("java\\.lang\\.Integer", -1).length - 1);
         Assert.assertFalse(body, body.contains("java.lang.String"));
     }
+
+
+    /*
+     * The reference implementation validates the begin, end and step
+     * attributes in their setters, throwing a JspTagException. The plugin
+     * must generate the equivalent checks rather than, for example, looping
+     * forever on step="0". The pages wrap the tag in c:catch and render the
+     * caught exception, pinning the reference exception type and message.
+     */
+    @Test
+    public void testStepZero() throws Exception {
+        doTestInvalidAttribute("foreach-step-zero.jsp", "'step' <= 0");
+    }
+
+
+    @Test
+    public void testBeginNegative() throws Exception {
+        doTestInvalidAttribute("foreach-begin-negative.jsp", "'begin' < 0");
+    }
+
+
+    @Test
+    public void testEndNegative() throws Exception {
+        doTestInvalidAttribute("foreach-end-negative.jsp", "'end' < 0");
+    }
+
+
+    private void doTestInvalidAttribute(String jsp, String message) throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/" + jsp, res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+        Assert.assertTrue(res.toString(), res.toString()
+                .contains("jakarta.servlet.jsp.JspTagException: " + message));
+    }
 }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestForTokens.java b/test/org/apache/jasper/tagplugins/jstl/core/TestForTokens.java
new file mode 100644
index 0000000000..7c1aa63e44
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestForTokens.java
@@ -0,0 +1,58 @@
+/*
+ * 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.jasper.tagplugins.jstl.core;
+
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestForTokens extends AbstractTestTag {
+
+    /*
+     * The reference implementation validates the begin, end and step
+     * attributes in their setters, throwing a JspTagException. The plugin
+     * must generate the equivalent checks rather than, for example, failing
+     * with an ArithmeticException on step="0". The pages wrap the tag in
+     * c:catch and render the caught exception, pinning the reference
+     * exception type and message.
+     */
+    @Test
+    public void testStepZero() throws Exception {
+        doTestInvalidAttribute("fortokens-step-zero.jsp", "'step' <= 0");
+    }
+
+
+    @Test
+    public void testBeginNegative() throws Exception {
+        doTestInvalidAttribute("fortokens-begin-negative.jsp", "'begin' < 0");
+    }
+
+
+    private void doTestInvalidAttribute(String jsp, String message) throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/" + jsp, res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+        Assert.assertTrue(res.toString(), res.toString()
+                .contains("jakarta.servlet.jsp.JspTagException: " + message));
+    }
+}
diff --git a/test/webapp/jstl/foreach-begin-negative.jsp b/test/webapp/jstl/foreach-begin-negative.jsp
new file mode 100644
index 0000000000..88dbcdf4c9
--- /dev/null
+++ b/test/webapp/jstl/foreach-begin-negative.jsp
@@ -0,0 +1,21 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forEach begin="-1" end="10" var="i">Should not be reached</c:forEach></c:catch>
+<p>error=${err}</p>
diff --git a/test/webapp/jstl/foreach-end-negative.jsp b/test/webapp/jstl/foreach-end-negative.jsp
new file mode 100644
index 0000000000..123db53581
--- /dev/null
+++ b/test/webapp/jstl/foreach-end-negative.jsp
@@ -0,0 +1,22 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forEach items="${['a','b']}" begin="0" end="-1"
+    var="i">Should not be reached</c:forEach></c:catch>
+<p>error=${err}</p>
diff --git a/test/webapp/jstl/foreach-step-zero.jsp b/test/webapp/jstl/foreach-step-zero.jsp
new file mode 100644
index 0000000000..753bbead87
--- /dev/null
+++ b/test/webapp/jstl/foreach-step-zero.jsp
@@ -0,0 +1,21 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forEach begin="0" end="10" step="0" var="i">Should not be reached</c:forEach></c:catch>
+<p>error=${err}</p>
diff --git a/test/webapp/jstl/fortokens-begin-negative.jsp b/test/webapp/jstl/fortokens-begin-negative.jsp
new file mode 100644
index 0000000000..837e378fd9
--- /dev/null
+++ b/test/webapp/jstl/fortokens-begin-negative.jsp
@@ -0,0 +1,21 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forTokens items="a,b,c" delims="," begin="-1" var="t">Should not be reached</c:forTokens></c:catch>
+<p>error=${err}</p>
diff --git a/test/webapp/jstl/fortokens-step-zero.jsp b/test/webapp/jstl/fortokens-step-zero.jsp
new file mode 100644
index 0000000000..02d6f20485
--- /dev/null
+++ b/test/webapp/jstl/fortokens-step-zero.jsp
@@ -0,0 +1,21 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forTokens items="a,b,c" delims="," step="0" var="t">Should not be reached</c:forTokens></c:catch>
+<p>error=${err}</p>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 31/46: Expose the ForEach tag plugin loop variable as an Integer

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 06acd5918f3cd3c320a628e17687bf63252fa6c6
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 13:06:55 2026 +0200

    Expose the ForEach tag plugin loop variable as an Integer
    
    In numeric range mode, the ForEach tag plugin generated
    _jspx_page_context.setAttribute(var, String.valueOf(index)), so the
    loop variable was published as a String. The reference JSTL
    implementation, LoopTagSupport's ToEndIterator, boxes the index with
    Integer.valueOf and therefore publishes an Integer. EL type coercion
    hides the difference for plain output, but type sensitive expressions
    (method arguments, getClass checks, operand-type dependent comparisons)
    and any consumer of the scoped variable behave differently than under
    the reference implementation.
    
    Box the generated index with Integer.valueOf, matching the reference
    implementation. Add a test page and a test asserting the published
    type when the plugin is active.
    
    Found by code review.
---
 .../apache/jasper/tagplugins/jstl/core/ForEach.java  |  3 ++-
 .../jasper/tagplugins/jstl/core/TestForEach.java     | 17 +++++++++++++++++
 test/webapp/jstl/foreach-numeric-var.jsp             | 20 ++++++++++++++++++++
 3 files changed, 39 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java b/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
index 66b8ff6304..89a162e340 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
@@ -72,7 +72,8 @@ public final class ForEach implements TagPlugin {
         if (hasVar /* && ctxt.hasEL() */) {
             ctxt.generateJavaSource("_jspx_page_context.setAttribute(");
             ctxt.generateAttribute("var");
-            ctxt.generateJavaSource(", String.valueOf(" + index + "));");
+            // The reference implementation exposes the index as an Integer.
+            ctxt.generateJavaSource(", Integer.valueOf(" + index + "));");
         }
         ctxt.generateBody();
         ctxt.generateJavaSource("}");
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java b/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
index e9acb94774..869961163b 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
@@ -55,4 +55,21 @@ public class TestForEach extends AbstractTestTag {
         Assert.assertTrue(body.contains("OK - 2"));
         Assert.assertTrue(body.contains("OK - 3"));
     }
+
+
+    @Test
+    public void testNumericRangeVarType() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/foreach-numeric-var.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        // The reference implementation exposes the loop variable as an
+        // Integer, not a String.
+        String body = res.toString();
+        Assert.assertEquals(2, body.split("java\\.lang\\.Integer", -1).length - 1);
+        Assert.assertFalse(body, body.contains("java.lang.String"));
+    }
 }
diff --git a/test/webapp/jstl/foreach-numeric-var.jsp b/test/webapp/jstl/foreach-numeric-var.jsp
new file mode 100644
index 0000000000..9ae6444b9e
--- /dev/null
+++ b/test/webapp/jstl/foreach-numeric-var.jsp
@@ -0,0 +1,20 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:forEach begin="1" end="2" var="i"><p><%= pageContext.getAttribute("i").getClass().getName() %></p></c:forEach>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 43/46: Keep UniqueAttributesImpl tracking in step with its attributes

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 511586603b03b219ba5b9e628162677a54c99454
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 17:04:45 2026 +0200

    Keep UniqueAttributesImpl tracking in step with its attributes
    
    setQName() removed the attribute's old name from the duplicate
    tracking set but never added the new one, so after a rename the new
    name was no longer detected as a duplicate and the old name was
    forgotten even though the rename could still be rejected later.
    setAttribute(int,...) lost the old name the same way whenever a
    rejected or tolerated duplicate left the attribute unchanged.
    
    Rename the tracking entry alongside the attribute, and restore the
    old name before consulting handleDuplicate() so the tracking stays
    consistent whether the duplicate is tolerated or rejected with an
    exception.
    
    Add TestUniqueAttributesImpl covering the rename, rename-to-existing
    and replacement cases.
    
    Found by code review.
---
 .../apache/jasper/util/UniqueAttributesImpl.java   |  20 +++-
 .../jasper/util/TestUniqueAttributesImpl.java      | 120 +++++++++++++++++++++
 2 files changed, 137 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/jasper/util/UniqueAttributesImpl.java b/java/org/apache/jasper/util/UniqueAttributesImpl.java
index b7ba09e5c4..e36268417d 100644
--- a/java/org/apache/jasper/util/UniqueAttributesImpl.java
+++ b/java/org/apache/jasper/util/UniqueAttributesImpl.java
@@ -78,10 +78,15 @@ public class UniqueAttributesImpl extends AttributesImpl {
 
     @Override
     public void setAttribute(int index, String uri, String localName, String qName, String type, String value) {
-        qNames.remove(super.getQName(index));
+        String oldQName = super.getQName(index);
+        qNames.remove(oldQName);
         if (qNames.add(qName)) {
             super.setAttribute(index, uri, localName, qName, type, value);
         } else {
+            // A duplicate, whether it is tolerated by the rules below or
+            // rejected with an exception, leaves this attribute unchanged, so
+            // restore its name in the tracking set
+            qNames.add(oldQName);
             handleDuplicate(qName, value);
         }
     }
@@ -94,8 +99,17 @@ public class UniqueAttributesImpl extends AttributesImpl {
 
     @Override
     public void setQName(int index, String qName) {
-        qNames.remove(super.getQName(index));
-        super.setQName(index, qName);
+        String oldQName = super.getQName(index);
+        qNames.remove(oldQName);
+        if (qNames.add(qName)) {
+            super.setQName(index, qName);
+        } else {
+            // A duplicate, whether it is tolerated by the rules below or
+            // rejected with an exception, leaves this attribute unchanged, so
+            // restore its name in the tracking set
+            qNames.add(oldQName);
+            handleDuplicate(qName, super.getValue(index));
+        }
     }
 
     private void handleDuplicate(String qName, String value) {
diff --git a/test/org/apache/jasper/util/TestUniqueAttributesImpl.java b/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
new file mode 100644
index 0000000000..68b2810e2c
--- /dev/null
+++ b/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
@@ -0,0 +1,120 @@
+/*
+ * 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.jasper.util;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+
+public class TestUniqueAttributesImpl {
+
+    private static UniqueAttributesImpl createAttributes() {
+        UniqueAttributesImpl attrs = new UniqueAttributesImpl();
+        attrs.addAttribute("", "a", "a", "CDATA", "1");
+        attrs.addAttribute("", "b", "b", "CDATA", "2");
+        return attrs;
+    }
+
+
+    /*
+     * Renaming an attribute to a new name must register that name, so a
+     * later attribute of the same name is still detected as a duplicate.
+     * The method used to remove the old name without adding the new one,
+     * leaving the tracking set behind the attributes.
+     */
+    @Test
+    public void testSetQNameRegistersNewName() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        attrs.setQName(1, "c");
+        Assert.assertEquals("c", attrs.getQName(1));
+
+        try {
+            attrs.addAttribute("", "c", "c", "CDATA", "3");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+
+    /*
+     * Renaming an attribute to the name of another attribute must be
+     * rejected as a duplicate rather than renaming onto it.
+     */
+    @Test
+    public void testSetQNameToExistingNameRejected() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        try {
+            attrs.setQName(1, "a");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+        // The rejected rename left the attribute unchanged
+        Assert.assertEquals("b", attrs.getQName(1));
+    }
+
+
+    /*
+     * Renaming an attribute to the name it already has must not unregister
+     * the name from duplicate detection.
+     */
+    @Test
+    public void testSetQNameToSameName() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        attrs.setQName(0, "a");
+        Assert.assertEquals("a", attrs.getQName(0));
+
+        try {
+            attrs.addAttribute("", "a", "a", "CDATA", "3");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+
+    /*
+     * Replacing an attribute with a duplicate name must be rejected and must
+     * keep the tracking set in step with the attributes, so the replaced
+     * attribute's name is still detected as a duplicate afterwards.
+     */
+    @Test
+    public void testSetAttributeToExistingNameRejected() throws Exception {
+        UniqueAttributesImpl attrs = createAttributes();
+
+        try {
+            attrs.setAttribute(1, "", "a", "a", "CDATA", "3");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+        // The rejected replacement left the attribute unchanged
+        Assert.assertEquals("b", attrs.getQName(1));
+
+        // The unchanged attribute's name must still be tracked
+        try {
+            attrs.addAttribute("", "b", "b", "CDATA", "4");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 38/46: Fall back when the Set tag plugin has nowhere to set

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit e48a38e62ce2aff9dc483b3e490f14f1c9e666cb
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 15:25:01 2026 +0200

    Fall back when the Set tag plugin has nowhere to set
    
    A c:set carrying a value but neither a var nor a target attribute is
    invalid, but the tag is complete as far as the tag library descriptor
    and its validator are concerned. The tag plugin generated the
    evaluation of the value and no further statement, so the value was
    computed and dropped and the page carried on, while the standard tag
    handler reports the missing target and fails the request.
    
    The plugin now falls back to the standard handler for that
    combination. Falling back is safe after code has already been
    generated for the tag, as that code is only reachable while the plug-in
    is in use, which the fallback turns off.
---
 .../apache/jasper/tagplugins/jstl/core/Set.java    |  7 +++++++
 .../jasper/tagplugins/jstl/core/TestSet.java       | 23 +++++++++++++++++++++
 test/webapp/jstl/set-no-var-target.jsp             | 24 ++++++++++++++++++++++
 webapps/docs/changelog.xml                         |  7 +++++++
 4 files changed, 61 insertions(+)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Set.java b/java/org/apache/jasper/tagplugins/jstl/core/Set.java
index e4af208be5..e732a988bb 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Set.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Set.java
@@ -65,6 +65,13 @@ public class Set implements TagPlugin {
             ctxt.generateJavaSource(resultName + " = ");
             ctxt.generateAttribute("value");
             ctxt.generateJavaSource(";");
+            // Without a var or a target, nothing receives the value. The
+            // standard handler fails this use on the missing target, so let
+            // it handle the tag.
+            if (!hasVar && !hasTarget) {
+                ctxt.dontUseTagPlugin();
+                return;
+            }
         } else {
             ctxt.dontUseTagPlugin();
             return;
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java b/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java
index 000e3e255c..e5c0526d83 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java
@@ -89,4 +89,27 @@ public class TestSet extends AbstractTestTag {
                         + "\"page\" scope is required but was \"request\"]"));
         Assert.assertTrue(body, body.contains("ERR2=[threw]"));
     }
+
+
+    /*
+     * A c:set with a value but neither var nor target sets nothing. The
+     * standard handler treats the absent target as an invalid target and
+     * fails, which the plugin has to keep doing.
+     */
+    @Test
+    public void testNoVarNoTarget() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/set-no-var-target.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("ERR=[threw]"));
+        Assert.assertTrue(body,
+                body.contains("ERRMSG=[Attempt to set the property of an invalid object in &lt;set&gt;.]"));
+        // A property makes no difference without a var or a target
+        Assert.assertTrue(body, body.contains("ERR2=[threw]"));
+    }
 }
diff --git a/test/webapp/jstl/set-no-var-target.jsp b/test/webapp/jstl/set-no-var-target.jsp
new file mode 100644
index 0000000000..f0e24b084d
--- /dev/null
+++ b/test/webapp/jstl/set-no-var-target.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:set value="foo" /></c:catch>
+<p>ERR=[${err ne null ? 'threw' : 'silent'}]</p>
+<p>ERRMSG=[${err.message}]</p>
+<c:catch var="err2"><c:set value="foo" property="bar" /></c:catch>
+<p>ERR2=[${err2 ne null ? 'threw' : 'silent'}]</p>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index bc4a623f0c..9d8f8e2c8d 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -470,6 +470,13 @@
         rejected for a deferred value, and mappings that would shadow a
         plain attribute are removed. (remm)
       </fix>
+      <fix>
+        The tag plugin for <code>c:set</code> now falls back to the standard
+        tag handler when the tag has a value but neither a
+        <code>var</code> nor a <code>target</code> attribute, so that the
+        invalid use fails as it does with the handler instead of being
+        silently ignored. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 26/46: Avoid StringIndexOutOfBoundsException forwarding a relative path from a slash-less servlet path

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 607192fa116ac6e25afdea3439a25c5908bc3bb2
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 11:52:19 2026 +0200

    Avoid StringIndexOutOfBoundsException forwarding a relative path from
    a slash-less servlet path
    
    PageContextImpl.getAbsolutePathRelativeToContext, used by
    pageContext.forward to resolve a relative path, truncated the current
    servlet path at its last '/' without checking that a '/' is present.
    When the servlet path contains no '/', for example for a servlet or JSP
    mapped with the empty url-pattern where the servlet path is the empty
    string, the substring call threw a StringIndexOutOfBoundsException,
    turning the forward into an uncontrolled 500 while the sibling include
    logic in JspRuntimeLibrary.getContextRelativePath, which guards the
    truncation, resolved the same request successfully.
    
    Skip the truncation when the servlet path has no '/' so forward and
    include resolve slash-less paths identically against the web
    application root.
    
    Found by code review.
---
 .../org/apache/jasper/runtime/PageContextImpl.java |  6 ++-
 .../apache/jasper/runtime/TestPageContextImpl.java | 62 ++++++++++++++++++++++
 2 files changed, 66 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/runtime/PageContextImpl.java b/java/org/apache/jasper/runtime/PageContextImpl.java
index 109044d833..9253b1195b 100644
--- a/java/org/apache/jasper/runtime/PageContextImpl.java
+++ b/java/org/apache/jasper/runtime/PageContextImpl.java
@@ -460,8 +460,10 @@ public class PageContextImpl extends PageContext {
             if (uri == null) {
                 uri = ((HttpServletRequest) request).getServletPath();
             }
-            String baseURI = uri.substring(0, uri.lastIndexOf('/'));
-            path = baseURI + '/' + path;
+            if (uri.lastIndexOf('/') >= 0) {
+                uri = uri.substring(0, uri.lastIndexOf('/'));
+            }
+            path = uri + '/' + path;
         }
 
         return path;
diff --git a/test/org/apache/jasper/runtime/TestPageContextImpl.java b/test/org/apache/jasper/runtime/TestPageContextImpl.java
index 9883009335..f8cd9a500f 100644
--- a/test/org/apache/jasper/runtime/TestPageContextImpl.java
+++ b/test/org/apache/jasper/runtime/TestPageContextImpl.java
@@ -122,6 +122,68 @@ public class TestPageContextImpl extends TomcatBaseTest {
     }
 
 
+    @Test
+    public void testForwardRelativePathWithEmptyServletPath() throws Exception {
+        Tomcat tomcat = getTomcatInstanceTestWebapp(false, false);
+
+        Context context = (Context) tomcat.getHost().findChild("/test");
+
+        // The forwarder is mapped to the context root using the empty url
+        // pattern so the servlet path in the request handled by it is the
+        // empty string, which contains no '/' to use as the base for
+        // resolving the relative forward path.
+        Tomcat.addServlet(context, "emptyPathForwarder", new EmptyPathForwarder());
+        context.addServletMapping("", "emptyPathForwarder");
+
+        Tomcat.addServlet(context, "forwardTarget", new ForwardTarget());
+        context.addServletMapping("/forwardTarget", "forwardTarget");
+
+        tomcat.start();
+
+        // The empty pattern matches the context root exactly.
+        ByteChunk res = new ByteChunk();
+        int rc = getUrl("http://localhost:" + getPort() + "/test/", res, null);
+
+        Assert.assertEquals(res.toString(), HttpServletResponse.SC_OK, rc);
+        Assert.assertTrue(res.toString(), res.toString().contains("FORWARDED"));
+    }
+
+
+    public static class EmptyPathForwarder extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+                throws ServletException, IOException {
+
+            PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(
+                    this, req, resp, null, false, JspWriter.DEFAULT_BUFFER, true);
+            try {
+                // Relative path resolution against the empty servlet path
+                // must not throw StringIndexOutOfBoundsException.
+                pageContext.forward("forwardTarget");
+            } finally {
+                JspFactory.getDefaultFactory().releasePageContext(pageContext);
+            }
+        }
+    }
+
+
+    public static class ForwardTarget extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+                throws ServletException, IOException {
+
+            resp.setContentType("text/plain;charset=UTF-8");
+            resp.getWriter().println("FORWARDED");
+        }
+    }
+
+
     @Test
     public void testIncludeThenForward() throws Exception {
         getTomcatInstanceTestWebapp(false, true);


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 02/46: Fix jspc infinite loop with a trailing -trimSpaces argument

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit f35f427c802382d0524aa76ffbe8c8a97158a701
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 20:54:58 2026 +0200

    Fix jspc infinite loop with a trailing -trimSpaces argument
    
    When -trimSpaces was the final command line argument, nextArg()
    returned null without consuming a token, the SINGLE value check
    failed for the null token and the rewind of the argument position
    to re-process the peeked token moved it back onto the -trimSpaces
    argument itself. The option was then re-processed forever and jspc
    never completed.
    
    The rewind is now only performed when a token was actually consumed.
    This also stops the full stop argument from being rewound onto, and
    later treated as a JSP file name, when -trimSpaces is directly
    followed by --.
    
    Add regression tests for the trailing -trimSpaces argument and for
    -trimSpaces followed by the full stop argument to TestJspC.
---
 java/org/apache/jasper/JspC.java     |  4 +++-
 test/org/apache/jasper/TestJspC.java | 29 +++++++++++++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/JspC.java b/java/org/apache/jasper/JspC.java
index babd616246..dbf961ed78 100644
--- a/java/org/apache/jasper/JspC.java
+++ b/java/org/apache/jasper/JspC.java
@@ -452,7 +452,9 @@ public class JspC extends Task implements Options {
                 xpoweredBy = true;
             } else if (tok.equals(SWITCH_TRIM_SPACES)) {
                 tok = nextArg();
-                if (TrimSpacesOption.SINGLE.toString().equalsIgnoreCase(tok)) {
+                if (tok == null) {
+                    setTrimSpaces(TrimSpacesOption.TRUE);
+                } else if (TrimSpacesOption.SINGLE.toString().equalsIgnoreCase(tok)) {
                     setTrimSpaces(TrimSpacesOption.SINGLE);
                 } else {
                     setTrimSpaces(TrimSpacesOption.TRUE);
diff --git a/test/org/apache/jasper/TestJspC.java b/test/org/apache/jasper/TestJspC.java
index a2577c1284..5b59946a21 100644
--- a/test/org/apache/jasper/TestJspC.java
+++ b/test/org/apache/jasper/TestJspC.java
@@ -166,6 +166,35 @@ public class TestJspC {
         Assert.assertEquals(List.of("-compile", "a.jsp"), jspc.pages);
     }
 
+    @Test
+    public void argsTrimSpacesLast() throws Exception {
+        // The setArgs() call must return, applying the default value of TRUE.
+        // Use a thread to avoid the test harness hanging if the option is
+        // ever re-processed in a loop again.
+        Thread thread = new Thread(() -> {
+            try {
+                jspc.setArgs(new String[] {"-trimSpaces"});
+            } catch (JasperException e) {
+                // Ignore
+            }
+        });
+        thread.setDaemon(true);
+        thread.start();
+        thread.join(10000);
+        Assert.assertFalse("setArgs() did not return", thread.isAlive());
+        Assert.assertEquals(TrimSpacesOption.TRUE, jspc.getTrimSpaces());
+        Assert.assertTrue(jspc.pages.isEmpty());
+    }
+
+    @Test
+    public void argsTrimSpacesBeforeFullStop() throws Exception {
+        // The full stop argument takes the place of the missing option value
+        // and must not be added to the list of JSP pages
+        jspc.setArgs(new String[] {"-trimSpaces", "--", "a.jsp", "b.jsp"});
+        Assert.assertEquals(TrimSpacesOption.TRUE, jspc.getTrimSpaces());
+        Assert.assertEquals(List.of("a.jsp", "b.jsp"), jspc.pages);
+    }
+
     @Test
     public void servletContextUsesAntLog() throws Exception {
         List<String> messages = new ArrayList<>();


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 07/46: Correct the "unusable error detail" line number in JavacErrorDetail

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit f2706e6e9773457e696e38a403115fbfc3d9d029
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 21:55:48 2026 +0200

    Correct the "unusable error detail" line number in JavacErrorDetail
    
    When the generated Java source belongs to an earlier, shorter
    compilation of the JSP page, the constructor returns early from the
    truncation guard introduced in r1725278, which predates the
    field-assignment refactoring and left this.jspBeginLineNum at 0. Since
    -1 is the value the API uses to mark an error detail as unusable (both
    other constructor exits follow this convention, and callers such as
    JspServletWrapper.handleJspException and Validator already treat -1 as
    "no usable location"), leave it at -1 on this path as well.
    Clarify the comment describing when and how the field is assigned.
---
 java/org/apache/jasper/compiler/JavacErrorDetail.java | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/compiler/JavacErrorDetail.java b/java/org/apache/jasper/compiler/JavacErrorDetail.java
index eef5f57205..158425a4dc 100644
--- a/java/org/apache/jasper/compiler/JavacErrorDetail.java
+++ b/java/org/apache/jasper/compiler/JavacErrorDetail.java
@@ -69,7 +69,10 @@ public class JavacErrorDetail {
         this.errMsg = errMsg;
         this.jspFileName = jspFileName;
         // Note: this.jspBeginLineNum is set at the end of this method as it may
-        // be modified (corrected) during the execution of this method
+        // be modified (corrected) during the execution of this method. It is
+        // left at -1, which marks the error detail as unusable, if the
+        // generated Java source turns out to belong to a different compilation
+        // of the JSP page.
 
         if (jspBeginLineNum > 0 && ctxt != null) {
             InputStream is = null;
@@ -99,6 +102,9 @@ public class JavacErrorDetail {
                         // Avoid ArrayIndexOutOfBoundsException
                         // Probably bug 48498 but could be some other cause
                         jspExtract = Localizer.getMessage("jsp.error.bug48498");
+                        // Report only the Java line, since the JSP line
+                        // cannot be validated against the truncated source
+                        this.jspBeginLineNum = -1;
                         return;
                     }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 05/46: Match JSP pages in sub-directories in JspConfig.isJspPage

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 46ce2c54d1c206f7c67ccd6fcbcd1025261c5cfd
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 21:26:52 2026 +0200

    Match JSP pages in sub-directories in JspConfig.isJspPage
    
    JspConfig.isJspPage(), used by jspc when scanning a web application for
    pages to process, compared the directory prefix of a jsp-property-group
    URL pattern with equals() against the page path, while the matcher used
    at runtime, findJspProperty(), uses startsWith(). Pages in directories
    below the one named by a path-prefix pattern such as /p/* were therefore
    silently skipped by jspc even though the container processes them as JSP
    pages.
    
    Match the prefix with startsWith() so the scan covers the same pages
    that the container's runtime matching selects.
---
 java/org/apache/jasper/compiler/JspConfig.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/compiler/JspConfig.java b/java/org/apache/jasper/compiler/JspConfig.java
index 5457c0b035..da61f6fc68 100644
--- a/java/org/apache/jasper/compiler/JspConfig.java
+++ b/java/org/apache/jasper/compiler/JspConfig.java
@@ -393,7 +393,7 @@ public class JspConfig {
                     return true;
                 }
             } else {
-                if ((path == null || path.equals(uriPath)) &&
+                if ((path == null || (uriPath != null && uriPath.startsWith(path))) &&
                         (extension.equals("*") || extension.equals(uriExtension))) {
                     // Matches *, *.ext, /p/*, or /p/*.ext
                     return true;


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 33/46: Fall back when c:when or c:otherwise has no choose parent

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 2a0b5a1cd0a1dc8221c35ca3560883eeca14fb3b
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 13:53:30 2026 +0200

    Fall back when c:when or c:otherwise has no choose parent
    
    The When plugin only stepped aside when its direct parent had no tag
    plugin context at all. Any other plugin-enabled direct parent, such as
    the default-registered c:forEach, passed the check, and the plugin
    emitted its opening if statement inside the parent's generated
    construct, leaving the brace chain unbalanced until the javac of the
    whole page failed with a syntax error at an unrelated line. The
    Otherwise plugin generated its "} else {" without any parent check at
    all, with the same result. The JSTL TLD validator does not reject this
    nesting, so the page reached code generation.
    
    Mark the Choose plugin context and have When and Otherwise fall back to
    the standard tag handlers unless their direct parent carries the mark.
    The standard handlers perform the same direct-parent check as the
    reference implementation and report the illegal nesting with a clean
    runtime JspTagException instead of failing the translation of the
    entire page. Add tests covering the misplaced tags and a test pinning
    that valid nesting still uses the plugins.
    
    Found by code review.
---
 .../apache/jasper/tagplugins/jstl/core/Choose.java |  4 ++
 .../jasper/tagplugins/jstl/core/Otherwise.java     |  9 ++++
 .../apache/jasper/tagplugins/jstl/core/When.java   | 12 ++++++
 .../jasper/tagplugins/jstl/core/TestChoose.java    | 35 ++++++++-------
 .../jasper/tagplugins/jstl/core/TestOtherwise.java | 47 ++++++++++++++++++++
 .../jasper/tagplugins/jstl/core/TestWhen.java      | 50 ++++++++++++++++++++++
 test/webapp/jstl/choose-basic.jsp                  | 24 +++++++++++
 test/webapp/jstl/otherwise-outside-choose.jsp      | 22 ++++++++++
 test/webapp/jstl/when-outside-choose.jsp           | 22 ++++++++++
 webapps/docs/changelog.xml                         | 10 +++++
 10 files changed, 217 insertions(+), 18 deletions(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Choose.java b/java/org/apache/jasper/tagplugins/jstl/core/Choose.java
index 60e5d6e9bd..bfbfd758a5 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Choose.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Choose.java
@@ -33,9 +33,13 @@ public final class Choose implements TagPlugin {
     @Override
     public void doTag(TagPluginContext ctxt) {
 
+        // Mark this context so that the <c:when> and <c:otherwise> tags in
+        // the body know that they are directly nested in a <c:choose>.
+
         // Not much to do here, much of the work will be done in the
         // containing tags, <c:when> and <c:otherwise>.
 
+        ctxt.setPluginAttribute("inChoose", "true");
         ctxt.generateBody();
         // See comments in When.java for the reason "}" is generated here.
         ctxt.generateJavaSource("}");
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Otherwise.java b/java/org/apache/jasper/tagplugins/jstl/core/Otherwise.java
index 0e1217de4c..8d143b1c69 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Otherwise.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Otherwise.java
@@ -33,6 +33,15 @@ public final class Otherwise implements TagPlugin {
     @Override
     public void doTag(TagPluginContext ctxt) {
 
+        // See When.java. An otherwise outside a plugin-enabled choose must
+        // not generate a stray "} else {".
+        TagPluginContext parentContext = ctxt.getParentContext();
+        if (parentContext == null ||
+                !"true".equals(parentContext.getPluginAttribute("inChoose"))) {
+            ctxt.dontUseTagPlugin();
+            return;
+        }
+
         // See When.java for the reason why "}" is needed at the beginning and
         // not at the end.
         ctxt.generateJavaSource("} else {");
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/When.java b/java/org/apache/jasper/tagplugins/jstl/core/When.java
index e8766fd609..bd84624c29 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/When.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/When.java
@@ -39,6 +39,18 @@ public final class When implements TagPlugin {
             return;
         }
 
+        /*
+         * The plugin-enabled parent is not a <c:choose>, for example a
+         * <c:forEach>, which the TLD validator does not reject. The generated
+         * if/else chain would be unbalanced and the whole page would fail to
+         * translate. Fall back to the standard tag handler, which reports the
+         * illegal nesting at runtime.
+         */
+        if (!"true".equals(parentContext.getPluginAttribute("inChoose"))) {
+            ctxt.dontUseTagPlugin();
+            return;
+        }
+
         if ("true".equals(parentContext.getPluginAttribute("hasBeenHere"))) {
             ctxt.generateJavaSource("} else if(");
             // See comment below for the reason we generate the extra "}" here.
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Choose.java b/test/org/apache/jasper/tagplugins/jstl/core/TestChoose.java
similarity index 56%
copy from java/org/apache/jasper/tagplugins/jstl/core/Choose.java
copy to test/org/apache/jasper/tagplugins/jstl/core/TestChoose.java
index 60e5d6e9bd..548e963d87 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Choose.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestChoose.java
@@ -16,28 +16,27 @@
  */
 package org.apache.jasper.tagplugins.jstl.core;
 
-import org.apache.jasper.compiler.tagplugin.TagPlugin;
-import org.apache.jasper.compiler.tagplugin.TagPluginContext;
+import jakarta.servlet.http.HttpServletResponse;
 
-/**
- * Tag plugin for the JSTL &lt;c:choose&gt; tag.
- */
-public final class Choose implements TagPlugin {
+import org.junit.Assert;
+import org.junit.Test;
 
-    /**
-     * Creates a new Choose tag plugin.
-     */
-    public Choose() {
-    }
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestChoose extends AbstractTestTag {
+
+    @Test
+    public void testChooseWhenOtherwise() throws Exception {
+        ByteChunk res = new ByteChunk();
 
-    @Override
-    public void doTag(TagPluginContext ctxt) {
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/choose-basic.jsp", res, null);
 
-        // Not much to do here, much of the work will be done in the
-        // containing tags, <c:when> and <c:otherwise>.
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
 
-        ctxt.generateBody();
-        // See comments in When.java for the reason "}" is generated here.
-        ctxt.generateJavaSource("}");
+        String body = res.toString();
+        Assert.assertTrue(body.contains("other-1"));
+        Assert.assertTrue(body.contains("two"));
+        Assert.assertTrue(body.contains("three"));
     }
 }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestOtherwise.java b/test/org/apache/jasper/tagplugins/jstl/core/TestOtherwise.java
new file mode 100644
index 0000000000..783ab93df2
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestOtherwise.java
@@ -0,0 +1,47 @@
+/*
+ * 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.jasper.tagplugins.jstl.core;
+
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestOtherwise extends AbstractTestTag {
+
+    /*
+     * A <c:otherwise> whose direct parent is not a <c:choose> must not
+     * generate a stray "} else {", which would fail the translation of the
+     * whole page. See TestWhen for the equivalent <c:when> case.
+     */
+    @Test
+    public void testOutsideChoose() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/otherwise-outside-choose.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("JspTagException"));
+        Assert.assertTrue(body, body.contains("style tag without"));
+        Assert.assertTrue(body, body.contains("as its direct parent"));
+    }
+}
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestWhen.java b/test/org/apache/jasper/tagplugins/jstl/core/TestWhen.java
new file mode 100644
index 0000000000..b64694fc3a
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestWhen.java
@@ -0,0 +1,50 @@
+/*
+ * 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.jasper.tagplugins.jstl.core;
+
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestWhen extends AbstractTestTag {
+
+    /*
+     * A <c:when> whose direct parent is not a <c:choose> (but is another
+     * plugin-enabled tag) must not generate an unbalanced if statement, which
+     * would fail the translation of the whole page. The plugin must step
+     * aside so that the standard tag handler reports the illegal nesting at
+     * runtime, as the reference implementation does. The TLD validator does
+     * not reject this nesting.
+     */
+    @Test
+    public void testOutsideChoose() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/when-outside-choose.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("JspTagException"));
+        Assert.assertTrue(body, body.contains("style tag without"));
+        Assert.assertTrue(body, body.contains("as its direct parent"));
+    }
+}
diff --git a/test/webapp/jstl/choose-basic.jsp b/test/webapp/jstl/choose-basic.jsp
new file mode 100644
index 0000000000..fd046a128c
--- /dev/null
+++ b/test/webapp/jstl/choose-basic.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:forEach items="${[1,2,3]}" var="n"><c:choose>
+  <c:when test="${n == 2}">two </c:when>
+  <c:when test="${n == 3}">three </c:when>
+  <c:otherwise>other-${n} </c:otherwise>
+</c:choose></c:forEach>
diff --git a/test/webapp/jstl/otherwise-outside-choose.jsp b/test/webapp/jstl/otherwise-outside-choose.jsp
new file mode 100644
index 0000000000..fb0913e949
--- /dev/null
+++ b/test/webapp/jstl/otherwise-outside-choose.jsp
@@ -0,0 +1,22 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forEach items="${['a','b']}" var="x"><c:otherwise
+    >O-${x}</c:otherwise></c:forEach></c:catch>
+<p>error=${err}</p>
diff --git a/test/webapp/jstl/when-outside-choose.jsp b/test/webapp/jstl/when-outside-choose.jsp
new file mode 100644
index 0000000000..f17cfa9d41
--- /dev/null
+++ b/test/webapp/jstl/when-outside-choose.jsp
@@ -0,0 +1,22 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:catch var="err"><c:forEach items="${['a','b']}" var="x"><c:when
+    test="${true}">X-${x}</c:when></c:forEach></c:catch>
+<p>error=${err}</p>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index a07fe17e74..e5de6744ce 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -429,6 +429,16 @@
         rejected and EL writes to such properties could be silently dropped
         when running in a GraalVM native image. (remm)
       </fix>
+      <fix>
+        The tag plugins for <code>c:when</code> and <code>c:otherwise</code>
+        now fall back to the standard tag handlers when the direct parent tag
+        is not a plugin enabled <code>c:choose</code>. Previously, they
+        generated unbalanced Java code for such misplaced tags, for example a
+        <code>c:when</code> nested directly in a <code>c:forEach</code>, which
+        failed the translation of the entire page instead of reporting the
+        illegal nesting at runtime as the reference implementation does.
+        (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 01/46: Fix jspc handling of the full stop (--) argument

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 17234c387e398c05cbb5158475e2ef9d4258e380
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 20:47:18 2026 +0200

    Fix jspc handling of the full stop (--) argument
    
    The full stop argument was never advanced past by nextArg(), while
    nextFile() incremented the argument position on every call when the
    full stop had been seen. The net result was that every second file
    argument after '--' was silently skipped, e.g. 'jspc -- a.jsp b.jsp
    c.jsp' only processed a.jsp and c.jsp.
    
    nextArg() now consumes the full stop argument exactly once and
    nextFile() no longer manipulates the argument position, so all
    remaining arguments are collected as files. In addition, the rewind
    for the first non-option argument is now unconditional, and option
    parsing stops whenever the full stop argument is consumed, including
    when it appears in an option value position, so that option-like
    arguments after '--' are treated as files. As a side effect, the
    previously possible infinite loop caused by a full stop argument
    directly after -trimSpaces no longer occurs.
    
    Add regression tests for the full stop argument handling to
    TestJspC.
---
 java/org/apache/jasper/JspC.java     | 39 +++++++++++++++++++++-------------
 test/org/apache/jasper/TestJspC.java | 41 ++++++++++++++++++++++++++++++++++++
 webapps/docs/changelog.xml           | 12 +++++++++++
 3 files changed, 77 insertions(+), 15 deletions(-)

diff --git a/java/org/apache/jasper/JspC.java b/java/org/apache/jasper/JspC.java
index f467db4294..babd616246 100644
--- a/java/org/apache/jasper/JspC.java
+++ b/java/org/apache/jasper/JspC.java
@@ -502,12 +502,16 @@ public class JspC extends Task implements Options {
                 if (tok.startsWith("-")) {
                     throw new JasperException(Localizer.getMessage("jspc.error.unknownOption", tok));
                 }
-                if (!fullstop) {
-                    argPos--;
-                }
+                // Re-process this argument as a JSP page
+                argPos--;
                 // Start treating the rest as JSP Pages
                 break;
             }
+            if (fullstop) {
+                // A full stop argument encountered while reading an option
+                // value also stops option parsing
+                break;
+            }
         }
 
         // Add all extra arguments to the list of files
@@ -1642,32 +1646,37 @@ public class JspC extends Task implements Options {
     // ==================== protected utility methods ====================
 
     /**
-     * Returns the next command-line argument.
+     * Returns the next command-line argument. Option parsing stops when the
+     * full stop argument {@code --} is encountered. The full stop argument is
+     * consumed and is never returned.
      *
-     * @return the next argument, or {@code null} if no more arguments
+     * @return the next argument, or {@code null} if no more arguments are
+     *             available or the full stop argument was reached
      */
     protected String nextArg() {
-        if ((argPos >= args.length) || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
+        if (argPos >= args.length) {
             return null;
-        } else {
-            return args[argPos++];
         }
+        if (SWITCH_FULL_STOP.equals(args[argPos])) {
+            fullstop = true;
+            argPos++;
+            return null;
+        }
+        return args[argPos++];
     }
 
     /**
-     * Returns the next file argument from the command-line.
+     * Returns the next file argument from the command-line. All remaining
+     * arguments are treated as files once option parsing has stopped.
      *
-     * @return the next file argument, or {@code null} if no more arguments
+     * @return the next file argument, or {@code null} if no more arguments are
+     *             available
      */
     protected String nextFile() {
-        if (fullstop) {
-            argPos++;
-        }
         if (argPos >= args.length) {
             return null;
-        } else {
-            return args[argPos++];
         }
+        return args[argPos++];
     }
 
     /**
diff --git a/test/org/apache/jasper/TestJspC.java b/test/org/apache/jasper/TestJspC.java
index da1f96fdee..a2577c1284 100644
--- a/test/org/apache/jasper/TestJspC.java
+++ b/test/org/apache/jasper/TestJspC.java
@@ -125,6 +125,47 @@ public class TestJspC {
         verify(webappOut);
     }
 
+    @Test
+    public void argsNoFullStop() throws Exception {
+        jspc.setArgs(new String[] {"a.jsp", "b.jsp"});
+        Assert.assertEquals(List.of("a.jsp", "b.jsp"), jspc.pages);
+    }
+
+    @Test
+    public void argsFullStop() throws Exception {
+        jspc.setArgs(new String[] {"--", "a.jsp", "b.jsp", "c.jsp"});
+        Assert.assertEquals(List.of("a.jsp", "b.jsp", "c.jsp"), jspc.pages);
+    }
+
+    @Test
+    public void argsFullStopAfterOptions() throws Exception {
+        jspc.setArgs(new String[] {"-compile", "--", "a.jsp", "b.jsp"});
+        Assert.assertTrue(jspc.compile);
+        Assert.assertEquals(List.of("a.jsp", "b.jsp"), jspc.pages);
+    }
+
+    @Test
+    public void argsFullStopFileStartingWithDash() throws Exception {
+        jspc.setArgs(new String[] {"--", "-a.jsp", "b.jsp"});
+        Assert.assertEquals(List.of("-a.jsp", "b.jsp"), jspc.pages);
+    }
+
+    @Test
+    public void argsFullStopAsOptionValue() throws Exception {
+        // The full stop argument takes the place of the missing option value
+        // and must not cause the first file argument to be dropped
+        jspc.setArgs(new String[] {"-d", "--", "a.jsp", "b.jsp"});
+        Assert.assertEquals(List.of("a.jsp", "b.jsp"), jspc.pages);
+    }
+
+    @Test
+    public void argsFullStopInOptionValuePositionStopsOptionParsing()
+            throws Exception {
+        jspc.setArgs(new String[] {"-cache", "--", "-compile", "a.jsp"});
+        Assert.assertFalse(jspc.compile);
+        Assert.assertEquals(List.of("-compile", "a.jsp"), jspc.pages);
+    }
+
     @Test
     public void servletContextUsesAntLog() throws Exception {
         List<String> messages = new ArrayList<>();
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 618b8a2ac0..4575af986d 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -401,6 +401,18 @@
       </fix>
     </changelog>
   </subsection>
+  <subsection name="Jasper">
+    <changelog>
+      <fix>
+        Correct the handling of the <code>--</code> argument by
+        <code>jspc</code>. The argument position was advanced past the full
+        stop argument on each iteration while collecting the JSP file
+        arguments, so every second file argument after <code>--</code> was
+        silently omitted from processing. Option parsing now stops at the
+        first full stop argument wherever it appears. (remm)
+      </fix>
+    </changelog>
+  </subsection>
   <subsection name="WebSocket">
     <changelog>
       <fix>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 20/46: Report bean getter and setter exceptions in GraalVM mode

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 37a1db8eb7a4bdba7b53482a782dc159ad82f58b
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 10:33:12 2026 +0200

    Report bean getter and setter exceptions in GraalVM mode
    
    GraalBeanELResolver caught exceptions raised while invoking a bean
    getter or setter, passed them through ExceptionUtils.handleThrowable()
    which only rethrows VirtualMachineError, and then returned as if the
    property had been resolved successfully. A throwing getter therefore
    yielded a null value and a throwing setter a silently dropped write.
    The ELResolver contract, and the standard BeanELResolver used outside
    GraalVM native image mode, wrap such failures in an ELException.
    
    Rethrow the unwrapped cause as an ELException after handleThrowable(),
    mirroring BeanELResolver so a native image build reports the same EL
    errors as a standard JVM. Test with bean properties whose accessor and
    mutator throw.
    
    Found by code review.
---
 java/org/apache/jasper/el/JasperELResolver.java    | 12 +++++---
 .../org/apache/jasper/el/TestJasperELResolver.java | 33 ++++++++++++++++++++++
 2 files changed, 41 insertions(+), 4 deletions(-)

diff --git a/java/org/apache/jasper/el/JasperELResolver.java b/java/org/apache/jasper/el/JasperELResolver.java
index 8fb27a8d77..ae13dcdeb1 100644
--- a/java/org/apache/jasper/el/JasperELResolver.java
+++ b/java/org/apache/jasper/el/JasperELResolver.java
@@ -218,8 +218,7 @@ public class JasperELResolver extends CompositeELResolver {
                     method.setAccessible(true);
                     value = method.invoke(base, (Object[]) null);
                 } catch (Exception e) {
-                    Throwable thr = ExceptionUtils.unwrapInvocationTargetException(e);
-                    ExceptionUtils.handleThrowable(thr);
+                    throw toELException(e);
                 }
             }
             return value;
@@ -241,8 +240,7 @@ public class JasperELResolver extends CompositeELResolver {
                     method.setAccessible(true);
                     method.invoke(base, value);
                 } catch (Exception e) {
-                    Throwable thr = ExceptionUtils.unwrapInvocationTargetException(e);
-                    ExceptionUtils.handleThrowable(thr);
+                    throw toELException(e);
                 }
             }
         }
@@ -287,6 +285,12 @@ public class JasperELResolver extends CompositeELResolver {
             return null;
         }
 
+        private static ELException toELException(Exception e) {
+            Throwable thr = ExceptionUtils.unwrapInvocationTargetException(e);
+            ExceptionUtils.handleThrowable(thr);
+            return new ELException(thr);
+        }
+
         private static String capitalize(String name) {
             if (name == null || name.isEmpty()) {
                 return name;
diff --git a/test/org/apache/jasper/el/TestJasperELResolver.java b/test/org/apache/jasper/el/TestJasperELResolver.java
index a6f202c36c..8343241fd0 100644
--- a/test/org/apache/jasper/el/TestJasperELResolver.java
+++ b/test/org/apache/jasper/el/TestJasperELResolver.java
@@ -22,6 +22,7 @@ import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import jakarta.el.ELContext;
+import jakarta.el.ELException;
 import jakarta.el.ELResolver;
 import jakarta.servlet.jsp.el.ImplicitObjectELResolver;
 
@@ -111,6 +112,32 @@ public class TestJasperELResolver {
         resolver.setValue(context, bean, "foo", Integer.valueOf(7));
         Assert.assertFalse("A mismatched value must leave the property unresolved",
                 context.isPropertyResolved());
+
+        // An exception thrown by a getter must be reported rather than
+        // swallowed. Before the fix it produced a silently resolved null.
+        context.setPropertyResolved(false);
+        try {
+            resolver.getValue(context, bean, "failing");
+            Assert.fail("A getter exception must be reported");
+        } catch (ELException e) {
+            Assert.assertTrue("The reported cause must be the thrown exception",
+                    e.getCause() instanceof IllegalStateException);
+            Assert.assertEquals("getter failed", e.getCause().getMessage());
+            Assert.assertTrue("A found property should be marked resolved", context.isPropertyResolved());
+        }
+
+        // An exception thrown by a setter must be reported rather than
+        // swallowed. Before the fix the failed write went unnoticed.
+        context.setPropertyResolved(false);
+        try {
+            resolver.setValue(context, bean, "failing", "some value");
+            Assert.fail("A setter exception must be reported");
+        } catch (ELException e) {
+            Assert.assertTrue("The reported cause must be the thrown exception",
+                    e.getCause() instanceof IllegalStateException);
+            Assert.assertEquals("setter failed", e.getCause().getMessage());
+            Assert.assertTrue("A found property should be marked resolved", context.isPropertyResolved());
+        }
     }
 
     public static class TestBean {
@@ -140,5 +167,11 @@ public class TestJasperELResolver {
         public Object getLastBla() {
             return bla;
         }
+        public String getFailing() {
+            throw new IllegalStateException("getter failed");
+        }
+        public void setFailing(@SuppressWarnings("unused") String value) {
+            throw new IllegalStateException("setter failed");
+        }
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 22/46: Correct the expression wrapper equals implementation

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 1a7f7ad2c93ff993182c323c384cf600c4da82dc
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 10:41:42 2026 +0200

    Correct the expression wrapper equals implementation
    
    JspValueExpression and JspMethodExpression delegated equals() to the
    target expression. The engine's ValueExpressionImpl and
    MethodExpressionImpl only consider their own type equal, so a wrapper
    was never equal to itself or to another wrapper around the same target,
    violating the reflexivity requirement of the contract while hashCode(),
    also delegated to the target, reported such wrappers as equal.
    
    Check for the same instance, then compare the JSP location mark and the
    target expression of two wrappers. A wrapper is not equal to anything
    else, which is symmetric with the target implementations rejecting the
    wrapper type. The delegated hash stays consistent because equal
    wrappers always wrap equal targets.
    
    Found by code review.
---
 java/org/apache/jasper/el/JspMethodExpression.java | 9 ++++++++-
 java/org/apache/jasper/el/JspValueExpression.java  | 9 ++++++++-
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/el/JspMethodExpression.java b/java/org/apache/jasper/el/JspMethodExpression.java
index d34be872c6..fddf3b8727 100644
--- a/java/org/apache/jasper/el/JspMethodExpression.java
+++ b/java/org/apache/jasper/el/JspMethodExpression.java
@@ -20,6 +20,7 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
+import java.util.Objects;
 
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
@@ -141,7 +142,13 @@ public final class JspMethodExpression extends MethodExpression implements Exter
 
     @Override
     public boolean equals(Object obj) {
-        return this.target.equals(obj);
+        if (obj == this) {
+            return true;
+        }
+        if (!(obj instanceof JspMethodExpression other)) {
+            return false;
+        }
+        return Objects.equals(this.mark, other.mark) && this.target.equals(other.target);
     }
 
     @Override
diff --git a/java/org/apache/jasper/el/JspValueExpression.java b/java/org/apache/jasper/el/JspValueExpression.java
index 889ec675f2..25858ca70d 100644
--- a/java/org/apache/jasper/el/JspValueExpression.java
+++ b/java/org/apache/jasper/el/JspValueExpression.java
@@ -20,6 +20,7 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
+import java.util.Objects;
 
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
@@ -146,7 +147,13 @@ public final class JspValueExpression extends ValueExpression implements Externa
 
     @Override
     public boolean equals(Object obj) {
-        return this.target.equals(obj);
+        if (obj == this) {
+            return true;
+        }
+        if (!(obj instanceof JspValueExpression other)) {
+            return false;
+        }
+        return Objects.equals(this.mark, other.mark) && this.target.equals(other.target);
     }
 
     @Override


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 12/46: Extract the SMAP from the end of the compiled class file

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit f0545bb99471b6eca4bd27791a6c88754f4161c8
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 23:45:40 2026 +0200

    Extract the SMAP from the end of the compiled class file
    
    SmapUtil.getSmap() scanned the class file from the start for the byte
    sequence "SMAP\n" and treated everything after the first occurrence as
    the SMAP. A compiled JSP servlet class can legitimately contain that
    byte sequence earlier, for example in a string constant in the constant
    pool created from template text that has the word "SMAP" at the end of
    a line. In that case the extraction returned garbage from the wrong
    offset, silently corrupting the JSP line mapping used to report errors.
    
    The SourceDebugExtension attribute that holds the SMAP is appended as
    the last attribute of the class file by SDEInstaller and, as generated
    by SmapStratum, it contains the marker only once, so take the SMAP from
    the last occurrence of the marker.
    
    Add tests that verify extraction from a class file where the marker
    only appears in the simulated SourceDebugExtension attribute and from
    one where an earlier occurrence is present in the simulated constant
    pool.
---
 java/org/apache/jasper/compiler/SmapUtil.java     | 66 ++++++----------
 test/org/apache/jasper/compiler/TestSmapUtil.java | 93 +++++++++++++++++++++++
 2 files changed, 116 insertions(+), 43 deletions(-)

diff --git a/java/org/apache/jasper/compiler/SmapUtil.java b/java/org/apache/jasper/compiler/SmapUtil.java
index 46bfeb059e..50424f8fba 100644
--- a/java/org/apache/jasper/compiler/SmapUtil.java
+++ b/java/org/apache/jasper/compiler/SmapUtil.java
@@ -16,7 +16,6 @@
  */
 package org.apache.jasper.compiler;
 
-import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -50,6 +49,9 @@ public class SmapUtil {
 
     private static final Charset SMAP_ENCODING = StandardCharsets.UTF_8;
 
+    // Marker that begins the SMAP data in the SourceDebugExtension attribute
+    private static final String SMAP_START_MARKER = "SMAP\n";
+
 
     /**
      * Generates an appropriate SMAP representing the current compilation context. (JSR-045.)
@@ -763,55 +765,33 @@ public class SmapUtil {
     }
 
 
-    @SuppressWarnings("null") // is cannot be null when used
     private static String getSmap(String className, ClassLoader cl) {
-        Charset encoding = StandardCharsets.ISO_8859_1;
-        boolean found = false;
-        String smap = null;
-
         InputStream is = null;
         try {
             is = cl.getResourceAsStream(className.replace(".", "/") + ".smap");
             if (is != null) {
-                encoding = SMAP_ENCODING;
-                found = true;
-            } else {
-                is = cl.getResourceAsStream(className.replace(".", "/") + ".class");
-                if (is != null) {
-                    // Alternative approach would be to read the class file as per the
-                    // JLS. That would require duplicating a lot of BCEL functionality.
-                    int b = is.read();
-                    while (b != -1) {
-                        if (b == 'S') {
-                            if ((b = is.read()) != 'M') {
-                                continue;
-                            }
-                            if ((b = is.read()) != 'A') {
-                                continue;
-                            }
-                            if ((b = is.read()) != 'P') {
-                                continue;
-                            }
-                            if ((b = is.read()) != '\n') {
-                                continue;
-                            }
-                            found = true;
-                            break;
-                        }
-                        b = is.read();
-                    }
-                }
+                return new String(is.readAllBytes(), SMAP_ENCODING);
             }
 
-            if (found) {
-                ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
-                byte[] buf = new byte[1024];
-                int numRead;
-                while ((numRead = is.read(buf)) >= 0) {
-                    baos.write(buf, 0, numRead);
+            is = cl.getResourceAsStream(className.replace(".", "/") + ".class");
+            if (is != null) {
+                // The SourceDebugExtension attribute that contains the SMAP
+                // is appended as the last attribute of the class file (see
+                // SDEInstaller) so the SMAP to extract is the one that starts
+                // at the last occurrence of the marker. The first occurrence
+                // cannot be used because the same byte sequence may appear
+                // earlier in the class file, for example in a string constant
+                // in the constant pool created from the template text of the
+                // page. Note that, unlike SmapStratum, the optional JSR-045
+                // terminator line "* END SMAP" also contains the marker. The
+                // SMAP data is installed as ISO-8859-1 (see installSmap())
+                // which preserves every byte of the class file, so the marker
+                // cannot be missed by the search below.
+                String classData = new String(is.readAllBytes(), StandardCharsets.ISO_8859_1);
+                int index = classData.lastIndexOf(SMAP_START_MARKER);
+                if (index >= 0) {
+                    return classData.substring(index + SMAP_START_MARKER.length());
                 }
-
-                smap = baos.toString(encoding);
             }
         } catch (IOException ioe) {
             Log log = LogFactory.getLog(SmapUtil.class);
@@ -826,6 +806,6 @@ public class SmapUtil {
                 }
             }
         }
-        return smap;
+        return null;
     }
 }
diff --git a/test/org/apache/jasper/compiler/TestSmapUtil.java b/test/org/apache/jasper/compiler/TestSmapUtil.java
new file mode 100644
index 0000000000..379a5751a9
--- /dev/null
+++ b/test/org/apache/jasper/compiler/TestSmapUtil.java
@@ -0,0 +1,93 @@
+/*
+ * 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.jasper.compiler;
+
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.startup.TomcatBaseTest;
+
+public class TestSmapUtil extends TomcatBaseTest {
+
+    // The SMAP of a Jasper generated class. The content is valid for
+    // loadSmap() and follows the format generated by SmapStratum.
+    private static final String SMAP = "SMAP\n" +
+            "test.jsp\n" +
+            "JSP\n" +
+            "*S JSP\n" +
+            "*F\n" +
+            "+ 0 test.jsp\n" +
+            "test.jsp\n" +
+            "*L\n" +
+            "1,4:120,0\n" +
+            "*E\n";
+
+    @Test
+    public void testLoadSmapFromDebugExtension() throws Exception {
+        // A class file that only contains the SMAP in the (simulated)
+        // SourceDebugExtension attribute at the end of the file
+        URLClassLoader cl = writeClass("clean", "CAFEBABE junk".getBytes(StandardCharsets.ISO_8859_1));
+
+        SmapStratum smapStratum = SmapUtil.loadSmap("clean", cl);
+
+        Assert.assertNotNull(smapStratum);
+        Assert.assertEquals(SMAP, smapStratum.toString());
+    }
+
+    @Test
+    public void testLoadSmapWithMarkerInConstantPool() throws Exception {
+        // Jasper does not read the class file as described by the JLS so a
+        // string constant in the constant pool that contains "SMAP\n" (which
+        // a page with the word "SMAP" at the end of a line of template text
+        // produces) must not be mistaken for the start of the SMAP. The SMAP
+        // of the SourceDebugExtension attribute has to be extracted even
+        // though an earlier occurrence of the marker is present.
+        byte[] junk =
+                "CAFEBABE constant pool junk that ends a line of template text with SMAP\nfake content\n"
+                        .getBytes(StandardCharsets.ISO_8859_1);
+
+        URLClassLoader cl = writeClass("junk", junk);
+
+        SmapStratum smapStratum = SmapUtil.loadSmap("junk", cl);
+
+        Assert.assertNotNull("SMAP extraction found the marker in the constant pool junk", smapStratum);
+        Assert.assertEquals(SMAP, smapStratum.toString());
+    }
+
+    /**
+     * Writes a file named [name].class to the test temporary directory. The
+     * content simulates the end of a compiled JSP class file: the given data
+     * followed by the SMAP, since Jasper places the SourceDebugExtension
+     * attribute last and loadSmap() does not parse the class file structure.
+     *
+     * @return a class loader for the directory containing the file
+     */
+    private URLClassLoader writeClass(String name, byte[] data) throws Exception {
+        File file = new File(getTemporaryDirectory(), name + ".class");
+
+        String classData = new String(data, StandardCharsets.ISO_8859_1) + SMAP;
+        Files.writeString(file.toPath(), classData, StandardCharsets.ISO_8859_1);
+
+        return new URLClassLoader(new URL[] { file.getParentFile().toURI().toURL() });
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 11/46: Match the JSP namespace exactly when detecting JSP documents

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit bab89e9ac2810d5199eca99775adbb881cc5d4f8
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 23:15:46 2026 +0200

    Match the JSP namespace exactly when detecting JSP documents
    
    ParserController.hasJspRoot() used a regionMatches() prefix comparison
    when checking the namespace bound to the root element's prefix. A
    namespace that merely started with "http://java.sun.com/JSP/Page", such
    as "http://java.sun.com/JSP/PageExtra", incorrectly triggered parsing of
    the page as a JSP document. Such pages were silently miscompiled as XML:
    a spurious XML declaration was prepended to the response, whitespace
    text between elements was removed and the namespace declaration was
    dropped from the root element.
    
    Read the full quoted attribute value and compare it with the JSP
    namespace using String.equals(), as the rest of Jasper already does when
    comparing this URI.
    
    Add tests that cover detection of a root element bound to the exact JSP
    namespace using both the jsp prefix and an arbitrary prefix, and
    non-detection when the namespace only starts with the JSP namespace.
---
 .../apache/jasper/compiler/ParserController.java   |  6 +-
 .../jasper/compiler/TestParserController.java      | 67 ++++++++++++++++++++++
 2 files changed, 72 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/compiler/ParserController.java b/java/org/apache/jasper/compiler/ParserController.java
index 7dbe122479..e9852b73ff 100644
--- a/java/org/apache/jasper/compiler/ParserController.java
+++ b/java/org/apache/jasper/compiler/ParserController.java
@@ -557,8 +557,12 @@ public class ParserController implements TagConstants {
                 index++;
             } while (index < root.length() && Character.isWhitespace(root.charAt(index)));
             if (index < root.length() && (root.charAt(index) == '"' || root.charAt(index) == '\'')) {
+                char quote = root.charAt(index);
                 index++;
-                return root.regionMatches(index, JSP_URI, 0, JSP_URI.length());
+                int end = root.indexOf(quote, index);
+                if (end > index) {
+                    return JSP_URI.equals(root.substring(index, end));
+                }
             }
         }
 
diff --git a/test/org/apache/jasper/compiler/TestParserController.java b/test/org/apache/jasper/compiler/TestParserController.java
index 51594b2512..09f33c6027 100644
--- a/test/org/apache/jasper/compiler/TestParserController.java
+++ b/test/org/apache/jasper/compiler/TestParserController.java
@@ -16,9 +16,14 @@
  */
 package org.apache.jasper.compiler;
 
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
 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.buf.ByteChunk;
 
@@ -40,4 +45,66 @@ public class TestParserController extends TomcatBaseTest {
         Assert.assertTrue(result, result.contains("The include [a b.jsp] is invalid"));
         Assert.assertFalse(result, result.contains("Cannot invoke"));
     }
+
+    @Test
+    public void testJspRootDetection() throws Exception {
+        // The pages for these tests are generated rather than stored with the
+        // tests so that the output, which is compared exactly, always uses
+        // Unix line endings for the template text
+        Tomcat tomcat = getTomcatInstance();
+        File appDir = new File(getTemporaryDirectory(), "root-detection");
+        Assert.assertTrue(appDir.mkdirs() || appDir.isDirectory());
+
+        // The root element may use any prefix as long as the prefix is bound
+        // to the exact JSP namespace URI
+        Files.writeString(new File(appDir, "jsp.jsp").toPath(),
+                "<jsp:root xmlns:jsp=\"" + TagConstants.JSP_URI + "\" version=\"2.0\">\n" +
+                        "<jsp:body>OK</jsp:body>\n</jsp:root>\n", StandardCharsets.UTF_8);
+        Files.writeString(new File(appDir, "other.jsp").toPath(),
+                "<mypfx:root xmlns:mypfx=\"" + TagConstants.JSP_URI + "\" version=\"2.0\">\n" +
+                        "<mypfx:body>OK</mypfx:body>\n</mypfx:root>\n", StandardCharsets.UTF_8);
+
+        tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
+        tomcat.start();
+
+        // Both pages must be parsed as JSP documents. They are handled as XML
+        // syntax so, as the output below shows, only the body content is
+        // written; the whitespace text between the elements is removed
+        ByteChunk res = new ByteChunk();
+        int sc = getUrl("http://localhost:" + getPort() + "/test/jsp.jsp", res, null);
+        Assert.assertEquals(200, sc);
+        Assert.assertEquals("OK", res.toString());
+
+        res = new ByteChunk();
+        sc = getUrl("http://localhost:" + getPort() + "/test/other.jsp", res, null);
+        Assert.assertEquals(200, sc);
+        Assert.assertEquals("OK", res.toString());
+    }
+
+    @Test
+    public void testRootPrefixNamespaceIsNotJspDocument() throws Exception {
+        // A namespace that only starts with the JSP namespace URI must not
+        // trigger parsing as a JSP document
+        Tomcat tomcat = getTomcatInstance();
+        File appDir = new File(getTemporaryDirectory(), "root-prefix");
+        Assert.assertTrue(appDir.mkdirs() || appDir.isDirectory());
+        Files.writeString(new File(appDir, "prefix.jsp").toPath(),
+                "<foo:root xmlns:foo=\"" + TagConstants.JSP_URI + "PageExtra\">\n" +
+                        "<p>hello</p>\n</foo:root>\n", StandardCharsets.UTF_8);
+
+        tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
+        tomcat.start();
+
+        ByteChunk res = new ByteChunk();
+        int sc = getUrl("http://localhost:" + getPort() + "/test/prefix.jsp", res, null);
+
+        Assert.assertEquals(200, sc);
+
+        // The page must be handled as standard syntax: the template text,
+        // including the line breaks written above, is output unchanged and no
+        // XML declaration is added
+        String result = res.toString();
+        Assert.assertTrue(result, result.contains("PageExtra\">\n<p>hello</p>"));
+        Assert.assertFalse(result, result.contains("<?xml"));
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 37/46: Store the Set tag plugin deferred value in the variable mapper

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 1e88dd946dfafbbf633f9e332ce4bce007e3fe3f
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 15:14:04 2026 +0200

    Store the Set tag plugin deferred value in the variable mapper
    
    When the value attribute of c:set with a var is a deferred expression
    (#{...}), the generated code hands the tag a value expression object
    rather than a value, as required by the deferred-value declaration of
    the tag. The plugin stored that object itself as the scoped attribute,
    so referencing the variable rendered the toString of the expression
    object instead of its lazily evaluated result, and setting the variable
    to null could not remove it. It also accepted a deferred value in any
    scope, while the standard handler requires the page scope for one.
    
    The var branch now mirrors the handler: a value expression is exported
    through the variable mapper of the EL context, any other scope is
    rejected for it, and mapper entries are removed when a plain value or a
    null takes the place of a deferred one, so no mapping shadows the
    attribute that is set or removed instead.
---
 .../apache/jasper/tagplugins/jstl/core/Set.java    | 30 +++++++++++++++--
 .../jasper/tagplugins/jstl/core/TestSet.java       | 38 +++++++++++++++++++++
 test/webapp/jstl/set-deferred.jsp                  | 39 ++++++++++++++++++++++
 webapps/docs/changelog.xml                         | 11 ++++++
 4 files changed, 115 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Set.java b/java/org/apache/jasper/tagplugins/jstl/core/Set.java
index c6e2cd3442..e4af208be5 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Set.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Set.java
@@ -16,6 +16,8 @@
  */
 package org.apache.jasper.tagplugins.jstl.core;
 
+import jakarta.servlet.jsp.PageContext;
+
 import org.apache.jasper.compiler.tagplugin.TagPlugin;
 import org.apache.jasper.compiler.tagplugin.TagPluginContext;
 import org.apache.jasper.tagplugins.jstl.Util;
@@ -87,10 +89,32 @@ public class Set implements TagPlugin {
         // if the attribute var has been specified then assign the result to the var;
         if (hasVar) {
             String strVar = ctxt.getConstantAttribute("var");
-            ctxt.generateJavaSource("if(null != " + resultName + "){");
-            ctxt.generateJavaSource(
-                    "    " + jspCtxt + ".setAttribute(\"" + strVar + "\"," + resultName + "," + iScope + ");");
+            String varMapper = jspCtxt + ".getELContext().getVariableMapper()";
+            // A deferred value is passed as a value expression and is then
+            // exported as a mapping in the variable mapper, as the standard
+            // handler does; only the page scope can hold such a mapping.
+            ctxt.generateJavaSource("if(" + resultName +
+                    " instanceof jakarta.el.ValueExpression) {");
+            if (iScope == PageContext.PAGE_SCOPE) {
+                ctxt.generateJavaSource("    " + varMapper + ".setVariable(\"" + strVar +
+                        "\", (jakarta.el.ValueExpression) " + resultName + ");");
+            } else {
+                ctxt.generateJavaSource("    throw new JspTagException(\"Invalid scope for ValueExpression in " +
+                        "&lt;set&gt;. \\\"page\\\" scope is required but was \\\"" + strScope + "\\\"\");");
+            }
+            ctxt.generateJavaSource("} else if(null != " + resultName + "){");
+            // A mapping in the variable mapper would shadow the attribute
+            if (iScope == PageContext.PAGE_SCOPE) {
+                ctxt.generateJavaSource("    if(" + varMapper + ".resolveVariable(\"" + strVar + "\") != null) {");
+                ctxt.generateJavaSource("        " + varMapper + ".setVariable(\"" + strVar + "\", null);");
+                ctxt.generateJavaSource("    }");
+            }
+            ctxt.generateJavaSource("    " + jspCtxt + ".setAttribute(\"" + strVar + "\"," + resultName + "," +
+                    iScope + ");");
             ctxt.generateJavaSource("} else {");
+            ctxt.generateJavaSource("    if(" + varMapper + ".resolveVariable(\"" + strVar + "\") != null) {");
+            ctxt.generateJavaSource("        " + varMapper + ".setVariable(\"" + strVar + "\", null);");
+            ctxt.generateJavaSource("    }");
             if (hasScope) {
                 ctxt.generateJavaSource("    " + jspCtxt + ".removeAttribute(\"" + strVar + "\"," + iScope + ");");
             } else {
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java b/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java
index 07e57e7cf7..000e3e255c 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestSet.java
@@ -51,4 +51,42 @@ public class TestSet extends AbstractTestTag {
         String body = res.toString();
         Assert.assertTrue(body.contains("OK - 42"));
     }
+
+
+    /*
+     * A deferred value expression on a c:set with var is stored as a
+     * mapping in the variable mapper of the EL context, not as an
+     * attribute, so later expressions evaluate it lazily. Only the page
+     * scope can hold such a mapping.
+     */
+    @Test
+    public void testDeferredValue() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/set-deferred.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        // The deferred value evaluates lazily when it is referenced, and is
+        // not kept as an attribute
+        Assert.assertTrue(body, body.contains("DEFERRED=[2]"));
+        Assert.assertTrue(body, body.contains("ATTR=[null]"));
+        // An explicit page scope behaves the same way
+        Assert.assertTrue(body, body.contains("EXPLICIT=[2]"));
+        // Setting the variable again replaces the mapping
+        Assert.assertTrue(body, body.contains("REPLACE=[3]"));
+        // A later plain value replaces the deferred one
+        Assert.assertTrue(body, body.contains("FIRST=[lazy]"));
+        Assert.assertTrue(body, body.contains("SECOND=[plain]"));
+        // A null value removes the variable, deferred or not
+        Assert.assertTrue(body, body.contains("THIRD=[]"));
+        // A deferred value in another scope fails
+        Assert.assertTrue(body, body.contains("ERR=[threw]"));
+        Assert.assertTrue(body,
+                body.contains("ERRMSG=[Invalid scope for ValueExpression in &lt;set&gt;. "
+                        + "\"page\" scope is required but was \"request\"]"));
+        Assert.assertTrue(body, body.contains("ERR2=[threw]"));
+    }
 }
diff --git a/test/webapp/jstl/set-deferred.jsp b/test/webapp/jstl/set-deferred.jsp
new file mode 100644
index 0000000000..fc969a9cc5
--- /dev/null
+++ b/test/webapp/jstl/set-deferred.jsp
@@ -0,0 +1,39 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:set var="d" value="#{1+1}" />
+<p>DEFERRED=[${d}]</p>
+<% out.print("ATTR=[" + pageContext.getAttribute("d") + "]"); %>
+<c:set var="d5" value="#{2}" scope="page" />
+<p>EXPLICIT=[${d5}]</p>
+<c:set var="d6" value="#{1}" />
+<c:set var="d6" value="#{3}" />
+<p>REPLACE=[${d6}]</p>
+<c:set var="d2" value="#{'lazy'}" />
+<p>FIRST=[${d2}]</p>
+<c:set var="d2" value="plain" />
+<p>SECOND=[${d2}]</p>
+<c:set var="d3" value="#{'gone'}" />
+<c:set var="d3" value="${null}" />
+<p>THIRD=[${d3}]</p>
+<c:catch var="err"><c:set var="d4" value="#{1+1}" scope="request" /></c:catch>
+<p>ERR=[${err ne null ? 'threw' : 'silent'}]</p>
+<p>ERRMSG=[${err.message}]</p>
+<c:catch var="err2"><c:set var="d7" value="#{1+1}" scope="session" /></c:catch>
+<p>ERR2=[${err2 ne null ? 'threw' : 'silent'}]</p>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 7c6798263a..bc4a623f0c 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -459,6 +459,17 @@
         inline, including its surrounding whitespace, and did not escape
         the body content. (remm)
       </fix>
+      <fix>
+        The tag plugin for <code>c:set</code> now handles a deferred value
+        expression (<code>#{...}</code>) with a <code>var</code> attribute
+        like the standard tag handler does. Such a value is passed to the
+        tag as a value expression object, and it is now stored as a mapping
+        in the variable mapper of the EL context, where it evaluates
+        lazily, rather than being stored as an attribute holding the raw
+        expression object. As in the standard handler, a non-page scope is
+        rejected for a deferred value, and mappings that would shadow a
+        plain attribute are removed. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 29/46: Resolve JspC resources whose path contains URI-illegal characters

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit dad31835dbb9947a6800c22f2be941e4248e473f
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 12:26:56 2026 +0200

    Resolve JspC resources whose path contains URI-illegal characters
    
    JspCServletContext.getResource() built the resource URI by raw string
    concatenation of the encoded base URL and the decoded logical resource
    path. Any path containing characters that are not permitted in a URI,
    for example a space or a non-ASCII character, produced a
    URISyntaxException that was swallowed by a catch-all, so the resource
    was silently reported as not found and JspC failed with a confusing
    resource not found error, even though the same application resolved and
    compiled fine at runtime.
    
    Percent-encode each segment of the path before appending it to the base
    URL, matching the behaviour of the runtime container. With that in
    place, only an IOException (openStream failing or a malformed URL) and
    a URISyntaxException indicate a missing resource, so the catch-all that
    previously converted any Throwable, including Errors, into a null
    result could be narrowed. Add a unit test with a space and a non-ASCII
    character in the resource name.
    
    Found by code review.
---
 .../apache/jasper/servlet/JspCServletContext.java  | 37 ++++++++++++++++--
 .../jasper/servlet/TestJspCServletContext.java     | 44 ++++++++++++++++++++++
 2 files changed, 78 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/jasper/servlet/JspCServletContext.java b/java/org/apache/jasper/servlet/JspCServletContext.java
index e875855b48..0f967958ed 100644
--- a/java/org/apache/jasper/servlet/JspCServletContext.java
+++ b/java/org/apache/jasper/servlet/JspCServletContext.java
@@ -24,6 +24,8 @@ import java.net.MalformedURLException;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -319,12 +321,17 @@ public class JspCServletContext implements ServletContext {
 
         URL url;
         try {
-            URI uri = new URI(myResourceBaseURL.toExternalForm() + path);
+            // The path is a decoded logical path. Percent-encode it before
+            // appending it to the (already encoded) base URL so that
+            // resources whose name contains characters that are not
+            // permitted in a URI, for example a space, can be resolved, as
+            // they are by the runtime container.
+            URI uri = new URI(myResourceBaseURL.toExternalForm() + encodePath(path));
             url = uri.toURL();
             try (InputStream is = url.openStream()) {
             }
-        } catch (Throwable t) {
-            ExceptionUtils.handleThrowable(t);
+        } catch (IOException | URISyntaxException e) {
+            // The resource does not exist or the URL could not be built.
             url = null;
         }
 
@@ -346,6 +353,30 @@ public class JspCServletContext implements ServletContext {
     }
 
 
+    /*
+     * Percent-encodes each segment of the given decoded resource path so the
+     * result can be appended to an already encoded base URL.
+     */
+    private static String encodePath(String path) {
+        StringBuilder result = new StringBuilder(path.length());
+        int start = 0;
+        for (;;) {
+            int slash = path.indexOf('/', start);
+            String segment = slash < 0 ? path.substring(start) : path.substring(start, slash);
+            // URLEncoder implements form encoding. It uses '+' for a space,
+            // which is not equivalent in a path segment. A literal '+' in the
+            // input is encoded as "%2B", so any '+' in the output is a space.
+            result.append(URLEncoder.encode(segment, StandardCharsets.UTF_8).replace("+", "%20"));
+            if (slash < 0) {
+                break;
+            }
+            result.append('/');
+            start = slash + 1;
+        }
+        return result.toString();
+    }
+
+
     @Override
     public InputStream getResourceAsStream(String path) {
         try {
diff --git a/test/org/apache/jasper/servlet/TestJspCServletContext.java b/test/org/apache/jasper/servlet/TestJspCServletContext.java
index cc0032e099..a61d82d484 100644
--- a/test/org/apache/jasper/servlet/TestJspCServletContext.java
+++ b/test/org/apache/jasper/servlet/TestJspCServletContext.java
@@ -17,6 +17,10 @@
 package org.apache.jasper.servlet;
 
 import java.io.File;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.Set;
@@ -153,6 +157,46 @@ public class TestJspCServletContext {
     }
 
 
+    @Test
+    public void testGetResourceWithUriIllegalCharacters() throws Exception {
+        // A resource path is a decoded logical path. Resources whose name
+        // contains characters that are not permitted in a URI, for example a
+        // space or a non-ASCII character, resolve correctly at runtime so
+        // they must also resolve for the offline compiler rather than be
+        // silently reported as not found.
+        File docBase = Files.createTempDirectory("jspc-illegal-chars").toFile();
+        try {
+            Files.writeString(new File(docBase, "my file.jsp").toPath(),
+                    "<jsp/>", StandardCharsets.UTF_8);
+            Files.writeString(new File(docBase, "unicode-\u00fc.jsp").toPath(),
+                    "<jsp/>", StandardCharsets.UTF_8);
+            JspCServletContext context = new JspCServletContext(
+                    null, docBase.toURI().toURL(), null, false, false);
+
+            URL url = context.getResource("/my file.jsp");
+            Assert.assertNotNull(url);
+            try (InputStream is = url.openStream()) {
+                Assert.assertEquals("<jsp/>",
+                        new String(is.readAllBytes(), StandardCharsets.UTF_8));
+            }
+            Assert.assertNotNull(context.getResource("/unicode-\u00fc.jsp"));
+        } finally {
+            deleteRecursively(docBase);
+        }
+    }
+
+
+    private static void deleteRecursively(File file) {
+        File[] children = file.listFiles();
+        if (children != null) {
+            for (File child : children) {
+                deleteRecursively(child);
+            }
+        }
+        Assert.assertTrue(file.delete());
+    }
+
+
     @Test
     public void testResourceJARs() throws Exception {
         File appDir = new File("test/webapp-fragments");


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 45/46: Match duplicate page directive attribute names exactly

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 9e7d4a6a7a901f51e6fd826a377ed5d6d1c259c2
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 17:11:48 2026 +0200

    Match duplicate page directive attribute names exactly
    
    handleDuplicate() tested import and pageEncoding case-insensitively
    although duplicates are only ever detected for the exact qname string,
    so a differently cased repeat such as Import reached the import merge
    branch where the exact-name lookup found no attribute and the merge
    threw ArrayIndexOutOfBoundsException for index -1 instead of reporting
    a duplicate name.
    
    Compare the constants exactly. A differently cased repeat is a
    different attribute per the XML qname rules and now follows the
    ordinary duplicate rules; the exact comparison still covers every
    attribute the merge branch can legitimately receive, since a detected
    duplicate always leaves the exact qname in the store.
    
    Add a test for the rejected, differently cased repeat.
    
    Found by code review.
---
 .../apache/jasper/util/UniqueAttributesImpl.java    |  7 +++++--
 .../jasper/util/TestUniqueAttributesImpl.java       | 21 +++++++++++++++++++++
 2 files changed, 26 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/util/UniqueAttributesImpl.java b/java/org/apache/jasper/util/UniqueAttributesImpl.java
index 174a94a819..aa809f50ad 100644
--- a/java/org/apache/jasper/util/UniqueAttributesImpl.java
+++ b/java/org/apache/jasper/util/UniqueAttributesImpl.java
@@ -131,14 +131,17 @@ public class UniqueAttributesImpl extends AttributesImpl {
     }
 
     private void handleDuplicate(String qName, String value, AttributesImpl store) {
+        // Duplicates are tracked by exact qname, so act on the exact qnames
+        // here too; a differently cased repeat of import or pageEncoding is a
+        // different attribute and follows the ordinary rules below
         if (pageDirective) {
-            if (IMPORT.equalsIgnoreCase(qName)) {
+            if (IMPORT.equals(qName)) {
                 // Always merge imports
                 int i = store.getIndex(IMPORT);
                 String v = store.getValue(i);
                 store.setValue(i, v + "," + value);
                 return;
-            } else if (PAGE_ENCODING.equalsIgnoreCase(qName)) {
+            } else if (PAGE_ENCODING.equals(qName)) {
                 // Page encoding can only occur once per file so a second
                 // attribute - even one with a duplicate value - is an error
             } else {
diff --git a/test/org/apache/jasper/util/TestUniqueAttributesImpl.java b/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
index ea46f43d1b..74f3c35215 100644
--- a/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
+++ b/test/org/apache/jasper/util/TestUniqueAttributesImpl.java
@@ -249,4 +249,25 @@ public class TestUniqueAttributesImpl {
         Assert.assertEquals(1, attrs.getLength());
         Assert.assertEquals("1", attrs.getValue("foo"));
     }
+
+
+    /*
+     * Names are tracked exactly, so a repeated, differently cased import is
+     * not the mergeable page directive import attribute and must be rejected
+     * like any other duplicate name rather than causing an internal error.
+     */
+    @Test
+    public void testDifferentlyCasedImportRepeatRejected() throws Exception {
+        UniqueAttributesImpl attrs = new UniqueAttributesImpl(true);
+
+        attrs.addAttribute("", "Import", "Import", "CDATA", "a");
+
+        try {
+            attrs.addAttribute("", "Import", "Import", "CDATA", "b");
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+        Assert.assertEquals(1, attrs.getLength());
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 25/46: Avoid NullPointerException releasing a PageContext when the pool size changed

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 6fe39d64b6d05d05a71cd905c9e158cffebaf4c4
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 11:33:38 2026 +0200

    Avoid NullPointerException releasing a PageContext when the pool
    size changed
    
    JspFactoryImpl is installed as the JVM-wide default JspFactory while
    its pool size is set per web application at startup. The per-thread
    PageContext pool is created by getPageContext only when pooling is
    enabled at that moment, but releasePageContext dereferenced the thread
    local pool unconditionally whenever pooling was enabled at release
    time. A thread that obtained a PageContext while pooling was disabled
    and released it after the shared pool size was increased (a second web
    application with pooling enabled started in between) threw a
    NullPointerException from the release, failing the request.
    
    Return the context to the pool only when the current thread actually
    has one, and make poolSize volatile since it is written by web
    application start threads and read by request threads without
    synchronization.
    
    Found by code review.
---
 java/org/apache/jasper/runtime/JspFactoryImpl.java | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/runtime/JspFactoryImpl.java b/java/org/apache/jasper/runtime/JspFactoryImpl.java
index 7b61fec7ca..9e6d753c1e 100644
--- a/java/org/apache/jasper/runtime/JspFactoryImpl.java
+++ b/java/org/apache/jasper/runtime/JspFactoryImpl.java
@@ -44,7 +44,7 @@ public class JspFactoryImpl extends JspFactory {
     }
 
     private final ThreadLocal<PageContextPool> localPool = new ThreadLocal<>();
-    private int poolSize = -1;
+    private volatile int poolSize = -1;
 
     @Override
     public PageContext getPageContext(Servlet servlet, ServletRequest request, ServletResponse response,
@@ -118,7 +118,14 @@ public class JspFactoryImpl extends JspFactory {
     private void internalReleasePageContext(PageContext pc) {
         pc.release();
         if (poolSize > 0 && (pc instanceof PageContextImpl)) {
-            localPool.get().put(pc);
+            // The thread local pool is only created by getPageContext() when
+            // pooling is enabled at that moment. The pool size may be changed
+            // (by the start of another web application) after this context was
+            // obtained on this thread, leaving the pool null here.
+            PageContextPool pool = localPool.get();
+            if (pool != null) {
+                pool.put(pc);
+            }
         }
     }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 42/46: Avoid NullPointerException rendering a null entry

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit bd9e004a37ac0eabef04aa9ba965e0fb216469e6
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 16:39:20 2026 +0200

    Avoid NullPointerException rendering a null entry
    
    Pushing null content to a FastRemovalDequeue was accepted but the
    Entry created for it rendered its content with a direct toString call,
    so converting the entry to a string failed with a null pointer
    exception. The JDK collections render a null element as the string
    null rather than failing, and the class javadoc treats the stored
    values as the caller's concern, so render the content with
    String.valueOf and pin the rendering of a null entry with a test.
    
    Found by code review.
---
 java/org/apache/jasper/util/FastRemovalDequeue.java     |  2 +-
 test/org/apache/jasper/util/TestFastRemovalDequeue.java | 15 +++++++++++++++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/util/FastRemovalDequeue.java b/java/org/apache/jasper/util/FastRemovalDequeue.java
index 35dfe2b436..1768ecc61b 100644
--- a/java/org/apache/jasper/util/FastRemovalDequeue.java
+++ b/java/org/apache/jasper/util/FastRemovalDequeue.java
@@ -323,7 +323,7 @@ public class FastRemovalDequeue<T> {
 
         @Override
         public String toString() {
-            return "Entry-" + content.toString();
+            return "Entry-" + String.valueOf(content);
         }
     }
 
diff --git a/test/org/apache/jasper/util/TestFastRemovalDequeue.java b/test/org/apache/jasper/util/TestFastRemovalDequeue.java
index 237b571fef..5834dbf2da 100644
--- a/test/org/apache/jasper/util/TestFastRemovalDequeue.java
+++ b/test/org/apache/jasper/util/TestFastRemovalDequeue.java
@@ -241,6 +241,21 @@ public class TestFastRemovalDequeue {
     }
 
 
+    /*
+     * The rendering of an entry must tolerate null content, as the JDK
+     * collections render null elements, rather than fail with a null pointer
+     * exception.
+     */
+    @Test
+    public void testNullContentToString() throws Exception {
+        FastRemovalDequeue<Object> q = new FastRemovalDequeue<>(2);
+
+        FastRemovalDequeue<Object>.Entry e = q.push(null);
+
+        Assert.assertEquals("Entry-null", e.toString());
+    }
+
+
     /*
      * A maximum size below one cannot produce a usable queue and is
      * rejected, rather than silently replaced by a different size.


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 40/46: Share the Url and Redirect tag plugin URLs with their params

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 64c4b06524536d7f9825c69f34ff13c50dccca66
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 16:27:19 2026 +0200

    Share the Url and Redirect tag plugin URLs with their params
    
    The Url and Redirect tag plugins exchanged the working URL of the tag
    with the Param plugin through the page scope attribute
    url_without_param: the URL plugin wrote the attribute before generating
    the tag body, the Param plugin read it back, appended to it and wrote
    it again, and the URL plugin finally read it back and removed it. The
    fixed name overwrote any application page attribute of the same name
    while the body was processed and removed it at the end. It also let
    nested URL tags interfere: a c:url nested in the body of a plugin
    enabled c:url, a nesting the JSTL tag library validator accepts,
    removed the attribute, so the outer tag read null and silently rendered
    the literal string null.
    
    Share the name of the generated local variable that holds the working
    URL through the plugin context instead, the mechanism the Choose plugin
    already uses and that the Import plugin adopted earlier. The Param
    plugin appends directly to that variable and looks for the closest URL
    tag ancestor by walking up the parent context chain, as the standard
    handler at runtime walks up the tag ancestors, so a parameter nested
    within an intermediate tag still reaches the URL of its enclosing URL
    tag. A parent context whose tag abandoned the plugin ends the search,
    since the body of such a tag is generated in a separate method of the
    generated servlet where the outer local variables are out of scope;
    the parameter then falls back to the standard handler. This matches the
    reference implementation, which keeps the parameters of each tag to
    itself through a per-tag parameter manager and never touches page scope
    attributes. Add tests for the nested and clobbering pages, the
    parameters of both URL plugins, parameters nested in a plugin
    processed or a fallen back tag, and the closest ancestor semantics.
    
    Found by code review.
---
 .../apache/jasper/compiler/TagPluginManager.java   |   9 ++
 .../compiler/tagplugin/TagPluginContext.java       |   5 +-
 .../apache/jasper/tagplugins/jstl/core/Import.java |   4 +-
 .../apache/jasper/tagplugins/jstl/core/Param.java  |  38 +++----
 .../jasper/tagplugins/jstl/core/Redirect.java      |  19 ++--
 .../apache/jasper/tagplugins/jstl/core/Url.java    |  21 ++--
 .../jasper/tagplugins/jstl/core/TestRedirect.java  |  27 +++++
 .../jasper/tagplugins/jstl/core/TestUrl.java       | 113 +++++++++++++++++++++
 .../tagplugins/jstl/core/redirect-tagPlugins.xml   |   4 +
 .../jasper/tagplugins/jstl/core/url-tagPlugins.xml |  12 +++
 test/webapp/jstl/redirect-params.jsp               |  22 ++++
 test/webapp/jstl/url-clobber.jsp                   |  23 +++++
 test/webapp/jstl/url-nested.jsp                    |  20 ++++
 test/webapp/jstl/url-param-fallback-nested.jsp     |  22 ++++
 test/webapp/jstl/url-param-nested-if.jsp           |  25 +++++
 test/webapp/jstl/url-params.jsp                    |  22 ++++
 webapps/docs/changelog.xml                         |  12 +++
 17 files changed, 359 insertions(+), 39 deletions(-)

diff --git a/java/org/apache/jasper/compiler/TagPluginManager.java b/java/org/apache/jasper/compiler/TagPluginManager.java
index f499327c51..867ceb9f7e 100644
--- a/java/org/apache/jasper/compiler/TagPluginManager.java
+++ b/java/org/apache/jasper/compiler/TagPluginManager.java
@@ -192,6 +192,15 @@ public class TagPluginManager {
 
         @Override
         public TagPluginContext getParentContext() {
+            // If the tag of this context no longer uses the plugin, its body
+            // is generated by the standard tag mechanism, which places
+            // scriptless body content in a separate method of the generated
+            // servlet. The local variables of the outer tags are then out of
+            // scope inside that body, so do not let a child walk through this
+            // context into an outer scope.
+            if (!node.useTagPlugin()) {
+                return null;
+            }
             Node parent = node.getParent();
             if (!(parent instanceof Node.CustomTag)) {
                 return null;
diff --git a/java/org/apache/jasper/compiler/tagplugin/TagPluginContext.java b/java/org/apache/jasper/compiler/tagplugin/TagPluginContext.java
index 519c732f3d..e17897e1f1 100644
--- a/java/org/apache/jasper/compiler/tagplugin/TagPluginContext.java
+++ b/java/org/apache/jasper/compiler/tagplugin/TagPluginContext.java
@@ -111,8 +111,9 @@ public interface TagPluginContext {
      * obtained is limited to getPluginAttribute and setPluginAttribute, and queries (e.g. isScriptless()). There should
      * be no calls to generate*().
      *
-     * @return The pluginContext for the parent node. null if the parent is not a custom tag, or if the parent custom
-     *             tag has no plugin context.
+     * @return The pluginContext for the parent node. null if the parent is not a custom tag, if the parent custom tag
+     *             has no plugin context, or if the tag associated with this context has abandoned the plugin, in which
+     *             case the body is not generated inline and the scopes of the generated code are disconnected.
      */
     TagPluginContext getParentContext();
 
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Import.java b/java/org/apache/jasper/tagplugins/jstl/core/Import.java
index 706cb48fb1..e4d2ca2dc4 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Import.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Import.java
@@ -31,7 +31,9 @@ public class Import implements TagPlugin {
      * the generated local variable that holds the URL and to which the
      * parameters are appended. Sharing the variable rather than a page scope
      * attribute with a fixed name makes the protocol re-entrant: a nested URL
-     * tag in the body cannot overwrite or remove the outer tag's URL.
+     * tag in the body cannot overwrite or remove the outer tag's URL. The
+     * Param plugin walks up the parent context chain, so a parameter nested
+     * in an intermediate tag finds the closest URL tag ancestor.
      */
     static final String URL_VARIABLE_ATTRIBUTE = "urlVariable";
 
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Param.java b/java/org/apache/jasper/tagplugins/jstl/core/Param.java
index 76e0d680f4..0cf10748d9 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Param.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Param.java
@@ -40,7 +40,6 @@ public class Param implements TagPlugin {
         // define names of all the temp variables
         String nameName = ctxt.getTemporaryVariableName();
         String valueName = ctxt.getTemporaryVariableName();
-        String urlName = ctxt.getTemporaryVariableName();
         String encName = ctxt.getTemporaryVariableName();
         String index = ctxt.getTemporaryVariableName();
 
@@ -52,20 +51,28 @@ public class Param implements TagPlugin {
             return;
         }
 
-        // Append the parameter to the parent tag's working URL. The Import
-        // plugin shares the name of the local variable holding that URL
-        // through the plugin context, so that nested URL tags cannot
-        // interfere with it through a shared page scope attribute. The Url
-        // and Redirect plugins still use such an attribute.
-        Object urlVariable = parent.getPluginAttribute(Import.URL_VARIABLE_ATTRIBUTE);
-        String urlTargetName;
-        if (urlVariable != null) {
-            urlTargetName = (String) urlVariable;
-        } else {
-            ctxt.generateJavaSource(
-                    "String " + urlName + " = " + "(String)_jspx_page_context.getAttribute(\"url_without_param\");");
-            urlTargetName = urlName;
+        // Append the parameter to the working URL of the enclosing URL tag.
+        // The Import, Url and Redirect plugins share the name of the local
+        // variable holding that URL through the plugin context, so that
+        // nested URL tags cannot interfere with each other through a shared
+        // page scope attribute. As in the standard handler, which at runtime
+        // adds the parameter to the closest URL tag ancestor, the search
+        // walks up the plugin context chain until a context provides the
+        // working URL, stopping at parents that no plugin handled.
+        TagPluginContext urlContext = parent;
+        while (urlContext != null &&
+                urlContext.getPluginAttribute(Import.URL_VARIABLE_ATTRIBUTE) == null) {
+            urlContext = urlContext.getParentContext();
+        }
+        if (urlContext == null) {
+            // No plugin handled an enclosing URL tag, so there is no working
+            // URL variable to append to. Let the standard tag handler process
+            // the parameter. A standard URL tag then takes it as usual, and
+            // the handler reports the error for a misplaced tag.
+            ctxt.dontUseTagPlugin();
+            return;
         }
+        String urlTargetName = (String) urlContext.getPluginAttribute(Import.URL_VARIABLE_ATTRIBUTE);
 
         // get the value of "name"
         ctxt.generateJavaSource("String " + nameName + " = ");
@@ -97,9 +104,6 @@ public class Param implements TagPlugin {
         ctxt.generateJavaSource("        " + urlTargetName + " = " + urlTargetName + " + \"&\" + " + nameName +
                 " + \"=\" + " + valueName + ";");
         ctxt.generateJavaSource("    }");
-        if (urlVariable == null) {
-            ctxt.generateJavaSource("    _jspx_page_context.setAttribute(\"url_without_param\"," + urlName + ");");
-        }
         ctxt.generateJavaSource("}");
     }
 }
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Redirect.java b/java/org/apache/jasper/tagplugins/jstl/core/Redirect.java
index fabad2c995..59e0069d09 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Redirect.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Redirect.java
@@ -41,7 +41,6 @@ public class Redirect implements TagPlugin {
         String urlName = ctxt.getTemporaryVariableName();
         String contextName = ctxt.getTemporaryVariableName();
         String baseUrlName = ctxt.getTemporaryVariableName();
-        String resultName = ctxt.getTemporaryVariableName();
         String responseName = ctxt.getTemporaryVariableName();
 
         // get context
@@ -60,27 +59,29 @@ public class Redirect implements TagPlugin {
         // get the raw url according to "url" and "context"
         ctxt.generateJavaSource("String " + baseUrlName + " = " + "org.apache.jasper.tagplugins.jstl.Util.resolveUrl(" +
                 urlName + ", " + contextName + ", _jspx_page_context);");
-        ctxt.generateJavaSource("_jspx_page_context.setAttribute" + "(\"url_without_param\", " + baseUrlName + ");");
+
+        // Share the working URL with the <c:param> tags in the body by
+        // handing them the name of the local variable that holds it.
+        // Appending to the variable directly is re-entrant: a nested URL tag
+        // in the body of this tag must not be able to overwrite or remove it,
+        // which a page scope attribute with a fixed name would allow.
+        ctxt.setPluginAttribute(Import.URL_VARIABLE_ATTRIBUTE, baseUrlName);
 
         // add params
         ctxt.generateBody();
 
-        ctxt.generateJavaSource(
-                "String " + resultName + " = " + "(String)_jspx_page_context.getAttribute(\"url_without_param\");");
-        ctxt.generateJavaSource("_jspx_page_context.removeAttribute" + "(\"url_without_param\");");
-
         // get the response object
         ctxt.generateJavaSource("HttpServletResponse " + responseName + " = " +
                 "((HttpServletResponse) _jspx_page_context.getResponse());");
 
         // if the url is relative, encode it
-        ctxt.generateJavaSource("if(!org.apache.jasper.tagplugins.jstl.Util.isAbsoluteUrl(" + resultName + ")){");
-        ctxt.generateJavaSource("    " + resultName + " = " + responseName + ".encodeRedirectURL(" + resultName + ");");
+        ctxt.generateJavaSource("if(!org.apache.jasper.tagplugins.jstl.Util.isAbsoluteUrl(" + baseUrlName + ")){");
+        ctxt.generateJavaSource("    " + baseUrlName + " = " + responseName + ".encodeRedirectURL(" + baseUrlName + ");");
         ctxt.generateJavaSource("}");
 
         // do redirect
         ctxt.generateJavaSource("try{");
-        ctxt.generateJavaSource("    " + responseName + ".sendRedirect(" + resultName + ");");
+        ctxt.generateJavaSource("    " + responseName + ".sendRedirect(" + baseUrlName + ");");
         // Avoid unreachable code error in compiler
         ctxt.generateJavaSource("    if (true) {");
         ctxt.generatePageTermination();
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Url.java b/java/org/apache/jasper/tagplugins/jstl/core/Url.java
index 8772218a75..198b211f2e 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Url.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Url.java
@@ -46,7 +46,6 @@ public class Url implements TagPlugin {
         String valueName = ctxt.getTemporaryVariableName();
         String contextName = ctxt.getTemporaryVariableName();
         String baseUrlName = ctxt.getTemporaryVariableName();
-        String resultName = ctxt.getTemporaryVariableName();
         String responseName = ctxt.getTemporaryVariableName();
 
         // get the scope
@@ -72,32 +71,34 @@ public class Url implements TagPlugin {
         // get the raw url
         ctxt.generateJavaSource("String " + baseUrlName + " = " + "org.apache.jasper.tagplugins.jstl.Util.resolveUrl(" +
                 valueName + ", " + contextName + ", _jspx_page_context);");
-        ctxt.generateJavaSource("_jspx_page_context.setAttribute" + "(\"url_without_param\", " + baseUrlName + ");");
+
+        // Share the working URL with the <c:param> tags in the body by
+        // handing them the name of the local variable that holds it.
+        // Appending to the variable directly is re-entrant: a nested URL tag
+        // in the body of this tag must not be able to overwrite or remove it,
+        // which a page scope attribute with a fixed name would allow.
+        ctxt.setPluginAttribute(Import.URL_VARIABLE_ATTRIBUTE, baseUrlName);
 
         // add params
         ctxt.generateBody();
 
-        ctxt.generateJavaSource(
-                "String " + resultName + " = " + "(String)_jspx_page_context.getAttribute(\"url_without_param\");");
-        ctxt.generateJavaSource("_jspx_page_context.removeAttribute(\"url_without_param\");");
-
         // if the url is relative, encode it
-        ctxt.generateJavaSource("if(!org.apache.jasper.tagplugins.jstl.Util.isAbsoluteUrl(" + resultName + ")){");
+        ctxt.generateJavaSource("if(!org.apache.jasper.tagplugins.jstl.Util.isAbsoluteUrl(" + baseUrlName + ")){");
         ctxt.generateJavaSource("    HttpServletResponse " + responseName + " = " +
                 "((HttpServletResponse) _jspx_page_context.getResponse());");
-        ctxt.generateJavaSource("    " + resultName + " = " + responseName + ".encodeURL(" + resultName + ");");
+        ctxt.generateJavaSource("    " + baseUrlName + " = " + responseName + ".encodeURL(" + baseUrlName + ");");
         ctxt.generateJavaSource("}");
 
         // if "var" is specified, the url string is stored in the attribute var
         if (hasVar) {
             String strVar = ctxt.getConstantAttribute("var");
             ctxt.generateJavaSource(
-                    "_jspx_page_context.setAttribute" + "(\"" + strVar + "\", " + resultName + ", " + iScope + ");");
+                    "_jspx_page_context.setAttribute" + "(\"" + strVar + "\", " + baseUrlName + ", " + iScope + ");");
 
             // if var is not specified, just print out the url string
         } else {
             ctxt.generateJavaSource("try{");
-            ctxt.generateJavaSource("    _jspx_page_context.getOut().print(" + resultName + ");");
+            ctxt.generateJavaSource("    _jspx_page_context.getOut().print(" + baseUrlName + ");");
             ctxt.generateJavaSource("}catch(java.io.IOException ex){");
             ctxt.generateJavaSource("    throw new JspTagException(ex.toString(), ex);");
             ctxt.generateJavaSource("}");
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestRedirect.java b/test/org/apache/jasper/tagplugins/jstl/core/TestRedirect.java
index 99de0c16d1..473e3ca8c3 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestRedirect.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestRedirect.java
@@ -18,6 +18,9 @@ package org.apache.jasper.tagplugins.jstl.core;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -30,6 +33,7 @@ import org.junit.Assert;
 import org.junit.Test;
 
 import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.http.Method;
 
 public class TestRedirect extends AbstractTestTag {
 
@@ -107,4 +111,27 @@ public class TestRedirect extends AbstractTestTag {
         Assert.assertTrue(pageStarted.await(1, TimeUnit.SECONDS));
         Assert.assertFalse(pageProcessingContinued.await(1, TimeUnit.SECONDS));
     }
+
+
+    /*
+     * The <c:param> plugin must append its parameters, URL-encoded, to the
+     * working URL of the enclosing <c:redirect> tag. The plugins used to
+     * exchange that URL through the page scope attribute "url_without_param"
+     * which interfered with nested URL tags and application attributes of the
+     * same name. The URL is now shared through the plugin context instead.
+     */
+    @Test
+    public void testRedirectParams() throws Exception {
+        ByteChunk res = new ByteChunk();
+        Map<String, List<String>> resHead = new HashMap<>();
+
+        int rc = methodUrl("http://localhost:" + getPort() + "/test/jstl/redirect-params.jsp", res,
+                DEFAULT_CLIENT_TIMEOUT_MS, null, resHead, Method.GET, false);
+
+        Assert.assertEquals(HttpServletResponse.SC_FOUND, rc);
+
+        String location = getSingleHeader("Location", resHead);
+        Assert.assertNotNull(location);
+        Assert.assertTrue(location, location.endsWith("/test/jstl/redirect-target.jsp?a=b&sp=x+y&u=%26%3D"));
+    }
 }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java b/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java
index 3ac0d1c396..84ca506899 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java
@@ -56,4 +56,117 @@ public class TestUrl extends AbstractTestTag {
         // A context without a trailing slash is simply concatenated
         Assert.assertTrue(body, body.contains("PLAIN=[/jstltest/index.jsp]"));
     }
+
+
+    /*
+     * The <c:param> plugin must add its parameters to the URL of its own
+     * <c:url> tag, URL-encoded, the first one following an existing query
+     * string with "&".
+     */
+    @Test
+    public void testParams() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/url-params.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("U=[/test/a.jsp?x=1&sp=x+y&u2=%26%3D]"));
+    }
+
+
+    /*
+     * A nested <c:url> in the body of another <c:url> (a nesting the JSTL tag
+     * library validator accepts) must not disturb the outer tag. The plugins
+     * used to exchange the working URL through the fixed page scope attribute
+     * "url_without_param": the inner tag removed that attribute, so the outer
+     * tag read it back as null and printed the literal "null". The working URL
+     * is now shared with the body through the plugin context, so the inner tag
+     * cannot interfere with the outer one.
+     */
+    @Test
+    public void testNestedUrl() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/url-nested.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        // The inner tag renders its URL, then the outer tag renders its own,
+        // never the literal "null"
+        Assert.assertTrue(body, body.contains("NEXT=[/test/b.jsp/test/a.jsp]"));
+    }
+
+
+    /*
+     * The <c:url>/<c:param> plugin pair must not clobber an application page
+     * scope attribute named "url_without_param". The plugins used to store the
+     * working URL in such an attribute and remove it afterwards, overwriting
+     * and then deleting the application attribute. The URL is now shared with
+     * the body through the plugin context instead.
+     */
+    @Test
+    public void testParamKeepsUserAttribute() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/url-clobber.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("KEEP=[keepme]"));
+        // The parameter is still appended to the tag's own URL
+        Assert.assertTrue(body, body.contains("U=[/test/a.jsp?p=q]"));
+    }
+
+
+    /*
+     * A <c:param> nested in a plugin processed tag inside the <c:url> body,
+     * as the JSTL tag library validator allows, must still reach the working
+     * URL of the enclosing URL tag, as the standard handler adds it to the
+     * closest URL tag ancestor. The append must stay conditional on the
+     * enclosing tag having been executed.
+     */
+    @Test
+    public void testParamNestedInIf() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/url-param-nested-if.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        // The parameter of the executed <c:if> reaches the URL
+        Assert.assertTrue(body, body.contains("U=[/test/a.jsp?p=q]"));
+        // The parameter of the skipped <c:if> does not
+        Assert.assertTrue(body, body.contains("U2=[/test/a.jsp]"));
+    }
+
+
+    /*
+     * A <c:param> nested in a tag whose plugin falls back to the standard
+     * handler, as <c:forEach> with a varStatus, is generated into the tag
+     * method of that handler, where the working URL variable of an enclosing
+     * plugin URL tag is out of scope. The page must still translate; the
+     * standard parameter handler then reports that no standard URL tag
+     * encloses it.
+     */
+    @Test
+    public void testParamNestedInPluginFallback() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/url-param-fallback-nested.jsp", res, null);
+
+        String body = res.toString();
+        // The page must not fail at translation time
+        Assert.assertFalse(body, body.contains("Unable to compile"));
+        Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
+    }
 }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/redirect-tagPlugins.xml b/test/org/apache/jasper/tagplugins/jstl/core/redirect-tagPlugins.xml
index 94441bb2eb..610f944386 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/redirect-tagPlugins.xml
+++ b/test/org/apache/jasper/tagplugins/jstl/core/redirect-tagPlugins.xml
@@ -20,4 +20,8 @@
     <tag-class>org.apache.taglibs.standard.tag.rt.core.RedirectTag</tag-class>
     <plugin-class>org.apache.jasper.tagplugins.jstl.core.Redirect</plugin-class>
   </tag-plugin>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.ParamTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.Param</plugin-class>
+  </tag-plugin>
 </tag-plugins>
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml b/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml
index 55860d0587..6c22ed0665 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml
+++ b/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml
@@ -20,4 +20,16 @@
     <tag-class>org.apache.taglibs.standard.tag.rt.core.UrlTag</tag-class>
     <plugin-class>org.apache.jasper.tagplugins.jstl.core.Url</plugin-class>
   </tag-plugin>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.ParamTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.Param</plugin-class>
+  </tag-plugin>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.IfTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.If</plugin-class>
+  </tag-plugin>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.ForEachTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.ForEach</plugin-class>
+  </tag-plugin>
 </tag-plugins>
diff --git a/test/webapp/jstl/redirect-params.jsp b/test/webapp/jstl/redirect-params.jsp
new file mode 100644
index 0000000000..7c233b7ae8
--- /dev/null
+++ b/test/webapp/jstl/redirect-params.jsp
@@ -0,0 +1,22 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:redirect url="/jstl/redirect-target.jsp?a=b"><c:param name="sp"
+    value="x y"/><c:param name="u" value="${'&='}"/></c:redirect>
+<p>NOTREACHED=[]</p>
diff --git a/test/webapp/jstl/url-clobber.jsp b/test/webapp/jstl/url-clobber.jsp
new file mode 100644
index 0000000000..2bccf15413
--- /dev/null
+++ b/test/webapp/jstl/url-clobber.jsp
@@ -0,0 +1,23 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:set var="url_without_param" value="keepme" scope="page" />
+<c:url value="/a.jsp" var="u"><c:param name="p" value="q"/></c:url>
+<p>KEEP=[${url_without_param}]</p>
+<p>U=[${u}]</p>
diff --git a/test/webapp/jstl/url-nested.jsp b/test/webapp/jstl/url-nested.jsp
new file mode 100644
index 0000000000..36d82e930c
--- /dev/null
+++ b/test/webapp/jstl/url-nested.jsp
@@ -0,0 +1,20 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<p>NEXT=[<c:url value="/a.jsp"><c:url value="/b.jsp"/></c:url>]</p>
diff --git a/test/webapp/jstl/url-param-fallback-nested.jsp b/test/webapp/jstl/url-param-fallback-nested.jsp
new file mode 100644
index 0000000000..66a826f658
--- /dev/null
+++ b/test/webapp/jstl/url-param-fallback-nested.jsp
@@ -0,0 +1,22 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:url var="u" value="/a.jsp"><c:forEach var="i" varStatus="s"
+    begin="1" end="1"><c:param name="p" value="q"/></c:forEach></c:url>
+<p>U=[${u}]</p>
diff --git a/test/webapp/jstl/url-param-nested-if.jsp b/test/webapp/jstl/url-param-nested-if.jsp
new file mode 100644
index 0000000000..5155b4e514
--- /dev/null
+++ b/test/webapp/jstl/url-param-nested-if.jsp
@@ -0,0 +1,25 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:url var="u" value="/a.jsp"><c:if test="${true}"><c:param
+    name="p" value="q"/></c:if></c:url>
+<p>U=[${u}]</p>
+<c:url var="u2" value="/a.jsp"><c:if test="${false}"><c:param
+    name="p" value="q"/></c:if></c:url>
+<p>U2=[${u2}]</p>
diff --git a/test/webapp/jstl/url-params.jsp b/test/webapp/jstl/url-params.jsp
new file mode 100644
index 0000000000..f572ad70c9
--- /dev/null
+++ b/test/webapp/jstl/url-params.jsp
@@ -0,0 +1,22 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:url value="/a.jsp?x=1" var="u"><c:param name="sp"
+    value="x y"/><c:param name="u2" value="${'&='}"/></c:url>
+<p>U=[${u}]</p>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index a719cb403f..1ff8129618 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -485,6 +485,18 @@
         with a doubled slash. Previously only the root context was handled.
         (remm)
       </fix>
+      <fix>
+        The tag plugins for <code>c:url</code>, <code>c:redirect</code> and
+        <code>c:param</code> now share the working URL of the URL tag through
+        the plugin context rather than the page scope attribute
+        <code>url_without_param</code>. That fixed name overwrote an
+        application attribute of the same name while the tag body was
+        processed and removed it afterwards, and it let a nested URL tag
+        destroy the outer tag's URL, which then silently rendered as
+        <code>null</code>. This matches the reference implementation, which
+        keeps the parameters of each tag to itself and never touches page
+        scope attributes. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 04/46: Report compilation errors before removing the generated source

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 84ec9f78002b0eac9964dcf40a41faf022afab29
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 21:19:40 2026 +0200

    Report compilation errors before removing the generated source
    
    The JSP compiler backends deleted the generated servlet source when
    keepGenerated was false before dispatching the accumulated compiler
    diagnostics to the error handler. If the delete failed, the exception
    thrown for it masked the compilation errors that were the primary
    problem, leaving the user without any indication of why the JSP failed
    to compile.
    
    Dispatch the errors first, then remove the generated source. As a side
    effect, the generated source of a failed compilation is now retained
    for inspection, since dispatching the errors completes abruptly. This
    is safe: a subsequent compilation attempt always removes any retained
    generated source before regenerating it.
    
    Add TestJavaCompiler to verify that compilation errors are reported
    and the generated source is retained after a failed compilation.
---
 java/org/apache/jasper/compiler/AntCompiler.java   |  16 +--
 java/org/apache/jasper/compiler/JDTCompiler.java   |  12 ++-
 java/org/apache/jasper/compiler/JavaCompiler.java  |  12 ++-
 .../apache/jasper/compiler/TestJavaCompiler.java   | 114 +++++++++++++++++++++
 4 files changed, 137 insertions(+), 17 deletions(-)

diff --git a/java/org/apache/jasper/compiler/AntCompiler.java b/java/org/apache/jasper/compiler/AntCompiler.java
index a00f9f6ed2..2ba27feef5 100644
--- a/java/org/apache/jasper/compiler/AntCompiler.java
+++ b/java/org/apache/jasper/compiler/AntCompiler.java
@@ -260,13 +260,8 @@ public class AntCompiler extends Compiler {
             errorReport.append(errorCapture);
         }
 
-        if (!ctxt.keepGenerated()) {
-            File javaFile = new File(javaFileName);
-            if (!javaFile.delete()) {
-                throw new JasperException(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile));
-            }
-        }
-
+        // Dispatch any compilation errors before deleting the generated
+        // source, so a failure to delete can not mask the real problem
         if (be != null) {
             String errorReportString = errorReport.toString();
             log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString));
@@ -279,6 +274,13 @@ public class AntCompiler extends Compiler {
             }
         }
 
+        if (!ctxt.keepGenerated()) {
+            File javaFile = new File(javaFileName);
+            if (!javaFile.delete()) {
+                throw new JasperException(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile));
+            }
+        }
+
         if (log.isDebugEnabled()) {
             long t2 = System.currentTimeMillis();
             log.debug(Localizer.getMessage("jsp.compiled", ctxt.getServletJavaFileName(), Long.valueOf(t2 - t1)));
diff --git a/java/org/apache/jasper/compiler/JDTCompiler.java b/java/org/apache/jasper/compiler/JDTCompiler.java
index f49e5b61d0..cb7f52932c 100644
--- a/java/org/apache/jasper/compiler/JDTCompiler.java
+++ b/java/org/apache/jasper/compiler/JDTCompiler.java
@@ -581,6 +581,13 @@ public class JDTCompiler extends org.apache.jasper.compiler.Compiler {
         Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
         compiler.compile(compilationUnits);
 
+        // Dispatch any compilation problems before deleting the generated
+        // source, so a failure to delete can not mask the real problem
+        if (!problemList.isEmpty()) {
+            JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
+            errDispatcher.javacError(jeds);
+        }
+
         if (!ctxt.keepGenerated()) {
             File javaFile = new File(ctxt.getServletJavaFileName());
             if (!javaFile.delete()) {
@@ -588,11 +595,6 @@ public class JDTCompiler extends org.apache.jasper.compiler.Compiler {
             }
         }
 
-        if (!problemList.isEmpty()) {
-            JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
-            errDispatcher.javacError(jeds);
-        }
-
         if (log.isDebugEnabled()) {
             long t2 = System.currentTimeMillis();
             log.debug(Localizer.getMessage("jsp.compiled", ctxt.getServletJavaFileName(), Long.valueOf(t2 - t1)));
diff --git a/java/org/apache/jasper/compiler/JavaCompiler.java b/java/org/apache/jasper/compiler/JavaCompiler.java
index 86443ac761..c9ef655fc5 100644
--- a/java/org/apache/jasper/compiler/JavaCompiler.java
+++ b/java/org/apache/jasper/compiler/JavaCompiler.java
@@ -83,6 +83,13 @@ public class JavaCompiler extends Compiler {
                 }
             }
 
+            // Dispatch any compilation errors before deleting the generated
+            // source, so a failure to delete can not mask the real problem
+            if (!problemList.isEmpty()) {
+                JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
+                errDispatcher.javacError(jeds);
+            }
+
             if (!ctxt.keepGenerated()) {
                 File javaFile = new File(ctxt.getServletJavaFileName());
                 if (!javaFile.delete()) {
@@ -90,11 +97,6 @@ public class JavaCompiler extends Compiler {
                 }
             }
 
-            if (!problemList.isEmpty()) {
-                JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
-                errDispatcher.javacError(jeds);
-            }
-
             if (log.isDebugEnabled()) {
                 long t2 = System.currentTimeMillis();
                 log.debug(Localizer.getMessage("jsp.compiled", ctxt.getServletJavaFileName(), Long.valueOf(t2 - t1)));
diff --git a/test/org/apache/jasper/compiler/TestJavaCompiler.java b/test/org/apache/jasper/compiler/TestJavaCompiler.java
new file mode 100644
index 0000000000..452a37322d
--- /dev/null
+++ b/test/org/apache/jasper/compiler/TestJavaCompiler.java
@@ -0,0 +1,114 @@
+/*
+ * 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.jasper.compiler;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.jasper.JasperException;
+import org.apache.jasper.JspCompilationContext;
+import org.apache.jasper.Options;
+import org.easymock.EasyMock;
+
+public class TestJavaCompiler {
+
+    private File outputDir;
+    private File javaFile;
+
+    @Before
+    public void setUp() throws Exception {
+        File tempDir = new File(System.getProperty("tomcat.test.temp",
+                "output/tmp"));
+        outputDir = new File(tempDir, "java-compiler");
+        Assert.assertTrue(outputDir.mkdirs() || outputDir.isDirectory());
+        javaFile = new File(outputDir, "Bad_jsp.java");
+        String source = "public class Bad_jsp {\n" +
+                "    public void service() {\n" +
+                "        int i = ;\n" +
+                "    }\n" +
+                "}\n";
+        Files.write(javaFile.toPath(),
+                source.getBytes(StandardCharsets.UTF_8));
+    }
+
+    @After
+    public void tearDown() {
+        removeFile(javaFile);
+        removeFile(new File(outputDir, "Bad_jsp.class"));
+        outputDir.delete();
+    }
+
+    private static void removeFile(File file) {
+        if (file != null && file.exists()) {
+            file.delete();
+        }
+    }
+
+    /*
+     * The compilation errors must be dispatched to the error handler before
+     * the generated source is removed, so that the errors are reported (and
+     * the source retained for inspection) rather than being masked by the
+     * cleanup of the generated source.
+     */
+    @Test
+    public void testCompilationErrorsDispatchedBeforeGeneratedSourceRemoved()
+            throws Exception {
+        Options options = EasyMock.createMock(Options.class);
+        EasyMock.expect(options.getJavaEncoding()).andReturn("UTF-8")
+                .anyTimes();
+        EasyMock.expect(options.getCompilerSourceVM()).andReturn("17")
+                .anyTimes();
+        EasyMock.expect(options.getCompilerTargetVM()).andReturn("17")
+                .anyTimes();
+        EasyMock.replay(options);
+
+        JspCompilationContext ctxt = EasyMock.createMock(
+                JspCompilationContext.class);
+        EasyMock.expect(ctxt.getOptions()).andReturn(options).anyTimes();
+        EasyMock.expect(ctxt.getServletJavaFileName())
+                .andReturn(javaFile.getAbsolutePath()).anyTimes();
+        EasyMock.expect(ctxt.getClassPath())
+                .andReturn(System.getProperty("java.class.path")).anyTimes();
+        EasyMock.expect(ctxt.keepGenerated()).andReturn(false).anyTimes();
+        EasyMock.replay(ctxt);
+
+        JavaCompiler compiler = new JavaCompiler();
+        compiler.init(ctxt, null);
+        compiler.pageNodes = new Node.Nodes();
+        compiler.errDispatcher = new ErrorDispatcher(false);
+
+        try {
+            compiler.generateClass(null);
+            Assert.fail("Compilation was expected to fail");
+        } catch (JasperException e) {
+            // The javac error must have been reported ...
+            Assert.assertTrue("Unexpected message: " + e.getMessage(),
+                    e.getMessage().contains("Bad_jsp.java"));
+            // ... before the generated source was removed, which also means
+            // the source is retained for inspection after a failure
+            Assert.assertTrue(javaFile.exists());
+        }
+
+        EasyMock.verify(options, ctxt);
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 39/46: Strip a trailing slash from the context in resolveUrl

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 437c0be2b6ddd420fafc94a9d72bfa18b3258db5
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 16:00:44 2026 +0200

    Strip a trailing slash from the context in resolveUrl
    
    The JSTL standard handlers strip a single trailing slash from the
    context path before joining it with a URL that starts with a slash,
    so a c:url or c:redirect context of /app/ with a value of /p.jsp
    resolves to /app/p.jsp. The shared tag plugin helper only recognized
    the exact root context / and otherwise concatenated the two strings
    directly, so any other context ending in a slash resolved to a path
    with a doubled slash in it.
    
    The helper now reproduces the handler rule, stripping one trailing
    slash from any context that ends in one, which reduces to the
    previous root context behavior for the context /. The change covers
    both plugins that share the helper, c:url and c:redirect. Neither
    plugin is registered by default, so only the web applications that
    explicitly enable them observe the difference.
---
 java/org/apache/jasper/tagplugins/jstl/Util.java   | 13 +++--
 .../jasper/tagplugins/jstl/core/TestUrl.java       | 59 ++++++++++++++++++++++
 .../jasper/tagplugins/jstl/core/url-tagPlugins.xml | 23 +++++++++
 test/webapp/jstl/url-context-slash.jsp             | 25 +++++++++
 webapps/docs/changelog.xml                         |  8 +++
 5 files changed, 123 insertions(+), 5 deletions(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/Util.java b/java/org/apache/jasper/tagplugins/jstl/Util.java
index a57dfe823e..f453c4a497 100644
--- a/java/org/apache/jasper/tagplugins/jstl/Util.java
+++ b/java/org/apache/jasper/tagplugins/jstl/Util.java
@@ -285,11 +285,14 @@ public class Util {
             if (!context.startsWith("/") || !url.startsWith("/")) {
                 throw new JspTagException(Localizer.getMessage("jstl.urlMustStartWithSlash"));
             }
-            if (context.equals("/")) {
-                // Don't produce string starting with '//', many
-                // browsers interpret this as host name, not as
-                // path on same host.
-                return url;
+            if (context.endsWith("/")) {
+                // Strip the trailing slash of the context, as the standard
+                // handler does, so that the joined path does not carry a
+                // doubled slash. For the root context this reduces to the
+                // URL itself, which also avoids producing a string starting
+                // with '//', as many browsers interpret this as host name,
+                // not as path on same host.
+                return context.substring(0, context.length() - 1) + url;
             } else {
                 return context + url;
             }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java b/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java
new file mode 100644
index 0000000000..3ac0d1c396
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestUrl.java
@@ -0,0 +1,59 @@
+/*
+ * 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.jasper.tagplugins.jstl.core;
+
+import java.io.File;
+
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestUrl extends AbstractTestTag {
+
+    @Override
+    protected File getTagPluginsFile() {
+        return new File("test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml");
+    }
+
+
+    /*
+     * A context path with a trailing slash must be joined with the value
+     * without producing a doubled slash, as the standard handler strips the
+     * trailing slash from the context before concatenation. Only the exact
+     * context "/" was special cased before, so any other context ending in a
+     * slash resolved to a path with "//" in it.
+     */
+    @Test
+    public void testContextWithTrailingSlash() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/url-context-slash.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("TRAILING=[/jstltest/index.jsp]"));
+        // The root context keeps resolving to just the value
+        Assert.assertTrue(body, body.contains("ROOT=[/index.jsp]"));
+        // A context without a trailing slash is simply concatenated
+        Assert.assertTrue(body, body.contains("PLAIN=[/jstltest/index.jsp]"));
+    }
+}
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml b/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml
new file mode 100644
index 0000000000..55860d0587
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/url-tagPlugins.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+-->
+<tag-plugins>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.UrlTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.Url</plugin-class>
+  </tag-plugin>
+</tag-plugins>
diff --git a/test/webapp/jstl/url-context-slash.jsp b/test/webapp/jstl/url-context-slash.jsp
new file mode 100644
index 0000000000..a964623ecb
--- /dev/null
+++ b/test/webapp/jstl/url-context-slash.jsp
@@ -0,0 +1,25 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:url var="trailing" context="/jstltest/" value="/index.jsp"/>
+<p>TRAILING=[${trailing}]</p>
+<c:url var="root" context="/" value="/index.jsp"/>
+<p>ROOT=[${root}]</p>
+<c:url var="plain" context="/jstltest" value="/index.jsp"/>
+<p>PLAIN=[${plain}]</p>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 9d8f8e2c8d..a719cb403f 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -477,6 +477,14 @@
         invalid use fails as it does with the handler instead of being
         silently ignored. (remm)
       </fix>
+      <fix>
+        The tag plugins for <code>c:url</code> and <code>c:redirect</code>
+        now strip a trailing slash from a <code>context</code> path before
+        joining it with the URL, as the standard tag handlers do, so that a
+        context path ending in a slash no longer produces a resolved path
+        with a doubled slash. Previously only the root context was handled.
+        (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 23/46: Use the canonical enum name in optimized tag setter code generation

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 01817b9e15c0e933568f931525c13845272b04fc
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 11:01:42 2026 +0200

    Use the canonical enum name in optimized tag setter code generation
    
    The optional ELInterpreterTagSetters optimization referenced the enum
    type of a tag attribute setter by Class.getName(). For a nested enum
    that returns the binary name with '$' separators, e.g.
    com.example.Tags$Status, which is not valid Java source, so a literal
    EL value like ${'ACTIVE'} for a setter taking a nested enum type made
    the generated JSP class fail to compile on first request.
    
    Use getCanonicalName() instead, matching the dot-separated name the
    non-optimized runtime path in JspUtil.interpreterCall already uses.
    
    Found by code review.
---
 .../optimizations/ELInterpreterTagSetters.java     |  5 +++-
 .../optimizations/TestELInterpreterTagSetters.java | 29 +++++++++++++++++++++
 test/webapp/WEB-INF/tag-setters.tld                | 11 ++++++++
 test/webapp/bug6nnnn/bug64872-nested-timeunit.jsp  | 30 ++++++++++++++++++++++
 4 files changed, 74 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/optimizations/ELInterpreterTagSetters.java b/java/org/apache/jasper/optimizations/ELInterpreterTagSetters.java
index 9841e4d5ad..18d88fc659 100644
--- a/java/org/apache/jasper/optimizations/ELInterpreterTagSetters.java
+++ b/java/org/apache/jasper/optimizations/ELInterpreterTagSetters.java
@@ -262,7 +262,10 @@ public class ELInterpreterTagSetters implements ELInterpreter {
                 try {
                     @SuppressWarnings({ "unchecked", "rawtypes" })
                     Enum<?> enumValue = Enum.valueOf((Class<? extends Enum>) expectedType, m.group(2));
-                    result = expectedType.getName() + "." + enumValue.name();
+                    // The canonical name (dot-separated) must be used here. The
+                    // binary name returned by getName() contains '$' separators
+                    // for nested types and is not valid Java source.
+                    result = expectedType.getCanonicalName() + "." + enumValue.name();
                 } catch (IllegalArgumentException iae) {
                     if (log.isDebugEnabled()) {
                         log.debug(Localizer.getMessage("jsp.error.typeConversion", m.group(2),
diff --git a/test/org/apache/jasper/optimizations/TestELInterpreterTagSetters.java b/test/org/apache/jasper/optimizations/TestELInterpreterTagSetters.java
index 1cdf5bd2c8..e9add535aa 100644
--- a/test/org/apache/jasper/optimizations/TestELInterpreterTagSetters.java
+++ b/test/org/apache/jasper/optimizations/TestELInterpreterTagSetters.java
@@ -90,6 +90,7 @@ public class TestELInterpreterTagSetters extends TomcatBaseTest {
             parameterSets.add(new Object[] { elInterpreter, "float", "12.34", ZERO, TWO });
             parameterSets.add(new Object[] { elInterpreter, "primitive-float", "12.34", ZERO, TWO });
             parameterSets.add(new Object[] { elInterpreter, "timeunit", "SECONDS", ZERO, TWO });
+            parameterSets.add(new Object[] { elInterpreter, "nested-timeunit", "SECONDS", ZERO, TWO });
             parameterSets.add(new Object[] { elInterpreter, "string", "bar", ZERO, TWO });
         }
         return parameterSets;
@@ -473,6 +474,34 @@ public class TestELInterpreterTagSetters extends TomcatBaseTest {
     }
 
 
+    /*
+     * Enum nested in a class to check the generated code uses the canonical
+     * name of the enum type, not the binary name.
+     */
+    public enum NestedTimeUnit {
+        SECONDS
+    }
+
+
+    public static class TagNestedTimeUnit extends SimpleTagSupport {
+
+        private NestedTimeUnit foo;
+
+        public NestedTimeUnit getFoo() {
+            return foo;
+        }
+
+        public void setFoo(NestedTimeUnit foo) {
+            this.foo = foo;
+        }
+
+        @Override
+        public void doTag() throws JspException, IOException {
+            getJspContext().getOut().print(foo);
+        }
+    }
+
+
     public static class TagBigDecimal extends SimpleTagSupport {
 
         private BigDecimal foo;
diff --git a/test/webapp/WEB-INF/tag-setters.tld b/test/webapp/WEB-INF/tag-setters.tld
index e02ae147bd..7158111a54 100644
--- a/test/webapp/WEB-INF/tag-setters.tld
+++ b/test/webapp/WEB-INF/tag-setters.tld
@@ -242,4 +242,15 @@
         <type>java.util.concurrent.TimeUnit</type>
       </attribute>
     </tag>
+    <tag>
+      <name>tagNestedTimeUnit</name>
+      <tag-class>org.apache.jasper.optimizations.TestELInterpreterTagSetters$TagNestedTimeUnit</tag-class>
+      <body-content>scriptless</body-content>
+      <attribute>
+        <name>foo</name>
+        <required>true</required>
+        <rtexprvalue>true</rtexprvalue>
+        <type>org.apache.jasper.optimizations.TestELInterpreterTagSetters$NestedTimeUnit</type>
+      </attribute>
+    </tag>
 </taglib>
\ No newline at end of file
diff --git a/test/webapp/bug6nnnn/bug64872-nested-timeunit.jsp b/test/webapp/bug6nnnn/bug64872-nested-timeunit.jsp
new file mode 100644
index 0000000000..621a80945b
--- /dev/null
+++ b/test/webapp/bug6nnnn/bug64872-nested-timeunit.jsp
@@ -0,0 +1,30 @@
+<%--
+ 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.
+--%>
+<%@ taglib uri="http://tomcat.apache.org/tag-setters" prefix="ts" %>
+<html>
+  <head><title>Bug 64872 nested enum test case</title></head>
+  <body>
+  <%
+  for (int i=0; i < Integer.parseInt(request.getParameter("iterations")); i++) {
+  %>
+    <p>01 The value of foo is [<ts:tagNestedTimeUnit foo="${'SECONDS'}" />]</p>
+    <p>02 The value of foo is [<ts:tagNestedTimeUnit foo='${"SECONDS"}' />]</p>
+  <%
+  }
+  %>
+  </body>
+</html>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 35/46: Share the Import tag plugin URL with its params via the plugin context

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 4ea3677f93ea736decf94c2b63a6bec3ccf00e8c
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 14:33:08 2026 +0200

    Share the Import tag plugin URL with its params via the plugin context
    
    The Import and Param tag plugins exchanged the working URL of the
    import tag through the page scope attribute url_without_param: the
    Import plugin wrote the attribute before generating the tag body, read
    it back afterwards and removed it. The fixed name overwrote any
    application page attribute of the same name while the body was
    processed, removed it at the end, and let nested plugin enabled URL
    tags interfere with the value read back. A c:import nested in the body
    of a plugin enabled c:url, a nesting the JSTL tag library validator
    accepts, therefore always failed at runtime, because the inner tag
    removed the attribute the outer tag then read as null.
    
    Share the name of the generated local variable that holds the working
    URL through the plugin context instead, the mechanism the Choose
    plugin already uses to mark its context for When and Otherwise. The
    generated code of the Param plugin appends directly to that variable
    when the parent provides it, and keeps the former attribute protocol
    otherwise, so the Url and Redirect plugins, which still use the
    attribute, generate byte-identical code. The nesting of an import
    inside a non-varReader import, the path the report assumed was legal
    from the body-content of the TLD, never reaches code generation since
    the JSTL tag library validator rejects any child other than c:param
    there. Add tests pinning the user attribute, the parameter appending
    and the validator rejection.
    
    Found by code review.
---
 .../apache/jasper/tagplugins/jstl/core/Import.java | 21 ++++-
 .../apache/jasper/tagplugins/jstl/core/Param.java  | 31 +++++--
 .../jasper/tagplugins/jstl/core/TestImport.java    | 95 ++++++++++++++++++++++
 .../tagplugins/jstl/core/import-tagPlugins.xml     | 27 ++++++
 test/webapp/jstl/import-clobber.jsp                | 24 ++++++
 test/webapp/jstl/import-nested.jsp                 | 23 ++++++
 test/webapp/jstl/import-params.jsp                 | 23 ++++++
 test/webapp/jstl/import-target.jsp                 | 19 +++++
 webapps/docs/changelog.xml                         | 11 +++
 9 files changed, 262 insertions(+), 12 deletions(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Import.java b/java/org/apache/jasper/tagplugins/jstl/core/Import.java
index 3f564c805d..706cb48fb1 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Import.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Import.java
@@ -25,6 +25,16 @@ import org.apache.jasper.tagplugins.jstl.Util;
  */
 public class Import implements TagPlugin {
 
+    /**
+     * Key of the plugin attribute through which a URL tag shares its working
+     * URL with the {@link Param} tags in its body. The value is the name of
+     * the generated local variable that holds the URL and to which the
+     * parameters are appended. Sharing the variable rather than a page scope
+     * attribute with a fixed name makes the protocol re-entrant: a nested URL
+     * tag in the body cannot overwrite or remove the outer tag's URL.
+     */
+    static final String URL_VARIABLE_ATTRIBUTE = "urlVariable";
+
     /**
      * Creates a new instance of the Import tag plugin.
      */
@@ -279,10 +289,15 @@ public class Import implements TagPlugin {
         // if the varReader is not specified
         else {
 
-            ctxt.generateJavaSource("_jspx_page_context.setAttribute(\"url_without_param\"," + urlName + ");");
+            // Share the working URL with the <c:param> tags in the body by
+            // handing them the name of the local variable that holds it.
+            // Appending to the variable directly is re-entrant: a nested URL
+            // tag in the body of this tag must not be able to overwrite or
+            // remove it, which a page scope attribute with a fixed name
+            // would allow.
+            ctxt.setPluginAttribute(URL_VARIABLE_ATTRIBUTE, urlName);
             ctxt.generateBody();
-            ctxt.generateJavaSource(urlName + " = (String)_jspx_page_context.getAttribute(\"url_without_param\");");
-            ctxt.generateJavaSource("_jspx_page_context.removeAttribute(\"url_without_param\");");
+
             String strScope = "page";
             if (hasScope) {
                 strScope = ctxt.getConstantAttribute("scope");
diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Param.java b/java/org/apache/jasper/tagplugins/jstl/core/Param.java
index 006bf2675d..76e0d680f4 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Param.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Param.java
@@ -52,9 +52,20 @@ public class Param implements TagPlugin {
             return;
         }
 
-        // get the url string before adding this param
-        ctxt.generateJavaSource(
-                "String " + urlName + " = " + "(String)_jspx_page_context.getAttribute(\"url_without_param\");");
+        // Append the parameter to the parent tag's working URL. The Import
+        // plugin shares the name of the local variable holding that URL
+        // through the plugin context, so that nested URL tags cannot
+        // interfere with it through a shared page scope attribute. The Url
+        // and Redirect plugins still use such an attribute.
+        Object urlVariable = parent.getPluginAttribute(Import.URL_VARIABLE_ATTRIBUTE);
+        String urlTargetName;
+        if (urlVariable != null) {
+            urlTargetName = (String) urlVariable;
+        } else {
+            ctxt.generateJavaSource(
+                    "String " + urlName + " = " + "(String)_jspx_page_context.getAttribute(\"url_without_param\");");
+            urlTargetName = urlName;
+        }
 
         // get the value of "name"
         ctxt.generateJavaSource("String " + nameName + " = ");
@@ -76,17 +87,19 @@ public class Param implements TagPlugin {
         ctxt.generateJavaSource(
                 "    " + valueName + " = java.net.URLEncoder.encode(" + valueName + ", " + encName + ");");
         ctxt.generateJavaSource("    int " + index + ";");
-        ctxt.generateJavaSource("    " + index + " = " + urlName + ".indexOf(\'?\');");
+        ctxt.generateJavaSource("    " + index + " = " + urlTargetName + ".indexOf(\'?\');");
         // if the current param is the first one, add a "?" ahead of it
         // else add a "&" ahead of it
         ctxt.generateJavaSource("    if(" + index + " == -1){");
-        ctxt.generateJavaSource(
-                "        " + urlName + " = " + urlName + " + \"?\" + " + nameName + " + \"=\" + " + valueName + ";");
+        ctxt.generateJavaSource("        " + urlTargetName + " = " + urlTargetName + " + \"?\" + " + nameName +
+                " + \"=\" + " + valueName + ";");
         ctxt.generateJavaSource("    }else{");
-        ctxt.generateJavaSource(
-                "        " + urlName + " = " + urlName + " + \"&\" + " + nameName + " + \"=\" + " + valueName + ";");
+        ctxt.generateJavaSource("        " + urlTargetName + " = " + urlTargetName + " + \"&\" + " + nameName +
+                " + \"=\" + " + valueName + ";");
         ctxt.generateJavaSource("    }");
-        ctxt.generateJavaSource("    _jspx_page_context.setAttribute(\"url_without_param\"," + urlName + ");");
+        if (urlVariable == null) {
+            ctxt.generateJavaSource("    _jspx_page_context.setAttribute(\"url_without_param\"," + urlName + ");");
+        }
         ctxt.generateJavaSource("}");
     }
 }
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestImport.java b/test/org/apache/jasper/tagplugins/jstl/core/TestImport.java
new file mode 100644
index 0000000000..2c59d5ce37
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestImport.java
@@ -0,0 +1,95 @@
+/*
+ * 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.jasper.tagplugins.jstl.core;
+
+import java.io.File;
+
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestImport extends AbstractTestTag {
+
+    @Override
+    protected File getTagPluginsFile() {
+        return new File("test/org/apache/jasper/tagplugins/jstl/core/import-tagPlugins.xml");
+    }
+
+    /*
+     * The <c:param> plugin must add its parameters to the URL of its own
+     * <c:import> tag. The plugins previously exchanged the working URL
+     * through a page scope attribute named "url_without_param". That fixed
+     * name overwrote any application attribute of the same name while the
+     * body was processed and removed it at the end. The URL is now shared
+     * with the body through the plugin context instead.
+     */
+    @Test
+    public void testParamKeepsUserAttribute() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/import-clobber.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("KEEP=[keepme]"));
+    }
+
+
+    /*
+     * Parameters are appended to the URL, URL-encoded, the first one
+     * following the existing query string with "&" (the target reads the
+     * query string of its include dispatch from the Servlet include
+     * attribute).
+     */
+    @Test
+    public void testParams() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/import-params.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("QS=[a=b&sp=x+y&u=%26%3D]"));
+    }
+
+
+    /*
+     * A nested <c:import> in the body of a non-varReader <c:import> is
+     * rejected by the JSTL tag library validator before code generation
+     * (only <c:param> children are allowed there), which is why the body of
+     * the tag can never remove the working URL of the outer tag.
+     */
+    @Test
+    public void testNestedImportRejected() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/import-nested.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
+
+        String body = res.toString();
+        Assert.assertTrue(body, body.contains("Illegal child tag"));
+    }
+}
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/import-tagPlugins.xml b/test/org/apache/jasper/tagplugins/jstl/core/import-tagPlugins.xml
new file mode 100644
index 0000000000..2ed6156c07
--- /dev/null
+++ b/test/org/apache/jasper/tagplugins/jstl/core/import-tagPlugins.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+-->
+<tag-plugins>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.ImportTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.Import</plugin-class>
+  </tag-plugin>
+  <tag-plugin>
+    <tag-class>org.apache.taglibs.standard.tag.rt.core.ParamTag</tag-class>
+    <plugin-class>org.apache.jasper.tagplugins.jstl.core.Param</plugin-class>
+  </tag-plugin>
+</tag-plugins>
diff --git a/test/webapp/jstl/import-clobber.jsp b/test/webapp/jstl/import-clobber.jsp
new file mode 100644
index 0000000000..a48880f440
--- /dev/null
+++ b/test/webapp/jstl/import-clobber.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:set var="url_without_param" value="keepme" scope="page" />
+<c:import url="import-target.jsp" var="outer"><c:param
+    name="p" value="q"/></c:import>
+<p>KEEP=[${url_without_param}]</p>
+<p>OUTER=[${outer}]</p>
diff --git a/test/webapp/jstl/import-nested.jsp b/test/webapp/jstl/import-nested.jsp
new file mode 100644
index 0000000000..34ad028b28
--- /dev/null
+++ b/test/webapp/jstl/import-nested.jsp
@@ -0,0 +1,23 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:import url="import-target.jsp" var="outer"><c:import
+    url="import-target.jsp?i=1" var="inner"/></c:import>
+<p>OUTER=[${outer}]</p>
+<p>INNER=[${inner}]</p>
diff --git a/test/webapp/jstl/import-params.jsp b/test/webapp/jstl/import-params.jsp
new file mode 100644
index 0000000000..d46323c33d
--- /dev/null
+++ b/test/webapp/jstl/import-params.jsp
@@ -0,0 +1,23 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<c:import url="import-target.jsp?a=b" var="outer"><c:param
+    name="sp" value="x y"/><c:param name="u"
+    value="${'&='}"/></c:import>
+<p>OUTER=[${outer}]</p>
diff --git a/test/webapp/jstl/import-target.jsp b/test/webapp/jstl/import-target.jsp
new file mode 100644
index 0000000000..edec2b4b86
--- /dev/null
+++ b/test/webapp/jstl/import-target.jsp
@@ -0,0 +1,19 @@
+<%--
+ 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.
+--%>
+<%@ page session="false" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+QS=[${requestScope['jakarta.servlet.include.query_string']}]
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index e5de6744ce..ee206f6ff6 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -439,6 +439,17 @@
         illegal nesting at runtime as the reference implementation does.
         (remm)
       </fix>
+      <fix>
+        The tag plugins for <code>c:import</code> and <code>c:param</code> now
+        share the working URL of the import tag through the plugin context
+        rather than the page scope attribute <code>url_without_param</code>.
+        The import plugin set that attribute while generating the tag body and
+        removed it afterwards, clobbering an application attribute of the same
+        name, and the fixed name made the exchange prone to interference
+        between nested URL tags. This matches the reference implementation,
+        which keeps the parameters of each tag to itself and never touches
+        page scope attributes. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 03/46: Stop the Ant compiler System.err capture when compilation fails unexpectedly

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit b94d6b83e6267a4d680d923e401347b567d4fc71
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 21:09:41 2026 +0200

    Stop the Ant compiler System.err capture when compilation fails unexpectedly
    
    AntCompiler.generateClass() starts a per-thread System.err capture with
    SystemLogHandler.setThread() but only stopped the capture on the
    straight-line path after javac had run. If configuring or executing the
    javac task failed with an unexpected exception, such as a BuildException
    when creating the task or a RuntimeException while configuring it, the
    exception escaped without the capture being stopped.
    
    Since the capture is installed behind a JVM-global System.err wrapper,
    all later System.err output on the failed thread was then silently
    discarded into the abandoned buffer, which kept growing for the life of
    that (pooled) thread.
    
    Stop the capture in a finally block so the thread state is always
    cleaned up. The content and ordering of the error report are unchanged
    on the paths where compilation completes.
    
    Add TestAntCompiler to verify the capture is not left installed when
    compilation fails unexpectedly.
---
 java/org/apache/jasper/compiler/AntCompiler.java   | 153 +++++++++++----------
 .../apache/jasper/compiler/TestAntCompiler.java    |  76 ++++++++++
 2 files changed, 154 insertions(+), 75 deletions(-)

diff --git a/java/org/apache/jasper/compiler/AntCompiler.java b/java/org/apache/jasper/compiler/AntCompiler.java
index 5c2dce7b40..a00f9f6ed2 100644
--- a/java/org/apache/jasper/compiler/AntCompiler.java
+++ b/java/org/apache/jasper/compiler/AntCompiler.java
@@ -166,92 +166,95 @@ public class AntCompiler extends Compiler {
         // Start capturing the System.err output for this thread
         SystemLogHandler.setThread();
 
-        // Initializing javac task
-        getProject();
-        Javac javac = (Javac) project.createTask("javac");
-
-        // Initializing classpath
-        Path path = new Path(project);
-        path.setPath(System.getProperty("java.class.path"));
-        info.append("    cp=").append(System.getProperty("java.class.path")).append("\n");
-        StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
-        while (tokenizer.hasMoreElements()) {
-            String pathElement = tokenizer.nextToken();
-            File repository = new File(pathElement);
-            path.setLocation(repository);
-            info.append("    cp=").append(repository).append("\n");
-        }
-
-        if (log.isTraceEnabled()) {
-            log.trace("Using classpath: " + System.getProperty("java.class.path") + File.pathSeparator + classpath);
-        }
-
-        // Initializing sourcepath
-        Path srcPath = new Path(project);
-        srcPath.setLocation(options.getScratchDir());
-
-        info.append("    work dir=").append(options.getScratchDir()).append("\n");
-
-        // Initialize and set java extensions
-        String exts = System.getProperty("java.ext.dirs");
-        if (exts != null) {
-            Path extdirs = new Path(project);
-            extdirs.setPath(exts);
-            javac.setExtdirs(extdirs);
-            info.append("    extension dir=").append(exts).append("\n");
-        }
-
-        // Configure the compiler object
-        javac.setEncoding(javaEncoding);
-        javac.setClasspath(path);
-        javac.setDebug(ctxt.getOptions().getClassDebugInfo());
-        javac.setSrcdir(srcPath);
-        javac.setTempdir(options.getScratchDir());
-        javac.setFork(ctxt.getOptions().getFork());
-        info.append("    srcDir=").append(srcPath).append("\n");
-
-        // Set the Java compiler to use
-        if (options.getCompiler() != null) {
-            javac.setCompiler(options.getCompiler());
-            info.append("    compiler=").append(options.getCompiler()).append("\n");
-        }
+        BuildException be = null;
+        String errorCapture;
+        try {
+            // Initializing javac task
+            getProject();
+            Javac javac = (Javac) project.createTask("javac");
+
+            // Initializing classpath
+            Path path = new Path(project);
+            path.setPath(System.getProperty("java.class.path"));
+            info.append("    cp=").append(System.getProperty("java.class.path")).append("\n");
+            StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
+            while (tokenizer.hasMoreElements()) {
+                String pathElement = tokenizer.nextToken();
+                File repository = new File(pathElement);
+                path.setLocation(repository);
+                info.append("    cp=").append(repository).append("\n");
+            }
 
-        if (options.getCompilerTargetVM() != null) {
-            javac.setTarget(options.getCompilerTargetVM());
-            info.append("   compilerTargetVM=").append(options.getCompilerTargetVM()).append("\n");
-        }
+            if (log.isTraceEnabled()) {
+                log.trace("Using classpath: " + System.getProperty("java.class.path") + File.pathSeparator + classpath);
+            }
 
-        if (options.getCompilerSourceVM() != null) {
-            javac.setSource(options.getCompilerSourceVM());
-            info.append("   compilerSourceVM=").append(options.getCompilerSourceVM()).append("\n");
-        }
+            // Initializing sourcepath
+            Path srcPath = new Path(project);
+            srcPath.setLocation(options.getScratchDir());
 
-        // Build includes path
-        PatternSet.NameEntry includes = javac.createInclude();
+            info.append("    work dir=").append(options.getScratchDir()).append("\n");
 
-        includes.setName(ctxt.getJavaPath());
-        info.append("    include=").append(ctxt.getJavaPath()).append("\n");
+            // Initialize and set java extensions
+            String exts = System.getProperty("java.ext.dirs");
+            if (exts != null) {
+                Path extdirs = new Path(project);
+                extdirs.setPath(exts);
+                javac.setExtdirs(extdirs);
+                info.append("    extension dir=").append(exts).append("\n");
+            }
 
-        BuildException be = null;
+            // Configure the compiler object
+            javac.setEncoding(javaEncoding);
+            javac.setClasspath(path);
+            javac.setDebug(ctxt.getOptions().getClassDebugInfo());
+            javac.setSrcdir(srcPath);
+            javac.setTempdir(options.getScratchDir());
+            javac.setFork(ctxt.getOptions().getFork());
+            info.append("    srcDir=").append(srcPath).append("\n");
+
+            // Set the Java compiler to use
+            if (options.getCompiler() != null) {
+                javac.setCompiler(options.getCompiler());
+                info.append("    compiler=").append(options.getCompiler()).append("\n");
+            }
 
-        try {
-            if (ctxt.getOptions().getFork()) {
-                javac.execute();
-            } else {
-                synchronized (javacLock) {
+            if (options.getCompilerTargetVM() != null) {
+                javac.setTarget(options.getCompilerTargetVM());
+                info.append("   compilerTargetVM=").append(options.getCompilerTargetVM()).append("\n");
+            }
+
+            if (options.getCompilerSourceVM() != null) {
+                javac.setSource(options.getCompilerSourceVM());
+                info.append("   compilerSourceVM=").append(options.getCompilerSourceVM()).append("\n");
+            }
+
+            // Build includes path
+            PatternSet.NameEntry includes = javac.createInclude();
+
+            includes.setName(ctxt.getJavaPath());
+            info.append("    include=").append(ctxt.getJavaPath()).append("\n");
+
+            try {
+                if (ctxt.getOptions().getFork()) {
                     javac.execute();
+                } else {
+                    synchronized (javacLock) {
+                        javac.execute();
+                    }
                 }
+            } catch (BuildException e) {
+                be = e;
+                log.error(Localizer.getMessage("jsp.error.javac"), e);
+                log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString());
             }
-        } catch (BuildException e) {
-            be = e;
-            log.error(Localizer.getMessage("jsp.error.javac"), e);
-            log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString());
-        }
 
-        errorReport.append(logger.getReport());
+            errorReport.append(logger.getReport());
+        } finally {
+            // Stop capturing the System.err output for this thread
+            errorCapture = SystemLogHandler.unsetThread();
+        }
 
-        // Stop capturing the System.err output for this thread
-        String errorCapture = SystemLogHandler.unsetThread();
         if (errorCapture != null) {
             errorReport.append(System.lineSeparator());
             errorReport.append(errorCapture);
diff --git a/test/org/apache/jasper/compiler/TestAntCompiler.java b/test/org/apache/jasper/compiler/TestAntCompiler.java
new file mode 100644
index 0000000000..76b939c65c
--- /dev/null
+++ b/test/org/apache/jasper/compiler/TestAntCompiler.java
@@ -0,0 +1,76 @@
+/*
+ * 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.jasper.compiler;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.jasper.JspCompilationContext;
+import org.apache.jasper.Options;
+import org.easymock.EasyMock;
+
+public class TestAntCompiler {
+
+    @After
+    public void clearCapture() {
+        // Never leave the System.err capture installed on the test thread,
+        // even if an assertion below fails
+        AntCompiler.SystemLogHandler.unsetThread();
+    }
+
+    /*
+     * A compilation that fails unexpectedly, with the exception escaping
+     * generateClass(), must not leave the per-thread System.err capture
+     * installed. Otherwise, later output to System.err on the (pooled) thread
+     * would be silently discarded for the life of that thread.
+     */
+    @Test
+    public void testErrorCaptureClearedWhenCompilationFails() throws Exception {
+        Options options = EasyMock.createMock(Options.class);
+        EasyMock.expect(options.getJavaEncoding()).andReturn("UTF-8").anyTimes();
+        EasyMock.expect(options.getCompiler()).andReturn(null).anyTimes();
+        EasyMock.replay(options);
+
+        JspCompilationContext ctxt = EasyMock.createMock(
+                JspCompilationContext.class);
+        EasyMock.expect(ctxt.getOptions()).andReturn(options).anyTimes();
+        EasyMock.expect(ctxt.getServletJavaFileName())
+                .andReturn("none_jsp.java").anyTimes();
+        // A null class path triggers an unexpected exception while the
+        // javac task is being configured, after the capture has started
+        EasyMock.expect(ctxt.getClassPath()).andReturn(null).anyTimes();
+        EasyMock.replay(ctxt);
+
+        AntCompiler compiler = new AntCompiler();
+        compiler.init(ctxt, null);
+
+        try {
+            compiler.generateClass(null);
+            Assert.fail("Compilation was expected to fail");
+        } catch (Exception expected) {
+            // Ignore
+        }
+
+        // The capture must not be active on this thread any more
+        Assert.assertNull(AntCompiler.SystemLogHandler.streams.get());
+        Assert.assertNull(AntCompiler.SystemLogHandler.data.get());
+        Assert.assertNull(AntCompiler.SystemLogHandler.unsetThread());
+
+        EasyMock.verify(options, ctxt);
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 16/46: Omit the id from validation messages without one

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 22c06ced0d8460d53cbbee2c2e86fbd85091d7c7
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 09:55:49 2026 +0200

    Omit the id from validation messages without one
    
    Validator.validateXmlView() appended the id of each ValidationMessage
    returned by a TagLibraryValidator followed by a separator
    unconditionally
    before the message. The JSP specification and the ValidationMessage
    javadoc allow the id to be null, meaning that no jsp:id information is
    available, so a validator returning such a message produced an error
    report containing the literal text "null: " in front of the message.
    
    Render the id the same way the parallel TagExtraInfoVisitor path
    already does: only when it is present.
    
    The regression test also pins the unchanged rendering for a message
    that does have an id.
    
    Found by code review.
---
 java/org/apache/jasper/compiler/Validator.java     |  6 ++--
 test/org/apache/jasper/compiler/TestValidator.java | 33 ++++++++++++++++++++++
 test/webapp/WEB-INF/null-id-tlv.tld                | 28 ++++++++++++++++++
 test/webapp/jsp/parsing/taglib-null-id-tlv.jsp     | 24 ++++++++++++++++
 4 files changed, 89 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/compiler/Validator.java b/java/org/apache/jasper/compiler/Validator.java
index 965f46b2b4..dfda3dc112 100644
--- a/java/org/apache/jasper/compiler/Validator.java
+++ b/java/org/apache/jasper/compiler/Validator.java
@@ -1695,8 +1695,10 @@ class Validator {
                 for (ValidationMessage error : errors) {
                     if (error != null) {
                         errMsg.append("<p>");
-                        errMsg.append(error.getId());
-                        errMsg.append(": ");
+                        if (error.getId() != null) {
+                            errMsg.append(error.getId());
+                            errMsg.append(": ");
+                        }
                         errMsg.append(error.getMessage());
                         errMsg.append("</p>");
                     }
diff --git a/test/org/apache/jasper/compiler/TestValidator.java b/test/org/apache/jasper/compiler/TestValidator.java
index 2e084ab744..b2ad3535f7 100644
--- a/test/org/apache/jasper/compiler/TestValidator.java
+++ b/test/org/apache/jasper/compiler/TestValidator.java
@@ -21,7 +21,10 @@ import java.io.IOException;
 
 import jakarta.servlet.http.HttpServletResponse;
 import jakarta.servlet.jsp.JspException;
+import jakarta.servlet.jsp.tagext.PageData;
+import jakarta.servlet.jsp.tagext.TagLibraryValidator;
 import jakarta.servlet.jsp.tagext.TagSupport;
+import jakarta.servlet.jsp.tagext.ValidationMessage;
 
 import org.junit.Assert;
 import org.junit.Test;
@@ -59,6 +62,27 @@ public class TestValidator extends TomcatBaseTest {
         Assert.assertFalse(result, result.contains("NumberFormatException"));
     }
 
+    @Test
+    public void testNullIdTlv() throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/parsing/taglib-null-id-tlv.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
+
+        // The validator returns a ValidationMessage with a null id. The id
+        // and the following separator must be omitted from the reported
+        // message. They were previously appended unconditionally which
+        // rendered the literal text "null: " in front of the message.
+        String result = res.toString();
+        Assert.assertTrue(result, result.contains("message without an id"));
+        Assert.assertFalse(result, result.contains("null: message"));
+        // The id of a ValidationMessage that has one is still reported
+        Assert.assertTrue(result, result.contains("123: message with an id"));
+    }
+
     @Test
     public void testTldVersions22() throws Exception {
         Tomcat tomcat = getTomcatInstance();
@@ -269,6 +293,15 @@ public class TestValidator extends TomcatBaseTest {
         Assert.assertTrue(result.indexOf("<p>08-hello world</p>") > 0);
     }
 
+    public static class NullIdValidator extends TagLibraryValidator {
+
+        @Override
+        public ValidationMessage[] validate(String prefix, String uri, PageData page) {
+            return new ValidationMessage[] { new ValidationMessage(null, "message without an id"),
+                    new ValidationMessage("123", "message with an id") };
+        }
+    }
+
     public static class Echo extends TagSupport {
 
         private static final long serialVersionUID = 1L;
diff --git a/test/webapp/WEB-INF/null-id-tlv.tld b/test/webapp/WEB-INF/null-id-tlv.tld
new file mode 100644
index 0000000000..e3d813b8e0
--- /dev/null
+++ b/test/webapp/WEB-INF/null-id-tlv.tld
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<taglib xmlns="http://java.sun.com/xml/ns/javaee"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
+    version="2.1">
+    <tlib-version>1.0</tlib-version>
+    <short-name>nlid</short-name>
+    <uri>http://tomcat.apache.org/null-id-tlv</uri>
+    <validator>
+      <validator-class>org.apache.jasper.compiler.TestValidator$NullIdValidator</validator-class>
+    </validator>
+</taglib>
diff --git a/test/webapp/jsp/parsing/taglib-null-id-tlv.jsp b/test/webapp/jsp/parsing/taglib-null-id-tlv.jsp
new file mode 100644
index 0000000000..ac58d59086
--- /dev/null
+++ b/test/webapp/jsp/parsing/taglib-null-id-tlv.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page contentType="text/html;charset=UTF-8" %>
+<%@ taglib uri="/WEB-INF/null-id-tlv.tld" prefix="nlid" %>
+<html>
+  <head><title>Tag library validator with a null id test case</title></head>
+  <body>
+    <p>Should fail</p>
+  </body>
+</html>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 41/46: Honour a FastRemovalDequeue maximum size of one

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit ab1313f0cc8a119f467c3f696c3ec23de12ba999
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 16:36:09 2026 +0200

    Honour a FastRemovalDequeue maximum size of one
    
    The constructor raised a maximum size of one, or below, silently to
    two. The queue is used by the JSP runtime to limit the number of
    loaded JSPs through the maxLoadedJsps init parameter, which is
    documented to accept any positive value, so a configured limit of one
    kept two JSPs loaded and evicted nothing until a third one was
    requested.
    
    Every operation of the queue handles a maximum size of one correctly,
    so the clamping is not needed for correctness. The constructor now
    honours a maximum size of one and rejects a maximum size below one
    with a localized IllegalArgumentException. The only in-tree caller
    creates the queue only for limits greater than zero, so no configured
    value can reach the new exception.
    
    Add tests for the size of one, including eviction from both ends and
    the no-op removal through an evicted handle, and for the rejected
    sizes. Update the two test comments that recorded the minimum of the
    maxLoadedJsps parameter as two.
    
    Found by code review.
---
 .../jasper/resources/LocalStrings.properties       |  1 +
 .../org/apache/jasper/util/FastRemovalDequeue.java |  9 ++-
 .../catalina/core/TestDefaultInstanceManager.java  |  2 +-
 test/org/apache/el/TestELInJsp.java                |  2 +-
 .../apache/jasper/util/TestFastRemovalDequeue.java | 67 ++++++++++++++++++++++
 5 files changed, 77 insertions(+), 4 deletions(-)

diff --git a/java/org/apache/jasper/resources/LocalStrings.properties b/java/org/apache/jasper/resources/LocalStrings.properties
index f82467d793..a7ed73bdc1 100644
--- a/java/org/apache/jasper/resources/LocalStrings.properties
+++ b/java/org/apache/jasper/resources/LocalStrings.properties
@@ -78,6 +78,7 @@ jsp.error.el.parse=[{0}] : [{1}]
 jsp.error.el.template.deferred=#{...} is not allowed in template text
 jsp.error.el_interpreter_class.instantiation=Failed to load or instantiate ELInterpreter class [{0}]
 jsp.error.fallback.invalidUse=jsp:fallback must be a direct child of jsp:plugin
+jsp.error.fastremovaldequeue.maxSize=The maximum size of the queue must be at least one but was [{0}]
 jsp.error.file.already.registered=Recursive include of file [{0}]
 jsp.error.file.cannot.read=Cannot read file: [{0}]
 jsp.error.file.close=Exception closing reader
diff --git a/java/org/apache/jasper/util/FastRemovalDequeue.java b/java/org/apache/jasper/util/FastRemovalDequeue.java
index 8fdce038b1..35dfe2b436 100644
--- a/java/org/apache/jasper/util/FastRemovalDequeue.java
+++ b/java/org/apache/jasper/util/FastRemovalDequeue.java
@@ -16,6 +16,8 @@
  */
 package org.apache.jasper.util;
 
+import org.apache.jasper.compiler.Localizer;
+
 /**
  * The FastRemovalDequeue is a Dequeue that supports constant time removal of entries. This is achieved by using a
  * doubly linked list and wrapping any object added to the collection with an Entry type, that is returned to the
@@ -55,10 +57,13 @@ public class FastRemovalDequeue<T> {
      * Initialize empty queue.
      *
      * @param maxSize The maximum size to which the queue will be allowed to grow
+     *
+     * @throws IllegalArgumentException if the maximum size is less than one
      */
     public FastRemovalDequeue(int maxSize) {
-        if (maxSize <= 1) {
-            maxSize = 2;
+        if (maxSize < 1) {
+            throw new IllegalArgumentException(
+                    Localizer.getMessage("jsp.error.fastremovaldequeue.maxSize", Integer.valueOf(maxSize)));
         }
         this.maxSize = maxSize;
         first = null;
diff --git a/test/org/apache/catalina/core/TestDefaultInstanceManager.java b/test/org/apache/catalina/core/TestDefaultInstanceManager.java
index 5f622a673d..7bd13c49e2 100644
--- a/test/org/apache/catalina/core/TestDefaultInstanceManager.java
+++ b/test/org/apache/catalina/core/TestDefaultInstanceManager.java
@@ -77,7 +77,7 @@ public class TestDefaultInstanceManager extends TomcatBaseTest {
         ctxt.addServletContainerInitializer(new JasperInitializer(), null);
 
         // Configure the defaults and then tweak the JSP servlet settings
-        // Note: Min value for maxLoadedJsps is 2
+        // Note: Min value for maxLoadedJsps is 1
         Tomcat.initWebappDefaults(ctxt);
         Wrapper w = (Wrapper) ctxt.findChild("jsp");
         w.addInitParameter("maxLoadedJsps", "2");
diff --git a/test/org/apache/el/TestELInJsp.java b/test/org/apache/el/TestELInJsp.java
index 3055bf47b8..40ddad3362 100644
--- a/test/org/apache/el/TestELInJsp.java
+++ b/test/org/apache/el/TestELInJsp.java
@@ -310,7 +310,7 @@ public class TestELInJsp extends TomcatBaseTest {
         ctxt.addServletContainerInitializer(new JasperInitializer(), null);
 
         // Configure the defaults and then tweak the JSP servlet settings
-        // Note: Min value for maxLoadedJsps is 2
+        // Note: Min value for maxLoadedJsps is 1
         Tomcat.initWebappDefaults(ctxt);
         Wrapper w = (Wrapper) ctxt.findChild("jsp");
 
diff --git a/test/org/apache/jasper/util/TestFastRemovalDequeue.java b/test/org/apache/jasper/util/TestFastRemovalDequeue.java
index cf676ae648..237b571fef 100644
--- a/test/org/apache/jasper/util/TestFastRemovalDequeue.java
+++ b/test/org/apache/jasper/util/TestFastRemovalDequeue.java
@@ -194,4 +194,71 @@ public class TestFastRemovalDequeue {
         Assert.assertNull(q.first);
         Assert.assertNull(q.last);
     }
+
+
+    /*
+     * A maximum size of one must be honoured. The constructor used to
+     * silently raise it to two, so a configured maxLoadedJsps of one kept
+     * two JSPs loaded and evicted nothing until a third one was requested.
+     */
+    @Test
+    public void testSingleSizeIsHonoured() throws Exception {
+        FastRemovalDequeue<Object> q = new FastRemovalDequeue<>(1);
+
+        Object o1 = new Object();
+        Object o2 = new Object();
+        Object o3 = new Object();
+
+        FastRemovalDequeue<Object>.Entry e1 = q.push(o1);
+        Assert.assertNull(e1.getReplaced());
+        Assert.assertEquals(1, q.getSize());
+
+        FastRemovalDequeue<Object>.Entry e2 = q.push(o2);
+        // Adding to a full queue of one displaces the single entry
+        Assert.assertSame(o1, e2.getReplaced());
+        Assert.assertEquals(1, q.getSize());
+        Assert.assertSame(o2, q.first.getContent());
+        Assert.assertSame(o2, q.last.getContent());
+
+        // Removing the handle of the evicted object is a NOP
+        q.remove(e1);
+        Assert.assertEquals(1, q.getSize());
+        Assert.assertSame(o2, q.first.getContent());
+        Assert.assertSame(o2, q.last.getContent());
+
+        FastRemovalDequeue<Object>.Entry e3 = q.unpop(o3);
+        // The symmetric case at the other end of the queue
+        Assert.assertSame(o2, e3.getReplaced());
+        Assert.assertEquals(1, q.getSize());
+        Assert.assertSame(o3, q.first.getContent());
+        Assert.assertSame(o3, q.last.getContent());
+
+        // Removing the single entry empties the queue
+        q.remove(e3);
+        Assert.assertEquals(0, q.getSize());
+        Assert.assertNull(q.first);
+        Assert.assertNull(q.last);
+    }
+
+
+    /*
+     * A maximum size below one cannot produce a usable queue and is
+     * rejected, rather than silently replaced by a different size.
+     */
+    @Test
+    public void testInvalidMaxSize() throws Exception {
+        try {
+            new FastRemovalDequeue<Object>(0);
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // The message is localized, pin the rendered value
+            Assert.assertTrue(e.getMessage(), e.getMessage().contains("[0]"));
+        }
+        try {
+            new FastRemovalDequeue<Object>(-1);
+            Assert.fail("Expected IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            Assert.assertTrue(e.getMessage(), e.getMessage().contains("[-1]"));
+        }
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 28/46: Avoid registering TLD listeners twice for a duplicate taglib URI

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 99083290a8016ce45b4e398c404cf9677b6c96d4
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 12:17:45 2026 +0200

    Avoid registering TLD listeners twice for a duplicate taglib URI
    
    TldScanner.parseTld() only skipped a TLD whose exact TldResourcePath
    had already been parsed. TldResourcePath.equals() includes the URL, so
    the same tag library discovered through a second resource path, for
    example a TLD declared in jsp-config of web.xml that an IDE also
    unpacked into WEB-INF/classes/META-INF, or the same TLD shipped in two
    JARs, passed the guard and its listeners were appended to the scanner's
    listener list again. JasperInitializer.onStartup() then invoked
    context.addListener() for each list entry, instantiating the listener
    class twice so that it received every container event twice. The
    taglib URI map already resolves such duplicates with first-wins
    semantics (JSP.7.3.6.1) but the listener list was not deduplicated.
    
    Detect the duplicate by taglib URI in parseTld() and skip the listener
    registration for it, while continuing to cache the parsed TLD under its
    own resource path since it may be referenced directly by that path.
    Add a unit test covering the duplicate URI scan.
    
    Found by code review.
---
 java/org/apache/jasper/servlet/TldScanner.java     | 12 ++++-
 test/org/apache/jasper/servlet/TestTldScanner.java | 61 ++++++++++++++++++++++
 2 files changed, 71 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/servlet/TldScanner.java b/java/org/apache/jasper/servlet/TldScanner.java
index c9da0a5e99..da2fb0ac0d 100644
--- a/java/org/apache/jasper/servlet/TldScanner.java
+++ b/java/org/apache/jasper/servlet/TldScanner.java
@@ -309,8 +309,14 @@ public class TldScanner {
             tld = tldParser.parse(path);
         }
         String uri = tld.getUri();
+        // JSP.7.3.6.1: the first mapping for a taglib URI wins. A TLD with a
+        // previously seen URI found via a different resource path (for
+        // example, an unpacked JAR in WEB-INF/classes/META-INF or the same
+        // TLD shipped in two JARs) is a duplicate.
+        boolean duplicateUri = false;
         if (uri != null) {
-            if (!uriTldResourcePathMap.containsKey(uri)) {
+            duplicateUri = uriTldResourcePathMap.containsKey(uri);
+            if (!duplicateUri) {
                 uriTldResourcePathMap.put(uri, path);
             }
         }
@@ -321,7 +327,9 @@ public class TldScanner {
         }
 
         tldResourcePathTaglibXmlMap.put(path, tld);
-        if (tld.getListeners() != null) {
+        if (tld.getListeners() != null && !duplicateUri) {
+            // The listeners of a duplicate tag library have already been
+            // registered when the tag library was first discovered.
             listeners.addAll(tld.getListeners());
         }
     }
diff --git a/test/org/apache/jasper/servlet/TestTldScanner.java b/test/org/apache/jasper/servlet/TestTldScanner.java
index 8e989aa67b..152a94b37d 100644
--- a/test/org/apache/jasper/servlet/TestTldScanner.java
+++ b/test/org/apache/jasper/servlet/TestTldScanner.java
@@ -39,6 +39,7 @@ import org.apache.catalina.startup.TomcatBaseTest;
 import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.Jar;
 import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.descriptor.tld.TldResourcePath;
 import org.apache.tomcat.util.scan.JarFactory;
 import org.apache.tomcat.util.scan.StandardJarScanner;
 import org.easymock.EasyMock;
@@ -138,6 +139,66 @@ public class TestTldScanner extends TomcatBaseTest {
     }
 
 
+    @Test
+    public void testListenersNotDuplicatedForDuplicateTaglibUri() throws Exception {
+        // The same tag library may be discovered more than once, for example
+        // a TLD declared in web.xml that is also found unpacked in
+        // WEB-INF/classes/META-INF or shipped in two JARs. The first mapping
+        // wins for the taglib URI and the listeners of the duplicate must not
+        // be registered again, otherwise the listener class is instantiated
+        // twice and receives each event twice.
+        ServletContext mockContext = EasyMock.createMock(ServletContext.class);
+        EasyMock.replay(mockContext);
+
+        TldScanner scanner = new TldScanner(mockContext, true, true, true);
+
+        File appDir = new File(getTemporaryDirectory(), "duplicate-listeners");
+        TldResourcePath first = createTld(appDir, "one",
+                "<uri>http://tomcat.apache.org/duplicate</uri>\n" +
+                "  <listener>\n" +
+                "    <listener-class>com.example.DuplicateListener</listener-class>\n" +
+                "  </listener>");
+        TldResourcePath second = createTld(appDir, "two",
+                "<uri>http://tomcat.apache.org/duplicate</uri>\n" +
+                "  <listener>\n" +
+                "    <listener-class>com.example.DuplicateListener</listener-class>\n" +
+                "  </listener>");
+
+        scanner.parseTld(first);
+        scanner.parseTld(second);
+
+        EasyMock.verify(mockContext);
+        Assert.assertEquals(1, scanner.getListeners().size());
+        Assert.assertEquals("com.example.DuplicateListener", scanner.getListeners().get(0));
+        // The first mapping wins for the taglib URI.
+        Assert.assertEquals(1, scanner.getUriTldResourcePathMap().size());
+        Assert.assertSame(first,
+                scanner.getUriTldResourcePathMap().get("http://tomcat.apache.org/duplicate"));
+        // Both parsed TLDs remain cached since they may also be referenced
+        // directly by resource path.
+        Assert.assertEquals(2, scanner.getTldResourcePathTaglibXmlMap().size());
+    }
+
+
+    private static TldResourcePath createTld(File appDir, String name,
+            String extraElements) throws Exception {
+        File tld = new File(appDir, name + "/example.tld");
+        Files.createDirectories(tld.getParentFile().toPath());
+        String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+                "<taglib xmlns=\"http://java.sun.com/xml/ns/j2ee\"\n" +
+                "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
+                "    xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee\n" +
+                "        http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd\"\n" +
+                "    version=\"2.0\">\n" +
+                "  <tlib-version>1.0</tlib-version>\n" +
+                "  <short-name>example</short-name>\n" +
+                "  " + extraElements + "\n" +
+                "</taglib>\n";
+        Files.writeString(tld.toPath(), content, StandardCharsets.UTF_8);
+        return new TldResourcePath(tld.toURI().toURL(), "/" + name + "/example.tld");
+    }
+
+
     private static void createImplicitTld(File appDir, String extraElements) throws Exception {
         File implicitTld = new File(appDir, "WEB-INF/tags/display/implicit.tld");
         Files.createDirectories(implicitTld.getParentFile().toPath());


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 15/46: Avoid NullPointerException when a cached TLD is removed

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 744a6e74c5cfb89bb5c475a878028811ef17a03a
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 09:51:15 2026 +0200

    Avoid NullPointerException when a cached TLD is removed
    
    TldCache entries are populated at startup. If a TLD file inside the web
    application is removed while the context is running, the next JSP
    compilation referencing the tag library checks the last modified time
    of the cached entry. ServletContext.getResource() returns null for a
    removed resource and that null was passed straight to the
    CloseableURLConnection constructor, which dereferences it. The
    resulting NullPointerException was not caught by the surrounding
    IOException handler so compiling a referencing page failed with a raw
    NPE/500.
    
    Treat a missing resource as an unknown last modified time, matching the
    -1 values the jar based implementations already use for removed
    entries. The cached entry is then seen as out of date and the re-parse
    of the removed TLD reports the failure via a JasperException wrapping
    the IOException from opening the TLD rather than serving stale data.
    If the TLD is restored, the recomputed last modified time differs from
    the stored -1 values and the TLD is re-parsed and cached as usual.
    
    Found by code review.
---
 java/org/apache/jasper/compiler/TldCache.java     |  6 +++
 test/org/apache/jasper/compiler/TestTldCache.java | 49 +++++++++++++++++++++++
 2 files changed, 55 insertions(+)

diff --git a/java/org/apache/jasper/compiler/TldCache.java b/java/org/apache/jasper/compiler/TldCache.java
index daefa751ce..3c9a3d5c82 100644
--- a/java/org/apache/jasper/compiler/TldCache.java
+++ b/java/org/apache/jasper/compiler/TldCache.java
@@ -175,6 +175,12 @@ public class TldCache {
                 // webappPath will be null for JARs containing TLDs that are on
                 // the class path but not part of the web application
                 URL url = servletContext.getResource(tldResourcePath.getWebappPath());
+                if (url == null) {
+                    // The resource has been removed. Return -1 values so that
+                    // the cached entry is seen as out of date and re-parsing
+                    // reports the failure rather than using stale data
+                    return result;
+                }
                 try (CloseableURLConnection conn = new CloseableURLConnection(url)) {
                     result[0] = conn.getLastModified();
                 }
diff --git a/test/org/apache/jasper/compiler/TestTldCache.java b/test/org/apache/jasper/compiler/TestTldCache.java
index 8b89a4ad06..efa2e34964 100644
--- a/test/org/apache/jasper/compiler/TestTldCache.java
+++ b/test/org/apache/jasper/compiler/TestTldCache.java
@@ -17,6 +17,7 @@
 package org.apache.jasper.compiler;
 
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.net.URL;
 import java.nio.file.Files;
@@ -29,6 +30,7 @@ import java.util.concurrent.atomic.AtomicReference;
 import org.junit.Assert;
 import org.junit.Test;
 
+import org.apache.jasper.JasperException;
 import org.apache.tomcat.unittest.TesterServletContext;
 import org.apache.tomcat.util.descriptor.tld.TaglibXml;
 import org.apache.tomcat.util.descriptor.tld.TldParser;
@@ -41,6 +43,7 @@ public class TestTldCache {
 
     private static final String URI_1 = "http://tomcat.apache.org/TesterTld1";
     private static final String URI_2 = "http://tomcat.apache.org/TesterTld2";
+    private static final String URI_3 = "http://tomcat.apache.org/TesterTld3";
 
 
     private static class TesterTldCacheServletContext extends TesterServletContext {
@@ -155,6 +158,52 @@ public class TestTldCache {
     }
 
 
+    /*
+     * A TLD that was present at startup is cached. If the TLD file is
+     * subsequently removed, ServletContext.getResource() returns null for it.
+     * getLastModified() previously passed that null on to
+     * CloseableURLConnection which threw a NullPointerException.
+     */
+    @Test
+    public void testRemovedTld() throws Exception {
+        File tldFile = createTld("test-tld-cache-removed", URI_3);
+        URL url = tldFile.toURI().toURL();
+
+        TesterTldCacheServletContext context = new TesterTldCacheServletContext();
+        context.resources.put("/removed.tld", url);
+
+        TldParser parser = new TldParser(true, false, true);
+        TldResourcePath path = new TldResourcePath(url, "/removed.tld");
+
+        Map<String,TldResourcePath> uriMap = new HashMap<>();
+        uriMap.put(URI_3, path);
+
+        Map<TldResourcePath,TaglibXml> xmlMap = new HashMap<>();
+        xmlMap.put(path, parser.parse(path));
+
+        TldCache cache = new TldCache(context, uriMap, xmlMap);
+
+        // The cached entry is up to date
+        Assert.assertEquals(URI_3, cache.getTaglibXml(path).getUri());
+
+        // Remove the TLD. The context, like a real web application context,
+        // no longer finds a resource at the path
+        context.resources.remove("/removed.tld");
+        Assert.assertTrue(tldFile.delete());
+
+        // The cached entry is out of date and the re-parse of the removed TLD
+        // must fail with a JasperException rather than a NullPointerException
+        try {
+            cache.getTaglibXml(path);
+            Assert.fail("Expected a JasperException for the removed TLD");
+        } catch (JasperException e) {
+            // Expected. The re-parse fails because the TLD can no longer be
+            // opened
+            Assert.assertTrue(String.valueOf(e.getCause()), e.getCause() instanceof FileNotFoundException);
+        }
+    }
+
+
     private void hammer(TldCache cache, TldResourcePath path, String expectedUri,
             CountDownLatch start, AtomicBoolean running,
             AtomicReference<Throwable> error) {


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 18/46: Correct the assignability check for Graal bean property writes

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 48208e0c783cf5f96b9887f959d3042b260f3e79
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 10:17:45 2026 +0200

    Correct the assignability check for Graal bean property writes
    
    GraalBeanELResolver.getWriteMethod() accepted a setter when the
    parameter type was assignable from the value type, which is the
    reverse of what is required to invoke setX(P) with a value of type V,
    namely that P accepts V. As a result, any setter whose parameter type
    was a super-type of the value type, for example a setter taking Object
    or an interface, was rejected. In a GraalVM native image, where this
    resolver stands in for the reflection-configured BeanELResolver, EL
    assignments to such properties were silently dropped and the
    properties were reported as read only.
    
    Flip the check so the write method's parameter type is checked for
    assignability from the value type.
    
    The shipped test encoded the incorrect behaviour by asserting that a
    property with a setBla(Object) setter was read only. That assertion is
    flipped and a regression test is added that verifies a write through a
    super-type setter reaches the bean.
    
    Found by code review.
---
 java/org/apache/jasper/el/JasperELResolver.java     |  2 +-
 test/org/apache/jasper/el/TestJasperELResolver.java | 16 ++++++++++++++--
 webapps/docs/changelog.xml                          |  8 ++++++++
 3 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/jasper/el/JasperELResolver.java b/java/org/apache/jasper/el/JasperELResolver.java
index 2d3d0b96b6..e7f33bb8e3 100644
--- a/java/org/apache/jasper/el/JasperELResolver.java
+++ b/java/org/apache/jasper/el/JasperELResolver.java
@@ -277,7 +277,7 @@ public class JasperELResolver extends CompositeELResolver {
             Method[] methods = beanClass.getMethods();
             for (Method method : methods) {
                 if (method.getParameterCount() == 1 && setter.equals(method.getName()) &&
-                        (valueClass == null || valueClass.isAssignableFrom(method.getParameterTypes()[0]))) {
+                        (valueClass == null || method.getParameterTypes()[0].isAssignableFrom(valueClass))) {
                     return method;
                 }
             }
diff --git a/test/org/apache/jasper/el/TestJasperELResolver.java b/test/org/apache/jasper/el/TestJasperELResolver.java
index ca15a25055..465e6faaa3 100644
--- a/test/org/apache/jasper/el/TestJasperELResolver.java
+++ b/test/org/apache/jasper/el/TestJasperELResolver.java
@@ -88,7 +88,14 @@ public class TestJasperELResolver {
         Assert.assertNull(resolver.getValue(context, new TestBean(), "foobar"));
         Assert.assertNull(resolver.getValue(context, new TestBean(), "bar"));
         Assert.assertFalse(resolver.isReadOnly(context, new TestBean(), "foo"));
-        Assert.assertTrue(resolver.isReadOnly(context, new TestBean(), "bla"));
+        Assert.assertFalse(resolver.isReadOnly(context, new TestBean(), "bla"));
+
+        // A setter whose parameter type is a supertype of the value type must
+        // be used. The inverted assignability check in getWriteMethod()
+        // previously rejected such setters, silently dropping the write.
+        TestBean bean = new TestBean();
+        resolver.setValue(context, bean, "bla", "a string value");
+        Assert.assertEquals("a string value", bean.getLastBla());
     }
 
     public static class TestBean {
@@ -108,10 +115,15 @@ public class TestJasperELResolver {
         public String isFoobar() {
             return "foobar";
         }
+        private Object bla;
         public String getBla() {
             return "bla";
         }
-        public void setBla(@SuppressWarnings("unused") Object bla) {
+        public void setBla(Object bla) {
+            this.bla = bla;
+        }
+        public Object getLastBla() {
+            return bla;
         }
     }
 }
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 089311352d..a07fe17e74 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -421,6 +421,14 @@
         text node from being trimmed when <code>trim</code> was
         <code>true</code>. (remm)
       </fix>
+      <fix>
+        Correct the assignability check <code>GraalBeanELResolver</code> uses
+        when selecting a setter for an EL value. The check was inverted, so a
+        setter whose parameter type was a super-type of the value type, for
+        example a setter taking <code>Object</code> or an interface, was
+        rejected and EL writes to such properties could be silently dropped
+        when running in a GraalVM native image. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 19/46: Avoid NullPointerException writing a null bean property value

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 5162412292d5d36b52cecfd7e1279f326dcdabc2
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 10:29:24 2026 +0200

    Avoid NullPointerException writing a null bean property value
    
    GraalBeanELResolver.setValue() derived the value class from the value
    itself in order to select a setter whose parameter type the value could
    be assigned to. A null value has no class, so writing null to any bean
    property raised a NullPointerException under GraalVM native image.
    
    Compute the value class defensively and pass null to getWriteMethod(),
    which already treats a null value class as matching any setter, so a
    reference-typed setter now receives the null value. Extend the existing
    Graal resolver test with the null value case and a type mismatch case
    that asserts the property is left unresolved.
    
    Found by code review.
---
 java/org/apache/jasper/el/JasperELResolver.java     |  5 ++++-
 test/org/apache/jasper/el/TestJasperELResolver.java | 15 +++++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/jasper/el/JasperELResolver.java b/java/org/apache/jasper/el/JasperELResolver.java
index e7f33bb8e3..8fb27a8d77 100644
--- a/java/org/apache/jasper/el/JasperELResolver.java
+++ b/java/org/apache/jasper/el/JasperELResolver.java
@@ -231,7 +231,10 @@ public class JasperELResolver extends CompositeELResolver {
             if (base == null || property == null) {
                 return;
             }
-            Method method = getWriteMethod(base.getClass(), property.toString(), value.getClass());
+            // A null value has no class to check the setter against. Pass null
+            // and let getWriteMethod() select a reference-typed setter
+            Class<?> valueClass = value == null ? null : value.getClass();
+            Method method = getWriteMethod(base.getClass(), property.toString(), valueClass);
             if (method != null) {
                 context.setPropertyResolved(base, property);
                 try {
diff --git a/test/org/apache/jasper/el/TestJasperELResolver.java b/test/org/apache/jasper/el/TestJasperELResolver.java
index 465e6faaa3..a6f202c36c 100644
--- a/test/org/apache/jasper/el/TestJasperELResolver.java
+++ b/test/org/apache/jasper/el/TestJasperELResolver.java
@@ -96,6 +96,21 @@ public class TestJasperELResolver {
         TestBean bean = new TestBean();
         resolver.setValue(context, bean, "bla", "a string value");
         Assert.assertEquals("a string value", bean.getLastBla());
+
+        // A null value has no class to check the setter against. It must reach
+        // a setter whose parameter can hold null. Before the fix, deriving the
+        // value class from the null value caused a NullPointerException here.
+        context.setPropertyResolved(false);
+        resolver.setValue(context, bean, "bla", null);
+        Assert.assertNull("A null value should be written to a reference-typed setter", bean.getLastBla());
+        Assert.assertTrue("A null value should resolve the property", context.isPropertyResolved());
+
+        // A value whose type the setter parameter cannot hold must be left
+        // unresolved so that another resolver in the chain can handle it
+        context.setPropertyResolved(false);
+        resolver.setValue(context, bean, "foo", Integer.valueOf(7));
+        Assert.assertFalse("A mismatched value must leave the property unresolved",
+                context.isPropertyResolved());
     }
 
     public static class TestBean {


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 46/46: Java compatibility

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit c15a98ec3d41f1f160583868ded9bf36155ac317
Author: remm <re...@apache.org>
AuthorDate: Mon Oct 19 23:42:45 2026 +0200

    Java compatibility
---
 java/org/apache/jasper/el/JspMethodExpression.java | 3 ++-
 java/org/apache/jasper/el/JspValueExpression.java  | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/jasper/el/JspMethodExpression.java b/java/org/apache/jasper/el/JspMethodExpression.java
index fddf3b8727..dc419bd1ed 100644
--- a/java/org/apache/jasper/el/JspMethodExpression.java
+++ b/java/org/apache/jasper/el/JspMethodExpression.java
@@ -145,9 +145,10 @@ public final class JspMethodExpression extends MethodExpression implements Exter
         if (obj == this) {
             return true;
         }
-        if (!(obj instanceof JspMethodExpression other)) {
+        if (!(obj instanceof JspMethodExpression)) {
             return false;
         }
+        JspMethodExpression other = (JspMethodExpression) obj;
         return Objects.equals(this.mark, other.mark) && this.target.equals(other.target);
     }
 
diff --git a/java/org/apache/jasper/el/JspValueExpression.java b/java/org/apache/jasper/el/JspValueExpression.java
index 25858ca70d..4f54a402e9 100644
--- a/java/org/apache/jasper/el/JspValueExpression.java
+++ b/java/org/apache/jasper/el/JspValueExpression.java
@@ -150,9 +150,10 @@ public final class JspValueExpression extends ValueExpression implements Externa
         if (obj == this) {
             return true;
         }
-        if (!(obj instanceof JspValueExpression other)) {
+        if (!(obj instanceof JspValueExpression)) {
             return false;
         }
+        JspValueExpression other = (JspValueExpression) obj;
         return Objects.equals(this.mark, other.mark) && this.target.equals(other.target);
     }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 10/46: Validate page directive buffer values against the JSP specification

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 947f7f75ca76b581790c0d8662f4bc98751542e3
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 22:40:21 2026 +0200

    Validate page directive buffer values against the JSP specification
    
    JSP.7.2.1 requires the buffer attribute to be "none" or a positive
    integer followed by "kb". PageInfo.setBufferValue() only checked that
    the value ended in "kb" and that the remainder parsed as an integer.
    The multiplication of that integer by 1024 was not range checked.
    
    Out of range values therefore produced nonsense buffer sizes in the
    generated servlet. For example, buffer="4194304kb" silently over-flowed
    to zero, running the page unbuffered, while buffer="2097152kb"
    over-flowed to Integer.MIN_VALUE and buffer="-1kb" produced a negative
    size. The negative sizes passed translation and made every request for
    the page fail at run time with an IllegalArgumentException from the
    JspWriterImpl constructor. Zero and negative values are invalid in
    themselves per the specification.
    
    Reject values outside the range 1kb to (Integer.MAX_VALUE / 1024)kb
    during translation using the existing error message. The validation is
    applied in setBufferValue() so it covers values from page directives,
    JSP property groups and the XML syntax equivalently.
    
    Found by code review.
---
 java/org/apache/jasper/compiler/PageInfo.java     | 10 +++
 test/org/apache/jasper/compiler/TestPageInfo.java | 79 +++++++++++++++++++++++
 test/webapp/jsp/pageinfo/buffer-min.jsp           | 18 ++++++
 test/webapp/jsp/pageinfo/buffer-negative.jsp      | 18 ++++++
 test/webapp/jsp/pageinfo/buffer-none.jsp          | 18 ++++++
 test/webapp/jsp/pageinfo/buffer-overflow.jsp      | 18 ++++++
 test/webapp/jsp/pageinfo/buffer-valid.jsp         | 18 ++++++
 test/webapp/jsp/pageinfo/buffer-zero.jsp          | 18 ++++++
 8 files changed, 197 insertions(+)

diff --git a/java/org/apache/jasper/compiler/PageInfo.java b/java/org/apache/jasper/compiler/PageInfo.java
index 9100102403..734291e187 100644
--- a/java/org/apache/jasper/compiler/PageInfo.java
+++ b/java/org/apache/jasper/compiler/PageInfo.java
@@ -623,6 +623,16 @@ public class PageInfo {
             try {
                 @SuppressWarnings("null") // value can't be null here
                 int k = Integer.parseInt(value.substring(0, value.length() - 2));
+                // JSP.7.2.1 requires a positive integer. Values outside this
+                // range are invalid in themselves and would additionally
+                // overflow the multiplication by 1024 below.
+                if (k <= 0 || k > Integer.MAX_VALUE / 1024) {
+                    if (n == null) {
+                        err.jspError("jsp.error.page.invalid.buffer");
+                    } else {
+                        err.jspError(n, "jsp.error.page.invalid.buffer");
+                    }
+                }
                 buffer = k * 1024;
             } catch (NumberFormatException e) {
                 if (n == null) {
diff --git a/test/org/apache/jasper/compiler/TestPageInfo.java b/test/org/apache/jasper/compiler/TestPageInfo.java
new file mode 100644
index 0000000000..4a97557bae
--- /dev/null
+++ b/test/org/apache/jasper/compiler/TestPageInfo.java
@@ -0,0 +1,79 @@
+/*
+ * 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.jasper.compiler;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.tomcat.util.buf.ByteChunk;
+
+public class TestPageInfo extends TomcatBaseTest {
+
+    @Test
+    public void testBufferNone() throws Exception {
+        doTestBuffer("none", 200, null);
+    }
+
+    @Test
+    public void testBufferValid() throws Exception {
+        doTestBuffer("valid", 200, null);
+    }
+
+    @Test
+    public void testBufferZero() throws Exception {
+        // JSP.7.2.1 requires a positive integer
+        doTestBuffer("zero", 500, "invalid value for buffer");
+    }
+
+    @Test
+    public void testBufferNegative() throws Exception {
+        // JSP.7.2.1 requires a positive integer
+        doTestBuffer("negative", 500, "invalid value for buffer");
+    }
+
+    @Test
+    public void testBufferOverflowMinimum() throws Exception {
+        // The multiplication by 1024 overflows to Integer.MIN_VALUE
+        doTestBuffer("min", 500, "invalid value for buffer");
+    }
+
+    @Test
+    public void testBufferOverflowWrapAround() throws Exception {
+        // The multiplication by 1024 overflows to zero
+        doTestBuffer("overflow", 500, "invalid value for buffer");
+    }
+
+    private void doTestBuffer(String name, int expectedStatus, String expectedMessage) throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk res = new ByteChunk();
+        int sc = getUrl("http://localhost:" + getPort() + "/test/jsp/pageinfo/buffer-" + name + ".jsp", res, null);
+
+        Assert.assertEquals(expectedStatus, sc);
+
+        String result = res.toString();
+        if (expectedMessage == null) {
+            Assert.assertTrue(result, result.contains("OK"));
+        } else {
+            // The page should fail translation with a clear message. Before
+            // the range was validated, overflow and negative values either
+            // passed translation silently or failed later at run time.
+            Assert.assertTrue(result, result.contains(expectedMessage));
+        }
+    }
+}
diff --git a/test/webapp/jsp/pageinfo/buffer-min.jsp b/test/webapp/jsp/pageinfo/buffer-min.jsp
new file mode 100644
index 0000000000..ef0dc6930f
--- /dev/null
+++ b/test/webapp/jsp/pageinfo/buffer-min.jsp
@@ -0,0 +1,18 @@
+<%--
+ 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.
+--%>
+<%@ page buffer="2097152kb" %>
+OK
diff --git a/test/webapp/jsp/pageinfo/buffer-negative.jsp b/test/webapp/jsp/pageinfo/buffer-negative.jsp
new file mode 100644
index 0000000000..36f4314739
--- /dev/null
+++ b/test/webapp/jsp/pageinfo/buffer-negative.jsp
@@ -0,0 +1,18 @@
+<%--
+ 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.
+--%>
+<%@ page buffer="-1kb" %>
+OK
diff --git a/test/webapp/jsp/pageinfo/buffer-none.jsp b/test/webapp/jsp/pageinfo/buffer-none.jsp
new file mode 100644
index 0000000000..e777f6d3db
--- /dev/null
+++ b/test/webapp/jsp/pageinfo/buffer-none.jsp
@@ -0,0 +1,18 @@
+<%--
+ 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.
+--%>
+<%@ page buffer="none" %>
+OK
diff --git a/test/webapp/jsp/pageinfo/buffer-overflow.jsp b/test/webapp/jsp/pageinfo/buffer-overflow.jsp
new file mode 100644
index 0000000000..1c4c1f86c5
--- /dev/null
+++ b/test/webapp/jsp/pageinfo/buffer-overflow.jsp
@@ -0,0 +1,18 @@
+<%--
+ 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.
+--%>
+<%@ page buffer="4194304kb" %>
+OK
diff --git a/test/webapp/jsp/pageinfo/buffer-valid.jsp b/test/webapp/jsp/pageinfo/buffer-valid.jsp
new file mode 100644
index 0000000000..0d78801afc
--- /dev/null
+++ b/test/webapp/jsp/pageinfo/buffer-valid.jsp
@@ -0,0 +1,18 @@
+<%--
+ 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.
+--%>
+<%@ page buffer="8kb" %>
+OK
diff --git a/test/webapp/jsp/pageinfo/buffer-zero.jsp b/test/webapp/jsp/pageinfo/buffer-zero.jsp
new file mode 100644
index 0000000000..315ce9d0c1
--- /dev/null
+++ b/test/webapp/jsp/pageinfo/buffer-zero.jsp
@@ -0,0 +1,18 @@
+<%--
+ 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.
+--%>
+<%@ page buffer="0kb" %>
+OK


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 36/46: Trim and escape the Out tag plugin body fallback

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit d18bcf61d18ac2aafd1060ad92384bec72e85c90
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 15:00:28 2026 +0200

    Trim and escape the Out tag plugin body fallback
    
    When the c:out value is null and no default attribute is given, the tag
    body provides the output. The reference tag handler buffers the body,
    trims it, and writes the result as text, escaping it when escapeXml is
    enabled. The tag plugin emitted the body inline instead, so the
    whitespace written around the body content was kept and the content of
    expressions within the body reached the response unescaped, whatever
    escapeXml said.
    
    The generated code now buffers the body through _jspx_page_context, like
    the handler does, and writes the trimmed string through the same helper
    that escapes the value attribute. The buffering is unwound in a finally
    block, as the container does for a buffered tag body, so a body that
    fails does not leave the output redirected to the discarded buffer.
---
 .../apache/jasper/tagplugins/jstl/core/Out.java    | 24 +++++++++++++
 .../jasper/tagplugins/jstl/core/TestOut.java       | 41 ++++++++++++++++++++++
 test/webapp/jstl/out-body.jsp                      | 38 ++++++++++++++++++++
 webapps/docs/changelog.xml                         |  9 +++++
 4 files changed, 112 insertions(+)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/Out.java b/java/org/apache/jasper/tagplugins/jstl/core/Out.java
index 12cd8471b4..a5f0811149 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/Out.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/Out.java
@@ -52,6 +52,8 @@ public final class Out implements TagPlugin {
         String strDefName = ctxt.getTemporaryVariableName();
         String strEscapeXmlName = ctxt.getTemporaryVariableName();
         String strSkipBodyName = ctxt.getTemporaryVariableName();
+        String strBodyContentName = ctxt.getTemporaryVariableName();
+        String strBodyName = ctxt.getTemporaryVariableName();
 
         // the value attribute is not mandatory; the tag body is a fallback.
         ctxt.generateImport("java.io.Reader");
@@ -90,7 +92,29 @@ public final class Out implements TagPlugin {
                 "boolean " + strSkipBodyName + " = " + "org.apache.jasper.tagplugins.jstl.core.Out.output(out, " +
                         strObjectName + ", " + strValName + ", " + strDefName + ", " + strEscapeXmlName + ");");
         ctxt.generateJavaSource("if(!" + strSkipBodyName + ") {");
+        // Neither the value nor the default produced output. As in the
+        // standard tag handler, capture the body content, then output it
+        // trimmed and escaped according to the escapeXml attribute. The
+        // capture is unwound in a finally block, so a failing body does
+        // not leave the output redirected, as the container does when a
+        // buffered tag body throws.
+        ctxt.generateJavaSource("jakarta.servlet.jsp.tagext.BodyContent " +
+                strBodyContentName + " = _jspx_page_context.pushBody();");
+        ctxt.generateJavaSource("out = " + strBodyContentName + ";");
+        ctxt.generateJavaSource("String " + strBodyName + ";");
+        ctxt.generateJavaSource("try {");
         ctxt.generateBody();
+        ctxt.generateJavaSource("} finally {");
+        ctxt.generateJavaSource("    " + strBodyName + " = " +
+                strBodyContentName + ".getString().trim();");
+        ctxt.generateJavaSource("    out = _jspx_page_context.popBody();");
+        ctxt.generateJavaSource("}");
+        ctxt.generateJavaSource("if(" + strEscapeXmlName + ") {");
+        ctxt.generateJavaSource("    out.write(org.apache.jasper.tagplugins.jstl.Util.escapeXml(" +
+                strBodyName + "));");
+        ctxt.generateJavaSource("} else {");
+        ctxt.generateJavaSource("    out.write(" + strBodyName + ");");
+        ctxt.generateJavaSource("}");
         ctxt.generateJavaSource("}");
     }
 
diff --git a/test/org/apache/jasper/tagplugins/jstl/core/TestOut.java b/test/org/apache/jasper/tagplugins/jstl/core/TestOut.java
index f578928ba7..de68d3f547 100644
--- a/test/org/apache/jasper/tagplugins/jstl/core/TestOut.java
+++ b/test/org/apache/jasper/tagplugins/jstl/core/TestOut.java
@@ -56,4 +56,45 @@ public class TestOut extends AbstractTestTag {
         Assert.assertTrue(body.contains("OK - 4"));
         Assert.assertFalse(body.contains("FAIL"));
     }
+
+
+    /*
+     * When the value is null, the tag body is the fallback. Like the
+     * reference JSTL implementation, the body content is used as a string
+     * that is trimmed and then escaped according to escapeXml.
+     */
+    @Test
+    public void testBodyFallback() throws Exception {
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() +
+                "/test/jstl/out-body.jsp", res, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String body = res.toString();
+        // The whitespace surrounding the body content is removed
+        Assert.assertTrue(body, body.contains("TRIM=[spaced body]"));
+        // The body content is escaped, like the value attribute is
+        Assert.assertTrue(body, body.contains("ESC=[&lt;x&gt;]"));
+        // ... unless escaping is switched off
+        Assert.assertTrue(body, body.contains("RAW=[<x>]"));
+        // A body of only whitespace outputs nothing
+        Assert.assertTrue(body, body.contains("SPACE=[]"));
+        // A non-null value skips the body
+        Assert.assertTrue(body, body.contains("SKIP=[V]"));
+        // An empty body outputs nothing
+        Assert.assertTrue(body, body.contains("NONE=[]"));
+        // A nested tag body is buffered by both tags, and the outer one
+        // still trims the whole content
+        Assert.assertTrue(body, body.contains("NEST=[AB inner CD]"));
+        // A Reader is written without escaping and skips the body
+        Assert.assertTrue(body, body.contains("READER=[READOK]"));
+        Assert.assertFalse(body, body.contains("IGNORED"));
+        // The content of a failing body is not written
+        Assert.assertFalse(body, body.contains("lost"));
+        // ... and output continues after it
+        Assert.assertTrue(body, body.contains("LEAK=[]"));
+        Assert.assertTrue(body, body.contains("TAIL=[visible]"));
+    }
 }
diff --git a/test/webapp/jstl/out-body.jsp b/test/webapp/jstl/out-body.jsp
new file mode 100644
index 0000000000..7e25efda2a
--- /dev/null
+++ b/test/webapp/jstl/out-body.jsp
@@ -0,0 +1,38 @@
+<%--
+ 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.
+--%>
+<%@ page session="true" contentType="text/html; charset=UTF-8"
+         pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
+<% request.setAttribute("testReader", new java.io.StringReader("READOK")); %>
+<p>TRIM=[<c:out value="${sessionScope.doesNotExist}">
+    spaced body
+</c:out>]</p>
+<p>ESC=[<c:out value="${sessionScope.doesNotExist}">${'<x>'}</c:out>]</p>
+<p>RAW=[<c:out value="${sessionScope.doesNotExist}"
+    escapeXml="false">${'<x>'}</c:out>]</p>
+<p>SPACE=[<c:out value="${sessionScope.doesNotExist}"> </c:out>]</p>
+<p>SKIP=[<c:out value="V">BODY</c:out>]</p>
+<p>NONE=[<c:out value="${sessionScope.doesNotExist}"/>]</p>
+<p>NEST=[<c:out value="${sessionScope.doesNotExist}">AB <c:out
+    value="${sessionScope.doesNotExist}"> inner </c:out> CD</c:out>]</p>
+<p>READER=[<c:out value="${testReader}">IGNORED</c:out>]</p>
+<p>LEAK=[<c:catch><c:out value="${sessionScope.doesNotExist}">lost<%
+    if (true) {
+        throw new IllegalStateException("body failed");
+    }
+%></c:out></c:catch>]</p>
+<p>TAIL=[visible]</p>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index ee206f6ff6..7c6798263a 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -450,6 +450,15 @@
         which keeps the parameters of each tag to itself and never touches
         page scope attributes. (remm)
       </fix>
+      <fix>
+        The tag plugin for <code>c:out</code> now uses its body as the
+        fallback for a null value like the standard tag handler does: the
+        body content is captured, trimmed, then written with escaping
+        according to the <code>escapeXml</code> attribute, and the capture
+        is unwound if the body fails. The plugin previously wrote the body
+        inline, including its surrounding whitespace, and did not escape
+        the body content. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 08/46: Fix the jsp:attribute trim loop skipping nodes after removal

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 0ffa6fac2d8c071dd3619d357649cfbcb2b2f540
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 22:16:49 2026 +0200

    Fix the jsp:attribute trim loop skipping nodes after removal
    
    When removing white-space only template text nodes from the body of a
    jsp:attribute action while parsing a JSP document, the loop in
    JspDocumentParser.endElement() did not re-examine the node that was
    shifted into the vacated position after a removal.
    
    Adjacent template text siblings occur in practice when the attribute
    body contains CDATA sections, because the startCDATA/endCDATA handling
    flushes the buffered characters into a template text node without
    creating a separating node. For such bodies the skipped node could be a
    second white-space only text node that then remained in the body, or the
    final text node which consequently was not trimmed when trim was true.
    
    Re-examine the shifted node after each removal so every text node
    receives the treatment required by the specification. Add a regression
    test using CDATA sections in jsp:attribute bodies.
    
    Found by code review.
---
 .../apache/jasper/compiler/JspDocumentParser.java  |  3 ++
 .../jasper/compiler/TestJspDocumentParser.java     | 23 ++++++++++++++
 test/webapp/jsp/document/named-attribute-trim.jspx | 37 ++++++++++++++++++++++
 webapps/docs/changelog.xml                         | 10 ++++++
 4 files changed, 73 insertions(+)

diff --git a/java/org/apache/jasper/compiler/JspDocumentParser.java b/java/org/apache/jasper/compiler/JspDocumentParser.java
index af9ade8dfd..8d3a07e816 100644
--- a/java/org/apache/jasper/compiler/JspDocumentParser.java
+++ b/java/org/apache/jasper/compiler/JspDocumentParser.java
@@ -550,6 +550,9 @@ class JspDocumentParser extends DefaultHandler2 implements TagConstants {
                 } else {
                     if (((Node.TemplateText) subElem).isAllSpace()) {
                         subElems.remove(subElem);
+                        // Re-examine the element that was shifted into this
+                        // position by the removal above
+                        i--;
                     }
                 }
             }
diff --git a/test/org/apache/jasper/compiler/TestJspDocumentParser.java b/test/org/apache/jasper/compiler/TestJspDocumentParser.java
index 71eedd8fca..bee183b256 100644
--- a/test/org/apache/jasper/compiler/TestJspDocumentParser.java
+++ b/test/org/apache/jasper/compiler/TestJspDocumentParser.java
@@ -85,6 +85,29 @@ public class TestJspDocumentParser extends TomcatBaseTest {
         Assert.assertEquals(HttpServletResponse.SC_OK, rc);
     }
 
+    @Test
+    public void testNamedAttributeTrimCdata() throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk bc = new ByteChunk();
+        int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/document/named-attribute-trim.jspx", bc, null);
+
+        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
+
+        String result = bc.toString();
+
+        // White-space only text nodes between the other body elements must be
+        // removed and the final text node must be trimmed
+        Assert.assertTrue(result, result.contains("<e1 a=\"x tail\"/>"));
+        Assert.assertTrue(result, result.contains("<e2 a=\"x\"/>"));
+        Assert.assertTrue(result, result.contains("<e3 a=\"xy\"/>"));
+        Assert.assertTrue(result, result.contains("<e4 a=\"x y\"/>"));
+        // With trim set to false, leading and trailing white-space only text
+        // nodes must be kept verbatim
+        Assert.assertTrue(result, result.contains("<t5 a=\"  \"/>"));
+        Assert.assertTrue(result, result.contains("<t6 a=\"x tail \"/>"));
+    }
+
     @Test
     public void testSchemaValidation() throws Exception {
         getTomcatInstanceTestWebapp(false, true);
diff --git a/test/webapp/jsp/document/named-attribute-trim.jspx b/test/webapp/jsp/document/named-attribute-trim.jspx
new file mode 100644
index 0000000000..5422dc524e
--- /dev/null
+++ b/test/webapp/jsp/document/named-attribute-trim.jspx
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
+  <!--
+    Regression tests for the handling of adjacent template text nodes -
+    produced by CDATA sections - in the body of a jsp:attribute action.
+    Expected results are given in comments below. Each element name encodes
+    the trim setting: e* for trim="true" (the default), t* for trim="false".
+  -->
+  <!-- Middle white-space only node removed, trailing node trimmed: "x tail" -->
+  <jsp:element name="e1"><jsp:attribute name="a"><jsp:text>x</jsp:text><![CDATA[ ]]><![CDATA[ tail ]]></jsp:attribute></jsp:element>
+  <!-- Both consecutive white-space only middle nodes removed: "x" -->
+  <jsp:element name="e2"><jsp:attribute name="a"><jsp:text>x</jsp:text><![CDATA[ ]]><![CDATA[ ]]></jsp:attribute></jsp:element>
+  <!-- Second of two consecutive white-space only middle nodes removed: "xy" -->
+  <jsp:element name="e3"><jsp:attribute name="a"><jsp:text>x</jsp:text><![CDATA[ ]]><![CDATA[ ]]><jsp:text>y</jsp:text></jsp:attribute></jsp:element>
+  <!-- Single CDATA between text nodes, trailing node trimmed: "x y" -->
+  <jsp:element name="e4"><jsp:attribute name="a">x<![CDATA[ ]]> y </jsp:attribute></jsp:element>
+  <!-- Leading and trailing white-space only nodes kept verbatim: "  " -->
+  <jsp:element name="t5"><jsp:attribute name="a" trim="false"><![CDATA[ ]]><![CDATA[ ]]></jsp:attribute></jsp:element>
+  <!-- Middle node removed, trailing node kept verbatim: "x tail " -->
+  <jsp:element name="t6"><jsp:attribute name="a" trim="false">x<![CDATA[ ]]><![CDATA[ tail ]]></jsp:attribute></jsp:element>
+</jsp:root>
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 4575af986d..089311352d 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -411,6 +411,16 @@
         silently omitted from processing. Option parsing now stops at the
         first full stop argument wherever it appears. (remm)
       </fix>
+      <fix>
+        When removing white-space only template text nodes from the body of a
+        <code>jsp:attribute</code> action while parsing a JSP document, the
+        node that was shifted into the vacated position is now re-examined.
+        Previously it was skipped, which, for bodies containing adjacent
+        template text nodes such as those produced by CDATA sections, could
+        leave a white-space only text node in the body or prevent the final
+        text node from being trimmed when <code>trim</code> was
+        <code>true</code>. (remm)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="WebSocket">


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 13/46: Report a translation error for an empty taglib URI

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 380eb782f9d60b941074349fa7d7046fb312f2ec
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 09:37:58 2026 +0200

    Report a translation error for an empty taglib URI
    
    A classic syntax page using <%@ taglib uri="" prefix="p" %> passed the
    null checks in Parser.parseTaglibDirective() with an empty string, so
    generateTldResourcePath() evaluated uri.charAt(0) on a zero-length
    string. The resulting StringIndexOutOfBoundsException was only caught
    by the generic RuntimeException handler in Compiler.generateJava(), so
    the page failed with a raw runtime exception instead of a JSP
    translation error.
    
    The XML syntax path could reach the same code by supplying an empty
    namespace remainder, for example xmlns:p="urn:jsptld:", since the
    plain URI handling in JspDocumentParser does not apply once the
    urn:jsptld: prefix has been removed.
    
    Reject an empty URI at the start of generateTldResourcePath() with the
    existing jsp.error.taglibDirective.uriInvalid message, which is the
    same error used by the sibling branches for malformed URIs.
    
    Found by code review.
---
 .../apache/jasper/compiler/TagLibraryInfoImpl.java |  4 ++++
 .../jasper/compiler/TestTagLibraryInfoImpl.java    | 18 ++++++++++++++++
 test/webapp/jsp/parsing/taglib-empty-uri.jsp       | 24 ++++++++++++++++++++++
 3 files changed, 46 insertions(+)

diff --git a/java/org/apache/jasper/compiler/TagLibraryInfoImpl.java b/java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
index 02aae498a4..7d02e5f8cb 100644
--- a/java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
+++ b/java/org/apache/jasper/compiler/TagLibraryInfoImpl.java
@@ -228,6 +228,10 @@ class TagLibraryInfoImpl extends TagLibraryInfo implements TagConstants {
      */
     private TldResourcePath generateTldResourcePath(String uri, JspCompilationContext ctxt) throws JasperException {
 
+        if (uri.isEmpty()) {
+            err.jspError("jsp.error.taglibDirective.uriInvalid", uri);
+        }
+
         // TODO: this matches the current implementation but the URL logic looks fishy
         // map URI to location per JSP 7.3.6.2
         if (uri.indexOf(':') != -1) {
diff --git a/test/org/apache/jasper/compiler/TestTagLibraryInfoImpl.java b/test/org/apache/jasper/compiler/TestTagLibraryInfoImpl.java
index a9caf237fa..c830607a58 100644
--- a/test/org/apache/jasper/compiler/TestTagLibraryInfoImpl.java
+++ b/test/org/apache/jasper/compiler/TestTagLibraryInfoImpl.java
@@ -55,6 +55,24 @@ public class TestTagLibraryInfoImpl extends TomcatBaseTest {
         Assert.assertEquals(HttpServletResponse.SC_OK, rc);
     }
 
+    @Test
+    public void testEmptyTaglibUri() throws Exception {
+        getTomcatInstanceTestWebapp(false, true);
+
+        ByteChunk res = new ByteChunk();
+
+        int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/parsing/taglib-empty-uri.jsp", res, null);
+        Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
+
+        // An empty taglib URI must produce a clean translation error. It
+        // previously triggered a StringIndexOutOfBoundsException in
+        // TagLibraryInfoImpl.generateTldResourcePath() that was reported
+        // instead of the translation error.
+        String result = res.toString();
+        Assert.assertTrue(result, result.contains("is not a valid URI"));
+        Assert.assertFalse(result, result.contains("StringIndexOutOfBoundsException"));
+    }
+
     /*
      * https://bz.apache.org/bugzilla/show_bug.cgi?id=64373
      */
diff --git a/test/webapp/jsp/parsing/taglib-empty-uri.jsp b/test/webapp/jsp/parsing/taglib-empty-uri.jsp
new file mode 100644
index 0000000000..b407e0c540
--- /dev/null
+++ b/test/webapp/jsp/parsing/taglib-empty-uri.jsp
@@ -0,0 +1,24 @@
+<%--
+ 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.
+--%>
+<%@ page contentType="text/html;charset=UTF-8" %>
+<%@ taglib uri="" prefix="p" %>
+<html>
+  <head><title>Taglib with an empty URI test case</title></head>
+  <body>
+    <p>Should fail</p>
+  </body>
+</html>


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 21/46: Keep the wrapped exception in the JSP EL exception cause chain

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 3428bfa6a47ecaa0581acf37f85770cfd3f1d320
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 10:37:48 2026 +0200

    Keep the wrapped exception in the JSP EL exception cause chain
    
    The four JSP EL exception wrappers prepended the JSP location mark to
    the message of the exception being wrapped but set the cause to the
    cause of that exception rather than the exception itself. When the
    wrapped exception had no cause, the wrapper ended up with no cause at
    all, discarding the wrapped exception's type and stack trace so that
    only the prefixed message text survived.
    
    Keep the wrapped exception itself as the cause. Its own cause remains
    reachable transitively, and sites that inspect the cause, such as
    PageContextImpl.handlePageException(), now observe the wrapped
    exception instead of losing it.
    
    Found by code review.
---
 java/org/apache/jasper/el/JspELException.java                  | 2 +-
 java/org/apache/jasper/el/JspMethodNotFoundException.java      | 2 +-
 java/org/apache/jasper/el/JspPropertyNotFoundException.java    | 2 +-
 java/org/apache/jasper/el/JspPropertyNotWritableException.java | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/java/org/apache/jasper/el/JspELException.java b/java/org/apache/jasper/el/JspELException.java
index 4394956d4f..6a28b9ef73 100644
--- a/java/org/apache/jasper/el/JspELException.java
+++ b/java/org/apache/jasper/el/JspELException.java
@@ -32,6 +32,6 @@ public class JspELException extends ELException {
      * @param e the underlying ELException
      */
     public JspELException(String mark, ELException e) {
-        super(mark + " " + e.getMessage(), e.getCause());
+        super(mark + " " + e.getMessage(), e);
     }
 }
diff --git a/java/org/apache/jasper/el/JspMethodNotFoundException.java b/java/org/apache/jasper/el/JspMethodNotFoundException.java
index b0947f226e..32614f666c 100644
--- a/java/org/apache/jasper/el/JspMethodNotFoundException.java
+++ b/java/org/apache/jasper/el/JspMethodNotFoundException.java
@@ -32,6 +32,6 @@ public class JspMethodNotFoundException extends MethodNotFoundException {
      * @param e the underlying MethodNotFoundException
      */
     public JspMethodNotFoundException(String mark, MethodNotFoundException e) {
-        super(mark + " " + e.getMessage(), e.getCause());
+        super(mark + " " + e.getMessage(), e);
     }
 }
diff --git a/java/org/apache/jasper/el/JspPropertyNotFoundException.java b/java/org/apache/jasper/el/JspPropertyNotFoundException.java
index 72c8ec150b..3bd7c655ec 100644
--- a/java/org/apache/jasper/el/JspPropertyNotFoundException.java
+++ b/java/org/apache/jasper/el/JspPropertyNotFoundException.java
@@ -32,7 +32,7 @@ public final class JspPropertyNotFoundException extends PropertyNotFoundExceptio
      * @param e The cause exception
      */
     public JspPropertyNotFoundException(String mark, PropertyNotFoundException e) {
-        super(mark + " " + e.getMessage(), e.getCause());
+        super(mark + " " + e.getMessage(), e);
     }
 
 }
diff --git a/java/org/apache/jasper/el/JspPropertyNotWritableException.java b/java/org/apache/jasper/el/JspPropertyNotWritableException.java
index 788b74680c..85185f9e34 100644
--- a/java/org/apache/jasper/el/JspPropertyNotWritableException.java
+++ b/java/org/apache/jasper/el/JspPropertyNotWritableException.java
@@ -32,6 +32,6 @@ public class JspPropertyNotWritableException extends PropertyNotWritableExceptio
      * @param e The cause exception
      */
     public JspPropertyNotWritableException(String mark, PropertyNotWritableException e) {
-        super(mark + " " + e.getMessage(), e.getCause());
+        super(mark + " " + e.getMessage(), e);
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 34/46: Compute the ForEach tag plugin's state flags per request

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit a0de9017cec3c87d97859b1410fae03f505cea90
Author: opencode <re...@apache.org>
AuthorDate: Mon Oct 19 13:58:11 2026 +0200

    Compute the ForEach tag plugin's state flags per request
    
    The plugin instance is shared across concurrent page
    translations, so the hasVar/hasBegin/hasEnd/hasStep flags that
    control the loop are now computed as locals in doTag() and
    passed to the iteration helpers instead of being stored in
    instance fields, which allowed one request's settings to be
    observed by another request iterating concurrently.
    
    Found by code review.
---
 .../apache/jasper/tagplugins/jstl/core/ForEach.java    | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)

diff --git a/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java b/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
index e69446a0f2..57353edcde 100644
--- a/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
+++ b/java/org/apache/jasper/tagplugins/jstl/core/ForEach.java
@@ -30,8 +30,6 @@ public final class ForEach implements TagPlugin {
         // Default constructor
     }
 
-    private boolean hasVar, hasBegin, hasEnd, hasStep;
-
     @Override
     public void doTag(TagPluginContext ctxt) {
 
@@ -43,14 +41,17 @@ public final class ForEach implements TagPlugin {
             return;
         }
 
-        hasVar = ctxt.isAttributeSpecified("var");
-        hasBegin = ctxt.isAttributeSpecified("begin");
-        hasEnd = ctxt.isAttributeSpecified("end");
-        hasStep = ctxt.isAttributeSpecified("step");
+        // Local variables, not instance fields: a single plugin instance is
+        // shared by all translations of the web application, which may run
+        // concurrently.
+        boolean hasVar = ctxt.isAttributeSpecified("var");
+        boolean hasBegin = ctxt.isAttributeSpecified("begin");
+        boolean hasEnd = ctxt.isAttributeSpecified("end");
+        boolean hasStep = ctxt.isAttributeSpecified("step");
 
         boolean hasItems = ctxt.isAttributeSpecified("items");
         if (hasItems) {
-            doCollection(ctxt);
+            doCollection(ctxt, hasVar, hasBegin, hasEnd, hasStep);
             return;
         }
 
@@ -118,7 +119,8 @@ public final class ForEach implements TagPlugin {
     /**
      * Generate codes for Collections.
      */
-    private void doCollection(TagPluginContext ctxt) {
+    private void doCollection(TagPluginContext ctxt, boolean hasVar,
+            boolean hasBegin, boolean hasEnd, boolean hasStep) {
 
         ctxt.generateImport("java.util.*");
         generateIterators(ctxt);


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org