/[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/Server.pm revision 77 by dpavlin, Fri Jun 22 13:09:08 2007 UTC google/trunk/lib/CWMP/Session.pm revision 206 by dpavlin, Wed Nov 14 23:07:42 2007 UTC
# Line 1  Line 1 
1  # Dobrica Pavlinusic, <dpavlin@rot13.org> 06/18/07 10:19:50 CEST  # Dobrica Pavlinusic, <dpavlin@rot13.org> 06/18/07 10:19:50 CEST
2  package CWMP::Server;  package CWMP::Session;
3    
4  use strict;  use strict;
5  use warnings;  use warnings;
# 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  port  create_dump
11  store_path  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/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  =head1 NAME  =head1 NAME
28    
29  CWMP::Server - implement logic of CWMP protocol  CWMP::Session - implement logic of CWMP protocol
30    
31  =head1 METHODS  =head1 METHODS
32    
33  =head2 new  =head2 new
34    
35    my $server = CWMP::Server->new({    my $server = CWMP::Session->new({
36          port => 3333,          sock => $io_socket_object,
37          store_path => 'state.db',          store => { ... },
38          debug => 1,          debug => 1,
39            create_dump => 1,
40    });    });
41    
 =head2 run  
   
   $server->run();  
   
42  =cut  =cut
43    
44  sub run {  sub new {
45          my $self = shift;          my $class = shift;
46            my $self = $class->SUPER::new( @_ );
47          my $listen = IO::Socket::INET->new(  
48                  Listen    => 5,          confess "need sock" unless $self->sock;
49  #               LocalAddr => 'localhost',          confess "need store" unless $self->store;
50                  LocalPort => $self->port,          my $peerhost = $self->sock->peerhost || confess "can't get sock->peerhost";
                 Proto     => 'tcp',  
                 Blocking  => 1,  
                 ReuseAddr => 1,  
         );  
   
         warn "ACS waiting for request on port ", $self->port,  
                 $self->queue ? " queue ( " . join(",",@{$self->queue}) . " )" : "",  
                 "\n";  
51    
52          $self->debug( 0 ) unless $self->debug;          $self->debug( 0 ) unless $self->debug;
         warn "## debug level: ", $self->debug, "\n" if $self->debug;  
53    
54          $self->store( CWMP::Store->new({          warn "created ", __PACKAGE__, "(", dump( @_ ), ") for $peerhost\n" if $self->debug;
55    
56            my $store_obj = CWMP::Store->new({
57                  debug => $self->debug,                  debug => $self->debug,
58                  path => $self->store_path,                  %{ $self->store },
59          }) );          });
         croak "can't open ", $self->store_path, ": $!" unless $self->store;  
   
         while ( my $sock = $listen->accept ) {  
                 $sock->autoflush(1);  
   
                 warn "connection from ", $sock->peerhost, "\n" if $self->debug;  
   
                 $self->sock( $sock );   # FIXME this will not work for multiple clients  
                 while ( $self->process_request ) {  
                         warn "...another one bites the dust...\n";  
                 }  
60    
61                  warn "...returning to accepting new connections\n";          croak "can't open ", dump( $self->store ), ": $!" unless $store_obj;
62          }  
63            # FIXME looks ugly. Should we have separate accessor for this?
64            $self->store( $store_obj );
65    
66            $self->create_dump( 1 ) if $self->debug > 2;
67    
68            return $self;
69  }  }
70    
71  =head2 process_request  =head2 process_request
# Line 89  One request from client/response from se Line 74  One request from client/response from se
74  facilitate brain-dead concept of adding state to stateless protocol like  facilitate brain-dead concept of adding state to stateless protocol like
75  HTTP.  HTTP.
76    
77    If used with debugging level of 3 or more, it will also create dumps of
78    requests named C<< dump/nr.request >> where C<nr> is number from 0 to total number
79    of requests in single session.
80    
81  =cut  =cut
82    
83    my $dump_nr = 0;
84    
85  sub process_request {  sub process_request {
86          my $self = shift;          my $self = shift;
87    
88          my $sock = $self->sock || die "no sock?";          my $sock = $self->sock || die "no sock?";
89    
90          die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'IO::Socket::INET' );  #       die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'Net::Server::Proto::TCP' );
91    
92          if ( ! $sock->connected ) {          if ( ! $sock->connected ) {
93                  warn "SOCKET NOT CONNECTED\n";                  warn "SOCKET NOT CONNECTED\n";
94                  return 0;                  return 0;
95          }          }
96    
97          $sock->autoflush( 1 );          bless $sock, 'HTTP::Daemon::ClientConn';
         $sock->blocking( 1 );  
98    
99          ### read the first line of response          # why do I have to do this?
100          my $line = $sock->getline;          # solution from http://use.perl.org/~Matts/journal/12896
101          return $self->error(400, "No Data") unless ( defined $line );          ${*$sock}{'httpd_daemon'} = HTTP::Daemon->new;
   
         $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";  
102    
103          ### read in other headers          my $r = $sock->get_request || confess "can't get_request";
         $self->read_headers || return $self->error(400, "Strange headers");  
104    
105          ### do we support the type          my $xml = $r->content;
 #       if ($method !~ /GET|POST|HEAD/) {  
         if ($method !~ /POST/) {  
                 return $self->error(400, "Unsupported Method");  
         }  
106    
107      my $chunk;          my $size = length( $xml );
         my $transfer_encoding = $self->header('Transfer-Encoding');  
108    
109          if ( $transfer_encoding && $transfer_encoding =~ qr/^chunked/i ) {          warn "<<<< ", $sock->peerhost, " [" . localtime() . "] ", $r->method, " ", $r->uri, " $size bytes\n";
110    
111                  my $len = 0;          $dump_nr++;
112            my $file = sprintf("dump/%04d-%s.request", $dump_nr, $sock->peerhost);
113    
114                  do {          if ( $self->create_dump ) {
115                    write_file( $file, $r->as_string );
116                          warn "get chunk len\n" if $self->debug > 1;                  warn "### request dumped to file: $file\n";
                           
                         my $hex;  
                         do {  
                                 $hex = $sock->getline;  
                                 $hex =~ s/[\n\r]+$//;  
                         } until ( $hex ne '' );  
   
                         die "chunk size not valid hex: $hex" unless ( $hex =~ m/^[0-9a-f]+$/i);  
                         $len = hex( $hex );  
   
                         warn "getting chunk of $len bytes\n" if $self->debug > 1;  
   
                         $sock->read( my $buff, $len );  
                         $chunk .= $buff;  
   
                         warn "--- $len bytes: --=>||$buff||<=--\n" if $self->debug > 1;  
   
                 } while ( $len > 0 );  
                 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";  
117          }          }
118    
         my $size = length( $chunk );  
   
         warn "<<<< " . $sock->peerhost . " [" . localtime() . "] request $size bytes\n";  
   
119          my $state;          my $state;
120    
121          if ( $size > 0 ) {          if ( $size > 0 ) {
122    
123                  die "no SOAPAction header in ",dump($chunk) unless defined ( $self->header('SOAPAction') );                  die "no SOAPAction header in ",dump($xml) unless defined ( $r->header('SOAPAction') );
124    
125                    warn "## request payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
126    
127                  if ( $chunk ) {                  $state = CWMP::Request->parse( $xml );
                         warn "## request chunk: ",length($chunk)," bytes\n$chunk\n" if $self->debug;  
128    
129                          $state = CWMP::Request->parse( $chunk );                  if ( defined( $state->{_dispatch} ) && $self->create_dump ) {
130                            my $type = sprintf("dump/%04d-%s-%s", $dump_nr, $sock->peerhost, $state->{_dispatch});
131                          warn "## acquired state = ", dump( $state ), "\n";                          symlink $file, $type || warn "can't symlink $file -> $type: $!";
132                    }
133    
134                          $self->state( $state );                  warn "## acquired state = ", dump( $state ), "\n";
135    
136                  } else {                  if ( ! defined( $state->{DeviceID} ) ) {
137                          warn "## empty request\n";                          warn "## state with DeviceID, using old one...\n";
138                            $state->{DeviceID} = $self->state->{DeviceID};
139                  }                  }
140    
141                    $self->state( $state );
142                    $self->store->update_state( ID => $state->{ID}, $state );
143    
144          } else {          } else {
145    
146                    warn "## empty request, using last request state\n";
147    
148                  $state = $self->state;                  $state = $self->state;
149                  warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;                  delete( $state->{_dispatch} );
150                    #warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;
151          }          }
152    
153    
# Line 200  sub process_request { Line 159  sub process_request {
159          )."\r\n");          )."\r\n");
160    
161          $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} );
162            
163          my $xml = '';          my $uid = $self->store->ID_to_uid( $state->{ID}, $state );
164    
165            my $queue = CWMP::Queue->new({
166                    id => $uid,
167                    debug => $self->debug,
168            });
169            my $job;
170            $xml = '';
171    
172          if ( my $dispatch = $state->{_dispatch} ) {          if ( my $dispatch = $state->{_dispatch} ) {
173                  $xml = $self->dispatch( $dispatch );                  $xml = $self->dispatch( $dispatch );
174          } elsif ( $dispatch = shift @{ $self->queue } ) {          } elsif ( $job = $queue->dequeue ) {
175                  $xml = $self->dispatch( $dispatch );                  $xml = $self->dispatch( $job->dispatch );
176          } elsif ( $size == 0 ) {          } elsif ( $size == 0 ) {
177                  warn ">>> closing connection\n";                  warn ">>> no more queued commands, closing connection to $uid\n";
178                  return 0;                  return 0;
179          } else {          } else {
180                  warn ">>> empty response\n";                  warn ">>> empty response to $uid\n";
181                  $state->{NoMoreRequests} = 1;                  $state->{NoMoreRequests} = 1;
182                  $xml = $self->dispatch( 'xml', sub {} );                  $xml = $self->dispatch( 'xml', sub {} );
183          }          }
# Line 219  sub process_request { Line 185  sub process_request {
185          $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );          $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
186          $sock->send( $xml ) or die "can't send response";          $sock->send( $xml ) or die "can't send response";
187    
188          warn ">>>> " . $sock->peerhost . " [" . localtime() . "] sent ", length( $xml )," bytes\n";          warn ">>>> " . $sock->peerhost . " [" . localtime() . "] sent ", length( $xml )," bytes to $uid\n";
189    
190          warn "### request over\n" if $self->debug;          $job->finish if $job;
191            warn "### request over for $uid\n" if $self->debug;
192    
193          return 1;       # next request          return 1;       # next request
194  };  };
# Line 230  sub process_request { Line 197  sub process_request {
197    
198    $xml = $self->dispatch('Inform', $response_arguments );    $xml = $self->dispatch('Inform', $response_arguments );
199    
200    If debugging level of 3 or more, it will create dumps of responses named C<< dump/nr.response >>
201    
202  =cut  =cut
203    
204  sub dispatch {  sub dispatch {
205          my $self = shift;          my $self = shift;
206    
207          my $dispatch = shift || die "no dispatch?";          my $dispatch = shift || die "no dispatch?";
208            my $args = shift;
209    
210          my $response = CWMP::Response->new({ debug => $self->debug });          my $response = CWMP::Methods->new({ debug => $self->debug });
211    
212          if ( $response->can( $dispatch ) ) {          if ( $response->can( $dispatch ) ) {
213                  warn ">>> dispatching to $dispatch\n";                  warn ">>> dispatching to $dispatch with args ",dump( $args ),"\n";
214                  my $xml = $response->$dispatch( $self->state, @_ );                  my $xml = $response->$dispatch( $self->state, $args );
215                  warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;                  warn "## response payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
216                    if ( $self->create_dump ) {
217                            my $file = sprintf("dump/%04d-%s.response", $dump_nr++, $self->sock->peerhost);
218                            write_file( $file, $xml );
219                            warn "### response dump: $file\n";
220                    }
221                  return $xml;                  return $xml;
222          } else {          } else {
223                  confess "can't dispatch to $dispatch";                  confess "can't dispatch to $dispatch";
224          }          }
225  };  };
226    
 =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;  
         }  
 }  
227    
228  =head2 error  =head2 error
229    

Legend:
Removed from v.77  
changed lines
  Added in v.206

  ViewVC Help
Powered by ViewVC 1.1.26