/[cwmp]/google/trunk/lib/CWMP/Session.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /google/trunk/lib/CWMP/Session.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

google/lib/CWMP/Session.pm revision 100 by dpavlin, Sun Jun 24 18:18:47 2007 UTC google/trunk/lib/CWMP/Session.pm revision 223 by dpavlin, Sat Nov 24 02:17:40 2007 UTC
# Line 7  use warnings; Line 7  use warnings;
7  use base qw/Class::Accessor/;  use base qw/Class::Accessor/;
8  __PACKAGE__->mk_accessors( qw/  __PACKAGE__->mk_accessors( qw/
9  debug  debug
10  store_path  create_dump
11    session
12    
13  sock  sock
14  state  state
 queue  
15  store  store
16  / );  / );
17    
18  use IO::Socket::INET;  use HTTP::Daemon;
19  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
20  use Carp qw/confess cluck croak/;  use Carp qw/carp confess cluck croak/;
21    use File::Slurp;
22    
23  use CWMP::Request;  use CWMP::Request;
24  use CWMP::Response;  use CWMP::Methods;
25  use CWMP::Store;  use CWMP::Store;
26    
27    #use Devel::LeakTrace::Fast;
28    
29  =head1 NAME  =head1 NAME
30    
31  CWMP::Session - implement logic of CWMP protocol  CWMP::Session - implement logic of CWMP protocol
# Line 32  CWMP::Session - implement logic of CWMP Line 35  CWMP::Session - implement logic of CWMP
35  =head2 new  =head2 new
36    
37    my $server = CWMP::Session->new({    my $server = CWMP::Session->new({
38          sock => $io_socket_object,          sock => $io_socket_object,
39          store_path => 'state.db',          store => { ... },
         queue => [ qw/GetRPCMethods GetParameterNames/ ],  
40          debug => 1,          debug => 1,
41            create_dump => 1,
42    });    });
43    
   
