001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.view.jsp;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022import java.io.*;
023
024import org.apache.juneau.http.response.*;
025import org.apache.juneau.rest.server.*;
026import org.apache.juneau.rest.server.view.*;
027
028/**
029 * Flavor-neutral worker bean carrying the JSP raw-template-dispatch logic shared by the
030 * {@link JspMixin} mixin, the {@link JspServlet} servlet, and the {@link JspResource} child flavors.
031 *
032 * <p>
033 * This is the <i>flavor-neutral worker</i> for the JSP capability: it is <b>not</b> one of the
034 * three {@code @Rest} flavor classes &mdash; it is a plain bean that implements
035 * {@link RawTemplateDispatcher} and holds the capability state ({@code basePath}) plus the raw-serve
036 * logic. Each flavor independently holds an instance of this worker and delegates to it, so no flavor
037 * is another flavor's worker.
038 *
039 * <h2 class='section'>See Also:</h2><ul>
040 *    <li class='jc'>{@link JspMixin}
041 *    <li class='jc'>{@link JspServlet}
042 *    <li class='jc'>{@link JspResource}
043 *    <li class='jic'>{@link RawTemplateDispatcher}
044 * </ul>
045 *
046 * @since 10.0.0
047 */
048public class JspDispatcher implements RawTemplateDispatcher {
049
050   /** Default base path applied when no {@link Builder#basePath(String)} call has been made. */
051   @SuppressWarnings({
052      "java:S1075" // Default for the configurable basePath setting, not a hardcoded location.
053   })
054   public static final String DEFAULT_BASE_PATH = "/templates/";
055
056   private final String basePath;
057
058   /**
059    * Creates a new builder.
060    *
061    * @return A new builder.
062    */
063   public static Builder create() {
064      return new Builder();
065   }
066
067   /**
068    * Builder constructor.
069    *
070    * @param builder The builder. Must not be {@code null}.
071    */
072   protected JspDispatcher(Builder builder) {
073      basePath = builder.basePath;
074   }
075
076   /**
077    * Returns the base path under which {@code .jsp} resources are resolved.
078    *
079    * @return The base path. Never {@code null}.
080    */
081   public String getBasePath() {
082      return basePath;
083   }
084
085   /**
086    * Forwards the request to the JSP engine for the raw {@code .jsp} resource at the trailing path.
087    *
088    * @param path The trailing path segment after the mount prefix (the JSP file name relative to
089    *    the configured {@link #getBasePath() base path}).
090    * @param req The current REST request.
091    * @param res The current REST response.
092    * @throws IOException If the underlying servlet writer fails.
093    * @throws NotFound If the JSP resource cannot be resolved.
094    */
095   @Override /* RawTemplateDispatcher */
096   public void render(String path, RestRequest req, RestResponse res) throws IOException, NotFound {
097      // joinPath delegates to FileUtils.resolveVirtualPathSafely, which throws IAE on any
098      // resolved target that escapes basePath (../, %2e%2e treated as literal, absolute-path
099      // injection, etc.). Map IAE → 403 (Forbidden); attackers can't distinguish from the
100      // container-layer rejection of malformed paths.
101      if (! ViewTemplateNames.isPlainName(path))
102         throw new NotFound("Template not found.");
103      String target;
104      try {
105         target = JspViewRenderer.joinPath(basePath, path);
106      } catch (IllegalArgumentException ex) {
107         throw new Forbidden("Path escapes configured base path.");
108      }
109      if (! isServable(basePath, target))
110         throw new NotFound("Template not found.");
111      try {
112         var ctx = req.getServletContext();
113         var rd = ctx.getRequestDispatcher(target);
114         if (rd == null)
115            throw new InternalServerError("Could not resolve RequestDispatcher for '%s'. %s",
116               target, JspViewRenderer.NO_ENGINE_DIAGNOSTIC);
117         rd.forward(req.getHttpServletRequest(), res.getHttpServletResponse());
118      } catch (InternalServerError | IOException | NotFound ex) {
119         // Re-throw as-is so the specific diagnostic constructed above, or a framework-level IOException
120         // or NotFound, isn't discarded by the generic fallback below.
121         throw ex;
122      } catch (NoClassDefFoundError ex) {
123         throw new InternalServerError(ex, JspViewRenderer.NO_ENGINE_DIAGNOSTIC);
124      } catch (Exception ex) {
125         throw new InternalServerError(ex, "JSP render failed for '%s'", target);
126      }
127   }
128
129   /**
130    * Whether a resolved forward target may be served: a plain {@code .jsp} name that does not point into
131    * {@code WEB-INF} or {@code META-INF} unless the configured base path itself lives there.
132    */
133   static boolean isServable(String basePath, String target) {
134      if (! ViewTemplateNames.isPlainName(target) || ! ViewTemplateNames.hasAllowedExtension(target, ".jsp"))
135         return false;
136      var lower = target.toLowerCase();
137      var base = basePath.toLowerCase();
138      for (var dir : new String[]{"/web-inf/", "/meta-inf/"})
139         if ((lower + "/").contains(dir) && ! (base + "/").contains(dir))
140            return false;
141      return true;
142   }
143
144   /**
145    * Builder for {@link JspDispatcher}.
146    */
147   public static class Builder {
148
149      String basePath = DEFAULT_BASE_PATH;
150
151      /** Constructor &mdash; package access for {@link JspDispatcher#create()}. */
152      protected Builder() {}
153
154      /**
155       * Sets the classpath / webapp base path under which {@code .jsp} resources are resolved.
156       *
157       * @param value The base path. {@code null} or blank values reset to the default
158       *    {@link JspDispatcher#DEFAULT_BASE_PATH}.
159       * @return This object.
160       */
161      public Builder basePath(String value) {
162         basePath = isBlank(value) ? DEFAULT_BASE_PATH : value;
163         return this;
164      }
165
166      /**
167       * Reads the current base path setting (test/inspection helper).
168       *
169       * @return The base path. Never {@code null}.
170       */
171      public String getBasePath() {
172         return basePath;
173      }
174
175      /**
176       * Builds the {@link JspDispatcher}.
177       *
178       * @return A new {@link JspDispatcher} instance.
179       */
180      public JspDispatcher build() {
181         if (basePath == null)
182            throw iaex("basePath must not be null");
183         return new JspDispatcher(this);
184      }
185   }
186}