Move the functionality that provides redirects for context roots and directories where a trailing <code>/</code> is added from the Mapper to the DefaultServlet. This enables such requests to be processed by any configured Valves and Filters before the redirect is made. This behaviour is configurable via the mapperContextRootRedirectEnabled and mapperDirectoryRedirectEnabled attributes of the Context which may be used to restore the previous behaviour.

git-svn-id: https://svn.apache.org/repos/asf/tomcat/tc8.0.x/trunk@1715207 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/java/org/apache/catalina/Context.java b/java/org/apache/catalina/Context.java
index 717fb6c..04112aa 100644
--- a/java/org/apache/catalina/Context.java
+++ b/java/org/apache/catalina/Context.java
@@ -1698,4 +1698,44 @@
      *         false}
      */
     public boolean getValidateClientProvidedNewSessionId();
+
+    /**
+     * If enabled, requests for a web application context root will be
+     * redirected (adding a trailing slash) by the Mapper. This is more
+     * efficient but has the side effect of confirming that the context path is
+     * valid.
+     *
+     * @param mapperContextRootRedirectEnabled Should the redirects be enabled?
+     */
+    public void setMapperContextRootRedirectEnabled(boolean mapperContextRootRedirectEnabled);
+
+    /**
+     * Determines if requests for a web application context root will be
+     * redirected (adding a trailing slash) by the Mapper. This is more
+     * efficient but has the side effect of confirming that the context path is
+     * valid.
+     *
+     * @return {@code true} if the Mapper level redirect is enabled for this
+     *         Context.
+     */
+    public boolean getMapperContextRootRedirectEnabled();
+
+    /**
+     * If enabled, requests for a directory will be redirected (adding a
+     * trailing slash) by the Mapper. This is more efficient but has the
+     * side effect of confirming that the directory is valid.
+     *
+     * @param mapperDirectoryRedirectEnabled Should the redirects be enabled?
+     */
+    public void setMapperDirectoryRedirectEnabled(boolean mapperDirectoryRedirectEnabled);
+
+    /**
+     * Determines if requests for a directory will be redirected (adding a
+     * trailing slash) by the Mapper. This is more efficient but has the
+     * side effect of confirming that the directory is valid.
+     *
+     * @return {@code true} if the Mapper level redirect is enabled for this
+     *         Context.
+     */
+    public boolean getMapperDirectoryRedirectEnabled();
 }
diff --git a/java/org/apache/catalina/core/StandardContext.java b/java/org/apache/catalina/core/StandardContext.java
index 000aa29..7a9ebcd 100644
--- a/java/org/apache/catalina/core/StandardContext.java
+++ b/java/org/apache/catalina/core/StandardContext.java
@@ -815,13 +815,53 @@
 
     private boolean validateClientProvidedNewSessionId = true;
 
+    boolean mapperContextRootRedirectEnabled = false;
+
+    boolean mapperDirectoryRedirectEnabled = false;
+
+
     // ----------------------------------------------------- Context Properties
 
     @Override
