forked from python-hyper/h2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.py
2047 lines (1738 loc) · 81 KB
/
connection.py
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
# -*- coding: utf-8 -*-
"""
h2/connection
~~~~~~~~~~~~~
An implementation of a HTTP/2 connection.
"""
import base64
from enum import Enum, IntEnum
from hyperframe.exceptions import InvalidPaddingError
from hyperframe.frame import (
GoAwayFrame, WindowUpdateFrame, HeadersFrame, DataFrame, PingFrame,
PushPromiseFrame, SettingsFrame, RstStreamFrame, PriorityFrame,
ContinuationFrame, AltSvcFrame, ExtensionFrame
)
from hpack.hpack import Encoder, Decoder
from hpack.exceptions import HPACKError, OversizedHeaderListError
from .config import H2Configuration
from .errors import ErrorCodes, _error_code_from_int
from .events import (
WindowUpdated, RemoteSettingsChanged, PingReceived, PingAckReceived,
SettingsAcknowledged, ConnectionTerminated, PriorityUpdated,
AlternativeServiceAvailable, UnknownFrameReceived
)
from .exceptions import (
ProtocolError, NoSuchStreamError, FlowControlError, FrameTooLargeError,
TooManyStreamsError, StreamClosedError, StreamIDTooLowError,
NoAvailableStreamIDError, RFC1122Error, DenialOfServiceError
)
from .frame_buffer import FrameBuffer
from .settings import Settings, SettingCodes
from .stream import H2Stream, StreamClosedBy
from .utilities import SizeLimitDict, guard_increment_window
from .windows import WindowManager
class ConnectionState(Enum):
IDLE = 0
CLIENT_OPEN = 1
SERVER_OPEN = 2
CLOSED = 3
class ConnectionInputs(Enum):
SEND_HEADERS = 0
SEND_PUSH_PROMISE = 1
SEND_DATA = 2
SEND_GOAWAY = 3
SEND_WINDOW_UPDATE = 4
SEND_PING = 5
SEND_SETTINGS = 6
SEND_RST_STREAM = 7
SEND_PRIORITY = 8
RECV_HEADERS = 9
RECV_PUSH_PROMISE = 10
RECV_DATA = 11
RECV_GOAWAY = 12
RECV_WINDOW_UPDATE = 13
RECV_PING = 14
RECV_SETTINGS = 15
RECV_RST_STREAM = 16
RECV_PRIORITY = 17
SEND_ALTERNATIVE_SERVICE = 18 # Added in 2.3.0
RECV_ALTERNATIVE_SERVICE = 19 # Added in 2.3.0
class AllowedStreamIDs(IntEnum):
EVEN = 0
ODD = 1
class H2ConnectionStateMachine:
"""
A single HTTP/2 connection state machine.
This state machine, while defined in its own class, is logically part of
the H2Connection class also defined in this file. The state machine itself
maintains very little state directly, instead focusing entirely on managing
state transitions.
"""
# For the purposes of this state machine we treat HEADERS and their
# associated CONTINUATION frames as a single jumbo frame. The protocol
# allows/requires this by preventing other frames from being interleved in
# between HEADERS/CONTINUATION frames.
#
# The _transitions dictionary contains a mapping of tuples of
# (state, input) to tuples of (side_effect_function, end_state). This map
# contains all allowed transitions: anything not in this map is invalid
# and immediately causes a transition to ``closed``.
_transitions = {
# State: idle
(ConnectionState.IDLE, ConnectionInputs.SEND_HEADERS):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.IDLE, ConnectionInputs.RECV_HEADERS):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.IDLE, ConnectionInputs.SEND_SETTINGS):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.RECV_SETTINGS):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.SEND_WINDOW_UPDATE):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.RECV_WINDOW_UPDATE):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.SEND_PING):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.RECV_PING):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.SEND_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.IDLE, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.IDLE, ConnectionInputs.SEND_PRIORITY):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.RECV_PRIORITY):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.SEND_ALTERNATIVE_SERVICE):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.IDLE, ConnectionInputs.RECV_ALTERNATIVE_SERVICE):
(None, ConnectionState.CLIENT_OPEN),
# State: open, client side.
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_HEADERS):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_DATA):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_WINDOW_UPDATE):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_PING):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_SETTINGS):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_PRIORITY):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_HEADERS):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PUSH_PROMISE):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_DATA):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PING):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_SETTINGS):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_RST_STREAM):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_RST_STREAM):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PRIORITY):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN,
ConnectionInputs.RECV_ALTERNATIVE_SERVICE):
(None, ConnectionState.CLIENT_OPEN),
# State: open, server side.
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_HEADERS):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PUSH_PROMISE):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_DATA):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_WINDOW_UPDATE):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PING):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_SETTINGS):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PRIORITY):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_HEADERS):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_DATA):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PING):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_SETTINGS):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PRIORITY):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_RST_STREAM):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_RST_STREAM):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN,
ConnectionInputs.SEND_ALTERNATIVE_SERVICE):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN,
ConnectionInputs.RECV_ALTERNATIVE_SERVICE):
(None, ConnectionState.SERVER_OPEN),
# State: closed
(ConnectionState.CLOSED, ConnectionInputs.SEND_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.CLOSED, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
}
def __init__(self):
self.state = ConnectionState.IDLE
def process_input(self, input_):
"""
Process a specific input in the state machine.
"""
if not isinstance(input_, ConnectionInputs):
raise ValueError("Input must be an instance of ConnectionInputs")
try:
func, target_state = self._transitions[(self.state, input_)]
except KeyError:
old_state = self.state
self.state = ConnectionState.CLOSED
raise ProtocolError(
"Invalid input %s in state %s" % (input_, old_state)
)
else:
self.state = target_state
if func is not None: # pragma: no cover
return func()
return []
class H2Connection:
"""
A low-level HTTP/2 connection object. This handles building and receiving
frames and maintains both connection and per-stream state for all streams
on this connection.
This wraps a HTTP/2 Connection state machine implementation, ensuring that
frames can only be sent/received when the connection is in a valid state.
It also builds stream state machines on demand to ensure that the
constraints of those state machines are met as well. Attempts to create
frames that cannot be sent will raise a ``ProtocolError``.
.. versionchanged:: 2.3.0
Added the ``header_encoding`` keyword argument.
.. versionchanged:: 2.5.0
Added the ``config`` keyword argument. Deprecated the ``client_side``
and ``header_encoding`` parameters.
.. versionchanged:: 3.0.0
Removed deprecated parameters and properties.
:param config: The configuration for the HTTP/2 connection.
.. versionadded:: 2.5.0
:type config: :class:`H2Configuration <h2.config.H2Configuration>`
"""
# The initial maximum outbound frame size. This can be changed by receiving
# a settings frame.
DEFAULT_MAX_OUTBOUND_FRAME_SIZE = 65535
# The initial maximum inbound frame size. This is somewhat arbitrarily
# chosen.
DEFAULT_MAX_INBOUND_FRAME_SIZE = 2**24
# The highest acceptable stream ID.
HIGHEST_ALLOWED_STREAM_ID = 2**31 - 1
# The largest acceptable window increment.
MAX_WINDOW_INCREMENT = 2**31 - 1
# The initial default value of SETTINGS_MAX_HEADER_LIST_SIZE.
DEFAULT_MAX_HEADER_LIST_SIZE = 2**16
# Keep in memory limited amount of results for streams closes
MAX_CLOSED_STREAMS = 2**16
def __init__(self, config=None):
self.state_machine = H2ConnectionStateMachine()
self.streams = {}
self.highest_inbound_stream_id = 0
self.highest_outbound_stream_id = 0
self.encoder = Encoder()
self.decoder = Decoder()
# This won't always actually do anything: for versions of HPACK older
# than 2.3.0 it does nothing. However, we have to try!
self.decoder.max_header_list_size = self.DEFAULT_MAX_HEADER_LIST_SIZE
#: The configuration for this HTTP/2 connection object.
#:
#: .. versionadded:: 2.5.0
self.config = config
if self.config is None:
self.config = H2Configuration(
client_side=True,
)
# Objects that store settings, including defaults.
#
# We set the MAX_CONCURRENT_STREAMS value to 100 because its default is
# unbounded, and that's a dangerous default because it allows
# essentially unbounded resources to be allocated regardless of how
# they will be used. 100 should be suitable for the average
# application. This default obviously does not apply to the remote
# peer's settings: the remote peer controls them!
#
# We also set MAX_HEADER_LIST_SIZE to a reasonable value. This is to
# advertise our defence against CVE-2016-6581. However, not all
# versions of HPACK will let us do it. That's ok: we should at least
# suggest that we're not vulnerable.
self.local_settings = Settings(
client=self.config.client_side,
initial_values={
SettingCodes.MAX_CONCURRENT_STREAMS: 100,
SettingCodes.MAX_HEADER_LIST_SIZE:
self.DEFAULT_MAX_HEADER_LIST_SIZE,
}
)
self.remote_settings = Settings(client=not self.config.client_side)
# The current value of the connection flow control windows on the
# connection.
self.outbound_flow_control_window = (
self.remote_settings.initial_window_size
)
#: The maximum size of a frame that can be emitted by this peer, in
#: bytes.
self.max_outbound_frame_size = self.remote_settings.max_frame_size
#: The maximum size of a frame that can be received by this peer, in
#: bytes.
self.max_inbound_frame_size = self.local_settings.max_frame_size
# Buffer for incoming data.
self.incoming_buffer = FrameBuffer(server=not self.config.client_side)
# A private variable to store a sequence of received header frames
# until completion.
self._header_frames = []
# Data that needs to be sent.
self._data_to_send = bytearray()
# Keeps track of how streams are closed.
# Used to ensure that we don't blow up in the face of frames that were
# in flight when a RST_STREAM was sent.
# Also used to determine whether we should consider a frame received
# while a stream is closed as either a stream error or a connection
# error.
self._closed_streams = SizeLimitDict(
size_limit=self.MAX_CLOSED_STREAMS
)
# The flow control window manager for the connection.
self._inbound_flow_control_window_manager = WindowManager(
max_window_size=self.local_settings.initial_window_size
)
# When in doubt use dict-dispatch.
self._frame_dispatch_table = {
HeadersFrame: self._receive_headers_frame,
PushPromiseFrame: self._receive_push_promise_frame,
SettingsFrame: self._receive_settings_frame,
DataFrame: self._receive_data_frame,
WindowUpdateFrame: self._receive_window_update_frame,
PingFrame: self._receive_ping_frame,
RstStreamFrame: self._receive_rst_stream_frame,
PriorityFrame: self._receive_priority_frame,
GoAwayFrame: self._receive_goaway_frame,
ContinuationFrame: self._receive_naked_continuation,
AltSvcFrame: self._receive_alt_svc_frame,
ExtensionFrame: self._receive_unknown_frame
}
def _prepare_for_sending(self, frames):
if not frames:
return
self._data_to_send += b''.join(f.serialize() for f in frames)
assert all(f.body_len <= self.max_outbound_frame_size for f in frames)
def _open_streams(self, remainder):
"""
A common method of counting number of open streams. Returns the number
of streams that are open *and* that have (stream ID % 2) == remainder.
While it iterates, also deletes any closed streams.
"""
count = 0
to_delete = []
for stream_id, stream in self.streams.items():
if stream.open and (stream_id % 2 == remainder):
count += 1
elif stream.closed:
to_delete.append(stream_id)
for stream_id in to_delete:
stream = self.streams.pop(stream_id)
self._closed_streams[stream_id] = stream.closed_by
return count
@property
def open_outbound_streams(self):
"""
The current number of open outbound streams.
"""
outbound_numbers = int(self.config.client_side)
return self._open_streams(outbound_numbers)
@property
def open_inbound_streams(self):
"""
The current number of open inbound streams.
"""
inbound_numbers = int(not self.config.client_side)
return self._open_streams(inbound_numbers)
@property
def inbound_flow_control_window(self):
"""
The size of the inbound flow control window for the connection. This is
rarely publicly useful: instead, use :meth:`remote_flow_control_window
<h2.connection.H2Connection.remote_flow_control_window>`. This
shortcut is largely present to provide a shortcut to this data.
"""
return self._inbound_flow_control_window_manager.current_window_size
def _begin_new_stream(self, stream_id, allowed_ids):
"""
Initiate a new stream.
.. versionchanged:: 2.0.0
Removed this function from the public API.
:param stream_id: The ID of the stream to open.
:param allowed_ids: What kind of stream ID is allowed.
"""
self.config.logger.debug(
"Attempting to initiate stream ID %d", stream_id
)
outbound = self._stream_id_is_outbound(stream_id)
highest_stream_id = (
self.highest_outbound_stream_id if outbound else
self.highest_inbound_stream_id
)
if stream_id <= highest_stream_id:
raise StreamIDTooLowError(stream_id, highest_stream_id)
if (stream_id % 2) != int(allowed_ids):
raise ProtocolError(
"Invalid stream ID for peer."
)
s = H2Stream(
stream_id,
config=self.config,
inbound_window_size=self.local_settings.initial_window_size,
outbound_window_size=self.remote_settings.initial_window_size
)
self.config.logger.debug("Stream ID %d created", stream_id)
s.max_outbound_frame_size = self.max_outbound_frame_size
self.streams[stream_id] = s
self.config.logger.debug("Current streams: %s", self.streams.keys())
if outbound:
self.highest_outbound_stream_id = stream_id
else:
self.highest_inbound_stream_id = stream_id
return s
def initiate_connection(self):
"""
Provides any data that needs to be sent at the start of the connection.
Must be called for both clients and servers.
"""
self.config.logger.debug("Initializing connection")
self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS)
if self.config.client_side:
preamble = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
else:
preamble = b''
f = SettingsFrame(0)
for setting, value in self.local_settings.items():
f.settings[setting] = value
self.config.logger.debug(
"Send Settings frame: %s", self.local_settings
)
self._data_to_send += preamble + f.serialize()
def initiate_upgrade_connection(self, settings_header=None):
"""
Call to initialise the connection object for use with an upgraded
HTTP/2 connection (i.e. a connection negotiated using the
``Upgrade: h2c`` HTTP header).
This method differs from :meth:`initiate_connection
<h2.connection.H2Connection.initiate_connection>` in several ways.
Firstly, it handles the additional SETTINGS frame that is sent in the
``HTTP2-Settings`` header field. When called on a client connection,
this method will return a bytestring that the caller can put in the
``HTTP2-Settings`` field they send on their initial request. When
called on a server connection, the user **must** provide the value they
received from the client in the ``HTTP2-Settings`` header field to the
``settings_header`` argument, which will be used appropriately.
Additionally, this method sets up stream 1 in a half-closed state
appropriate for this side of the connection, to reflect the fact that
the request is already complete.
Finally, this method also prepares the appropriate preamble to be sent
after the upgrade.
.. versionadded:: 2.3.0
:param settings_header: (optional, server-only): The value of the
``HTTP2-Settings`` header field received from the client.
:type settings_header: ``bytes``
:returns: For clients, a bytestring to put in the ``HTTP2-Settings``.
For servers, returns nothing.
:rtype: ``bytes`` or ``None``
"""
self.config.logger.debug(
"Upgrade connection. Current settings: %s", self.local_settings
)
frame_data = None
# Begin by getting the preamble in place.
self.initiate_connection()
if self.config.client_side:
f = SettingsFrame(0)
for setting, value in self.local_settings.items():
f.settings[setting] = value
frame_data = f.serialize_body()
frame_data = base64.urlsafe_b64encode(frame_data)
elif settings_header:
# We have a settings header from the client. This needs to be
# applied, but we want to throw away the ACK. We do this by
# inserting the data into a Settings frame and then passing it to
# the state machine, but ignoring the return value.
settings_header = base64.urlsafe_b64decode(settings_header)
f = SettingsFrame(0)
f.parse_body(settings_header)
self._receive_settings_frame(f)
# Set up appropriate state. Stream 1 in a half-closed state:
# half-closed(local) for clients, half-closed(remote) for servers.
# Additionally, we need to set up the Connection state machine.
connection_input = (
ConnectionInputs.SEND_HEADERS if self.config.client_side
else ConnectionInputs.RECV_HEADERS
)
self.config.logger.debug("Process input %s", connection_input)
self.state_machine.process_input(connection_input)
# Set up stream 1.
self._begin_new_stream(stream_id=1, allowed_ids=AllowedStreamIDs.ODD)
self.streams[1].upgrade(self.config.client_side)
return frame_data
def _get_or_create_stream(self, stream_id, allowed_ids):
"""
Gets a stream by its stream ID. Will create one if one does not already
exist. Use allowed_ids to circumvent the usual stream ID rules for
clients and servers.
.. versionchanged:: 2.0.0
Removed this function from the public API.
"""
try:
return self.streams[stream_id]
except KeyError:
return self._begin_new_stream(stream_id, allowed_ids)
def _get_stream_by_id(self, stream_id):
"""
Gets a stream by its stream ID. Raises NoSuchStreamError if the stream
ID does not correspond to a known stream and is higher than the current
maximum: raises if it is lower than the current maximum.
.. versionchanged:: 2.0.0
Removed this function from the public API.
"""
try:
return self.streams[stream_id]
except KeyError:
outbound = self._stream_id_is_outbound(stream_id)
highest_stream_id = (
self.highest_outbound_stream_id if outbound else
self.highest_inbound_stream_id
)
if stream_id > highest_stream_id:
raise NoSuchStreamError(stream_id)
else:
raise StreamClosedError(stream_id)
def get_next_available_stream_id(self):
"""
Returns an integer suitable for use as the stream ID for the next
stream created by this endpoint. For server endpoints, this stream ID
will be even. For client endpoints, this stream ID will be odd. If no
stream IDs are available, raises :class:`NoAvailableStreamIDError
<h2.exceptions.NoAvailableStreamIDError>`.
.. warning:: The return value from this function does not change until
the stream ID has actually been used by sending or pushing
headers on that stream. For that reason, it should be
called as close as possible to the actual use of the
stream ID.
.. versionadded:: 2.0.0
:raises: :class:`NoAvailableStreamIDError
<h2.exceptions.NoAvailableStreamIDError>`
:returns: The next free stream ID this peer can use to initiate a
stream.
:rtype: ``int``
"""
# No streams have been opened yet, so return the lowest allowed stream
# ID.
if not self.highest_outbound_stream_id:
next_stream_id = 1 if self.config.client_side else 2
else:
next_stream_id = self.highest_outbound_stream_id + 2
self.config.logger.debug(
"Next available stream ID %d", next_stream_id
)
if next_stream_id > self.HIGHEST_ALLOWED_STREAM_ID:
raise NoAvailableStreamIDError("Exhausted allowed stream IDs")
return next_stream_id
def send_headers(self, stream_id, headers, end_stream=False,
priority_weight=None, priority_depends_on=None,
priority_exclusive=None):
"""
Send headers on a given stream.
This function can be used to send request or response headers: the kind
that are sent depends on whether this connection has been opened as a
client or server connection, and whether the stream was opened by the
remote peer or not.
If this is a client connection, calling ``send_headers`` will send the
headers as a request. It will also implicitly open the stream being
used. If this is a client connection and ``send_headers`` has *already*
been called, this will send trailers instead.
If this is a server connection, calling ``send_headers`` will send the
headers as a response. It is a protocol error for a server to open a
stream by sending headers. If this is a server connection and
``send_headers`` has *already* been called, this will send trailers
instead.
When acting as a server, you may call ``send_headers`` any number of
times allowed by the following rules, in this order:
- zero or more times with ``(':status', '1XX')`` (where ``1XX`` is a
placeholder for any 100-level status code).
- once with any other status header.
- zero or one time for trailers.
That is, you are allowed to send as many informational responses as you
like, followed by one complete response and zero or one HTTP trailer
blocks.
Clients may send one or two header blocks: one request block, and
optionally one trailer block.
If it is important to send HPACK "never indexed" header fields (as
defined in `RFC 7451 Section 7.1.3
<https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
instead provide headers using the HPACK library's :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
<hpack:hpack.NeverIndexedHeaderTuple>` objects.
This method also allows users to prioritize the stream immediately,
by sending priority information on the HEADERS frame directly. To do
this, any one of ``priority_weight``, ``priority_depends_on``, or
``priority_exclusive`` must be set to a value that is not ``None``. For
more information on the priority fields, see :meth:`prioritize
<h2.connection.H2Connection.prioritize>`.
.. warning:: In HTTP/2, it is mandatory that all the HTTP/2 special
headers (that is, ones whose header keys begin with ``:``) appear
at the start of the header block, before any normal headers.
.. versionchanged:: 2.3.0
Added support for using :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` objects to store headers.
.. versionchanged:: 2.4.0
Added the ability to provide priority keyword arguments:
``priority_weight``, ``priority_depends_on``, and
``priority_exclusive``.
:param stream_id: The stream ID to send the headers on. If this stream
does not currently exist, it will be created.
:type stream_id: ``int``
:param headers: The request/response headers to send.
:type headers: An iterable of two tuples of bytestrings or
:class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
:param end_stream: Whether this headers frame should end the stream
immediately (that is, whether no more data will be sent after this
frame). Defaults to ``False``.
:type end_stream: ``bool``
:param priority_weight: Sets the priority weight of the stream. See
:meth:`prioritize <h2.connection.H2Connection.prioritize>` for more
about how this field works. Defaults to ``None``, which means that
no priority information will be sent.
:type priority_weight: ``int`` or ``None``
:param priority_depends_on: Sets which stream this one depends on for
priority purposes. See :meth:`prioritize
<h2.connection.H2Connection.prioritize>` for more about how this
field works. Defaults to ``None``, which means that no priority
information will be sent.
:type priority_depends_on: ``int`` or ``None``
:param priority_exclusive: Sets whether this stream exclusively depends
on the stream given in ``priority_depends_on`` for priority
purposes. See :meth:`prioritize
<h2.connection.H2Connection.prioritize>` for more about how this
field workds. Defaults to ``None``, which means that no priority
information will be sent.
:type priority_depends_on: ``bool`` or ``None``
:returns: Nothing
"""
self.config.logger.debug(
"Send headers on stream ID %d", stream_id
)
# Check we can open the stream.
if stream_id not in self.streams:
max_open_streams = self.remote_settings.max_concurrent_streams
if (self.open_outbound_streams + 1) > max_open_streams:
raise TooManyStreamsError(
"Max outbound streams is %d, %d open" %
(max_open_streams, self.open_outbound_streams)
)
self.state_machine.process_input(ConnectionInputs.SEND_HEADERS)
stream = self._get_or_create_stream(
stream_id, AllowedStreamIDs(self.config.client_side)
)
frames = stream.send_headers(
headers, self.encoder, end_stream
)
# We may need to send priority information.
priority_present = (
(priority_weight is not None) or
(priority_depends_on is not None) or
(priority_exclusive is not None)
)
if priority_present:
if not self.config.client_side:
raise RFC1122Error("Servers SHOULD NOT prioritize streams.")
headers_frame = frames[0]
headers_frame.flags.add('PRIORITY')
frames[0] = _add_frame_priority(
headers_frame,
priority_weight,
priority_depends_on,
priority_exclusive
)
self._prepare_for_sending(frames)
def send_data(self, stream_id, data, end_stream=False, pad_length=None):
"""
Send data on a given stream.
This method does no breaking up of data: if the data is larger than the
value returned by :meth:`local_flow_control_window
<h2.connection.H2Connection.local_flow_control_window>` for this stream
then a :class:`FlowControlError <h2.exceptions.FlowControlError>` will
be raised. If the data is larger than :data:`max_outbound_frame_size
<h2.connection.H2Connection.max_outbound_frame_size>` then a
:class:`FrameTooLargeError <h2.exceptions.FrameTooLargeError>` will be
raised.
h2 does this to avoid buffering the data internally. If the user
has more data to send than h2 will allow, consider breaking it up
and buffering it externally.
:param stream_id: The ID of the stream on which to send the data.
:type stream_id: ``int``
:param data: The data to send on the stream.
:type data: ``bytes``
:param end_stream: (optional) Whether this is the last data to be sent
on the stream. Defaults to ``False``.
:type end_stream: ``bool``
:param pad_length: (optional) Length of the padding to apply to the
data frame. Defaults to ``None`` for no use of padding. Note that
a value of ``0`` results in padding of length ``0``
(with the "padding" flag set on the frame).
.. versionadded:: 2.6.0
:type pad_length: ``int``
:returns: Nothing
"""
self.config.logger.debug(
"Send data on stream ID %d with len %d", stream_id, len(data)
)
frame_size = len(data)
if pad_length is not None:
if not isinstance(pad_length, int):
raise TypeError("pad_length must be an int")
if pad_length < 0 or pad_length > 255:
raise ValueError("pad_length must be within range: [0, 255]")
# Account for padding bytes plus the 1-byte padding length field.
frame_size += pad_length + 1
self.config.logger.debug(
"Frame size on stream ID %d is %d", stream_id, frame_size
)
if frame_size > self.local_flow_control_window(stream_id):
raise FlowControlError(
"Cannot send %d bytes, flow control window is %d." %
(frame_size, self.local_flow_control_window(stream_id))
)
elif frame_size > self.max_outbound_frame_size:
raise FrameTooLargeError(
"Cannot send frame size %d, max frame size is %d" %
(frame_size, self.max_outbound_frame_size)
)
self.state_machine.process_input(ConnectionInputs.SEND_DATA)
frames = self.streams[stream_id].send_data(
data, end_stream, pad_length=pad_length
)
self._prepare_for_sending(frames)
self.outbound_flow_control_window -= frame_size
self.config.logger.debug(
"Outbound flow control window size is %d",
self.outbound_flow_control_window
)
assert self.outbound_flow_control_window >= 0
def end_stream(self, stream_id):
"""
Cleanly end a given stream.
This method ends a stream by sending an empty DATA frame on that stream
with the ``END_STREAM`` flag set.
:param stream_id: The ID of the stream to end.
:type stream_id: ``int``
:returns: Nothing
"""
self.config.logger.debug("End stream ID %d", stream_id)
self.state_machine.process_input(ConnectionInputs.SEND_DATA)
frames = self.streams[stream_id].end_stream()
self._prepare_for_sending(frames)
def increment_flow_control_window(self, increment, stream_id=None):
"""
Increment a flow control window, optionally for a single stream. Allows
the remote peer to send more data.
.. versionchanged:: 2.0.0
Rejects attempts to increment the flow control window by out of
range values with a ``ValueError``.
:param increment: The amount to increment the flow control window by.
:type increment: ``int``
:param stream_id: (optional) The ID of the stream that should have its
flow control window opened. If not present or ``None``, the
connection flow control window will be opened instead.
:type stream_id: ``int`` or ``None``
:returns: Nothing
:raises: ``ValueError``
"""
if not (1 <= increment <= self.MAX_WINDOW_INCREMENT):
raise ValueError(
"Flow control increment must be between 1 and %d" %
self.MAX_WINDOW_INCREMENT
)
self.state_machine.process_input(ConnectionInputs.SEND_WINDOW_UPDATE)
if stream_id is not None:
stream = self.streams[stream_id]
frames = stream.increase_flow_control_window(
increment
)
self.config.logger.debug(
"Increase stream ID %d flow control window by %d",
stream_id, increment
)
else:
self._inbound_flow_control_window_manager.window_opened(increment)
f = WindowUpdateFrame(0)
f.window_increment = increment
frames = [f]
self.config.logger.debug(
"Increase connection flow control window by %d", increment
)
self._prepare_for_sending(frames)
def push_stream(self, stream_id, promised_stream_id, request_headers):
"""
Push a response to the client by sending a PUSH_PROMISE frame.
If it is important to send HPACK "never indexed" header fields (as
defined in `RFC 7451 Section 7.1.3
<https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
instead provide headers using the HPACK library's :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
<hpack:hpack.NeverIndexedHeaderTuple>` objects.
:param stream_id: The ID of the stream that this push is a response to.
:type stream_id: ``int``
:param promised_stream_id: The ID of the stream that the pushed
response will be sent on.
:type promised_stream_id: ``int``
:param request_headers: The headers of the request that the pushed
response will be responding to.
:type request_headers: An iterable of two tuples of bytestrings or
:class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
:returns: Nothing
"""
self.config.logger.debug(
"Send Push Promise frame on stream ID %d", stream_id
)
if not self.remote_settings.enable_push:
raise ProtocolError("Remote peer has disabled stream push")
self.state_machine.process_input(ConnectionInputs.SEND_PUSH_PROMISE)
stream = self._get_stream_by_id(stream_id)
# We need to prevent users pushing streams in response to streams that
# they themselves have already pushed: see #163 and RFC 7540 § 6.6. The
# easiest way to do that is to assert that the stream_id is not even:
# this shortcut works because only servers can push and the state
# machine will enforce this.
if (stream_id % 2) == 0:
raise ProtocolError("Cannot recursively push streams.")
new_stream = self._begin_new_stream(
promised_stream_id, AllowedStreamIDs.EVEN
)
self.streams[promised_stream_id] = new_stream
frames = stream.push_stream_in_band(
promised_stream_id, request_headers, self.encoder
)
new_frames = new_stream.locally_pushed()
self._prepare_for_sending(frames + new_frames)
def ping(self, opaque_data):
"""
Send a PING frame.
:param opaque_data: A bytestring of length 8 that will be sent in the
PING frame.
:returns: Nothing
"""
self.config.logger.debug("Send Ping frame")
if not isinstance(opaque_data, bytes) or len(opaque_data) != 8:
raise ValueError("Invalid value for ping data: %r" % opaque_data)
self.state_machine.process_input(ConnectionInputs.SEND_PING)
f = PingFrame(0)
f.opaque_data = opaque_data
self._prepare_for_sending([f])