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

Legend:
Removed from v.43  
changed lines
  Added in v.150

  ViewVC Help
Powered by ViewVC 1.1.26