Threaded/WebClient.pm untested

filter: Statementstmt 0.0% 0 / 202 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 364 CC 42 SCAR 58.8
CC
42
Cov
0%
handleSocketEvent
812.0
new
72.0
run
42.0
CRAP 358.0
1 =pod
2  
3 =begin classdoc
4  
5 Provides web-based request handling. A pool of WebClient
6 objects are created and managed by HTTP::Daemon::Threaded::Listener. As
7 web connection requests are received, a WebClient
8 is allocated and assigned the network connection. A minimal
9 HTTP protocol implementation is provided via a subclass of HTTP::Daemon::ClientConn.
10 As requests are received, they are processed as needed,
11 possibly resulting in calls to any installed content handler components.
12 <p>
13 Content handlers are specified as an arrayref of 2-tuples
14 consisting of
15 <pre>
16 [ regular expression string, content handler class name ]
17 </pre>
18 When a client HTTP request is received, each registered content handler's regular expression
19 string is applied to the URI <i>in the order in which the handler's are listed in the
20 content handler map</i> until a match is found, at which point the content handler class's
21 <code>getContent()/putContent()/getHeader()</code> method is invoked.
22 If no regular expression matches the URI,
23 a HTTP 404 (NOT FOUND) error is returned to the client.
24 <p>
25 Application specific parameters for content handlers may be provided by
26 creating a concrete implemention of the HTTP::Daemon::Threaded::ContentParams
27 class, and supplying any constructor parameters as additional key/value
28 pairs in the WebClient constructor hash.
29 <p>
30 Copyright&copy 2006-2008, Dean Arnold, Presicient Corp., USA<br>
31 All rights reserved.
32 <p>
33 Licensed under the Academic Free License version 3.0, as specified at
34 <a href='http://www.opensource.org/licenses/afl-3.0.php'>OpenSource.org</a>.
35  
36 @author D. Arnold
37 @since 2006-08-21
38 @self $self
39  
40 =end classdoc
41  
42 =cut
43  
44 use strict;
45 use warnings;
46  
47 package HTTP::Daemon::Threaded::WebClient;
48 use Socket;
49 use threads;
50 use threads::shared;
51 use Time::Local;
52 use Time::HiRes qw(sleep);
53 use HTTP::Response;
54 use LWP::MediaTypes qw(add_type);
55 use HTTP::Daemon::Threaded::Socket;
56 use HTTP::Daemon::Threaded::Logable;
57 use HTTP::Daemon::Threaded::CGIAdapter;
58 use Thread::Apartment::MuxServer;
59 use URI::Escape;
60 use CGI;
61 use base qw(HTTP::Daemon::Threaded::Logable Thread::Apartment::MuxServer);
62  
63 our $VERSION = '0.91';
64  
65 =pod
66  
67 =begin classdoc
68  
69 @constructor
70  
71 Creates an empty HTTP::Daemon::Threaded::Socket object.
72 Creates any specified ContentParams object, and installs the content handler map.
73 <p>
74 Note that the following parameters are recognized by
75 HTTP::Daemon::Threaded::WebClient, but
76 applications may supply additional parameter key/value pairs
77 which will be provided to the constructor for any specified
78 HTTP::Daemon::Threaded::ContentParams class.
79  
80 @param HTTPD the parent daemon object
81 @param LogLevel <i>(optional)</i> logging level; 1 => errors only; 2 => errors and warnings only; 3 => errors, warnings,
82 and info messages; default 1
83 @param EventLogger <i>(optional)</i> Instance of a HTTP::Daemon::Threaded::Logger to receive
84 event notifications (except for web requests)
85 @param WebLogger <i>(optional)</i> Instance of a HTTP::Daemon::Threaded::Logger to receive
86 web request notifications
87 @param Handlers arrayref mapping URL regex strings to handler classes
88 @param ID unique client identifier
89 @param InactivityTimer <i>(optional)</i> number of seconds to wait before disconnecting an idle connection
90 @param ContentParams <i>(optional)</i> name of a ContentsParam concrete implementation
91 @param UserAuth <i>(optional)</i> User authentication package name <i>(not yet supported)</i>
92 @param SessionCache <i>(optional)</i> threads::shared object implementing HTTP::Daemon::Threaded::SessionCache
93 @param DocRoot <i>(optional)</i> root directory for default file based content handler
94 @param URL the base address/port of our listener
95 @param ProductTokens product token string from listener
96 @param MediaTypes <i>(optional)</i> hashref mapping 'Content-Type' specifications to
97 file qualifier strings. Values may be either a single string literal, or
98 an arrayref of string literals, e.g.,<br>
99 <code>MediaTypes =&gt; { 'text/css' => 'css' }</code>. Used to
100 add media types for LWP::MediaTypes::guess_media_type()
101 @param FreeList free client list; threads::shared array optimized to quickly
102 allocate/free WebClient objects
103 @param SelectInterval seconds to wait in select()'s on sockets. May be fractional; default 0.5
104  
105 @return HTTP::Daemon::Threaded::WebClient object
106  
107 =end classdoc
108  
109 =cut
110  
111 sub new {
112 my ($class, %args) = @_;
113 #
114 # install all web client modules
115 #
116 my $media = delete $args{MediaTypes};
117 my $self = { %args };
118 bless $self, $class;
119 $self->set_client(delete $self->{AptTAC})
120 if $self->{AptTAC};
121 $self->logInfo("WebClient $args{ID} created\n");
122 #
123 # create any content handlers
124 #
125 my %handlers = ();
126 my $i = 0;
127 while ($i <= $#{$args{Handlers}}) {
128 #
129 # compile the regexp string
130 #
131 $args{Handlers}[$i++] = qr/$args{Handlers}[$i]/;
132  
133 my $module = $args{Handlers}[$i];
134 unless ($module eq '*') {
135 if (exists $handlers{$module}) {
136 $args{Handlers}[$i] = $handlers{$module};
137 }
138 else {
139 eval "require $module;";
140 $self->logError("Can't load content handler $module: $@"),
141 $@ = "Can't load content handler $module: $@",
142 return undef
143 if $@;
144 $args{Handlers}[$i] = $handlers{$module} =
145 ${module}->new(
146 SessionCache => $args{SessionCache},
147 ContentParams => $args{ContentParams},
148 LogLevel => $args{LogLevel},
149 EventLogger => $args{EventLogger},
150 );
151 $@ = "Can't create instance of content handler $module",
152 return undef
153 unless defined $handlers{$module};
154 }
155 }
156 $i++;
157 }
158 # print "WebClient has ", join("\n", @{$args{Handlers}}), "\n";
159 #
160 # create a selector
161 #
162 $self->{_sktsel} = HTTP::Daemon::Threaded::IOSelector->new($args{SelectInterval});
163 #
164 # use current time for display
165 #
166 my @ts = split(/\s+/, scalar localtime());
167 $self->{_started} = join(' ', $ts[3], $ts[0], $ts[1], $ts[2], $ts[4]);
168 #
169 # add add'l media types
170 #
171 if ($media) {
172 my ($ct, $fq);
173 add_type($ct => (ref $fq ? @$fq : $fq))
174 while (($ct, $fq) = each %$media);
175 }
176 #
177 # crate local'ized %ENV
178 #
179 local *ENV = { %ENV };
180 return $self;
181 }
182  
183 =pod
184  
185 =begin classdoc
186  
187 Overrides Thread::Apartment::Server::get_simplex_methods().
188  
189 @return hashref of simplex method names
190  
191 =end classdoc
192  
193 =cut
194  
195 sub get_simplex_methods {
196 return {
197 setLogLevel => 1,
198 };
199 }
200 =pod
201  
202 =begin classdoc
203  
204 Accepts a web client connection. Called from HTTP::Daemon::Threaded when a new connection
205 event occurs. Collects the peer info for logging purposes.
206 Converts the supplied socket file number to a HTTP::Daemon::Threaded::Socket
207 object.
208  
209 @param $fn file number of the new socket
210  
211 @return the object
212 @see HTTP::Daemon::Threaded::Socket
213  
214 =end classdoc
215  
216 =cut
217  
218 sub acceptConnection {
219 my ($self, $fn) = @_;
220 #
221 # create empty socket
222 #
223 my $fd = HTTP::Daemon::Threaded::Socket->new();
224 $self->logWarning("WebClient: fdopen($fn) failed: $!."),
225 return undef
226 unless $fd->fdopen($fn, '+>>');
227  
228 binmode $fd;
229 #
230 # collect peer info
231 #
232 my $sockaddr = getpeername($fd);
233 my ($port, $addr) = sockaddr_in($sockaddr);
234 my $clientaddr = inet_ntoa($addr) . ":$port";
235 my $prefix = "Web client $clientaddr";
236 # print "LINGER is ", join(', ', @res), "\n";
237 #
238 # make sure to set options
239 #
240 # $fd->sockopt(SO_KEEPALIVE, pack('l', 1));
241 # $fd->setsockopt(SOL_SOCKET, SO_LINGER, pack('ll', 1,1));
242 # my @res = $fd->getsockopt(SOL_SOCKET, SO_LINGER);
243 # print "LINGER is ", join(', ', @res), "\n";
244 $self->{LogPrefix}{$fn} = $prefix;
245 $fd->setContext($self, 1);
246 #
247 # add to selector
248 #
249 $self->{_sktsel}->addNoWrite($fd);
250 $fd->setSelector($self->{_sktsel});
251  
252 $self->{_curr_skt} = $fd;
253 $self->{_idle_timer} = time();
254 return $self->{ID};
255 }
256  
257 =pod
258  
259 =begin classdoc
260  
261 Thread::Apartment::MuxServer::run() implementation.
262  
263 @return 1
264  
265 =end classdoc
266  
267 =cut
268  
269 sub run {
270 my $self = shift;
271  
272 while (1) {
273 #
274 # HTTP::Daemon::Threaded::IOSelector does the heavy lifting
275 #
276 if (exists $self->{_curr_skt}) {
277 my $elapsed = $self->{_sktsel}->select();
278 #
279 # check idle time
280 #
281 if ($self->{_curr_sess}) {
282 $self->_shutdown()
283 if $self->{_curr_sess}->isInactive($self->{_idle_timer});
284 }
285 elsif ($self->{InactivityTimer} < (time() - $self->{_idle_timer})) {
286 $self->_shutdown();
287 }
288 }
289 else {
290 #
291 # if no connection installed, just kill time
292 #
293 select(undef, undef, undef, 0.1);
294 }
295 return undef
296 unless $self->handle_method_requests();
297 }
298  
299 return 1;
300 }
301  
302 sub _shutdown {
303 my $self = shift;
304 $self->logInfo("Shutting down connection...\n");
305 my $fd = delete $self->{_curr_skt};
306 delete $self->{LogPrefix}{fileno($fd)};
307 $fd->close();
308 $self->{_curr_sess}->close(),
309 delete $self->{_curr_sess}
310 if $self->{_curr_sess};
311 $self->freeClient();
312 return 1;
313 }
314  
315 =pod
316  
317 =begin classdoc
318  
319 Handles a socket event. Accumulates a client request, parses it,
320 and then dispatches to the associated URL handler. Only a single
321 client request is handled, but the connection may be retained
322 indefinitely (for HTTP 1.1 Connection: keepalive clients).
323  
324 @param $fd the HTTP::Daemon::Threaded::Socket object on which the event occured
325  
326 @return the object
327  
328 =end classdoc
329  
330 =cut
331  
332 sub handleSocketEvent {
333 my ($self, $fd) = @_;
334  
335 my ($page, $method, $buffer, $request, $cgi, $params, $handler, $session);
336 my $close_on_resp;
337 $fd = $self->{_curr_skt};
338 my $handlers = $self->{Handlers};
339 #
340 # read the request in (up to some max size) and validate
341 # the header
342 #
343 $request = $fd->get_request();
344 return $self->_shutdown()
345 unless $request;
346  
347 # $self->logInfo("Got a request as a " . (ref $request) . "\n");
348 #
349 # get HTTP protocol level; if < 1.1, we close the connection on exit
350 #
351 # $self->logInfo("Got pre 1.1 client\n"),
352 $close_on_resp = 1,
353 $fd->force_last_request()
354 unless $fd->proto_ge("1.1");
355  
356 $session = $self->{SessionCache}->getSession($request)
357 if $self->{SessionCache};
358 $self->logInfo("Got a session\n") if $session;
359 $page = $request->uri;
360 $method = $request->method;
361 $self->logInfo("Got web request for $method $page\n");
362 $self->{_idle_timer} = time();
363 #
364 # should use other error...should also support HEAD and eventually
365 # PUT and UPLOAD
366 #
367 $fd->send_error(404),
368 return $self->_shutdown()
369 unless (($method eq 'GET') ||
370 ($method eq 'POST') ||
371 ($method eq 'HEAD') ||
372 ($method eq 'PUT'));
373  
374 if ($page=~/^([^\?]+?)\?(.*)$/) {
375 #
376 # extract params and normalize uri
377 #
378 ($page, $cgi, $params) = ($1, 1, $2);
379 $self->logInfo("Its a CGI with params $params\n");
380 }
381 else {
382 #
383 # disable params and normalize uri
384 #
385 ($cgi, $params) = (undef, undef);
386 $page .= 'index.html'
387 if (substr($page, -1, 1) eq '/');
388 }
389 #
390 # if uri is just 'stop', shut everything down
391 #
392 if (($page eq '/stop') && ($method eq 'GET')) {
393 $self->_shutdown();
394 my $httpd = $self->{HTTPD};
395 $httpd->close();
396 return 1;
397 }
398  
399 my $i = 0;
400  
401 $i += 2
402 while ($i <= $#$handlers) &&
403 $self->logInfo("Trying $$handlers[$i] on $page\n") &&
404 ($page!~/$$handlers[$i]/);
405  
406 unless ($i <= $#$handlers) {
407 # $self->logInfo("$prefix: Unknown request URL $page\n"),
408 $self->logInfo("Unknown request URL $page\n");
409 $fd->send_error(404);
410 $self->_shutdown()
411 if $close_on_resp;
412 return 1;
413 }
414  
415 $handler = $handlers->[$i+1];
416 #
417 # read the rest of it (if anymore)
418 # see HTTP::Daemon::ClientConn
419 #
420 my $ct = (($method eq 'GET') || ($method eq 'HEAD')) ?
421 'application/x-www-form-urlencoded' :
422 $request->content_type();
423  
424 if ($ct && ($ct eq 'application/x-www-form-urlencoded')) {
425 $params = $request->content(),
426 $cgi = 1
427 if ($method eq 'POST');
428 #
429 # convert request to (param => value) hash
430 #
431 my %reqparams = ();
432 if ($cgi) {
433 my @request = split(/\&/, $params);
434 $self->logInfo("Orig Params are " . join(', ', @request) . "\n");
435 my ($key, $val);
436  
437 foreach (@request) {
438 ($key, $val) = split /=/;
439 #
440 # fixed per D. Hastings' bug report
441 # NOTE: the unescape might be faster by running the regex locally
442 #
443 $key=~tr/+/ /;
444 $val=~tr/+/ /;
445 ($key, $val) = uri_unescape($key, $val);
446 #
447 # support duplicate params
448 #
449 if (exists $reqparams{$key}) {
450 $reqparams{$key} = [ $reqparams{$key} ]
451 unless ref $reqparams{$key};
452 push @{$reqparams{$key}}, $val;
453 }
454 else {
455 $reqparams{$key} = $val;
456 }
457 }
458 $params = \%reqparams;
459 $self->logInfo("Params are " . join(', ', %reqparams) . "\n");
460 }
461 }
462 elsif ($ct && (length($ct) > 10) && (substr($ct, 0, 10) eq 'multipart/')) {
463 #
464 # multipart request (e.g., file upload); collect the parts
465 #
466 my @parts = $request->parts();
467 $params = \@parts;
468 }
469 elsif ($method eq 'POST') {
470 #
471 # could be anything, just grab it as the parameter and treat as a cgi
472 #
473 $params = $request->content();
474 $cgi = 1;
475 }
476 elsif ($method eq 'PUT') {
477 $params = $request->content();
478 }
479 #
480 # if handler is docroot, just return the file (or its metadata as header)
481 #
482 # $self->logInfo("Using handler " . (ref $handler) . "\n");
483 unless (ref $handler) {
484 #
485 # trim possible leading slash
486 #
487 $page = substr($page, 1)
488 if (substr($page, 0, 1) eq '/');
489 $self->logInfo("Fetching $self->{DocRoot}$page\n");
490 ($method eq 'GET') ?
491 $fd->send_file_response($self->{DocRoot} . $page) :
492 $fd->send_file_header($self->{DocRoot} . $page);
493 $self->_shutdown()
494 if $close_on_resp;
495 return 1;
496 }
497 #
498 # if handler is a CGI, build a CGI object for it
499 #
500 if ($handler->isa('HTTP::Daemon::Threaded::CGIHandler')) {
501 $self->logInfo("Routing to request for $page to handler " . (ref $handler) . "\n");
502 # print STDERR "*** routing CGI request\n";
503 my $cgireq = HTTP::Daemon::Threaded::CGIAdapter->new($request, $fd, $ct);
504 # print STDERR "*** got CGI request, create CGI object\n";
505 my $cgiobj = CGI->new();
506 # print STDERR "*** got CGI object, call handleCGI\n";
507 $handler->handleCGI($cgiobj, $session);
508 # print STDERR "*** got CGI response, send response\n";
509 my $rsp = $cgireq->restore->response;
510 # print STDERR "*** Response is \n", $rsp->as_string(), "\n";
511 $fd->send_response($rsp);
512 # print STDERR "*** sent response\n";
513 #
514 # !!!BE CAREFUL WHEN MERGING W/ 1.01: async will eave stdin/stoud/ENV
515 # in bogus states; we'll need to restore as needed
516 }
517 else {
518
519 $self->logInfo("Routing to request for $page to handler " . (ref $handler) . "\n");
520 my $result =
521 ($method eq 'HEAD') ?
522 $handler->getHeader($fd, $request, $page, $params, $session) :
523 ($method eq 'PUT') ?
524 $handler->putContent($fd, $request, $page, $params, $session) :
525 $handler->getContent($fd, $request, $page, $params, $session);
526 }
527 $self->_shutdown()
528 if $close_on_resp;
529 return 1;
530 }
531 #
532 # borrowed from HTTP::Daemon::ClientConn to emulate HTTP::Daemon
533 #
534 sub url
535 {
536 return $_[0]->{URL};
537 }
538  
539 sub product_tokens
540 {
541 return $_[0]->{ProductTokens};
542 }
543  
544 =pod
545  
546 =begin classdoc
547  
548 Return a client to the free list.
549  
550 @param $client ID of the client being freed
551  
552 @return 1
553  
554 =end classdoc
555  
556 =cut
557  
558 sub freeClient {
559 my $self = shift;
560 {
561 lock(@{$self->{FreeList}});
562 unshift @{$self->{FreeList}}, $self->{ID};
563 }
564 }
565  
566 1;
567