Lightspeed/Client.pm untested

filter: Statementstmt 0.0% 0 / 248 Branchbran 0.0% 0 / 134 Conditioncond 0.0% 0 / 56 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 503 CC 68 SCAR 57.9
CC
68
Cov
0%
spawn
702.0
InputLine
506.0
GotConnection
30.0
CRAP 325.9
1 # Declare our package
2 package POE::Component::Lightspeed::Client;
3  
4 # Standard stuff to catch errors
5 use strict qw(subs vars refs); # Make sure we can't mess up
6 use warnings FATAL => 'all'; # Enable warnings to catch errors
7  
8 # Initialize our version
9 our $VERSION = '1.' . sprintf( "%04d", (qw($Revision: 1082 $))[1] );
10  
11 # Import what we need
12 use Carp qw( croak );
13 use Time::HiRes qw( gettimeofday );
14 use POE;
15 use POE::Wheel::SocketFactory;
16 use POE::Wheel::ReadWrite;
17 use POE::Driver::SysRW;
18 use POE::Filter::Line;
19 use POE::Filter::Reference;
20 use POE::Component::Lightspeed::Router;
21 use POE::Component::Lightspeed::Constants qw( MSG_TIMESTAMP MSG_ACTION );
22  
23 # Set some constants
24 BEGIN {
25 # Debug fun!
26 if ( ! defined &DEBUG ) {
27 eval "sub DEBUG () { 0 }";
28 }
29 }
30  
31 # Spawn the Router session
32 POE::Component::Lightspeed::Router->spawn();
33  
34 # Spawns an instance of the client
35 sub spawn {
36 # Get the OOP's type
37 my $type = shift;
38  
39 # Sanity checking
40 if ( @_ & 1 ) {
41 croak( 'POE::Component::Lightspeed::Client->spawn needs even number of options' );
42 }
43  
44 # The options hash
45 my %opt = @_;
46  
47 # Our own options
48 my ( $ALIAS, $KERNEL, $ADDRESS, $PORT, $SERIALIZERS, $COMPRESSION, $USESSL, $PASSWORD );
49  
50 # Get the session alias
51 if ( exists $opt{'ALIAS'} and defined $opt{'ALIAS'} and length( $opt{'ALIAS'} ) ) {
52 $ALIAS = delete $opt{'ALIAS'};
53 } else {
54 # Debugging info...
55 if ( DEBUG ) {
56 warn 'Using default ALIAS = lightspeed_client';
57 }
58  
59 # Set the default
60 $ALIAS = 'lightspeed_client';
61  
62 # Remove any lingering ALIAS
63 if ( exists $opt{'ALIAS'} ) {
64 delete $opt{'ALIAS'};
65 }
66 }
67  
68 # Get the KERNEL
69 if ( exists $opt{'KERNEL'} and defined $opt{'KERNEL'} and length( $opt{'KERNEL'} ) ) {
70 $KERNEL = delete $opt{'KERNEL'};
71 } else {
72 # Debugging info...
73 if ( DEBUG ) {
74 warn 'Using default KERNEL = Supplied by POE';
75 }
76  
77 # Set the default
78 $KERNEL = $poe_kernel->ID;
79  
80 if ( exists $opt{'KERNEL'} ) {
81 delete $opt{'KERNEL'};
82 }
83 }
84  
85 # Get the ADDRESS
86 if ( exists $opt{'ADDRESS'} and defined $opt{'ADDRESS'} and length( $opt{'ADDRESS'} ) ) {
87 $ADDRESS = delete $opt{'ADDRESS'};
88 } else {
89 warn 'POE::Component::Lightspeed::Server->spawn must get at least 1 argument - the address to connect!';
90 return undef;
91 }
92  
93 # Get the PORT
94 if ( exists $opt{'PORT'} and defined $opt{'PORT'} and length( $opt{'PORT'} ) ) {
95 $PORT = delete $opt{'PORT'};
96 } else {
97 # Debugging info...
98 if ( DEBUG ) {
99 warn 'Using default PORT = 9876';
100 }
101  
102 # Set the default
103 $PORT = 9876;
104  
105 if ( exists $opt{'PORT'} ) {
106 delete $opt{'PORT'};
107 }
108 }
109  
110 # Get the SERIALIZERS
111 if ( exists $opt{'SERIALIZERS'} and defined $opt{'SERIALIZERS'} and ref( $opt{'SERIALIZERS'} ) and ref( $opt{'SERIALIZERS'} ) eq 'ARRAY' ) {
112 $SERIALIZERS = delete $opt{'SERIALIZERS'};
113 } else {
114 # Debugging info...
115 if ( DEBUG ) {
116 warn 'Using default SERIALIZERS = Storable, YAML';
117 }
118  
119 # Set the default
120 $SERIALIZERS = [ 'Storable', 'YAML' ];
121  
122 if ( exists $opt{'SERIALIZERS'} ) {
123 delete $opt{'SERIALIZERS'};
124 }
125 }
126  
127 # Get the COMPRESSION
128 if ( exists $opt{'COMPRESSION'} and defined $opt{'COMPRESSION'} and length( $opt{'COMPRESSION'} ) ) {
129 $COMPRESSION = delete $opt{'COMPRESSION'};
130 } else {
131 # Debugging info...
132 if ( DEBUG ) {
133 warn 'Using default COMPRESSION = false';
134 }
135  
136 # Set the default
137 $COMPRESSION = 0;
138  
139 if ( exists $opt{'COMPRESSION'} ) {
140 delete $opt{'COMPRESSION'};
141 }
142 }
143  
144 # Get the USESSL
145 if ( exists $opt{'USESSL'} and defined $opt{'USESSL'} and length( $opt{'USESSL'} ) ) {
146 $USESSL = delete $opt{'USESSL'};
147  
148 # Check if we want it
149 if ( $USESSL ) {
150 eval {
151 use POE::Component::SSLify qw( Client_SSLify );
152 };
153  
154 # Error-checking
155 if ( $@ ) {
156 warn "Unable to load SSLify: $@";
157 $USESSL = 0;
158 }
159 }
160 } else {
161 # Debugging info...
162 if ( DEBUG ) {
163 warn 'Using default USESSL = false';
164 }
165  
166 # Set the default
167 $USESSL = 0;
168  
169 if ( exists $opt{'USESSL'} ) {
170 delete $opt{'USESSL'};
171 }
172 }
173  
174 # Get the PASSWORD
175 if ( exists $opt{'PASSWORD'} and defined $opt{'PASSWORD'} and length( $opt{'PASSWORD'} ) ) {
176 $PASSWORD = delete $opt{'PASSWORD'};
177 } else {
178 # Debugging info...
179 if ( DEBUG ) {
180 warn 'Using default PASSWORD = undef';
181 }
182  
183 # Set the default
184 $PASSWORD = undef;
185  
186 if ( exists $opt{'PASSWORD'} ) {
187 delete $opt{'PASSWORD'};
188 }
189 }
190  
191 # Create the POE Session!
192 POE::Session->create(
193 'inline_states' => {
194 # Generic stuff
195 '_start' => \&StartClient,
196 '_stop' => sub {},
197  
198 # Public events
199 'shutdown' => \&StopClient,
200  
201 # SocketFactory events
202 'CreateSF' => \&Create_SocketFactory,
203 'GotConnection' => \&GotConnection,
204 'SFError' => \&SFError,
205  
206 # ReadWrite events
207 'InputLine' => \&InputLine,
208 'InputHash' => \&InputHash,
209 'Flushed' => sub {},
210 'RWError' => \&RWError,
211  
212 # Router events
213 'send' => \&Send_Packet,
214 'killclient' => \&StopClient,
215 },
216  
217 # Our own heap
218 'heap' => {
219 'ALIAS' => $ALIAS,
220 'MYKERNEL' => $KERNEL,
221  
222 # Connection stuff
223 'PHASE' => 'no',
224 'SERIALIZER_C' => 0,
225 'FILTER' => undef,
226 'WHEEL' => undef,
227 'SF' => undef,
228  
229 # Packet statistics
230 'PACKETS_IN' => 0,
231 'PACKETS_OUT' => 0,
232  
233 # The server info
234 'SERVER_IP' => $ADDRESS,
235 'SERVER_PORT' => $PORT,
236 'SERVER_VER' => undef,
237 'SERVER_KERNEL' => undef,
238 'SERIALIZER' => $SERIALIZERS,
239 'COMPRESSION' => $COMPRESSION,
240 'USESSL' => $USESSL,
241 'PASSWORD' => $PASSWORD,
242 },
243 ) or die 'Unable to create a new session!';
244  
245 # Return success
246 return 1;
247 }
248  
249 # Connects to a lightspeed server
250 sub StartClient {
251 # Okay, can we take the alias?
252 if ( ! $_[KERNEL]->_resolve_session( $_[HEAP]->{'ALIAS'} ) ) {
253 # Set it!
254 $_[KERNEL]->alias_set( $_[HEAP]->{'ALIAS'} );
255 } else {
256 # Loop over fake numbers
257 my $num = 0;
258 while ( ++$num ) {
259 if ( ! $_[KERNEL]->_resolve_session( $_[HEAP]->{'ALIAS'} . '_' . $num ) ) {
260 # Set this as our new alias
261 $_[HEAP]->{'ALIAS'} = $_[HEAP]->{'ALIAS'} . '_' . $num;
262  
263 # Debug stuff
264 if ( DEBUG ) {
265 warn "Finally found an alias to use -> " . $_[HEAP]->{'ALIAS'};
266 }
267  
268 # Actually set it!
269 $_[KERNEL]->alias_set( $_[HEAP]->{'ALIAS'} );
270 last;
271 }
272 }
273 }
274  
275 # Create the wheel
276 $_[KERNEL]->yield( 'CreateSF' );
277  
278 # All done!
279 return 1;
280 }
281  
282 # Shuts ourself down
283 sub StopClient {
284 # ARG0 = wheel id but we don't care :)
285  
286 # Debug stuff
287 if ( DEBUG ) {
288 warn "Shutting down the client '$_[HEAP]->{'ALIAS'}'";
289 }
290  
291 # Remove the alias
292 $_[KERNEL]->alias_remove( $_[HEAP]->{'ALIAS'} );
293  
294 # If we received a packet, that means we've told the router we are connected
295 # Also, if the wheel is still alive, that means somebody TOLD us to shutdown
296 if ( $_[HEAP]->{'PACKETS_IN'} and defined $_[HEAP]->{'RW'} ) {
297 # Let the router know the link is down
298 $_[KERNEL]->call( $POE::Component::Lightspeed::Router::SES_ALIAS, 'link_down', $_[HEAP]->{'RW'}->ID );
299 }
300  
301 # Remove any wheels
302 undef $_[HEAP]->{'SF'};
303 undef $_[HEAP]->{'RW'};
304  
305 # All done!
306 return 1;
307 }
308  
309 # Actually creates the SocketFactory wheel
310 sub Create_SocketFactory {
311 # Okay, time to create the connection!
312 $_[HEAP]->{'SF'} = POE::Wheel::SocketFactory->new(
313 'RemotePort' => $_[HEAP]->{'SERVER_PORT'},
314 'RemoteAddress' => $_[HEAP]->{'SERVER_IP'},
315 'SuccessEvent' => 'GotConnection',
316 'FailureEvent' => 'SFError',
317 );
318  
319 # All done!
320 return 1;
321 }
322  
323 # We are connected to the server!
324 sub GotConnection {
325 # ARG0 = Socket, ARG1 = Remote Address, ARG2 = Remote Port, ARG3 = wheelid
326 my $socket = $_[ARG0];
327  
328 # Get rid of the SocketFactory
329 undef $_[HEAP]->{'SF'};
330  
331 # Should we use SSL?
332 if ( $_[HEAP]->{'USESSL'} ) {
333 eval { $socket = Client_SSLify( $socket ); };
334  
335 # Error Checking
336 if ( $@ ) {
337 if ( DEBUG ) {
338 warn "Unable to turn socket into SSL -> $@";
339 }
340  
341 # Shutdown!
342 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
343 }
344 }
345  
346 # Set up the Wheel to read from the socket
347 my $wheel = POE::Wheel::ReadWrite->new(
348 'Handle' => $socket,
349 'Driver' => POE::Driver::SysRW->new(),
350 'Filter' => POE::Filter::Line->new(),
351 'InputEvent' => 'InputLine',
352 'FlushedEvent' => 'Flushed',
353 'ErrorEvent' => 'RWError',
354 );
355  
356 # Save this wheel!
357 $_[HEAP]->{'RW'} = $wheel;
358  
359 # Debug stuff
360 if ( DEBUG ) {
361 warn "GotConnection completed creation of ReadWrite wheel ( " . $wheel->ID . " )";
362 }
363  
364 # Success!
365 return 1;
366 }
367  
368 # Got some sort of error from SocketFactory
369 sub SFError {
370 # ARG0 = operation, ARG1 = error number, ARG2 = error string, ARG3 = wheel ID
371 my ( $operation, $errnum, $errstr, $wheel_id ) = @_[ ARG0 .. ARG3 ];
372  
373 # Debug stuff
374 if ( DEBUG ) {
375 warn "SocketFactory Wheel $wheel_id generated $operation error $errnum: $errstr\n";
376 }
377  
378 # Shutdown ourself
379 $_[KERNEL]->yield( 'shutdown' );
380  
381 # Success!
382 return 1;
383 }
384  
385 # Helper sub to get the next serializer available
386 sub _Get_NextSerializer {
387 # Get the heap
388 my $h = shift;
389  
390 # Okay, generate the next one
391 while ( 1 ) {
392 # Reality check!
393 if ( ! defined $h->{'SERIALIZER'}->[ $h->{'SERIALIZER_C'} ] ) {
394 warn "Unable to find a working serializer!";
395  
396 # Close the connection, grudingly
397 undef $h->{'RW'};
398  
399 # Tell ourself to shutdown
400 $poe_kernel->yield( 'shutdown' );
401  
402 # All done
403 return undef;
404 }
405  
406 # Proceed with the next serializer we have
407 my $filter = [ $h->{'SERIALIZER'}->[ $h->{'SERIALIZER_C'}++ ] ];
408 eval { $filter->[1] = POE::Filter::Reference->new( $filter->[0], $h->{'COMPRESSION'} ); };
409  
410 if ( $@ ) {
411 if ( DEBUG ) {
412 warn "Serializer $filter->[0] failed to load!";
413 }
414 next;
415 } else {
416 $h->{'FILTER'} = $filter;
417 return 1;
418 }
419 }
420 }
421  
422 # Got some input!
423 sub InputLine {
424 # ARG0 = input, ARG1 = wheel id
425 my $line = $_[ARG0];
426  
427 # Skip empty lines
428 return if $line eq '';
429  
430 # Did we get an error?
431 if ( $line =~ /^ERROR/ ) {
432 # Aw, dang!
433 if ( DEBUG ) {
434 warn "Got ERROR from server in the $_[HEAP]->{'PHASE'} phase -> $line";
435 }
436  
437 # Get rid of ourself...
438 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
439 return undef;
440 }
441  
442 # Ok, what stage of negotiations are we on?
443 if ( $_[HEAP]->{'PHASE'} eq 'no' ) {
444 # Should be the welcome line
445 if ( $line =~ /^SERVER\s+Lightspeed\s+v\/(.*)\s+kernel\s+(.*)$/ ) {
446 # Okay, this server talks lightspeed :)
447 $_[HEAP]->{'SERVER_VER'} = $1;
448 $_[HEAP]->{'SERVER_KERNEL'} = $2;
449  
450 # Send the client stuff
451 $_[HEAP]->{'RW'}->put( 'CLIENT Lightspeed v/' . $VERSION . ' kernel ' . $_[HEAP]->{'MYKERNEL'} );
452  
453 # Do we have a password?
454 if ( defined $_[HEAP]->{'PASSWORD'} ) {
455 $_[HEAP]->{'PHASE'} = 'password';
456  
457 # Send it off!
458 $_[HEAP]->{'RW'}->put( 'PASSWORD ' . $_[HEAP]->{'PASSWORD'} );
459 } else {
460 $_[HEAP]->{'PHASE'} = 'compression';
461  
462 # Do we want compression?
463 if ( $_[HEAP]->{'COMPRESSION'} ) {
464 $_[HEAP]->{'RW'}->put( 'COMPRESSION ON' );
465 } else {
466 $_[HEAP]->{'RW'}->put( 'COMPRESSION OFF' );
467 }
468 }
469 } else {
470 # Doesn't talk lightspeed?
471 if ( DEBUG ) {
472 warn "Server doesn't talk Lightspeed -> input was: $line";
473 }
474  
475 # Shutdown!
476 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
477 }
478 } elsif ( $_[HEAP]->{'PHASE'} eq 'password' ) {
479 # Should be the password line
480 if ( $line eq 'PASSWORD OK' ) {
481 # Move on to the next phase
482 $_[HEAP]->{'PHASE'} = 'compression';
483  
484 # Do we want compression?
485 if ( $_[HEAP]->{'COMPRESSION'} ) {
486 $_[HEAP]->{'RW'}->put( 'COMPRESSION ON' );
487 } else {
488 $_[HEAP]->{'RW'}->put( 'COMPRESSION OFF' );
489 }
490 } else {
491 # Doesn't talk lightspeed?
492 if ( DEBUG ) {
493 warn "Server doesn't talk Lightspeed -> input was: $line";
494 }
495  
496 # Shutdown!
497 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
498 }
499 } elsif ( $_[HEAP]->{'PHASE'} eq 'compression' ) {
500 # Should be the compress line
501 if ( $line eq 'COMPRESSION NOT OK' ) {
502 # Server disagreed with our choice, dangit!
503 if ( DEBUG ) {
504 warn "Server didn't like our compression: $_[HEAP]->{'COMPRESSION'}";
505 }
506  
507 # Shutdown!
508 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
509 } else {
510 # Move on to the next phase
511 $_[HEAP]->{'PHASE'} = 'serializer';
512  
513 # Send the serializer line
514 if ( _Get_NextSerializer( $_[HEAP] ) ) {
515 $_[HEAP]->{'RW'}->put( 'SERIALIZER ' . $_[HEAP]->{'FILTER'}->[0] );
516 } else {
517 # Found no serializer, abort
518 if ( DEBUG ) {
519 warn "Exhausted our serializer options, no choice but to shut down";
520 }
521  
522 # Shutdown!
523 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
524 }
525 }
526 } elsif ( $_[HEAP]->{'PHASE'} eq 'serializer' ) {
527 # Should be the serializer line
528 if ( $line eq 'SERIALIZER OK' ) {
529 # Yay, we are all done...
530 $_[HEAP]->{'RW'}->put( 'DONE' );
531  
532 # We are connected!
533 $_[HEAP]->{'PHASE'} = 'connected';
534  
535 # Change the filter
536 $_[HEAP]->{'RW'}->set_filter( $_[HEAP]->{'FILTER'}->[1] );
537 $_[HEAP]->{'RW'}->event( 'InputEvent', 'InputHash' );
538  
539 # Let the Router know a link is up
540 $_[KERNEL]->call( $POE::Component::Lightspeed::Router::SES_ALIAS, 'link_up', $_[HEAP]->{'RW'}->ID, $_[HEAP]->{'MYKERNEL'}, $_[HEAP]->{'SERVER_KERNEL'}, 'Client' );
541 } else {
542 # Send the serializer line
543 if ( _Get_NextSerializer( $_[HEAP] ) ) {
544 $_[HEAP]->{'RW'}->put( 'SERIALIZER ' . $_[HEAP]->{'FILTER'}->[0] );
545 } else {
546 # Found no serializer, abort
547 if ( DEBUG ) {
548 warn "Exhausted our serializer options, no choice but to shut down";
549 }
550  
551 # Shutdown!
552 $_[KERNEL]->call( $_[SESSION], 'shutdown' );
553 }
554 }
555 }
556  
557 # All done!
558 return 1;
559 }
560  
561 # The main method of communication
562 sub InputHash {
563 # ARG0 = data, ARG1 = wheel id
564 my( $msg, $id ) = @_[ ARG0, ARG1 ];
565  
566 if ( DEBUG ) {
567 warn "Received packet from server $_[HEAP]->{'SERVER_IP'} - $_[HEAP]->{'SERVER_PORT'}:\n" . Data::Dumper::Dumper( $msg );
568 }
569  
570 # Send it off to the Router!
571 $_[KERNEL]->post( $POE::Component::Lightspeed::Router::SES_ALIAS, 'ACTION_' . $msg->[ MSG_ACTION ], $msg, $id );
572  
573 # Increment the packet count
574 $_[HEAP]->{'PACKETS_IN'}++;
575  
576 # All done!
577 return 1;
578 }
579  
580 # ReadWrite error
581 sub RWError {
582 # ARG0 = operation, ARG1 = error number, ARG2 = error string, ARG3 = wheel ID
583 my ( $operation, $errnum, $errstr, $wheel_id ) = @_[ ARG0 .. ARG3 ];
584  
585 # Debug stuff
586 if ( DEBUG ) {
587 warn "ReadWrite Wheel $wheel_id generated $operation error $errnum: $errstr\n";
588 }
589  
590 # Get rid of our RW wheel
591 undef $_[HEAP]->{'RW'};
592  
593 # Let the router know the link is down
594 if ( $_[HEAP]->{'PHASE'} eq 'connected' ) {
595 $_[KERNEL]->call( $POE::Component::Lightspeed::Router::SES_ALIAS, 'link_down', $wheel_id );
596 }
597  
598 # Shutdown ourself
599 $_[KERNEL]->yield( 'shutdown' );
600  
601 # Success!
602 return 1;
603 }
604  
605 # Sends a packet down the wire
606 sub Send_Packet {
607 # ARG0 = wheel id, ARG1 = packet
608 my $packet = $_[ARG1];
609  
610 # Sanity check
611 if ( ! defined $_[HEAP]->{'RW'} ) {
612 if ( DEBUG ) {
613 warn "Link is down, received a packet to send...";
614 }
615 return;
616 }
617  
618 # Add the timestamp
619 if ( ! defined $packet->[ MSG_TIMESTAMP ] ) {
620 $packet->[ MSG_TIMESTAMP ] = gettimeofday();
621 }
622  
623 if ( DEBUG ) {
624 warn "Sending packet to server $_[HEAP]->{'SERVER_IP'} - $_[HEAP]->{'SERVER_PORT'}:\n" . Data::Dumper::Dumper( $packet );
625 }
626  
627 # Send it...
628 $_[HEAP]->{'RW'}->put( $packet );
629  
630 # Increment the packet count
631 $_[HEAP]->{'PACKETS_OUT'}++;
632  
633 # All done!
634 return 1;
635 }
636  
637 # End of module
638 1;
639 __END__