blib/lib/POE/Component/Client/WebSocket.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 12 Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 247 CC 17 SCAR 21.3
CC
17
Cov
0%
_send
30.0
new
20.0
_socket_input
20.0
CRAP 8.4
1 package POE::Component::Client::WebSocket;
2  
3 use v5.26.0;;
4 use strict;
5 use warnings;
6  
7 use vars qw($VERSION);
8 $VERSION = '0.29';
9  
10 use Carp qw(carp croak);
11 use Errno qw(ETIMEDOUT ECONNRESET);
12  
13 # Explicit use to import the parameter constants;
14 use POE::Session;
15 use POE::Driver::SysRW;
16 use POE::Wheel::ReadWrite;
17 use POE::Wheel::SocketFactory;
18 use POE::Filter::Stackable;
19 use POE::Filter::SSL;
20 use POE::Filter::Stream;
21  
22 # Other various stuff
23 use URI::Split qw(uri_split);
24 use MIME::Base64;
25 use Data::Dumper;
26  
27 # Crazy frame stuff
28 use Protocol::WebSocket::Frame;
29  
30 # HTTP parsing modules
31 require HTTP::Request;
32 require HTTP::Response;
33  
34 # Global stuff for checks etc.
35 my $validOpts = {
36 types => {
37 'continuation' => 1,
38 'text' => 1,
39 'binary' => 1,
40 'ping' => 1,
41 'pong' => 1,
42 'close' => 1,
43 }
44 };
45  
46 =head1 NAME
47  
48 POE::Component::Client::WebSocket - A POE compatible websocket client
49  
50 =head1 VERSION
51  
52 Version 0.29
53  
54 =head1 WARNING: Work in progress! Only uploaded early for testing purposes!
55  
56 This module appears to work perfectly, however its not really been tested that much and I will be amazed if there are not bugs.
57  
58 =head1 SYNOPSIS
59  
60 #!/usr/bin/env perl
61  
62 use warnings;
63 use strict;
64  
65 use POE qw(Component::Client::WebSocket);
66  
67 POE::Session->create(
68 inline_states => {
69 _start => sub {
70 my $ws = POE::Component::Client::WebSocket->new('wss://echo.websocket.org');
71 $ws->handler('connected','connected');
72 $ws->connect;
73  
74 $_[HEAP]->{ws} = $ws;
75  
76 $_[KERNEL]->yield("next")
77 },
78 next => sub {
79 $_[KERNEL]->delay(next => 1);
80 },
81 websocket_read => sub {
82 my ($kernel,$read) = @_[KERNEL,ARG0];
83  
84 print "Read: $read\n";
85 },
86 websocket_disconnected => sub {
87 warn "Disconnected";
88 },
89 connected => sub {
90 my $req = $_[ARG0];
91 },
92 websocket_handshake => sub {
93 my $res = $_[ARG0];
94  
95 $_[KERNEL]->post( $_[SENDER]->ID, 'send', 1234 );
96  
97 $_[HEAP]->{ws}->send(5678);
98 },
99 },
100 );
101  
102 POE::Kernel->run();
103 exit;
104  
105  
106 =head1 SUBROUTINES/METHODS
107  
108 =head2 new
109  
110 Create a new object, takes 1 argument.. a fully qualified websocket URI.
111  
112 =cut
113  
114 sub new {
115 my ($class,$uri) = @_;
116  
117 my $self = bless {
118 alias => __PACKAGE__,
119 session => 0,
120 }, $class;
121  
122 my ($scheme, $auth, $path, $query, $frag) = uri_split($uri);
123 my ($host,$port) = split(/:/,$auth);
124  
125 # If we are on WSS we are probably using https, if not probably http
126 if (!$port) {
127 if (uc($scheme) eq 'WSS') { $port = 443 }
128 else { $port = 80 }
129 }
130  
131 my $key = "";
132 for (1..16) { $key .= int(rand(9)) }
133  
134 my $origin = (uc $scheme eq 'WSS' ? 'https' : 'http') . "://$host";
135  
136 $self->{session} = POE::Session->create(
137 package_states => [
138 $self => {
139 _start => '_start',
140 _stop => '_stop',
141 keep_alive => '_keep_alive',
142 connect => '_connect',
143 handler => '_handler',
144 origin => '_origin',
145 send => '_send',
146 parent => '_parent',
147 socket_birth => '_socket_birth',
148 socket_death => '_socket_death',
149 socket_input => '_socket_input',
150 }
151 ],
152 heap => {
153 parent => POE::Kernel->get_active_session()->ID,
154 handlers => {
155 read => 'websocket_read',
156 connected => 'websocket_connected',
157 handshake => 'websocket_handshake',
158 disconnected => 'websocket_disconnected',
159 error => 'websocket_error',
160 },
161 uri => {
162 scheme => $scheme,
163 auth => $auth,
164 path => $path,
165 query => $query,
166 frag => $frag,
167 host => $host,
168 port => $port,
169 full => $uri
170 },
171 req => {
172 'origin' => $origin,
173 'sec-websocket-key' => encode_base64($key),
174 },
175 _state => {
176 run => 1,
177 frame => Protocol::WebSocket::Frame->new,
178 },
179
180 }
181 );
182  
183 $self->{id} = $self->{session}->ID;
184  
185 return $self;
186 }
187  
188 =head1 Default handlers and arguments
189  
190 All of these can be changed with the 'handler' function, note the 'event key'.
191  
192 =head2 read (websocket_read)
193  
194 event key: read
195 default handler: websocket_read
196  
197 Data that has been read and decoded from the server.
198  
199  
200 =head2 disconnected (websocket_disconnected)
201  
202 event key: disconnected
203 default handler: websocket_disconnected
204  
205 Called when the websocket is disconnected.
206  
207 =head2 connected (websocket_connected)
208  
209 event key: connected
210 default handler: websocket_connected
211  
212 Called when the websocket is connected (before the handshake) ARG0 contains the HTTP::Request sent.
213  
214 =head2 handshake (websocket_handshake)
215  
216 event key: handshake
217 default handler: websocket_handshake
218  
219 Called when the socket handshake is completed, ARG0 contains the HTTP::Response from the server.
220  
221 =head2 error (websocket_error)
222  
223 event key: error
224 default handler: websocket_error
225  
226 Called when an error is retrieved, this is a bit vague at the moment ARG0 should contain something.
227  
228 =head1 OOP mappings from obj to POE
229  
230 These can be called with a standard POE style POST or directly from the object (see SYNOPSIS for examples of both)
231  
232 =head2 connect
233  
234 Start the connection
235  
236 =cut
237  
238 sub connect {
239 my $self = shift;
240 POE::Kernel->post( $self->{session}->ID, 'connect', @_ );
241 }
242  
243 =head2 handler
244  
245 Adjust the handlers events are sent to
246  
247 =cut
248  
249 sub handler {
250 my ($self,$target,$destination) = @_;
251  
252 return if ( (!$target) || (!$destination) );
253  
254 POE::Kernel->post(
255 $self->{session}->ID,
256 'handler',
257 $target,
258 $destination
259 );
260 }
261  
262 =head2 origin
263  
264 Change the origin from the automatically generated one to something else.
265  
266 =cut
267  
268 sub origin {
269 my ($self,$target) = @_;
270  
271 return if (!$target);
272  
273 POE::Kernel->post(
274 $self->{session}->ID,
275 'origin',
276 $target
277 );
278 }
279  
280 =head2 parent
281  
282 Override the 'send to' parent for the module, by default this is the module that the component was started from.
283  
284 =cut
285  
286 sub parent {
287 my ($self,$target) = @_;
288  
289 return if (!$target);
290  
291 POE::Kernel->post(
292 $self->{session}->ID,
293 'parent',
294 $target
295 );
296 }
297  
298 =head2 send
299  
300 Send data to the server, arguments are:
301 1: 'data' the information you want to send.
302 2: 'type' the type of information to send (default 'text')
303 3: 'fin' wether to send the 'fin' flag (default 1)
304 4: 'masked' wether the frame should be masked (default 0)
305  
306 =cut
307  
308 sub send {
309 my ($self,$data,$type,$fin,$masked) = @_;
310  
311 return if (!$data);
312  
313 POE::Kernel->post(
314 $self->{session}->ID,
315 'send',
316 $data,$type,$fin,$masked
317 );
318 }
319  
320  
321 =head1 Internal functions (do not call these directly)
322  
323 =head2 _start
324  
325 Initial start handler
326  
327 =cut
328  
329 sub _start {
330 my ($kernel,$heap) = @_[KERNEL,HEAP];
331  
332 $kernel->yield('keep_alive');
333 }
334  
335 =head2 _stop
336  
337 Default stop handler for tidying things up
338  
339 =cut
340  
341 sub _stop {
342 }
343  
344 =head2 _keep_alive
345  
346 Do not allow the module to stop running
347  
348 =cut
349  
350 sub _keep_alive {
351 my ($kernel,$heap) = @_[KERNEL,HEAP];
352  
353 return if (!$heap->{_state}->{run});
354  
355 $kernel->delay_add('keep_alive' => 1);
356 }
357  
358 =head2 _connect
359  
360 Initate a connect to the websocket
361  
362 =cut
363  
364 sub _connect {
365 my ($kernel,$heap) = @_[KERNEL,HEAP];
366  
367 $heap->{socket} = POE::Wheel::SocketFactory->new(
368 RemoteAddress => $heap->{uri}->{host},
369 RemotePort => $heap->{uri}->{port},
370 SuccessEvent => 'socket_birth',
371 FailureEvent => 'socket_death',
372 );
373 }
374  
375 =head2 _handler
376  
377 Adjust the distribution map for handlers
378  
379 =cut
380  
381 sub _handler {
382 my ($kernel,$heap,$target,$destination) = @_[KERNEL,HEAP,ARG0,ARG1];
383  
384 $heap->{handlers}->{lc($target)} = $destination;
385 }
386  
387 =head2 _origin
388  
389 Change the origin used in the opening handshake
390  
391 =cut
392  
393 sub _origin {
394 my ($kernel,$heap,$target) = @_[KERNEL,HEAP,ARG0];
395  
396 $heap->{req}->{origin} = $target;
397 }
398  
399 =head2 _parent
400  
401 Change the currently targeted session to communicate events with.
402  
403 =cut
404  
405 sub _parent {
406 my ($kernel,$heap,$target) = @_[KERNEL,HEAP,ARG0];
407  
408 $heap->{parent} = $target;
409 }
410  
411 =head2 _send
412  
413 Send a frame encoded request to the server
414  
415 =cut
416  
417 sub _send {
418 my ($kernel,$heap,$data,$type,$fin,$masked) = @_[KERNEL,HEAP,ARG0,ARG1,ARG2,ARG3];
419  
420 $data = "" if (!$data);
421 $type = 'text' if ( (!$type) || (! $validOpts->{types}->{$type}) );
422 $fin = 1 if ((!defined $fin) || ($fin !~ m#^[01]$#));
423 $masked = 1 if ((!defined $masked) || ($fin !~ m#^[01]$#));
424  
425 my $frame = Protocol::WebSocket::Frame->new( buffer => $data, type => $type, fin => $fin, masked => $masked );
426 $heap->{wheel}->put($frame->to_bytes);
427 }
428  
429 =head2 _socket_birth
430  
431 Handle a socket when it connects to something
432  
433 =cut
434  
435 sub _socket_birth {
436 my ($kernel, $socket, $sockid, $heap) = @_[KERNEL, ARG0, ARG3, HEAP];
437  
438 if ( uc($heap->{uri}->{scheme}) eq 'WSS' ) {
439 $heap->{_state}->{sslfilter} = POE::Filter::SSL->new(
440 client => 1,
441 sni => $heap->{uri}->{host},
442 );
443  
444 $heap->{filters}->{output} = POE::Filter::Stackable->new(Filters => [ $heap->{_state}->{sslfilter} ]);
445 $heap->{filters}->{input} = POE::Filter::Stackable->new(Filters => [ $heap->{_state}->{sslfilter} ]);
446 } else {
447 $heap->{filters}->{output} = POE::Filter::Stackable->new(Filters => []);
448 $heap->{filters}->{input} = POE::Filter::Stackable->new(Filters => []);
449 }
450  
451 $heap->{filters}->{output}->push(POE::Filter::Stream->new());
452 $heap->{filters}->{input}->push(POE::Filter::Stream->new());
453  
454 $heap->{wheel} = POE::Wheel::ReadWrite->new(
455 Handle => $socket,
456 Driver => POE::Driver::SysRW->new(),
457 OutputFilter => $heap->{filters}->{output},
458 InputFilter => $heap->{filters}->{input},
459 InputEvent => 'socket_input',
460 ErrorEvent => 'socket_death',
461 );
462  
463 my $request = HTTP::Request->new(GET => $heap->{uri}->{full});
464 $request->protocol('HTTP/1.1');
465 $request->header(
466 'Upgrade' => 'WebSocket',
467 'Connection' => 'Upgrade',
468 'Host' => $heap->{uri}->{host},
469 'Origin' => $heap->{req}->{origin},
470 'Sec-WebSocket-Key' => $heap->{req}->{'sec-websocket-key'},
471 'Sec-WebSocket-Protocol' => 'chat',
472 'Sec-WebSocket-Version' => 13,
473 'Cache-Control' => 'no-cache',
474 'Pragma' => 'no-cache',
475 'User-Agent' => "POE::Component::Client::WebSocket $VERSION"
476 );
477  
478 # Add a lock for when to stop reading the stream
479 $heap->{httpresp} = 1;
480  
481 # Send the request to the server
482 $heap->{wheel}->put($request->as_string("\r\n"));
483  
484 # Incase we want to investigate what we sent later.
485 $heap->{_state}->{req} = $request;
486  
487 # Post back a copy of the request
488 $kernel->post( $heap->{parent}, $heap->{handlers}->{'connected'}, $request );
489 }
490  
491 =head2 _socket_death
492  
493 Handle a socket when it is disconnected
494  
495 =cut
496  
497 sub _socket_death {
498 my ($kernel,$heap) = @_[KERNEL,HEAP];
499
500 $kernel->post( $heap->{parent}, $heap->{handlers}->{disconnected} )
501 }
502  
503 =head2 _socket_input
504  
505 Read data from the socket
506  
507 =cut
508  
509 sub _socket_input {
510 my ($kernel,$heap,$buf) = @_[KERNEL,HEAP,ARG0];
511  
512 if ( $heap->{httpresp} ) {
513 $heap->{httpbuf} .= $buf;
514
515 if ( $heap->{httpbuf} =~ m#\r\n$#m ) {
516 # Remove the lock
517 delete $heap->{httpresp};
518  
519 # Keep a copy of the response we got incase we want to have a look at it later
520 $heap->{_state}->{res} = $buf;
521  
522 # Create an investigatable response object
523 my $resp = HTTP::Response->parse($heap->{httpbuf});
524  
525 # Lets see if we can proceed
526 if ($resp->code() == 101) {
527 # Ok connected
528  
529 # Send a copy of the handshake back to the users space
530 $kernel->post( $heap->{parent}, $heap->{handlers}->{'handshake'}, $resp );
531 }
532 }
533  
534 return;
535 }
536  
537 $heap->{_state}->{frame}->append($buf);
538  
539 while (my $frame = $heap->{_state}->{frame}->next) {
540 $kernel->post( $heap->{parent}, $heap->{handlers}->{read}, $frame )
541 }
542 }
543
544 =head1 AUTHOR
545  
546 Paul G Webster, C<< <daemon at cpan.org> >>
547  
548 =head1 Contributors
549  
550 Tom Ryder C << anonymous@while.verifying >>
551  
552 =head1 BUGS
553  
554 Please report any bugs or feature requests to L<https://github.com/PaulGWebster/POE-Component-Client-Websocket>
555  
556 =head1 SUPPORT
557  
558 You can find documentation for this module with the perldoc command.
559  
560 perldoc POE::Component::Client::WebSocket
561  
562  
563 You can also look for information at:
564  
565 =over 4
566  
567 =item * GitHub (please report bugs here)
568  
569 L<https://github.com/PaulGWebster/POE-Component-Client-Websocket/issues>
570  
571 =item * AnnoCPAN: Annotated CPAN documentation
572  
573 L<http://annocpan.org/dist/POE-Component-Client-WebSocket>
574  
575 =item * Search MetaCPAN
576  
577 L<http://search.metacpan.org/dist/POE-Component-Client-WebSocket/>
578  
579 =back
580  
581  
582 =head1 ACKNOWLEDGEMENTS
583  
584  
585 =head1 LICENSE AND COPYRIGHT
586  
587 Copyright 2021 Paul G Webster.
588  
589 This program is free software; you can redistribute it and/or modify it
590 under the terms of the the Artistic License (2.0). You may obtain a
591 copy of the full license at:
592  
593 L<http://www.perlfoundation.org/artistic_license_2_0>
594  
595 Any use, modification, and distribution of the Standard or Modified
596 Versions is governed by this Artistic License. By using, modifying or
597 distributing the Package, you accept this license. Do not use, modify,
598 or distribute the Package, if you do not accept this license.
599  
600 If your Modified Version has been derived from a Modified Version made
601 by someone other than you, you are nevertheless required to ensure that
602 your Modified Version complies with the requirements of this license.
603  
604 This license does not grant you the right to use any trademark, service
605 mark, tradename, or logo of the Copyright Holder.
606  
607 This license includes the non-exclusive, worldwide, free-of-charge
608 patent license to make, have made, use, offer to sell, sell, import and
609 otherwise transfer the Package with respect to any patent claims
610 licensable by the Copyright Holder that are necessarily infringed by the
611 Package. If you institute patent litigation (including a cross-claim or
612 counterclaim) against any party alleging that the Package constitutes
613 direct or contributory patent infringement, then this Artistic License
614 to you shall terminate on the date that such litigation is filed.
615  
616 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
617 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
618 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
619 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
620 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
621 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
622 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
623 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
624  
625  
626 =cut
627  
628 1; # End of POE::Component::Client::WebSocket