SimpleHTTP.pm

filter: Statementstmt 51.4% 257 / 500 Branchbran 30.6% 65 / 212 Conditioncond 16.6% 19 / 114 MC/DCmcdc 0.0% 0 / 67 Subroutinesub 70.0% 42 / 60 Podpod 11.1% 1 / 9 totaltotal 39.9% 384 / 962 CC 247 SCAR 42.6
CC
247
Cov
41%
STREAM
272.0
__ANON__
272.0
DONE
108.3
CRAP 70.9
↑ Summary SimpleHTTP/Connection.pm »
1 package POE::Component::Server::SimpleHTTP;
2  
3 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 7 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 7 $VERSION = '2.22';
9  
10 7 ▶use POE;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use POE::Wheel::SocketFactory;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use POE::Wheel::ReadWrite;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 7 ▶use POE::Filter::HTTPD;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 7 ▶use POE::Filter::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 7 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 7 ▶use Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 7 ▶use HTTP::Date qw( time2str );
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 7 ▶use POE::Component::Server::SimpleHTTP::Connection;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 7 ▶use POE::Component::Server::SimpleHTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 7 ▶use POE::Component::Server::SimpleHTTP::State;
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 BEGIN {
26  
27 # Debug fun!
28 7 ▶ if ( !defined &DEBUG ) {
Subroutine BEGIN: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
unless (defined &POE::Component::Server::SimpleHTTP::DEBUG) 7 0 7
29 7 eval "sub DEBUG () { 0 }";
30 }
31  
32 # Our own definition of the max retries
33 7 ▶ if ( !defined &MAX_RETRIES ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined &POE::Component::Server::SimpleHTTP::MAX_RETRIES) 7 0 7
34 7 eval "sub MAX_RETRIES () { 5 }";
35 }
36 }
37  
38 7 ▶use MooseX::POE;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 7 ▶use Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
40  
41  
42 7 has 'alias' => (
43 is => 'ro',
44 );
45  
46 7 has 'address' => (
47 is => 'ro',
48 );
49  
50 has 'port' => (
51 is => 'ro',
52 0 ▶ default => sub { 0 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
53 7 writer => '_set_port',
54 );
55  
56 has 'hostname' => (
57 is => 'ro',
58 0 ▶ default => sub { require Sys::Hostname; return Sys::Hostname::hostname(); },
Subroutine __ANON__: not called CC=1 SCAR=6.9
59 7 );
60  
61 has 'proxymode' => (
62 is => 'ro',
63 isa => 'Bool',
64 6 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
65 7 );
66  
67 has 'keepalive' => (
68 is => 'ro',
69 isa => 'Bool',
70 5 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
71 7 );
72  
73 has 'sslkeycert' => (
74 is => 'ro',
75 0 ▶ isa => subtype 'ArrayRef' => where { scalar @$_ == 2 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
76 7 );
77  
78 7 has 'sslintermediatecacert' => (
79 is => 'ro',
80 isa => 'Str',
81 );
82  
83 has 'headers' => (
84 is => 'ro',
85 isa => 'HashRef',
86 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
87 7 );
88  
89 7 has 'handlers' => (
90 is => 'ro',
91 isa => 'ArrayRef',
92 required => 1,
93 writer => '_set_handlers',
94 );
95  
96 has 'errorhandler' => (
97 is => 'ro',
98 isa => 'HashRef',
99 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
100 7 );
101  
102 has 'loghandler' => (
103 is => 'ro',
104 isa => 'HashRef',
105 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
106 7 );
107  
108 has 'log2handler' => (
109 is => 'ro',
110 isa => 'HashRef',
111 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
112 7 );
113  
114 has 'setuphandler' => (
115 is => 'ro',
116 isa => 'HashRef',
117 0 ▶ default => sub {{}},
Subroutine __ANON__: not called CC=1 SCAR=6.9
118 7 );
119  
120 has 'retries' => (
121 traits => ['Counter'],
122 is => 'ro',
123 isa => 'Num',
124 6 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
125 7 handles => {
126 inc_retry => 'inc',
127 dec_retry => 'dec',
128 reset_retries => 'reset',
129 },
130 );
131  
132 has '_requests' => (
133 is => 'ro',
134 isa => 'HashRef',
135 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
136 7 init_arg => undef,
137 clearer => '_clear_requests',
138 );
139  
140 has '_connections' => (
141 is => 'ro',
142 isa => 'HashRef',
143 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
144 7 init_arg => undef,
145 clearer => '_clear_connections',
146 );
147  
148 has '_chunkcount' => (
149 is => 'ro',
150 isa => 'HashRef',
151 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
152 7 init_arg => undef,
153 clearer => '_clear_chunkcount',
154 );
155  
156 has '_responses' => (
157 is => 'ro',
158 isa => 'HashRef',
159 6 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
160 7 init_arg => undef,
161 clearer => '_clear_responses',
162 );
163  
164 7 has '_factory' => (
165 is => 'ro',
166 isa => 'POE::Wheel::SocketFactory',
167 init_arg => undef,
168 clearer => '_clear_factory',
169 writer => '_set_factory',
170 );
171  
172 sub BUILDARGS {
173 6 ▶ my $class = shift;
Subroutine BUILDARGS: called CC=7 SCAR=32.4
Pod documented
174 6 my %args = @_;
175 6 $args{lc $_} = delete $args{$_} for keys %args;
176  
177 6 ▶ if ( $args{sslkeycert} and ref $args{sslkeycert} eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"sslkeycert"} and ref $args{"sslkeycert"} eq "ARRAY" and scalar @{$args{"sslkeycert"};} == 2) 0 6 6
Condition33%2/6
$args{"sslkeycert"} and ref $args{"sslkeycert"} eq "ARRAY" and scalar @{$args{"sslkeycert"};} == 2
!ll&&!rl&&r
600
$args{"sslkeycert"} and ref $args{"sslkeycert"} eq "ARRAY"
!ll&&!rl&&r
600
MC/DC0%0/3
$args{"sslkeycert"} and ref $args{"sslkeycert"} eq "ARRAY" and scalar @{$args{"sslkeycert"};} == 2
$args{"sslkeycert"} ref $args{"sslkeycert"} eq "ARRAY" scalar @{$args{"sslkeycert"};} == 2
Truth table25%1/4
A and B and C
A= $args{"sslkeycert"}B= ref $args{"sslkeycert"} eq "ARRAY"C= scalar @{$args{"sslkeycert"};} == 2
ABCresult
0XX0
10X0
1100
1111
178 0 and scalar @{ $args{sslkeycert} } == 2 ) {
179  
180 0 eval {
181 0 require POE::Component::SSLify;
182 0 import POE::Component::SSLify
183 qw( SSLify_Options SSLify_GetSocket Server_SSLify SSLify_GetCipher SSLify_GetCTX );
184 0 SSLify_Options( @{ $args{sslkeycert} } );
185 };
186 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
187 0 warn "Unable to load PoCo::SSLify -> $@" if DEBUG;
188 0 delete $args{sslkeycert};
189 }
190 else {
191 0 ▶ if ( $args{sslintermediatecacert} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"sslintermediatecacert"}) 0 0 0
192 0 my $ctx = SSLify_GetCTX();
193 0 Net::SSLeay::CTX_load_verify_locations($ctx, $args{sslintermediatecacert}, '');
194 }
195 }
196 }
197  
198 6 return $class->SUPER::BUILDARGS(%args);
199 }
200  
201 sub session_id {
202 0 ▶ shift->get_session_id;
Subroutine session_id: not called CC=1 SCAR=6.9
Pod undocumented
203 }
204  
205 sub getsockname {
206 0 ▶ shift->_factory->getsockname;
Subroutine getsockname: not called CC=1 SCAR=6.9
Pod undocumented
207 }
208  
209 sub shutdown {
210 0 ▶ my $self = shift;
Subroutine shutdown: not called CC=1 SCAR=6.9
Pod undocumented
211 0 $poe_kernel->call( $self->get_session_id, 'SHUTDOWN', @_ );
212 }
213  
214 # This subroutine, when SimpleHTTP exits, will search for leaks
215 sub STOP {
216 6 ▶ my $self = $_[OBJECT];
Subroutine STOP: called CC=2 SCAR=6.9
Pod undocumented
217 # Loop through all of the requests
218 6 foreach my $req ( keys %{ $self->_requests } ) {
219  
220 # Bite the programmer!
221 warn 'Did not get DONE/CLOSE event for Wheel ID '
222 . $req
223 . ' from IP '
224 5 . $self->_requests->{$req}->response->connection->remote_ip;
225 }
226  
227 # All done!
228 6 return 1;
229 }
230  
231 sub START {
232 6 ▶ my ($kernel,$self) = @_[KERNEL,OBJECT];
Subroutine START: called CC=3 SCAR=11.2
Pod undocumented
233 6 ▶ $kernel->alias_set( $self->alias ) if $self->alias;
Branch: 1 branch
BranchTrueFalseTotal
if $self->alias 6 0 6
234 6 ▶ $kernel->refcount_increment( $self->get_session_id, __PACKAGE__ )
Branch: 1 branch
BranchTrueFalseTotal
unless $self->alias 0 6 6
235 unless $self->alias;
236 6 MassageHandlers( $self->handlers );
237 # Start Listener
238 6 $kernel->yield( 'start_listener' );
239 6 return;
240 }
241  
242 # 'SHUTDOWN'
243 # Stops the server!
244 event 'SHUTDOWN' => sub {
245 0 ▶ my ($kernel,$self,$graceful) = @_[KERNEL,OBJECT,ARG0];
Subroutine __ANON__: not called CC=13 SCAR=39.7
Subroutine SHUTDOWN: called CC=13 SCAR=39.7
246 # Shutdown the SocketFactory wheel
247 0 ▶ $self->_clear_factory if $self->_factory;
Branch: 2 branches
BranchTrueFalseTotal
if $self->_factory 0 0 0
if $self->_factory 1 2 3
248  
249 # Debug stuff
250 0 warn 'Stopped listening for new connections!' if DEBUG;
251  
252 # Are we gracefully shutting down or not?
253 0 ▶ if ( $graceful ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($graceful) 0 0 0
if ($graceful) 2 1 3
254  
255 # Check for existing requests and keep-alive connections
256 0 ▶ if ( keys( %{ $self->_requests } ) == 0
Branch: 2 branches
BranchTrueFalseTotal
if (keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0) 0 0 0
if (keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0) 2 0 2
Condition16%1/6
keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0
!ll&&!rl&&r
000
keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0
!ll&&!rl&&r
200
MC/DC0%0/2
keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0
keys %{$self->_requests;} == 0 keys %{$self->_connections;} == 0
MC/DC0%0/2
keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0
keys %{$self->_requests;} == 0 keys %{$self->_connections;} == 0
Truth table0%0/3
A and B
A= keys %{$self->_requests;} == 0B= keys %{$self->_connections;} == 0
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= keys %{$self->_requests;} == 0B= keys %{$self->_connections;} == 0
ABresult
0X0
100
111
257 0 and keys( %{ $self->_connections } ) == 0 )
258 {
259  
260 # Alright, shutdown anyway
261  
262 # Delete our alias
263 0 $kernel->alias_remove( $_ ) for $kernel->alias_list();
264 0 ▶ $kernel->refcount_decrement( $self->get_session_id, __PACKAGE__ )
Branch: 2 branches
BranchTrueFalseTotal
unless $self->alias 0 0 0
unless $self->alias 2 0 2
265 unless $self->alias;
266  
267 # Debug stuff
268 0 warn 'Stopped SimpleHTTP gracefully, no requests left' if DEBUG;
269 }
270  
271 # All done!
272 0 return 1;
273 }
274  
275 # Forcibly close all sockets that are open
276 0 foreach my $S ( $self->_requests, $self->_connections ) {
277 0 foreach my $conn ( keys %$S ) {
278  
279 # Can't call method "shutdown_input" on an undefined value at
280 # /usr/lib/perl5/site_perl/5.8.2/POE/Component/Server/SimpleHTTP.pm line 323.
281 0 ▶ if ( defined $S->{$conn}->wheel
Branch: 2 branches
BranchTrueFalseTotal
if (defined $S->{$conn}->wheel and defined $S->{$conn}->wheel->get_input_handle) 0 0 0
if (defined $S->{$conn}->wheel and defined $S->{$conn}->wheel->get_input_handle) 2 0 2
Condition16%1/6
defined $S->{$conn}->wheel and defined $S->{$conn}->wheel->get_input_handle
!ll&&!rl&&r
000
defined $S->{$conn}->wheel and defined $S->{$conn}->wheel->get_input_handle
!ll&&!rl&&r
002
MC/DC0%0/2
defined $S->{$conn}->wheel and defined $S->{$conn}->wheel->get_input_handle
defined $S->{$conn}->wheel defined $S->{$conn}->wheel->get_input_handle
MC/DC0%0/2
defined $S->{$conn}->wheel and defined $S->{$conn}->wheel->get_input_handle
defined $S->{$conn}->wheel defined $S->{$conn}->wheel->get_input_handle
Truth table0%0/3
A and B
A= defined $S->{$conn}->wheelB= defined $S->{$conn}->wheel->get_input_handle
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= defined $S->{$conn}->wheelB= defined $S->{$conn}->wheel->get_input_handle
ABresult
0X0
100
111
282 and defined $S->{$conn}->wheel->get_input_handle() )
283 {
284 0 $S->{$conn}->close_wheel;
285 }
286  
287 # Delete this request
288 0 delete $S->{$conn};
289 }
290 }
291  
292 # Delete our alias
293 0 $kernel->alias_remove( $_ ) for $kernel->alias_list();
294 0 ▶ $kernel->refcount_decrement( $self->get_session_id, __PACKAGE__ )
Branch: 2 branches
BranchTrueFalseTotal
unless $self->alias 0 0 0
unless $self->alias 0 3 3
295 unless $self->alias;
296  
297 # Debug stuff
298 0 warn 'Successfully stopped SimpleHTTP' if DEBUG;
299  
300 # Return success
301 0 return 1;
302 7 };
303  
304 # Sets up the SocketFactory wheel :)
305 event 'start_listener' => sub {
306 4 ▶ my ($kernel,$self,$noinc) = @_[KERNEL,OBJECT,ARG0];
Subroutine __ANON__: called CC=10 SCAR=27.2
307  
308 4 warn "Creating SocketFactory wheel now\n" if DEBUG;
309  
310 # Check if we should set up the wheel
311 4 ▶ if ( $self->retries == MAX_RETRIES ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->retries == 5) { } 0 4 4
312 0 die 'POE::Component::Server::SimpleHTTP tried '
313 . MAX_RETRIES
314 . ' times to create a Wheel and is giving up...';
315 }
316 else {
317  
318 4 ▶ $self->inc_retry unless $noinc;
Branch: 1 branch
BranchTrueFalseTotal
unless $noinc 4 0 4
319  
320 # Create our own SocketFactory Wheel :)
321 4 ▶ my $factory = POE::Wheel::SocketFactory->new(
Branch: 1 branch
BranchTrueFalseTotal
$self->address ? : 4 0 4
322 BindPort => $self->port,
323 ( $self->address ? ( BindAddress => $self->address ) : () ),
324 Reuse => 'yes',
325 SuccessEvent => 'got_connection',
326 FailureEvent => 'listener_error',
327 );
328  
329 4 my ( $port, $address ) =
330 sockaddr_in( $factory->getsockname );
331 4 ▶ $self->_set_port( $port ) if $self->port == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->port == 0 4 0 4
332  
333 4 $self->_set_factory( $factory );
334  
335 4 ▶ if ( $self->setuphandler ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->setuphandler) 4 0 4
336 4 my $setuphandler = $self->setuphandler;
337 4 ▶ if ( $setuphandler->{POSTBACK} and
Branch: 1 branch
BranchTrueFalseTotal
if ($setuphandler->{'POSTBACK'} and ref $setuphandler->{'POSTBACK'} eq 'POE::Session::AnonEvent') { } 0 4 4
Condition33%1/3
$setuphandler->{"POSTBACK"} and ref $setuphandler->{"POSTBACK"} eq "POE::Session::AnonEvent"
!ll&&!rl&&r
400
MC/DC0%0/2
$setuphandler->{"POSTBACK"} and ref $setuphandler->{"POSTBACK"} eq "POE::Session::AnonEvent"
$setuphandler->{"POSTBACK"} ref $setuphandler->{"POSTBACK"} eq "POE::Session::AnonEvent"
Truth table33%1/3
A and B
A= $setuphandler->{"POSTBACK"}B= ref $setuphandler->{"POSTBACK"} eq "POE::Session::AnonEvent"
ABresult
0X0
100
111
338 ref $setuphandler->{POSTBACK} eq 'POE::Session::AnonEvent' ) {
339 0 $setuphandler->{POSTBACK}->( $port, $address );
340 }
341 else {
342 $kernel->post(
343 $setuphandler->{'SESSION'},
344 $setuphandler->{'EVENT'},
345 $port, $address,
346 4 ▶ ) if $setuphandler->{'SESSION'} and $setuphandler->{'EVENT'};
Branch: 1 branch
BranchTrueFalseTotal
if $setuphandler->{"SESSION"} and $setuphandler->{"EVENT"} 4 0 4
Condition33%1/3
$setuphandler->{"SESSION"} and $setuphandler->{"EVENT"}
!ll&&!rl&&r
004
MC/DC0%0/2
$setuphandler->{"SESSION"} and $setuphandler->{"EVENT"}
$setuphandler->{"SESSION"} $setuphandler->{"EVENT"}
Truth table33%1/3
A and B
A= $setuphandler->{"SESSION"}B= $setuphandler->{"EVENT"}
ABresult
0X0
100
111
347 }
348 }
349 }
350  
351 4 return 1;
352 7 };
353  
354 # Got some sort of error from SocketFactory
355 event listener_error => sub {
356 0 ▶ my ($kernel,$self,$operation,$errnum,$errstr,$wheel_id) = @_[KERNEL,OBJECT,ARG0..ARG3];
Subroutine __ANON__: not called CC=1 SCAR=6.9
357 0 warn
358 "SocketFactory Wheel $wheel_id generated $operation error $errnum: $errstr\n"
359 if DEBUG;
360  
361 0 $self->call( 'start_listener' );
362 0 return 1;
363 7 };
364  
365 # 'STARTLISTEN'
366 # Starts listening on the socket
367 event 'STARTLISTEN' => sub {
368 0 ▶ warn 'STARTLISTEN called, resuming accepts on SocketFactory'
Subroutine __ANON__: not called CC=1 SCAR=6.9
369 if DEBUG;
370 0 $_[OBJECT]->call( 'start_listener', 'noinc' );
371 0 return 1;
372 7 };
373  
374 # 'STOPLISTEN'
375 # Stops listening on the socket
376 event 'STOPLISTEN' => sub {
377 0 ▶ my $self = $_[OBJECT];
Subroutine STOPLISTEN: not called CC=2 SCAR=17.9
378 0 warn 'STOPLISTEN called, pausing accepts on SocketFactory'
379 if DEBUG;
380 0 ▶ $self->_clear_factory if $self->_factory;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_factory 0 0 0
381 0 return 1;
382 7 };
383  
384 # 'SETHANDLERS'
385 # Sets the HANDLERS
386 event 'SETHANDLERS' => sub {
387 0 ▶ my ($self,$handlers) = @_[OBJECT,ARG0];
Subroutine __ANON__: not called CC=1 SCAR=6.9
388 0 MassageHandlers($handlers);
389 0 $self->_set_handlers( $handlers );
390 0 return 1;
391 7 };
392  
393 # 'GETHANDLERS'
394 # Gets the HANDLERS
395 event 'GETHANDLERS' => sub {
396 0 ▶ my ($kernel,$self,$session,$event ) = @_[KERNEL,OBJECT,ARG0,ARG1];
Subroutine __ANON__: not called CC=4 SCAR=30.0
397 0 ▶ return unless $session and $event;
Branch: 1 branch
BranchTrueFalseTotal
unless $session and $event 0 0 0
Condition0%0/3
$session and $event
!ll&&!rl&&r
000
MC/DC0%0/2
$session and $event
$session $event
Truth table0%0/3
A and B
A= $sessionB= $event
ABresult
0X0
100
111
398 0 require Storable;
399 0 my $handlers = Storable::dclone( $self->handlers );
400 0 delete $_->{'RE'} for @{ $handlers };
401 0 $kernel->post( $session, $event, $handlers );
402 0 return 1;
403 7 };
404  
405 # This subroutine massages the HANDLERS for internal use
406 # Should probably support POSTBACK/CALLBACK
407 sub MassageHandlers {
408 6 ▶ my $handler = shift;
Subroutine MassageHandlers: called CC=15 SCAR=34.9
Pod undocumented
409  
410 # Make sure it is ref to array
411 6 ▶ if ( !ref $handler or ref($handler) ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $handler or ref $handler ne "ARRAY") 0 6 6
Condition33%1/3
not ref $handler or ref $handler ne "ARRAY"
l!l&&r!l&&!r
006
MC/DC0%0/2
not ref $handler or ref $handler ne "ARRAY"
not ref $handler ref $handler ne "ARRAY"
Truth table33%1/3
not(A) or B
A= not ref $handlerB= ref $handler ne "ARRAY"
ABresult
1X1
011
000
412 0 croak("HANDLERS is not a ref to an array!");
413 }
414  
415 # Massage the handlers
416 6 my $count = 0;
417 6 ▶ while ( $count < scalar(@$handler) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count < scalar @$handler) 18 6 24
418  
419 # Must be ref to hash
420 18 ▶ if ( ref $handler->[$count] and ref( $handler->[$count] ) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $handler->[$count] and ref $handler->[$count] eq 'HASH') { } 18 0 18
Condition33%1/3
ref $handler->[$count] and ref $handler->[$count] eq "HASH"
!ll&&!rl&&r
0018
MC/DC0%0/2
ref $handler->[$count] and ref $handler->[$count] eq "HASH"
ref $handler->[$count] ref $handler->[$count] eq "HASH"
Truth table33%1/3
A and B
A= ref $handler->[$count]B= ref $handler->[$count] eq "HASH"
ABresult
0X0
100
111
421  
422 # Make sure all the keys are uppercase
423 $handler->[$count]->{ uc $_ } = delete $handler->[$count]->{$_}
424 18 for keys %{ $handler->[$count] };
425  
426 # Make sure it got the 3 parts necessary
427 18 ▶ if ( !exists $handler->[$count]->{'SESSION'}
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $handler->[$count]{"SESSION"} and defined $handler->[$count]{"SESSION"}) 0 18 18
Condition33%1/3
exists $handler->[$count]{"SESSION"} and defined $handler->[$count]{"SESSION"}
!ll&&!rl&&r
0018
MC/DC0%0/2
exists $handler->[$count]{"SESSION"} and defined $handler->[$count]{"SESSION"}
exists $handler->[$count]{"SESSION"} defined $handler->[$count]{"SESSION"}
Truth table33%1/3
A and B
A= exists $handler->[$count]{"SESSION"}B= defined $handler->[$count]{"SESSION"}
ABresult
0X0
100
111
428 or !defined $handler->[$count]->{'SESSION'} )
429 {
430 0 croak("HANDLER number $count does not have a SESSION argument!");
431 }
432 18 ▶ if ( !exists $handler->[$count]->{'EVENT'}
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $handler->[$count]{"EVENT"} and defined $handler->[$count]{"EVENT"}) 0 18 18
Condition33%1/3
exists $handler->[$count]{"EVENT"} and defined $handler->[$count]{"EVENT"}
!ll&&!rl&&r
0018
MC/DC0%0/2
exists $handler->[$count]{"EVENT"} and defined $handler->[$count]{"EVENT"}
exists $handler->[$count]{"EVENT"} defined $handler->[$count]{"EVENT"}
Truth table33%1/3
A and B
A= exists $handler->[$count]{"EVENT"}B= defined $handler->[$count]{"EVENT"}
ABresult
0X0
100
111
433 or !defined $handler->[$count]->{'EVENT'} )
434 {
435 0 croak("HANDLER number $count does not have an EVENT argument!");
436 }
437 18 ▶ if ( !exists $handler->[$count]->{'DIR'}
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $handler->[$count]{"DIR"} and defined $handler->[$count]{"DIR"}) 0 18 18
Condition33%1/3
exists $handler->[$count]{"DIR"} and defined $handler->[$count]{"DIR"}
!ll&&!rl&&r
0018
MC/DC0%0/2
exists $handler->[$count]{"DIR"} and defined $handler->[$count]{"DIR"}
exists $handler->[$count]{"DIR"} defined $handler->[$count]{"DIR"}
Truth table33%1/3
A and B
A= exists $handler->[$count]{"DIR"}B= defined $handler->[$count]{"DIR"}
ABresult
0X0
100
111
438 or !defined $handler->[$count]->{'DIR'} )
439 {
440 0 croak("HANDLER number $count does not have a DIR argument!");
441 }
442  
443 # Convert SESSION to ID
444 18 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($handler->[$count]{"SESSION"}, "POE::Session")) 0 18 18
445 UNIVERSAL::isa( $handler->[$count]->{'SESSION'}, 'POE::Session' ) )
446 {
447 $handler->[$count]->{'SESSION'} =
448 0 $handler->[$count]->{'SESSION'}->ID;
449 }
450  
451 # Convert DIR to qr// format
452 18 my $regex = undef;
453 18 eval { $regex = qr/$handler->[ $count ]->{'DIR'}/ };
454  
455 # Check for errors
456 18 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 18 18
457 0 croak("HANDLER number $count has a malformed DIR -> $@");
458 }
459 else {
460  
461 # Store it!
462 18 $handler->[$count]->{'RE'} = $regex;
463 }
464 }
465 else {
466 0 croak("HANDLER number $count is not a reference to a HASH!");
467 }
468  
469 # Done with this one!
470 18 $count++;
471 }
472  
473 # Got here, success!
474 6 return 1;
475 }
476  
477 # 'Got_Connection'
478 # The actual manager of connections
479 event 'got_connection' => sub {
480 6 ▶ my ($kernel,$self,$socket,$peeraddr,$peerport) = @_[KERNEL,OBJECT,ARG0..ARG2];
Subroutine got_connection: called CC=3 SCAR=14.7
481  
482  
483 # Should we SSLify it?
484 6 ▶ if ( $self->sslkeycert ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sslkeycert) 0 6 6
485  
486 # SSLify it!
487 0 eval { $socket = Server_SSLify($socket) };
488 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
489 0 warn "Unable to turn on SSL for connection from "
490 . Socket::inet_ntoa( $peeraddr )
491 . " -> $@";
492 0 close $socket;
493 0 return 1;
494 }
495 }
496  
497 # Set up the Wheel to read from the socket
498 6 my $wheel = POE::Wheel::ReadWrite->new(
499 Handle => $socket,
500 Filter => POE::Filter::HTTPD->new(),
501 InputEvent => 'got_input',
502 FlushedEvent => 'got_flush',
503 ErrorEvent => 'got_error',
504 );
505  
506 6 if ( DEBUG and keys %{ $self->_connections } ) {
507  
508 # use Data::Dumper;
509 warn "conn id=", $wheel->ID, " [",
510 join( ', ', keys %{ $self->_connections } ), "]";
511 }
512  
513 # Save this wheel!
514 # 0 = wheel, 1 = Output done?, 2 = SimpleHTTP::Response object, 3 == request, 4 == streaming?
515 6 $self->_requests->{ $wheel->ID } =
516 POE::Component::Server::SimpleHTTP::State->new( wheel => $wheel );
517  
518 # Debug stuff
519 6 if (DEBUG) {
520 warn "Got_Connection completed creation of ReadWrite wheel ( "
521 . $wheel->ID . " )";
522 }
523  
524 # Success!
525 6 return 1;
526 7 };
527  
528 # 'Got_Input'
529 # Finally got input, set some stuff and send away!
530 event 'got_input' => sub {
531 6 ▶ my ($kernel,$self,$request,$id) = @_[KERNEL,OBJECT,ARG0,ARG1];
Subroutine __ANON__: called CC=23 SCAR=46.7
532 6 my $connection;
533  
534 # This whole thing is a mess. Keep-Alive was bolted on and it
535 # shows. Streaming is unpredictable. There are checks everywhere
536 # because it leaks wheels. *sigh*
537  
538 # Was this request Keep-Alive?
539 6 ▶ if ( $self->_connections->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_connections->{$id}) 0 6 6
540 0 my $state = delete $self->_connections->{$id};
541 0 $state->reset;
542 0 $connection = $state->connection;
543 0 $state->clear_connection;
544 0 $self->_requests->{$id} = $state;
545 0 warn "Keep-alive id=$id next request..." if DEBUG;
546 }
547  
548 # Quick check to see if the socket died already...
549 # Initially reported by Tim Wood
550 6 ▶ unless ( $self->_requests->{$id}->wheel_alive ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_requests->{$id}->wheel_alive) 0 6 6
551 0 warn 'Got a request, but socket died already!' if DEBUG;
552 # Destroy this wheel!
553 0 $self->_requests->{$id}->close_wheel;
554 0 delete $self->_requests->{$id};
555 0 return;
556 }
557  
558 SWITCH: {
559  
560 6 ▶ last SWITCH if $connection; # connection was kept-alive
Branch: 1 branch
BranchTrueFalseTotal
if $connection 0 6 6
561  
562 # Directly access POE::Wheel::ReadWrite's HANDLE_INPUT -> to get the socket itself
563 # Hmm, if we are SSL, then have to do an extra step!
564 6 ▶ if ( $self->sslkeycert ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sslkeycert) 0 6 6
565 $connection = POE::Component::Server::SimpleHTTP::Connection->new(
566 SSLify_GetSocket(
567 0 $self->_requests->{$id}->wheel->get_input_handle() )
568 );
569 0 last SWITCH;
570 }
571 $connection = POE::Component::Server::SimpleHTTP::Connection->new(
572 6 $self->_requests->{$id}->wheel->get_input_handle()
573 );
574 }
575  
576 # The HTTP::Response object, the path
577 6 my ( $response, $path, $malformed_req );
578  
579 # Check if it is HTTP::Request or Response
580 # Quoting POE::Filter::HTTPD
581 # The HTTPD filter parses the first HTTP 1.0 request from an incoming stream into an
582 # HTTP::Request object (if the request is good) or an HTTP::Response object (if the
583 # request was malformed).
584  
585 6 ▶ if ( $request->isa('HTTP::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->isa('HTTP::Response')) { } 0 6 6
586 # Make the request nothing
587 0 $response = $request;
588 0 $request = undef;
589  
590 # Mark that this is a malformed request
591 0 $malformed_req = 1;
592  
593 # Hack it to simulate POE::Component::Server::SimpleHTTP::Response->new( $id, $conn );
594 0 bless( $response, 'POE::Component::Server::SimpleHTTP::Response' );
595 0 $response->_WHEEL( $id );
596  
597 0 $response->set_connection( $connection );
598  
599 # Set the path to an empty string
600 0 $path = '';
601 }
602 else {
603 6 ▶ unless ( $self->proxymode ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->proxymode) { } 0 6 6
604 # Add stuff it needs!
605 6 my $uri = $request->uri;
606 6 $uri->scheme('http');
607 6 $uri->host( $self->hostname );
608 6 $uri->port( $self->port );
609  
610 # Get the path
611 6 $path = $uri->path();
612 6 ▶ if ( !defined $path or $path eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $path or $path eq "") 0 6 6
Condition33%1/3
not defined $path or $path eq ""
l!l&&r!l&&!r
006
MC/DC0%0/2
not defined $path or $path eq ""
not defined $path $path eq ""
Truth table33%1/3
not(A) or B
A= not defined $pathB= $path eq ""
ABresult
1X1
011
000
613 # Make it the default handler
614 0 $path = '/';
615 }
616 }
617 else {
618 # We're in PROXYMODE set the path to the full URI
619 0 $path = $request->uri->as_string();
620 }
621  
622 # Get the response
623 6 $response =
624 POE::Component::Server::SimpleHTTP::Response->new( $id, $connection );
625  
626 # Stuff the default headers
627 0 $response->header( %{ $self->headers } )
628 6 ▶ if keys( %{ $self->headers } ) != 0;
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$self->headers;} != 0 0 6 6
629 }
630  
631 # Check if the SimpleHTTP::Connection object croaked ( happens when sockets just disappear )
632 6 ▶ unless ( defined $response->connection ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $response->connection) 0 6 6
633 # Debug stuff
634 0 warn "could not make connection object" if DEBUG;
635 # Destroy this wheel!
636 0 $self->_requests->{$id}->close_wheel;
637 0 delete $self->_requests->{$id};
638 0 return;
639 }
640  
641 # If we used SSL, turn on the flag!
642 6 ▶ if ( $self->sslkeycert ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sslkeycert) 0 6 6
643 0 $response->connection->ssl(1);
644  
645 # Put the cipher type for people who want it
646 $response->connection->sslcipher(
647 0 SSLify_GetCipher( $self->_requests->{$id}->wheel->get_input_handle() )
648 );
649 }
650  
651 6 ▶ if ( !defined( $request ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $request) 0 6 6
652 0 $self->_requests->{$id}->close_wheel;
653 0 delete $self->_requests->{$id};
654 0 return;
655 }
656  
657 # Add this response to the wheel
658 6 $self->_requests->{$id}->set_response( $response );
659 6 $self->_requests->{$id}->set_request( $request );
660 6 $response->connection->ID($id);
661  
662 # If they have a log handler registered, send out the needed information
663 # TODO if we received a malformed request, we will not have a request object
664 # We need to figure out what we're doing because they can't always expect to have
665 # a request object, or should we keep it from being ?undef'd?
666  
667 6 ▶ if ( $self->loghandler and scalar keys %{ $self->loghandler } == 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->loghandler and scalar keys %{$self->loghandler;} == 2) 0 6 6
Condition33%1/3
$self->loghandler and scalar keys %{$self->loghandler;} == 2
!ll&&!rl&&r
060
MC/DC0%0/2
$self->loghandler and scalar keys %{$self->loghandler;} == 2
$self->loghandler scalar keys %{$self->loghandler;} == 2
Truth table33%1/3
A and B
A= $self->loghandlerB= scalar keys %{$self->loghandler;} == 2
ABresult
0X0
100
111
668 0 $! = undef;
669 $kernel->post(
670 $self->loghandler->{'SESSION'},
671 0 $self->loghandler->{'EVENT'},
672 $request, $response->connection->remote_ip()
673 );
674  
675 # Warn if we had a problem dispatching to the log handler above
676 warn(
677 "I had a problem posting to event '",
678 $self->loghandler->{'EVENT'},
679 "' of the log handler alias '",
680 0 ▶ $self->loghandler->{'SESSION'},
Branch: 1 branch
BranchTrueFalseTotal
if $! 0 0 0
681 "'. As reported by Kernel: '$!', perhaps the alias is spelled incorrectly for this handler?"
682 ) if $!;
683 }
684  
685 # If we received a malformed request then
686 # let's not try to dispatch to a handler
687  
688 6 ▶ if ($malformed_req) {
Branch: 1 branch
BranchTrueFalseTotal
if ($malformed_req) 0 6 6
689 # Just push out the response we got from POE::Filter::HTTPD saying your request was bad
690 $kernel->post(
691 $self->errorhandler->{SESSION},
692 $self->errorhandler->{EVENT},
693 'BadRequest (by POE::Filter::HTTPD)',
694 $response->connection->remote_ip()
695 0 ▶ ) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
Branch: 1 branch
BranchTrueFalseTotal
if $self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"} 0 0 0
Condition0%0/6
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
!ll&&!rl&&r
000
$self->errorhandler and $self->errorhandler->{"SESSION"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
$self->errorhandler $self->errorhandler->{"SESSION"} $self->errorhandler->{"EVENT"}
Truth table0%0/4
A and B and C
A= $self->errorhandlerB= $self->errorhandler->{"SESSION"}C= $self->errorhandler->{"EVENT"}
ABCresult
0XX0
10X0
1100
1111
696 0 $kernel->yield( 'DONE', $response );
697 0 return;
698 }
699  
700 # Find which handler will handle this one
701 6 foreach my $handler ( @{ $self->handlers } ) {
702  
703 # Check if this matches
704 18 ▶ if ( $path =~ $handler->{'RE'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /$handler->{"RE"}/) 5 13 18
705  
706 # Send this off!
707 $kernel->post( $handler->{'SESSION'}, $handler->{'EVENT'}, $request,
708 5 $response, $handler->{'DIR'}, );
709  
710 # Make sure we croak if we have an issue posting
711 5 ▶ croak(
Branch: 1 branch
BranchTrueFalseTotal
if $! 5 0 5
712 "I had a problem posting to event $handler->{'EVENT'} of session $handler->{'SESSION'} for DIR handler '$handler->{'DIR'}'",
713 ". As reported by Kernel: '$!', perhaps the session name is spelled incorrectly for this handler?"
714 ) if $!;
715  
716 # All done!
717 0 return;
718 }
719 }
720  
721 # If we reached here, no handler was able to handle it...
722 # Set response code to 404 and tell the client we didn't find anything
723 1 $response->code(404);
724 1 $response->content('404 Not Found');
725 1 $kernel->yield( 'DONE', $response );
726 1 return;
727 7 };
728  
729 # 'Got_Flush'
730 # Finished with a request!
731 event 'got_flush' => sub {
732 1 ▶ my ($kernel,$self,$id) = @_[KERNEL,OBJECT,ARG0];
Subroutine got_flush: called CC=8 SCAR=31.3
733  
734 1 ▶ return unless defined $self->_requests->{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->_requests->{$id} 0 1 1
735  
736 # Debug stuff
737 1 warn "Got Flush event for wheel ID ( $id )" if DEBUG;
738  
739 1 ▶ if ( $self->_requests->{$id}->streaming ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_requests->{$id}->streaming) 0 1 1
740 # Do the stream !
741 0 warn "Streaming in progress ...!" if DEBUG;
742 0 return;
743 }
744  
745 # Check if we are shutting down
746 1 ▶ if ( $self->_requests->{$id}->done ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_requests->{$id}->done) { } 1 0 1
747  
748 1 ▶ if ( $self->must_keepalive( $id ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->must_keepalive($id)) { } 0 1 1
749 0 warn "Keep-alive id=$id ..." if DEBUG;
750 0 my $state = delete $self->_requests->{$id};
751 0 $state->set_connection( $state->response->connection );
752 0 $state->reset;
753 0 $self->_connections->{$id} = $state;
754 0 delete $self->_chunkcount->{$id};
755 0 delete $self->_responses->{$id};
756 }
757 else {
758 # Shutdown read/write on the wheel
759 1 $self->_requests->{$id}->close_wheel;
760 1 delete $self->_requests->{$id};
761 }
762  
763 }
764 else {
765  
766 # Ignore this, eh?
767 0 if (DEBUG) {
768 warn
769 "Got Flush event for socket ( $id ) when we did not send anything!";
770 }
771 }
772  
773 # Alright, do we have to shutdown?
774 1 ▶ unless ( $self->_factory ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_factory) 0 1 1
775 # Check to see if we have any more requests
776 0 ▶ if ( keys( %{ $self->_requests } ) == 0
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0) 0 0 0
Condition0%0/3
keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0
!ll&&!rl&&r
000
MC/DC0%0/2
keys %{$self->_requests;} == 0 and keys %{$self->_connections;} == 0
keys %{$self->_requests;} == 0 keys %{$self->_connections;} == 0
Truth table0%0/3
A and B
A= keys %{$self->_requests;} == 0B= keys %{$self->_connections;} == 0
ABresult
0X0
100
111
777 0 and keys( %{ $self->_connections } ) == 0 )
778 {
779 # Shutdown!
780 0 $kernel->yield('SHUTDOWN');
781 }
782 }
783  
784 # Success!
785 1 return 1;
786 7 };
787  
788 # should we keep-alive the connection?
789 sub must_keepalive {
790 1 ▶ my ( $self, $id ) = @_;
Subroutine must_keepalive: called CC=10 SCAR=44.3
Pod undocumented
791  
792 1 ▶ return unless $self->keepalive;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->keepalive 1 0 1
793  
794 0 my $resp = $self->_requests->{$id}->response;
795 0 my $req = $self->_requests->{$id}->request;
796  
797 # error = close
798 0 ▶ return 0 if $resp->is_error;
Branch: 1 branch
BranchTrueFalseTotal
if $resp->is_error 0 0 0
799  
800 # Connection is a comma-seperated header
801 0 ▶ my $conn = lc ($req->header('Connection') || '');
Condition0%0/2
$req->header('Connection') || ''
l!l
00
MC/DC0%0/1
$req->header('Connection') || ''
$req->header('Connection')
Truth table0%0/2
A
A= $req->header('Connection')
Aresult
11
00
802 0 ▶ return 0 if ",$conn," =~ /,\s*close\s*,/;
Branch: 1 branch
BranchTrueFalseTotal
if (",$conn,") =~ /,\s*close\s*,/ 0 0 0
803 0 ▶ $conn = lc ($req->header('Proxy-Connection') || '');
Condition0%0/2
$req->header('Proxy-Connection') || ''
l!l
00
MC/DC0%0/1
$req->header('Proxy-Connection') || ''
$req->header('Proxy-Connection')
Truth table0%0/2
A
A= $req->header('Proxy-Connection')
Aresult
11
00
804 0 ▶ return 0 if ",$conn," =~ /,\s*close\s*,/;
Branch: 1 branch
BranchTrueFalseTotal
if (",$conn,") =~ /,\s*close\s*,/ 0 0 0
805 0 ▶ $conn = lc ($resp->header('Connection') || '');
Condition0%0/2
$resp->header('Connection') || ''
l!l
00
MC/DC0%0/1
$resp->header('Connection') || ''
$resp->header('Connection')
Truth table0%0/2
A
A= $resp->header('Connection')
Aresult
11
00
806 0 ▶ return 0 if ",$conn," =~ /,\s*close\s*,/;
Branch: 1 branch
BranchTrueFalseTotal
if (",$conn,") =~ /,\s*close\s*,/ 0 0 0
807  
808 # HTTP/1.1 = keep
809 0 ▶ return 1 if $req->protocol eq 'HTTP/1.1';
Branch: 1 branch
BranchTrueFalseTotal
if $req->protocol eq "HTTP/1.1" 0 0 0
810 0 return 0;
811 }
812  
813 # 'Got_Error'
814 # Got some sort of error from ReadWrite
815 event 'got_error' => sub {
816 0 ▶ my ($kernel,$self,$operation,$errnum,$errstr,$id) = @_[KERNEL,OBJECT,ARG0..ARG3];
Subroutine __ANON__: not called CC=4 SCAR=28.9
817  
818 # Only do this for non-EOF on read
819 #unless ( $operation eq 'read' and $errnum == 0 ) {
820 {
821  
822 # Debug stuff
823 0 warn "Wheel $id generated $operation error $errnum: $errstr\n"
824 if DEBUG;
825  
826 0 my $connection;
827 0 ▶ if ( $self->_connections->{$id} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_connections->{$id}) { } 0 0 0
if ($self->_connections->{$id}) { } 2 0 2
828 0 my $c = delete $self->_connections->{$id};
829 0 $connection = $c->connection;
830 0 $c->close_wheel;
831 }
832 else {
833  
834 0 ▶ if( defined $self->_requests->{$id}->response ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_requests->{$id}->response) { } 0 0 0
835 0 $connection = $self->_requests->{$id}->response->connection;
836 }
837 else {
838 0 warn "response for $id is undefined" if DEBUG;
839 }
840  
841 # Delete this connection
842 0 $self->_requests->{$id}->close_wheel;
843 }
844  
845 0 delete $self->_requests->{$id};
846 0 delete $self->_responses->{$id};
847  
848 # Mark the client dead
849 0 ▶ $connection->dead(1) if $connection;
Branch: 1 branch
BranchTrueFalseTotal
if $connection 0 0 0
850 }
851  
852 # Success!
853 0 return 1;
854 7 };
855  
856 # 'DONE'
857 # Output to the client!
858 event 'DONE' => sub {
859 1 ▶ my ($kernel,$self,$response) = @_[KERNEL,OBJECT,ARG0];
Subroutine DONE: called CC=17 SCAR=46.9
860  
861 # Check if we got it
862 1 ▶ if ( !defined $response or !UNIVERSAL::isa( $response, 'HTTP::Response' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $response and UNIVERSAL::isa($response, "HTTP::Response")) 0 1 1
Condition33%1/3
defined $response and UNIVERSAL::isa($response, "HTTP::Response")
!ll&&!rl&&r
001
MC/DC0%0/2
defined $response and UNIVERSAL::isa($response, "HTTP::Response")
defined $response UNIVERSAL::isa($response, "HTTP::Response")
Truth table33%1/3
A and B
A= defined $responseB= UNIVERSAL::isa($response, "HTTP::Response")
ABresult
0X0
100
111
863 0 warn 'Did not get a HTTP::Response object!' if DEBUG;
864 # Abort...
865 0 return;
866 }
867  
868 # Get the wheel ID
869 1 my $id = $response->_WHEEL;
870  
871 # Check if the wheel exists ( sometimes it gets closed by the client, but the application doesn't know that... )
872 1 ▶ unless ( exists $self->_requests->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->_requests->{$id}) 0 1 1
873  
874 # Debug stuff
875 0 warn
876 'Wheel disappeared, but the application sent us a DONE event, discarding it'
877 if DEBUG;
878  
879 $kernel->post(
880 $self->errorhandler->{SESSION},
881 $self->errorhandler->{EVENT},
882 'Wheel disappeared !'
883 0 ▶ ) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
Branch: 1 branch
BranchTrueFalseTotal
if $self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"} 0 0 0
Condition0%0/6
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
!ll&&!rl&&r
000
$self->errorhandler and $self->errorhandler->{"SESSION"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
$self->errorhandler $self->errorhandler->{"SESSION"} $self->errorhandler->{"EVENT"}
Truth table0%0/4
A and B and C
A= $self->errorhandlerB= $self->errorhandler->{"SESSION"}C= $self->errorhandler->{"EVENT"}
ABCresult
0XX0
10X0
1100
1111
884  
885 # All done!
886 0 return 1;
887 }
888  
889  
890 # Check if we have already sent the response
891 1 ▶ if ( $self->_requests->{$id}->done ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_requests->{$id}->done) 0 1 1
892 # Tried to send twice!
893 0 die 'Tried to send a response to the same connection twice!';
894 }
895  
896 # Quick check to see if the wheel/socket died already...
897 # Initially reported by Tim Wood
898 1 ▶ unless ( $self->_requests->{$id}->wheel_alive ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_requests->{$id}->wheel_alive) 0 1 1
899 0 warn 'Tried to send data over a closed/nonexistant socket!' if DEBUG;
900 $kernel->post(
901 $self->errorhandler->{SESSION},
902 $self->errorhandler->{EVENT},
903 'Socket closed/nonexistant !'
904 0 ▶ ) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
Branch: 1 branch
BranchTrueFalseTotal
if $self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"} 0 0 0
Condition0%0/6
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
!ll&&!rl&&r
000
$self->errorhandler and $self->errorhandler->{"SESSION"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
$self->errorhandler $self->errorhandler->{"SESSION"} $self->errorhandler->{"EVENT"}
Truth table0%0/4
A and B and C
A= $self->errorhandlerB= $self->errorhandler->{"SESSION"}C= $self->errorhandler->{"EVENT"}
ABCresult
0XX0
10X0
1100
1111
905 0 return;
906 }
907  
908 # Check if we were streaming.
909  
910 1 ▶ if ( $self->_requests->{$id}->streaming ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_requests->{$id}->streaming) 0 1 1
911 0 $self->_requests->{$id}->set_streaming(0);
912 0 $self->_requests->{$id}->set_done(1); # Finished streaming
913 # TODO: We might not get a flush, trigger it ourselves.
914 0 ▶ if ( !$self->_requests->{$id}->wheel->get_driver_out_messages ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_requests->{$id}->wheel->get_driver_out_messages) 0 0 0
915 0 $kernel->yield( 'got_flush', $id );
916 }
917 0 return;
918 }
919
920  
921 1 $self->fix_headers( $response );
922  
923 # Send it out!
924 1 $self->_requests->{$id}->wheel->put($response);
925  
926 # Mark this socket done
927 1 $self->_requests->{$id}->set_done(1);
928  
929 # Log FINALLY If they have a logFinal handler registered, send out the needed information
930 1 ▶ if ( $self->log2handler and scalar keys %{ $self->log2handler } == 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->log2handler and scalar keys %{$self->log2handler;} == 2) 0 1 1
Condition33%1/3
$self->log2handler and scalar keys %{$self->log2handler;} == 2
!ll&&!rl&&r
010
MC/DC0%0/2
$self->log2handler and scalar keys %{$self->log2handler;} == 2
$self->log2handler scalar keys %{$self->log2handler;} == 2
Truth table33%1/3
A and B
A= $self->log2handlerB= scalar keys %{$self->log2handler;} == 2
ABresult
0X0
100
111
931 0 $! = undef;
932 $kernel->call(
933 $self->log2handler->{'SESSION'},
934 $self->log2handler->{'EVENT'},
935 0 $self->_requests->{$id}->request, $response
936 );
937  
938 # Warn if we had a problem dispatching to the log handler above
939 warn(
940 "I had a problem posting to event '",
941 $self->log2handler->{'EVENT'},
942 "' of the log handler alias '",
943 0 ▶ $self->log2handler->{'SESSION'},
Branch: 1 branch
BranchTrueFalseTotal
if $! 0 0 0
944 "'. As reported by Kernel: '$!', perhaps the alias is spelled incorrectly for this handler?"
945 ) if $!;
946 }
947  
948 # Debug stuff
949 1 warn "Completed with Wheel ID $id" if DEBUG;
950  
951 # Success!
952 1 return 1;
953 7 };
954  
955 # 'STREAM'
956 # Stream output to the client
957 event 'STREAM' => sub {
958 0 ▶ my ($kernel,$self,$response) = @_[KERNEL,OBJECT,ARG0];
Subroutine STREAM: not called CC=16 SCAR=56.1
959  
960 # Check if we got it
961 0 ▶ unless ( defined $response and UNIVERSAL::isa( $response, 'HTTP::Response' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $response and UNIVERSAL::isa($response, "HTTP::Response")) 0 0 0
Condition0%0/3
defined $response and UNIVERSAL::isa($response, "HTTP::Response")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $response and UNIVERSAL::isa($response, "HTTP::Response")
defined $response UNIVERSAL::isa($response, "HTTP::Response")
Truth table0%0/3
A and B
A= defined $responseB= UNIVERSAL::isa($response, "HTTP::Response")
ABresult
0X0
100
111
962 0 warn 'Did not get a HTTP::Response object!' if DEBUG;
963 # Abort...
964 0 return;
965 }
966  
967 # Get the wheel ID
968 0 my $id = $response->_WHEEL;
969 0 $self->_chunkcount->{$id}++;
970  
971 0 ▶ if ( defined $response->STREAM ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $response->STREAM) { } 0 0 0
972  
973 # Keep track if we plan to stream ...
974 0 ▶ if ( $self->_responses->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_responses->{$id}) { } 0 0 0
975 0 warn "Restoring response from HEAP and id $id " if DEBUG;
976 0 $response = $self->_responses->{$id};
977 }
978 else {
979 0 warn "Saving HEAP response to id $id " if DEBUG;
980 0 $self->_responses->{$id} = $response;
981 }
982 }
983 else {
984 0 warn
985 'Can\'t push on a response that has not been not set as a STREAM!'
986 if DEBUG;
987 # Abort...
988 0 return;
989 }
990  
991 # Check if the wheel exists ( sometimes it gets closed by the client, but the application doesn't know that... )
992 0 ▶ unless ( exists $self->_requests->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->_requests->{$id}) 0 0 0
993  
994 # Debug stuff
995 0 warn
996 'Wheel disappeared, but the application sent us a DONE event, discarding it'
997 if DEBUG;
998  
999 $kernel->post(
1000 $self->errorhandler->{SESSION},
1001 $self->errorhandler->{EVENT},
1002 'Wheel disappeared !'
1003 0 ▶ ) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
Branch: 1 branch
BranchTrueFalseTotal
if $self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"} 0 0 0
Condition0%0/6
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
!ll&&!rl&&r
000
$self->errorhandler and $self->errorhandler->{"SESSION"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
$self->errorhandler $self->errorhandler->{"SESSION"} $self->errorhandler->{"EVENT"}
Truth table0%0/4
A and B and C
A= $self->errorhandlerB= $self->errorhandler->{"SESSION"}C= $self->errorhandler->{"EVENT"}
ABCresult
0XX0
10X0
1100
1111
1004  
1005 # All done!
1006 0 return 1;
1007 }
1008  
1009 # Quick check to see if the wheel/socket died already...
1010 # Initially reported by Tim Wood
1011 0 ▶ unless ( $self->_requests->{$id}->wheel_alive ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_requests->{$id}->wheel_alive) 0 0 0
1012 0 warn 'Tried to send data over a closed/nonexistant socket!' if DEBUG;
1013 $kernel->post(
1014 $self->errorhandler->{SESSION},
1015 $self->errorhandler->{EVENT},
1016 'Socket closed/nonexistant !'
1017 0 ▶ ) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
Branch: 1 branch
BranchTrueFalseTotal
if $self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"} 0 0 0
Condition0%0/6
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
!ll&&!rl&&r
000
$self->errorhandler and $self->errorhandler->{"SESSION"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->errorhandler and $self->errorhandler->{"SESSION"} and $self->errorhandler->{"EVENT"}
$self->errorhandler $self->errorhandler->{"SESSION"} $self->errorhandler->{"EVENT"}
Truth table0%0/4
A and B and C
A= $self->errorhandlerB= $self->errorhandler->{"SESSION"}C= $self->errorhandler->{"EVENT"}
ABCresult
0XX0
10X0
1100
1111
1018 0 return;
1019 }
1020  
1021 0 $self->fix_headers( $response, 1 );
1022  
1023 # Sets the correct POE::Filter
1024 0 ▶ unless ( defined $response->IS_STREAMING ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $response->IS_STREAMING) 0 0 0
1025  
1026 # Mark this socket done
1027 0 $self->_requests->{$id}->set_streaming(1);
1028 0 $response->set_streaming(1);
1029 }
1030  
1031 0 if (DEBUG) {
1032 warn "Sending stream via "
1033 . $response->STREAM_SESSION . "/"
1034 . $response->STREAM
1035 . " with id $id \n";
1036 }
1037  
1038 0 ▶ if ( $self->_chunkcount->{$id} > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_chunkcount->{$id} > 1) { } 0 0 0
1039 0 my $wheel = $self->_requests->{ $response->_WHEEL }->wheel;
1040 0 $wheel->set_output_filter( POE::Filter::Stream->new() );
1041 0 $wheel->put( $response->content );
1042 }
1043 else {
1044 0 my $wheel = $self->_requests->{ $response->_WHEEL }->wheel;
1045 0 $wheel->set_output_filter( $wheel->get_input_filter() );
1046 0 $wheel->put($response);
1047 }
1048  
1049 # we send the event to stream with wheels request and response to the session
1050 # that has registered the streaming event
1051 0 ▶ unless ( $response->DONT_FLUSH ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->DONT_FLUSH) 0 0 0
1052 $kernel->post(
1053 $response->STREAM_SESSION, # callback session
1054 $response->STREAM, # callback event
1055 0 $self->_responses->{ $response->_WHEEL }
1056 );
1057 }
1058  
1059 # Success!
1060 0 return 1;
1061 7 };
1062  
1063 # Add required headers to a response
1064 sub fix_headers {
1065 1 ▶ my ( $self, $response, $stream ) = @_;
Subroutine fix_headers: called CC=11 SCAR=28.1
Pod undocumented
1066  
1067 # Set the date if needed
1068 1 ▶ if ( !$response->header('Date') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->header("Date")) 1 0 1
1069 1 $response->header( 'Date', time2str(time) );
1070 }
1071  
1072 # Set the Content-Length if needed
1073 1 ▶ if ( !$stream and !$self->proxymode
Branch: 1 branch
BranchTrueFalseTotal
if (not $stream || $self->proxymode || defined $response->header("Content-Length") and my $len = length $response->content) 1 0 1
Condition33%3/9
not $stream || $self->proxymode || defined $response->header("Content-Length") and my $len = length $response->content
!ll&&!rl&&r
001
$stream || $self->proxymode || defined $response->header('Content-Length')
l!l&&r!l&&!r
001
$stream or $self->proxymode
l!l&&r!l&&!r
001
MC/DC0%0/4
not $stream || $self->proxymode || defined $response->header("Content-Length") and my $len = length $response->content
$stream $self->proxymode defined $response->header('Content-Length') my $len = length $response->content
Truth table20%1/5
not(A or B || C) and D
A= $streamB= $self->proxymodeC= defined $response->header('Content-Length')D= my $len = length $response->content
ABCDresult
1XXX0
01XX0
001X0
00000
00011
1074 and !defined $response->header('Content-Length')
1075 and my $len = length $response->content )
1076 {
1077 7 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1078 1 $response->header( 'Content-Length', $len );
1079 }
1080  
1081 # Set the Content-Type if needed
1082 1 ▶ if ( !$response->header('Content-Type') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->header("Content-Type")) 1 0 1
1083 1 $response->header( 'Content-Type', 'text/plain' );
1084 }
1085  
1086 1 ▶ if ( !$response->protocol ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $response->protocol) 1 0 1
1087 1 my $request = $self->_requests->{ $response->_WHEEL }->request;
1088 1 ▶ return unless $request and $request->isa('HTTP::Request');
Branch: 1 branch
BranchTrueFalseTotal
unless $request and $request->isa("HTTP::Request") 0 1 1
Condition33%1/3
$request and $request->isa("HTTP::Request")
!ll&&!rl&&r
001
MC/DC0%0/2
$request and $request->isa("HTTP::Request")
$request $request->isa("HTTP::Request")
Truth table33%1/3
A and B
A= $requestB= $request->isa("HTTP::Request")
ABresult
0X0
100
111
1089 1 ▶ unless ( $request->method eq 'HEAD' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($request->method eq "HEAD") 1 0 1
1090 1 $response->protocol( $request->protocol );
1091 }
1092 }
1093 }
1094  
1095 # 'CLOSE'
1096 # Closes the connection
1097 event 'CLOSE' => sub {
1098 0 ▶ my ($kernel,$self,$response) = @_[KERNEL,OBJECT,ARG0];
Subroutine __ANON__: not called CC=6 SCAR=37.4
1099  
1100 # Check if we got it
1101 0 ▶ unless ( defined $response and UNIVERSAL::isa( $response, 'HTTP::Response' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $response and UNIVERSAL::isa($response, "HTTP::Response")) 0 0 0
Condition0%0/3
defined $response and UNIVERSAL::isa($response, "HTTP::Response")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $response and UNIVERSAL::isa($response, "HTTP::Response")
defined $response UNIVERSAL::isa($response, "HTTP::Response")
Truth table0%0/3
A and B
A= defined $responseB= UNIVERSAL::isa($response, "HTTP::Response")
ABresult
0X0
100
111
1102 0 warn 'Did not get a HTTP::Response object!' if DEBUG;
1103 # Abort...
1104 0 return;
1105 }
1106  
1107 # Get the wheel ID
1108 0 my $id = $response->_WHEEL;
1109  
1110 0 ▶ if ( $self->_connections->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_connections->{$id}) 0 0 0
1111 0 $self->_requests->{$id} = delete $self->_connections->{$id};
1112 }
1113  
1114 # Check if the wheel exists ( sometimes it gets closed by the client, but the application doesn't know that... )
1115 0 ▶ unless ( exists $self->_requests->{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->_requests->{$id}) 0 0 0
1116 0 warn
1117 'Wheel disappeared, but the application sent us a CLOSE event, discarding it'
1118 if DEBUG;
1119 0 return 1;
1120 }
1121  
1122 # Kill it!
1123 0 ▶ $self->_requests->{$id}->close_wheel if $self->_requests->{$id}->wheel_alive;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_requests->{$id}->wheel_alive 0 0 0
1124  
1125 # Delete it!
1126 0 delete $self->_requests->{$id};
1127 0 delete $self->_responses->{$id};
1128  
1129 0 warn 'Delete references to the connection done.' if DEBUG;
1130  
1131 # All done!
1132 0 return 1;
1133 7 };
1134  
1135 # Registers a POE inline state (primarly for streaming)
1136 event 'REGISTER' => sub {
1137 0 ▶ my ( $session, $state, $code_ref ) = @_[ SESSION, ARG0 .. ARG1 ];
Subroutine REGISTER: not called CC=1 SCAR=6.9
1138 0 warn 'Registering state in POE session' if DEBUG;
1139 0 return $session->register_state( $state, $code_ref );
1140 7 };
1141  
1142 # SETCLOSEHANDLER
1143 event 'SETCLOSEHANDLER' => sub {
1144 0 ▶ my ($self,$sender) = @_[OBJECT,SENDER ];
Subroutine __ANON__: not called CC=7 SCAR=40.3
1145 0 my ($connection,$state,@params) = @_[ARG0..$#_];
1146  
1147 # turn connection ID into the connection object
1148 0 ▶ unless ( ref $connection ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $connection) 0 0 0
1149 0 my $id = $connection;
1150 0 ▶ if ( $self->_connections->{$id} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_connections->{$id}) { } 0 0 0
elsif ($self->_requests->{$id} and $self->_requests->{$id}->response) { } 0 0 0
1151 0 $connection = $self->_connections->{$id}->connection;
1152 }
1153 ▶ elsif ($self->_requests->{$id}
Condition0%0/3
$self->_requests->{$id} and $self->_requests->{$id}->response
!ll&&!rl&&r
000
MC/DC0%0/2
$self->_requests->{$id} and $self->_requests->{$id}->response
$self->_requests->{$id} $self->_requests->{$id}->response
Truth table0%0/3
A and B
A= $self->_requests->{$id}B= $self->_requests->{$id}->response
ABresult
0X0
100
111
1154 and $self->_requests->{$id}->response )
1155 {
1156 0 $connection = $self->_requests->{$id}->response->connection;
1157 }
1158 0 ▶ unless ( ref $connection ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $connection) 0 0 0
1159 0 die "Can't find connection object for request $id";
1160 }
1161 }
1162  
1163 0 ▶ if ($state) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state) { } 0 0 0
1164 0 $connection->_on_close( $sender->ID, $state, @params );
1165 }
1166 else {
1167 0 $connection->_on_close($sender->ID);
1168 }
1169 7 };
1170  
1171 7 ▶no MooseX::POE;
Subroutine BEGIN: called CC=1 SCAR=0.0
1172  
1173 7 __PACKAGE__->meta->make_immutable( );
1174  
1175 7 "Simple In'it";
1176  
1177 __END__
1178  
1179 =head1 NAME
1180  
1181 POE::Component::Server::SimpleHTTP - Perl extension to serve HTTP requests in POE.
1182  
1183 =head1 SYNOPSIS
1184  
1185 use POE;
1186 use POE::Component::Server::SimpleHTTP;
1187  
1188 # Start the server!
1189 POE::Component::Server::SimpleHTTP->new(
1190 'ALIAS' => 'HTTPD',
1191 'PORT' => 11111,
1192 'HOSTNAME' => 'MySite.com',
1193 'HANDLERS' => [
1194 {
1195 'DIR' => '^/bar/.*',
1196 'SESSION' => 'HTTP_GET',
1197 'EVENT' => 'GOT_BAR',
1198 },
1199 {
1200 'DIR' => '^/$',
1201 'SESSION' => 'HTTP_GET',
1202 'EVENT' => 'GOT_MAIN',
1203 },
1204 {
1205 'DIR' => '^/foo/.*',
1206 'SESSION' => 'HTTP_GET',
1207 'EVENT' => 'GOT_NULL',
1208 },
1209 {
1210 'DIR' => '.*',
1211 'SESSION' => 'HTTP_GET',
1212 'EVENT' => 'GOT_ERROR',
1213 },
1214 ],
1215  
1216 'LOGHANDLER' => { 'SESSION' => 'HTTP_GET',
1217 'EVENT' => 'GOT_LOG',
1218 },
1219  
1220 'LOG2HANDLER' => { 'SESSION' => 'HTTP_GET',
1221 'EVENT' => 'POSTLOG',
1222 },
1223  
1224 # In the testing phase...
1225 'SSLKEYCERT' => [ 'private-key.pem', 'public-cert.pem' ],
1226 'SSLINTERMEDIATECACERT' => 'intermediate-ca-cert.pem',
1227 ) or die 'Unable to create the HTTP Server';
1228  
1229 # Create our own session to receive events from SimpleHTTP
1230 POE::Session->create(
1231 inline_states => {
1232 '_start' => sub { $_[KERNEL]->alias_set( 'HTTP_GET' );
1233 $_[KERNEL]->post( 'HTTPD', 'GETHANDLERS', $_[SESSION], 'GOT_HANDLERS' );
1234 },
1235  
1236 'GOT_BAR' => \&GOT_REQ,
1237 'GOT_MAIN' => \&GOT_REQ,
1238 'GOT_ERROR' => \&GOT_ERR,
1239 'GOT_NULL' => \&GOT_NULL,
1240 'GOT_HANDLERS' => \&GOT_HANDLERS,
1241 'GOT_LOG' => \&GOT_LOG,
1242 },
1243 );
1244  
1245 # Start POE!
1246 POE::Kernel->run();
1247  
1248 sub GOT_HANDLERS {
1249 # ARG0 = HANDLERS array
1250 my $handlers = $_[ ARG0 ];
1251  
1252 # Move the first handler to the last one
1253 push( @$handlers, shift( @$handlers ) );
1254  
1255 # Send it off!
1256 $_[KERNEL]->post( 'HTTPD', 'SETHANDLERS', $handlers );
1257 }
1258  
1259 sub GOT_NULL {
1260 # ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
1261 my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
1262  
1263 # Kill this!
1264 $_[KERNEL]->post( 'HTTPD', 'CLOSE', $response );
1265 }
1266  
1267 sub GOT_REQ {
1268 # ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
1269 my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
1270  
1271 # Do our stuff to HTTP::Response
1272 $response->code( 200 );
1273 $response->content( 'Some funky HTML here' );
1274  
1275 # We are done!
1276 # For speed, you could use $_[KERNEL]->call( ... )
1277 $_[KERNEL]->post( 'HTTPD', 'DONE', $response );
1278 }
1279  
1280 sub GOT_ERR {
1281 # ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
1282 my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
1283  
1284 # Check for errors
1285 if ( ! defined $request ) {
1286 $_[KERNEL]->post( 'HTTPD', 'DONE', $response );
1287 return;
1288 }
1289  
1290 # Do our stuff to HTTP::Response
1291 $response->code( 404 );
1292 $response->content( "Hi visitor from " . $response->connection->remote_ip . ", Page not found -> '" . $request->uri->path . "'" );
1293  
1294 # We are done!
1295 # For speed, you could use $_[KERNEL]->call( ... )
1296 $_[KERNEL]->post( 'HTTPD', 'DONE', $response );
1297 }
1298  
1299 sub GOT_LOG {
1300 # ARG0 = HTTP::Request object, ARG1 = remote IP
1301 my ($request, $remote_ip) = @_[ARG0,ARG1];
1302  
1303 # Do some sort of logging activity.
1304 # If the request was malformed, $request = undef
1305 # CHECK FOR A REQUEST OBJECT BEFORE USING IT.
1306 if( $request ) {
1307 {
1308 warn join(' ', time(), $remote_ip, $request->uri ), "\n";
1309 } else {
1310 warn join(' ', time(), $remote_ip, 'Bad request' ), "\n";
1311 }
1312  
1313 return;
1314 }
1315  
1316 =head1 ABSTRACT
1317  
1318 An easy to use HTTP daemon for POE-enabled programs
1319  
1320 =head1 DESCRIPTION
1321  
1322 This module makes serving up HTTP requests a breeze in POE.
1323  
1324 The hardest thing to understand in this module is the HANDLERS. That's it!
1325  
1326 The standard way to use this module is to do this:
1327  
1328 use POE;
1329 use POE::Component::Server::SimpleHTTP;
1330  
1331 POE::Component::Server::SimpleHTTP->new( ... );
1332  
1333 POE::Session->create( ... );
1334  
1335 POE::Kernel->run();
1336  
1337 =head2 Starting SimpleHTTP
1338  
1339 To start SimpleHTTP, just call it's new method:
1340  
1341 POE::Component::Server::SimpleHTTP->new(
1342 'ALIAS' => 'HTTPD',
1343 'ADDRESS' => '192.168.1.1',
1344 'PORT' => 11111,
1345 'HOSTNAME' => 'MySite.com',
1346 'HEADERS' => {},
1347 'HANDLERS' => [ ],
1348 );
1349  
1350 This method will die on error or return success.
1351  
1352 This constructor accepts only 7 options.
1353  
1354 =over 4
1355  
1356 =item C<ALIAS>
1357  
1358 This will set the alias SimpleHTTP uses in the POE Kernel.
1359 This will default to "SimpleHTTP"
1360  
1361 =item C<ADDRESS>
1362  
1363 This value will be passed to POE::Wheel::SocketFactory to bind to, will use INADDR_ANY if it is nothing is provided.
1364  
1365 =item C<PORT>
1366  
1367 This value will be passed to POE::Wheel::SocketFactory to bind to.
1368  
1369 =item C<HOSTNAME>
1370  
1371 This value is for the HTTP::Request's URI to point to.
1372 If this is not supplied, SimpleHTTP will use Sys::Hostname to find it.
1373  
1374 =item C<HEADERS>
1375  
1376 This should be a hashref, that will become the default headers on all HTTP::Response objects.
1377 You can override this in individual requests by setting it via $request->header( ... )
1378  
1379 For more information, consult the L<HTTP::Headers> module.
1380  
1381 =item C<HANDLERS>
1382  
1383 This is the hardest part of SimpleHTTP :)
1384  
1385 You supply an array, with each element being a hash. All the hashes should contain those 3 keys:
1386  
1387 DIR -> The regexp that will be used, more later.
1388  
1389 SESSION -> The session to send the input
1390  
1391 EVENT -> The event to trigger
1392  
1393 The DIR key should be a valid regexp. This will be matched against the current request path.
1394 Pseudocode is: if ( $path =~ /$DIR/ )
1395  
1396 NOTE: The path is UNIX style, not MSWIN style ( /blah/foo not \blah\foo )
1397  
1398 Now, if you supply 100 handlers, how will SimpleHTTP know what to do? Simple! By passing in an array in the first place,
1399 you have already told SimpleHTTP the order of your handlers. They will be tried in order, and if a match is not found,
1400 SimpleHTTP will return a 404 response.
1401  
1402 This allows some cool things like specifying 3 handlers with DIR of:
1403 '^/foo/.*', '^/$', '.*'
1404  
1405 Now, if the request is not in /foo or not root, your 3rd handler will catch it, becoming the "404 not found" handler!
1406  
1407 NOTE: You might get weird Session/Events, make sure your handlers are in order, for example: '^/', '^/foo/.*'
1408 The 2nd handler will NEVER get any requests, as the first one will match ( no $ in the regex )
1409  
1410 Now, here's what a handler receives:
1411  
1412 ARG0 -> HTTP::Request object
1413  
1414 ARG1 -> POE::Component::Server::SimpleHTTP::Response object
1415  
1416 ARG2 -> The exact DIR that matched, so you can see what triggered what
1417  
1418 NOTE: If ARG0 is undef, that means POE::Filter::HTTPD encountered an error parsing the client request, simply modify the HTTP::Response
1419 object and send some sort of generic error. SimpleHTTP will set the path used in matching the DIR regexes to an empty string, so if there
1420 is a "catch-all" DIR regex like '.*', it will catch the errors, and only that one.
1421  
1422 NOTE: The only way SimpleHTTP will leak memory ( hopefully heh ) is if you discard the SimpleHTTP::Response object without sending it
1423 back to SimpleHTTP via the DONE/CLOSE events, so never do that!
1424  
1425 =item C<KEEPALIVE>
1426  
1427 Set to true to enable HTTP keep-alive support. Connections will be
1428 kept alive until the client closes the connection. All HTTP/1.1 connections
1429 are kept-open, unless you set the response C<Connection> header to C<close>.
1430  
1431 $response->header( Connection => 'close' );
1432  
1433 If you want more control, use L<POE::Component::Server::HTTP::KeepAlive>.
1434  
1435 =item C<LOGHANDLER>
1436  
1437 Expects a hashref with the following key, values:
1438  
1439 SESSION -> The session to send the input
1440  
1441 EVENT -> The event to trigger
1442  
1443 You will receive an event for each request to the server from clients. Malformed client requests will not be passed into the handler. Instead
1444 undef will be passed.
1445 Event is called before ANY content handler is called.
1446  
1447 The event will have the following parameters:
1448  
1449 ARG0 -> HTTP::Request object/undef if client request was malformed.
1450  
1451 ARG1 -> the IP address of the client
1452  
1453 =item C<LOG2HANDLER>
1454  
1455 Expect a hashref with the following key, values:
1456  
1457 SESSION -> The session to send the input
1458  
1459 EVENT -> The event to trigger
1460  
1461 You will receive an event for each response that hit DONE call. Malformed client requests will not be passed into the handler.
1462 Event is after processing all content handlers.
1463  
1464 The event will have the following parameters:
1465  
1466 ARG0 -> HTTP::Request object
1467  
1468 ARG1 -> HTTP::Response object
1469  
1470 That makes possible following code:
1471  
1472 my ($login, $password) = $request->authorization_basic();
1473 printf STDERR "%s - %s [%s] \"%s %s %s\" %d %d\n",
1474 $response->connection->remote_ip, $login||'-', POSIX::strftime("%d/%b/%Y:%T %z",localtime(time())),
1475 $request->method(), $request->uri()->path(), $request->protocol(),
1476 $response->code(), length($response->content());
1477  
1478 Emulate apache-like logs for PoCo::Server::SimpleHTTP
1479  
1480 =item C<SETUPHANDLER>
1481  
1482 Expects a hashref with the following key, values:
1483  
1484 SESSION -> The session to send the input
1485  
1486 EVENT -> The event to trigger
1487  
1488 You will receive an event when the listener wheel has been setup.
1489  
1490 Currently there are no parameters returned.
1491  
1492 =item C<SSLKEYCERT>
1493  
1494 This should be an arrayref of only 2 elements - the private key and public certificate locations. Now, this is still in the experimental stage, and testing
1495 is greatly welcome!
1496  
1497 Again, this will automatically turn every incoming connection into a SSL socket. Once enough testing has been done, this option will be augmented with more SSL stuff!
1498  
1499 =item C<SSLINTERMEDIATECACERT>
1500  
1501 This option is needed in case the SSL certificate references an intermediate certification authority certificate.
1502  
1503 =item C<PROXYMODE>
1504  
1505 Set this to a true value to enable the server to act as a proxy server, ie. it won't mangle the HTTP::Request
1506 URI.
1507  
1508 =back
1509  
1510 =head2 Events
1511  
1512 SimpleHTTP is so simple, there are only 8 events available.
1513  
1514 =over 4
1515  
1516 =item C<DONE>
1517  
1518 This event accepts only one argument: the HTTP::Response object we sent to the handler.
1519  
1520 Calling this event implies that this particular request is done, and will proceed to close the socket.
1521  
1522 NOTE: This method automatically sets those 3 headers if they are not already set:
1523 Date -> Current date stringified via HTTP::Date->time2str
1524 Content-Type -> text/html
1525 Content-Length -> length( $response->content )
1526  
1527 To get greater throughput and response time, do not post() to the DONE event, call() it!
1528 However, this will force your program to block while servicing web requests...
1529  
1530 =item C<CLOSE>
1531  
1532 This event accepts only one argument: the HTTP::Response object we sent to the handler.
1533  
1534 Calling this event will close the socket, not sending any output
1535  
1536 =item C<GETHANDLERS>
1537  
1538 This event accepts 2 arguments: The session + event to send the response to
1539  
1540 This event will send back the current HANDLERS array ( deep-cloned via Storable::dclone )
1541  
1542 The resulting array can be played around to your tastes, then once you are done...
1543  
1544 =item C<SETHANDLERS>
1545  
1546 This event accepts only one argument: pointer to HANDLERS array
1547  
1548 BEWARE: if there is an error in the HANDLERS, SimpleHTTP will die!
1549  
1550 =item C<SETCLOSEHANDLER>
1551  
1552 $_[KERNEL]->call( $_[SENDER], 'SETCLOSEHANDLER', $connection,
1553 $event, @args );
1554  
1555 Calls C<$event> in the current session when C<$connection> is closed. You
1556 could use for persistent connection handling.
1557  
1558 Multiple session may register close handlers.
1559  
1560 Calling SETCLOSEHANDLER without C<$event> to remove the current session's
1561 handler:
1562  
1563 $_[KERNEL]->call( $_[SENDER], 'SETCLOSEHANDLER', $connection );
1564  
1565 You B<must> make sure that C<@args> doesn't cause a circular
1566 reference. Ideally, use C<$connection->ID> or some other unique value
1567 associated with this C<$connection>.
1568  
1569 =item C<STARTLISTEN>
1570  
1571 Starts the listening socket, if it was shut down
1572  
1573 =item C<STOPLISTEN>
1574  
1575 Simply a wrapper for SHUTDOWN GRACEFUL, but will not shutdown SimpleHTTP if there is no more requests
1576  
1577 =item C<SHUTDOWN>
1578  
1579 Without arguments, SimpleHTTP does this:
1580 Close the listening socket
1581 Kills all pending requests by closing their sockets
1582 Removes it's alias
1583  
1584 With an argument of 'GRACEFUL', SimpleHTTP does this:
1585 Close the listening socket
1586 Waits for all pending requests to come in via DONE/CLOSE, then removes it's alias
1587  
1588 =item C<STREAM>
1589  
1590 With a $response argument it streams the content and calls back the streaming event
1591 of the user's session (or with the dont_flush option you're responsible for calling
1592 back your session's streaming event).
1593  
1594 To use the streaming feature see below.
1595  
1596 =back
1597  
1598 =head2 Streaming with SimpleHTTP
1599  
1600 It's possible to send data as a stream to clients (unbuffered and integrated in the
1601 POE loop).
1602  
1603 Just create your session to receive events from SimpleHTTP as usually and add a
1604 streaming event, this event will be triggered over and over each time you set the
1605 $response to a streaming state and once you trigger it:
1606  
1607 # sets the response as streamed within our session which alias is HTTP_GET
1608 # with the event GOT_STREAM
1609 $response->stream(
1610 session => 'HTTP_GET',
1611 event => 'GOT_STREAM',
1612 dont_flush => 1
1613 );
1614  
1615 # then you can simply yield your streaming event, once the GOT_STREAM event
1616 # has reached its end it will be triggered again and again, until you
1617 # send a CLOSE event to the kernel with the appropriate response as parameter
1618 $kernel->yield('GOT_STREAM', $response);
1619  
1620 The optional dont_flush option gives the user the ability to control the callback
1621 to the streaming event, which means once your stream event has reached its end
1622 it won't be called, you have to call it back.
1623  
1624 You can now send data by chunks and either call yourself back (via POE) or
1625 shutdown when your streaming is done (EOF for example).
1626  
1627 sub GOT_STREAM {
1628 my ( $kernel, $heap, $response ) = @_[KERNEL, HEAP, ARG0];
1629  
1630 # sets the content of the response
1631 $response->content("Hello World\n");
1632  
1633 # send it to the client
1634 POE::Kernel->post('HTTPD', 'STREAM', $response);
1635  
1636 # if we have previously set the dont_flush option
1637 # we have to trigger our event back until the end of
1638 # the stream like this (that can be a yield, of course):
1639 #
1640 # $kernel->delay('GOT_STREAM', 1, $stream );
1641  
1642 # otherwise the GOT_STREAM event is triggered continuously until
1643 # we call the CLOSE event on the response like that :
1644 #
1645 if ($heap{'streaming_is_done'}) {
1646 # close the socket and end the stream
1647 POE::Kernel->post('HTTPD', 'CLOSE', $response );
1648 }
1649 }
1650  
1651 The dont_flush option is there to be able to control the frequency of flushes
1652 to the client.
1653  
1654 =head2 SimpleHTTP Notes
1655  
1656 You can enable debugging mode by doing this:
1657  
1658 sub POE::Component::Server::SimpleHTTP::DEBUG () { 1 }
1659 use POE::Component::Server::SimpleHTTP;
1660  
1661 Also, this module will try to keep the Listening socket alive.
1662 if it dies, it will open it again for a max of 5 retries.
1663  
1664 You can override this behavior by doing this:
1665  
1666 sub POE::Component::Server::SimpleHTTP::MAX_RETRIES () { 10 }
1667 use POE::Component::Server::SimpleHTTP;
1668  
1669 For those who are pondering about basic-authentication, here's a tiny snippet to put in the Event handler
1670  
1671 # Contributed by Rocco Caputo
1672 sub Got_Request {
1673 # ARG0 = HTTP::Request, ARG1 = HTTP::Response
1674 my( $request, $response ) = @_[ ARG0, ARG1 ];
1675  
1676 # Get the login
1677 my ( $login, $password ) = $request->authorization_basic();
1678  
1679 # Decide what to do
1680 if ( ! defined $login or ! defined $password ) {
1681 # Set the authorization
1682 $response->header( 'WWW-Authenticate' => 'Basic realm="MyRealm"' );
1683 $response->code( 401 );
1684 $response->content( 'FORBIDDEN.' );
1685  
1686 # Send it off!
1687 $_[KERNEL]->post( 'SimpleHTTP', 'DONE', $response );
1688 } else {
1689 # Authenticate the user and move on
1690 }
1691 }
1692  
1693 =head2 EXPORT
1694  
1695 Nothing.
1696  
1697 =head1 SEE ALSO
1698  
1699 L<POE>
1700  
1701 L<POE::Filter::HTTPD>
1702  
1703 L<HTTP::Request>
1704  
1705 L<HTTP::Response>
1706  
1707 L<POE::Component::Server::SimpleHTTP::Connection>
1708  
1709 L<POE::Component::Server::SimpleHTTP::Response>
1710  
1711 L<POE::Component::Server::SimpleHTTP::PreFork>
1712  
1713 L<POE::Component::SSLify>
1714  
1715 =head1 AUTHOR
1716  
1717 Apocalypse E<lt>apocal@cpan.orgE<gt>
1718  
1719 =head1 COPYRIGHT AND LICENSE
1720  
1721 Copyright 2006 by Apocalypse
1722  
1723 This library is free software; you can redistribute it and/or modify
1724 it under the same terms as Perl itself.
1725  
1726 =cut
↑ Summary SimpleHTTP/Connection.pm »