1 |
# Dobrica Pavlinusic, <dpavlin@rot13.org> 06/18/07 10:19:50 CEST |
2 |
package CWMP::Server; |
3 |
|
4 |
use strict; |
5 |
use warnings; |
6 |
|
7 |
use base qw/HTTP::Server::Simple::CGI Class::Accessor/; |
8 |
__PACKAGE__->mk_accessors( qw/ |
9 |
debug |
10 |
/ ); |
11 |
|
12 |
use Data::Dump qw/dump/; |
13 |
use CWMP::Request; |
14 |
use CWMP::Response; |
15 |
use Carp qw/confess/; |
16 |
|
17 |
=head1 NAME |
18 |
|
19 |
CWMP::Server - implement logic of CWMP protocol |
20 |
|
21 |
=head1 METHODS |
22 |
|
23 |
=head2 handler |
24 |
|
25 |
We override L<HTTP::Server::Simple::CGI/handler> so that we can support |
26 |
chunked transfer encoding. |
27 |
|
28 |
=cut |
29 |
|
30 |
sub handler { |
31 |
my $self = shift; |
32 |
|
33 |
my $chunk; |
34 |
|
35 |
my $transfer_encoding = $self->header('Transfer-Encoding'); |
36 |
|
37 |
if ( $transfer_encoding && $transfer_encoding =~ qr/^chunked/i ) { |
38 |
|
39 |
my $len = 0; |
40 |
my $hex; |
41 |
do { |
42 |
$hex = <STDIN>; # get chunk length |
43 |
$hex =~ s/[\n\r]*$//s; |
44 |
$len = hex( $hex ); |
45 |
|
46 |
warn "getting chunk of 0x$hex $len bytes\n" if $self->debug; |
47 |
|
48 |
while( $len > 0 ) { |
49 |
my $line = <STDIN>; |
50 |
$chunk .= $line; |
51 |
$len -= length( $line ); |
52 |
} |
53 |
|
54 |
} while ( hex( $hex ) != 0 ); |
55 |
} |
56 |
|
57 |
warn "handler got ", length($chunk), " bytes\n" if $self->debug; |
58 |
|
59 |
my $cgi = new CGI( $chunk ); |
60 |
|
61 |
eval { $self->handle_request($cgi) }; |
62 |
if ($@) { |
63 |
my $error = $@; |
64 |
warn $error; |
65 |
} |
66 |
} |
67 |
|
68 |
=head2 handle_request |
69 |
|
70 |
Implementation of dispatch logic |
71 |
|
72 |
=cut |
73 |
|
74 |
sub handle_request { |
75 |
my ($self, $cgi) = @_; |
76 |
|
77 |
#... do something, print output to default |
78 |
# selected filehandle... |
79 |
|
80 |
warn "<<< " . localtime() . " " . $ENV{REMOTE_ADDR} . "\n"; |
81 |
|
82 |
warn "not SOAP request" unless defined ( $cgi->header('SOAPAction') ); |
83 |
|
84 |
my $state; |
85 |
|
86 |
if ( my $payload = $cgi->param('POSTDATA') ) { |
87 |
warn "request payload:\n$payload\n" if $self->debug; |
88 |
|
89 |
$state = CWMP::Request->parse( $payload ); |
90 |
|
91 |
warn "acquired state = ", dump( $state ); |
92 |
|
93 |
} else { |
94 |
warn "empty request\n"; |
95 |
} |
96 |
|
97 |
my $response = CWMP::Response->new({ debug => $self->debug }); |
98 |
|
99 |
print "Content-Type: text/xml\r\n\r\n"; |
100 |
|
101 |
if ( my $dispatch = $state->{_dispatch} ) { |
102 |
if ( $response->can( $dispatch ) ) { |
103 |
warn ">>> dispatching to $dispatch\n"; |
104 |
print $response->$dispatch; |
105 |
} else { |
106 |
confess "can't dispatch to $dispatch"; |
107 |
} |
108 |
} else { |
109 |
warn ">>> empty response\n"; |
110 |
} |
111 |
|
112 |
}; |
113 |
|
114 |
1; |
115 |
|