create symlinks based on _dispatch to dumped requsts
[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::Methods;
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         $dump_nr++;
111         my $file = sprintf("dump/%04d-%s.request", $dump_nr, $sock->peerhost);
112
113         if ( $self->debug > 2 ) {
114                 write_file( $file, $r->as_string );
115                 warn "### request dumped to file: $file\n";
116         }
117
118         my $state;
119
120         if ( $size > 0 ) {
121
122                 die "no SOAPAction header in ",dump($xml) unless defined ( $r->header('SOAPAction') );
123
124                 warn "## request payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
125
126                 $state = CWMP::Request->parse( $xml );
127
128                 if ( defined( $state->{_dispatch} ) && $self->debug > 2 ) {
129                         my $type = sprintf("dump/%04d-%s-%s", $dump_nr, $sock->peerhost, $state->{_dispatch});
130                         symlink $file, $type || warn "can't symlink $file -> $type: $!";
131                 }
132
133                 warn "## acquired state = ", dump( $state ), "\n";
134
135                 $self->state( $state );
136                 $self->store->update_state( ID => $state->{ID}, $state );
137
138         } else {
139
140                 warn "## empty request, using last request state\n";
141
142                 $state = $self->state;
143                 delete( $state->{_dispatch} );
144                 #warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;
145         }
146
147
148         $sock->send(join("\r\n",
149                 'HTTP/1.1 200 OK',
150                 'Content-Type: text/xml; charset="utf-8"',
151                 'Server: AcmeCWMP/42',
152                 'SOAPServer: AcmeCWMP/42'
153         )."\r\n");
154
155         $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );
156         
157         $xml = '';
158
159         if ( my $dispatch = $state->{_dispatch} ) {
160                 $xml = $self->dispatch( $dispatch );
161         } elsif ( $dispatch = shift @{ $self->queue } ) {
162                 $xml = $self->dispatch( $dispatch );
163         } elsif ( $size == 0 ) {
164                 warn ">>> no more queued commands, closing connection\n";
165                 return 0;
166         } else {
167                 warn ">>> empty response\n";
168                 $state->{NoMoreRequests} = 1;
169                 $xml = $self->dispatch( 'xml', sub {} );
170         }
171
172         $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
173         $sock->send( $xml ) or die "can't send response";
174
175         warn ">>>> " . $sock->peerhost . " [" . localtime() . "] sent ", length( $xml )," bytes\n";
176
177         warn "### request over\n" if $self->debug;
178
179         return 1;       # next request
180 };
181
182 =head2 dispatch
183
184   $xml = $self->dispatch('Inform', $response_arguments );
185
186 If debugging level of 3 or more, it will create dumps of responses named C<< dump/nr.response >>
187
188 =cut
189
190 sub dispatch {
191         my $self = shift;
192
193         my $dispatch = shift || die "no dispatch?";
194         my @args = @_;
195
196         if ( ref($dispatch) eq 'ARRAY' ) {
197                 my @a = @$dispatch;
198                 $dispatch = shift @a;
199                 push @args, @a;
200         }
201
202         my $response = CWMP::Methods->new({ debug => $self->debug });
203
204         if ( $response->can( $dispatch ) ) {
205                 warn ">>> dispatching to $dispatch\n";
206                 my $xml = $response->$dispatch( $self->state, @args );
207                 warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
208                 if ( $self->debug > 2 ) {
209                         my $file = sprintf("dump/%04d-%s.response", $dump_nr++, $self->sock->peerhost);
210                         write_file( $file, $xml );
211                         warn "### response dump: $file\n";
212                 }
213                 return $xml;
214         } else {
215                 confess "can't dispatch to $dispatch";
216         }
217 };
218
219
220 =head2 error
221
222   return $self->error( 501, 'System error' );
223
224 =cut
225
226 sub error {
227   my ($self, $number, $msg) = @_;
228   $msg ||= 'ERROR';
229   $self->sock->send( "HTTP/1.1 $number $msg\r\n" );
230   warn "Error - $number - $msg\n";
231   return 0;     # close connection
232 }
233
234 1;