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

markt-asf pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/9.0.x by this push:
     new cfae70907e Fix AsyncContext.dispatch() when the request URI contains 
dot segments
cfae70907e is described below

commit cfae70907ec3f1b3b4c1fd20ecd8a5bf522e79bf
Author: Mark Thomas <[email protected]>
AuthorDate: Wed Nov 25 19:10:09 2026 +0000

    Fix AsyncContext.dispatch() when the request URI contains dot segments
    
    getContextPathEncoded() returned the first prefix of the request URI that
    matched the context path. If the remainder of the URI then climbed out of
    the context (e.g. /examples/../examples/async/async0 or
    /examples/a/b/c/../../../../examples/async/async0) the dispatch path was
    rejected, an UnsupportedOperationException was thrown and, if the caller was
    not a container thread, the request stayed in the async state until it
    timed out.
    
    Keep extending the candidate until the remainder stays within the context
    and fall back to the first match if there is no such candidate.
    
    Also check that there is a dispatcher before updating the async attributes
    so a failed dispatch does not modify the request.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
    (cherry picked from commit 721d23f70b74463cf6075041e1652abaa43c3a0c)
---
 .../apache/catalina/core/ApplicationContext.java   |  16 +-
 .../org/apache/catalina/core/AsyncContextImpl.java |  12 +-
 java/org/apache/catalina/util/RequestUtil.java     | 138 ++++++---
 .../apache/catalina/core/TestAsyncContextImpl.java | 233 +++++++++++++++
 test/org/apache/catalina/util/TestRequestUtil.java | 327 +++++++++++++++++++++
 webapps/docs/changelog.xml                         |  10 +
 6 files changed, 691 insertions(+), 45 deletions(-)

