e96f08d46592290fa54daedcb4e14dba74a14c22
[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 create_dump
11 session
12
13 sock
14 state
15 store
16 / );
17
18 use HTTP::Daemon;
19 use Data::Dump qw/dump/;
20 use Carp qw/carp confess cluck croak/;
21 use File::Slurp;
22 use File::Path qw/mkpath/;
23
24 use CWMP::Request;
25 use CWMP::Methods;
26 use CWMP::Store;
27
28 #use Devel::LeakTrace::Fast;
29
30 =head1 NAME
31
32 CWMP::Session - implement logic of CWMP protocol
33
34 =head1 METHODS
35
36 =head2 new
37
38   my $server = CWMP::Session->new({
39         sock => $io_socket_object,
40         store => { ... },
41         debug => 1,
42         create_dump => 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         confess "need store" unless $self->store;
53         my $peerhost = $self->sock->peerhost || confess "can't get sock->peerhost";
54
55         $self->debug( 0 ) unless $self->debug;
56
57         warn "created ", __PACKAGE__, "(", dump( @_ ), ") for $peerhost\n" if $self->debug;
58
59         my $store_obj = CWMP::Store->new({
60                 debug => $self->debug,
61                 %{ $self->store },
62         });
63
64         croak "can't open ", dump( $self->store ), ": $!" unless $store_obj;
65
66         # FIXME looks ugly. Should we have separate accessor for this?
67         $self->store( $store_obj );
68
69         $self->create_dump( 1 ) if $self->debug > 2;
70
71         return $self;
72 }
73
74 =head2 process_request
75
76 One request from client/response from server cycle. Call multiple times to
77 facilitate brain-dead concept of adding state to stateless protocol like
78 HTTP.
79
80 If used with debugging level of 3 or more, it will also create dumps of
81 requests named C<< dump/nr.request >> where C<nr> is number from 0 to total number
82 of requests in single session.
83
84 =cut
85
86 my $dump_by_ip;
87
88 sub process_request {
89         my $self = shift;
90
91         my $sock = $self->sock || die "no sock?";
92
93 #       die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'Net::Server::Proto::TCP' );
94
95         if ( ! $sock->connected ) {
96                 warn "SOCKET NOT CONNECTED\n";
97                 return 0;
98         }
99
100         bless $sock, 'HTTP::Daemon::ClientConn';
101
102         # why do I have to do this?
103         # solution from http://use.perl.org/~Matts/journal/12896
104         ${*$sock}{'httpd_daemon'} = HTTP::Daemon->new;
105
106         my $r = $sock->get_request;
107         
108         if ( ! $r ) {
109                 carp "can't get_request";
110                 return 0;
111         }
112
113         my $ip = $sock->peerhost || confess "can't get peerhost from sock: $!";
114
115         my $xml = $r->content;
116
117         my $size = length( $xml );
118
119         warn "<<<< $ip [" . localtime() . "] ", $r->method, " ", $r->uri, " $size bytes\n";
120
121         my $dump_nr = $dump_by_ip->{$ip}++;
122         my $file = sprintf("./dump/%s/%04d.request", $ip, $dump_nr);
123
124         if ( $self->create_dump ) {
125                 mkpath "dump/$ip" unless -e "dump/$ip";
126                 write_file( $file, $r->as_string );
127                 warn "### request dumped to file: $file\n" if $self->debug;
128         }
129
130         my $state;
131
132         if ( $size > 0 ) {
133
134                 die "no SOAPAction header in ",dump($xml) unless defined ( $r->header('SOAPAction') );
135
136                 warn "## request payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
137
138                 $state = CWMP::Request->parse( $xml );
139
140                 if ( defined( $state->{_trigger} ) && $self->create_dump ) {
141                         my $type = sprintf("dump/%s/%04d-%s", $ip, $dump_nr, $state->{_trigger});
142                         $file =~ s!^.*?([^/]+)$!$1!;    #!vim
143                         symlink $file, $type || warn "can't symlink $file -> $type: $!";
144                 }
145
146                 warn "## acquired state = ", dump( $state ), "\n" if $self->debug;
147
148                 if ( ! defined( $state->{DeviceID} ) ) {
149                         warn "## state with DeviceID, using old one...\n";
150                         $state->{DeviceID} = $self->state->{DeviceID};
151                 }
152
153                 $self->state( $state );
154                 $self->store->update_state( $state );
155
156         } else {
157
158                 warn "## empty request, using last request state\n";
159
160                 $state = $self->state;
161                 delete( $state->{_dispatch} );
162                 #warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;
163         }
164
165         $sock->send(join("\r\n",
166                 'HTTP/1.1 200 OK',
167                 'Content-Type: text/xml; charset="utf-8"',
168                 'Server: PerlCWMP/42',
169                 'SOAPServer: PerlCWMP/42'
170         )."\r\n");
171
172         $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );
173
174         my $uid = $self->store->state_to_uid( $state );
175
176         my $to_uid = join(" ", grep { defined($_) } "to $uid",
177                         # board
178                         $state->{Parameter}->{'InternetGatewayDevice.DeviceInfo.HardwareVersion'},
179                         # version
180                         $state->{Parameter}->{'InternetGatewayDevice.DeviceInfo.SoftwareVersion'},
181                         # summary
182 #                       $state->{Parameter}->{'InternetGatewayDevice.DeviceSummary'},
183         ) . "\n";
184
185         my $queue = CWMP::Queue->new({
186                 id => $uid,
187                 debug => $self->debug,
188         });
189         my $job;
190         $xml = '';
191
192         if ( my $dispatch = $state->{_dispatch} ) {
193                 $xml = $self->dispatch( $dispatch );
194         } elsif ( $job = $queue->dequeue ) {
195                 $xml = $self->dispatch( $job->dispatch );
196         } elsif ( $size == 0 ) {
197                 warn ">>> over, closing connection $to_uid";
198                 $sock->close;
199                 return;
200         } else {
201                 warn ">>> empty response $to_uid";
202                 $state->{NoMoreRequests} = 1;
203                 $xml = $self->dispatch( 'xml', sub {} );
204         }
205
206         $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
207         $sock->send( $xml ) or die "can't send response";
208
209         warn ">>>> " . $ip . " [" . localtime() . "] sent ", length( $xml )," bytes $to_uid";
210
211         $job->finish if $job;
212         warn "### request over for $uid\n" if $self->debug;
213
214         return 1;       # next request
215 };
216
217 =head2 dispatch
218
219   $xml = $self->dispatch('Inform', $response_arguments );
220
221 If debugging level of 3 or more, it will create dumps of responses named C<< dump/nr.response >>
222
223 =cut
224
225 sub dispatch {
226         my $self = shift;
227
228         my $dispatch = shift || die "no dispatch?";
229         my $args = shift;
230
231         my $response = CWMP::Methods->new({ debug => $self->debug });
232
233         if ( $response->can( $dispatch ) ) {
234                 warn ">>> dispatching to $dispatch with args ",dump( $args ),"\n";
235                 my $xml = $response->$dispatch( $self->state, $args );
236                 warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
237                 if ( $self->create_dump ) {
238                         my $ip = $self->sock->peerhost || confess "can't get sock->peerhost: $!";
239                         my $dump_nr = $dump_by_ip->{$ip}++;
240                         my $file = sprintf("dump/%s/%04d.response", $ip, $dump_nr );
241                         write_file( $file, $xml );
242                         warn "### response dump: $file\n" if $self->debug;
243                 }
244                 return $xml;
245         } else {
246                 confess "can't dispatch to $dispatch";
247         }
248 };
249
250
251 =head2 error
252
253   return $self->error( 501, 'System error' );
254
255 =cut
256
257 sub error {
258   my ($self, $number, $msg) = @_;
259   $msg ||= 'ERROR';
260   $self->sock->send( "HTTP/1.1 $number $msg\r\n" );
261   warn "Error - $number - $msg\n";
262   return 0;     # close connection
263 }
264
265 1;