View Javadoc
1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.server.handler;
20  
21  import java.io.IOException;
22  import java.io.PrintWriter;
23  import java.io.StringWriter;
24  import java.io.Writer;
25  import java.nio.ByteBuffer;
26  import java.nio.charset.Charset;
27  import java.nio.charset.StandardCharsets;
28  import java.util.List;
29  
30  import javax.servlet.ServletContext;
31  import javax.servlet.RequestDispatcher;
32  import javax.servlet.ServletException;
33  import javax.servlet.http.HttpServletRequest;
34  import javax.servlet.http.HttpServletResponse;
35  
36  import org.eclipse.jetty.http.HttpFields;
37  import org.eclipse.jetty.http.HttpHeader;
38  import org.eclipse.jetty.http.HttpMethod;
39  import org.eclipse.jetty.http.HttpStatus;
40  import org.eclipse.jetty.http.MimeTypes;
41  import org.eclipse.jetty.server.Dispatcher;
42  import org.eclipse.jetty.server.Request;
43  import org.eclipse.jetty.server.Server;
44  import org.eclipse.jetty.util.BufferUtil;
45  import org.eclipse.jetty.util.StringUtil;
46  import org.eclipse.jetty.util.log.Log;
47  import org.eclipse.jetty.util.log.Logger;
48  
49  /* ------------------------------------------------------------ */
50  /** Handler for Error pages
51   * An ErrorHandler is registered with {@link ContextHandler#setErrorHandler(ErrorHandler)} or
52   * {@link Server#setErrorHandler(ErrorHandler)}.
53   * It is called by the HttpResponse.sendError method to write a error page via {@link #handle(String, Request, HttpServletRequest, HttpServletResponse)}
54   * or via {@link #badMessageError(int, String, HttpFields)} for bad requests for which a dispatch cannot be done.
55   *
56   */
57  public class ErrorHandler extends AbstractHandler
58  {    
59      private static final Logger LOG = Log.getLogger(ErrorHandler.class);
60      public final static String ERROR_PAGE="org.eclipse.jetty.server.error_page";
61      
62      boolean _showStacks=true;
63      boolean _showMessageInTitle=true;
64      String _cacheControl="must-revalidate,no-cache,no-store";
65  
66      /* ------------------------------------------------------------ */
67      public ErrorHandler()
68      {
69      }
70  
71      /* ------------------------------------------------------------ */
72      /*
73       * @see org.eclipse.jetty.server.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
74       */
75      @Override
76      public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
77      {
78          doError(target,baseRequest,request,response);
79      }
80      
81      @Override
82      public void doError(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
83      {
84          String method = request.getMethod();
85          if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method))
86          {
87              baseRequest.setHandled(true);
88              return;
89          }
90          
91          if (this instanceof ErrorPageMapper)
92          {
93              String error_page=((ErrorPageMapper)this).getErrorPage(request);
94              if (error_page!=null)
95              {
96                  String old_error_page=(String)request.getAttribute(ERROR_PAGE);
97                  ServletContext servlet_context = request.getServletContext();
98                  if (servlet_context==null)
99                      servlet_context=ContextHandler.getCurrentContext();
100                 if (servlet_context==null)
101                 {
102                     LOG.warn("No ServletContext for error page {}",error_page);       
103                 }
104                 else if (old_error_page!=null && old_error_page.equals(error_page))
105                 {
106                     LOG.warn("Error page loop {}",error_page); 
107                 }
108                 else
109                 {
110                     request.setAttribute(ERROR_PAGE, error_page);
111 
112                     Dispatcher dispatcher = (Dispatcher) servlet_context.getRequestDispatcher(error_page);
113                     try
114                     {
115                         if (LOG.isDebugEnabled())
116                             LOG.debug("error page dispatch {}->{}",error_page,dispatcher);
117                         if(dispatcher!=null)
118                         {
119                             dispatcher.error(request, response);
120                             return;
121                         }
122                         LOG.warn("No error page found "+error_page);
123                     }
124                     catch (ServletException e)
125                     {
126                         LOG.warn(Log.EXCEPTION, e);
127                         return;
128                     }
129                 }
130             } 
131             else 
132             {
133                 if (LOG.isDebugEnabled())
134                 {
135                     LOG.debug("No Error Page mapping for request({} {}) (using default)",request.getMethod(),request.getRequestURI());
136                 }
137             }
138         }
139 
140         if (_cacheControl != null)
141             response.setHeader(HttpHeader.CACHE_CONTROL.asString(), _cacheControl);
142         generateAcceptableResponse(baseRequest,request,response,response.getStatus(),baseRequest.getResponse().getReason());
143     }
144 
145     /** 
146      * Generate an acceptable error response.
147      * <p>This method is called to generate an Error page of a mime type that is 
148      * acceptable to the user-agent.  The Accept header is evaluated in 
149      * quality order and the method 
150      * {@link #generateAcceptableResponse(Request, HttpServletRequest, HttpServletResponse, int, String, String)}
151      * is called for each mimetype until {@link Request#isHandled()} is true.</p>
152      * @param baseRequest The base request
153      * @param request The servlet request (may be wrapped)
154      * @param response The response (may be wrapped)
155      * @throws IOException if the response cannot be generated
156      */
157     protected void generateAcceptableResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response, int code, String message)
158         throws IOException
159     {
160         List<String> acceptable=baseRequest.getHttpFields().getQualityCSV(HttpHeader.ACCEPT);
161         
162         if (acceptable.isEmpty() && !baseRequest.getHttpFields().contains(HttpHeader.ACCEPT))
163             generateAcceptableResponse(baseRequest,request,response,code,message,MimeTypes.Type.TEXT_HTML.asString());
164         else
165         {
166             for (String mimeType:acceptable)
167             {
168                 generateAcceptableResponse(baseRequest,request,response,code,message,mimeType);
169                 if (baseRequest.isHandled())
170                     return;
171             }
172         }
173         baseRequest.setHandled(true);
174     }
175 
176     /** 
177      * Returns an acceptable writer for an error page.
178      * <p>Uses the user-agent's <code>Accept-Charset</code> to get response
179      * {@link Writer}.  The acceptable charsets are tested in quality order 
180      * if they are known to the JVM and the first known is set on
181      * {@link HttpServletResponse#setCharacterEncoding(String)} and the 
182      * {@link HttpServletResponse#getWriter()} method used to return a writer.
183      * If there is no <code>Accept-Charset</code> header then 
184      * <code>ISO-8859-1</code> is used.  If '*' is the highest quality known
185      * charset, then <code>utf-8</code> is used.
186      * </p>     
187      * @param baseRequest The base request
188      * @param request The servlet request (may be wrapped)
189      * @param response The response (may be wrapped)
190      * @return A {@link Writer} if there is a known acceptable charset or null
191      * @throws IOException if a Writer cannot be returned
192      */
193     protected Writer getAcceptableWriter(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
194         throws IOException
195     {
196         List<String> acceptable=baseRequest.getHttpFields().getQualityCSV(HttpHeader.ACCEPT_CHARSET);
197         if (acceptable.isEmpty())
198         {
199             response.setCharacterEncoding(StandardCharsets.ISO_8859_1.name());
200             return response.getWriter();
201         }
202         
203         for (String charset:acceptable)
204         {
205             try
206             {
207                 if ("*".equals(charset))
208                     response.setCharacterEncoding(StandardCharsets.UTF_8.name());
209                 else
210                     response.setCharacterEncoding(Charset.forName(charset).name());
211                 return response.getWriter();
212             }
213             catch(Exception e)
214             {
215                 LOG.ignore(e);
216             }
217         }
218         return null;
219     }
220         
221     /* ------------------------------------------------------------ */
222     /** Generate an acceptable error response for a mime type.
223      * <p>This method is called for each mime type in the users agent's
224      * <code>Accept</code> header, until {@link Request#isHandled()} is true and a 
225      * response of the appropriate type is generated.
226      * 
227      * @param baseRequest The base request
228      * @param request The servlet request (may be wrapped)
229      * @param response The response (may be wrapped)
230      * @param mimeType The mimetype to generate (may be *&#47;*or other wildcard)
231      * @throws IOException if a response cannot be generated
232      */
233     protected void generateAcceptableResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response, int code, String message, String mimeType)
234         throws IOException
235     {
236         switch(mimeType)
237         {
238             case "text/html":
239             case "text/*":
240             case "*/*":
241             {
242                 baseRequest.setHandled(true);
243                 Writer writer = getAcceptableWriter(baseRequest,request,response);
244                 if (writer!=null)
245                 {
246                     response.setContentType(MimeTypes.Type.TEXT_HTML.asString());
247                     handleErrorPage(request, writer, code, message);
248                 }
249             }
250         }        
251     }
252     
253     /* ------------------------------------------------------------ */
254     protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message)
255         throws IOException
256     {
257         writeErrorPage(request, writer, code, message, _showStacks);
258     }
259 
260     /* ------------------------------------------------------------ */
261     protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
262         throws IOException
263     {
264         if (message == null)
265             message=HttpStatus.getMessage(code);
266 
267         writer.write("<html>\n<head>\n");
268         writeErrorPageHead(request,writer,code,message);
269         writer.write("</head>\n<body>");
270         writeErrorPageBody(request,writer,code,message,showStacks);
271         writer.write("\n</body>\n</html>\n");
272     }
273 
274     /* ------------------------------------------------------------ */
275     protected void writeErrorPageHead(HttpServletRequest request, Writer writer, int code, String message)
276         throws IOException
277         {
278         writer.write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n");
279         writer.write("<title>Error ");
280         writer.write(Integer.toString(code));
281 
282         if (_showMessageInTitle)
283         {
284             writer.write(' ');
285             write(writer,message);
286         }
287         writer.write("</title>\n");
288     }
289 
290     /* ------------------------------------------------------------ */
291     protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
292         throws IOException
293     {
294         String uri= request.getRequestURI();
295 
296         writeErrorPageMessage(request,writer,code,message,uri);
297         if (showStacks)
298             writeErrorPageStacks(request,writer);
299 
300         Request.getBaseRequest(request).getHttpChannel().getHttpConfiguration()
301             .writePoweredBy(writer,"<hr>","<hr/>\n");
302     }
303 
304     /* ------------------------------------------------------------ */
305     protected void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code, String message,String uri)
306     throws IOException
307     {
308         writer.write("<h2>HTTP ERROR ");
309         writer.write(Integer.toString(code));
310         writer.write("</h2>\n<p>Problem accessing ");
311         write(writer,uri);
312         writer.write(". Reason:\n<pre>    ");
313         write(writer,message);
314         writer.write("</pre></p>");
315     }
316 
317     /* ------------------------------------------------------------ */
318     protected void writeErrorPageStacks(HttpServletRequest request, Writer writer)
319         throws IOException
320     {
321         Throwable th = (Throwable)request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
322         while(th!=null)
323         {
324             writer.write("<h3>Caused by:</h3><pre>");
325             StringWriter sw = new StringWriter();
326             PrintWriter pw = new PrintWriter(sw);
327             th.printStackTrace(pw);
328             pw.flush();
329             write(writer,sw.getBuffer().toString());
330             writer.write("</pre>\n");
331 
332             th =th.getCause();
333         }
334     }
335 
336     /* ------------------------------------------------------------ */
337     /** Bad Message Error body
338      * <p>Generate a error response body to be sent for a bad message.
339      * In this case there is something wrong with the request, so either
340      * a request cannot be built, or it is not safe to build a request.
341      * This method allows for a simple error page body to be returned 
342      * and some response headers to be set.
343      * @param status The error code that will be sent
344      * @param reason The reason for the error code (may be null)
345      * @param fields The header fields that will be sent with the response.
346      * @return The content as a ByteBuffer, or null for no body.
347      */
348     public ByteBuffer badMessageError(int status, String reason, HttpFields fields)
349     {
350         if (reason==null)
351             reason=HttpStatus.getMessage(status);
352         fields.put(HttpHeader.CONTENT_TYPE,MimeTypes.Type.TEXT_HTML_8859_1.asString());
353         return BufferUtil.toBuffer("<h1>Bad Message " + status + "</h1><pre>reason: " + reason + "</pre>");
354     }    
355     
356     /* ------------------------------------------------------------ */
357     /** Get the cacheControl.
358      * @return the cacheControl header to set on error responses.
359      */
360     public String getCacheControl()
361     {
362         return _cacheControl;
363     }
364 
365     /* ------------------------------------------------------------ */
366     /** Set the cacheControl.
367      * @param cacheControl the cacheControl header to set on error responses.
368      */
369     public void setCacheControl(String cacheControl)
370     {
371         _cacheControl = cacheControl;
372     }
373 
374     /* ------------------------------------------------------------ */
375     /**
376      * @return True if stack traces are shown in the error pages
377      */
378     public boolean isShowStacks()
379     {
380         return _showStacks;
381     }
382 
383     /* ------------------------------------------------------------ */
384     /**
385      * @param showStacks True if stack traces are shown in the error pages
386      */
387     public void setShowStacks(boolean showStacks)
388     {
389         _showStacks = showStacks;
390     }
391 
392     /* ------------------------------------------------------------ */
393     /**
394      * @param showMessageInTitle if true, the error message appears in page title
395      */
396     public void setShowMessageInTitle(boolean showMessageInTitle)
397     {
398         _showMessageInTitle = showMessageInTitle;
399     }
400 
401 
402     /* ------------------------------------------------------------ */
403     public boolean getShowMessageInTitle()
404     {
405         return _showMessageInTitle;
406     }
407 
408     /* ------------------------------------------------------------ */
409     protected void write(Writer writer,String string)
410         throws IOException
411     {
412         if (string==null)
413             return;
414 
415         writer.write(StringUtil.sanitizeXmlString(string));
416     }
417 
418     /* ------------------------------------------------------------ */
419     public interface ErrorPageMapper
420     {
421         String getErrorPage(HttpServletRequest request);
422     }
423 
424     /* ------------------------------------------------------------ */
425     public static ErrorHandler getErrorHandler(Server server, ContextHandler context)
426     {
427         ErrorHandler error_handler=null;
428         if (context!=null)
429             error_handler=context.getErrorHandler();
430         if (error_handler==null && server!=null)
431             error_handler = server.getBean(ErrorHandler.class);
432         return error_handler;
433     }
434 }