+    public void setMapperContextRootRedirectEnabled(boolean mapperContextRootRedirectEnabled) {
+        this.mapperContextRootRedirectEnabled = mapperContextRootRedirectEnabled;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     * <p>
+     * The default value for this implementation is {@code false}.
+     */
+    @Override
+    public boolean getMapperContextRootRedirectEnabled() {
+        return mapperContextRootRedirectEnabled;
+    }
+
+
+    @Override
+    public void setMapperDirectoryRedirectEnabled(boolean mapperDirectoryRedirectEnabled) {
+        this.mapperDirectoryRedirectEnabled = mapperDirectoryRedirectEnabled;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     * <p>
+     * The default value for this implementation is {@code false}.
+     */
+    @Override
+    public boolean getMapperDirectoryRedirectEnabled() {
+        return mapperDirectoryRedirectEnabled;
+    }
+
+
+    @Override
     public void setValidateClientProvidedNewSessionId(boolean validateClientProvidedNewSessionId) {
         this.validateClientProvidedNewSessionId = validateClientProvidedNewSessionId;
     }
 
+
     /**
      * {@inheritDoc}
      * <p>
@@ -832,6 +872,7 @@
         return validateClientProvidedNewSessionId;
     }
 
+
     @Override
     public void setCookieProcessor(CookieProcessor cookieProcessor) {
         if (cookieProcessor == null) {
diff --git a/java/org/apache/catalina/core/mbeans-descriptors.xml b/java/org/apache/catalina/core/mbeans-descriptors.xml
index bafd270..2893730 100644
--- a/java/org/apache/catalina/core/mbeans-descriptors.xml
+++ b/java/org/apache/catalina/core/mbeans-descriptors.xml
@@ -177,6 +177,14 @@
                description="Associated manager."
                type="org.apache.catalina.Manager" />
 
+    <attribute name="mapperContextRootRedirectEnabled"
+               description="Should the Mapper be used for context root redirects"
+               type="boolean" />
+
+    <attribute name="mapperDirectoryRedirectEnabled"
+               description="Should the Mapper be used for directory redirects"
+               type="boolean" />
+
     <attribute name="namingContextListener"
                description="Associated naming context listener."
                type="org.apache.catalina.core.NamingContextListener" />
diff --git a/java/org/apache/catalina/mapper/Mapper.java b/java/org/apache/catalina/mapper/Mapper.java
index 088a0af..318031c 100644
--- a/java/org/apache/catalina/mapper/Mapper.java
+++ b/java/org/apache/catalina/mapper/Mapper.java
@@ -884,7 +884,8 @@
             }
         }
 
-        if(mappingData.wrapper == null && noServletPath) {
+        if(mappingData.wrapper == null && noServletPath &&
+                mappingData.context.getMapperContextRootRedirectEnabled()) {
             // The path is empty, redirect to "/"
             mappingData.redirectPath.setChars
                 (path.getBuffer(), pathOffset, pathEnd-pathOffset);
@@ -1002,9 +1003,9 @@
             char[] buf = path.getBuffer();
             if (contextVersion.resources != null && buf[pathEnd -1 ] != '/') {
                 String pathStr = path.toString();
-                WebResource file =
-                        contextVersion.resources.getResource(pathStr);
-                if (file != null && file.isDirectory()) {
+                WebResource file = contextVersion.resources.getResource(pathStr);
+                if (file != null && file.isDirectory() &&
+                        mappingData.context.getMapperDirectoryRedirectEnabled()) {
                     // Note: this mutates the path: do not do any processing
                     // after this (since we set the redirectPath, there
                     // shouldn't be any)
@@ -1021,7 +1022,6 @@
 
         path.setOffset(pathOffset);
         path.setEnd(pathEnd);
-
     }
 
 
diff --git a/java/org/apache/catalina/servlets/DefaultServlet.java b/java/org/apache/catalina/servlets/DefaultServlet.java
index 9c10098..d3d3ccb 100644
--- a/java/org/apache/catalina/servlets/DefaultServlet.java
+++ b/java/org/apache/catalina/servlets/DefaultServlet.java
@@ -816,6 +816,17 @@
         long contentLength = -1L;
 
         if (resource.isDirectory()) {
+            if (!path.endsWith("/")) {
+                StringBuilder location = new StringBuilder(request.getRequestURI());
+                location.append('/');
+                if (request.getQueryString() != null) {
+                    location.append('?');
+                    location.append(request.getQueryString());
+                }
+                response.sendRedirect(response.encodeRedirectURL(location.toString()));
+                return;
+            }
+
             // Skip directory listings if we have been configured to
             // suppress them
             if (!listings) {
diff --git a/java/org/apache/catalina/startup/FailedContext.java b/java/org/apache/catalina/startup/FailedContext.java
index f2383ff..9a0407b 100644
--- a/java/org/apache/catalina/startup/FailedContext.java
+++ b/java/org/apache/catalina/startup/FailedContext.java
@@ -764,9 +764,25 @@
 
     @Override
     public void setValidateClientProvidedNewSessionId(boolean validateClientProvidedNewSessionId) {
-        //NO-OP
+        // NO-OP
     }
 
     @Override
     public boolean getValidateClientProvidedNewSessionId() { return false; }
+
+    @Override
+    public void setMapperContextRootRedirectEnabled(boolean mapperContextRootRedirectEnabled) {
+        // NO-OP
+    }
+
+    @Override
+    public boolean getMapperContextRootRedirectEnabled() { return false; }
+
+    @Override
+    public void setMapperDirectoryRedirectEnabled(boolean mapperDirectoryRedirectEnabled) {
+        // NO-OP
+    }
+
+    @Override
+    public boolean getMapperDirectoryRedirectEnabled() { return false; }
 }
\ No newline at end of file
diff --git a/test/org/apache/catalina/core/TesterContext.java b/test/org/apache/catalina/core/TesterContext.java
index d544c40..cdc5f78 100644
--- a/test/org/apache/catalina/core/TesterContext.java
+++ b/test/org/apache/catalina/core/TesterContext.java
@@ -1234,4 +1234,20 @@
 
     @Override
     public boolean getValidateClientProvidedNewSessionId() { return false; }
+
+    @Override
+    public void setMapperContextRootRedirectEnabled(boolean mapperContextRootRedirectEnabled) {
+        // NO-OP
+    }
+
+    @Override
+    public boolean getMapperContextRootRedirectEnabled() { return false; }
+
+    @Override
+    public void setMapperDirectoryRedirectEnabled(boolean mapperDirectoryRedirectEnabled) {
+        // NO-OP
+    }
+
+    @Override
+    public boolean getMapperDirectoryRedirectEnabled() { return false; }
 }
diff --git a/test/org/apache/catalina/mapper/TestMapperWebapps.java b/test/org/apache/catalina/mapper/TestMapperWebapps.java
index 51e725c..236eff2 100644
--- a/test/org/apache/catalina/mapper/TestMapperWebapps.java
+++ b/test/org/apache/catalina/mapper/TestMapperWebapps.java
@@ -18,6 +18,7 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.net.HttpURLConnection;
 import java.util.HashMap;
 import java.util.List;
 
@@ -33,7 +34,10 @@
 import org.apache.catalina.core.StandardContext;
 import org.apache.catalina.startup.Tomcat;
 import org.apache.catalina.startup.TomcatBaseTest;
+import org.apache.catalina.valves.RemoteAddrValve;
 import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.descriptor.web.SecurityCollection;
+import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
 import org.apache.tomcat.websocket.server.WsContextListener;
 
 /**
@@ -225,6 +229,66 @@
         Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
     }
 
+    @Test
+    public void testRedirect() throws Exception {
+        // Disable the following of redirects for this test only
+        boolean originalValue = HttpURLConnection.getFollowRedirects();
+        HttpURLConnection.setFollowRedirects(false);
+        try {
+            Tomcat tomcat = getTomcatInstance();
+
+            // Use standard test webapp as ROOT
+            File rootDir = new File("test/webapp");
+            org.apache.catalina.Context root =
+                    tomcat.addWebapp(null, "", rootDir.getAbsolutePath());
+
+            // Add a security constraint
+            SecurityConstraint constraint = new SecurityConstraint();
+            SecurityCollection collection = new SecurityCollection();
+            collection.addPattern("/welcome-files/*");
+            collection.addPattern("/welcome-files");
+            constraint.addCollection(collection);
+            constraint.addAuthRole("foo");
+            root.addConstraint(constraint);
+
+            // Also make examples available
+            File examplesDir = new File(getBuildDirectory(), "webapps/examples");
+            org.apache.catalina.Context examples  = tomcat.addWebapp(
+                    null, "/examples", examplesDir.getAbsolutePath());
+            // Then block access to the examples to test redirection
+            RemoteAddrValve rav = new RemoteAddrValve();
+            rav.setDeny(".*");
+            rav.setDenyStatus(404);
+            examples.getPipeline().addValve(rav);
+
+            tomcat.start();
+
+            // Redirects within a web application
+            doRedirectTest("/welcome-files", 401);
+            doRedirectTest("/welcome-files/", 401);
+
+            doRedirectTest("/jsp", 302);
+            doRedirectTest("/jsp/", 404);
+
+            doRedirectTest("/WEB-INF", 404);
+            doRedirectTest("/WEB-INF/", 404);
+
+            // Redirects between web applications
+            doRedirectTest("/examples", 404);
+            doRedirectTest("/examples/", 404);
+        } finally {
+            HttpURLConnection.setFollowRedirects(originalValue);
+        }
+    }
+
+
+    private void doRedirectTest(String path, int expected) throws IOException {
+        ByteChunk bc = new ByteChunk();
+        int rc = getUrl("http://localhost:" + getPort() + path, bc, null);
+        Assert.assertEquals(expected, rc);
+    }
+
+
     /**
      * Prepare a string to search in messages that contain a timestamp, when it
      * is known that the timestamp was printed between {@code timeA} and
diff --git a/test/org/apache/catalina/startup/TomcatBaseTest.java b/test/org/apache/catalina/startup/TomcatBaseTest.java
index f5613dd..bdf9f01 100644
--- a/test/org/apache/catalina/startup/TomcatBaseTest.java
+++ b/test/org/apache/catalina/startup/TomcatBaseTest.java
@@ -646,8 +646,7 @@
             String method) throws IOException {
 
         URL url = new URL(path);
-        HttpURLConnection connection =
-            (HttpURLConnection) url.openConnection();
+        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setUseCaches(false);
         connection.setReadTimeout(readTimeout);
         connection.setRequestMethod(method);
diff --git a/test/org/apache/catalina/valves/rewrite/TestRewriteValve.java b/test/org/apache/catalina/valves/rewrite/TestRewriteValve.java
index 0603515..47f9440 100644
--- a/test/org/apache/catalina/valves/rewrite/TestRewriteValve.java
+++ b/test/org/apache/catalina/valves/rewrite/TestRewriteValve.java
@@ -20,6 +20,7 @@
 import org.junit.Test;
 
 import org.apache.catalina.Context;
+import org.apache.catalina.servlets.DefaultServlet;
 import org.apache.catalina.startup.Tomcat;
 import org.apache.catalina.startup.TomcatBaseTest;
 import org.apache.tomcat.util.buf.ByteChunk;
@@ -75,6 +76,8 @@
         Tomcat.addServlet(ctx, "snoop", new SnoopServlet());
         ctx.addServletMapping("/a/%255A", "snoop");
         ctx.addServletMapping("/c/*", "snoop");
+        Tomcat.addServlet(ctx, "default", new DefaultServlet());
+        ctx.addServletMapping("/", "default");
 
         tomcat.start();
 
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index a45603f..940cb94 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -188,6 +188,16 @@
         Ensure that in an embedded Tomcat the logging configuration is
         not lost during garbage collection. (violetagg)
       </fix>
+      <add>
+        Move the functionality that provides redirects for context roots and
+        directories where a trailing <code>/</code> is added from the Mapper to
+        the <code>DefaultServlet</code>. This enables such requests to be
+        processed by any configured Valves and Filters before the redirect is
+        made. This behaviour is configurable via the
+        <code>mapperContextRootRedirectEnabled</code> and
+        <code>mapperDirectoryRedirectEnabled</code> attributes of the Context
+        which may be used to restore the previous behaviour. (markt)
+      </add>
     </changelog>
   </subsection>
   <subsection name="Coyote">
diff --git a/webapps/docs/config/context.xml b/webapps/docs/config/context.xml
index b69d076..b5c2a80 100644
--- a/webapps/docs/config/context.xml
+++ b/webapps/docs/config/context.xml
@@ -360,6 +360,22 @@
         default value of <code>false</code> is used.</p>
       </attribute>
 
+      <attribute name="mapperContextRootRedirectEnabled" required="false">
+        <p>If enabled, requests for a web application context root will be
+        redirected (adding a trailing slash) if necessary by the Mapper rather
+        than the default Servlet. This is more efficient but has the side effect
+        of confirming that the context path exists. If not specified, the
+        default value of <code>false</code> is used.</p>
+      </attribute>
+
+      <attribute name="mapperDirectoryRedirectEnabled" required="false">
+        <p>If enabled, requests for a web application directory will be
+        redirected (adding a trailing slash) if necessary by the Mapper rather
+        than the default Servlet. This is more efficient but has the side effect
+        of confirming that the directory is exists. If not specified, the
+        default value of <code>false</code> is used.</p>
+      </attribute>
+
       <attribute name="override" required="false">
         <p>Set to <code>true</code> to ignore any settings in both the global
         or <a href="host.html">Host</a> default contexts.  By default, settings