/
ErrorHandler.java
603 lines (549 loc) · 22.2 KB
/
ErrorHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.QuotedQualityCSV;
import org.eclipse.jetty.io.ByteBufferOutputStream;
import org.eclipse.jetty.server.Dispatcher;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* Handler for Error pages
* An ErrorHandler is registered with {@link ContextHandler#setErrorHandler(ErrorHandler)} or
* {@link Server#setErrorHandler(ErrorHandler)}.
* It is called by the HttpResponse.sendError method to write an error page via {@link #handle(String, Request, HttpServletRequest, HttpServletResponse)}
* or via {@link #badMessageError(int, String, HttpFields)} for bad requests for which a dispatch cannot be done.
*/
public class ErrorHandler extends AbstractHandler
{
// TODO This classes API needs to be majorly refactored/cleanup in jetty-10
private static final Logger LOG = Log.getLogger(ErrorHandler.class);
public static final String ERROR_PAGE = "org.eclipse.jetty.server.error_page";
public static final String ERROR_CONTEXT = "org.eclipse.jetty.server.error_context";
boolean _showStacks = true;
boolean _disableStacks = false;
boolean _showMessageInTitle = true;
String _cacheControl = "must-revalidate,no-cache,no-store";
public ErrorHandler()
{
}
public boolean errorPageForMethod(String method)
{
switch (method)
{
case "GET":
case "POST":
case "HEAD":
return true;
default:
return false;
}
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// TODO inline this and remove method in jetty-10
doError(target, baseRequest, request, response);
}
@Override
public void doError(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
String cacheControl = getCacheControl();
if (cacheControl != null)
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), cacheControl);
// Look for an error page dispatcher
// This logic really should be in ErrorPageErrorHandler, but some implementations extend ErrorHandler
// and implement ErrorPageMapper directly, so we do this here in the base class.
String errorPage = (this instanceof ErrorPageMapper) ? ((ErrorPageMapper)this).getErrorPage(request) : null;
ContextHandler.Context context = baseRequest.getErrorContext();
Dispatcher errorDispatcher = (errorPage != null && context != null)
? (Dispatcher)context.getRequestDispatcher(errorPage) : null;
try
{
if (errorDispatcher != null)
{
try
{
errorDispatcher.error(request, response);
return;
}
catch (ServletException e)
{
LOG.debug(e);
if (response.isCommitted())
return;
}
}
String message = (String)request.getAttribute(Dispatcher.ERROR_MESSAGE);
if (message == null)
message = baseRequest.getResponse().getReason();
generateAcceptableResponse(baseRequest, request, response, response.getStatus(), message);
}
finally
{
baseRequest.setHandled(true);
}
}
/**
* Generate an acceptable error response.
* <p>This method is called to generate an Error page of a mime type that is
* acceptable to the user-agent. The Accept header is evaluated in
* quality order and the method
* {@link #generateAcceptableResponse(Request, HttpServletRequest, HttpServletResponse, int, String, String)}
* is called for each mimetype until the response is written to or committed.</p>
*
* @param baseRequest The base request
* @param request The servlet request (may be wrapped)
* @param response The response (may be wrapped)
* @param code the http error code
* @param message the http error message
* @throws IOException if the response cannot be generated
*/
protected void generateAcceptableResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response, int code, String message)
throws IOException
{
List<String> acceptable = baseRequest.getHttpFields().getQualityCSV(HttpHeader.ACCEPT, QuotedQualityCSV.MOST_SPECIFIC_MIME_ORDERING);
if (acceptable.isEmpty() && !baseRequest.getHttpFields().contains(HttpHeader.ACCEPT))
{
generateAcceptableResponse(baseRequest, request, response, code, message, MimeTypes.Type.TEXT_HTML.asString());
}
else
{
for (String mimeType : acceptable)
{
generateAcceptableResponse(baseRequest, request, response, code, message, mimeType);
if (response.isCommitted() || baseRequest.getResponse().isWritingOrStreaming())
break;
}
}
}
/**
* Returns an acceptable writer for an error page.
* <p>Uses the user-agent's <code>Accept-Charset</code> to get response
* {@link Writer}. The acceptable charsets are tested in quality order
* if they are known to the JVM and the first known is set on
* {@link HttpServletResponse#setCharacterEncoding(String)} and the
* {@link HttpServletResponse#getWriter()} method used to return a writer.
* If there is no <code>Accept-Charset</code> header then
* <code>ISO-8859-1</code> is used. If '*' is the highest quality known
* charset, then <code>utf-8</code> is used.
* </p>
*
* @param baseRequest The base request
* @param request The servlet request (may be wrapped)
* @param response The response (may be wrapped)
* @return A {@link Writer} if there is a known acceptable charset or null
* @throws IOException if a Writer cannot be returned
*/
@Deprecated
protected Writer getAcceptableWriter(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException
{
List<String> acceptable = baseRequest.getHttpFields().getQualityCSV(HttpHeader.ACCEPT_CHARSET);
if (acceptable.isEmpty())
{
response.setCharacterEncoding(StandardCharsets.ISO_8859_1.name());
return response.getWriter();
}
for (String charset : acceptable)
{
try
{
if ("*".equals(charset))
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
else
response.setCharacterEncoding(Charset.forName(charset).name());
return response.getWriter();
}
catch (Exception e)
{
LOG.ignore(e);
}
}
return null;
}
/**
* Generate an acceptable error response for a mime type.
* <p>This method is called for each mime type in the users agent's
* <code>Accept</code> header, until {@link Request#isHandled()} is true and a
* response of the appropriate type is generated.
* </p>
* <p>The default implementation handles "text/html", "text/*" and "*/*".
* The method can be overridden to handle other types. Implementations must
* immediate produce a response and may not be async.
* </p>
*
* @param baseRequest The base request
* @param request The servlet request (may be wrapped)
* @param response The response (may be wrapped)
* @param code the http error code
* @param message the http error message
* @param contentType The mimetype to generate (may be */*or other wildcard)
* @throws IOException if a response cannot be generated
*/
protected void generateAcceptableResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response, int code, String message, String contentType)
throws IOException
{
// We can generate an acceptable contentType, but can we generate an acceptable charset?
// TODO refactor this in jetty-10 to be done in the other calling loop
Charset charset = null;
List<String> acceptable = baseRequest.getHttpFields().getQualityCSV(HttpHeader.ACCEPT_CHARSET);
if (!acceptable.isEmpty())
{
for (String name : acceptable)
{
if ("*".equals(name))
{
charset = StandardCharsets.UTF_8;
break;
}
try
{
charset = Charset.forName(name);
}
catch (Exception e)
{
LOG.ignore(e);
}
}
if (charset == null)
return;
}
MimeTypes.Type type;
switch (contentType)
{
case "text/html":
case "text/*":
case "*/*":
type = MimeTypes.Type.TEXT_HTML;
if (charset == null)
charset = StandardCharsets.ISO_8859_1;
break;
case "text/json":
case "application/json":
type = MimeTypes.Type.TEXT_JSON;
if (charset == null)
charset = StandardCharsets.UTF_8;
break;
case "text/plain":
type = MimeTypes.Type.TEXT_PLAIN;
if (charset == null)
charset = StandardCharsets.ISO_8859_1;
break;
default:
return;
}
// write into the response aggregate buffer and flush it asynchronously.
while (true)
{
try
{
// TODO currently the writer used here is of fixed size, so a large
// TODO error page may cause a BufferOverflow. In which case we try
// TODO again with stacks disabled. If it still overflows, it is
// TODO written without a body.
ByteBuffer buffer = baseRequest.getResponse().getHttpOutput().acquireBuffer();
ByteBufferOutputStream out = new ByteBufferOutputStream(buffer);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, charset));
switch (type)
{
case TEXT_HTML:
response.setContentType(MimeTypes.Type.TEXT_HTML.asString());
response.setCharacterEncoding(charset.name());
handleErrorPage(request, writer, code, message);
break;
case TEXT_JSON:
response.setContentType(contentType);
writeErrorJson(request, writer, code, message);
break;
case TEXT_PLAIN:
response.setContentType(MimeTypes.Type.TEXT_PLAIN.asString());
response.setCharacterEncoding(charset.name());
writeErrorPlain(request, writer, code, message);
break;
default:
throw new IllegalStateException();
}
writer.flush();
break;
}
catch (BufferOverflowException e)
{
LOG.warn("Error page too large: {} {} {}", code, message, request);
if (LOG.isDebugEnabled())
LOG.warn(e);
baseRequest.getResponse().resetContent();
if (!_disableStacks)
{
LOG.info("Disabling showsStacks for " + this);
_disableStacks = true;
continue;
}
break;
}
}
// Do an asynchronous completion.
baseRequest.getHttpChannel().sendResponseAndComplete();
}
protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message)
throws IOException
{
writeErrorPage(request, writer, code, message, _showStacks);
}
protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
throws IOException
{
if (message == null)
message = HttpStatus.getMessage(code);
writer.write("<html>\n<head>\n");
writeErrorPageHead(request, writer, code, message);
writer.write("</head>\n<body>");
writeErrorPageBody(request, writer, code, message, showStacks);
writer.write("\n</body>\n</html>\n");
}
protected void writeErrorPageHead(HttpServletRequest request, Writer writer, int code, String message)
throws IOException
{
writer.write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n");
writer.write("<title>Error ");
// TODO this code is duplicated in writeErrorPageMessage
String status = Integer.toString(code);
writer.write(status);
if (message != null && !message.equals(status))
{
writer.write(' ');
writer.write(StringUtil.sanitizeXmlString(message));
}
writer.write("</title>\n");
}
protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
throws IOException
{
String uri = request.getRequestURI();
writeErrorPageMessage(request, writer, code, message, uri);
if (showStacks && !_disableStacks)
writeErrorPageStacks(request, writer);
Request.getBaseRequest(request).getHttpChannel().getHttpConfiguration()
.writePoweredBy(writer, "<hr>", "<hr/>\n");
}
protected void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code, String message, String uri)
throws IOException
{
writer.write("<h2>HTTP ERROR ");
String status = Integer.toString(code);
writer.write(status);
if (message != null && !message.equals(status))
{
writer.write(' ');
writer.write(StringUtil.sanitizeXmlString(message));
}
writer.write("</h2>\n");
writer.write("<table>\n");
htmlRow(writer, "URI", uri);
htmlRow(writer, "STATUS", status);
htmlRow(writer, "MESSAGE", message);
htmlRow(writer, "SERVLET", request.getAttribute(Dispatcher.ERROR_SERVLET_NAME));
Throwable cause = (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);
while (cause != null)
{
htmlRow(writer, "CAUSED BY", cause);
cause = cause.getCause();
}
writer.write("</table>\n");
}
private void htmlRow(Writer writer, String tag, Object value)
throws IOException
{
writer.write("<tr><th>");
writer.write(tag);
writer.write(":</th><td>");
if (value == null)
writer.write("-");
else
writer.write(StringUtil.sanitizeXmlString(value.toString()));
writer.write("</td></tr>\n");
}
private void writeErrorPlain(HttpServletRequest request, PrintWriter writer, int code, String message)
{
writer.write("HTTP ERROR ");
writer.write(Integer.toString(code));
writer.write(' ');
writer.write(StringUtil.sanitizeXmlString(message));
writer.write("\n");
writer.printf("URI: %s%n", request.getRequestURI());
writer.printf("STATUS: %s%n", code);
writer.printf("MESSAGE: %s%n", message);
writer.printf("SERVLET: %s%n", request.getAttribute(Dispatcher.ERROR_SERVLET_NAME));
Throwable cause = (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);
while (cause != null)
{
writer.printf("CAUSED BY %s%n", cause);
if (_showStacks && !_disableStacks)
cause.printStackTrace(writer);
cause = cause.getCause();
}
}
private void writeErrorJson(HttpServletRequest request, PrintWriter writer, int code, String message)
{
Throwable cause = (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);
Object servlet = request.getAttribute(Dispatcher.ERROR_SERVLET_NAME);
Map<String,String> json = new HashMap<>();
json.put("url", request.getRequestURI());
json.put("status", Integer.toString(code));
json.put("message", message);
if (servlet != null)
{
json.put("servlet", servlet.toString());
}
int c = 0;
while (cause != null)
{
json.put("cause" + c++, cause.toString());
cause = cause.getCause();
}
writer.append(json.entrySet().stream()
.map(e -> QuotedStringTokenizer.quote(e.getKey()) +
":" +
QuotedStringTokenizer.quote((e.getValue())))
.collect(Collectors.joining(",\n", "{\n", "\n}")));
}
protected void writeErrorPageStacks(HttpServletRequest request, Writer writer)
throws IOException
{
Throwable th = (Throwable)request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
while (th != null)
{
writer.write("<h3>Caused by:</h3><pre>");
// You have to pre-generate and then use #write(writer, String)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
pw.flush();
write(writer, sw.getBuffer().toString()); // IMPORTANT STEP
writer.write("</pre>\n");
th = th.getCause();
}
}
/**
* Bad Message Error body
* <p>Generate an error response body to be sent for a bad message.
* In this case there is something wrong with the request, so either
* a request cannot be built, or it is not safe to build a request.
* This method allows for a simple error page body to be returned
* and some response headers to be set.
*
* @param status The error code that will be sent
* @param reason The reason for the error code (may be null)
* @param fields The header fields that will be sent with the response.
* @return The content as a ByteBuffer, or null for no body.
*/
public ByteBuffer badMessageError(int status, String reason, HttpFields fields)
{
if (reason == null)
reason = HttpStatus.getMessage(status);
fields.put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.TEXT_HTML_8859_1.asString());
return BufferUtil.toBuffer("<h1>Bad Message " + status + "</h1><pre>reason: " + reason + "</pre>");
}
/**
* Get the cacheControl.
*
* @return the cacheControl header to set on error responses.
*/
public String getCacheControl()
{
return _cacheControl;
}
/**
* Set the cacheControl.
*
* @param cacheControl the cacheControl header to set on error responses.
*/
public void setCacheControl(String cacheControl)
{
_cacheControl = cacheControl;
}
/**
* @return True if stack traces are shown in the error pages
*/
public boolean isShowStacks()
{
return _showStacks;
}
/**
* @param showStacks True if stack traces are shown in the error pages
*/
public void setShowStacks(boolean showStacks)
{
_showStacks = showStacks;
}
/**
* @param showMessageInTitle if true, the error message appears in page title
*/
public void setShowMessageInTitle(boolean showMessageInTitle)
{
_showMessageInTitle = showMessageInTitle;
}
public boolean getShowMessageInTitle()
{
return _showMessageInTitle;
}
protected void write(Writer writer, String string)
throws IOException
{
if (string == null)
return;
writer.write(StringUtil.sanitizeXmlString(string));
}
public interface ErrorPageMapper
{
String getErrorPage(HttpServletRequest request);
}
public static ErrorHandler getErrorHandler(Server server, ContextHandler context)
{
ErrorHandler errorHandler = null;
if (context != null)
errorHandler = context.getErrorHandler();
if (errorHandler == null && server != null)
errorHandler = server.getBean(ErrorHandler.class);
return errorHandler;
}
}