| 1 | ## -*- Mode: CPerl -*- | ||
| 2 | ## | ||
| 3 | ## File: DTA::CAB::Server::HTTP::UNIX.pm | ||
| 4 | ## Author: Bryan Jurish <moocow@cpan.org> | ||
| 5 | ## Description: DTA::CAB standalone HTTP server using HTTP::Daemon::UNIX | ||
| 6 | |||
| 7 | package DTA::CAB::Server::HTTP::UNIX; | ||
| 8 | use DTA::CAB::Server::HTTP; | ||
| 9 | use HTTP::Daemon::UNIX; | ||
| 10 | use File::Basename qw(basename dirname); | ||
| 11 | use File::Path qw(make_path); | ||
| 12 | use POSIX ':sys_wait_h'; | ||
| 13 | use Socket qw(SOMAXCONN); | ||
| 14 | use Carp; | ||
| 15 | use strict; | ||
| 16 | |||
| 17 | ##============================================================================== | ||
| 18 | ## Globals | ||
| 19 | ##============================================================================== | ||
| 20 | |||
| 21 | our @ISA = qw(DTA::CAB::Server::HTTP); | ||
| 22 | |||
| 23 | ##============================================================================== | ||
| 24 | ## Constructors etc. | ||
| 25 | ##============================================================================== | ||
| 26 | |||
| 27 | ## $obj = CLASS_OR_OBJ->new(%args) | ||
| 28 | ## + object structure: HASH ref | ||
| 29 | ## { | ||
| 30 | ## ##-- DTA::CAB::Server::HTTP::UNIX overrides | ||
| 31 | ## daemonArgs => \%daemonArgs, ##-- overrides for HTTP::Daemon::UNIX->new(); default={Local=>'/tmp/dta-cab.sock'} | ||
| 32 | ## socketPerms => $mode, ##-- socket permissions as an octal string (default='0666') | ||
| 33 | ## socketUser => $user, ##-- socket user or uid (root only; default=undef: current user) | ||
| 34 | ## socketGroup => $group, ##-- socket group or gid (default=undef: current group) | ||
| 35 | ## _socketPath => $path, ##-- bound socket path (for unlink() on destroy) | ||
| 36 | ## #_socketDirs => \@dirs, ##-- auto-created socket directories (DISABLED) | ||
| 37 | ## relayCmd => \@cmd, ##-- TCP relay command-line for exec() (default=[qw(socat ...)], see prepareRelay()) | ||
| 38 | ## relayAddr => $addr, ##-- TCP relay address to bind (default=$daemonArgs{LocalAddr}, see prepareRelay()) | ||
| 39 | ## relayPort => $port, ##-- TCP relay address to bind (default=$daemonArgs{LocalPort}, see prepareRelay()) | ||
| 40 | ## relayPid => $pid, ##-- child PID for TCP relay process (sockrelay.perl / socat; see prepareRelay()) | ||
| 41 | ## | ||
| 42 | ## ##-- (inherited from DTA::CAB::Server:HTTP): Underlying HTTP::Daemon server | ||
| 43 | ## daemonMode => $daemonMode, ##-- one of 'serial' or 'fork' [default='serial'] | ||
| 44 | ## #daemonArgs => \%daemonArgs, ##-- args to HTTP::Daemon->new(); default={LocalAddr=>'0.0.0.0',LocalPort=>8088} | ||
| 45 | ## paths => \%path2handler, ##-- maps local URL paths to configs | ||
| 46 | ## daemon => $daemon, ##-- underlying HTTP::Daemon::UNIX object | ||
| 47 | ## cxsrv => $cxsrv, ##-- associated DTA::CAB::Server::XmlRpc object for XML-RPC handlers | ||
| 48 | ## xopt => \%xmlRpcOpts, ##-- options for RPC::XML::Server sub-object (for XML-RPC handlers; default: {no_http=>1}) | ||
| 49 | ## ## | ||
| 50 | ## ##-- (inherited from DTA::CAB::Server:HTTP): caching & status | ||
| 51 | ## cacheSize => $nelts, ##-- maximum number of responses to cache (default=1024; undef for no cache) | ||
| 52 | ## cacheLimit => $nbytes, ##-- max number of content bytes for cached responses (default=undef: no limit) | ||
| 53 | ## cache => $lruCache, ##-- response cache: (key = $url, value = $response), a DTA::CAB::Cache::LRU object | ||
| 54 | ## nRequests => $nRequests, ##-- number of requests (after access control) | ||
| 55 | ## nCacheHits => $nCacheHits, ##-- number of cache hits | ||
| 56 | ## nErrors => $nErrors, ##-- number of client errors | ||
| 57 | ## ## | ||
| 58 | ## ##-- (inherited from DTA::CAB::Server:HTTP): security | ||
| 59 | ## allowUserOptions => $bool, ##-- allow user options? (default: true) | ||
| 60 | ## allow => \@allow_ip_regexes, ##-- allow queries from these clients (default=none) | ||
| 61 | ## deny => \@deny_ip_regexes, ##-- deny queries from these clients (default=none) | ||
| 62 | ## _allow => $allow_ip_regex, ##-- single allow regex (compiled by 'prepare()') | ||
| 63 | ## _deny => $deny_ip_regex, ##-- single deny regex (compiled by 'prepare()') | ||
| 64 | ## maxRequestSize => $bytes, ##-- maximum request content-length in bytes (default: undef//-1: no max) | ||
| 65 | ## bgConnectTimeout => $secs, ##-- timeout for detecting chrome-style "background connections": connected sockets with no data on them (0:none; default=1) | ||
| 66 | ## ## | ||
| 67 | ## ##-- (inherited from DTA::CAB::Server:HTTP): forking | ||
| 68 | ## forkOnGet => $bool, ##-- fork() handler for HTTP GET requests? (default=0) | ||
| 69 | ## forkOnPost => $bool, ##-- fork() handler for HTTP POST requests? (default=1) | ||
| 70 | ## forkMax => $n, ##-- maximum number of subprocess to spwan (default=4; 0~no limit) | ||
| 71 | ## children => \%pids, ##-- child PIDs | ||
| 72 | ## pid => $pid, ##-- PID of parent server process | ||
| 73 | ## ## | ||
| 74 | ## ##-- (inherited from DTA::CAB::Server:HTTP): logging | ||
| 75 | ## logRegisterPath => $level, ##-- log registration of path handlers at $level (default='info') | ||
| 76 | ## logAttempt => $level, ##-- log connection attempts at $level (default=undef: none) | ||
| 77 | ## logConnect => $level, ##-- log successful connections (client IP and requested path) at $level (default='debug') | ||
| 78 | ## logRquestData => $level, ##-- log full client request data at $level (default=undef: none) | ||
| 79 | ## logResponse => $level, ##-- log full client response at $level (default=undef: none) | ||
| 80 | ## logCache => $level, ##-- log cache hit data at $level (default=undef: none) | ||
| 81 | ## logClientError => $level, ##-- log errors to client at $level (default='debug') | ||
| 82 | ## logClose => $level, ##-- log close client connections (default=undef: none) | ||
| 83 | ## logReap => $level, ##-- log harvesting of child pids (default=undef: none) | ||
| 84 | ## logSpawn => $level, ##-- log spawning of child pids (default=undef: none) | ||
| 85 | ## ## | ||
| 86 | ## ##-- (inherited from DTA::CAB::Server) | ||
| 87 | ## as => \%analyzers, ##-- ($name=>$cab_analyzer_obj, ...) | ||
| 88 | ## aos => \%anlOptions, ##-- ($name=>\%analyzeOptions, ...) : %opts passed to $anl->analyzeXYZ($xyz,%opts) | ||
| 89 | ## } | ||
| 90 | ## | ||
| 91 | ## + path handlers are as for DTA::CAB::Server::HTTP | ||
| 92 | sub new { | ||
| 93 | my $that = shift; | ||
| 94 | return $that->SUPER::new( | ||
| 95 | ##-- underlying server | ||
| 96 | daemonArgs => { | ||
| 97 | Local => "/tmp/dta-cab.sock", | ||
| 98 | #Listen => SOMAXCONN, | ||
| 99 | }, | ||
| 100 | socketPerms => '0666', | ||
| 101 | socketUser => undef, | ||
| 102 | socketGroup => undef, | ||
| 103 | _socketPath => undef, | ||
| 104 | #_socketDirs => undef, | ||
| 105 | |||
| 106 | ##-- user args | ||
| 107 | @_ | ||
| 108 | ); | ||
| 109 | } | ||
| 110 | |||
| 111 | ## undef = $obj->initialize() | ||
| 112 | ## + called to initialize new objects after new() | ||
| 113 | |||
| 114 | ## undef = $obj->DESTROY() | ||
| 115 | ## + override unlinks any bound UNIX socket | ||
| 116 | sub DESTROY { | ||
| 117 | my $srv = shift; | ||
| 118 | |||
| 119 | ##-- only run this for the "real" parent server process | ||
| 120 | if ($$ == ($srv->{pid}//0)) { | ||
| 121 | ##-- terminate tcp-relay subprocess | ||
| 122 | kill('TERM'=>$srv->{relayPid}) if ($srv->{relayPid}); | ||
| 123 | |||
| 124 | ##-- destroy daemon (force-close socket) | ||
| 125 | delete($srv->{daemon}) if ($srv->{daemon}); | ||
| 126 | |||
| 127 | ##-- unlink socket if we got it | ||
| 128 | if ($srv->{_socketPath} && -e $srv->{_socketPath}) { | ||
| 129 | unlink($srv->{_socketPath}) | ||
| 130 | or warn("failed to unlink server socket $srv->{_socketPath}: $!"); | ||
| 131 | delete $srv->{_socketPath}; | ||
| 132 | } | ||
| 133 | |||
| 134 | ##-- remove auto-created directories (only if empty) | ||
| 135 | #foreach (reverse @{$srv->{_socketDirs}||[]}) { | ||
| 136 | # last if (!rmdir($_)); | ||
| 137 | #} | ||
| 138 | } | ||
| 139 | |||
| 140 | ##-- superclass destruction if available | ||
| 141 | $srv->SUPER::DESTROY() if ($srv->can('SUPER::DESTROY')); | ||
| 142 | } | ||
| 143 | |||
| 144 | ##============================================================================== | ||
| 145 | ## Methods: HTTP server API (abstractions for HTTP::UNIX) | ||
| 146 | |||
| 147 | ##-------------------------------------------------------------- | ||
| 148 | ## $str = $srv->socketLabel() | ||
| 149 | ## + returns symbolic label for bound socket address | ||
| 150 | sub socketLabel { | ||
| 151 | my $srv = shift; | ||
| 152 | return $srv->{daemonArgs}{Local}; | ||
| 153 | } | ||
| 154 | |||
| 155 | ##-------------------------------------------------------------- | ||
| 156 | ## $str = $srv->daemonLabel() | ||
| 157 | ## + returns symbolic label for running daemon | ||
| 158 | sub daemonLabel { | ||
| 159 | my $srv = shift; | ||
| 160 | return $srv->{daemon}->hostpath; | ||
| 161 | } | ||
| 162 | |||
| 163 | ##-------------------------------------------------------------- | ||
| 164 | ## $bool = $srv->canBindSocket() | ||
| 165 | ## + returns true iff socket can be bound; should set $! on error | ||
| 166 | sub canBindSocket { | ||
| 167 | my $srv = shift; | ||
| 168 | my $dargs = $srv->{daemonArgs} || {}; | ||
| 169 | my $sockpath = $dargs->{Local} | ||
| 170 | or $srv->logconfess("canBindSocket(): no socket path defined"); | ||
| 171 | $srv->ensureSocketDir($sockpath) | ||
| 172 | or $srv->logconfess("canBindSocket(): failed to create socket directory for $sockpath: $!"); | ||
| 173 | my $sock = IO::Socket::UNIX->new(%$dargs,Listen=>1); | ||
| 174 | |||
| 175 | if (!$sock) { | ||
| 176 | ##-- first bind attempt failed: check whether there's a process behind it by trying to connect | ||
| 177 | $srv->logwarn("WARNING: socket path $sockpath already exists; trying to recover"); | ||
| 178 | if (-w $sockpath && !IO::Socket::UNIX->new(Peer=>$sockpath)) { | ||
| 179 | $srv->logwarn("WARNING: client connection to $sockpath failed; force-removing"); | ||
| 180 | if (!unlink($sockpath)) { | ||
| 181 | $srv->logwarn("WARNING: failed to unlink existing socket path $sockpath"); | ||
| 182 | return 0; | ||
| 183 | } | ||
| 184 | $sock = IO::Socket::UNIX->new(%$dargs,Listen=>1); | ||
| 185 | } | ||
| 186 | if (!$sock) { | ||
| 187 | ##-- recovery failed | ||
| 188 | $srv->logwarn("WARNING: cannot recycle socket path $sockpath (is another process listening on it?)"); | ||
| 189 | return 0; | ||
| 190 | } | ||
| 191 | } | ||
| 192 | |||
| 193 | ##-- cleanup | ||
| 194 | undef $sock; | ||
| 195 | unlink($sockpath); | ||
| 196 | |||
| 197 | return 1; | ||
| 198 | } | ||
| 199 | |||
| 200 | ##-------------------------------------------------------------- | ||
| 201 | ## $class = $srv->daemonClass() | ||
| 202 | ## + get HTTP::Daemon class | ||
| 203 | sub daemonClass { | ||
| 204 | return 'HTTP::Daemon::UNIX'; | ||
| 205 | } | ||
| 206 | |||
| 207 | ##-------------------------------------------------------------- | ||
| 208 | ## $class_or_undef = $srv->clientClass() | ||
| 209 | ## + get class for client connections | ||
| 210 | sub clientClass { | ||
| 211 | return 'DTA::CAB::Server::HTTP::UNIX::ClientConn'; | ||
| 212 | } | ||
| 213 | |||
| 214 | ##-------------------------------------------------------------- | ||
| 215 | ## $addr_or_false = $srv->relayAddr() | ||
| 216 | ## + new in Server::HTTP::UNIX | ||
| 217 | sub relayAddr { return $_[0]{relayAddr} || $_[0]{daemonArgs}{LocalAddr}; } | ||
| 218 | |||
| 219 | ##-------------------------------------------------------------- | ||
| 220 | ## $port_or_false = $srv->relayPort() | ||
| 221 | ## + new in Server::HTTP::UNIX | ||
| 222 | sub relayPort { return $_[0]{relayPort} || $_[0]{daemonArgs}{LocalPort}; } | ||
| 223 | |||
| 224 | ##-------------------------------------------------------------- | ||
| 225 | ## $label_or_false = $srv->relayLabel() | ||
| 226 | ## + new in Server::HTTP::UNIX | ||
| 227 | sub relayLabel { | ||
| 228 | my ($addr,$port) = ($_[0]->relayAddr,$_[0]->relayPort); | ||
| 229 | return undef if (!$addr && !$port); ##-- no relay required | ||
| 230 | return ($addr||'0.0.0.0').":".$port; | ||
| 231 | } | ||
| 232 | |||
| 233 | ##============================================================================== | ||
| 234 | ## Methods: Generic Server API: mostly inherited | ||
| 235 | ##============================================================================== | ||
| 236 | |||
| 237 | ##-------------------------------------------------------------- | ||
| 238 | ## $bool = $srv->ensureSocketDir() | ||
| 239 | ## $bool = $srv->ensureSocketDir($socketPath) | ||
| 240 | ## + ensures that directory of $socketPath exists | ||
| 241 | ## + sets $srv->{_socketDirs} if any directories are created | ||
| 242 | sub ensureSocketDir { | ||
| 243 | my ($srv,$sockpath) = @_; | ||
| 244 | $sockpath ||= ($srv->{_socketPath} | ||
| 245 | || ($srv->{daemon} ? $srv->{daemon}->hostpath : undef) | ||
| 246 | || $srv->{daemonArgs}{Local}); | ||
| 247 | $srv->logconfess("ensureSocketDir(): no socket path defined") | ||
| 248 | if (!$sockpath); | ||
| 249 | |||
| 250 | my $sockdir = dirname($sockpath); | ||
| 251 | if (!-d $sockdir) { | ||
| 252 | my @created = make_path($sockdir) | ||
| 253 | or $srv->logconfess("ensureSocketDir(): failed to create socket directory '$sockdir': $!"); | ||
| 254 | $srv->{_socketDirs} = \@created; | ||
| 255 | } | ||
| 256 | |||
| 257 | return 1; | ||
| 258 | } | ||
| 259 | |||
| 260 | ##-------------------------------------------------------------- | ||
| 261 | ## $rc = $srv->prepareLocal() | ||
| 262 | ## + subclass-local initialization | ||
| 263 | sub prepareLocal { | ||
| 264 | my $srv = shift; | ||
| 265 | |||
| 266 | ##-- ensure socket path directory | ||
| 267 | my $sockpath = $srv->{daemonArgs}{Local} | ||
| 268 | or $srv->logconfess("prepareLocal(): no socket path defined in {daemonArgs}{Local}"); | ||
| 269 | $srv->ensureSocketDir($sockpath) | ||
| 270 | or $srv->logconfess("prepareLocal(): failed to create directory for socket $sockpath: $!"); | ||
| 271 | |||
| 272 | ##-- Server::HTTP initialization | ||
| 273 | my $rc = $srv->SUPER::prepareLocal(@_); | ||
| 274 | return $rc if (!$rc); | ||
| 275 | $srv->{daemon}->listen( $srv->{daemonArgs}{Listen}||SOMAXCONN ); ##-- workaround for missing option pass-through HTTP::Daemon::UNIX v0.06 | ||
| 276 | |||
| 277 | ##-- get socket path | ||
| 278 | $sockpath = $srv->{_socketPath} = $srv->{daemon}->hostpath() | ||
| 279 | or $srv->logconfess("prepareLocal(): daemon returned bad socket path"); | ||
| 280 | |||
| 281 | ##-- setup socket ownership | ||
| 282 | my $sockuid = (($srv->{socketUser}//'') =~ /^[0-9]+$/ | ||
| 283 | ? $srv->{socketUser} | ||
| 284 | : getpwnam($srv->{socketUser}//'')); | ||
| 285 | my $sockgid = (($srv->{socketGroup}//'') =~ /^[0-9]+$/ | ||
| 286 | ? $srv->{socketGroup} | ||
| 287 | : getgrnam($srv->{socketGroup}//'')); | ||
| 288 | if (defined($sockuid) || defined($sockgid)) { | ||
| 289 | $sockuid //= $>; | ||
| 290 | $sockgid //= $); | ||
| 291 | $srv->vlog('info', "setting socket ownership (".scalar(getpwuid $sockuid).".".scalar(getgrgid $sockgid).") on $sockpath"); | ||
| 292 | chown($sockuid, $sockgid, $sockpath) | ||
| 293 | or $srv->logconfess("prepareLocal(): failed to set ownership for socket '$sockpath': $!"); | ||
| 294 | |||
| 295 | foreach my $dir (reverse @{$srv->{_socketDirs}||[]}) { | ||
| 296 | $srv->vlog('info', "setting directory ownership (".scalar(getpwuid $sockuid).".".scalar(getgrgid $sockgid).") on $dir"); | ||
| 297 | chown($sockuid, $sockgid, $dir) | ||
| 298 | or $srv->logconfess("prepareLocal(): failed to set ownership for directory '$dir': $!"); | ||
| 299 | } | ||
| 300 | } | ||
| 301 | |||
| 302 | ##-- setup socket permissions | ||
| 303 | if ( ($srv->{socketPerms}//'') ne '' ) { | ||
| 304 | my $sockperms = oct($srv->{socketPerms}); | ||
| 305 | $srv->vlog('info', sprintf("setting socket permissions (0%03o) on %s", $sockperms, $sockpath)); | ||
| 306 | chmod($sockperms, $sockpath) | ||
| 307 | or $srv->logconfess("prepareLocal(): failed to set permissions for socket '$sockpath': $!"); | ||
| 308 | foreach my $dir (reverse @{$srv->{_socketDirs}||[]}) { | ||
| 309 | $srv->vlog('info', sprintf("setting directory permissions (0%03o) on %s", ($sockperms|0111), $dir)); | ||
| 310 | chmod(($sockperms|0111), $dir) | ||
| 311 | or $srv->logconfess("prepareLocal(): failed to set permissions for directory '$dir': $!"); | ||
| 312 | } | ||
| 313 | } | ||
| 314 | |||
| 315 | ##-- setup TCP relay subprocess | ||
| 316 | $rc &&= $srv->prepareRelay(@_); | ||
| 317 | |||
| 318 | ##-- ok | ||
| 319 | return $rc; | ||
| 320 | } | ||
| 321 | |||
| 322 | ##-------------------------------------------------------------- | ||
| 323 | ## $bool = $srv->prepareRelay() | ||
| 324 | ## + sets up TCP relay subprocess | ||
| 325 | ## + returns -1 if relay process couldn't be started | ||
| 326 | sub prepareRelay { | ||
| 327 | my $srv = shift; | ||
| 328 | my $addr = $srv->relayAddr; | ||
| 329 | my $port = $srv->relayPort; | ||
| 330 | return 1 if (!$addr && !$port); ##-- no relay required | ||
| 331 | |||
| 332 | my $sockpath = $srv->{_socketPath}; | ||
| 333 | $addr ||= '0.0.0.0'; | ||
| 334 | @$srv{qw(relayAddr relayPort)} = ($addr,$port); | ||
| 335 | |||
| 336 | ##-- check whether relay address is already bound | ||
| 337 | if (!$srv->SUPER::canBindSocket({LocalAddr=>($srv->relayAddr||'0.0.0.0'), LocalPort=>$srv->relayPort})) { | ||
| 338 | $srv->logwarn("WARNING: cannot bind TCP socket relay on ${addr}:${port} (is there a stale relay still running?): $!"); | ||
| 339 | return -1; | ||
| 340 | } | ||
| 341 | |||
| 342 | $srv->vlog('trace',"starting TCP socket relay on ${addr}:${port}"); | ||
| 343 | $SIG{CHLD} ||= $srv->reaper(); | ||
| 344 | |||
| 345 | ##-- set main server process as group leader (kill whole process group with `pkill -g $SERVER_PID`) | ||
| 346 | POSIX::setpgid(0,0); | ||
| 347 | my $pgid = POSIX::getpgrp(); | ||
| 348 | |||
| 349 | if ( ($srv->{relayPid}=fork()) ) { | ||
| 350 | ##-- parent | ||
| 351 | $srv->vlog('info', "started TCP socket relay process for ${addr}:${port} on pid=$srv->{relayPid}"); | ||
| 352 | } else { | ||
| 353 | ##-- child (relay) | ||
| 354 | |||
| 355 | ##-- cleanup: close file desriptors | ||
| 356 | POSIX::close($_) foreach (3..1024); | ||
| 357 | |||
| 358 | ##-- join main server's process group | ||
| 359 | POSIX::setpgid($$, $pgid); | ||
| 360 | |||
| 361 | ##-- cleanup: environment | ||
| 362 | #delete @ENV{grep {$_ !~ /^(?:PATH|PERL|LANG|L[CD]_)/} keys %ENV}; | ||
| 363 | |||
| 364 | ##-- get relay command | ||
| 365 | my $cmd = ($srv->{relayCmd} | ||
| 366 | || [ | ||
| 367 | #qw(env -i), ##-- be paranoid | ||
| 368 | #qw(sockrelay.perl -syslog), "-label=dta-cab-relay/$port", | ||
| 369 | qw(socat -d -ly), | ||
| 370 | ## | ||
| 371 | #"-lpdta-cab-relay/$port", ##-- doesn't set environment varaibles | ||
| 372 | "-lpdta_cab_relay", ##-- environment variable prefix: DTA_CAB_RELAY_PEERADDR, ... | ||
| 373 | ## | ||
| 374 | "TCP-LISTEN:${port},bind=${addr},backlog=".IO::Socket->SOMAXCONN.",reuseaddr,fork", | ||
| 375 | ## | ||
| 376 | #"UNIX-CLIENT:$sockpath", | ||
| 377 | qq{EXEC:socat -d -ly - 'UNIX-CLIENT:$sockpath'}, ##-- use EXEC:socat idiom to populate socat environment variables (SOCAT_PEERADDR,SOCAT_PEERPORT) | ||
| 378 | ]); | ||
| 379 | |||
| 380 | $srv->vlog('trace', "RELAY: ", join(' ', @$cmd)); | ||
| 381 | exec(@$cmd) | ||
| 382 | or $srv->logconfess("prepareLocal(): failed to start TCP socket relay: $!"); | ||
| 383 | } | ||
| 384 | |||
| 385 | return 1; ##-- never reached | ||
| 386 | } | ||
| 387 | |||
| 388 | |||
| 389 | ##============================================================================== | ||
| 390 | ## Methods: Local: spawn and reap | ||
| 391 | |||
| 392 | ## \&reaper = $srv->reaper() | ||
| 393 | ## + zombie-harvesting code; installed to local %SIG | ||
| 394 | sub reaper { | ||
| 395 | my $srv = shift; | ||
| 396 | return sub { | ||
| 397 | my ($child); | ||
| 398 | while (($child = waitpid(-1,WNOHANG)) > 0) { | ||
| 399 | |||
| 400 | ##-- check whether required subprocess bailed on us | ||
| 401 | if ($srv->{relayPid} && $child == $srv->{relayPid}) { | ||
| 402 | delete $srv->{relayPid}; | ||
| 403 | $srv->logdie("TCP relay process ($child) exited with status ".($?>>8)); | ||
| 404 | } | ||
| 405 | |||
| 406 | ##-- normal case: handle client-level forks (e.g. for POST) | ||
| 407 | $srv->vlog($srv->{logReap},"reaped subprocess pid=$child, status=".($?>>8)); | ||
| 408 | delete $srv->{children}{$child}; | ||
| 409 | } | ||
| 410 | |||
| 411 | #$SIG{CHLD}=$srv->reaper() if ($srv->{installReaper}); ##-- re-install reaper for SysV | ||
| 412 | }; | ||
| 413 | } | ||
| 414 | |||
| 415 | |||
| 416 | |||
| 417 | ##============================================================================== | ||
| 418 | ## Methods: Local: Path Handlers: inherited | ||
| 419 | |||
| 420 | ##============================================================================== | ||
| 421 | ## Methods: Local: Access Control: inherited | ||
| 422 | |||
| 423 | ##====================================================================== | ||
| 424 | ## Methods: Local: error handling: inherited | ||
| 425 | |||
| 426 | ##============================================================================== | ||
| 427 | ## PACKAGE: DTA::CAB::Server::HTTP::UNIX::ClientConn | ||
| 428 | package DTA::CAB::Server::HTTP::UNIX::ClientConn; | ||
| 429 | use File::Basename qw(basename); | ||
| 430 | use DTA::CAB::Utils qw(:proc); | ||
| 431 | our @ISA = qw(HTTP::Daemon::ClientConn); | ||
| 432 | |||
| 433 | ## ($pid,$uid,$gid) = $sock->peercred() | ||
| 434 | ## + gets peer credentials; returns (-1,-1,-1) on failure | ||
| 435 | sub peercred { | ||
| 436 | my $sock = shift; | ||
| 437 | if ($sock->can('SO_PEERCRED')) { | ||
| 438 | my $buf = $sock->sockopt($sock->SO_PEERCRED); | ||
| 439 | return unpack('lll',$buf); | ||
| 440 | } | ||
| 441 | return (-1,-1,-1); | ||
| 442 | } | ||
| 443 | |||
| 444 | ## \%env = $sock->peerenv() | ||
| 445 | ## \%env = $sock->peerenv($pid) | ||
| 446 | ## + gets environment variables for peer process, if possible | ||
| 447 | ## + uses cached value in ${*sock}{peerenv} if present | ||
| 448 | ## + returns undef on failure | ||
| 449 | sub peerenv { | ||
| 450 | my ($sock,$pid) = @_; | ||
| 451 | return ${*$sock}{'peerenv'} if (${*$sock}{'peerenv'}); | ||
| 452 | ($pid) = $sock->peercred if (!$pid); | ||
| 453 | my ($fh,%env); | ||
| 454 | if (open($fh,"</proc/$pid/environ")) { | ||
| 455 | local $/ = "\0"; | ||
| 456 | my ($key,$val); | ||
| 457 | while (defined($_=<$fh>)) { | ||
| 458 | chomp($_); | ||
| 459 | ($key,$val) = split(/=/,$_,2); | ||
| 460 | $env{$key} = $val; | ||
| 461 | } | ||
| 462 | close($fh); | ||
| 463 | } | ||
| 464 | |||
| 465 | ##-- debug | ||
| 466 | #print STDERR "PEERENV($sock): $_=$env{$_}\n" foreach (sort keys %env); | ||
| 467 | |||
| 468 | ${*$sock}{'peerenv'} = \%env; | ||
| 469 | } | ||
| 470 | |||
| 471 | ## $str = $sock->peerstr() | ||
| 472 | ## $str = $sock->peerstr($uid,$gid,$pid) | ||
| 473 | ## + returns stringified unix peer credentials: "${USER}.${GROUP}[${PID}]" | ||
| 474 | sub peerstr { | ||
| 475 | my ($sock,$pid,$uid,$gid) = @_; | ||
| 476 | ($pid,$uid,$gid) = $sock->peercred() if (@_ < 4); | ||
| 477 | return ( | ||
| 478 | (defined($uid) ? (getpwuid($uid)//'?') : '?') | ||
| 479 | .'.' | ||
| 480 | .(defined($gid) ? (getgrgid($gid)//'?') : '?') | ||
| 481 | .':' | ||
| 482 | .(defined($pid) ? (basename(pid_cmd($pid)//'?')."[$pid]") : '?[?]') | ||
| 483 | ); | ||
| 484 | } | ||
| 485 | |||
| 486 | ## $host = peerhost() | ||
| 487 | ## + for relayed connections, gets underlying TCP peer via socat environment | ||
| 488 | ## + for unix connections, returns UNIX credentials as as for peerstr() | ||
| 489 | sub peerhost { | ||
| 490 | my $sock = shift; | ||
| 491 | |||
| 492 | ##-- get UNIX socket credentials | ||
| 493 | my ($pid,$uid,$gid) = $sock->peercred(); | ||
| 494 | if (defined($pid) && basename(pid_cmd($pid)//'?') eq 'socat') { | ||
| 495 | ##-- get socat environment variable if applicable | ||
| 496 | my $env = $sock->peerenv(); | ||
| 497 | return $env->{DTA_CAB_RELAY_PEERADDR} if ($env && $env->{DTA_CAB_RELAY_PEERADDR}); | ||
| 498 | } | ||
| 499 | |||
| 500 | ##-- return UNIX socket credentials | ||
| 501 | return $sock->peerstr($pid,$uid,$gid); | ||
| 502 | } | ||
| 503 | |||
| 504 | ## $port = peerport() | ||
| 505 | ## + for relayed connections, gets underlying TCP port via socat environment | ||
| 506 | ## + for unix connections, returns socket path | ||
| 507 | sub peerport { | ||
| 508 | my $sock = shift; | ||
| 509 | |||
| 510 | ##-- get UNIX socket credentials | ||
| 511 | my ($pid,$uid,$gid) = $sock->peercred(); | ||
| 512 | if (defined($pid) && basename(pid_cmd($pid)//'?') eq 'socat') { | ||
| 513 | ##-- get socat environment variable if applicable | ||
| 514 | my $env = $sock->peerenv(); | ||
| 515 | return $env->{DTA_CAB_RELAY_PEERPORT} if ($env && $env->{DTA_CAB_RELAY_PEERPORT}); | ||
| 516 | } | ||
| 517 | |||
| 518 | ##-- return UNIX socket path | ||
| 519 | return $sock->peerpath(); | ||
| 520 | } | ||
| 521 | |||
| 522 | |||
| 523 | |||
| 524 | 1; ##-- be happy | ||
| 525 | |||
| 526 | __END__ |