diff --git a/java/org/apache/catalina/core/ApplicationContext.java 
b/java/org/apache/catalina/core/ApplicationContext.java
index b7fd13a02a..70653980c3 100644
--- a/java/org/apache/catalina/core/ApplicationContext.java
+++ b/java/org/apache/catalina/core/ApplicationContext.java
@@ -379,7 +379,15 @@ public class ApplicationContext implements ServletContext {
         if (path == null) {
             return null;
         }
-        if (!path.startsWith("/")) {
+        /*
+         * The path must start with a '/'. The exception is a path from 
AsyncContext.dispatch(). That is a substring of
+         * the request URI and, as the connector may treat an encoded solidus 
(%2f) or an encoded reverse solidus (%5c)
+         * as a path separator, it may start with one. Whether such a path is 
valid depends on the configuration of the
+         * Context so that is checked once the path has been decoded.
+         */
+        boolean startsWithEncodedSeparator = 
AsyncContextImpl.uriEncoded.get().booleanValue() &&
+                (path.regionMatches(true, 0, "%2f", 0, 3) || 
path.regionMatches(true, 0, "%5c", 0, 3));
+        if (!path.startsWith("/") && !startsWithEncodedSeparator) {
             throw new 
IllegalArgumentException(sm.getString("applicationContext.requestDispatcher.iae",
 path));
         }
 
@@ -409,6 +417,12 @@ public class ApplicationContext implements ServletContext {
                     context.getEncodedReverseSolidusHandlingEnum());
         }
 
+        if (startsWithEncodedSeparator && !uriToMap.startsWith("/") && 
!uriToMap.startsWith("\\")) {
+            // The encoded separator at the start of the path was not decoded 
(it is being passed through) so the path
+            // does not start with a '/'
+            throw new 
IllegalArgumentException(sm.getString("applicationContext.requestDispatcher.iae",
 path));
+        }
+
         // Then normalize
         uriToMap = RequestUtil.normalize(uriToMap);
         if (uriToMap == null) {
diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java 
b/java/org/apache/catalina/core/AsyncContextImpl.java
index 84473b9745..41e4230f90 100644
--- a/java/org/apache/catalina/core/AsyncContextImpl.java
+++ b/java/org/apache/catalina/core/AsyncContextImpl.java
@@ -271,6 +271,13 @@ public class AsyncContextImpl implements AsyncContext, 
AsyncContextCallback {
             if (dispatch != null) {
                 throw new 
IllegalStateException(sm.getString("asyncContextImpl.dispatchingStarted"));
             }
+            final RequestDispatcher requestDispatcher = 
servletContext.getRequestDispatcher(path);
+            if (!(requestDispatcher instanceof AsyncDispatcher)) {
+                // Fail before changing the state of the request so the caller 
can recover (e.g. complete() or
+                // dispatch to a different path)
+                throw new 
UnsupportedOperationException(sm.getString("asyncContextImpl.noAsyncDispatcher"));
+            }
+            final AsyncDispatcher applicationDispatcher = (AsyncDispatcher) 
requestDispatcher;
             if (request.getAttribute(ASYNC_REQUEST_URI) == null) {
                 request.setAttribute(ASYNC_REQUEST_URI, 
request.getRequestURI());
                 request.setAttribute(ASYNC_CONTEXT_PATH, 
request.getContextPath());
@@ -278,11 +285,6 @@ public class AsyncContextImpl implements AsyncContext, 
AsyncContextCallback {
                 request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo());
                 request.setAttribute(ASYNC_QUERY_STRING, 
request.getQueryString());
             }
-            final RequestDispatcher requestDispatcher = 
servletContext.getRequestDispatcher(path);
-            if (!(requestDispatcher instanceof AsyncDispatcher)) {
-                throw new 
UnsupportedOperationException(sm.getString("asyncContextImpl.noAsyncDispatcher"));
-            }
-            final AsyncDispatcher applicationDispatcher = (AsyncDispatcher) 
requestDispatcher;
             final ServletRequest servletRequest = getRequest();
             final ServletResponse servletResponse = getResponse();
             this.dispatch = new AsyncRunnable(request, applicationDispatcher, 
servletRequest, servletResponse);
diff --git a/java/org/apache/catalina/util/RequestUtil.java 
b/java/org/apache/catalina/util/RequestUtil.java
index 7df9a18583..40609f56f8 100644
--- a/java/org/apache/catalina/util/RequestUtil.java
+++ b/java/org/apache/catalina/util/RequestUtil.java
@@ -36,6 +36,9 @@ public final class RequestUtil {
 
     private static final StringManager sm = 
StringManager.getManager(RequestUtil.class);
 
+    // Marker for 'no candidate has matched the context path yet'. -1 is used 
to represent the end of the URI.
+    private static final int NO_MATCH = -2;
+
     /**
      * Default constructor.
      */
@@ -221,6 +224,7 @@ public final class RequestUtil {
         String canonicalContextPath = 
request.getServletContext().getContextPath();
         Connector connector = request.getConnector();
         EncodedSolidusHandling encodedSolidusHandling = 
connector.getEncodedSolidusHandlingInternal();
+        EncodedSolidusHandling encodedReverseSolidusHandling = 
connector.getEncodedReverseSolidusHandlingInternal();
 
         int pos = 0;
         if (!context.getAllowMultipleLeadingForwardSlashInPath()) {
@@ -237,49 +241,89 @@ public final class RequestUtil {
         char[] uriChars = uri.toCharArray();
         // Need at least the number of slashes in the context path
         while (lastSlash > 0) {
-            pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling);
+            pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling, 
encodedReverseSolidusHandling);
             if (pos == -1) {
                 break;
             }
             lastSlash--;
         }
-        // Now allow for path parameters, normalization and/or encoding.
-        // Essentially, keep extending the candidate path up to the next slash
-        // until the decoded and normalized candidate path (with the path
-        // parameters removed) is the same as the canonical path.
-        String candidate;
-        if (pos == -1) {
-            candidate = uri;
-        } else {
-            candidate = uri.substring(0, pos);
-        }
-        candidate = removePathParameters(candidate);
-        candidate = UDecoder.URLDecode(candidate, connector.getURICharset());
-        candidate = 
org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
-        boolean match = canonicalContextPath.equals(candidate);
-        while (!match && pos != -1) {
-            pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling);
-            if (pos == -1) {
-                candidate = uri;
-            } else {
-                candidate = uri.substring(0, pos);
-            }
+        /*
+         * Now allow for path parameters, normalization and/or encoding. 
Essentially, keep extending the candidate path
+         * up to the next slash until the decoded and normalized candidate 
path (with the path parameters removed) is
+         * the same as the canonical path.
+         *
+         * There may be more than one candidate that matches. For example, 
/examples/../examples matches the context
+         * path /examples as does /examples. If the remainder of the URI after 
the first candidate climbs out of the
+         * context (e.g. /../examples/foo or /a/b/../../../examples/foo) then 
the context path in the URI must be
+         * longer. Keep going until a candidate that matches is followed by a 
remainder that stays within the
+         * context. If there isn't one, fall back to the first match, which is 
what was returned before the remainder
+         * was considered. That should only be possible for a URI that the 
connector would not have mapped to this
+         * context in which case no candidate can be used for a dispatch.
+         */
+        int firstMatchPos = NO_MATCH;
+        while (true) {
+            String candidate = pos == -1 ? uri : uri.substring(0, pos);
             candidate = removePathParameters(candidate);
-            candidate = UDecoder.URLDecode(candidate, 
connector.getURICharset());
-            candidate = 
org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
-            match = canonicalContextPath.equals(candidate);
-        }
-        if (match) {
+            try {
+                candidate = decode(candidate, connector);
+                candidate = 
org.apache.tomcat.util.http.RequestUtil.normalize(candidate);
+            } catch (IllegalArgumentException iae) {
+                // Invalid or rejected encoding. This candidate can't match.
+                candidate = null;
+            }
+            if (canonicalContextPath.equals(candidate)) {
+                if (firstMatchPos == NO_MATCH) {
+                    firstMatchPos = pos;
+                }
+                if (pos == -1 || isRemainderWithinContext(uri.substring(pos), 
connector)) {
+                    return pos == -1 ? uri : uri.substring(0, pos);
+                }
+            }
             if (pos == -1) {
-                return uri;
-            } else {
-                return uri.substring(0, pos);
+                break;
             }
-        } else {
-            // Should never happen
-            throw new IllegalStateException(
-                    sm.getString("requestUtil.getContextPath.ise", 
canonicalContextPath, uri));
+            pos = nextSlash(uriChars, pos + 1, encodedSolidusHandling, 
encodedReverseSolidusHandling);
         }
+
+        if (firstMatchPos != NO_MATCH) {
+            return firstMatchPos == -1 ? uri : uri.substring(0, firstMatchPos);
+        }
+
+        // Should never happen
+        throw new 
IllegalStateException(sm.getString("requestUtil.getContextPath.ise", 
canonicalContextPath, uri));
+    }
+
+
+    /**
+     * Does the remainder of the URI, after the context path, stay within the 
context once path parameters have been
+     * removed, it has been decoded and normalized? This is the same 
processing that is applied to the path of a
+     * dispatch so a remainder that fails this test could not be used for one. 
The decoding must follow the connector's
+     * configuration for encoded solidus and reverse solidus. If, for example, 
they are passed through, an encoded
+     * solidus is part of a path segment and not a separator so it can not be 
part of a '..' that leaves the context.
+     */
+    private static boolean isRemainderWithinContext(String remainder, 
Connector connector) {
+        String path = removePathParameters(remainder);
+        try {
+            path = decode(path, connector);
+        } catch (IllegalArgumentException iae) {
+            /*
+             * Invalid or, more likely, rejected encoding. A request with such 
a URI would have been rejected before
+             * it was processed. Don't look for a longer context path.
+             */
+            return true;
+        }
+        return org.apache.tomcat.util.http.RequestUtil.normalize(path) != null;
+    }
+
+
+    /**
+     * Decode part of a request URI using the connector's configuration for 
encoded solidus and reverse solidus. These
+     * must be handled in the same way as when the connector processed the 
request URI. If, for example, they are
+     * passed through, an encoded solidus is part of a path segment and not a 
separator.
+     */
+    private static String decode(String input, Connector connector) {
+        return UDecoder.URLDecode(input, connector.getURICharset(), 
connector.getEncodedSolidusHandlingInternal(),
+                connector.getEncodedReverseSolidusHandlingInternal());
     }
 
 
@@ -309,16 +353,32 @@ public final class RequestUtil {
     }
 
 
-    private static int nextSlash(char[] uri, int startPos, 
EncodedSolidusHandling encodedSolidusHandling) {
+    private static int nextSlash(char[] uri, int startPos, 
EncodedSolidusHandling encodedSolidusHandling,
+            EncodedSolidusHandling encodedReverseSolidusHandling) {
         int len = uri.length;
         int pos = startPos;
         while (pos < len) {
             if (uri[pos] == '/') {
                 return pos;
-            } else if (encodedSolidusHandling == EncodedSolidusHandling.DECODE 
&&
-                    uri[pos] == '%' && pos + 2 < len && uri[pos + 1] == '2' &&
-                    (uri[pos + 2] == 'f' || uri[pos + 2] == 'F')) {
-                return pos;
+            } else if (uri[pos] == ';') {
+                /*
+                 * Path parameters are removed before the URI is decoded so 
anything that looks like an encoded solidus
+                 * (or reverse solidus) within them is not a separator. Skip 
to the end of the path parameters which is
+                 * the next solidus.
+                 */
+                do {
+                    pos++;
+                } while (pos < len && uri[pos] != '/');
+                return pos < len ? pos : -1;
+            } else if (uri[pos] == '%' && pos + 2 < len) {
+                // An encoded solidus (or reverse solidus) is a separator if 
the connector decodes it
+                if (encodedSolidusHandling == EncodedSolidusHandling.DECODE && 
uri[pos + 1] == '2' &&
+                        (uri[pos + 2] == 'f' || uri[pos + 2] == 'F')) {
+                    return pos;
+                } else if (encodedReverseSolidusHandling == 
EncodedSolidusHandling.DECODE && uri[pos + 1] == '5' &&
+                        (uri[pos + 2] == 'c' || uri[pos + 2] == 'C')) {
+                    return pos;
+                }
             }
             pos++;
         }
diff --git a/test/org/apache/catalina/core/TestAsyncContextImpl.java 
b/test/org/apache/catalina/core/TestAsyncContextImpl.java
index db3c10d16a..7061174415 100644
--- a/test/org/apache/catalina/core/TestAsyncContextImpl.java
+++ b/test/org/apache/catalina/core/TestAsyncContextImpl.java
@@ -53,6 +53,7 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.junit.Assert;
+import org.junit.BeforeClass;
 import org.junit.Test;
 
 import static org.apache.catalina.startup.SimpleHttpClient.CRLF;
@@ -77,6 +78,16 @@ import org.easymock.EasyMock;
 
 public class TestAsyncContextImpl extends TomcatBaseTest {
 
+    /*
+     * Some of the tests use a request URI that contains an encoded reverse 
solidus which the connector decodes. The
+     * resulting backslash is only accepted if backslashes are allowed. That 
is a JVM wide setting that is read when
+     * CoyoteAdapter is loaded so it applies to the entire test class.
+     */
+    @BeforeClass
+    public static void allowBackslash() {
+        
System.setProperty("org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH",
 "true");
+    }
+
     // Time for a request to process (need to allow for threads to start etc.)
     private static final long REQUEST_TIME = 1500;
     // Timeout thread (where used) checks for timeout every second
@@ -2548,6 +2559,228 @@ public class TestAsyncContextImpl extends 
TomcatBaseTest {
     }
 
 
+    /*
+     * The request URI includes dot segments that return to the context path. 
The remainder of the URI must still be
+     * used for the dispatch. The servlet should see exactly the same path 
info before and after the dispatch.
+     */
+    @Test
+    public void testAsyncDispatchDotSegmentsAfterContextPath() throws 
Exception {
+        doTestAsyncDispatchPath("/test/../test/semicolon/foo", "/foo|/foo");
+    }
+
+
+    @Test
+    public void testAsyncDispatchDotSegmentsAfterContextPathRepeated() throws 
Exception {
+        doTestAsyncDispatchPath("/test/../test/../test/semicolon/foo", 
"/foo|/foo");
+    }
+
+
+    /*
+     * The dot segments that climb out of the context follow other segments 
rather than immediately following the
+     * context path.
+     */
+    @Test
+    public void testAsyncDispatchDotSegmentsLaterClimbOutOfContext() throws 
Exception {
+        doTestAsyncDispatchPath("/test/a/b/c/../../../../test/semicolon/foo", 
"/foo|/foo");
+    }
+
+
+    @Test
+    public void testAsyncDispatchEncodedDotSegmentsAfterContextPath() throws 
Exception {
+        doTestAsyncDispatchPath("/test/%2e%2e/test/semicolon/foo", 
"/foo|/foo");
+    }
+
+
+    /*
+     * A failed dispatch must not change the state of the request. The 
application must be able to recover from the
+     * failure. In particular, the async attributes that record the original 
request must not have been set by the
+     * failed attempt.
+     */
+    @Test
+    public void testAsyncDispatchFailureLeavesRequestUnchanged() throws 
Exception {
+        Tomcat tomcat = getTomcatInstance();
+        Context context = tomcat.addContext("/test", null);
+        // Disable class path scanning - it slows the tests down by almost an 
order of magnitude
+        ((StandardJarScanner) context.getJarScanner()).setScanClassPath(false);
+
+        Wrapper w = Tomcat.addServlet(context, "recover", new 
AsyncDispatchFailureServlet());
+        w.setAsyncSupported(true);
+        context.addServletMapping("/recover", "recover");
+        tomcat.start();
+
+        ByteChunk responseBody = new ByteChunk();
+        int rc = getUrl("http://localhost:"; + getPort() + "/test/recover", 
responseBody, null);
+
+        Assert.assertEquals(200, rc);
+        // Failed with UnsupportedOperationException, no async attribute set, 
then the recovery dispatch worked
+        Assert.assertEquals("UOE|null|dispatched", responseBody.toString());
+    }
+
+
+    private static class AsyncDispatchFailureServlet extends HttpServlet {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
+            if (req.getDispatcherType() == DispatcherType.ASYNC) {
+                resp.setContentType("text/plain");
+                resp.getWriter().print(req.getAttribute("result") + 
"|dispatched");
+                return;
+            }
+
+            AsyncContext ac = req.startAsync();
+            String result;
+            try {
+                // Escapes the context so there is no dispatcher
+                ac.dispatch("/../outside");
+                result = "dispatched?";
+            } catch (UnsupportedOperationException e) {
+                result = "UOE";
+            }
+            // The async attributes (set when a dispatch is made) must not 
have been set by the failed attempt
+            result = result + "|" + 
req.getAttribute(AsyncContext.ASYNC_REQUEST_URI);
+            req.setAttribute("result", result);
+            // Recover from the failure
+            ac.dispatch();
+        }
+    }
+
+
+    /*
+     * The connector decodes encoded solidus so, when the context path is 
removed from the request URI, an encoded solidus
+     * may be the first character of the path that is used for the dispatch. 
That is only a valid path if the context
+     * is configured to decode encoded solidus. The servlet must see exactly 
the same path info before and after the
+     * dispatch.
+     */
+    private static final String[][] ENCODED_SOLIDUS_CASES = {
+            { "/test%2fsemicolon%2ffoo", "/foo|/foo" },
+            { "/test/../test%2fsemicolon/foo", "/foo|/foo" },
+            { "/test%2f..%2ftest%2fsemicolon%2ffoo", "/foo|/foo" },
+            { "/test/../test%2fx/../semicolon/foo", "/foo|/foo" },
+            // Only one level of decoding
+            { "/test%2fsemicolon%2ffoo%252fbar", "/foo%2fbar|/foo%2fbar" } };
+
+
+    @Test
+    public void testAsyncDispatchEncodedSolidusDecodeContextDecode() throws 
Exception {
+        doTestAsyncDispatchPaths(ENCODED_SOLIDUS_CASES, "decode", "reject", 
"decode", "reject", 200);
+    }
+
+
+    @Test
+    public void testAsyncDispatchEncodedSolidusDecodeContextReject() throws 
Exception {
+        // The path used for the dispatch starts with an encoded solidus which 
the context rejects
+        doTestAsyncDispatchPaths(
+                new String[][] { ENCODED_SOLIDUS_CASES[0], 
ENCODED_SOLIDUS_CASES[1], ENCODED_SOLIDUS_CASES[2] },
+                "decode", "reject", "reject", "reject", 500);
+    }
+
+
+    @Test
+    public void testAsyncDispatchEncodedSolidusDecodeContextPassThrough() 
throws Exception {
+        // The encoded solidus is not decoded so the path used for the 
dispatch does not start with a '/'
+        doTestAsyncDispatchPaths(new String[][] { ENCODED_SOLIDUS_CASES[0] }, 
"decode", "reject", "passthrough",
+                "reject", 500);
+    }
+
+
+    /*
+     * The encoded solidus are passed through so test%2fx is a single path 
segment. The dot segments return to the
+     * context path after it. The path used for the dispatch does not contain 
an encoded solidus so does not depend on
+     * the configuration of the context.
+     */
+    @Test
+    public void testAsyncDispatchEncodedSolidusPassThroughContextReject() 
throws Exception {
+        doTestAsyncDispatchPaths(new String[][] { { 
"/test/../test%2fx/../test/semicolon/foo", "/foo|/foo" } },
+                "passthrough", "passthrough", "reject", "reject", 200);
+    }
+
+
+    @Test
+    public void testAsyncDispatchEncodedSolidusPassThroughContextPassThrough() 
throws Exception {
+        doTestAsyncDispatchPaths(new String[][] { { 
"/test/../test%2fx/../test/semicolon/foo", "/foo|/foo" } },
+                "passthrough", "passthrough", "passthrough", "passthrough", 
200);
+    }
+
+
+    /*
+     * Path parameters are removed before the request URI is decoded so an 
encoded solidus or reverse solidus within one
+     * is not a separator. The path used for the dispatch is the path that 
follows the path parameters.
+     */
+    @Test
+    public void testAsyncDispatchEncodedSeparatorInPathParameter() throws 
Exception {
+        doTestAsyncDispatchPaths(new String[][] { { 
"/test;v=%2fignored/semicolon/foo", "/foo|/foo" },
+                { "/test;v=%5cignored/semicolon/foo", "/foo|/foo" } }, 
"decode", "decode", "decode", "decode",
+                200);
+    }
+
+
+    @Test
+    public void testAsyncDispatchEncodedReverseSolidusDecodeContextDecode() 
throws Exception {
+        doTestAsyncDispatchPaths(
+                new String[][] { { "/test%5csemicolon%5cfoo", "/foo|/foo" },
+                        { "/test/../test%5cx/../semicolon/foo", "/foo|/foo" } 
},
+                "reject", "decode", "reject", "decode", 200);
+    }
+
+
+    @Test
+    public void testAsyncDispatchEncodedReverseSolidusDecodeContextReject() 
throws Exception {
+        doTestAsyncDispatchPaths(new String[][] { { "/test%5csemicolon%5cfoo", 
"/foo|/foo" } }, "reject", "decode",
+                "reject", "reject", 500);
+    }
+
+
+    private void doTestAsyncDispatchPaths(String[][] cases, String 
encodedSolidusHandling,
+            String encodedReverseSolidusHandling, String 
contextEncodedSolidusHandling,
+            String contextEncodedReverseSolidusHandling, int expectedStatus)
+            throws Exception {
+        Tomcat tomcat = getTomcatInstance();
+        
tomcat.getConnector().setEncodedSolidusHandling(encodedSolidusHandling);
+        
tomcat.getConnector().setEncodedReverseSolidusHandling(encodedReverseSolidusHandling);
+        Context context = tomcat.addContext("/test", null);
+        context.setEncodedSolidusHandling(contextEncodedSolidusHandling);
+        
context.setEncodedReverseSolidusHandling(contextEncodedReverseSolidusHandling);
+        // Disable class path scanning - it slows the tests down by almost an 
order of magnitude
+        ((StandardJarScanner) context.getJarScanner()).setScanClassPath(false);
+
+        Wrapper w = Tomcat.addServlet(context, "semicolon", new 
AsyncDispatchPathInfoServlet());
+        w.setAsyncSupported(true);
+        context.addServletMapping("/semicolon/*", "semicolon");
+        tomcat.start();
+
+        for (String[] testCase : cases) {
+            ByteChunk responseBody = new ByteChunk();
+            int rc = getUrl("http://localhost:"; + getPort() + testCase[0], 
responseBody, null);
+
+            Assert.assertEquals(testCase[0], expectedStatus, rc);
+            if (expectedStatus == 200) {
+                Assert.assertEquals(testCase[0], testCase[1], 
responseBody.toString());
+            }
+        }
+    }
+
+
+    private void doTestAsyncDispatchPath(String path, String expected) throws 
Exception {
+        Tomcat tomcat = getTomcatInstance();
+        Context context = tomcat.addContext("/test", null);
+        // Disable class path scanning - it slows the tests down by almost an 
order of magnitude
+        ((StandardJarScanner) context.getJarScanner()).setScanClassPath(false);
+
+        Wrapper w = Tomcat.addServlet(context, "semicolon", new 
AsyncDispatchPathInfoServlet());
+        w.setAsyncSupported(true);
+        context.addServletMapping("/semicolon/*", "semicolon");
+        tomcat.start();
+
+        ByteChunk responseBody = new ByteChunk();
+        int rc = getUrl("http://localhost:"; + getPort() + path, responseBody, 
null);
+
+        Assert.assertEquals(200, rc);
+        Assert.assertEquals(expected, responseBody.toString());
+    }
+
+
     /*
      * Multiple leading slashes in the request URI must not break 
AsyncContext.dispatch(). The servlet should see
      * exactly the same path info before and after the dispatch.
diff --git a/test/org/apache/catalina/util/TestRequestUtil.java 
b/test/org/apache/catalina/util/TestRequestUtil.java
new file mode 100644
index 0000000000..a197145f79
--- /dev/null
+++ b/test/org/apache/catalina/util/TestRequestUtil.java
@@ -0,0 +1,327 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.catalina.util;
+
+import javax.servlet.ServletContext;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.connector.Connector;
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.mapper.MappingData;
+import org.easymock.EasyMock;
+
+public class TestRequestUtil {
+
+    @Test
+    public void testGetContextPathEncodedRoot() {
+        doTestGetContextPathEncoded("", "/foo/bar", "");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedSimple() {
+        doTestGetContextPathEncoded("/examples", "/examples/async/async0", 
"/examples");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedNoServletPath() {
+        doTestGetContextPathEncoded("/examples", "/examples", "/examples");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedMultiSegment() {
+        doTestGetContextPathEncoded("/a/b", "/a/b/c/d", "/a/b");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedPathParameters() {
+        doTestGetContextPathEncoded("/examples", "/examples;a=b/async/async0", 
"/examples;a=b");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncoded() {
+        doTestGetContextPathEncoded("/ex amples", "/ex%20amples/async/async0", 
"/ex%20amples");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedMultipleSlashes() {
+        doTestGetContextPathEncoded("/examples", "/examples//async/async0", 
"/examples");
+    }
+
+
+    /*
+     * The context path is reached via a path that is normalized by the 
container.
+     */
+    @Test
+    public void testGetContextPathEncodedLeadingDotSegments() {
+        doTestGetContextPathEncoded("/examples", 
"/a/b/../../examples/async/async0", "/a/b/../../examples");
+    }
+
+
+    /*
+     * The first candidate that matches is followed by '..' so the context 
path must be longer. If it isn't, the
+     * remainder of the URI is not within the context.
+     */
+    @Test
+    public void testGetContextPathEncodedDotSegmentsAfterContext() {
+        doTestGetContextPathEncoded("/examples", 
"/examples/../examples/async/async0", "/examples/../examples");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedDotSegmentsAfterContextRepeated() {
+        doTestGetContextPathEncoded("/examples", 
"/examples/../examples/../examples/async/async0",
+                "/examples/../examples/../examples");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedDotSegmentsAfterContext() {
+        doTestGetContextPathEncoded("/examples", 
"/examples/%2e%2e/examples/async/async0",
+                "/examples/%2e%2e/examples");
+        doTestGetContextPathEncoded("/examples", 
"/examples/.%2E/examples/async/async0", "/examples/.%2E/examples");
+    }
+
+
+    @Test
+    public void 
testGetContextPathEncodedDotSegmentsWithPathParameterAfterContext() {
+        doTestGetContextPathEncoded("/examples", 
"/examples/..;x=y/examples/async/async0",
+                "/examples/..;x=y/examples");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedMultiSegmentDotSegmentsAfterContext() 
{
+        doTestGetContextPathEncoded("/a/b", "/a/b/../b/c/d", "/a/b/../b");
+    }
+
+
+    /*
+     * The dot segments that climb out of the context do not immediately 
follow the first match for the context path.
+     */
+    @Test
+    public void testGetContextPathEncodedDotSegmentsLaterClimbOutOfContext() {
+        doTestGetContextPathEncoded("/examples", 
"/examples/a/../../examples/async/async0",
+                "/examples/a/../../examples");
+        doTestGetContextPathEncoded("/examples", 
"/examples/a/b/c/../../../../examples/async/async0",
+                "/examples/a/b/c/../../../../examples");
+        doTestGetContextPathEncoded("/examples", 
"/examples/a/b/c/../../../../examples/a/../b",
+                "/examples/a/b/c/../../../../examples");
+    }
+
+
+    /*
+     * Enough dot segments to reach the context path but not to climb out of 
the context.
+     */
+    @Test
+    public void testGetContextPathEncodedDotSegmentsReturnToContext() {
+        doTestGetContextPathEncoded("/examples", "/examples/a/b/c/../../..", 
"/examples");
+        doTestGetContextPathEncoded("/examples", "/examples/a/b/c/../../../d", 
"/examples");
+    }
+
+
+    /*
+     * Dot segments that are within the servlet path / path info (do not climb 
out of the context) are not part of the
+     * context path.
+     */
+    @Test
+    public void testGetContextPathEncodedDotSegmentsWithinContext() {
+        doTestGetContextPathEncoded("/examples", "/examples/foo/../bar", 
"/examples");
+        doTestGetContextPathEncoded("/examples", "/examples/./bar", 
"/examples");
+    }
+
+
+    /*
+     * If there is no longer candidate that matches, the first match is used 
rather than failing.
+     */
+    @Test
+    public void testGetContextPathEncodedDotSegmentsNoLongerMatch() {
+        doTestGetContextPathEncoded("/examples", "/examples/../x", 
"/examples");
+        doTestGetContextPathEncoded("/examples", "/examples/..", "/examples");
+        // More dot segments than there are segments (the request would be 
rejected before this point)
+        doTestGetContextPathEncoded("/examples", 
"/examples/a/b/c/../../../../..", "/examples");
+    }
+
+
+    /*
+     * Encoded solidus and reverse solidus. The remainder of the URI must be 
decoded using the connector's
+     * configuration. If the encoded characters are passed through they are 
part of a path segment (not separators)
+     * so there is no '..' segment and the remainder does not leave the 
context.
+     */
+    @Test
+    public void testGetContextPathEncodedEncodedSolidusPassThrough() {
+        doTestGetContextPathEncoded("/test", 
"/test/a%2f..%2f..%2ftest/target", "/test", "passthrough",
+                "reject");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedSolidusDecode() {
+        // The encoded solidus are separators so the remainder does leave the 
context
+        doTestGetContextPathEncoded("/test", 
"/test/a%2f..%2f..%2ftest/target", "/test/a%2f..%2f..%2ftest", "decode",
+                "reject");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedSolidusReject() {
+        // Such requests are rejected before this method would be called. It 
must not fail.
+        doTestGetContextPathEncoded("/test", 
"/test/a%2f..%2f..%2ftest/target", "/test", "reject", "reject");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedReverseSolidusPassThrough() {
+        doTestGetContextPathEncoded("/test", 
"/test/a%5c..%5c..%5ctest/target", "/test", "reject", "passthrough");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedReverseSolidusDecode() {
+        doTestGetContextPathEncoded("/test", 
"/test/a%5c..%5c..%5ctest/target", "/test/a%5c..%5c..%5ctest", "reject",
+                "decode");
+    }
+
+
+    /*
+     * The candidates for the context path must be decoded using the 
connector's configuration too. If the encoded
+     * solidus are passed through, test%2fx is a single segment so 
/test/../test%2fx/.. does not return to /test.
+     */
+    @Test
+    public void testGetContextPathEncodedEncodedSolidusPassThroughCandidates() 
{
+        doTestGetContextPathEncoded("/test", 
"/test/../test%2fx/../test/target", "/test/../test%2fx/../test",
+                "passthrough", "reject");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedSolidusDecodeCandidates() {
+        // test%2fx is test/x so /test/../test%2fx/.. does return to /test
+        doTestGetContextPathEncoded("/test", 
"/test/../test%2fx/../test/target", "/test/../test",
+                "decode", "reject");
+    }
+
+
+    @Test
+    public void 
testGetContextPathEncodedEncodedReverseSolidusPassThroughCandidates() {
+        doTestGetContextPathEncoded("/test", 
"/test/../test%5cx/../test/target", "/test/../test%5cx/../test", "reject",
+                "passthrough");
+    }
+
+
+    @Test
+    public void 
testGetContextPathEncodedEncodedReverseSolidusDecodeCandidates() {
+        // The encoded reverse solidus is a separator so the context path ends 
at the first one that follows /test/../test
+        doTestGetContextPathEncoded("/test", 
"/test/../test%5cx/../test/target", "/test/../test", "reject", "decode");
+    }
+
+
+    /*
+     * If the connector decodes encoded solidus and/or encoded reverse solidus 
they are path separators so the context
+     * path may end at one.
+     */
+    @Test
+    public void testGetContextPathEncodedContextPathEndsAtEncodedSolidus() {
+        doTestGetContextPathEncoded("/test", "/test%2fx/target", "/test", 
"decode", "reject");
+        doTestGetContextPathEncoded("/test", "/test%5cx/target", "/test", 
"reject", "decode");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedContextPathContainsEncodedSolidus() {
+        doTestGetContextPathEncoded("/a/b", "/a%2fb/target", "/a%2fb", 
"decode", "reject");
+        doTestGetContextPathEncoded("/a/b", "/a%5cb/target", "/a%5cb", 
"reject", "decode");
+        doTestGetContextPathEncoded("/a/b/c", "/a%2fb%5cc/target", 
"/a%2fb%5cc", "decode", "decode");
+    }
+
+
+    /*
+     * Path parameters are removed before the URI is decoded so an encoded 
solidus or reverse solidus within a path
+     * parameter is not a separator.
+     */
+    @Test
+    public void testGetContextPathEncodedEncodedSeparatorInPathParameter() {
+        doTestGetContextPathEncoded("/test", "/test;v=%5cignored/target", 
"/test;v=%5cignored", "reject", "decode");
+        doTestGetContextPathEncoded("/test", "/test;v=%2fignored/target", 
"/test;v=%2fignored", "decode", "reject");
+        doTestGetContextPathEncoded("/test", "/test;a=%2f;b=%5c/target", 
"/test;a=%2f;b=%5c", "decode", "decode");
+        doTestGetContextPathEncoded("/a/b", "/a;x=%2f/b;y=%5c/c", 
"/a;x=%2f/b;y=%5c", "decode", "decode");
+    }
+
+
+    @Test
+    public void 
testGetContextPathEncodedEncodedSeparatorInPathParameterAfterContext() {
+        doTestGetContextPathEncoded("/test", "/test/target;v=%2fx", "/test", 
"decode", "decode");
+        doTestGetContextPathEncoded("/test", "/test/..;v=%2f/test/target", 
"/test/..;v=%2f/test", "decode", "decode");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedPathParameterToEndOfUri() {
+        doTestGetContextPathEncoded("/test", "/test;v=%2f", "/test;v=%2f", 
"decode", "decode");
+    }
+
+
+    @Test
+    public void testGetContextPathEncodedEncodedSeparatorsNotDecoded() {
+        // Neither is a separator unless the connector decodes it
+        doTestGetContextPathEncoded("/test", "/test/x%2fy%5cz", "/test", 
"passthrough", "passthrough");
+    }
+
+
+    private static void doTestGetContextPathEncoded(String 
canonicalContextPath, String requestUri, String expected,
+            String encodedSolidusHandling, String 
encodedReverseSolidusHandling) {
+        Connector connector = new Connector();
+        connector.setEncodedSolidusHandling(encodedSolidusHandling);
+        
connector.setEncodedReverseSolidusHandling(encodedReverseSolidusHandling);
+        doTestGetContextPathEncoded(canonicalContextPath, requestUri, 
expected, connector);
+    }
+
+
+    private static void doTestGetContextPathEncoded(String 
canonicalContextPath, String requestUri, String expected) {
+        doTestGetContextPathEncoded(canonicalContextPath, requestUri, 
expected, new Connector());
+    }
+
+
+    private static void doTestGetContextPathEncoded(String 
canonicalContextPath, String requestUri, String expected,
+            Connector connector) {
+        ServletContext servletContext = 
EasyMock.createMock(ServletContext.class);
+        
EasyMock.expect(servletContext.getContextPath()).andStubReturn(canonicalContextPath);
+        Context context = EasyMock.createMock(Context.class);
+        
EasyMock.expect(Boolean.valueOf(context.getAllowMultipleLeadingForwardSlashInPath())).andStubReturn(
+                Boolean.FALSE);
+        MappingData mappingData = new MappingData();
+        mappingData.contextSlashCount = (int) 
canonicalContextPath.chars().filter(c -> c == '/').count();
+        Request request = EasyMock.createMock(Request.class);
+        EasyMock.expect(request.getMappingData()).andStubReturn(mappingData);
+        
EasyMock.expect(request.getServletContext()).andStubReturn(servletContext);
+        EasyMock.expect(request.getContext()).andStubReturn(context);
+        EasyMock.expect(request.getConnector()).andStubReturn(connector);
+        EasyMock.expect(request.getRequestURI()).andStubReturn(requestUri);
+        EasyMock.replay(servletContext, context, request);
+
+        Assert.assertEquals(requestUri, expected, 
RequestUtil.getContextPathEncoded(request));
+    }
+
+}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 17a6d5318b..892aa6ba39 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -175,6 +175,16 @@
         fails because the protocol in use, such as AJP or HTTP/2, does not
         support HTTP upgrade. (markt)
       </fix>
+      <fix>
+        Fix <code>AsyncContext.dispatch()</code> when the request URI contains
+        <code>..</code> segments that return to the context path, such as
+        <code>/examples/../examples/async</code>. The context path derived from
+        the request URI now includes those segments so that the remainder of
+        the URI remains within the context. The context path, decoded as per 
the
+        connector settings, is removed before the remaining path is processed 
as
+        per the context decoding settings. Also ensure that a failed
+        asynchronous dispatch does not modify the request attributes. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to