/[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 223 by dpavlin, Sat Nov 24 02:17:40 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/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 Carp qw/confess cluck/;  use CWMP::Store;
26    
27    #use Devel::LeakTrace::Fast;
28    
29  =head1 NAME  =head1 NAME
30    
31  CWMP::Server - implement logic of CWMP protocol  CWMP::Session - implement logic of CWMP protocol
32    
33  =head1 METHODS  =head1 METHODS
34    
35  =head2 new  =head2 new
36    
37    my $server = CWMP::Server->new({ port => 3333 });    my $server = CWMP::Session->new({
38            sock => $io_socket_object,
39            store => { ... },
40            debug => 1,
41            create_dump => 1,
42      });
43    
44  =head2 run  =cut
45    
46    $server->run();  sub new {
47            my $class = shift;
48            my $self = $class->SUPER::new( @_ );
49    
50  =cut          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  sub run {          $self->debug( 0 ) unless $self->debug;
         my $self = shift;  
55    
56          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);  
57    
58                  warn "connection from ", $sock->peerhost, "\n";          my $store_obj = CWMP::Store->new({
59                    debug => $self->debug,
60                    %{ $self->store },
61            });
62    
63                  $self->process_request( $sock );          croak "can't open ", dump( $self->store ), ": $!" unless $store_obj;
64    
65                  warn "...another one bites a dust...\n";          # FIXME looks ugly. Should we have separate accessor for this?
66                  sleep 1;          $self->store( $store_obj );
67          }  
68            $self->create_dump( 1 ) if $self->debug > 2;
69    
70            return $self;
71  }  }
72    
73  sub process_request {  =head2 process_request
         my $self = shift;  
74    
75          my $sock = shift || die "no sock?";  One request from client/response from server cycle. Call multiple times to
76    facilitate brain-dead concept of adding state to stateless protocol like
77    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          die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'IO::Socket::INET' );  =cut
84    
85          $sock->autoflush( 1 );  my $dump_nr = 0;
         $sock->blocking( 1 );  
86    
87          ### read the first line of response  sub process_request {
88          my $line = $sock->getline; # || $self->error(400, "No Data");          my $self = shift;
89    
90          $line =~ s/[\r\n]+$//;          my $sock = $self->sock || die "no sock?";
         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";  
91    
92          ### read in other headers  #       die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'Net::Server::Proto::TCP' );
         $self->read_headers($sock) || return $self->error(400, "Strange headers");  
93    
94          ### do we support the type          if ( ! $sock->connected ) {
95  #       if ($method !~ /GET|POST|HEAD/) {                  warn "SOCKET NOT CONNECTED\n";
96          if ($method !~ /POST/) {                  return 0;
                 return $self->error(400, "Unsupported Method");  
97          }          }
98    
99      my $chunk;          bless $sock, 'HTTP::Daemon::ClientConn';
         my $transfer_encoding = $self->header('Transfer-Encoding');  
100    
101          if ( $transfer_encoding && $transfer_encoding =~ qr/^chunked/i ) {          # why do I have to do this?
102            # solution from http://use.perl.org/~Matts/journal/12896
103            ${*$sock}{'httpd_daemon'} = HTTP::Daemon->new;
104    
105                  my $len = 0;          my $r = $sock->get_request;
106            
107            if ( ! $r ) {
108                    carp "can't get_request";
109                    return 0;
110            }
111    
112                  do {          my $xml = $r->content;
113    
114                          warn "get chunk len\n" if $self->debug;          my $size = length( $xml );
                           
                         my $hex;  
                         do {  
                                 $hex = $sock->getline;  
                                 $hex =~ s/[\n\r]+$//;  
                         } until ( $hex ne '' );  
115    
116                          die "chunk size not valid hex: $hex" unless ( $hex =~ m/^[0-9a-f]+$/i);          warn "<<<< ", $sock->peerhost, " [" . localtime() . "] ", $r->method, " ", $r->uri, " $size bytes\n";
                         $len = hex( $hex );  
117    
118                          warn "getting chunk of $len bytes\n" if $self->debug;          $dump_nr++;
119            my $file = sprintf("dump/%04d-%s.request", $dump_nr, $sock->peerhost);
120    
121                          $sock->read( my $buff, $len );          if ( $self->create_dump ) {
122                          $chunk .= $buff;                  write_file( $file, $r->as_string );
123                    warn "### request dumped to file: $file\n" if $self->debug;
124            }
125    
126                          warn "--- $len bytes: --=>||$buff||<=--\n";          my $state;
127    
128                  } while ( $len > 0 );          if ( $size > 0 ) {
129    
130          } else {                  die "no SOAPAction header in ",dump($xml) unless defined ( $r->header('SOAPAction') );
                 die "right now, we support only Transfer-Encoding: chunked";  
         }  
131    
132          warn "handler got ", length($chunk), " bytes\n" if $self->debug;                  warn "## request payload: ",length($xml)," bytes\n$xml\n" if $self->debug;
133    
134          warn "<<< " . localtime() . " " . $sock->peerhost . "\n";                  $state = CWMP::Request->parse( $xml );
135    
136          die "not SOAP request" unless defined ( $self->header('SOAPAction') );                  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          my $state;                  warn "## acquired state = ", dump( $state ), "\n" if $self->debug;
142    
143          if ( $chunk ) {                  if ( ! defined( $state->{DeviceID} ) ) {
144                  warn "## request chunk: ",length($chunk)," bytes\n$chunk\n" if $self->debug;                          warn "## state with DeviceID, using old one...\n";
145                            $state->{DeviceID} = $self->state->{DeviceID};
146                    }
147    
148                  $state = CWMP::Request->parse( $chunk );                  $self->state( $state );
149                    $self->store->update_state( $state );
150    
                 warn "acquired state = ", dump( $state ), "\n";  
           
151          } else {          } else {
                 warn "empty request\n";  
         }  
152    
153                    warn "## empty request, using last request state\n";
154    
155          my $response = CWMP::Response->new({ debug => $self->debug });                  $state = $self->state;
156                    delete( $state->{_dispatch} );
157          print $self->status(200), $self->content_type('text/xml; charset="utf-8"'), "\r\n";                  #warn "last request state = ", dump( $state ), "\n" if $self->debug > 1;
158            }
         print "Server: AcmeCWMP/42\r\nSOAPServer: AcmeCWMP/42\r\n";  
