/[cwmp]/google/lib/CWMP/Server.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/lib/CWMP/Server.pm

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

revision 36 by dpavlin, Tue Jun 19 00:38:49 2007 UTC revision 51 by dpavlin, Tue Jun 19 21:35:35 2007 UTC
# Line 4  package CWMP::Server; Line 4  package CWMP::Server;
4  use strict;  use strict;
5  use warnings;  use warnings;
6    
7  use base qw/HTTP::Server::Simple::CGI Class::Accessor/;  use base qw/Class::Accessor/;
8  __PACKAGE__->mk_accessors( qw/  __PACKAGE__->mk_accessors( qw/
9  debug  debug
10    port
11    sock
12    state
13    queue
14  / );  / );
15    
16    use IO::Socket::INET;
17  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
18  use CWMP::Request;  use CWMP::Request;
19  use CWMP::Response;  use CWMP::Response;
20  use Carp qw/confess/;  use Carp qw/confess cluck/;
21    
22  =head1 NAME  =head1 NAME
23    
# Line 20  CWMP::Server - implement logic of CWMP p Line 25  CWMP::Server - implement logic of CWMP p
25    
26  =head1 METHODS  =head1 METHODS
27    
28  =head2 handler  =head2 new
29    
30  We override L<HTTP::Server::Simple::CGI/handler> so that we can support    my $server = CWMP::Server->new({ port => 3333 });
31  chunked transfer encoding.  
32    =head2 run
33    
34      $server->run();
35    
36  =cut  =cut
37    
38  sub handler {  sub run {
39      my $self = shift;          my $self = shift;
40    
41      my $chunk;          my $listen = IO::Socket::INET->new(
42                    Listen    => 5,
43    #               LocalAddr => 'localhost',
44                    LocalPort => $self->port,
45                    Proto     => 'tcp',
46                    Blocking  => 1,
47                    ReuseAddr => 1,
48            );
49    
50            warn "ACS waiting for request on port ", $self->port, " queue ( ", join(",",@{$self->queue}), " )\n";
51    
52            while ( my $sock = $listen->accept ) {
53                    $sock->autoflush(1);
54    
55                    warn "connection from ", $sock->peerhost, "\n";
56    
57                    $self->sock( $sock );   # FIXME this will not work for multiple clients
58                    while ( $self->process_request ) {
59                            warn "...another one bites a dust...\n";
60                    }
61    
62                    warn "...returning to accepting new connections\n";
63            }
64    }
65    
66    =head2 process_request
67    
68    One request from client/response from server cycle. Call multiple times to
69    facilitate brain-dead concept of adding state to stateless protocol like
70    HTTP.
71    
72    =cut
73    
74    sub process_request {
75            my $self = shift;
76    
77            my $sock = $self->sock || die "no sock?";
78    
79            die "not IO::Socket::INET but ", ref( $sock ) unless ( ref($sock) eq 'IO::Socket::INET' );
80    
81            if ( ! $sock->connected ) {
82                    warn "SOCKET NOT CONNECTED";
83                    return 0;
84            }
85    
86            $sock->autoflush( 1 );
87            $sock->blocking( 1 );
88    
89            ### read the first line of response
90            my $line = $sock->getline;
91            return $self->error(400, "No Data") unless ( defined $line );
92    
93            $line =~ s/[\r\n]+$//;
94            if ($line !~ /^ (\w+) \ + (\S+) \ + (HTTP\/1.\d) $ /x) {
95                    warn "ERROR: $line\n";
96                    return $self->error(400, "Bad request");
97            }
98            my ($method, $req, $protocol) = ($1, $2, $3);
99            warn "<<<< ", $sock->peerhost, " - - [" . localtime() . "] \"$method $req $protocol\"\n";
100    
101            ### read in other headers
102            $self->read_headers || return $self->error(400, "Strange headers");
103    
104            ### do we support the type
105    #       if ($method !~ /GET|POST|HEAD/) {
106            if ($method !~ /POST/) {
107                    return $self->error(400, "Unsupported Method");
108            }
109    
110        my $chunk;
111          my $transfer_encoding = $self->header('Transfer-Encoding');          my $transfer_encoding = $self->header('Transfer-Encoding');
112    
113          if ( $transfer_encoding && $transfer_encoding =~ qr/^chunked/i ) {          if ( $transfer_encoding && $transfer_encoding =~ qr/^chunked/i ) {
114    
115                  my $len = 0;                  my $len = 0;
116                  my $hex;  
117                  do {                  do {
118                          $hex = <STDIN>;         # get chunk length  
119                          $hex =~ s/[\n\r]*$//s;                          warn "get chunk len\n" if $self->debug;
120                            
121                            my $hex;
122                            do {
123                                    $hex = $sock->getline;
124                                    $hex =~ s/[\n\r]+$//;
125                            } until ( $hex ne '' );
126    
127                            die "chunk size not valid hex: $hex" unless ( $hex =~ m/^[0-9a-f]+$/i);
128                          $len = hex( $hex );                          $len = hex( $hex );
129    
130                          warn "getting chunk of 0x$hex $len bytes\n" if $self->debug;                          warn "getting chunk of $len bytes\n" if $self->debug;
131    
132                          while( $len > 0 ) {                          $sock->read( my $buff, $len );
133                                  my $line = <STDIN>;                          $chunk .= $buff;
                                 $chunk .= $line;  
                                 $len -= length( $line );  
                         }  
134    
135                  } while ( hex( $hex ) != 0 );                          warn "--- $len bytes: --=>||$buff||<=--\n";
         }  
136    
137          warn "handler got ", length($chunk), " bytes\n" if $self->debug;                  } while ( $len > 0 );
138                    my $sep = $sock->getline;
139                    die "expected separator, not ", dump( $sep ) if ( $sep !~ m/^[\n\r]+$/ );
140    
141      my $cgi  = new CGI( $chunk );          } else {
142                    die "right now, we support only Transfer-Encoding: chunked";
143            }
144    
145      eval { $self->handle_request($cgi) };          my $size = length( $chunk );
     if ($@) {  
         my $error = $@;  
         warn $error;  
     }  
 }  
146    
147  =head2 handle_request          warn "<<< " . $sock->peerhost . " [" . localtime() . "] request $size bytes\n";
148    
149  Implementation of dispatch logic          my $state;
150    
151  =cut          if ( $size > 0 ) {
152    
153  sub handle_request {                  die "no SOAPAction header in ",dump($chunk) unless defined ( $self->header('SOAPAction') );
         my ($self, $cgi) = @_;  
                                                                       
         #... do something, print output to default  
         # selected filehandle...  
154    
         warn "<<< " . localtime() . " " . $ENV{REMOTE_ADDR} . "\n";  
155    
156          warn "not SOAP request" unless defined ( $cgi->header('SOAPAction') );                  if ( $chunk ) {
157                            warn "## request chunk: ",length($chunk)," bytes\n$chunk\n" if $self->debug;
158    
159          my $state;                          $state = CWMP::Request->parse( $chunk );
160    
161          if ( my $payload = $cgi->param('POSTDATA') ) {                          warn "acquired state = ", dump( $state ), "\n";
                 warn "request payload:\n$payload\n" if $self->debug;  
162    
163                  $state = CWMP::Request->parse( $payload );                          $self->state( $state );
164    
165                    } else {
166                            warn "empty request\n";
167                    }
168    
                 warn "acquired state = ", dump( $state );  
           
169          } else {          } else {
170                  warn "empty request\n";                  $state = $self->state;
171                    warn "last request state = ", dump( $state ), "\n";
172          }          }
173    
         my $response = CWMP::Response->new({ debug => $self->debug });  
174    
175          print "Content-Type: text/xml\r\n\r\n";          $sock->send(join("\r\n",
176                    'HTTP/1.1 200 OK',
177                    'Content-Type: text/xml; charset="utf-8"',
178                    'Server: AcmeCWMP/42',
179                    'SOAPServer: AcmeCWMP/42'
180            ));
181    
182            $sock->send( "Set-Cookie: ID=" . $state->{ID} . "; path=/\r\n" ) if ( $state->{ID} );
183            
184            my $xml = '';
185    
186          if ( my $dispatch = $state->{_dispatch} ) {          if ( my $dispatch = $state->{_dispatch} ) {
187                  if ( $response->can( $dispatch ) ) {                  $xml = $self->dispatch( $dispatch );
188                          warn ">>> dispatching to $dispatch\n";          } elsif ( $dispatch = shift @{ $self->queue } ) {
189                          print $response->$dispatch;                  $xml = $self->dispatch( $dispatch );
190                  } else {          } elsif ( $size == 0 ) {
191                          confess "can't dispatch to $dispatch";                  warn ">>> closing connection\n";
192                  }                  return 0;
193          } else {          } else {
194                  warn ">>> empty response\n";                  warn ">>> empty response\n";
195                    $state->{NoMoreRequests} = 1;
196                    $xml = $self->dispatch( 'xml', sub {} );
197          }          }
198            
199            $sock->send( "Content-Length: " . length( $xml ) . "\r\n\r\n" );
200            $sock->send( $xml ) or die "can't send response";
201    
202            warn "### request over";
203    
204  };  };
205    
206  1;  =head2 dispatch
207    
208      $xml = $self->dispatch('Inform', $response_arguments );
209    
210    =cut
211    
212    sub dispatch {
213            my $self = shift;
214    
215            my $dispatch = shift || die "no dispatch?";
216    
217            my $response = CWMP::Response->new({ debug => $self->debug });
218    
219            if ( $response->can( $dispatch ) ) {
220                    warn ">>> dispatching to $dispatch\n";
221                    my $xml = $response->$dispatch( $self->state, @_ ) . "\r\n";
222                    warn "## response payload: ",length($xml)," bytes\n$xml\n";
223                    return $xml;
224            } else {
225                    confess "can't dispatch to $dispatch";
226            }
227    };
228    
229    =head2 read_headers
230    
231    parse headers from request
232    
233    =cut
234    
235    sub read_headers {
236      my $self = shift;
237    
238      $self->{headers} = {};
239    
240      while (defined($_ = $self->sock->getline)) {
241        s/[\r\n]+$//;
242        last unless length $_;
243            warn "-- $_\n";
244        return 0 if ! /^ ([\w\-]+) :[\ \t]* (.*) $/x;
245        $self->{headers}->{$1} = $2;
246      }
247    
248      return 1;
249    }
250    
251    =head2 header
252    
253    Getter for specific header
254    
255      $self->header('Cookies');
256    
257    =cut
258    
259    sub header {
260            my $self = shift;
261            my $header = shift || die "no header?";
262            if ( defined( $self->{headers}->{$header} )) {
263                    return $self->{headers}->{$header};
264            } else {
265                    return;
266            }
267    }
268    
269    =head2 error
270    
271      return $self->error( 501, 'System error' );
272    
273    =cut
274    
275    sub error {
276      my ($self, $number, $msg) = @_;
277      $msg ||= 'ERROR';
278      $self->sock->send( "HTTP/1.1 $number $msg\r\n" );
279      warn "Error - $number - $msg\n";
280      return 0;     # close connection
281    }
282    
283    1;

Legend:
Removed from v.36  
changed lines
  Added in v.51

  ViewVC Help
Powered by ViewVC 1.1.26