Async/WebSocket/Server/Connection.pm

filter: Statementstmt 33.3% 1 / 3 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 1 / 1 Podpod n/a totaltotal 50.0% 2 / 4 CC 1 SCAR 2.6
CC
1
Cov
33%
BEGIN
1.3
CRAP 1.3
« Async/WebSocket/Server.pm ↑ Summary Async.pm »
1 package Web::Async::WebSocket::Server::Connection;
2 0 ▶use Full::Class qw(:v1), extends => 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=2.6
3  
4 our $VERSION = '0.006'; ## VERSION
5 ## AUTHORITY
6  
7 use Web::Async::WebSocket::Frame;
8  
9 use List::Util qw(pairmap);
10 use Compress::Zlib;
11 use POSIX ();
12 use URI;
13 use URI::ws;
14 use Time::Moment;
15 use Digest::SHA qw(sha1);
16 use MIME::Base64 qw(encode_base64);
17 use Unicode::UTF8 qw(valid_utf8);
18  
19 # As defined in the RFC - it's used as part of the hashing for the security header in the response
20 use constant WEBSOCKET_GUID => '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
21  
22 # Opcodes have a registry here: https://www.iana.org/assignments/websocket/websocket.xhtml#opcode
23 our %OPCODE_BY_CODE = (
24 0 => 'continuation',
25 1 => 'text',
26 2 => 'binary',
27 8 => 'close',
28 9 => 'ping',
29 10 => 'pong',
30 );
31 our %OPCODE_BY_NAME = reverse %OPCODE_BY_CODE;
32  
33 our %COMPRESSIBLE_OPCODE = (
34 $OPCODE_BY_NAME{text} => 1,
35 $OPCODE_BY_NAME{binary} => 1,
36 );
37  
38 # Whether we're `ws` or `wss`
39 field $scheme : reader : param = 'ws';
40 # The Web::Async::WebSocket::Server instance
41 field $server : reader : param = undef;
42  
43 # Given the state of websockets in general, this is unlikely to change from `HTTP/1.1` anytime soon
44 field $http_version : reader : param = 'HTTP/1.1';
45 # 101 Upgrade is defined by the RFC, but if you have special requirements you can override via the constructor
46 field $status : reader : param = '101';
47 # The message is probably ignored by everything
48 field $msg : reader : param = 'Switching Protocols';
49 # There aren't a vast number of extensions, at the time of writing https://www.iana.org/assignments/websocket/websocket.xhtml#extension-name
50 # lists just two of 'em
51 field $supported_extension : reader : param {
52 +{
53 'permessage-deflate' => 1,
54 'server_no_context_takeover' => 1,
55 'client_no_context_takeover' => 1,
56 'server_max_window_bits' => 1,
57 'client_max_window_bits' => 1,
58 }
59 }
60  
61 field $method : reader = undef;
62 field $url : reader = undef;
63 field $uri : reader = undef;
64 field $headers : reader { +{ } }
65  
66 # What to report in the `Server:` header
67 field $server_name : reader : param = 'perl';
68  
69 # Restriction on number of raw (pre-decompression!) bytes,
70 # advised to set this to a nonzero value to avoid clients
71 # burning up all your memory...
72 field $maximum_payload_size : reader : param = undef;
73  
74 # Our current deflation (compression) state
75 field $deflation;
76 # Our current inflation (decompression) state
77 field $inflation;
78  
79 field $ryu : param : reader;
80  
81 # A coderef for processing requests before starting to accept traffic,
82 # should return a failed Future if the connection should be rejected.
83 field $handshake : param : reader = undef;
84  
85 field $on_handshake_failure : param : reader = undef;
86 field $on_handshake_complete : reader = undef;
87  
88 # A Ryu::Source representing the messages received from the client
89 field $incoming_frame : reader : param { $self->ryu->source }
90 # A Ryu::Source representing the messages to be sent to the client
91 field $outgoing_frame : reader : param { $self->ryu->source }
92  
93 field $compression_options : reader { +{ } }
94  
95 # The IO::Async::Stream representing the network connection
96 # to the client
97 field $stream;
98  
99 field $closed : reader : param = undef;
100  
101 method configure (%args) {
102 $http_version = delete $args{http_version} if exists $args{http_version};
103 $status = delete $args{status} if exists $args{status};
104 $msg = delete $args{msg} if exists $args{msg};
105 $ryu = delete $args{ryu} if exists $args{ryu};
106 $stream = delete $args{stream} if exists $args{stream};
107 weaken($server = delete $args{server}) if exists $args{server};
108 $server_name = delete $args{server_name} if exists $args{server_name};
109 $maximum_payload_size = delete $args{maximum_payload_size} if exists $args{maximum_payload_size};
110 $on_handshake_failure = delete $args{on_handshake_failure} if exists $args{on_handshake_failure};
111 $handshake = delete $args{handshake} if exists $args{handshake};
112 return $self->next::method(%args);
113 }
114  
115 method _add_to_loop ($loop) {
116 $on_handshake_failure //= async method ($stream, $error, @) {
117 await $stream->write("$http_version 400 $error\x0D\x0A\x0D\x0A");
118 };
119 $closed //= $self->loop->new_future;
120 $on_handshake_complete //= $self->loop->new_future;
121 $stream->configure(
122 on_closed => $self->$curry::weak(async method (@) {
123 $closed->done unless $closed->is_ready;
124 $server->on_client_disconnect($self);
125 }),
126 );
127 }
128  
129 =head2 send_text_frame
130  
131 Send a text frame.
132  
133 Expects a Unicode Perl text string as the first parameter - this will be
134 encoded to UTF-8 and sent to the client.
135  
136 =cut
137  
138 async method send_text_frame ($text, %args) {
139 return await $self->write_frame(
140 payload => $text,
141 type => 'text',
142 %args
143 );
144 }
145  
146 =head2 send_binary_frame
147  
148 Send a binary data frame.
149  
150 Expects the raw binary data bytes as the first parameter.
151  
152 =cut
153  
154 async method send_data_frame ($data, %args) {
155 return await $self->write_frame(
156 payload => $data,
157 type => 'binary',
158 %args
159 );
160 }
161  
162 =head2 write_frame
163  
164 Sends one or more frames to the client.
165  
166 =cut
167  
168 async method write_frame (%args) {
169 die 'already closed' if $closed->is_ready;
170 for my $frame ($self->prepare_frames(%args)) {
171 await $stream->write($frame);
172 }
173 return;
174 }
175  
176 async method prepare_frames (%args) {
177 my @frames;
178 $log->tracef('Write frame with %s', \%args);
179 my $opcode = $OPCODE_BY_NAME{$args{type}} // die 'invalid frame type';
180 my $compressed = ($args{compress} // 1) && $compression_options->{compress} && $COMPRESSIBLE_OPCODE{$opcode};
181 my $payload = $args{payload};
182 $payload = encode_utf8($payload) if $opcode == $OPCODE_BY_NAME{text};
183  
184 $opcode |= 0x80;
185 if($compressed) {
186 $opcode |= 0x40;
187 my $original = length $payload;
188 $payload = $self->deflate($payload);
189 # Strip terminator if we have one
190 $payload =~ s{\x00\x00\xFF\xFF$}{};
191 $log->tracef(
192 'Size after deflation is %d/%d, ratio of %4.1f%%',
193 length($payload),
194 $original,
195 100.0 * (length($payload) / ($original || 1)),
196 );
197 }
198 my $len = length $payload;
199 my $msg = pack('C1', $opcode);
200 if($len < 126) {
201 $msg .= pack('C1', $len);
202 } elsif($len <= 0xFFFF) {
203 $msg .= pack('C1n1', 126, $len);
204 } else {
205 $msg .= pack('C1Q>1', 127, $len);
206 }
207 $msg .= $payload;
208 push @frames, $msg;
209 return @frames;
210 }
211  
212 method deflate ($data) {
213 undef $deflation unless $compression_options->{server_context};
214 $deflation //= deflateInit(
215 -WindowBits => -($compression_options->{server_bits} || 15)
216 ) or die "Cannot create a deflation stream\n" ;
217  
218 my ($output, $status) = $deflation->deflate($data);
219 die "deflation failed - $status\n" unless $status == Z_OK;
220 (my $block, $status) = $deflation->flush(Z_SYNC_FLUSH);
221 die "deflation failed at flush stage\n" unless $status == Z_OK;
222  
223 return $output . $block;
224 }
225  
226 method inflate ($data) {
227 undef $inflation unless $compression_options->{client_context};
228 $inflation //= inflateInit(
229 -WindowBits => -($compression_options->{client_bits} || 15)
230 ) or die "Cannot create a deflation stream\n" ;
231  
232 my ($block, $status) = $inflation->inflate($data);
233 die "inflation failed - $status\n" unless $status == Z_STREAM_END or $status == Z_OK;
234 return $block;
235 }
236  
237 async method read_headers () {
238 while(1) {
239 my $line = decode_utf8('' . await $stream->read_until("\x0D\x0A"));
240 $line =~ s/\x0D\x0A$//;
241 last unless length $line;
242  
243 my ($k, $v) = $line =~ /^([^:]+):\s+(.*)$/;
244 $k = lc($k =~ tr{-}{_}r);
245 $headers->{$k} = $v;
246 }
247 return $headers;
248 }
249  
250 method generate_response_key ($key) {
251 die "No websocket key provided\n" unless defined $key and length $key;
252 return encode_base64(sha1($key . WEBSOCKET_GUID), '');
253 }
254  
255 async method handle_connection () {
256 try {
257 $self->add_child($stream);
258 my $first = await $stream->read_until("\x0D\x0A");
259 ($method, $url, my $version) = $first =~ m{^(\S+)\s+(\S+)\s+(HTTP/\d+\.\d+)\x0D\x0A$}a;
260 $log->tracef('HTTP request is [%s] for [%s] version %s', $method, $url, $version);
261 my $hdr = await $self->read_headers();
262  
263 $log->tracef('url = %s, headers = %s', $url, format_json_text($hdr));
264  
265 # We rely on the caller to tell us the scheme, defaulting to plain `ws`,
266 # and everything else in the URI comes directly from the request.
267 $uri = URI->new($scheme . '://localhost');
268 $uri->host($hdr->{host}) if exists $hdr->{host};
269 $uri->path($url);
270  
271 unless($hdr->{upgrade} =~ /^websocket$/i) {
272 die sprintf "No upgrade: websocket header, ignoring connection\n";
273 }
274 unless($hdr->{sec_websocket_version} >= 13) {
275 die sprintf "Invalid websocket version %s\n", $hdr->{sec_websocket_version};
276 }
277  
278 my %output = (
279 'Upgrade' => 'websocket',
280 'Connection' => 'upgrade',
281 'Server' => $server_name,
282 'Date' => Time::Moment->now_utc->strftime("%a, %d %b %Y %H:%M:%S GMT"),
283 );
284 $output{'Sec-WebSocket-Accept'} = $self->generate_response_key($hdr->{sec_websocket_key});
285  
286 if(exists $hdr->{sec_websocket_extensions}) {
287 my $extensions;
288 VALID: {
289 SELECTION:
290 for my $selection (split /\s*,\s*/, $hdr->{sec_websocket_extensions} // '') {
291 my @options = map {; /^(\S+)(?:\s*=\s*(.*)\s*)?$/ ? ($1, $2) : () } split /\s*;\s*/, $selection;
292 my @order = pairmap { $a } @options;
293 my %options = @options;
294 my @invalid = grep { !$supported_extension->{$_} } sort keys %options;
295 if(@invalid) {
296 $log->infof('Rejecting invalid option combination %s', \@invalid);
297 next SELECTION;
298 }
299  
300 $log->infof('Acceptable options: %s', \%options);
301 $options{client_max_window_bits} //= 15 if exists $options{client_max_window_bits};
302 $compression_options->{client_bits} = $options{client_max_window_bits};
303 $compression_options->{server_bits} = $options{server_max_window_bits} || 15;
304 $extensions = join '; ', map { defined($options{$_}) ? "$_=$options{$_}" : $_ } @order;
305 $compression_options->{server_context} = (exists $options{server_no_context_takeover}) ? 0 : 1;
306 $compression_options->{client_context} = (exists $options{client_no_context_takeover}) ? 0 : 1;
307 $compression_options->{compress} = 1 if exists $options{'permessage-deflate'};
308 last VALID;
309 }
310 $log->infof('No acceptable extension options, giving up: %s', $hdr->{sec_websocket_extensions});
311 await $stream->write(
312 join(
313 "\x0D\x0A",
314 "$http_version 400 No acceptable extensions",
315 (pairmap {
316 encode_utf8("$a: $b")
317 } %output),
318 # Blank line at the end of the headers
319 '', ''
320 )
321 );
322 die "no acceptable extensions\n";
323 }
324 $output{'Sec-Websocket-Extensions'} = $extensions;
325 }
326  
327 try {
328 await $handshake->(
329 client => $self,
330 response_headers => \%output,
331 ) if $handshake;
332 } catch ($e) {
333 await $stream->write(
334 join(
335 "\x0D\x0A",
336 "$http_version 400 Handshake rejected",
337 (pairmap {
338 encode_utf8("$a: $b")
339 } %output),
340 # Blank line at the end of the headers
341 '', ''
342 )
343 );
344 die "handshake rejected\n";
345 }
346  
347 # Send the entire header block in a single write
348 await $stream->write(
349 join(
350 "\x0D\x0A",
351 "$http_version $status $msg",
352 (pairmap {
353 encode_utf8("$a: $b")
354 } %output),
355 # Blank line at the end of the headers
356 '', ''
357 )
358 );
359 } catch ($e) {
360 $log->errorf('Failed - %s', $e);
361 await $self->$on_handshake_failure($stream, $e);
362 return;
363 }
364  
365 # Once the handshake is complete, we don't need the handler any more,
366 # and keeping it around could lead to unwanted refcount cycles
367 undef $on_handshake_failure;
368 $on_handshake_complete->done;
369  
370 # Body processing
371 try {
372 $log->tracef('Start reading frames');
373 while(1) {
374 await $incoming_frame->unblocked;
375 my $frame = await $self->read_frame();
376 $log->tracef('Had frame: %s', $frame);
377 $incoming_frame->emit($frame);
378 }
379 } catch ($e) {
380 $log->errorf('Problem, %s', $e) unless $e =~ /^EOF/;
381 await $self->close(
382 code => 1011, # internal error
383 reason => 'Internal error'
384 );
385 }
386 }
387  
388 async method read_frame () {
389 $log->tracef('Reading frames from %s', "$stream");
390 my $fin;
391 my $data = '';
392 my $compressed;
393 my $type;
394 do {
395 my ($chunk, $eof);
396 ($chunk, $eof) = await $stream->read_exactly(2);
397 die "EOF\n" if $eof;
398 my ($opcode, $len) = unpack 'C1C1', $chunk;
399 my $masked = $len & 0x80;
400 die "unmasked frame\n" unless $masked;
401 $len &= ~0x80;
402 $fin = ($opcode & 0x80) ? 1 : 0;
403 my @rsv = map { ($opcode & $_) ? 1 : 0 } 0x40, 0x20, 0x10;
404 $compressed //= $compression_options->{compress} && $rsv[0];
405 return await $self->close(
406 code => 1002,
407 reason => 'Reserved bit 0 set with compression disabled',
408 ) if $rsv[0] and not $compression_options->{compress};
409 return await $self->close(
410 code => 1002,
411 reason => 'Unexpected reserved bit set',
412 ) if any { $_ } @rsv[1..2];
413 $type //= $opcode & 0x0F;
414 return await $self->close(
415 code => 1002,
416 reason => 'Unknown opcode',
417 ) unless $OPCODE_BY_CODE{$type};
418 if($len == 126) {
419 ($chunk, $eof) = await $stream->read_exactly(2);
420 die "EOF\n" if $eof;
421 ($len) = unpack 'n1', $chunk;
422 die 'invalid length' if $len < 126;
423 } elsif($len == 127) {
424 ($chunk, $eof) = await $stream->read_exactly(8);
425 die "EOF\n" if $eof;
426 ($len) = unpack 'Q>1', $chunk;
427 die 'invalid length' if $len < 0xFFFF or $len & 0x80000000;
428 }
429 my $mask = '';
430 if($masked) {
431 ($mask, $eof) = await $stream->read_exactly(4);
432 die "EOF\n" if $eof;
433 }
434 $log->tracef(
435 'Frame opcode %d, length %d, fin = %s, rsv = %s %s %s, mask key %v0x',
436 $opcode,
437 $len,
438 $fin,
439 @rsv,
440 $mask
441 );
442 die "excessive length\n" if defined($maximum_payload_size) and $len + length($data) > $maximum_payload_size;
443 (my $payload, $eof) = await $stream->read_exactly($len);
444 die "EOF\n" if $eof;
445 if($masked) {
446 $log->tracef('Masked payload = %v0x', $payload);
447 my ($frac, $int) = POSIX::modf(length($payload) / 4);
448 $payload ^.= ($mask x $int) . substr($mask, 0, 4 * $frac);
449 }
450 $log->tracef('Payload = %v0x', $payload);
451 $data .= $payload;
452 } until $fin;
453 $data = $self->inflate($data . "\x00\x00\xFF\xFF") if $compressed;
454 $log->tracef('Frame opcode is %s', $OPCODE_BY_CODE{$type});
455 if($type == $OPCODE_BY_NAME{text}) {
456 return await $self->close(
457 code => 1002,
458 reason => 'Invalid UTF-8 data in text frame',
459 ) unless valid_utf8($data);
460 $data = decode_utf8($data);
461 }
462 $log->tracef('Finished, data is now %s', $data);
463 my $frame = Web::Async::WebSocket::Frame->new(
464 payload => $data,
465 opcode => $type
466 );
467 if($OPCODE_BY_CODE{$type} equ 'close') {
468 my ($code, $reason) = unpack 'na*', $frame->payload;
469 return await $self->close(
470 code => 1002,
471 reason => 'Invalid UTF-8 reason in close frame',
472 ) unless valid_utf8($reason);
473 await $self->close(
474 code => ($code || 0),
475 reason => decode_utf8($reason // ''),
476 );
477 }
478 return $frame;
479 }
480  
481 async method close (%args) {
482 # Can only close once
483 return if $closed->is_ready;
484  
485 if($server) {
486 $server->on_client_close($self, %args);
487 }
488  
489 # No point trying to write anything if the remote has closed the connection
490 if($stream->is_read_eof) {
491 $closed->done(%args);
492 $stream->close;
493 return;
494 }
495  
496 my $f = $self->write_frame(
497 type => 'close',
498 payload => pack(
499 'na*' => ($args{code} // 0), encode_utf8($args{reason} // '')
500 ),
501 );
502 $closed->done(%args);
503 await $f;
504 $stream->close;
505 }
506  
507 1;
« Async/WebSocket/Server.pm ↑ Summary Async.pm »