44  =cut  =cut
45    
46  sub new {  sub new {
# Line 46  sub new { Line 48  sub new {
48          my $self = $class->SUPER::new( @_ );          my $self = $class->SUPER::new( @_ );
49    
50          confess "need sock" unless $self->sock;          confess "need sock" unless $self->sock;
51            confess "need store" unless $self->store;
52            my $peerhost = $self->sock->peerhost || confess "can't get sock->peerhost";
53    
54          $self->debug( 0 ) unless $self->debug;          $self->debug( 0 ) unless $self->debug;
55    
56          warn "created ", __PACKAGE__, "(", dump( @_ ), ") for ", $self->sock->peerhost, "\n" if $self->debug;          warn "created ", __PACKAGE__, "(", dump( @_ ), ") for $peerhost\n" if $self->debug;
57    
58          $self->store( CWMP::Store->new({          my $store_obj = CWMP::Store->new({
59                  debug => $self->debug,                  debug => $self->debug,
60                  path => $self->store_path,                  %{ $self->store },
61          }) );          });
62    
63            croak "can't open ", dump( $self->store ), ": $!" unless $store_obj;
64    
65            # FIXME looks ugly. Should we have separate accessor for this?
66            $self->store( $store_obj );
67    
68          croak "can't open ", $self->store_path, ": $!" unless $self->store;          $self->create_dump( 1 ) if $self->debug > 2;
69    
70          return $self;          return $self;
71  }  }
# Line 67  One request from client/response from se Line 76  One request from client/response from se
76  facilitate brain-dead concept of adding state to stateless protocol like  facilitate brain-dead concept of adding state to stateless protocol like
77  HTTP.  HTTP.
78    
79    If used with debugging level of 3 or more, it will also create dumps of
80    requests named C<< dump/nr.request >> where C<nr> is number from 0 to total number
81    of requests in single session.
82    
83  =cut  =cut
84    
85    my $dump_nr = 0;
86    
87  sub process_request {  sub process_request {
88          my $self = shift;          my $self = shift;
89    
90          my $sock = $self->sock || die "no sock?";          my $sock = $self->sock || die "no sock?";
91    
92          die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'Net::Server::Proto::TCP' );  #       die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'Net::Server::Proto::TCP' );
93    
94          if ( ! $sock->connected ) {          if ( ! $sock->connected ) {
95                  warn "SOCKET NOT CONNECTED\n";                  warn "SOCKET NOT CONNECTED\n";
96                  return 0;                  return 0;
97          }          }
98    
99          $sock->autoflush( 1 );          bless $sock, 'HTTP::Daemon::ClientConn';
         $sock->blocking( 1 );  
   
         ### read the first line of response  
         my $line = $sock->getline;  
         return $self->error(400, "No Data") unless ( defined $line );  
   
         $line =~ s/[\r\n]+$//;  
         if ($line !~ /^ (\w+) \ + (\S+) \ + (HTTP\/1.\d) $ /x) {  
                 warn "ERROR: $line\n";  
                 return $self->error(400, "Bad request");  
         }  
         my ($method, $req, $protocol) = ($1, $2, $3);  
         warn "<<<< ", $sock->peerhost, " - - [" . localtime() . "] \"$method $req $protocol\"\n";  
100    
101          ### read in other headers          # why do I have to do this?
102          $self->read_headers || return $self->error(400, "Strange headers");          # solution from http://use.perl.org/~Matts/journal/12896
103            ${*$sock}{'httpd_daemon'} = HTTP::Daemon->new;
104    
105          ### do we support the type          my $r = $sock->get_request;
106  #       if ($method !~ /GET|POST|HEAD/) {          
107          if ($method !~ /POST/) {          if ( ! $r ) {
108                  return $self->error(400, "Unsupported Method");                  carp "can't get_request";
109                    return 0;
110          }          }
111    
112      my $chunk;          my $xml = $r->content;
         my $transfer_encoding = $self->header('Transfer-Encoding');  
   
         if ( $transfer_encoding && $transfer_encoding =~ qr/^chunked/i ) {  
   
                 my $len = 0;  
   
                 do {  
   
                         warn "get chunk len\n" if $self->debug > 1;  
                           
                         my $hex;  
                         do {  
                                 $hex = $sock->getline;  
                                 $hex =~ s/[\n\r]+$//;  
                         } until ( $hex ne '' );  
113    
114                          die "chunk size not valid hex: $hex" unless ( $hex =~ m/^[0-9a-f]+$/i);          my $size = length( $xml );
                         $len = hex( $hex );  
115    
116                          warn "getting chunk of $len bytes\n" if $self->debug > 1;          warn "<<<< ", $sock->peerhost, " [" . localtime() . "] ", $r->method, " ", $r->uri, " $size bytes\n";
117    
118                          $sock->read( my $buff, $len );          $dump_nr++;
119                          $chunk .= $buff;          my $file = sprintf("dump/%04d-%s.request", $dump_nr, $sock->peerhost);
120    
121                          warn "--- $len bytes: --=>||$buff||<=--\n" if $self->debug > 1;          if ( $self->create_dump ) {
122                    write_file( $file, $r->as_string );
123                  } while ( $len > 0 );                  warn "### request dumped to file: $file\n" if $self->debug;
                 my $sep = $sock->getline;  
                 die "expected separator, not ", dump( $sep ) if ( $sep !~ m/^[\n\r]+$/ );  
   
         } else {  
                 die "right now, we support only Transfer-Encoding: chunked";  
124          }          }
125    
         my $size = length( $chunk );  
   
         warn "<<<< " . $sock->peerhost . " [" . localtime() . "] request $size bytes\n";  
   
126          my $state;          my $state;
127    
128          if ( $size > 0 ) {          if ( $size > 0 ) {
129    
130                  die "no SOAPAction header in ",dump($chunk) unless defined ( $self->header('SOAPAction') );                  die "no SOAPAction header in ",dump($xml) unless defined ( $r->header('SOAPAction') );
   
131    
132                  if ( $chunk ) {                  warn "## request payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
                         warn "## request chunk: ",length($chunk)," bytes\n$chunk\n" if $self->debug;  
133    
134                          $state = CWMP::Request->parse( $chunk );                  $state = CWMP::Request->parse( $xml );
135    
136                          warn "## acquired state = ", dump( $state ), "\n";                  if ( defined( $state->{_dispatch} ) && $self->create_dump ) {
137                            my $type = sprintf("dump/%04d-%s-%s", $dump_nr, $sock->peerhost, $state->{_dispatch});
138                            symlink $file, $type || warn "can't symlink $file -> $type: $!";
139                    }
140    
141                          $self->state( $state );                  warn "## acquired state = ", dump( $state ), "\n" if $self->debug;
                         $self->store->update_state( ID => $state->{ID}, $state );  
142    
143                  } else {                  if ( ! defined( $state->{DeviceID} ) ) {
144                          warn "## empty request\n";                          warn "## state with DeviceID, using old one...\n";
145                            $state->{DeviceID} = $self->state->{DeviceID};
146                  }                  }
147    
148                    $self->state( $state );
149                    $self->store->update_state( $state );
150    
151          } else {          } else {
152    
153                    warn "## empty request, using last request state\n";
154    
155                  $state = $self->state;                  $state = $self->state;
156                  warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;                  delete( $state->{_dispatch} );
157                    #warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;
158          }          }
159    
   
160          $sock->send(join("\r\n",          $sock->send(join("\r\n",
161                  'HTTP/1.1 200 OK',                  'HTTP/1.1 200 OK',
162                  'Content-Type: text/xml; charset="utf-8"',                  'Content-Type: text/xml; charset="utf-8"',
163                  'Server: AcmeCWMP/42',                  'Server: PerlCWMP/42',
164                  'SOAPServer: AcmeCWMP/42'                  'SOAPServer: PerlCWMP/42'
165          )."\r\n");          )."\r\n");
166    
167          $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );          $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );
168            
169          my $xml = '';          my $uid = $self->store->state_to_uid( $state );
170    
171            my $to_uid = join(" ", grep { defined($_) } "to $uid",
172                            # board
173                            $state->{Parameter}->{'InternetGatewayDevice.DeviceInfo.HardwareVersion'},
174                            # version
175                            $state->{Parameter}->{'InternetGatewayDevice.DeviceInfo.SoftwareVersion'},
176                            # summary
177    #                       $state->{Parameter}->{'InternetGatewayDevice.DeviceSummary'},
178            ) . "\n";
179    
180            my $queue = CWMP::Queue->new({
181                    id => $uid,
182                    debug => $self->debug,
183            });
184            my $job;
185            $xml = '';
186    
187          if ( my $dispatch = $state->{_dispatch} ) {          if ( my $dispatch = $state->{_dispatch} ) {
188                  $xml = $self->dispatch( $dispatch );                  $xml = $self->dispatch( $dispatch );
189          } elsif ( $dispatch = shift @{ $self->queue } ) {          } elsif ( $job = $queue->dequeue ) {
190                  $xml = $self->dispatch( $dispatch );                  $xml = $self->dispatch( $job->dispatch );
191          } elsif ( $size == 0 ) {          } elsif ( $size == 0 ) {
192                  warn ">>> closing connection\n";                  warn ">>> no more queued commands, no client pending, closing connection $to_uid";
193                  return 0;                  $sock->close;
194                    return;
195          } else {          } else {
196                  warn ">>> empty response\n";                  warn ">>> empty response $to_uid";
197                  $state->{NoMoreRequests} = 1;                  $state->{NoMoreRequests} = 1;
198                  $xml = $self->dispatch( 'xml', sub {} );                  $xml = $self->dispatch( 'xml', sub {} );
199          }          }
# Line 198  sub process_request { Line 201  sub process_request {
201          $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );          $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
202          $sock->send( $xml ) or die "can't send response";          $sock->send( $xml ) or die "can't send response";
203    
204          warn ">>>> " . $sock->peerhost . " [" . localtime() . "] sent ", length( $xml )," bytes\n";          warn ">>>> " . $sock->peerhost . " [" . localtime() . "] sent ", length( $xml )," bytes $to_uid";
205    
206          warn "### request over\n" if $self->debug;          $job->finish if $job;
207            warn "### request over for $uid\n" if $self->debug;
208    
209          return 1;       # next request          return 1;       # next request
210  };  };
# Line 209  sub process_request { Line 213  sub process_request {
213    
214    $xml = $self->dispatch('Inform', $response_arguments );    $xml = $self->dispatch('Inform', $response_arguments );
215    
216    If debugging level of 3 or more, it will create dumps of responses named C<< dump/nr.response >>
217    
218  =cut  =cut
219    
220  sub dispatch {  sub dispatch {
221          my $self = shift;          my $self = shift;
222    
223          my $dispatch = shift || die "no dispatch?";          my $dispatch = shift || die "no dispatch?";
224            my $args = shift;
225    
226          my $response = CWMP::Response->new({ debug => $self->debug });          my $response = CWMP::Methods->new({ debug => $self->debug });
227    
228          if ( $response->can( $dispatch ) ) {          if ( $response->can( $dispatch ) ) {
229                  warn ">>> dispatching to $dispatch\n";                  warn ">>> dispatching to $dispatch with args ",dump( $args ),"\n";
230                  my $xml = $response->$dispatch( $self->state, @_ );                  my $xml = $response->$dispatch( $self->state, $args );
231                  warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;                  warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
232                    if ( $self->create_dump ) {
233                            my $file = sprintf("dump/%04d-%s.response", $dump_nr++, $self->sock->peerhost);
234                            write_file( $file, $xml );
235                            warn "### response dump: $file\n" if $self->debug;
236                    }
237                  return $xml;                  return $xml;
238          } else {          } else {
239                  confess "can't dispatch to $dispatch";                  confess "can't dispatch to $dispatch";
240          }          }
241  };  };
242    
 =head2 read_headers  
   
 parse headers from request  
   
 =cut  
   
 sub read_headers {  
   my $self = shift;  
   
   $self->{headers} = {};  
   
   while (defined($_ = $self->sock->getline)) {  
     s/[\r\n]+$//;  
     last unless length $_;  
         warn "-- $_\n" if $self->debug;  
     return 0 if ! /^ ([\w\-]+) :[\ \t]* (.*) $/x;  
     $self->{headers}->{$1} = $2;  
   }  
   
   return 1;  
 }  
   
 =head2 header  
   
 Getter for specific header  
   
   $self->header('Cookies');  
   
 =cut  
   
 sub header {  
         my $self = shift;  
         my $header = shift || die "no header?";  
         if ( defined( $self->{headers}->{$header} )) {  
                 return $self->{headers}->{$header};  
         } else {  
                 return;  
         }  
 }  
243    
244  =head2 error  =head2 error
245    

Legend:
Removed from v.100  
changed lines
  Added in v.223

  ViewVC Help
Powered by ViewVC 1.1.26