/
HttpChannel.java
1594 lines (1410 loc) · 52.8 KB
/
HttpChannel.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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.QuietException;
import org.eclipse.jetty.server.HttpChannelState.Action;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.eclipse.jetty.util.thread.Invocable.InvocationType.NON_BLOCKING;
/**
* HttpChannel represents a single endpoint for HTTP semantic processing.
* The HttpChannel is both an HttpParser.RequestHandler, where it passively receives events from
* an incoming HTTP request, and a Runnable, where it actively takes control of the request/response
* life cycle and calls the application (perhaps suspending and resuming with multiple calls to run).
* The HttpChannel signals the switch from passive mode to active mode by returning true to one of the
* HttpParser.RequestHandler callbacks. The completion of the active phase is signalled by a call to
* HttpTransport.completed().
*/
public abstract class HttpChannel implements Runnable, HttpOutput.Interceptor
{
public static Listener NOOP_LISTENER = new Listener() {};
private static final Logger LOG = LoggerFactory.getLogger(HttpChannel.class);
private final AtomicLong _requests = new AtomicLong();
private final Connector _connector;
private final Executor _executor;
private final HttpConfiguration _configuration;
private final EndPoint _endPoint;
private final HttpTransport _transport;
private final HttpChannelState _state;
private final Request _request;
private final Response _response;
private final HttpChannel.Listener _combinedListener;
@Deprecated
private final List<Listener> _transientListeners = new ArrayList<>();
private MetaData.Response _committedMetaData;
private RequestLog _requestLog;
private long _oldIdleTimeout;
/**
* Bytes written after interception (eg after compression)
*/
private long _written;
public HttpChannel(Connector connector, HttpConfiguration configuration, EndPoint endPoint, HttpTransport transport)
{
_connector = connector;
_configuration = Objects.requireNonNull(configuration);
_endPoint = endPoint;
_transport = transport;
_state = new HttpChannelState(this);
_request = new Request(this, newHttpInput(_state));
_response = new Response(this, newHttpOutput());
_executor = connector.getServer().getThreadPool();
_requestLog = connector.getServer().getRequestLog();
_combinedListener = (connector instanceof AbstractConnector)
? ((AbstractConnector)connector).getHttpChannelListeners()
: NOOP_LISTENER;
if (LOG.isDebugEnabled())
LOG.debug("new {} -> {},{},{}",
this,
_endPoint,
_endPoint == null ? null : _endPoint.getConnection(),
_state);
}
public boolean isSendError()
{
return _state.isSendError();
}
/** Format the address or host returned from Request methods
* @param addr The address or host
* @return Default implementation returns {@link HostPort#normalizeHost(String)}
*/
protected String formatAddrOrHost(String addr)
{
return HostPort.normalizeHost(addr);
}
private HttpInput newHttpInput(HttpChannelState state)
{
return new HttpInput(state);
}
/**
* Notify the channel that content is needed. If some content is immediately available, true is returned and
* {@link #produceContent()} has to be called and will return a non-null object.
* If no content is immediately available, an attempt to produce content must be made; if new content has been
* produced, true is returned; otherwise {@link HttpInput#onContentProducible()} is called once some content
* arrives and {@link #produceContent()} can be called without returning {@code null}.
* If a failure happens, then {@link HttpInput#onContentProducible()} will be called and an error content will
* return the error on the next call to {@link #produceContent()}.
* @return true if content is immediately available.
*/
public abstract boolean needContent();
/**
* Produce a {@link HttpInput.Content} object with data currently stored within the channel. The produced content
* can be special (meaning calling {@link HttpInput.Content#isSpecial()} returns true) if the channel reached a special
* state, like EOF or an error.
* Once a special content has been returned, all subsequent calls to this method will always return a special content
* of the same kind and {@link #needContent()} will always return true.
* The returned content is "raw", i.e.: not decoded.
* @return a {@link HttpInput.Content} object if one is immediately available without blocking, null otherwise.
*/
public abstract HttpInput.Content produceContent();
/**
* Fail all content that is currently stored within the channel.
* @param failure the failure to fail the content with.
* @return true if EOF was reached while failing all content, false otherwise.
*/
public abstract boolean failAllContent(Throwable failure);
/**
* Fail the channel's input.
* @param failure the failure.
* @return true if the channel needs to be rescheduled.
*/
public abstract boolean failed(Throwable failure);
/**
* Mark the channel's input as EOF.
* @return true if the channel needs to be rescheduled.
*/
protected abstract boolean eof();
protected HttpOutput newHttpOutput()
{
return new HttpOutput(this);
}
public HttpChannelState getState()
{
return _state;
}
/**
* Add a transient Listener to the HttpChannel.
* <p>Listeners added by this method will only be notified
* if the HttpChannel has been constructed with an instance of
* {@link TransientListeners} as an {@link AbstractConnector}
* provided listener</p>
* <p>Transient listeners are removed after every request cycle</p>
* @param listener the listener to add
* @return true if the listener was added.
*/
@Deprecated
public boolean addListener(Listener listener)
{
return _transientListeners.add(listener);
}
@Deprecated
public boolean removeListener(Listener listener)
{
return _transientListeners.remove(listener);
}
@Deprecated
public List<Listener> getTransientListeners()
{
return _transientListeners;
}
public long getBytesWritten()
{
return _written;
}
/**
* @return the number of requests handled by this connection
*/
public long getRequests()
{
return _requests.get();
}
public Connector getConnector()
{
return _connector;
}
public HttpTransport getHttpTransport()
{
return _transport;
}
public RequestLog getRequestLog()
{
return _requestLog;
}
public void setRequestLog(RequestLog requestLog)
{
_requestLog = requestLog;
}
public void addRequestLog(RequestLog requestLog)
{
if (_requestLog == null)
_requestLog = requestLog;
else if (_requestLog instanceof RequestLogCollection)
((RequestLogCollection)_requestLog).add(requestLog);
else
_requestLog = new RequestLogCollection(_requestLog, requestLog);
}
public MetaData.Response getCommittedMetaData()
{
return _committedMetaData;
}
/**
* Get the idle timeout.
* <p>This is implemented as a call to {@link EndPoint#getIdleTimeout()}, but may be
* overridden by channels that have timeouts different from their connections.
*
* @return the idle timeout (in milliseconds)
*/
public long getIdleTimeout()
{
return _endPoint.getIdleTimeout();
}
/**
* Set the idle timeout.
* <p>This is implemented as a call to {@link EndPoint#setIdleTimeout(long)}, but may be
* overridden by channels that have timeouts different from their connections.
*
* @param timeoutMs the idle timeout in milliseconds
*/
public void setIdleTimeout(long timeoutMs)
{
_endPoint.setIdleTimeout(timeoutMs);
}
public ByteBufferPool getByteBufferPool()
{
return _connector.getByteBufferPool();
}
public HttpConfiguration getHttpConfiguration()
{
return _configuration;
}
public Server getServer()
{
return _connector.getServer();
}
public Request getRequest()
{
return _request;
}
public Response getResponse()
{
return _response;
}
public Connection getConnection()
{
return _endPoint.getConnection();
}
public EndPoint getEndPoint()
{
return _endPoint;
}
/**
* <p>Return the local name of the connected channel.</p>
*
* <p>
* This is the host name after the connector is bound and the connection is accepted.
* </p>
* <p>
* Value can be overridden by {@link HttpConfiguration#setLocalAddress(SocketAddress)}.
* </p>
* <p>
* Note: some connectors are not based on IP networking, and default behavior here will
* result in a null return. Use {@link HttpConfiguration#setLocalAddress(SocketAddress)}
* to set the value to an acceptable host name.
* </p>
*
* @return the local name, or null
*/
public String getLocalName()
{
HttpConfiguration httpConfiguration = getHttpConfiguration();
if (httpConfiguration != null)
{
SocketAddress localAddress = httpConfiguration.getLocalAddress();
if (localAddress instanceof InetSocketAddress)
return ((InetSocketAddress)localAddress).getHostName();
}
InetSocketAddress local = getLocalAddress();
if (local != null)
return local.getHostString();
return null;
}
/**
* <p>Return the Local Port of the connected channel.</p>
*
* <p>
* This is the port the connector is bound to and is accepting connections on.
* </p>
* <p>
* Value can be overridden by {@link HttpConfiguration#setLocalAddress(SocketAddress)}.
* </p>
* <p>
* Note: some connectors are not based on IP networking, and default behavior here will
* result in a value of 0 returned. Use {@link HttpConfiguration#setLocalAddress(SocketAddress)}
* to set the value to an acceptable port.
* </p>
*
* @return the local port, or 0 if unspecified
*/
public int getLocalPort()
{
HttpConfiguration httpConfiguration = getHttpConfiguration();
if (httpConfiguration != null)
{
SocketAddress localAddress = httpConfiguration.getLocalAddress();
if (localAddress instanceof InetSocketAddress)
return ((InetSocketAddress)localAddress).getPort();
}
InetSocketAddress local = getLocalAddress();
return local == null ? 0 : local.getPort();
}
public InetSocketAddress getLocalAddress()
{
HttpConfiguration httpConfiguration = getHttpConfiguration();
if (httpConfiguration != null)
{
SocketAddress localAddress = httpConfiguration.getLocalAddress();
if (localAddress instanceof InetSocketAddress)
return ((InetSocketAddress)localAddress);
}
SocketAddress local = _endPoint.getLocalSocketAddress();
if (local instanceof InetSocketAddress)
return (InetSocketAddress)local;
return null;
}
public InetSocketAddress getRemoteAddress()
{
SocketAddress remote = _endPoint.getRemoteSocketAddress();
if (remote instanceof InetSocketAddress)
return (InetSocketAddress)remote;
return null;
}
/**
* @return return the HttpConfiguration server authority override
*/
public HostPort getServerAuthority()
{
HttpConfiguration httpConfiguration = getHttpConfiguration();
if (httpConfiguration != null)
return httpConfiguration.getServerAuthority();
return null;
}
/**
* If the associated response has the Expect header set to 100 Continue,
* then accessing the input stream indicates that the handler/servlet
* is ready for the request body and thus a 100 Continue response is sent.
*
* @param available estimate of the number of bytes that are available
* @throws IOException if the InputStream cannot be created
*/
public void continue100(int available) throws IOException
{
throw new UnsupportedOperationException();
}
public void recycle()
{
_request.recycle();
_response.recycle();
_committedMetaData = null;
_requestLog = _connector == null ? null : _connector.getServer().getRequestLog();
_written = 0;
_oldIdleTimeout = 0;
_transientListeners.clear();
}
@Override
public void run()
{
handle();
}
/**
* @return True if the channel is ready to continue handling (ie it is not suspended)
*/
public boolean handle()
{
if (LOG.isDebugEnabled())
LOG.debug("handle {} {} ", _request.getHttpURI(), this);
HttpChannelState.Action action = _state.handling();
// Loop here to handle async request redispatches.
// The loop is controlled by the call to async.unhandle in the
// finally block below. Unhandle will return false only if an async dispatch has
// already happened when unhandle is called.
loop:
while (!getServer().isStopped())
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("action {} {}", action, this);
switch (action)
{
case TERMINATED:
onCompleted();
break loop;
case WAIT:
// break loop without calling unhandle
break loop;
case DISPATCH:
{
if (!_request.hasMetaData())
throw new IllegalStateException("state=" + _state);
dispatch(DispatcherType.REQUEST, () ->
{
for (HttpConfiguration.Customizer customizer : _configuration.getCustomizers())
{
customizer.customize(getConnector(), _configuration, _request);
if (_request.isHandled())
return;
}
getServer().handle(HttpChannel.this);
});
break;
}
case ASYNC_DISPATCH:
{
dispatch(DispatcherType.ASYNC, () -> getServer().handleAsync(this));
break;
}
case ASYNC_TIMEOUT:
_state.onTimeout();
break;
case SEND_ERROR:
{
try
{
// Get ready to send an error response
_response.resetContent();
// the following is needed as you cannot trust the response code and reason
// as those could have been modified after calling sendError
Integer code = (Integer)_request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (code == null)
code = HttpStatus.INTERNAL_SERVER_ERROR_500;
_response.setStatus(code);
// The handling of the original dispatch failed and we are now going to either generate
// and error response ourselves or dispatch for an error page. If there is content left over
// from the failed dispatch, then we try to consume it here and if we fail we add a
// Connection:close. This can't be deferred to COMPLETE as the response will be committed
// by then.
ensureConsumeAllOrNotPersistent();
ContextHandler.Context context = (ContextHandler.Context)_request.getAttribute(ErrorHandler.ERROR_CONTEXT);
ErrorHandler errorHandler = ErrorHandler.getErrorHandler(getServer(), context == null ? null : context.getContextHandler());
// If we can't have a body, then create a minimal error response.
if (HttpStatus.hasNoBody(_response.getStatus()) || errorHandler == null || !errorHandler.errorPageForMethod(_request.getMethod()))
{
sendResponseAndComplete();
break;
}
dispatch(DispatcherType.ERROR, () ->
{
errorHandler.handle(null, _request, _request, _response);
_request.setHandled(true);
});
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Could not perform ERROR dispatch, aborting", x);
if (_state.isResponseCommitted())
abort(x);
else
{
try
{
_response.resetContent();
sendResponseAndComplete();
}
catch (Throwable t)
{
if (x != t)
x.addSuppressed(t);
abort(x);
}
}
}
finally
{
// clean up the context that was set in Response.sendError
_request.removeAttribute(ErrorHandler.ERROR_CONTEXT);
}
break;
}
case ASYNC_ERROR:
{
throw _state.getAsyncContextEvent().getThrowable();
}
case READ_CALLBACK:
{
ContextHandler handler = _state.getContextHandler();
if (handler != null)
handler.handle(_request, _request.getHttpInput());
else
_request.getHttpInput().run();
break;
}
case WRITE_CALLBACK:
{
ContextHandler handler = _state.getContextHandler();
if (handler != null)
handler.handle(_request, _response.getHttpOutput());
else
_response.getHttpOutput().run();
break;
}
case COMPLETE:
{
if (!_response.isCommitted())
{
if (!_request.isHandled() && !_response.getHttpOutput().isClosed())
{
// The request was not actually handled
_response.sendError(HttpStatus.NOT_FOUND_404);
break;
}
// Indicate Connection:close if we can't consume all.
if (_response.getStatus() >= 200)
ensureConsumeAllOrNotPersistent();
}
// RFC 7230, section 3.3.
if (!_request.isHead() &&
_response.getStatus() != HttpStatus.NOT_MODIFIED_304 &&
!_response.isContentComplete(_response.getHttpOutput().getWritten()))
{
if (sendErrorOrAbort("Insufficient content written"))
break;
}
// If send error is called we need to break.
if (checkAndPrepareUpgrade())
break;
// Set a close callback on the HttpOutput to make it an async callback
_response.completeOutput(Callback.from(NON_BLOCKING, () -> _state.completed(null), _state::completed));
break;
}
default:
throw new IllegalStateException(this.toString());
}
}
catch (Throwable failure)
{
if ("org.eclipse.jetty.continuation.ContinuationThrowable".equals(failure.getClass().getName()))
LOG.trace("IGNORED", failure);
else
handleException(failure);
}
action = _state.unhandle();
}
if (LOG.isDebugEnabled())
LOG.debug("!handle {} {}", action, this);
boolean suspended = action == Action.WAIT;
return !suspended;
}
public void ensureConsumeAllOrNotPersistent()
{
switch (_request.getHttpVersion())
{
case HTTP_1_0:
if (_request.getHttpInput().consumeAll())
return;
// Remove any keep-alive value in Connection headers
_response.getHttpFields().computeField(HttpHeader.CONNECTION, (h, fields) ->
{
if (fields == null || fields.isEmpty())
return null;
String v = fields.stream()
.flatMap(field -> Stream.of(field.getValues()).filter(s -> !HttpHeaderValue.KEEP_ALIVE.is(s)))
.collect(Collectors.joining(", "));
if (StringUtil.isEmpty(v))
return null;
return new HttpField(HttpHeader.CONNECTION, v);
});
break;
case HTTP_1_1:
if (_request.getHttpInput().consumeAll())
return;
// Add close value to Connection headers
_response.getHttpFields().computeField(HttpHeader.CONNECTION, (h, fields) ->
{
if (fields == null || fields.isEmpty())
return HttpConnection.CONNECTION_CLOSE;
if (fields.stream().anyMatch(f -> f.contains(HttpHeaderValue.CLOSE.asString())))
{
if (fields.size() == 1)
{
HttpField f = fields.get(0);
if (HttpConnection.CONNECTION_CLOSE.equals(f))
return f;
}
return new HttpField(HttpHeader.CONNECTION, fields.stream()
.flatMap(field -> Stream.of(field.getValues()).filter(s -> !HttpHeaderValue.KEEP_ALIVE.is(s)))
.collect(Collectors.joining(", ")));
}
return new HttpField(HttpHeader.CONNECTION,
Stream.concat(fields.stream()
.flatMap(field -> Stream.of(field.getValues()).filter(s -> !HttpHeaderValue.KEEP_ALIVE.is(s))),
Stream.of(HttpHeaderValue.CLOSE.asString()))
.collect(Collectors.joining(", ")));
});
break;
default:
break;
}
}
/**
* @param message the error message.
* @return true if we have sent an error, false if we have aborted.
*/
public boolean sendErrorOrAbort(String message)
{
try
{
if (isCommitted())
{
abort(new IOException(message));
return false;
}
_response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, message);
return true;
}
catch (Throwable x)
{
LOG.trace("IGNORED", x);
abort(x);
}
return false;
}
private void dispatch(DispatcherType type, Dispatchable dispatchable) throws IOException, ServletException
{
try
{
_request.setHandled(false);
_response.reopen();
_request.setDispatcherType(type);
_combinedListener.onBeforeDispatch(_request);
dispatchable.dispatch();
}
catch (Throwable x)
{
_combinedListener.onDispatchFailure(_request, x);
throw x;
}
finally
{
_combinedListener.onAfterDispatch(_request);
_request.setDispatcherType(null);
}
}
/**
* <p>Sends an error 500, performing a special logic to detect whether the request is suspended,
* to avoid concurrent writes from the application.</p>
* <p>It may happen that the application suspends, and then throws an exception, while an application
* spawned thread writes the response content; in such case, we attempt to commit the error directly
* bypassing the {@link ErrorHandler} mechanisms and the response OutputStream.</p>
*
* @param failure the Throwable that caused the problem
*/
protected void handleException(Throwable failure)
{
// Unwrap wrapping Jetty and Servlet exceptions.
Throwable quiet = unwrap(failure, QuietException.class);
Throwable noStack = unwrap(failure, BadMessageException.class, IOException.class, TimeoutException.class);
if (quiet != null || !getServer().isRunning())
{
if (LOG.isDebugEnabled())
LOG.debug(_request.getRequestURI(), failure);
}
else if (noStack != null)
{
// No stack trace unless there is debug turned on
if (LOG.isDebugEnabled())
LOG.warn("handleException {}", _request.getRequestURI(), failure);
else
LOG.warn("handleException {} {}", _request.getRequestURI(), noStack.toString());
}
else
{
LOG.warn(_request.getRequestURI(), failure);
}
if (isCommitted())
{
abort(failure);
}
else
{
try
{
_state.onError(failure);
}
catch (IllegalStateException e)
{
abort(failure);
}
}
}
/**
* Unwrap failure causes to find target class
*
* @param failure The throwable to have its causes unwrapped
* @param targets Exception classes that we should not unwrap
* @return A target throwable or null
*/
protected Throwable unwrap(Throwable failure, Class<?>... targets)
{
while (failure != null)
{
for (Class<?> x : targets)
{
if (x.isInstance(failure))
return failure;
}
failure = failure.getCause();
}
return null;
}
public void sendResponseAndComplete()
{
try
{
_request.setHandled(true);
_state.completing();
sendResponse(null, _response.getHttpOutput().getBuffer(), true, Callback.from(() -> _state.completed(null), _state::completed));
}
catch (Throwable x)
{
abort(x);
}
}
public boolean isExpecting100Continue()
{
return false;
}
public boolean isExpecting102Processing()
{
return false;
}
@Override
public String toString()
{
long timeStamp = _request.getTimeStamp();
return String.format("%s@%x{s=%s,r=%s,c=%b/%b,a=%s,uri=%s,age=%d}",
getClass().getSimpleName(),
hashCode(),
_state,
_requests,
isRequestCompleted(),
isResponseCompleted(),
_state.getState(),
_request.getHttpURI(),
timeStamp == 0 ? 0 : System.currentTimeMillis() - timeStamp);
}
public void onRequest(MetaData.Request request)
{
_requests.incrementAndGet();
_request.setTimeStamp(System.currentTimeMillis());
HttpFields.Mutable fields = _response.getHttpFields();
if (_configuration.getSendDateHeader() && !fields.contains(HttpHeader.DATE))
fields.put(_connector.getServer().getDateField());
long idleTO = _configuration.getIdleTimeout();
_oldIdleTimeout = getIdleTimeout();
if (idleTO >= 0 && _oldIdleTimeout != idleTO)
setIdleTimeout(idleTO);
_request.setMetaData(request);
_combinedListener.onRequestBegin(_request);
if (LOG.isDebugEnabled())
LOG.debug("REQUEST for {} on {}{}{} {} {}{}{}", request.getURIString(), this, System.lineSeparator(),
request.getMethod(), request.getURIString(), request.getHttpVersion(), System.lineSeparator(),
request.getFields());
}
public boolean onContent(HttpInput.Content content)
{
if (LOG.isDebugEnabled())
LOG.debug("onContent {} {}", this, content);
_combinedListener.onRequestContent(_request, content.getByteBuffer());
return false;
}
public boolean onContentComplete()
{
if (LOG.isDebugEnabled())
LOG.debug("onContentComplete {}", this);
_combinedListener.onRequestContentEnd(_request);
return false;
}
public void onTrailers(HttpFields trailers)
{
if (LOG.isDebugEnabled())
LOG.debug("onTrailers {} {}", this, trailers);
_request.setTrailerHttpFields(trailers);
_combinedListener.onRequestTrailers(_request);
}
public boolean onRequestComplete()
{
if (LOG.isDebugEnabled())
LOG.debug("onRequestComplete {}", this);
boolean result = eof();
_combinedListener.onRequestEnd(_request);
return result;
}
/**
* <p>Checks whether the processing of the request resulted in an upgrade,
* and if so performs upgrade preparation steps <em>before</em> the upgrade
* response is sent back to the client.</p>
* <p>This avoids a race where the server is unprepared if the client sends
* data immediately after having received the upgrade response.</p>
* @return true if the channel is not complete and more processing is required,
* typically because sendError has been called.
*/
protected boolean checkAndPrepareUpgrade()
{
return false;
}
public void onCompleted()
{
if (LOG.isDebugEnabled())
LOG.debug("onCompleted for {} written={}", getRequest().getRequestURI(), getBytesWritten());
long idleTO = _configuration.getIdleTimeout();
if (idleTO >= 0 && getIdleTimeout() != _oldIdleTimeout)
setIdleTimeout(_oldIdleTimeout);
_request.onCompleted();
_combinedListener.onComplete(_request);
_transport.onCompleted();
}
public void onBadMessage(BadMessageException failure)
{
int status = failure.getCode();
String reason = failure.getReason();
if (status < HttpStatus.BAD_REQUEST_400 || status > 599)
failure = new BadMessageException(HttpStatus.BAD_REQUEST_400, reason, failure);
_combinedListener.onRequestFailure(_request, failure);
Action action;
try
{
action = _state.handling();
}
catch (Throwable e)
{
// The bad message cannot be handled in the current state,
// so rethrow, hopefully somebody will be able to handle.
abort(e);
throw failure;
}
try
{
if (action == Action.DISPATCH)
{
ByteBuffer content = null;
HttpFields.Mutable fields = HttpFields.build();
ErrorHandler handler = getServer().getBean(ErrorHandler.class);