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

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