159    
160          print "Set-Cookie: ID=" , $state->{ID}, "; path=/\r\n" if ( $state->{ID} );          $sock->send(join("\r\n",
161                            'HTTP/1.1 200 OK',
162          my $xml = '';                  'Content-Type: text/xml; charset="utf-8"',
163                    'Server: PerlCWMP/42',
164                    'SOAPServer: PerlCWMP/42'
165            )."\r\n");
166    
167            $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );
168    
169            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                  if ( $response->can( $dispatch ) ) {                  $xml = $self->dispatch( $dispatch );
189                          warn ">>> dispatching to $dispatch\n";          } elsif ( $job = $queue->dequeue ) {
190                          $xml = $response->$dispatch( $state ) . "\r\n";                  $xml = $self->dispatch( $job->dispatch );
191                          warn "## response payload: ",length($xml)," bytes\n$xml\n";          } elsif ( $size == 0 ) {
192                  } else {                  warn ">>> no more queued commands, no client pending, closing connection $to_uid";
193                          confess "can't dispatch to $dispatch";                  $sock->close;
194                  }                  return;
195          } else {          } else {
196                  warn ">>> empty response\n";                  warn ">>> empty response $to_uid";
197                    $state->{NoMoreRequests} = 1;
198                    $xml = $self->dispatch( 'xml', sub {} );
199          }          }
200    
201          print "Content-length: ", length( $xml ), "\r\n\r\n";          $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
202          print $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 $to_uid";
205    
206          warn "### request over";          $job->finish if $job;
207            warn "### request over for $uid\n" if $self->debug;
208    
209            return 1;       # next request
210  };  };
211    
212    =head2 dispatch
213    
214  sub read_headers {    $xml = $self->dispatch('Inform', $response_arguments );
   my $self = shift;  
215    
216          my $sock = shift || die "no sock?";  If debugging level of 3 or more, it will create dumps of responses named C<< dump/nr.response >>
217    
218    $self->{headers} = {};  =cut
219    
220    while (defined($_ = $sock->getline)) {  sub dispatch {
221      s/[\r\n]+$//;          my $self = shift;
     last unless length $_;  
         warn "-- $_\n";  
     return 0 if ! /^ ([\w\-]+) :[\ \t]* (.*) $/x;  
     $self->{headers}->{$1} = $2;  
   }  
222    
223    return 1;          my $dispatch = shift || die "no dispatch?";
224  }          my $args = shift;
225    
226  sub header {          my $response = CWMP::Methods->new({ debug => $self->debug });
227          my $self = shift;  
228          my $header = shift || die "no header?";          if ( $response->can( $dispatch ) ) {
229          if ( defined( $self->{headers}->{$header} )) {                  warn ">>> dispatching to $dispatch with args ",dump( $args ),"\n";
230                  return $self->{headers}->{$header};                  my $xml = $response->$dispatch( $self->state, $args );
231                    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;
238          } else {          } else {
239                  return;                  confess "can't dispatch to $dispatch";
240          }          }
241  }  };
242    
 sub content_type {  
   my ($self, $type) = @_;  
   $self->http_header;  
   return "Content-type: $type\r\n";  
 }  
243    
244  sub error{  =head2 error
   my ($self, $number, $msg) = @_;  
   print $self->status($number, $msg), "\r\n";  
   warn "Error - $number - $msg\n";  
 }  
245    
246  sub status {    return $self->error( 501, 'System error' );
247    my ($self, $number, $msg) = @_;  
248    $msg = '' if ! defined $msg;  =cut
   return if $self->http_header($number);  
   return "Status $number: $msg\r\n";  
 }  
249    
250  sub http_header {  sub error {
251    my $self = shift;    my ($self, $number, $msg) = @_;
252    my $number = shift || 200;    $msg ||= 'ERROR';
253    return if ! delete $self->{needs_header};    $self->sock->send( "HTTP/1.1 $number $msg\r\n" );
254    print "HTTP/1.0 $number\r\n";    warn "Error - $number - $msg\n";
255    return 1;    return 0;     # close connection
256  }  }
257    
258  1;  1;

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

  ViewVC Help
Powered by ViewVC 1.1.26