| 1 | ## -*- Mode: CPerl -*- | ||
| 2 | ## | ||
| 3 | ## File: DTA::CAB::Server::HTTP.pm | ||
| 4 | ## Author: Bryan Jurish <moocow@cpan.org> | ||
| 5 | ## Description: DTA::CAB standalone HTTP server using HTTP::Daemon | ||
| 6 | |||
| 7 | package DTA::CAB::Server::HTTP; | ||
| 8 | use DTA::CAB::Server; | ||
| 9 | use DTA::CAB::Server::HTTP::Handler::Builtin; | ||
| 10 | use DTA::CAB::Cache::LRU; | ||
| 11 | use DTA::CAB::Utils qw(:xml); | ||
| 12 | use HTTP::Daemon; | ||
| 13 | use HTTP::Status; | ||
| 14 | use POSIX ':sys_wait_h'; | ||
| 15 | use Socket qw(SOMAXCONN); | ||
| 16 | use Time::HiRes qw(gettimeofday tv_interval); | ||
| 17 | use Carp; | ||
| 18 | use strict; | ||
| 19 | |||
| 20 | ##============================================================================== | ||
| 21 | ## Globals | ||
| 22 | ##============================================================================== | ||
| 23 | |||
| 24 | our @ISA = qw(DTA::CAB::Server); | ||
| 25 | |||
| 26 | ##============================================================================== | ||
| 27 | ## Constructors etc. | ||
| 28 | ##============================================================================== | ||
| 29 | |||
| 30 | ## $obj = CLASS_OR_OBJ->new(%args) | ||
| 31 | ## + object structure: HASH ref | ||
| 32 | ## { | ||
| 33 | ## ##-- Underlying HTTP::Daemon server | ||
| 34 | ## daemonMode => $daemonMode, ##-- one of 'serial' or 'fork' [default='serial'] | ||
| 35 | ## daemonArgs => \%daemonArgs, ##-- args to HTTP::Daemon->new(); default={LocalAddr=>'0.0.0.0',LocalPort=>8088} | ||
| 36 | ## paths => \%path2handler, ##-- maps local URL paths to configs | ||
| 37 | ## daemon => $daemon, ##-- underlying HTTP::Daemon object | ||
| 38 | ## cxsrv => $cxsrv, ##-- associated DTA::CAB::Server::XmlRpc object for XML-RPC handlers | ||
| 39 | ## xopt => \%xmlRpcOpts, ##-- options for RPC::XML::Server sub-object (for XML-RPC handlers; default: {no_http=>1}) | ||
| 40 | ## ## | ||
| 41 | ## ##-- caching & status | ||
| 42 | ## cacheSize => $nelts, ##-- maximum number of responses to cache (default=1024; undef for no cache) | ||
| 43 | ## cacheLimit => $nbytes, ##-- max number of content bytes for cached responses (default=undef: no limit) | ||
| 44 | ## cache => $lruCache, ##-- response cache: (key = $url, value = $response), a DTA::CAB::Cache::LRU object | ||
| 45 | ## nRequests => $nRequests, ##-- number of requests (after access control) | ||
| 46 | ## nCacheHits => $nCacheHits, ##-- number of cache hits | ||
| 47 | ## nErrors => $nErrors, ##-- number of client errors | ||
| 48 | ## qtAvg => $qtAvg, ##-- query time load average (exponential moving average for 1m,5m,15m, a la linux cpuload), sample values in seconds | ||
| 49 | ## qt0 => \@time, ##-- time we started processing most recent query (Time::HiRes::gettimeofday) | ||
| 50 | ## ## | ||
| 51 | ## ##-- security | ||
| 52 | ## allowUserOptions => $bool, ##-- allow user options? (default: true) | ||
| 53 | ## allow => \@allow_ip_regexes, ##-- allow queries from these clients (default=none) | ||
| 54 | ## deny => \@deny_ip_regexes, ##-- deny queries from these clients (default=none) | ||
| 55 | ## _allow => $allow_ip_regex, ##-- single allow regex (compiled by 'prepare()') | ||
| 56 | ## _deny => $deny_ip_regex, ##-- single deny regex (compiled by 'prepare()') | ||
| 57 | ## maxRequestSize => $bytes, ##-- maximum request content-length in bytes (default: undef//-1: no max) | ||
| 58 | ## bgConnectTimeout => $secs, ##-- timeout for detecting chrome-style "background connections": connected sockets with no data on them (0:none; default=1) | ||
| 59 | ## ## | ||
| 60 | ## ##-- forking | ||
| 61 | ## forkOnGet => $bool, ##-- fork() handler for HTTP GET requests? (default=0) | ||
| 62 | ## forkOnPost => $bool, ##-- fork() handler for HTTP POST requests? (default=1) | ||
| 63 | ## forkMax => $n, ##-- maximum number of subprocess to spwan (default=4; 0~no limit) | ||
| 64 | ## children => \%pids, ##-- child PIDs | ||
| 65 | ## pid => $pid, ##-- PID of parent server process | ||
| 66 | ## ## | ||
| 67 | ## ##-- logging | ||
| 68 | ## logRegisterPath => $level, ##-- log registration of path handlers at $level (default='info') | ||
| 69 | ## logAttempt => $level, ##-- log connection attempts at $level (default=undef: none) | ||
| 70 | ## logConnect => $level, ##-- log successful connections (client IP and requested path) at $level (default='debug') | ||
| 71 | ## logRquestData => $level, ##-- log full client request data at $level (default=undef: none) | ||
| 72 | ## logResponse => $level, ##-- log full client response at $level (default=undef: none) | ||
| 73 | ## logCache => $level, ##-- log cache hit data at $level (default=undef: none) | ||
| 74 | ## logClientError => $level, ##-- log errors to client at $level (default='debug') | ||
| 75 | ## logClose => $level, ##-- log close client connections (default=undef: none) | ||
| 76 | ## logReap => $level, ##-- log harvesting of child pids (default=undef: none) | ||
| 77 | ## logSpawn => $level, ##-- log spawning of child pids (default=undef: none) | ||
| 78 | ## ## | ||
| 79 | ## ##-- (inherited from DTA::CAB::Server) | ||
| 80 | ## as => \%analyzers, ##-- ($name=>$cab_analyzer_obj, ...) | ||
| 81 | ## aos => \%anlOptions, ##-- ($name=>\%analyzeOptions, ...) : %opts passed to $anl->analyzeXYZ($xyz,%opts) | ||
| 82 | ## } | ||
| 83 | ## | ||
| 84 | ## + path handlers: | ||
| 85 | ## - object descended from DTA::CAB::Server::HTTP::Handler | ||
| 86 | ## - or HASH ref { class=>$subclass, %classNewArgs } | ||
| 87 | ## - or ARRAY ref [ $subclass, @classNewArgs ] | ||
| 88 | ## | ||
| 89 | sub new { | ||
| 90 | my $that = shift; | ||
| 91 | return $that->SUPER::new( | ||
| 92 | ##-- underlying server | ||
| 93 | daemonArgs => { | ||
| 94 | LocalAddr=>'0.0.0.0', ##-- all | ||
| 95 | LocalPort=>8088, | ||
| 96 | ReuseAddr=>1, | ||
| 97 | #ReusePort=>1, ##-- don't set this; it causes errors "Your vendor has not defined Socket macro SO_REUSEPORT" | ||
| 98 | }, | ||
| 99 | #cxsrv => undef, | ||
| 100 | xopt => {no_http=>1}, | ||
| 101 | |||
| 102 | ##-- path config | ||
| 103 | paths => {}, | ||
| 104 | |||
| 105 | ##-- caching & status | ||
| 106 | cacheSize => 1024, | ||
| 107 | cacheLimit => undef, | ||
| 108 | cache => undef, | ||
| 109 | nRequests => 0, | ||
| 110 | nCacheHits => 0, | ||
| 111 | nErrors => 0, | ||
| 112 | qtAvg => DTA::CAB::Utils::EMA->new(decay=>[60,(5*60),(15*60)]), | ||
| 113 | qt0 => undef, | ||
| 114 | |||
| 115 | ##-- security | ||
| 116 | allowUserOptions => 1, | ||
| 117 | allow => [], | ||
| 118 | deny => [], | ||
| 119 | _allow => undef, | ||
| 120 | _deny => undef, | ||
| 121 | maxRequestSize => undef, | ||
| 122 | bgConnectTimeout => 1, | ||
| 123 | |||
| 124 | ##-- forking | ||
| 125 | children => {}, | ||
| 126 | forkOnGet => 0, | ||
| 127 | forkOnPost => 1, | ||
| 128 | forkMax => 4, | ||
| 129 | |||
| 130 | ##-- logging | ||
| 131 | logRegisterPath => 'info', | ||
| 132 | logAttempt => 'off', | ||
| 133 | logConnect => 'debug', | ||
| 134 | logRequestData => undef, | ||
| 135 | logResponse => undef, | ||
| 136 | logCache => 'debug', | ||
| 137 | logClose => 'off', | ||
| 138 | logClientError => 'trace', | ||
| 139 | |||
| 140 | ##-- logging, XML-RPC sub-objects | ||
| 141 | logRegisterProc => 'off', | ||
| 142 | logCallData => 'off', | ||
| 143 | logCall => 'off', | ||
| 144 | |||
| 145 | ##-- logging, fork-related | ||
| 146 | logSpawn => 'off', | ||
| 147 | logReap => 'off', | ||
| 148 | |||
| 149 | ##-- user args | ||
| 150 | @_ | ||
| 151 | ); | ||
| 152 | } | ||
| 153 | |||
| 154 | ## undef = $obj->initialize() | ||
| 155 | ## + called to initialize new objects after new() | ||
| 156 | |||
| 157 | ##============================================================================== | ||
| 158 | ## Methods: subclass API (abstractions for HTTP::UNIX) | ||
| 159 | |||
| 160 | ## $str = $srv->socketLabel() | ||
| 161 | ## + returns symbolic label for bound socket address | ||
| 162 | sub socketLabel { | ||
| 163 | my $srv = shift; | ||
| 164 | return ($srv->{daemonArgs}{LocalAddr}||'0.0.0.0').':'.($srv->{daemonArgs}{LocalPort}); | ||
| 165 | } | ||
| 166 | |||
| 167 | ## $str = $srv->daemonLabel() | ||
| 168 | ## + returns symbolic label for running daemon | ||
| 169 | sub daemonLabel { | ||
| 170 | my $srv = shift; | ||
| 171 | return ($srv->{daemon}->sockhost.":".$srv->{daemon}->sockport); | ||
| 172 | } | ||
| 173 | |||
| 174 | ## $bool = $srv->canBindSocket() | ||
| 175 | ## $bool = $srv->canBindSocket(\%daemonArgs) | ||
| 176 | ## + returns true iff socket can be bound; should set $! on error | ||
| 177 | sub canBindSocket { | ||
| 178 | my $srv = shift; | ||
| 179 | my $dargs = (@_ ? shift : $srv->{daemonArgs}) || {}; | ||
| 180 | $dargs->{LocalAddr} ||= '0.0.0.0'; | ||
| 181 | my $sock = IO::Socket::INET->new(%$dargs, Listen=>1) or return 0; | ||
| 182 | undef $sock; | ||
| 183 | return 1; | ||
| 184 | } | ||
| 185 | |||
| 186 | ## $class = $srv->daemonClass() | ||
| 187 | ## + get HTTP::Daemon class | ||
| 188 | sub daemonClass { | ||
| 189 | return 'HTTP::Daemon'; | ||
| 190 | } | ||
| 191 | |||
| 192 | ## $class_or_undef = $srv->clientClass() | ||
| 193 | ## + get class for client connections | ||
| 194 | sub clientClass { | ||
| 195 | return undef; | ||
| 196 | } | ||
| 197 | |||
| 198 | ##============================================================================== | ||
| 199 | ## Methods: Generic Server API | ||
| 200 | ##============================================================================== | ||
| 201 | |||
| 202 | ## $rc = $srv->prepareLocal() | ||
| 203 | ## + subclass-local initialization | ||
| 204 | sub prepareLocal { | ||
| 205 | my $srv = shift; | ||
| 206 | |||
| 207 | ##-- setup HTTP::Daemon object | ||
| 208 | $srv->{daemonArgs}{Listen} ||= SOMAXCONN; | ||
| 209 | if (!($srv->{daemon}=$srv->daemonClass->new(%{$srv->{daemonArgs}}))) { | ||
| 210 | $srv->logconfess("could not create ", $srv->daemonClass, " daemon object: $!"); | ||
| 211 | } | ||
| 212 | my $daemon = $srv->{daemon}; | ||
| 213 | |||
| 214 | ##-- register path handlers | ||
| 215 | my ($path,$ph); | ||
| 216 | while (($path,$ph)=each %{$srv->{paths}}) { | ||
| 217 | $ph = $srv->registerPathHandler($path,$ph) | ||
| 218 | or $srv->logconfess("registerPathHandler() failed for path '$path': $!"); | ||
| 219 | $srv->vlog($srv->{logRegisterPath}, "registered path handler: '$path' => ".(ref($ph)||$ph)); | ||
| 220 | } | ||
| 221 | |||
| 222 | ##-- compile allow/deny regexes | ||
| 223 | foreach my $policy (qw(allow deny)) { | ||
| 224 | my $re = $srv->{$policy} && @{$srv->{$policy}} ? join('|', map {"(?:$_)"} @{$srv->{$policy}}) : '^$'; | ||
| 225 | $srv->{"_".$policy} = qr/$re/; | ||
| 226 | } | ||
| 227 | |||
| 228 | ##-- setup cache | ||
| 229 | $srv->{cache} = DTA::CAB::Cache::LRU->new(max_size=>$srv->{cacheSize}) if (!$srv->{cache} && $srv->{cacheSize}>0); | ||
| 230 | |||
| 231 | ##-- setup mode-specific options | ||
| 232 | $srv->{daemonMode} //= 'serial'; | ||
| 233 | $srv->{pid} //= $$; | ||
| 234 | if ($srv->{daemonMode} eq 'fork') { | ||
| 235 | $srv->{children} //= {}; | ||
| 236 | $SIG{CHLD} = $srv->reaper(); | ||
| 237 | } | ||
| 238 | |||
| 239 | return 1; | ||
| 240 | } | ||
| 241 | |||
| 242 | ## $rc = $srv->run() | ||
| 243 | ## + run the server | ||
| 244 | sub run { | ||
| 245 | my $srv = shift; | ||
| 246 | $srv->prepare() if (!$srv->{daemon}); ##-- sanity check | ||
| 247 | $srv->logcroak("run(): no underlying daemon object!") if (!$srv->{daemon}); | ||
| 248 | |||
| 249 | my $daemon = $srv->{daemon}; | ||
| 250 | my $mode = $srv->{daemonMode} || 'serial'; | ||
| 251 | my $cclass = $srv->clientClass; | ||
| 252 | my $bgConnectTimeout = $srv->{bgConnectTimeout} || 0; | ||
| 253 | $srv->info("server starting in $mode mode on ", $srv->daemonLabel, "\n"); | ||
| 254 | |||
| 255 | ##-- setup SIGPIPE handler (avoid heinous death) | ||
| 256 | ## + following suggestion on http://www.perlmonks.org/?node_id=580411 | ||
| 257 | $SIG{PIPE} = sub { ++$srv->{nErrors}; $srv->vlog('warn',"got SIGPIPE (ignoring)"); }; | ||
| 258 | |||
| 259 | ##-- HACK: set HTTP::Daemon protocol to HTTP 1.0 (avoid keepalive) | ||
| 260 | $HTTP::Daemon::PROTO = "HTTP/1.0"; | ||
| 261 | |||
| 262 | my ($csock,$chost,$hreq,$urikey,$forkable,$cacheable,$handler,$localPath,$pid,$rsp); | ||
| 263 | my ($fdset); | ||
| 264 | while (1) { | ||
| 265 | ##-- track total processing time for *last* query | ||
| 266 | $srv->qtfinish(); | ||
| 267 | |||
| 268 | ##-- call accept() within the loop to avoid breaking out in fork mode | ||
| 269 | if (!defined($csock=$daemon->accept())) { | ||
| 270 | #sleep(1); | ||
| 271 | next; | ||
| 272 | } | ||
| 273 | |||
| 274 | ##-- query processing starts | ||
| 275 | $srv->{qt0} = [gettimeofday]; | ||
| 276 | |||
| 277 | ##-- re-bless client socket (for UNIX-domain server) | ||
| 278 | bless($csock,$cclass) if ($cclass); | ||
| 279 | |||
| 280 | ##-- got client $csock (HTTP::Daemon::ClientConn object; see HTTP::Daemon(3pm)) | ||
| 281 | $chost = $csock->peerhost(); | ||
| 282 | |||
| 283 | ##-- avoid blocking on weird EOF sockets sent e.g. by chromium: no joy | ||
| 284 | if ($bgConnectTimeout > 0) { | ||
| 285 | vec(($fdset=""), $csock->fileno, 1) = 1; | ||
| 286 | if (!select($fdset,undef,undef,$bgConnectTimeout)) { | ||
| 287 | $srv->vlog($srv->{logAttempt}, "ignoring background connection from client $chost"); | ||
| 288 | #++$srv->{nErrors}; | ||
| 289 | next; | ||
| 290 | } | ||
| 291 | } | ||
| 292 | |||
| 293 | ##-- access control | ||
| 294 | $srv->vlog($srv->{logAttempt}, "attempted connect from client $chost"); | ||
| 295 | if (!$srv->clientAllowed($csock,$chost)) { | ||
| 296 | $srv->denyClient($csock); | ||
| 297 | next; | ||
| 298 | } | ||
| 299 | |||
| 300 | ##-- track number of requests | ||
| 301 | ++$srv->{nRequests}; | ||
| 302 | |||
| 303 | ##-- serve client: parse HTTP request | ||
| 304 | ## | ||
| 305 | ## Strangeness Fri, 17 May 2013 14:14:56 +0200 | ||
| 306 | ## + returning true from demo.js cabUpload() causes weird 'Client closed' errors on post-upload 'Back' clicks from chromium | ||
| 307 | ## + problem maybe related to bizarre closed-client crashes for HTTP::Daemon::ClientConn observed elsewhere: persists even within eval BLOCK | ||
| 308 | ## + symptom(s): | ||
| 309 | ## - get_request() fails after ca. 10sec | ||
| 310 | ## - HTTP::Daemon::DEBUG output shows "Need more data for complete header\nsysread()\n" | ||
| 311 | ## - no data is actually read into $csock buffer (checked with debugger) | ||
| 312 | ## - $csock invalidates with $csock->reason='Client closed', but $csock->opened()==1 | ||
| 313 | ## - attempting to write to $csock in this state (e.g. by clientError()) causes immediate termination of the running server! | ||
| 314 | ## | ||
| 315 | ##DEBUG | ||
| 316 | #$srv->vlog($srv->{logAttempt}, "get_request() for client $chost"); | ||
| 317 | #$HTTP::Daemon::DEBUG=1; | ||
| 318 | ${*$csock}{'io_socket_timeout'} = 5; | ||
| 319 | ${*$csock}{'httpd_client_proto'} = HTTP::Daemon::ClientConn::_http_version("HTTP/1.0"); ##-- HACK: force status line on send_error() from $csock->get_request() | ||
| 320 | ##/DEBUG | ||
| 321 | $hreq = $csock->get_request(); | ||
| 322 | if (!$hreq) { | ||
| 323 | $srv->clientError($csock, RC_BAD_REQUEST, "could not parse HTTP request: ", xml_escape($csock->reason || 'get_request() failed')); | ||
| 324 | ++$srv->{nErrors}; | ||
| 325 | next; | ||
| 326 | } | ||
| 327 | |||
| 328 | ##-- log basic request, and possibly request data | ||
| 329 | $urikey = $hreq->uri->as_string; | ||
| 330 | $srv->vlog($srv->{logConnect}, "client $chost: ", $hreq->method, ' ', $urikey); | ||
| 331 | $srv->vlog($srv->{logRequestData}, "client $chost: HTTP::Request={\n", $hreq->as_string, "}"); | ||
| 332 | |||
| 333 | ##-- check global content-length limit | ||
| 334 | if (($srv->{maxRequestSize}//-1) >= 0 && ($hreq->content_length//0) > $srv->{maxRequestSize}) { | ||
| 335 | $srv->clientError($csock, RC_REQUEST_ENTITY_TOO_LARGE, "request exceeds server limit (max=$srv->{maxRequestSize} bytes)"); | ||
| 336 | ++$srv->{nErrors}; | ||
| 337 | next; | ||
| 338 | } | ||
| 339 | |||
| 340 | ##-- map request to handler | ||
| 341 | ($handler,$localPath) = $srv->getPathHandler($hreq->uri); | ||
| 342 | if (!defined($handler)) { | ||
| 343 | $srv->clientError($csock, RC_NOT_FOUND, "cannot resolve URI ", xml_escape($hreq->uri)); | ||
| 344 | ++$srv->{nErrors}; | ||
| 345 | next; | ||
| 346 | } | ||
| 347 | |||
| 348 | ##-- check whether we can fork for this request (by default only for POST) | ||
| 349 | $forkable = ($mode eq 'fork' | ||
| 350 | && $srv->{"forkOn".ucfirst(lc($hreq->method))} | ||
| 351 | && (!$srv->{forkMax} || scalar(keys %{$srv->{children}}) < $srv->{forkMax})); | ||
| 352 | |||
| 353 | ##-- check cache (GET requests only) | ||
| 354 | $cacheable = ($srv->{cache} | ||
| 355 | && (!defined($handler->{cacheable}) || $handler->{cacheable}) | ||
| 356 | && $hreq->method eq 'GET' | ||
| 357 | && ($hreq->header('Pragma')||'') !~ /\bno-cache\b/); | ||
| 358 | if ($cacheable | ||
| 359 | && ($hreq->header('Cache-Control')||'') !~ /\bno-cache\b/ | ||
| 360 | && defined($rsp = $srv->{cache}->get($urikey))) | ||
| 361 | { | ||
| 362 | ++$srv->{nCacheHits}; | ||
| 363 | $srv->vlog($srv->{logCache}, "using cached response"); | ||
| 364 | $rsp->header('X-Cached' => 1); | ||
| 365 | $srv->vlog($srv->{logResponse}, "cached response: ", $rsp->as_string) if ($srv->{logResponse}); | ||
| 366 | $csock->send_response($rsp); | ||
| 367 | next; | ||
| 368 | } | ||
| 369 | |||
| 370 | ##-- maybe fork | ||
| 371 | $pid = $forkable ? fork() : undef; | ||
| 372 | if ($pid) { | ||
| 373 | ##-- parent code | ||
| 374 | $srv->{children}{$pid} = undef; | ||
| 375 | $srv->vlog($srv->{logSpawn}, "spawned subprocess $pid"); | ||
| 376 | $srv->{qt0} = undef; | ||
| 377 | next; | ||
| 378 | } | ||
| 379 | |||
| 380 | ##-- child|serial code: pass request to handler | ||
| 381 | eval { | ||
| 382 | $rsp = $handler->run($srv,$localPath,$csock,$hreq); | ||
| 383 | }; | ||
| 384 | if ($@) { | ||
| 385 | $srv->clientError($csock,RC_INTERNAL_SERVER_ERROR,"handler ", (ref($handler)||$handler), "::run() died:<br/><pre>", xml_escape($@), "</pre>"); | ||
| 386 | $srv->reapClient($csock,$handler,$chost); | ||
| 387 | ++$srv->{nErrors}; | ||
| 388 | } | ||
| 389 | elsif (!defined($rsp)) { | ||
| 390 | $srv->clientError($csock,RC_INTERNAL_SERVER_ERROR,"handler ", (ref($handler)||$handler), "::run() failed"); | ||
| 391 | $srv->reapClient($csock,$handler,$chost); | ||
| 392 | ++$srv->{nErrors}; | ||
| 393 | } | ||
| 394 | |||
| 395 | ##-- maybe cache response | ||
| 396 | if ($cacheable | ||
| 397 | && !$forkable ##-- no caching if we're forked | ||
| 398 | && ($hreq->header('Cache-Control')||'') !~ /\bno-store\b/) | ||
| 399 | { | ||
| 400 | if (!defined($srv->{cacheLimit}) || length(${$rsp->content_ref}) <= $srv->{cacheLimit}) { | ||
| 401 | $srv->vlog($srv->{logCache}, "caching response"); | ||
| 402 | $srv->{cache}->set($urikey,$rsp); | ||
| 403 | } else { | ||
| 404 | $srv->vlog($srv->{logCache}, | ||
| 405 | "response length=", | ||
| 406 | length(${$rsp->content_ref}), | ||
| 407 | " exceeds server limit=$srv->{cacheLimit}: NOT caching response"); | ||
| 408 | } | ||
| 409 | } | ||
| 410 | |||
| 411 | #sleep(3); ##-- DEBUG: simulate long processing | ||
| 412 | |||
| 413 | ##-- ... and dump response to client | ||
| 414 | if (!$csock->opened) { | ||
| 415 | $srv->logwarn("client socket closed unexpectedly"); | ||
| 416 | ++$srv->{nErrors}; | ||
| 417 | next; | ||
| 418 | } elsif ($csock->error) { | ||
| 419 | $srv->logwarn("client socket has errors"); | ||
| 420 | ++$srv->{nErrors}; | ||
| 421 | next; | ||
| 422 | } | ||
| 423 | $srv->vlog($srv->{logResponse}, "cached response: ", $rsp->as_string) if ($srv->{logResponse}); | ||
| 424 | $csock->send_response($rsp); | ||
| 425 | } | ||
| 426 | continue { | ||
| 427 | ##-- cleanup after client | ||
| 428 | $srv->reapClient($csock,$handler,$chost) if (!$pid); | ||
| 429 | $hreq=$handler=$localPath=$pid=$rsp=undef; | ||
| 430 | } | ||
| 431 | |||
| 432 | |||
| 433 | $srv->info("server exiting\n"); | ||
| 434 | return $srv->finish(); | ||
| 435 | } | ||
| 436 | |||
| 437 | |||
| 438 | ##============================================================================== | ||
| 439 | ## Methods: Local: spawn and reap | ||
| 440 | |||
| 441 | ## \&reaper = $srv->reaper() | ||
| 442 | ## + zombie-harvesting code; installed to local %SIG | ||
| 443 | sub reaper { | ||
| 444 | my $srv = shift; | ||
| 445 | return sub { | ||
| 446 | my ($child); | ||
| 447 | while (($child = waitpid(-1,WNOHANG)) > 0) { | ||
| 448 | $srv->vlog($srv->{logReap},"reaped subprocess pid=$child, status=$?"); | ||
| 449 | delete $srv->{children}{$child}; | ||
| 450 | } | ||
| 451 | #$SIG{CHLD}=$srv->reaper() if ($srv->{installReaper}); ##-- re-install reaper for SysV | ||
| 452 | }; | ||
| 453 | } | ||
| 454 | |||
| 455 | ## undef = $srv->reapClient($csock, $handler_or_undef, $chost_or_undef) | ||
| 456 | sub reapClient { | ||
| 457 | my ($srv,$csock,$handler,$chost) = @_; | ||
| 458 | return if (!$csock); | ||
| 459 | $srv->vlog($srv->{logClose}, "closing connection to client ", ($chost // ($csock->opened ? $csock->peerhost : '-undef-'))); | ||
| 460 | if ($csock->opened) { | ||
| 461 | $csock->force_last_request(); | ||
| 462 | $csock->shutdown(2); | ||
| 463 | } | ||
| 464 | $handler->finish($srv,$csock) if (defined($handler)); | ||
| 465 | exit 0 if ($srv->{pid} && $srv->{pid} != $$); | ||
| 466 | return; | ||
| 467 | } | ||
| 468 | |||
| 469 | ##============================================================================== | ||
| 470 | ## Methods: Local: Path Handlers | ||
| 471 | |||
| 472 | ## $handler = $srv->registerPathHandler($pathStr, \%handlerSpec) | ||
| 473 | ## $handler = $srv->registerPathHandler($pathStr, \@handlerSpec) | ||
| 474 | ## $handler = $srv->registerPathHandler($pathStr, $handlerObject) | ||
| 475 | ## + registers a path handler for path $pathStr | ||
| 476 | ## + sets $srv->{paths}{$pathStr} = $handler | ||
| 477 | sub registerPathHandler { | ||
| 478 | my ($srv,$path,$ph) = @_; | ||
| 479 | |||
| 480 | if (ref($ph) && ref($ph) eq 'HASH') { | ||
| 481 | ##-- HASH ref: implicitly parse | ||
| 482 | my $class = DTA::CAB::Server::HTTP::Handler->fqClass($ph->{class}); | ||
| 483 | $srv->logconfess("unknown class '", ($ph->{class}||'??'), "' for path '$path'") | ||
| 484 | if (!UNIVERSAL::isa($class,'DTA::CAB::Server::HTTP::Handler')); | ||
| 485 | $ph = $class->new(%$ph); | ||
| 486 | } | ||
| 487 | elsif (ref($ph) && ref($ph) eq 'ARRAY') { | ||
| 488 | ##-- ARRAY ref: implicitly parse | ||
| 489 | my $class = DTA::CAB::Server::HTTP::Handler->fqClass($ph->[0]); | ||
| 490 | $srv->logconfess("unknown class '", ($ph->[0]||'??'), "' for path '$path'") | ||
| 491 | if (!UNIVERSAL::isa($class,'DTA::CAB::Server::HTTP::Handler')); | ||
| 492 | $ph = $class->new(@$ph[1..$#$ph]); | ||
| 493 | } | ||
| 494 | |||
| 495 | ##-- prepare URI | ||
| 496 | $ph->prepare($srv,$path) | ||
| 497 | or $srv->logconfess("Path::prepare() failed for path string '$path'"); | ||
| 498 | |||
| 499 | return $srv->{paths}{$path} = $ph; | ||
| 500 | } | ||
| 501 | |||
| 502 | |||
| 503 | ## ($handler,$localPath) = $srv->getPathHandler($hreq_uri) | ||
| 504 | sub getPathHandler { | ||
| 505 | my ($srv,$uri) = @_; | ||
| 506 | |||
| 507 | my @segs = $uri->canonical->path_segments; | ||
| 508 | my ($i,$path,$handler); | ||
| 509 | for ($i=$#segs; $i >= 0; $i--) { | ||
| 510 | $path = join('/',@segs[0..$i]); | ||
| 511 | return ($handler,$path) if (defined($handler=$srv->{paths}{$path})); | ||
| 512 | } | ||
| 513 | return ($handler,$path); | ||
| 514 | } | ||
| 515 | |||
| 516 | |||
| 517 | |||
| 518 | ##============================================================================== | ||
| 519 | ## Methods: Local: Access Control | ||
| 520 | |||
| 521 | ## $bool = $srv->clientAllowed($clientSock) | ||
| 522 | ## + returns true iff $cli may access the server | ||
| 523 | sub clientAllowed { | ||
| 524 | my ($srv,$csock,$chost) = @_; | ||
| 525 | $chost = $csock->peerhost() if (!$chost); | ||
| 526 | return ($chost =~ $srv->{_allow} || $chost !~ $srv->{_deny}); | ||
| 527 | } | ||
| 528 | |||
| 529 | ## undef = $srv->denyClient($clientSock) | ||
| 530 | ## undef = $srv->denyClient($clientSock, $denyMessage) | ||
| 531 | ## + denies access to $client | ||
| 532 | ## + shuts down client socket | ||
| 533 | sub denyClient { | ||
| 534 | my ($srv,$csock,@msg) = @_; | ||
| 535 | my $chost = $csock->peerhost(); | ||
| 536 | @msg = "Access denied from client $chost" if (!@msg); | ||
| 537 | $srv->clientError($csock, RC_FORBIDDEN, @msg); | ||
| 538 | } | ||
| 539 | |||
| 540 | ##====================================================================== | ||
| 541 | ## Methods: Local: error handling | ||
| 542 | |||
| 543 | ## undef = $srv->clientError($clientSock,$status,@message) | ||
| 544 | ## + send an error message to the client | ||
| 545 | ## + $status defaults to RC_INTERNAL_SERVER_ERROR | ||
| 546 | ## + shuts down the client socket | ||
| 547 | sub clientError { | ||
| 548 | my ($srv,$csock,$status,@msg) = @_; | ||
| 549 | if ($csock->opened) { | ||
| 550 | my $chost = $csock->peerhost(); | ||
| 551 | my $msg = join('',@msg); | ||
| 552 | $status = RC_INTERNAL_SERVER_ERROR if (!defined($status)); | ||
| 553 | $srv->vlog($srv->{logClientError}, "clientError($chost): $msg"); | ||
| 554 | if ($msg !~ /: client closed$/i) { | ||
| 555 | ##-- don't try to write to sockets reporting 'client closed': this crashes the running server inexplicably! | ||
| 556 | my $_warn=$^W; | ||
| 557 | $^W=0; | ||
| 558 | #$csock->send_error($status, $msg); ##-- response not parseable as xml (see mantis bug #12941) | ||
| 559 | $csock->send_response(DTA::CAB::Server::HTTP::Handler->errorResponse($status,$msg)); | ||
| 560 | $^W=$_warn; | ||
| 561 | } | ||
| 562 | $csock->force_last_request(); | ||
| 563 | $csock->shutdown(2); | ||
| 564 | } | ||
| 565 | $csock->close() if (UNIVERSAL::can($csock,'close')); | ||
| 566 | $@ = undef; ##-- unset eval error | ||
| 567 | return undef; | ||
| 568 | } | ||
| 569 | |||
| 570 | ## $qtavg = $srv->qtfinish() | ||
| 571 | ## + called at end of query-processing to update the query-time average | ||
| 572 | sub qtfinish { | ||
| 573 | my $srv = shift; | ||
| 574 | return $srv->{qtAvg} if (!$srv->{qt0}); | ||
| 575 | my $t0 = $srv->{qt0}; | ||
| 576 | my $t1 = [gettimeofday]; | ||
| 577 | $srv->{qt0} = undef; | ||
| 578 | return $srv->{qtAvg}->append(tv_interval($t0,$t1),$t1); | ||
| 579 | } | ||
| 580 | |||
| 581 | 1; ##-- be happy | ||
| 582 | |||
| 583 | __END__ |