/[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

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

Legend:
Removed from v.34  
changed lines
  Added in v.55

  ViewVC Help
Powered by ViewVC 1.1.26