| 1 | =head1 NAME | ||
| 2 | |||
| 3 | Net::RVP::Server - listening RVP server using the Event module | ||
| 4 | |||
| 5 | =head1 METHODS | ||
| 6 | |||
| 7 | =cut | ||
| 8 | package Net::RVP::Server; | ||
| 9 | |||
| 10 | use strict; | ||
| 11 | use base qw(Event::IO::Record); | ||
| 12 | |||
| 13 | use HTTP::Parser; | ||
| 14 | use HTTP::Status; | ||
| 15 | |||
| 16 | |||
| 17 | =head2 new ( named parameters ) | ||
| 18 | |||
| 19 | IM notify server connection object. | ||
| 20 | |||
| 21 | =cut | ||
| 22 | sub new { | ||
| 23 | my ($class,%param) = shift; | ||
| 24 | my $self = $class->SUPER::new(@_); | ||
| 25 | @{$self}{qw(rs_state rs_parser)} = ('','',undef); | ||
| 26 | $self->IRS("\x0d?\x0a\x0d?\x0a"); # look for end of HTTP headers | ||
| 27 | return $self; | ||
| 28 | } | ||
| 29 | |||
| 30 | |||
| 31 | =head2 init_event ( callback ) | ||
| 32 | |||
| 33 | The callback should be a CODE ref which is called with an HTTP::Request and | ||
| 34 | should return an HTTP::Response object. See also L<Event::IO::Server>. | ||
| 35 | |||
| 36 | =cut | ||
| 37 | sub init_event { | ||
| 38 | my ($self,$cb) = @_; | ||
| 39 | $self->{rs_sink} = $cb; | ||
| 40 | $self->SUPER::init_event(); | ||
| 41 | } | ||
| 42 | |||
| 43 | |||
| 44 | =head2 line_event ( line ) | ||
| 45 | |||
| 46 | Received a line of input. | ||
| 47 | |||
| 48 | =cut | ||
| 49 | sub line_event { | ||
| 50 | my ($self,$line) = @_; | ||
| 51 | |||
| 52 | # parse HTTP header if we have it | ||
| 53 | if($self->{rs_state} eq '') { | ||
| 54 | $self->{rs_parser} = HTTP::Parser->new(); | ||
| 55 | $line .= "\x0d\x0a\x0d\x0a"; | ||
| 56 | $self->IRS('\z'); | ||
| 57 | } | ||
| 58 | |||
| 59 | my $result = eval { $self->{rs_state} = $self->{rs_parser}->add($line); }; | ||
| 60 | if($@) { | ||
| 61 | $self->write("$@\n"); | ||
| 62 | return $self->close(); | ||
| 63 | } | ||
| 64 | |||
| 65 | if(0 == $result) { | ||
| 66 | $result = $self->{rs_parser}->request(); | ||
| 67 | my $response = $self->{rs_sink}->($result); | ||
| 68 | $response = HTTP::Response->new(RC_INTERNAL_SERVER_ERROR,$response) | ||
| 69 | unless ref $response; | ||
| 70 | |||
| 71 | my $http_ver = $result->header('X-HTTP-Version') || '1.1'; | ||
| 72 | $self->write("HTTP/$http_ver ".$response->code().' '.$response->message(). | ||
| 73 | "\x0d\x0a".$response->headers()->as_string("\x0d\x0a")."\x0d\x0a". | ||
| 74 | $response->content()); | ||
| 75 | |||
| 76 | # close connection if < HTTP 1.1 or Connection: close requested | ||
| 77 | if($http_ver < 1.1 or grep /\bclose\b/, $result->header('connection')) { | ||
| 78 | $self->close(); | ||
| 79 | } else { | ||
| 80 | $self->{rs_state} = ''; # ready for another request | ||
| 81 | $self->IRS("\x0d?\x0a\x0d?\x0a"); | ||
| 82 | } | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | |||
| 87 | =head1 AUTHOR | ||
| 88 | |||
| 89 | David Robins E<lt>dbrobins@davidrobins.netE<gt>. | ||
| 90 | |||
| 91 | =cut | ||
| 92 | |||
| 93 | |||
| 94 | 1; |