POE-Component-Server-SimpleHTTP
view release on metacpan or search on metacpan
lib/POE/Component/Server/SimpleHTTP.pm view on Meta::CPAN
# Check for errors
if ($@) {
croak("HANDLER number $count has a malformed DIR -> $@");
}
else {
# Store it!
$handler->[$count]->{'RE'} = $regex;
}
}
else {
croak("HANDLER number $count is not a reference to a HASH!");
}
# Done with this one!
$count++;
}
# Got here, success!
return 1;
}
# 'Got_Connection'
# The actual manager of connections
event 'got_connection' => sub {
my ( $kernel, $self, $socket ) = @_[KERNEL, OBJECT, ARG0];
my ( $family, $address, $port, $straddress ) =
POE::Component::Server::SimpleHTTP::Connection->get_sockaddr_info(
getpeername($socket) );
# Should we SSLify it?
if ( $self->sslkeycert ) {
# SSLify it!
eval { $socket = Server_SSLify($socket) };
if ($@) {
warn "Unable to turn on SSL for connection from $straddress -> $@";
close $socket;
return 1;
}
}
# Set up the Wheel to read from the socket
my $wheel = POE::Wheel::ReadWrite->new(
Handle => $socket,
Filter => POE::Filter::HTTPD->new(),
InputEvent => 'got_input',
FlushedEvent => 'got_flush',
ErrorEvent => 'got_error',
);
if ( DEBUG and keys %{ $self->_connections } ) {
# use Data::Dumper;
warn "conn id=", $wheel->ID, " [",
join( ', ', keys %{ $self->_connections } ), "]";
}
# Save this wheel!
# 0 = wheel, 1 = Output done?, 2 = SimpleHTTP::Response object, 3 == request, 4 == streaming?
$self->_requests->{ $wheel->ID } =
POE::Component::Server::SimpleHTTP::State->new( wheel => $wheel );
# Debug stuff
if (DEBUG) {
warn "Got_Connection completed creation of ReadWrite wheel ( "
. $wheel->ID . " )";
}
# Success!
return 1;
};
# 'Got_Input'
# Finally got input, set some stuff and send away!
event 'got_input' => sub {
my ($kernel,$self,$request,$id) = @_[KERNEL,OBJECT,ARG0,ARG1];
my $connection;
# This whole thing is a mess. Keep-Alive was bolted on and it
# shows. Streaming is unpredictable. There are checks everywhere
# because it leaks wheels. *sigh*
# Was this request Keep-Alive?
if ( $self->_connections->{$id} ) {
my $state = delete $self->_connections->{$id};
$state->reset;
$connection = $state->connection;
$state->clear_connection;
$self->_requests->{$id} = $state;
warn "Keep-alive id=$id next request..." if DEBUG;
}
# Quick check to see if the socket died already...
# Initially reported by Tim Wood
unless ( $self->_requests->{$id}->wheel_alive ) {
warn 'Got a request, but socket died already!' if DEBUG;
# Destroy this wheel!
$self->_requests->{$id}->close_wheel;
delete $self->_requests->{$id};
return;
}
SWITCH: {
last SWITCH if $connection; # connection was kept-alive
# Directly access POE::Wheel::ReadWrite's HANDLE_INPUT -> to get the socket itself
# Hmm, if we are SSL, then have to do an extra step!
if ( $self->sslkeycert ) {
$connection = POE::Component::Server::SimpleHTTP::Connection->new(
SSLify_GetSocket(
$self->_requests->{$id}->wheel->get_input_handle() )
);
last SWITCH;
}
$connection = POE::Component::Server::SimpleHTTP::Connection->new(
$self->_requests->{$id}->wheel->get_input_handle()
);
}
lib/POE/Component/Server/SimpleHTTP.pm view on Meta::CPAN
"' of the log handler alias '",
$self->loghandler->{'SESSION'},
"'. As reported by Kernel: '$!', perhaps the alias is spelled incorrectly for this handler?"
) unless $ok;
}
# If we received a malformed request then
# let's not try to dispatch to a handler
if ($malformed_req) {
# Just push out the response we got from POE::Filter::HTTPD saying your request was bad
$kernel->post(
$self->errorhandler->{SESSION},
$self->errorhandler->{EVENT},
'BadRequest (by POE::Filter::HTTPD)',
$response->connection->remote_ip()
) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
$kernel->yield( 'DONE', $response );
return;
}
# Find which handler will handle this one
foreach my $handler ( @{ $self->handlers } ) {
# Check if this matches
if ( $path =~ $handler->{'RE'} ) {
# Send this off!
my $ok = $kernel->post( $handler->{'SESSION'}, $handler->{'EVENT'}, $request,
$response, $handler->{'DIR'}, );
# Make sure we croak if we have an issue posting
croak(
"I had a problem posting to event $handler->{'EVENT'} of session $handler->{'SESSION'} for DIR handler '$handler->{'DIR'}'",
". As reported by Kernel: '$!', perhaps the session name is spelled incorrectly for this handler?"
) unless $ok;
# All done!
return;
}
}
# If we reached here, no handler was able to handle it...
# Set response code to 404 and tell the client we didn't find anything
$response->code(404);
$response->content('404 Not Found');
$kernel->yield( 'DONE', $response );
return;
};
# 'Got_Flush'
# Finished with a request!
event 'got_flush' => sub {
my ($kernel,$self,$id) = @_[KERNEL,OBJECT,ARG0];
return unless defined $self->_requests->{$id};
# Debug stuff
warn "Got Flush event for wheel ID ( $id )" if DEBUG;
if ( $self->_requests->{$id}->streaming ) {
# Do the stream !
warn "Streaming in progress ...!" if DEBUG;
return;
}
# Check if we are shutting down
if ( $self->_requests->{$id}->done ) {
if ( $self->must_keepalive( $id ) ) {
warn "Keep-alive id=$id ..." if DEBUG;
my $state = delete $self->_requests->{$id};
$state->set_connection( $state->response->connection );
$state->reset;
$self->_connections->{$id} = $state;
delete $self->_chunkcount->{$id};
delete $self->_responses->{$id};
}
else {
# Shutdown read/write on the wheel
$self->_requests->{$id}->close_wheel;
delete $self->_requests->{$id};
}
}
else {
# Ignore this, eh?
if (DEBUG) {
warn
"Got Flush event for socket ( $id ) when we did not send anything!";
}
}
# Alright, do we have to shutdown?
unless ( $self->_factory ) {
# Check to see if we have any more requests
if ( keys( %{ $self->_requests } ) == 0
and keys( %{ $self->_connections } ) == 0 )
{
# Shutdown!
$kernel->yield('SHUTDOWN');
}
}
# Success!
return 1;
};
# should we keep-alive the connection?
sub must_keepalive {
my ( $self, $id ) = @_;
return unless $self->keepalive;
my $resp = $self->_requests->{$id}->response;
my $req = $self->_requests->{$id}->request;
# error = close
return 0 if $resp->is_error;
lib/POE/Component/Server/SimpleHTTP.pm view on Meta::CPAN
# Mark the client dead
$connection->dead(1) if $connection;
}
# Success!
return 1;
};
# 'DONE'
# Output to the client!
event 'DONE' => sub {
my ($kernel,$self,$response) = @_[KERNEL,OBJECT,ARG0];
# Check if we got it
if ( !defined $response or !UNIVERSAL::isa( $response, 'HTTP::Response' ) ) {
warn 'Did not get a HTTP::Response object!' if DEBUG;
# Abort...
return;
}
# Get the wheel ID
my $id = $response->_WHEEL;
# Check if the wheel exists ( sometimes it gets closed by the client, but the application doesn't know that... )
unless ( exists $self->_requests->{$id} ) {
# Debug stuff
warn
'Wheel disappeared, but the application sent us a DONE event, discarding it'
if DEBUG;
$kernel->post(
$self->errorhandler->{SESSION},
$self->errorhandler->{EVENT},
'Wheel disappeared !'
) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
# All done!
return 1;
}
# Check if we have already sent the response
if ( $self->_requests->{$id}->done ) {
# Tried to send twice!
die 'Tried to send a response to the same connection twice!';
}
# Quick check to see if the wheel/socket died already...
# Initially reported by Tim Wood
unless ( $self->_requests->{$id}->wheel_alive ) {
warn 'Tried to send data over a closed/nonexistant socket!' if DEBUG;
$kernel->post(
$self->errorhandler->{SESSION},
$self->errorhandler->{EVENT},
'Socket closed/nonexistant !'
) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
return;
}
# Check if we were streaming.
if ( $self->_requests->{$id}->streaming ) {
$self->_requests->{$id}->set_streaming(0);
$self->_requests->{$id}->set_done(1); # Finished streaming
# TODO: We might not get a flush, trigger it ourselves.
if ( !$self->_requests->{$id}->wheel->get_driver_out_messages ) {
$kernel->yield( 'got_flush', $id );
}
return;
}
$self->fix_headers( $response );
# Send it out!
$self->_requests->{$id}->wheel->put($response);
# Mark this socket done
$self->_requests->{$id}->set_done(1);
# Log FINALLY If they have a logFinal handler registered, send out the needed information
if ( $self->log2handler and scalar keys %{ $self->log2handler } == 2 ) {
$! = undef;
$kernel->call(
$self->log2handler->{'SESSION'},
$self->log2handler->{'EVENT'},
$self->_requests->{$id}->request, $response
);
# Warn if we had a problem dispatching to the log handler above
warn(
"I had a problem posting to event '",
$self->log2handler->{'EVENT'},
"' of the log handler alias '",
$self->log2handler->{'SESSION'},
"'. As reported by Kernel: '$!', perhaps the alias is spelled incorrectly for this handler?"
) if $!;
}
# Debug stuff
warn "Completed with Wheel ID $id" if DEBUG;
# Success!
return 1;
};
# 'STREAM'
# Stream output to the client
event 'STREAM' => sub {
my ($kernel,$self,$response) = @_[KERNEL,OBJECT,ARG0];
# Check if we got it
unless ( defined $response and UNIVERSAL::isa( $response, 'HTTP::Response' ) ) {
warn 'Did not get a HTTP::Response object!' if DEBUG;
# Abort...
return;
}
# Get the wheel ID
my $id = $response->_WHEEL;
$self->_chunkcount->{$id}++;
if ( defined $response->STREAM ) {
# Keep track if we plan to stream ...
if ( $self->_responses->{$id} ) {
warn "Restoring response from HEAP and id $id " if DEBUG;
$response = $self->_responses->{$id};
}
else {
warn "Saving HEAP response to id $id " if DEBUG;
$self->_responses->{$id} = $response;
}
}
else {
warn
'Can\'t push on a response that has not been not set as a STREAM!'
if DEBUG;
# Abort...
return;
}
# Check if the wheel exists ( sometimes it gets closed by the client, but the application doesn't know that... )
unless ( exists $self->_requests->{$id} ) {
# Debug stuff
warn
'Wheel disappeared, but the application sent us a DONE event, discarding it'
if DEBUG;
$kernel->post(
$self->errorhandler->{SESSION},
$self->errorhandler->{EVENT},
'Wheel disappeared !'
) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
# All done!
return 1;
}
# Quick check to see if the wheel/socket died already...
# Initially reported by Tim Wood
unless ( $self->_requests->{$id}->wheel_alive ) {
warn 'Tried to send data over a closed/nonexistant socket!' if DEBUG;
$kernel->post(
$self->errorhandler->{SESSION},
$self->errorhandler->{EVENT},
'Socket closed/nonexistant !'
) if $self->errorhandler and $self->errorhandler->{SESSION} and $self->errorhandler->{EVENT};
return;
}
$self->fix_headers( $response, 1 );
# Sets the correct POE::Filter
unless ( defined $response->IS_STREAMING ) {
# Mark this socket done
$self->_requests->{$id}->set_streaming(1);
$response->set_streaming(1);
}
if (DEBUG) {
warn "Sending stream via "
. $response->STREAM_SESSION . "/"
. $response->STREAM
. " with id $id \n";
}
if ( $self->_chunkcount->{$id} > 1 ) {
my $wheel = $self->_requests->{ $response->_WHEEL }->wheel;
$wheel->set_output_filter( POE::Filter::Stream->new() );
$wheel->put( $response->content );
}
else {
my $wheel = $self->_requests->{ $response->_WHEEL }->wheel;
$wheel->set_output_filter( $wheel->get_input_filter() );
$wheel->put($response);
}
# we send the event to stream with wheels request and response to the session
# that has registered the streaming event
unless ( $response->DONT_FLUSH ) {
$kernel->post(
$response->STREAM_SESSION, # callback session
$response->STREAM, # callback event
$self->_responses->{ $response->_WHEEL }
);
}
# Success!
return 1;
};
# Add required headers to a response
sub fix_headers {
my ( $self, $response, $stream ) = @_;
# Set the date if needed
if ( !$response->header('Date') ) {
$response->header( 'Date', time2str(time) );
}
# Set the Content-Length if needed
if ( !$stream and !$self->proxymode
and !defined $response->header('Content-Length')
and my $len = length $response->content )
{
use bytes;
$response->header( 'Content-Length', $len );
}
# Set the Content-Type if needed
if ( !$response->header('Content-Type') ) {
$response->header( 'Content-Type', 'text/plain' );
}
if ( !$response->protocol ) {
my $request = $self->_requests->{ $response->_WHEEL }->request;
return unless $request and $request->isa('HTTP::Request');
unless ( $request->method eq 'HEAD' ) {
$response->protocol( $request->protocol );
}
}
}
# 'CLOSE'
# Closes the connection
event 'CLOSE' => sub {
my ($kernel,$self,$response) = @_[KERNEL,OBJECT,ARG0];
# Check if we got it
unless ( defined $response and UNIVERSAL::isa( $response, 'HTTP::Response' ) ) {
warn 'Did not get a HTTP::Response object!' if DEBUG;
# Abort...
return;
}
# Get the wheel ID
my $id = $response->_WHEEL;
if ( $self->_connections->{$id} ) {
$self->_requests->{$id} = delete $self->_connections->{$id};
}
# Check if the wheel exists ( sometimes it gets closed by the client, but the application doesn't know that... )
unless ( exists $self->_requests->{$id} ) {
warn
'Wheel disappeared, but the application sent us a CLOSE event, discarding it'
if DEBUG;
return 1;
}
# Kill it!
$self->_requests->{$id}->close_wheel if $self->_requests->{$id}->wheel_alive;
# Delete it!
delete $self->_requests->{$id};
delete $self->_responses->{$id};
warn 'Delete references to the connection done.' if DEBUG;
# All done!
return 1;
};
# Registers a POE inline state (primarly for streaming)
event 'REGISTER' => sub {
my ( $session, $state, $code_ref ) = @_[ SESSION, ARG0 .. ARG1 ];
warn 'Registering state in POE session' if DEBUG;
return $session->register_state( $state, $code_ref );
};
# SETCLOSEHANDLER
event 'SETCLOSEHANDLER' => sub {
my ($self,$sender) = @_[OBJECT,SENDER ];
my ($connection,$state,@params) = @_[ARG0..$#_];
# turn connection ID into the connection object
unless ( ref $connection ) {
my $id = $connection;
if ( $self->_connections->{$id} ) {
$connection = $self->_connections->{$id}->connection;
}
elsif ($self->_requests->{$id}
and $self->_requests->{$id}->response )
{
$connection = $self->_requests->{$id}->response->connection;
}
unless ( ref $connection ) {
die "Can't find connection object for request $id";
}
}
if ($state) {
$connection->_on_close( $sender->ID, $state, @params );
}
else {
$connection->_on_close($sender->ID);
}
};
no MooseX::POE;
__PACKAGE__->meta->make_immutable( );
"Simple In'it";
__END__
=pod
=encoding UTF-8
=head1 NAME
POE::Component::Server::SimpleHTTP - Perl extension to serve HTTP requests in POE.
=head1 VERSION
version 2.30
=head1 SYNOPSIS
use POE;
use POE::Component::Server::SimpleHTTP;
lib/POE/Component/Server/SimpleHTTP.pm view on Meta::CPAN
=item C<CLOSE>
This event accepts only one argument: the HTTP::Response object we sent to the handler.
Calling this event will close the socket, not sending any output
=item C<GETHANDLERS>
This event accepts 2 arguments: The session + event to send the response to
This event will send back the current HANDLERS array ( deep-cloned via Storable::dclone )
The resulting array can be played around to your tastes, then once you are done...
=item C<SETHANDLERS>
This event accepts only one argument: pointer to HANDLERS array
BEWARE: if there is an error in the HANDLERS, SimpleHTTP will die!
=item C<SETCLOSEHANDLER>
$_[KERNEL]->call( $_[SENDER], 'SETCLOSEHANDLER', $connection,
$event, @args );
Calls C<$event> in the current session when C<$connection> is closed. You
could use for persistent connection handling.
Multiple session may register close handlers.
Calling SETCLOSEHANDLER without C<$event> to remove the current session's
handler:
$_[KERNEL]->call( $_[SENDER], 'SETCLOSEHANDLER', $connection );
You B<must> make sure that C<@args> doesn't cause a circular
reference. Ideally, use C<$connection->ID> or some other unique value
associated with this C<$connection>.
=item C<STARTLISTEN>
Starts the listening socket, if it was shut down
=item C<STOPLISTEN>
Simply a wrapper for SHUTDOWN GRACEFUL, but will not shutdown SimpleHTTP if there is no more requests
=item C<SHUTDOWN>
Without arguments, SimpleHTTP does this:
Close the listening socket
Kills all pending requests by closing their sockets
Removes it's alias
With an argument of 'GRACEFUL', SimpleHTTP does this:
Close the listening socket
Waits for all pending requests to come in via DONE/CLOSE, then removes it's alias
=item C<STREAM>
With a $response argument it streams the content and calls back the streaming event
of the user's session (or with the dont_flush option you're responsible for calling
back your session's streaming event).
To use the streaming feature see below.
=back
=head2 Streaming with SimpleHTTP
It's possible to send data as a stream to clients (unbuffered and integrated in the
POE loop).
Just create your session to receive events from SimpleHTTP as usually and add a
streaming event, this event will be triggered over and over each time you set the
$response to a streaming state and once you trigger it:
# sets the response as streamed within our session which alias is HTTP_GET
# with the event GOT_STREAM
$response->stream(
session => 'HTTP_GET',
event => 'GOT_STREAM',
dont_flush => 1
);
# then you can simply yield your streaming event, once the GOT_STREAM event
# has reached its end it will be triggered again and again, until you
# send a CLOSE event to the kernel with the appropriate response as parameter
$kernel->yield('GOT_STREAM', $response);
The optional dont_flush option gives the user the ability to control the callback
to the streaming event, which means once your stream event has reached its end
it won't be called, you have to call it back.
You can now send data by chunks and either call yourself back (via POE) or
shutdown when your streaming is done (EOF for example).
sub GOT_STREAM {
my ( $kernel, $heap, $response ) = @_[KERNEL, HEAP, ARG0];
# sets the content of the response
$response->content("Hello World\n");
# send it to the client
POE::Kernel->post('HTTPD', 'STREAM', $response);
# if we have previously set the dont_flush option
# we have to trigger our event back until the end of
# the stream like this (that can be a yield, of course):
#
# $kernel->delay('GOT_STREAM', 1, $stream );
# otherwise the GOT_STREAM event is triggered continuously until
# we call the CLOSE event on the response like that :
#
if ($heap{'streaming_is_done'}) {
# close the socket and end the stream
POE::Kernel->post('HTTPD', 'CLOSE', $response );
}
}
The dont_flush option is there to be able to control the frequency of flushes
to the client.
=head2 SimpleHTTP Notes
You can enable debugging mode by doing this:
sub POE::Component::Server::SimpleHTTP::DEBUG () { 1 }
use POE::Component::Server::SimpleHTTP;
Also, this module will try to keep the Listening socket alive.
if it dies, it will open it again for a max of 5 retries.
You can override this behavior by doing this:
sub POE::Component::Server::SimpleHTTP::MAX_RETRIES () { 10 }
use POE::Component::Server::SimpleHTTP;
For those who are pondering about basic-authentication, here's a tiny snippet to put in the Event handler
# Contributed by Rocco Caputo
sub Got_Request {
# ARG0 = HTTP::Request, ARG1 = HTTP::Response
my( $request, $response ) = @_[ ARG0, ARG1 ];
# Get the login
my ( $login, $password ) = $request->authorization_basic();
# Decide what to do
if ( ! defined $login or ! defined $password ) {
# Set the authorization
$response->header( 'WWW-Authenticate' => 'Basic realm="MyRealm"' );
$response->code( 401 );
$response->content( 'FORBIDDEN.' );
# Send it off!
$_[KERNEL]->post( 'SimpleHTTP', 'DONE', $response );
} else {
# Authenticate the user and move on
}
}
=head2 EXPORT
Nothing.
=for Pod::Coverage MassageHandlers
START
STOP
fix_headers
getsockname
must_keepalive
session_id
shutdown
( run in 0.376 second using v1.01-cache-2.11-cpan-140bd7fdf52 )