- implement parametars to commands in queue (just pass array as command)
[perl-cwmp.git] / lib / CWMP / Session.pm
1 # Dobrica Pavlinusic, <dpavlin@rot13.org> 06/18/07 10:19:50 CEST
2 package CWMP::Session;
3
4 use strict;
5 use warnings;
6
7 use base qw/Class::Accessor/;
8 __PACKAGE__->mk_accessors( qw/
9 debug
10 store
11
12 sock
13 state
14 queue
15 store
16 / );
17
18 use HTTP::Daemon;
19 use Data::Dump qw/dump/;
20 use Carp qw/confess cluck croak/;
21 use File::Slurp;
22
23 use CWMP::Request;
24 use CWMP::Response;
25 use CWMP::Store;
26
27 =head1 NAME
28
29 CWMP::Session - implement logic of CWMP protocol
30
31 =head1 METHODS
32
33 =head2 new
34
35   my $server = CWMP::Session->new({
36         sock => $io_socket_object,
37         store => 'state.db',
38         queue => [
39                 'GetRPCMethods',
40                 [ 'GetParameterValyes', 'InternetGatewayDevice.DeviceInfo.SerialNumber', 0 ],
41         ],
42         debug => 1,
43   });
44
45 =cut
46
47 sub new {
48         my $class = shift;
49         my $self = $class->SUPER::new( @_ );
50
51         confess "need sock" unless $self->sock;
52
53         $self->debug( 0 ) unless $self->debug;
54
55         warn "created ", __PACKAGE__, "(", dump( @_ ), ") for ", $self->sock->peerhost, "\n" if $self->debug;
56
57         my $store_obj = CWMP::Store->new({
58                 debug => $self->debug,
59                 %{ $self->store },
60         });
61
62         croak "can't open ", dump( $self->store ), ": $!" unless $store_obj;
63
64         # FIXME looks ugly. Should we have separate accessor for this?
65         $self->store( $store_obj );
66
67         return $self;
68 }
69
70 =head2 process_request
71
72 One request from client/response from server cycle. Call multiple times to
73 facilitate brain-dead concept of adding state to stateless protocol like
74 HTTP.
75
76 If used with debugging level of 3 or more, it will also create dumps of
77 requests named C<< dump/nr.request >> where C<nr> is number from 0 to total number
78 of requests in single session.
79
80 =cut
81
82 my $dump_nr = 0;
83
84 sub process_request {
85         my $self = shift;
86
87         my $sock = $self->sock || die "no sock?";
88
89 #       die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'Net::Server::Proto::TCP' );
90
91         if ( ! $sock->connected ) {
92                 warn "SOCKET NOT CONNECTED\n";
93                 return 0;
94         }
95
96         bless $sock, 'HTTP::Daemon::ClientConn';
97
98         # why do I have to do this?
99         # solution from http://use.perl.org/~Matts/journal/12896
100         ${*$sock}{'httpd_daemon'} = HTTP::Daemon->new;
101
102         my $r = $sock->get_request || confess "can't get_request";
103
104         my $xml = $r->content;
105
106         my $size = length( $xml );
107
108         warn "<<<< ", $sock->peerhost, " [" . localtime() . "] ", $r->method, " ", $r->uri, " $size bytes\n";
109
110         if ( $self->debug > 2 ) {
111                 my $file = sprintf("dump/%04d-%s.request", $dump_nr++, $sock->peerhost);
112                 write_file( $file, $r->as_string );
113                 warn "### request dumped to file: $file\n";
114         }
115
116         my $state;
117
118         if ( $size > 0 ) {
119
120                 die "no SOAPAction header in ",dump($xml) unless defined ( $r->header('SOAPAction') );
121
122                 warn "## request payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
123
124                 $state = CWMP::Request->parse( $xml );
125
126                 warn "## acquired state = ", dump( $state ), "\n";
127
128                 $self->state( $state );
129                 $self->store->update_state( ID => $state->{ID}, $state );
130
131         } else {
132
133                 warn "## empty request, using last request state\n";
134
135                 $state = $self->state;
136                 delete( $state->{_dispatch} );
137                 #warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;
138         }
139
140
141         $sock->send(join("\r\n",
142                 'HTTP/1.1 200 OK',
143                 'Content-Type: text/xml; charset="utf-8"',
144                 'Server: AcmeCWMP/42',
145                 'SOAPServer: AcmeCWMP/42'
146         )."\r\n");
147
148         $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );
149         
150         my $xml = '';
151
152         if ( my $dispatch = $state->{_dispatch} ) {
153                 $xml = $self->dispatch( $dispatch );
154         } elsif ( $dispatch = shift @{ $self->queue } ) {
155                 $xml = $self->dispatch( $dispatch );
156         } elsif ( $size == 0 ) {
157                 warn ">>> no more queued commands, closing connection\n";
158                 return 0;
159         } else {
160                 warn ">>> empty response\n";
161                 $state->{NoMoreRequests} = 1;
162                 $xml = $self->dispatch( 'xml', sub {} );
163         }
164
165         $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
166         $sock->send( $xml ) or die "can't send response";
167
168         warn ">>>> " . $sock->peerhost . " [" . localtime() . "] sent ", length( $xml )," bytes\n";
169
170         warn "### request over\n" if $self->debug;
171
172         return 1;       # next request
173 };
174
175 =head2 dispatch
176
177   $xml = $self->dispatch('Inform', $response_arguments );
178
179 If debugging level of 3 or more, it will create dumps of responses named C<< dump/nr.response >>
180
181 =cut
182
183 sub dispatch {
184         my $self = shift;
185
186         my $dispatch = shift || die "no dispatch?";
187         my @args = @_;
188
189         if ( ref($dispatch) eq 'ARRAY' ) {
190                 my @a = @$dispatch;
191                 $dispatch = shift @a;
192                 push @args, @a;
193         }
194
195         my $response = CWMP::Response->new({ debug => $self->debug });
196
197         if ( $response->can( $dispatch ) ) {
198                 warn ">>> dispatching to $dispatch\n";
199                 my $xml = $response->$dispatch( $self->state, @args );
200                 warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
201                 if ( $self->debug > 2 ) {
202                         my $file = sprintf("dump/%04d-%s.response", $dump_nr++, $self->sock->peerhost);
203                         write_file( $file, $xml );
204                         warn "### response dump: $file\n";
205                 }
206                 return $xml;
207         } else {
208                 confess "can't dispatch to $dispatch";
209         }
210 };
211
212
213 =head2 error
214
215   return $self->error( 501, 'System error' );
216
217 =cut
218
219 sub error {
220   my ($self, $number, $msg) = @_;
221   $msg ||= 'ERROR';
222   $self->sock->send( "HTTP/1.1 $number $msg\r\n" );
223   warn "Error - $number - $msg\n";
224   return 0;     # close connection
225 }
226
227 1;