Debian Codegraph @

lib/Protocol/HTTP2/Connection.pm

raw
1 package Protocol::HTTP2::Connection;
2 use strict;
3 use warnings;
4 use Protocol::HTTP2::Constants
5 qw(const_name :frame_types :errors :settings :flags :states
6 :limits :endpoints);
7 use Protocol::HTTP2::HeaderCompression qw(headers_encode);
8 use Protocol::HTTP2::Frame;
9 use Protocol::HTTP2::Stream;
10 use Protocol::HTTP2::Upgrade;
11 use Protocol::HTTP2::Trace qw(tracer);
12
13 # Mixin
14 our @ISA =
15 qw(Protocol::HTTP2::Frame Protocol::HTTP2::Stream Protocol::HTTP2::Upgrade);
16
17 # Default settings
18 my %default_settings = (
19 &SETTINGS_HEADER_TABLE_SIZE => DEFAULT_HEADER_TABLE_SIZE,
20 &SETTINGS_ENABLE_PUSH => DEFAULT_ENABLE_PUSH,
21 &SETTINGS_MAX_CONCURRENT_STREAMS => DEFAULT_MAX_CONCURRENT_STREAMS,
22 &SETTINGS_INITIAL_WINDOW_SIZE => DEFAULT_INITIAL_WINDOW_SIZE,
23 &SETTINGS_MAX_FRAME_SIZE => DEFAULT_MAX_FRAME_SIZE,
24 &SETTINGS_MAX_HEADER_LIST_SIZE => DEFAULT_MAX_HEADER_LIST_SIZE,
25 );
26
27 sub new {
28 my ( $class, $type, %opts ) = @_;
29 my $self = bless {
30 type => $type,
31
32 streams => {},
33 closed_streams => [],
34 max_closed_streams => PH2_MAX_CLOSED_STREAMS,
35
36 last_stream => $type == CLIENT ? 1 : 2,
37 last_peer_stream => 0,
38 active_peer_streams => 0,
39
40 encode_ctx => {
41
42 # HPACK. Header Table
43 header_table => [],
44
45 # HPACK. Header Table size
46 ht_size => 0,
47 max_ht_size => DEFAULT_HEADER_TABLE_SIZE,
48
49 settings => {%default_settings},
50
51 },
52
53 decode_ctx => {
54
55 # HPACK. Header Table
56 header_table => [],
57
58 # HPACK. Header Table size
59 ht_size => 0,
60 max_ht_size => DEFAULT_HEADER_TABLE_SIZE,
61
62 # HPACK. Emitted headers
63 emitted_headers => [],
64
65 # last frame
66 frame => {},
67
68 settings => {%default_settings},
69 },
70
71 # Current error
72 error => 0,
73
74 # Output frames queue
75 queue => [],
76
77 # Connection must be shutdown
78 shutdown => 0,
79
80 # issued GOAWAY: no new streams on this connection
81 goaway => 0,
82
83 # get preface
84 preface => 0,
85
86 # perform upgrade
87 upgrade => 0,
88
89 # flow control
90 fcw_send => DEFAULT_INITIAL_WINDOW_SIZE,
91 fcw_recv => DEFAULT_INITIAL_WINDOW_SIZE,
92
93 # stream where expected CONTINUATION frames
94 pending_stream => undef,
95
96 }, $class;
97
98 for (qw(on_change_state on_new_peer_stream on_error upgrade max_closed_streams)) {
99 $self->{$_} = $opts{$_} if exists $opts{$_};
100 }
101
102 if ( exists $opts{settings} ) {
103 for ( keys %{ $opts{settings} } ) {
104 $self->{decode_ctx}->{settings}->{$_} = $opts{settings}{$_};
105 }
106 }
107
108 # Sync decode context max_ht_size
109 $self->{decode_ctx}->{max_ht_size} =
110 $self->{decode_ctx}->{settings}->{&SETTINGS_HEADER_TABLE_SIZE};
111
112 $self;
113 }
114
115 sub decode_context {
116 shift->{decode_ctx};
117 }
118
119 sub encode_context {
120 shift->{encode_ctx};
121 }
122
123 sub pending_stream {
124 shift->{pending_stream};
125 }
126
127 sub dequeue {
128 my $self = shift;
129 shift @{ $self->{queue} };
130 }
131
132 sub enqueue_raw {
133 my $self = shift;
134 push @{ $self->{queue} }, @_;
135 }
136
137 sub enqueue {
138 my $self = shift;
139 while ( my ( $type, $flags, $stream_id, $data_ref ) = splice( @_, 0, 4 ) ) {
140 push @{ $self->{queue} },
141 $self->frame_encode( $type, $flags, $stream_id, $data_ref );
142 $self->state_machine( 'send', $type, $flags, $stream_id );
143 }
144 }
145
146 sub enqueue_first {
147 my $self = shift;
148 my $i = 0;
149 for ( 0 .. $#{ $self->{queue} } ) {
150 my $type =
151 ( $self->frame_header_decode( \$self->{queue}->[$_], 0 ) )[1];
152 last if $type != CONTINUATION && $type != PING;
153 $i++;
154 }
155 while ( my ( $type, $flags, $stream_id, $data_ref ) = splice( @_, 0, 4 ) ) {
156 splice @{ $self->{queue} }, $i++, 0,
157 $self->frame_encode( $type, $flags, $stream_id, $data_ref );
158 $self->state_machine( 'send', $type, $flags, $stream_id );
159 }
160 }
161
162 sub finish {
163 my $self = shift;
164 $self->enqueue( GOAWAY, 0, 0,
165 [ $self->{last_peer_stream}, $self->{error} ] )
166 unless $self->shutdown;
167 $self->shutdown(1);
168 }
169
170 sub shutdown {
171 my $self = shift;
172 $self->{shutdown} = shift if @_;
173 $self->{shutdown};
174 }
175
176 sub goaway {
177 my $self = shift;
178 $self->{goaway} = shift if @_;
179 $self->{goaway};
180 }
181
182 sub preface {
183 my $self = shift;
184 $self->{preface} = shift if @_;
185 $self->{preface};
186 }
187
188 sub upgrade {
189 my $self = shift;
190 $self->{upgrade} = shift if @_;
191 $self->{upgrade};
192 }
193
194 sub state_machine {
195 my ( $self, $act, $type, $flags, $stream_id ) = @_;
196
197 return
198 if $stream_id == 0
199 || $type == SETTINGS
200 || $type == GOAWAY
201 || $self->upgrade
202 || !$self->preface;
203
204 my $promised_sid = $self->stream_promised_sid($stream_id);
205
206 my $prev_state = $self->{streams}->{ $promised_sid || $stream_id }->{state};
207
208 # REFUSED_STREAM error
209 return if !defined $prev_state && $type == RST_STREAM && $act eq 'send';
210
211 # Direction server->client
212 my $srv2cln = ( $self->{type} == SERVER && $act eq 'send' )
213 || ( $self->{type} == CLIENT && $act eq 'recv' );
214
215 # Direction client->server
216 my $cln2srv = ( $self->{type} == SERVER && $act eq 'recv' )
217 || ( $self->{type} == CLIENT && $act eq 'send' );
218
219 # Do we expect CONTINUATION after this frame?
220 my $pending = ( $type == HEADERS || $type == PUSH_PROMISE )
221 && !( $flags & END_HEADERS );
222
223 #tracer->debug(
224 # sprintf "\e[0;31mStream state: frame %s is %s%s on %s stream %i\e[m\n",
225 # const_name( "frame_types", $type ),
226 # $act,
227 # $pending ? "*" : "",
228 # const_name( "states", $prev_state ),
229 # $promised_sid || $stream_id,
230 #);
231
232 # Wait until all CONTINUATION frames arrive
233 if ( my $ps = $self->stream_pending_state($stream_id) ) {
234 if ( $type != CONTINUATION ) {
235 tracer->error(
236 sprintf "invalid frame type %s. Expected CONTINUATION frame\n",
237 const_name( "frame_types", $type )
238 );
239 $self->error(PROTOCOL_ERROR);
240 }
241 elsif ( $flags & END_HEADERS ) {
242 $self->stream_promised_sid( $stream_id, undef ) if $promised_sid;
243 $self->stream_pending_state( $promised_sid || $stream_id, undef );
244 $self->stream_state( $promised_sid || $stream_id, $ps );
245 }
246 }
247
248 # Unexpected CONTINUATION frame
249 elsif ( $type == CONTINUATION ) {
250 tracer->error("Unexpected CONTINUATION frame\n");
251 $self->error(PROTOCOL_ERROR);
252 }
253
254 # State machine
255 # IDLE
256 elsif ( $prev_state == IDLE ) {
257 if ( $type == HEADERS && $cln2srv ) {
258 $self->stream_state( $stream_id,
259 ( $flags & END_STREAM ) ? HALF_CLOSED : OPEN, $pending );
260 }
261 elsif ( $type == PUSH_PROMISE && $srv2cln ) {
262 $self->stream_state( $promised_sid, RESERVED, $pending );
263 $self->stream_promised_sid( $stream_id, undef )
264 if $flags & END_HEADERS;
265 }
266
267 # first frame in stream is invalid, so state is yet IDLE
268 elsif ( $type == RST_STREAM && $act eq 'send' ) {
269 tracer->notice('send RST_STREAM on IDLE state. possible bug?');
270 $self->stream_state( $stream_id, CLOSED );
271 }
272 elsif ( $type != PRIORITY ) {
273 tracer->error(
274 sprintf "invalid frame type %s for current stream state %s\n",
275 const_name( "frame_types", $type ),
276 const_name( "states", $prev_state )
277 );
278 $self->error(PROTOCOL_ERROR);
279 }
280 }
281
282 # OPEN
283 elsif ( $prev_state == OPEN ) {
284 if ( ( $flags & END_STREAM )
285 && ( $type == DATA || $type == HEADERS ) )
286 {
287 $self->stream_state( $stream_id, HALF_CLOSED, $pending );
288 }
289 elsif ( $type == RST_STREAM ) {
290 $self->stream_state( $stream_id, CLOSED );
291 }
292 elsif ($type == HEADERS
293 && !$pending
294 && $self->stream_trailer($stream_id) )
295 {
296 tracer->error("expected END_STREAM flag for trailer HEADERS frame");
297 $self->error(PROTOCOL_ERROR);
298 }
299 }
300
301 # RESERVED (local/remote)
302 elsif ( $prev_state == RESERVED ) {
303 if ( $type == RST_STREAM ) {
304 $self->stream_state( $stream_id, CLOSED );
305 }
306 elsif ( $type == HEADERS && $srv2cln ) {
307 $self->stream_state( $stream_id,
308 ( $flags & END_STREAM ) ? CLOSED : HALF_CLOSED, $pending );
309 }
310 elsif ( $type != PRIORITY && $cln2srv ) {
311 tracer->error("invalid frame $type for state RESERVED");
312 $self->error(PROTOCOL_ERROR);
313 }
314 }
315
316 # HALF_CLOSED (local/remote)
317 elsif ( $prev_state == HALF_CLOSED ) {
318 if ( ( $type == RST_STREAM )
319 || ( ( $flags & END_STREAM ) && $srv2cln ) )
320 {
321 $self->stream_state( $stream_id, CLOSED, $pending );
322 }
323 elsif ( ( !grep { $type == $_ } ( WINDOW_UPDATE, PRIORITY ) )
324 && $cln2srv )
325 {
326 tracer->error( sprintf "invalid frame %s for state HALF CLOSED\n",
327 const_name( "frame_types", $type ) );
328 $self->error(PROTOCOL_ERROR);
329 }
330 }
331
332 # CLOSED
333 elsif ( $prev_state == CLOSED ) {
334 if ( $type != PRIORITY && ( $type != WINDOW_UPDATE && $cln2srv ) ) {
335
336 tracer->error("stream is closed\n");
337 $self->error(STREAM_CLOSED);
338 }
339 }
340 else {
341 tracer->error("oops!\n");
342 $self->error(INTERNAL_ERROR);
343 }
344 }
345
346 # TODO: move this to some other module
347 sub send_headers {
348 my ( $self, $stream_id, $headers, $end ) = @_;
349 my $max_size = $self->enc_setting(SETTINGS_MAX_FRAME_SIZE);
350
351 my $header_block = headers_encode( $self->encode_context, $headers );
352
353 my $flags = $end ? END_STREAM : 0;
354 $flags |= END_HEADERS if length($header_block) <= $max_size;
355
356 $self->enqueue( HEADERS, $flags, $stream_id,
357 { hblock => \substr( $header_block, 0, $max_size, '' ) } );
358 while ( length($header_block) > 0 ) {
359 my $flags = length($header_block) <= $max_size ? END_HEADERS : 0;
360 $self->enqueue( CONTINUATION, $flags,
361 $stream_id, \substr( $header_block, 0, $max_size, '' ) );
362 }
363 }
364
365 sub send_pp_headers {
366 my ( $self, $stream_id, $promised_id, $headers ) = @_;
367 my $max_size = $self->enc_setting(SETTINGS_MAX_FRAME_SIZE);
368
369 my $header_block = headers_encode( $self->encode_context, $headers );
370
371 my $flags = length($header_block) <= $max_size ? END_HEADERS : 0;
372
373 $self->enqueue( PUSH_PROMISE, $flags, $stream_id,
374 [ $promised_id, \substr( $header_block, 0, $max_size - 4, '' ) ] );
375
376 while ( length($header_block) > 0 ) {
377 my $flags = length($header_block) <= $max_size ? END_HEADERS : 0;
378 $self->enqueue( CONTINUATION, $flags,
379 $stream_id, \substr( $header_block, 0, $max_size, '' ) );
380 }
381 }
382
383 sub send_data {
384 my ( $self, $stream_id, $chunk, $end ) = @_;
385 my $data = $self->stream_blocked_data($stream_id);
386 $data .= defined $chunk ? $chunk : '';
387 $self->stream_end( $stream_id, $end ) if defined $end;
388 $end = $self->stream_end($stream_id);
389
390 while (1) {
391 my $l = length($data);
392 my $size = $self->enc_setting(SETTINGS_MAX_FRAME_SIZE);
393 for ( $l, $self->fcw_send, $self->stream_fcw_send($stream_id) ) {
394 $size = $_ if $size > $_;
395 }
396
397 # Flow control
398 last if $l != 0 && $size <= 0;
399 $self->fcw_send( -$size );
400 $self->stream_fcw_send( $stream_id, -$size );
401
402 $self->enqueue(
403 DATA, $end && $l == $size ? END_STREAM : 0,
404 $stream_id, \substr( $data, 0, $size, '' )
405 );
406 last if $l == $size;
407 }
408 $self->stream_blocked_data( $stream_id, $data );
409 }
410
411 sub send_blocked {
412 my $self = shift;
413 for my $stream_id ( keys %{ $self->{streams} } ) {
414 $self->stream_send_blocked($stream_id);
415 }
416 }
417
418 sub error {
419 my $self = shift;
420 if ( @_ && !$self->{shutdown} ) {
421 $self->{error} = shift;
422 $self->{on_error}->( $self->{error} ) if exists $self->{on_error};
423 $self->finish;
424 }
425 $self->{error};
426 }
427
428 sub setting {
429 require Carp;
430 Carp::confess("setting is deprecated\n");
431 }
432
433 sub _setting {
434 my ( $ctx, $self, $setting ) = @_;
435 my $s = $self->{$ctx}->{settings};
436 return undef unless exists $s->{$setting};
437 $s->{$setting} = pop if @_ > 3;
438 $s->{$setting};
439 }
440
441 sub enc_setting {
442 _setting( 'encode_ctx', @_ );
443 }
444
445 sub dec_setting {
446 _setting( 'decode_ctx', @_ );
447 }
448
449 sub accept_settings {
450 my $self = shift;
451 $self->enqueue( SETTINGS, ACK, 0, {} );
452 }
453
454 # Flow control windown of connection
455 sub _fcw {
456 my $dir = shift;
457 my $self = shift;
458
459 if (@_) {
460 $self->{$dir} += shift;
461 tracer->debug( "$dir now is " . $self->{$dir} . "\n" );
462 }
463 $self->{$dir};
464 }
465
466 sub fcw_send {
467 _fcw( 'fcw_send', @_ );
468 }
469
470 sub fcw_recv {
471 _fcw( 'fcw_recv', @_ );
472 }
473
474 sub fcw_update {
475 my $self = shift;
476
477 # TODO: check size of data in memory
478 my $size = $self->dec_setting(SETTINGS_INITIAL_WINDOW_SIZE);
479 tracer->debug("update fcw recv of connection with $size b.\n");
480 $self->fcw_recv($size);
481 $self->enqueue( WINDOW_UPDATE, 0, 0, $size );
482 }
483
484 sub fcw_initial_change {
485 my ( $self, $size ) = @_;
486 my $prev_size = $self->enc_setting(SETTINGS_INITIAL_WINDOW_SIZE);
487 my $diff = $size - $prev_size;
488 tracer->debug(
489 "Change flow control window on not closed streams with diff $diff\n");
490 for my $stream_id ( keys %{ $self->{streams} } ) {
491 next if $self->stream_state($stream_id) == CLOSED;
492 $self->stream_fcw_send( $stream_id, $diff );
493 }
494 }
495
496 sub ack_ping {
497 my ( $self, $payload_ref ) = @_;
498 $self->enqueue_first( PING, ACK, 0, $payload_ref );
499 }
500
501 sub send_ping {
502 my ( $self, $payload ) = @_;
503 if ( !defined $payload ) {
504 $payload = pack "C*", map { rand(256) } 1 .. PING_PAYLOAD_SIZE;
505 }
506 elsif ( length($payload) != PING_PAYLOAD_SIZE ) {
507 $payload = sprintf "%*.*s",
508 -PING_PAYLOAD_SIZE(), PING_PAYLOAD_SIZE, $payload;
509 }
510 $self->enqueue( PING, 0, 0, \$payload );
511 }
512
513 1;