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

Legend:
Removed from v.40  
changed lines
  Added in v.210

  ViewVC Help
Powered by ViewVC 1.1.26