/
HTTP2Session.java
2361 lines (2149 loc) · 80.4 KB
/
HTTP2Session.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-2021 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.http2;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http2.api.Session;
import org.eclipse.jetty.http2.api.Stream;
import org.eclipse.jetty.http2.frames.DataFrame;
import org.eclipse.jetty.http2.frames.FailureFrame;
import org.eclipse.jetty.http2.frames.Frame;
import org.eclipse.jetty.http2.frames.FrameType;
import org.eclipse.jetty.http2.frames.GoAwayFrame;
import org.eclipse.jetty.http2.frames.HeadersFrame;
import org.eclipse.jetty.http2.frames.PingFrame;
import org.eclipse.jetty.http2.frames.PrefaceFrame;
import org.eclipse.jetty.http2.frames.PriorityFrame;
import org.eclipse.jetty.http2.frames.PushPromiseFrame;
import org.eclipse.jetty.http2.frames.ResetFrame;
import org.eclipse.jetty.http2.frames.SettingsFrame;
import org.eclipse.jetty.http2.frames.StreamFrame;
import org.eclipse.jetty.http2.frames.WindowUpdateFrame;
import org.eclipse.jetty.http2.generator.Generator;
import org.eclipse.jetty.http2.hpack.HpackException;
import org.eclipse.jetty.http2.parser.Parser;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.CyclicTimeouts;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.WriteFlusher;
import org.eclipse.jetty.util.AtomicBiInteger;
import org.eclipse.jetty.util.Atomics;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.CountingCallback;
import org.eclipse.jetty.util.MathUtils;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.DumpableCollection;
import org.eclipse.jetty.util.thread.AutoLock;
import org.eclipse.jetty.util.thread.Invocable;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ManagedObject
public abstract class HTTP2Session extends ContainerLifeCycle implements ISession, Parser.Listener
{
private static final Logger LOG = LoggerFactory.getLogger(HTTP2Session.class);
private final ConcurrentMap<Integer, IStream> streams = new ConcurrentHashMap<>();
private final AtomicLong streamsOpened = new AtomicLong();
private final AtomicLong streamsClosed = new AtomicLong();
private final StreamsState streamsState = new StreamsState();
private final AtomicInteger localStreamIds = new AtomicInteger();
private final AtomicInteger lastRemoteStreamId = new AtomicInteger();
private final AtomicInteger localStreamCount = new AtomicInteger();
private final AtomicBiInteger remoteStreamCount = new AtomicBiInteger();
private final AtomicInteger sendWindow = new AtomicInteger();
private final AtomicInteger recvWindow = new AtomicInteger();
private final AtomicLong bytesWritten = new AtomicLong();
private final EndPoint endPoint;
private final Generator generator;
private final Session.Listener listener;
private final FlowControlStrategy flowControl;
private final HTTP2Flusher flusher;
private final StreamTimeouts streamTimeouts;
private int maxLocalStreams;
private int maxRemoteStreams;
private long streamIdleTimeout;
private int initialSessionRecvWindow;
private int writeThreshold;
private boolean pushEnabled;
private boolean connectProtocolEnabled;
public HTTP2Session(Scheduler scheduler, EndPoint endPoint, Generator generator, Session.Listener listener, FlowControlStrategy flowControl, int initialStreamId)
{
this.endPoint = endPoint;
this.generator = generator;
this.listener = listener;
this.flowControl = flowControl;
this.flusher = new HTTP2Flusher(this);
this.streamTimeouts = new StreamTimeouts(scheduler);
this.maxLocalStreams = -1;
this.maxRemoteStreams = -1;
this.localStreamIds.set(initialStreamId);
this.streamIdleTimeout = endPoint.getIdleTimeout();
this.sendWindow.set(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
this.recvWindow.set(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
this.writeThreshold = 32 * 1024;
this.pushEnabled = true; // SPEC: by default, push is enabled.
addBean(flowControl);
addBean(flusher);
}
@Override
protected void doStop() throws Exception
{
super.doStop();
streamsState.halt("stop");
}
@ManagedAttribute(value = "The flow control strategy", readonly = true)
public FlowControlStrategy getFlowControlStrategy()
{
return flowControl;
}
@ManagedAttribute(value = "The total number of streams opened", readonly = true)
public long getStreamsOpened()
{
return streamsOpened.get();
}
@ManagedAttribute(value = "The total number of streams closed", readonly = true)
public long getStreamsClosed()
{
return streamsClosed.get();
}
@ManagedAttribute("The maximum number of concurrent local streams")
public int getMaxLocalStreams()
{
return maxLocalStreams;
}
public void setMaxLocalStreams(int maxLocalStreams)
{
this.maxLocalStreams = maxLocalStreams;
}
@ManagedAttribute("The maximum number of concurrent remote streams")
public int getMaxRemoteStreams()
{
return maxRemoteStreams;
}
public void setMaxRemoteStreams(int maxRemoteStreams)
{
this.maxRemoteStreams = maxRemoteStreams;
}
@ManagedAttribute("The stream's idle timeout")
public long getStreamIdleTimeout()
{
return streamIdleTimeout;
}
public void setStreamIdleTimeout(long streamIdleTimeout)
{
this.streamIdleTimeout = streamIdleTimeout;
}
@ManagedAttribute("The initial size of session's flow control receive window")
public int getInitialSessionRecvWindow()
{
return initialSessionRecvWindow;
}
public void setInitialSessionRecvWindow(int initialSessionRecvWindow)
{
this.initialSessionRecvWindow = initialSessionRecvWindow;
}
@ManagedAttribute("The number of bytes that trigger a TCP write")
public int getWriteThreshold()
{
return writeThreshold;
}
public void setWriteThreshold(int writeThreshold)
{
this.writeThreshold = writeThreshold;
}
public EndPoint getEndPoint()
{
return endPoint;
}
public Generator getGenerator()
{
return generator;
}
@Override
public long getBytesWritten()
{
return bytesWritten.get();
}
@Override
public void onData(DataFrame frame)
{
onData(frame, Callback.NOOP);
}
@Override
public void onData(DataFrame frame, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
int streamId = frame.getStreamId();
IStream stream = getStream(streamId);
// SPEC: the session window must be updated even if the stream is null.
// The flow control length includes the padding bytes.
int flowControlLength = frame.remaining() + frame.padding();
flowControl.onDataReceived(this, stream, flowControlLength);
if (stream != null)
{
if (getRecvWindow() < 0)
{
onSessionFailure(ErrorCode.FLOW_CONTROL_ERROR.code, "session_window_exceeded", callback);
}
else
{
if (stream.updateRecvWindow(0) < 0)
{
// It's a bad client, it does not deserve to be
// treated gently by just resetting the stream.
onSessionFailure(ErrorCode.FLOW_CONTROL_ERROR.code, "stream_window_exceeded", callback);
}
else
{
stream.process(frame, new DataCallback(callback, stream, flowControlLength));
}
}
}
else
{
if (LOG.isDebugEnabled())
LOG.debug("Stream #{} not found on {}", streamId, this);
// We must enlarge the session flow control window,
// otherwise other requests will be stalled.
flowControl.onDataConsumed(this, null, flowControlLength);
if (isStreamClosed(streamId))
reset(null, new ResetFrame(streamId, ErrorCode.STREAM_CLOSED_ERROR.code), callback);
else
onSessionFailure(ErrorCode.PROTOCOL_ERROR.code, "unexpected_data_frame", callback);
}
}
private boolean isStreamClosed(int streamId)
{
return isLocalStream(streamId) ? isLocalStreamClosed(streamId) : isRemoteStreamClosed(streamId);
}
private boolean isLocalStream(int streamId)
{
return (streamId & 1) == (localStreamIds.get() & 1);
}
protected boolean isLocalStreamClosed(int streamId)
{
return streamId <= localStreamIds.get();
}
protected boolean isRemoteStreamClosed(int streamId)
{
return streamId <= getLastRemoteStreamId();
}
@Override
public abstract void onHeaders(HeadersFrame frame);
@Override
public void onPriority(PriorityFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
}
@Override
public void onReset(ResetFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
int streamId = frame.getStreamId();
IStream stream = getStream(streamId);
if (stream != null)
{
stream.process(frame, new OnResetCallback());
}
else
{
onResetForUnknownStream(frame);
}
}
protected void onResetForUnknownStream(ResetFrame frame)
{
if (isStreamClosed(frame.getStreamId()))
notifyReset(this, frame);
else
onConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "unexpected_rst_stream_frame");
}
@Override
public void onSettings(SettingsFrame frame)
{
// SPEC: SETTINGS frame MUST be replied.
onSettings(frame, true);
}
public void onSettings(SettingsFrame frame, boolean reply)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
if (frame.isReply())
return;
// Iterate over all settings
for (Map.Entry<Integer, Integer> entry : frame.getSettings().entrySet())
{
int key = entry.getKey();
int value = entry.getValue();
switch (key)
{
case SettingsFrame.HEADER_TABLE_SIZE:
{
if (LOG.isDebugEnabled())
LOG.debug("Updating HPACK header table size to {} for {}", value, this);
generator.setHeaderTableSize(value);
break;
}
case SettingsFrame.ENABLE_PUSH:
{
boolean enabled = value == 1;
if (LOG.isDebugEnabled())
LOG.debug("{} push for {}", enabled ? "Enabling" : "Disabling", this);
pushEnabled = enabled;
break;
}
case SettingsFrame.MAX_CONCURRENT_STREAMS:
{
if (LOG.isDebugEnabled())
LOG.debug("Updating max local concurrent streams to {} for {}", value, this);
maxLocalStreams = value;
break;
}
case SettingsFrame.INITIAL_WINDOW_SIZE:
{
if (LOG.isDebugEnabled())
LOG.debug("Updating initial stream window size to {} for {}", value, this);
flowControl.updateInitialStreamWindow(this, value, false);
break;
}
case SettingsFrame.MAX_FRAME_SIZE:
{
if (LOG.isDebugEnabled())
LOG.debug("Updating max frame size to {} for {}", value, this);
generator.setMaxFrameSize(value);
break;
}
case SettingsFrame.MAX_HEADER_LIST_SIZE:
{
if (LOG.isDebugEnabled())
LOG.debug("Updating max header list size to {} for {}", value, this);
generator.setMaxHeaderListSize(value);
break;
}
case SettingsFrame.ENABLE_CONNECT_PROTOCOL:
{
boolean enabled = value == 1;
if (LOG.isDebugEnabled())
LOG.debug("{} CONNECT protocol for {}", enabled ? "Enabling" : "Disabling", this);
connectProtocolEnabled = enabled;
break;
}
default:
{
if (LOG.isDebugEnabled())
LOG.debug("Unknown setting {}:{} for {}", key, value, this);
break;
}
}
}
notifySettings(this, frame);
if (reply)
{
SettingsFrame replyFrame = new SettingsFrame(Collections.emptyMap(), true);
settings(replyFrame, Callback.NOOP);
}
}
@Override
public void onPing(PingFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
if (frame.isReply())
{
notifyPing(this, frame);
}
else
{
PingFrame reply = new PingFrame(frame.getPayload(), true);
control(null, Callback.NOOP, reply);
}
}
/**
* <p>This method is called when receiving a GO_AWAY from the other peer.</p>
*
* @param frame the GO_AWAY frame that has been received.
* @see #close(int, String, Callback)
* @see #onShutdown()
* @see #onIdleTimeout()
*/
@Override
public void onGoAway(GoAwayFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
streamsState.onGoAway(frame);
}
@Override
public void onWindowUpdate(WindowUpdateFrame frame)
{
if (LOG.isDebugEnabled())
LOG.debug("Received {} on {}", frame, this);
int streamId = frame.getStreamId();
int windowDelta = frame.getWindowDelta();
if (streamId > 0)
{
IStream stream = getStream(streamId);
if (stream != null)
{
int streamSendWindow = stream.updateSendWindow(0);
if (MathUtils.sumOverflows(streamSendWindow, windowDelta))
{
reset(stream, new ResetFrame(streamId, ErrorCode.FLOW_CONTROL_ERROR.code), Callback.NOOP);
}
else
{
stream.process(frame, Callback.NOOP);
onWindowUpdate(stream, frame);
}
}
else
{
if (!isStreamClosed(streamId))
onConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "unexpected_window_update_frame");
}
}
else
{
int sessionSendWindow = updateSendWindow(0);
if (MathUtils.sumOverflows(sessionSendWindow, windowDelta))
onConnectionFailure(ErrorCode.FLOW_CONTROL_ERROR.code, "invalid_flow_control_window");
else
onWindowUpdate(null, frame);
}
}
@Override
public void onWindowUpdate(IStream stream, WindowUpdateFrame frame)
{
// WindowUpdateFrames arrive concurrently with writes.
// Increasing (or reducing) the window size concurrently
// with writes requires coordination with the flusher, that
// decides how many frames to write depending on the available
// window sizes. If the window sizes vary concurrently, the
// flusher may take non-optimal or wrong decisions.
// Here, we "queue" window updates to the flusher, so it will
// be the only component responsible for window updates, for
// both increments and reductions.
flusher.window(stream, frame);
}
@Override
public void onStreamFailure(int streamId, int error, String reason)
{
Callback callback = Callback.from(() -> reset(getStream(streamId), new ResetFrame(streamId, error), Callback.NOOP));
Throwable failure = toFailure(error, reason);
if (LOG.isDebugEnabled())
LOG.debug("Stream #{} failure {}", streamId, this, failure);
IStream stream = getStream(streamId);
if (stream != null)
failStream(stream, error, reason, failure, callback);
else
callback.succeeded();
}
@Override
public void onConnectionFailure(int error, String reason)
{
onSessionFailure(error, reason, Callback.NOOP);
}
private void onSessionFailure(int error, String reason, Callback callback)
{
streamsState.onSessionFailure(error, reason, callback);
}
void onWriteFailure(Throwable failure)
{
streamsState.onWriteFailure(failure);
}
protected void abort(String reason, Throwable failure, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("Session abort {} for {}", reason, this, failure);
onFailure(ErrorCode.NO_ERROR.code, reason, failure, callback);
}
private void onFailure(int error, String reason, Throwable failure, Callback callback)
{
Collection<Stream> streams = getStreams();
int count = streams.size();
Callback countCallback = new CountingCallback(callback, count + 1);
for (Stream stream : streams)
{
if (stream.isClosed())
countCallback.succeeded();
else
failStream(stream, error, reason, failure, countCallback);
}
notifyFailure(this, failure, countCallback);
}
private void failStreams(Predicate<IStream> matcher, String reason, boolean reset)
{
int error = ErrorCode.CANCEL_STREAM_ERROR.code;
Throwable failure = toFailure(error, reason);
for (Stream stream : getStreams())
{
if (stream.isClosed())
continue;
if (!matcher.test((IStream)stream))
continue;
if (LOG.isDebugEnabled())
LOG.debug("Failing stream {} of {}", stream, this);
failStream(stream, error, reason, failure, Callback.NOOP);
if (reset)
stream.reset(new ResetFrame(stream.getId(), error), Callback.NOOP);
}
}
private void failStream(Stream stream, int error, String reason, Throwable failure, Callback callback)
{
((IStream)stream).process(new FailureFrame(error, reason, failure), callback);
}
private Throwable toFailure(int error, String reason)
{
return new IOException(String.format("%s/%s", ErrorCode.toString(error, null), reason));
}
@Override
public void newStream(HeadersFrame frame, Promise<Stream> promise, Stream.Listener listener)
{
newStream(new IStream.FrameList(frame), promise, listener);
}
@Override
public void newStream(IStream.FrameList frames, Promise<Stream> promise, Stream.Listener listener)
{
streamsState.newLocalStream(frames, promise, listener);
}
/**
* <p>Creates a new stream allocating a stream id if the given HEADERS frame does not have one.</p>
*
* @param frame the HEADERS frame that triggered the stream creation
* allocated stream id, or null if not interested in the modified headers frame
* @param listener the listener that gets notified of stream events
*/
public Stream newUpgradeStream(HeadersFrame frame, Stream.Listener listener, Consumer<Throwable> failFn)
{
return streamsState.newUpgradeStream(frame, listener, failFn);
}
protected IStream newStream(int streamId, MetaData.Request request, boolean local)
{
return new HTTP2Stream(this, streamId, request, local);
}
@Override
public int priority(PriorityFrame frame, Callback callback)
{
return streamsState.priority(frame, callback);
}
@Override
public void push(IStream stream, Promise<Stream> promise, PushPromiseFrame frame, Stream.Listener listener)
{
streamsState.push(frame, new Promise.Wrapper<>(promise)
{
@Override
public void succeeded(Stream pushedStream)
{
// Pushed streams are implicitly remotely closed.
// They are closed when sending an end-stream DATA frame.
((IStream)pushedStream).updateClose(true, CloseState.Event.RECEIVED);
super.succeeded(pushedStream);
}
}, listener);
}
@Override
public void settings(SettingsFrame frame, Callback callback)
{
control(null, callback, frame);
}
@Override
public void ping(PingFrame frame, Callback callback)
{
if (frame.isReply())
callback.failed(new IllegalArgumentException());
else
control(null, callback, frame);
}
void reset(IStream stream, ResetFrame frame, Callback callback)
{
control(stream, Callback.from(() ->
{
if (stream != null)
{
stream.close();
removeStream(stream);
}
}, callback), frame);
}
/**
* <p>Invoked internally and by applications to send a GO_AWAY frame to the other peer.</p>
*
* @param error the error code
* @param reason the reason
* @param callback the callback to invoke when the operation is complete
* @see #onGoAway(GoAwayFrame)
* @see #onShutdown()
* @see #onIdleTimeout()
*/
@Override
public boolean close(int error, String reason, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("Closing {}/{} {}", ErrorCode.toString(error, null), reason, this);
return goAway(newGoAwayFrame(error, reason), callback);
}
@Override
public CompletableFuture<Void> shutdown()
{
return streamsState.shutdown();
}
public boolean goAway(GoAwayFrame frame, Callback callback)
{
return streamsState.goAway(frame, callback);
}
private GoAwayFrame newGoAwayFrame(int error, String reason)
{
return newGoAwayFrame(getLastRemoteStreamId(), error, reason);
}
private GoAwayFrame newGoAwayFrame(int lastRemoteStreamId, int error, String reason)
{
byte[] payload = null;
if (reason != null)
{
// Trim the reason to avoid attack vectors.
reason = reason.substring(0, Math.min(reason.length(), 32));
payload = reason.getBytes(StandardCharsets.UTF_8);
}
return new GoAwayFrame(lastRemoteStreamId, error, payload);
}
@Override
public boolean isClosed()
{
return getCloseState() != CloseState.NOT_CLOSED;
}
public CloseState getCloseState()
{
return streamsState.getCloseState();
}
private void control(IStream stream, Callback callback, Frame frame)
{
frames(stream, List.of(frame), callback);
}
@Override
public void frames(IStream stream, List<? extends Frame> frames, Callback callback)
{
// We want to generate as late as possible to allow re-prioritization;
// generation will happen while processing the entries.
// The callback needs to be notified only when the last frame completes.
int count = frames.size();
if (count > 1)
callback = new CountingCallback(callback, count);
for (int i = 1; i <= count; ++i)
{
Frame frame = frames.get(i - 1);
HTTP2Flusher.Entry entry = newEntry(frame, stream, callback);
frame(entry, i == count);
}
}
private HTTP2Flusher.Entry newEntry(Frame frame, IStream stream, Callback callback)
{
return frame.getType() == FrameType.DATA
? new DataEntry((DataFrame)frame, stream, callback)
: new ControlEntry(frame, stream, callback);
}
@Override
public void data(IStream stream, Callback callback, DataFrame frame)
{
// We want to generate as late as possible to allow re-prioritization.
frame(newEntry(frame, stream, callback), true);
}
private void frame(HTTP2Flusher.Entry entry, boolean flush)
{
if (LOG.isDebugEnabled())
LOG.debug("{} {} on {}", flush ? "Sending" : "Queueing", entry, this);
// Ping frames are prepended to process them as soon as possible.
boolean queued = entry.hasHighPriority() ? flusher.prepend(entry) : flusher.append(entry);
if (queued && flush)
{
if (entry.stream != null)
entry.stream.notIdle();
flusher.iterate();
}
}
protected IStream createLocalStream(int streamId, MetaData.Request request, Consumer<Throwable> failFn)
{
while (true)
{
int localCount = localStreamCount.get();
int maxCount = getMaxLocalStreams();
if (maxCount >= 0 && localCount >= maxCount)
{
IllegalStateException failure = new IllegalStateException("Max local stream count " + maxCount + " exceeded: " + localCount);
if (LOG.isDebugEnabled())
LOG.debug("Could not create local stream #{} for {}", streamId, this, failure);
failFn.accept(failure);
return null;
}
if (localStreamCount.compareAndSet(localCount, localCount + 1))
break;
}
IStream stream = newStream(streamId, request, true);
if (streams.putIfAbsent(streamId, stream) == null)
{
stream.setIdleTimeout(getStreamIdleTimeout());
flowControl.onStreamCreated(stream);
if (LOG.isDebugEnabled())
LOG.debug("Created local {} for {}", stream, this);
return stream;
}
else
{
localStreamCount.decrementAndGet();
failFn.accept(new IllegalStateException("Duplicate stream " + streamId));
return null;
}
}
protected IStream createRemoteStream(int streamId, MetaData.Request request)
{
// This stream has been seen the server.
// Even if the stream cannot be created because this peer is closing,
// updating the lastRemoteStreamId ensures that in-flight HEADERS and
// DATA frames can be read (and discarded) without causing an error.
updateLastRemoteStreamId(streamId);
if (!streamsState.newRemoteStream(streamId))
{
if (LOG.isDebugEnabled())
LOG.debug("Could not create remote stream #{} for {}", streamId, this);
return null;
}
// SPEC: exceeding max concurrent streams is treated as stream error.
while (true)
{
long encoded = remoteStreamCount.get();
int remoteCount = AtomicBiInteger.getHi(encoded);
int remoteClosing = AtomicBiInteger.getLo(encoded);
int maxCount = getMaxRemoteStreams();
if (maxCount >= 0 && remoteCount - remoteClosing >= maxCount)
{
IllegalStateException failure = new IllegalStateException("Max remote stream count " + maxCount + " exceeded: " + remoteCount + "+" + remoteClosing);
if (LOG.isDebugEnabled())
LOG.debug("Could not create remote stream #{} for {}", streamId, this, failure);
reset(null, new ResetFrame(streamId, ErrorCode.REFUSED_STREAM_ERROR.code), Callback.from(() -> onStreamDestroyed(streamId)));
return null;
}
if (remoteStreamCount.compareAndSet(encoded, remoteCount + 1, remoteClosing))
break;
}
IStream stream = newStream(streamId, request, false);
if (streams.putIfAbsent(streamId, stream) == null)
{
stream.setIdleTimeout(getStreamIdleTimeout());
flowControl.onStreamCreated(stream);
if (LOG.isDebugEnabled())
LOG.debug("Created remote {} for {}", stream, this);
return stream;
}
else
{
remoteStreamCount.addAndGetHi(-1);
onStreamDestroyed(streamId);
// SPEC: duplicate stream is treated as connection error.
onConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "duplicate_stream");
return null;
}
}
void updateStreamCount(boolean local, int deltaStreams, int deltaClosing)
{
if (local)
localStreamCount.addAndGet(deltaStreams);
else
remoteStreamCount.add(deltaStreams, deltaClosing);
}
@Override
public boolean removeStream(IStream stream)
{
int streamId = stream.getId();
IStream removed = streams.remove(streamId);
if (removed == null)
return false;
if (LOG.isDebugEnabled())
LOG.debug("Removed {} {} from {}", stream.isLocal() ? "local" : "remote", stream, this);
onStreamClosed(stream);
flowControl.onStreamDestroyed(stream);
onStreamDestroyed(streamId);
return true;
}
@Override
public Collection<Stream> getStreams()
{
return new ArrayList<>(streams.values());
}
@ManagedAttribute("The number of active streams")
public int getStreamCount()
{
return streamsState.streamCount.intValue();
}
@Override
public IStream getStream(int streamId)
{
return streams.get(streamId);
}
@Override
public InetSocketAddress getLocalAddress()
{
SocketAddress local = getLocalSocketAddress();
if (local instanceof InetSocketAddress)
return (InetSocketAddress)local;
return null;
}
@Override
public SocketAddress getLocalSocketAddress()
{
return endPoint.getLocalSocketAddress();
}
@Override
public InetSocketAddress getRemoteAddress()
{
SocketAddress remote = getRemoteSocketAddress();
if (remote instanceof InetSocketAddress)
return (InetSocketAddress)remote;
return null;
}
@Override
public SocketAddress getRemoteSocketAddress()
{
return endPoint.getRemoteSocketAddress();
}
@ManagedAttribute(value = "The flow control send window", readonly = true)
public int getSendWindow()
{
return sendWindow.get();
}
@ManagedAttribute(value = "The flow control receive window", readonly = true)
public int getRecvWindow()
{
return recvWindow.get();
}
@Override
public int updateSendWindow(int delta)
{
return sendWindow.getAndAdd(delta);
}
@Override
public int updateRecvWindow(int delta)
{
return recvWindow.getAndAdd(delta);
}
@Override
@ManagedAttribute(value = "Whether HTTP/2 push is enabled", readonly = true)
public boolean isPushEnabled()
{
return pushEnabled;
}
@ManagedAttribute(value = "Whether CONNECT requests supports a protocol", readonly = true)
public boolean isConnectProtocolEnabled()
{
return connectProtocolEnabled;
}
public void setConnectProtocolEnabled(boolean connectProtocolEnabled)
{
this.connectProtocolEnabled = connectProtocolEnabled;
}
/**
* <p>This method is called when the TCP FIN is received from the remote peer.</p>
*
* @see #onGoAway(GoAwayFrame)
* @see #close(int, String, Callback)
* @see #onIdleTimeout()
*/
@Override
public void onShutdown()
{
streamsState.onShutdown();
}
/**
* <p>This method is invoked when the idle timeout expires.</p>
*
* @return true if the session should be closed, false otherwise
* @see #onGoAway(GoAwayFrame)
* @see #close(int, String, Callback)