| File: | blib/lib/Class/Shared/Backend.pm |
| Coverage: | 90.5% |
| line | stmt | bran | path | cond | sub | pod | time | code |
|---|---|---|---|---|---|---|---|---|
| 1 | package Class::Shared::Backend; | |||||||
| 2 | ||||||||
| 3 | 68 68 68 | 233198 59 892 | use strict; | |||||
| 4 | 68 68 68 | 100 52 1218 | use warnings; | |||||
| 5 | ||||||||
| 6 | 68 68 68 | 123 38 650 | use Carp (); | |||||
| 7 | 68 68 68 | 86 43 4653 | use Fcntl qw(:flock F_SETFD FD_CLOEXEC O_RDWR O_WRONLY O_CREAT O_EXCL); | |||||
| 8 | 68 68 68 | 160 53 532 | use File::Spec (); | |||||
| 9 | 68 68 68 | 2953 67654 307 | use IO::Socket::INET; | |||||
| 10 | 68 68 68 | 14759 41 231 | use IO::Socket::UNIX; | |||||
| 11 | 68 68 68 | 15459 54 521 | use Scalar::Util (); | |||||
| 12 | 68 68 68 | 85 42 1629 | use Socket qw(SOCK_STREAM); | |||||
| 13 | 68 68 68 | 858 4788 333 | use Storable (); | |||||
| 14 | 68 68 68 | 2734 6415 468 | use Time::HiRes (); | |||||
| 15 | ||||||||
| 16 | 68 68 68 | 29141 3892535 913 | use Log::Abstraction (); | |||||
| 17 | 68 68 68 | 18942 565421 800 | use Object::Configure (); | |||||
| 18 | 68 68 68 | 152 46 408 | use Params::Get (); | |||||
| 19 | 68 68 68 | 104 62 341 | use Params::Validate::Strict (); | |||||
| 20 | ||||||||
| 21 | 68 68 68 | 605 96 351 | use Class::Shared (); | |||||
| 22 | 68 68 68 | 4900 60 512 | use Class::Shared::Protocol (); | |||||
| 23 | ||||||||
| 24 | # version->declare here alone: this is VERSION_FROM, and with it MakeMaker | |||||||
| 25 | # writes 0.001.0 into META; a plain dotted string becomes v0.001.0 there. | |||||||
| 26 | 68 68 68 | 120 42 225 | use version; our $VERSION = version->declare('0.001.0'); | |||||
| 27 | ||||||||
| 28 | our $DEFAULT_MAX_CLIENTS = 128; | |||||||
| 29 | our $DEFAULT_MAX_OBJECTS = 4096; | |||||||
| 30 | ||||||||
| 31 | # How long a new backend waits, in seconds, for a lock that a backend which is | |||||||
| 32 | # shutting down still holds. | |||||||
| 33 | our $DEFAULT_START_TIMEOUT = 2; | |||||||
| 34 | ||||||||
| 35 | # The accept queue of the listening socket. | |||||||
| 36 | our $LISTEN_BACKLOG = 64; | |||||||
| 37 | ||||||||
| 38 | # The most one read takes from a client. A larger frame arrives over several | |||||||
| 39 | # turns of the loop and waits in that client's buffer. | |||||||
| 40 | our $READ_CHUNK = 65536; | |||||||
| 41 | ||||||||
| 42 | # While a TLS handshake is pending the loop wakes this often, in seconds, to | |||||||
| 43 | # expire the ones that have run out of time. | |||||||
| 44 | our $HANDSHAKE_POLL = 0.25; | |||||||
| 45 | ||||||||
| 46 | # How long a connection may spend on its TLS handshake. The handshake is done | |||||||
| 47 | # a little at a time from the select loop, so a peer that connects and then | |||||||
| 48 | # says nothing costs one connection slot for this long, not the whole backend. | |||||||
| 49 | our $HANDSHAKE_TIMEOUT = 5; | |||||||
| 50 | ||||||||
| 51 | # How much may be waiting to be written to one client before it is dropped. | |||||||
| 52 | # Replies are queued per connection and written from the loop as the socket | |||||||
| 53 | # takes them, so this is what stops a client that asks for an answer and then | |||||||
| 54 | # stops reading from holding that reply, and the memory for it, indefinitely. | |||||||
| 55 | # The default is one maximum-size frame, so no reply the protocol allows is | |||||||
| 56 | # refused for being large. | |||||||
| 57 | our $MAX_QUEUED = $Class::Shared::Protocol::MAX_FRAME + 4096; | |||||||
| 58 | ||||||||
| 59 | # max_queued bounds how much one client may have waiting; this bounds how long | |||||||
| 60 | # it may have it there. A stalled queue that the socket will not take is a | |||||||
| 61 | # client that has stopped reading, and holding its memory for ever is what the | |||||||
| 62 | # bound alone allows. The clock is fractional, so a slow reader that keeps | |||||||
| 63 | # taking bytes is not dropped early by the second hand. | |||||||
| 64 | our $WRITE_TIMEOUT = 30; | |||||||
| 65 | ||||||||
| 66 | # A request that has only partly arrived is held in memory until the rest | |||||||
| 67 | # does. max_queued_total bounds replies; these two bound requests. Without | |||||||
| 68 | # them every client could send nearly a whole maximum-size frame, stop, and | |||||||
| 69 | # leave the backend holding max_clients times that for as long as it liked. | |||||||
| 70 | our $MAX_BUFFERED_TOTAL = 4 * ($Class::Shared::Protocol::MAX_FRAME + 4096); | |||||||
| 71 | our $READ_TIMEOUT = 30; | |||||||
| 72 | ||||||||
| 73 | # A request no longer than this is thawed straight away. Each level of nesting | |||||||
| 74 | # takes at least one byte, and this many levels fit easily on any C stack; a | |||||||
| 75 | # longer request is first tried in a child process. | |||||||
| 76 | our $THAW_UNCHECKED = 4096; | |||||||
| 77 | ||||||||
| 78 | # The most seconds that trial may take. | |||||||
| 79 | our $THAW_TRIAL_TIMEOUT = 30; | |||||||
| 80 | ||||||||
| 81 | # The log is copied to LOG.1 and emptied when it passes this many bytes, so the | |||||||
| 82 | # two together are bounded however much a client makes the backend say. | |||||||
| 83 | our $MAX_LOG_SIZE = 10 * 1024 * 1024; | |||||||
| 84 | ||||||||
| 85 | # How long a greeted client may send nothing at all. 0, the default, is for | |||||||
| 86 | # ever: a client that holds an object and uses it rarely is the normal case. | |||||||
| 87 | our $IDLE_TIMEOUT = 0; | |||||||
| 88 | ||||||||
| 89 | # How long, in seconds, the listener is left alone after accept() failed for | |||||||
| 90 | # want of file descriptors or memory. | |||||||
| 91 | our $ACCEPT_PAUSE = 0.1; | |||||||
| 92 | ||||||||
| 93 | # How long one call to a target (a method, or its constructor) may run, in | |||||||
| 94 | # seconds. The backend runs one request at a time, so a call that does not | |||||||
| 95 | # return holds every client; this is what ends it. 0 means no limit. | |||||||
| 96 | our $CALL_TIMEOUT = 60; | |||||||
| 97 | ||||||||
| 98 | # What a connection is told when it asks for an object before naming a class. | |||||||
| 99 | our $NO_CLASS_ERROR = 'this connection named no class in its handshake'; | |||||||
| 100 | ||||||||
| 101 | # What each option to new() may be. The checks here are the ones that do not | |||||||
| 102 | # depend on another option; the rules that do ("a TCP listener needs a token") | |||||||
| 103 | # stay in new(), where they can explain themselves. An empty token or TLS file | |||||||
| 104 | # name is allowed on purpose, so that those rules, not a type error, are what the | |||||||
| 105 | # caller reads. A token is limited to printable ASCII because it is turned into | |||||||
| 106 | # an HMAC key as bytes (see "ENCODING" in the POD). | |||||||
| 107 | my %OPTION_SCHEMA = ( | |||||||
| 108 | socket => { type => 'string', optional => 1, min => 1 }, | |||||||
| 109 | dir => { type => 'string', optional => 1, min => 1 }, | |||||||
| 110 | host => { type => 'string', optional => 1, min => 1 }, | |||||||
| 111 | port => { type => 'integer', optional => 1, min => 1, max => 65535 }, | |||||||
| 112 | tls_cert => { type => 'string', optional => 1 }, | |||||||
| 113 | tls_key => { type => 'string', optional => 1 }, | |||||||
| 114 | tls_ca => { type => 'string', optional => 1 }, | |||||||
| 115 | token => { type => 'string', optional => 1, matches => qr/\A[\x20-\x7E]*\z/ }, | |||||||
| 116 | log => { type => 'string', optional => 1, min => 1 }, | |||||||
| 117 | daemonize => { type => 'boolean', optional => 1 }, | |||||||
| 118 | max_clients => { type => 'integer', optional => 1, min => 1 }, | |||||||
| 119 | max_objects => { type => 'integer', optional => 1, min => 1 }, | |||||||
| 120 | max_queued => { type => 'integer', optional => 1, min => 1 }, | |||||||
| 121 | max_queued_total => { type => 'integer', optional => 1, min => 1 }, | |||||||
| 122 | write_timeout => { type => 'number', optional => 1, min => 0 }, | |||||||
| 123 | handshake_timeout => { type => 'number', optional => 1, min => 0 }, | |||||||
| 124 | start_timeout => { type => 'number', optional => 1, min => 0 }, | |||||||
| 125 | call_timeout => { type => 'number', optional => 1, min => 0 }, | |||||||
| 126 | read_timeout => { type => 'number', optional => 1, min => 0 }, | |||||||
| 127 | max_buffered_total => { type => 'integer', optional => 1, min => 1 }, | |||||||
| 128 | idle_timeout => { type => 'number', optional => 1, min => 0 }, | |||||||
| 129 | max_log_size => { type => 'integer', optional => 1, min => 0 }, | |||||||
| 130 | ||||||||
| 131 | # Not options of the backend: they say where to look for site settings. | |||||||
| 132 | config_file => { type => 'string', optional => 1, min => 1 }, | |||||||
| 133 | config_dirs => { type => 'arrayref', optional => 1 }, | |||||||
| 134 | ); | |||||||
| 135 | ||||||||
| 136 | # The two entries above that only locate settings, and so are never kept. | |||||||
| 137 | my %LOCATES_SETTINGS = (config_file => 1, config_dirs => 1); | |||||||
| 138 | ||||||||
| 139 | # The options that are the backend's own. Worked out once, because the schema | |||||||
| 140 | # does not change: Premise 1: %OPTION_SCHEMA is fixed when the module loads. | |||||||
| 141 | # Premise 2: what is a backend option depends only on the schema. Conclusion: | |||||||
| 142 | # there is no reason to filter it again on every call to new(). | |||||||
| 143 | my @BACKEND_OPTIONS = grep { !$LOCATES_SETTINGS{$_} } sort keys %OPTION_SCHEMA; | |||||||
| 144 | ||||||||
| 145 | # A listener's TLS identity is these three files together. | |||||||
| 146 | my @TLS_FILES = qw(tls_cert tls_key tls_ca); | |||||||
| 147 | ||||||||
| 148 | # Every refusal from new() starts with this, so a caller can rely on it | |||||||
| 149 | # (bin/class-shared removes it before showing the message to a person). | |||||||
| 150 | my $REFUSAL_PREFIX = __PACKAGE__ . '->new: '; | |||||||
| 151 | ||||||||
| 152 | # The backend loads each class a client names, once, and holds many objects | |||||||
| 153 | # made from them: one per frontend. Clients talk to it over a unix socket or | |||||||
| 154 | # TCP. | |||||||
| 155 | sub new { | |||||||
| 156 | 551 | 3183798 | my $class = shift; | |||||
| 157 | ||||||||
| 158 | # new(%options) and new(\%options) are both fine, and so is new(). | |||||||
| 159 | 551 551 | 474 1283 | my %opt = %{ _options($class, Params::Get::get_params(undef, \@_)) }; | |||||
| 160 | ||||||||
| 161 | 438 | 810 | my ($host, $port, $socket) = @opt{qw(host port socket)}; | |||||
| 162 | ||||||||
| 163 | # Premise 1: _options leaves no undef value in %opt, so "defined" means "was | |||||||
| 164 | # given". Premise 2: an empty token or TLS file name is let through the | |||||||
| 165 | # schema on purpose, so "given" is not "set": a value is set when it is not | |||||||
| 166 | # empty. Conclusion: each of the three facts below is worked out once, and | |||||||
| 167 | # every rule after this reads it, where the rules used to repeat the test. | |||||||
| 168 | 438 | 969 | my $tcp = defined $host || defined $port; | |||||
| 169 | 438 | 934 | my $has_token = length($opt{token} // '') ? 1 : 0; | |||||
| 170 | 438 1314 | 426 1558 | my $tls_set = grep { length($opt{$_} // '') } @TLS_FILES; | |||||
| 171 | ||||||||
| 172 | 438 | 286 | my $control; | |||||
| 173 | ||||||||
| 174 | 438 | 415 | if ($tcp) { | |||||
| 175 | 100 | 206 | _refuse('a TCP listener needs both host and port') | |||||
| 176 | unless defined $host && defined $port; | |||||||
| 177 | ||||||||
| 178 | 82 | 92 | _refuse('use either socket or host/port, not both') | |||||
| 179 | if defined $socket; | |||||||
| 180 | ||||||||
| 181 | # A TCP port is reachable by anybody who can route to it, and thawing | |||||||
| 182 | # is running code, so refuse to be the listener that would deserialise | |||||||
| 183 | # whatever a stranger sends. | |||||||
| 184 | 73 | 127 | _refuse('a TCP listener needs a token: without one it would thaw whatever arrives') | |||||
| 185 | unless $has_token; | |||||||
| 186 | ||||||||
| 187 | # TLS is not a wrapper here but the listener itself: this certificate | |||||||
| 188 | # proves who the backend is, tls_ca decides which client certificates | |||||||
| 189 | # are welcome, and a client without one is never accepted. All three | |||||||
| 190 | # are needed, so the number that are set must be the number there are. | |||||||
| 191 | 54 | 75 | _refuse('a TCP listener needs tls_cert, tls_key and tls_ca: ' | |||||
| 192 | . 'without them the traffic would be readable to anyone who can route to it') | |||||||
| 193 | unless $tls_set == @TLS_FILES; | |||||||
| 194 | ||||||||
| 195 | # Premise: a TCP listener has no socket (refused above). Its lock, pid | |||||||
| 196 | # file and log still live in the directory a socket would have used. | |||||||
| 197 | 16 | 46 | $control = Class::Shared::socket_path($opt{dir}); | |||||
| 198 | } else { | |||||||
| 199 | # Premise: the guards above did not run, so there is no host or port. | |||||||
| 200 | # Conclusion: the socket is either the one given or the default one, and | |||||||
| 201 | # it is also the control path, so it is worked out once, here. | |||||||
| 202 | $socket = defined $socket | |||||||
| 203 | ? Class::Shared::check_socket_path($socket) | |||||||
| 204 | 338 | 950 | : Class::Shared::socket_path($opt{dir}); | |||||
| 205 | 329 | 298 | $control = $socket; | |||||
| 206 | ||||||||
| 207 | # The socket is mode 0600 in a directory only its owner can write to, | |||||||
| 208 | # so the kernel has already decided who may connect: a digest on every | |||||||
| 209 | # frame would buy nothing here and cost 32 bytes on each message. | |||||||
| 210 | 329 | 328 | _refuse("a unix socket needs no token: $Class::Shared::UNIX_TRUST_REASON") | |||||
| 211 | if $has_token; | |||||||
| 212 | ||||||||
| 213 | 317 | 312 | _refuse("a unix socket needs no TLS: $Class::Shared::UNIX_TRUST_REASON") | |||||
| 214 | if $tls_set; | |||||||
| 215 | } | |||||||
| 216 | ||||||||
| 217 | # What is used when an option is not given. Read here, each time, and not | |||||||
| 218 | # once when the module loads, because these are package variables that a | |||||||
| 219 | # program may set before it calls new(). Premise 1 makes "not given" the | |||||||
| 220 | # same as "not in %opt", so one merge replaces a test for each option; and | |||||||
| 221 | # because the schema never allows a zero here, the merge cannot differ from | |||||||
| 222 | # the "x || default" it replaces, except for a log that is called "0", which | |||||||
| 223 | # "||" wrongly treated as not given. | |||||||
| 224 | 324 | 1621 | my %set = ( | |||||
| 225 | max_clients => $DEFAULT_MAX_CLIENTS, | |||||||
| 226 | max_objects => $DEFAULT_MAX_OBJECTS, | |||||||
| 227 | max_queued => $MAX_QUEUED, | |||||||
| 228 | write_timeout => $WRITE_TIMEOUT, | |||||||
| 229 | handshake_timeout => $HANDSHAKE_TIMEOUT, | |||||||
| 230 | start_timeout => $DEFAULT_START_TIMEOUT, | |||||||
| 231 | call_timeout => $CALL_TIMEOUT, | |||||||
| 232 | read_timeout => $READ_TIMEOUT, | |||||||
| 233 | max_buffered_total => $MAX_BUFFERED_TOTAL, | |||||||
| 234 | idle_timeout => $IDLE_TIMEOUT, | |||||||
| 235 | max_log_size => $MAX_LOG_SIZE, | |||||||
| 236 | daemonize => 0, | |||||||
| 237 | log => $control . '.log', | |||||||
| 238 | %opt, | |||||||
| 239 | ); | |||||||
| 240 | ||||||||
| 241 | # Four times one client's bound by default: enough that a few clients may | |||||||
| 242 | # each be holding a maximum-size reply, small enough that a few hundred | |||||||
| 243 | # cannot each be holding one. | |||||||
| 244 | 324 | 844 | $set{max_queued_total} //= $set{max_queued} * 4; | |||||
| 245 | ||||||||
| 246 | my $self = bless { | |||||||
| 247 | classes => {}, | |||||||
| 248 | socket => $socket, | |||||||
| 249 | host => $host, | |||||||
| 250 | port => $port, | |||||||
| 251 | # An empty token is none: kept, it would sign frames with an empty key. | |||||||
| 252 | token => $has_token ? $opt{token} : undef, | |||||||
| 253 | tls_cert => $opt{tls_cert}, | |||||||
| 254 | tls_key => $opt{tls_key}, | |||||||
| 255 | tls_ca => $opt{tls_ca}, | |||||||
| 256 | dir_hint => $opt{dir}, | |||||||
| 257 | control => $control, | |||||||
| 258 | log => $set{log}, | |||||||
| 259 | ||||||||
| 260 | # The schema says a boolean is 0 or 1 once it has been checked, so | |||||||
| 261 | # nothing here has to turn "true" into 1. | |||||||
| 262 | daemonize => $set{daemonize}, | |||||||
| 263 | max_clients => $set{max_clients}, | |||||||
| 264 | max_objects => $set{max_objects}, | |||||||
| 265 | max_queued => $set{max_queued}, | |||||||
| 266 | max_queued_total => $set{max_queued_total}, | |||||||
| 267 | write_timeout => $set{write_timeout}, | |||||||
| 268 | handshake_timeout => $set{handshake_timeout}, | |||||||
| 269 | start_timeout => $set{start_timeout}, | |||||||
| 270 | call_timeout => $set{call_timeout}, | |||||||
| 271 | read_timeout => $set{read_timeout}, | |||||||
| 272 | max_buffered_total => $set{max_buffered_total}, | |||||||
| 273 | idle_timeout => $set{idle_timeout}, | |||||||
| 274 | max_log_size => $set{max_log_size}, | |||||||
| 275 | 324 | 3473 | objects => {}, | |||||
| 276 | clients => {}, | |||||||
| 277 | queued => 0, | |||||||
| 278 | next_id => 1, | |||||||
| 279 | next_serial => 1, | |||||||
| 280 | calls => 0, | |||||||
| 281 | constructed => 0, | |||||||
| 282 | started => time, | |||||||
| 283 | stop => 0, | |||||||
| 284 | cleaned => 0, | |||||||
| 285 | logger => undef, | |||||||
| 286 | logger_pid => undef, | |||||||
| 287 | listener => undef, | |||||||
| 288 | lock => undef, | |||||||
| 289 | owns_socket => 0, | |||||||
| 290 | owner_pid => undef, | |||||||
| 291 | address => undef, | |||||||
| 292 | }, $class; | |||||||
| 293 | ||||||||
| 294 | 324 | 1038 | return $self; | |||||
| 295 | } | |||||||
| 296 | ||||||||
| 297 | # Purpose: refuse the arguments of new() in this module's usual form. | |||||||
| 298 | # Entry: $why is the reason, without the prefix or a line break. | |||||||
| 299 | # Exit status: none: it dies. | |||||||
| 300 | # Side effects: none. | |||||||
| 301 | sub _refuse { | |||||||
| 302 | 115 | 9192 | my ($why) = @_; | |||||
| 303 | ||||||||
| 304 | 115 | 428 | die $REFUSAL_PREFIX . $why . "\n"; | |||||
| 305 | } | |||||||
| 306 | ||||||||
| 307 | # Purpose: work out the options for one backend from three places, in | |||||||
| 308 | # this order of importance: what the caller passed, then the | |||||||
| 309 | # environment (Class__Shared__Backend__NAME), then a config file | |||||||
| 310 | # (class-shared-backend.yml). The caller always wins, so a | |||||||
| 311 | # stray variable in the environment cannot override a token or a | |||||||
| 312 | # certificate that the program chose. | |||||||
| 313 | # Entry: $class is the class being built; $given is a hash reference | |||||||
| 314 | # of the caller's arguments, or undef if there were none. | |||||||
| 315 | # Exit status: a hash reference of valid options (only those that were set); | |||||||
| 316 | # dies with "Class::Shared::Backend->new: ..." if an argument | |||||||
| 317 | # or a configured value is unknown or has the wrong type. | |||||||
| 318 | # Side effects: reads config files and the environment. | |||||||
| 319 | sub _options { | |||||||
| 320 | 580 | 12851 | my ($class, $given) = @_; | |||||
| 321 | ||||||||
| 322 | # What the caller passed is checked first, so that a misspelt name is | |||||||
| 323 | # reported as theirs, and not lost among the site settings. | |||||||
| 324 | 580 | 1067 | my $explicit = _validate($given || {}, 'an argument'); | |||||
| 325 | ||||||||
| 326 | # undef means "not given", which is how bin/class-shared passes an option | |||||||
| 327 | # it has nothing for; it must not hide a site setting. | |||||||
| 328 | 470 470 1370 470 | 430 380 1017 443 | delete @{$explicit}{ grep { !defined $explicit->{$_} } keys %{$explicit} }; | |||||
| 329 | ||||||||
| 330 | # Object::Configure gives the caller's values the LOWEST priority and adds | |||||||
| 331 | # keys of its own (a logger, the config path). So it is given only the | |||||||
| 332 | # place to look, and only the options this class knows are taken back. | |||||||
| 333 | # The backend writes its own log, so no logger is wanted from it. The two | |||||||
| 334 | # locators are taken out of $explicit as they are passed on, so what is left | |||||||
| 335 | # in it is exactly what is kept. | |||||||
| 336 | 8 | 12 | my %locate = map { $_ => delete $explicit->{$_} } | |||||
| 337 | 470 940 | 567 761 | grep { exists $explicit->{$_} } keys %LOCATES_SETTINGS; | |||||
| 338 | ||||||||
| 339 | 470 | 1366 | my $configured = Object::Configure::configure($class, { logger => 'NULL', %locate }); | |||||
| 340 | ||||||||
| 341 | 43 | 58 | my %site = map { $_ => $configured->{$_} } | |||||
| 342 | 470 10340 | 444237 5445 | grep { defined $configured->{$_} } @BACKEND_OPTIONS; | |||||
| 343 | ||||||||
| 344 | # Values from a file or the environment arrive as text, so they are checked | |||||||
| 345 | # (and turned into numbers) in the same way as the caller's. Premise: every | |||||||
| 346 | # entry in the schema is optional. Premise: nothing was configured. | |||||||
| 347 | # Conclusion: there is nothing to check and nothing to turn into a number, | |||||||
| 348 | # so the checker is not called for an empty set. | |||||||
| 349 | 470 | 609 | my $site = %site ? _validate(\%site, 'a configured value') : {}; | |||||
| 350 | ||||||||
| 351 | 459 459 459 | 326 358 1531 | return { %{$site}, %{$explicit} }; | |||||
| 352 | } | |||||||
| 353 | ||||||||
| 354 | # Purpose: check one set of options against %OPTION_SCHEMA. | |||||||
| 355 | # Entry: $input is a hash reference; $source says where it came from, for | |||||||
| 356 | # the message ("an argument", "a configured value"). | |||||||
| 357 | # Exit status: the validated hash reference (numbers and booleans coerced); | |||||||
| 358 | # dies with a message in this module's usual form if not. | |||||||
| 359 | # Side effects: none. | |||||||
| 360 | sub _validate { | |||||||
| 361 | # Evals below must not leave their errors in the caller's $@. | |||||||
| 362 | 641 | 14626 | local $@; | |||||
| 363 | 641 | 670 | my ($input, $source) = @_; | |||||
| 364 | ||||||||
| 365 | 641 | 483 | my $valid = eval { | |||||
| 366 | 641 | 1329 | Params::Validate::Strict::validate_strict( | |||||
| 367 | schema => \%OPTION_SCHEMA, | |||||||
| 368 | input => $input, | |||||||
| 369 | ); | |||||||
| 370 | }; | |||||||
| 371 | ||||||||
| 372 | 641 | 330284 | if (!$valid) { | |||||
| 373 | # The validator names its own source line and ours; neither helps a | |||||||
| 374 | # person, who needs to know which option and what was wrong with it. | |||||||
| 375 | 138 | 136 | my $why = $@ || 'invalid options'; | |||||
| 376 | 138 | 285 | $why =~ s/\AParams::Validate::Strict line \d+: validate_strict: //; | |||||
| 377 | 138 | 320 | $why =~ s/ at \S+ line \d+\.?\s*\z//; | |||||
| 378 | 138 | 223 | $why =~ s/\s+\z//; | |||||
| 379 | ||||||||
| 380 | 138 | 383 | die "Class::Shared::Backend->new: $source is not valid: $why\n"; | |||||
| 381 | } | |||||||
| 382 | ||||||||
| 383 | 503 | 551 | return $valid; | |||||
| 384 | } | |||||||
| 385 | ||||||||
| 386 | sub run { | |||||||
| 387 | 68 | 1780 | my $self = shift; | |||||
| 388 | ||||||||
| 389 | # A backend object is one life. After a normal stop the socket, pid file | |||||||
| 390 | # and lock have already been given back, so running again would bind a new | |||||||
| 391 | # socket that the finished cleanup would never remove. | |||||||
| 392 | 68 | 204 | die "this backend has already run and stopped\n" if $self->{cleaned}; | |||||
| 393 | ||||||||
| 394 | 68 | 156 | $self->_daemonize if $self->{daemonize}; | |||||
| 395 | ||||||||
| 396 | 62 62 13 | 89 223 37 | my $started = eval { $self->_setup; 1 }; | |||||
| 397 | 62 | 327 | if (!$started) { | |||||
| 398 | 49 | 125 | my $error = $@ || 'unknown error'; | |||||
| 399 | 49 | 383 | $self->_log("fatal: $error", 'error'); | |||||
| 400 | ||||||||
| 401 | # Give back whatever was taken before the failure, so that another | |||||||
| 402 | # start can succeed while this object is still alive. | |||||||
| 403 | 49 | 291 | $self->_cleanup; | |||||
| 404 | 49 49 | 98 63 | @{$self}{qw(cleaned owns_socket)} = (0, 0); | |||||
| 405 | ||||||||
| 406 | 49 | 240 | die $error unless $self->{daemonize}; | |||||
| 407 | 3 | 117 | exit 1; | |||||
| 408 | } | |||||||
| 409 | ||||||||
| 410 | $self->_log("serving on $self->{address} (pid $$" | |||||||
| 411 | . ($self->{token} ? ', token required' : '') | |||||||
| 412 | 13 | 89 | . (defined $self->{host} ? ', TLS with client certificates' : '') . ')'); | |||||
| 413 | ||||||||
| 414 | 13 | 41 | $self->_loop; | |||||
| 415 | 13 | 24 | $self->_cleanup; | |||||
| 416 | ||||||||
| 417 | 13 | 27 | $self->_log('stopped'); | |||||
| 418 | ||||||||
| 419 | 13 | 28 | return 0; | |||||
| 420 | } | |||||||
| 421 | ||||||||
| 422 | # Remove the socket only if this object bound it. A backend that failed to | |||||||
| 423 | # start because another one is already serving never owned the path, and | |||||||
| 424 | # unlinking it here would leave the live backend running but unreachable. | |||||||
| 425 | sub DESTROY { | |||||||
| 426 | 329 | 3743637 | my $self = shift; | |||||
| 427 | 329 | 674 | return if $self->{cleaned}; | |||||
| 428 | ||||||||
| 429 | # A target that forks leaves a copy of this object in the child, and the | |||||||
| 430 | # socket is not the child's to remove. | |||||||
| 431 | 313 | 561 | return if defined $self->{owner_pid} && $self->{owner_pid} != $$; | |||||
| 432 | ||||||||
| 433 | 313 | 301 | $self->{cleaned} = 1; | |||||
| 434 | ||||||||
| 435 | # A destructor must not disturb the $@ or $! of the code that was running | |||||||
| 436 | # when the object went out of scope. | |||||||
| 437 | 313 | 1957 | local ($@, $!); | |||||
| 438 | ||||||||
| 439 | 313 | 531 | if ($self->{owns_socket} && -e $self->{socket}) { | |||||
| 440 | unlink($self->{socket}) | |||||||
| 441 | 4 | 110 | or Carp::carp("Class::Shared::Backend: cannot remove $self->{socket}: $!"); | |||||
| 442 | } | |||||||
| 443 | ||||||||
| 444 | 313 | 4676 | return; | |||||
| 445 | } | |||||||
| 446 | ||||||||
| 447 | # The class is the client's choice, so it is loaded when a client asks for it | |||||||
| 448 | # rather than at startup: require brings the file in, and import is called | |||||||
| 449 | # because a module with exports is normally used with use, not require. Each | |||||||
| 450 | # class is loaded once however many clients want it. | |||||||
| 451 | sub _load_class { | |||||||
| 452 | 33 | 12117 | my ($self, $class) = @_; | |||||
| 453 | ||||||||
| 454 | 33 | 64 | return 1 if $self->{classes}{$class}; | |||||
| 455 | ||||||||
| 456 | 19 | 14 | my $file = $class; | |||||
| 457 | 19 | 245 | $file =~ s{::}{/}g; | |||||
| 458 | 19 | 17 | $file .= '.pm'; | |||||
| 459 | ||||||||
| 460 | 19 19 12 | 14 3541 597 | eval { require $file; 1 } | |||||
| 461 | or return (0, "cannot load $class: " . ($@ || 'unknown error')); | |||||||
| 462 | ||||||||
| 463 | 12 | 67 | if ($class->can('import')) { | |||||
| 464 | 12 12 10 | 10 48 14 | eval { $class->import; 1 } | |||||
| 465 | or return (0, "cannot import $class: " . ($@ || 'unknown error')); | |||||||
| 466 | } | |||||||
| 467 | ||||||||
| 468 | 10 | 16 | $self->{classes}{$class} = 1; | |||||
| 469 | ||||||||
| 470 | 10 | 21 | return (1); | |||||
| 471 | } | |||||||
| 472 | ||||||||
| 473 | sub _setup { | |||||||
| 474 | 64 | 1153 | my $self = shift; | |||||
| 475 | ||||||||
| 476 | # The lock, the pid file and the default log live beside the control path, | |||||||
| 477 | # so that is the only directory this backend needs. | |||||||
| 478 | 64 | 259 | my $dir = Class::Shared::dir_of($self->{control}); | |||||
| 479 | ||||||||
| 480 | 64 | 193 | my ($dir_ok, $dir_error) = Class::Shared::ensure_dir($dir); | |||||
| 481 | 64 | 148 | die "$dir_error\n" unless $dir_ok; | |||||
| 482 | ||||||||
| 483 | 56 | 86 | my $lock_path = $self->{control} . '.owner'; | |||||
| 484 | 56 | 92 | my $lock; | |||||
| 485 | 56 | 1818 | sysopen($lock, $lock_path, O_RDWR | O_CREAT, 0600) | |||||
| 486 | or die "cannot open $lock_path: $!\n"; | |||||||
| 487 | ||||||||
| 488 | # A backend that is shutting down still holds the lock for a moment, so | |||||||
| 489 | # give it a short while before deciding that somebody else is serving. | |||||||
| 490 | 54 | 168 | my $deadline = time + $self->{start_timeout}; | |||||
| 491 | 54 | 55 | while (1) { | |||||
| 492 | 519 | 3400 | last if flock($lock, LOCK_EX | LOCK_NB); | |||||
| 493 | 488 | 1100 | if (time >= $deadline) { | |||||
| 494 | 23 | 609 | die "another backend is already serving ($lock_path is locked)\n"; | |||||
| 495 | } | |||||||
| 496 | 465 | 896 | Class::Shared::poll_pause(); | |||||
| 497 | } | |||||||
| 498 | 31 | 55 | $self->{lock} = $lock; | |||||
| 499 | ||||||||
| 500 | 31 | 69 | if (defined $self->{socket}) { | |||||
| 501 | 23 | 88 | $self->_setup_unix; | |||||
| 502 | } else { | |||||||
| 503 | 8 | 31 | $self->_setup_tcp; | |||||
| 504 | } | |||||||
| 505 | ||||||||
| 506 | # A listener that leaked into a method's exec'd child would keep the socket | |||||||
| 507 | # open after this backend had gone. | |||||||
| 508 | 12 | 835 | fcntl($self->{listener}, F_SETFD, FD_CLOEXEC) | |||||
| 509 | or die "cannot mark the listener close-on-exec: $!\n"; | |||||||
| 510 | ||||||||
| 511 | # The pid file is a convenience for administrators, so failing to write it | |||||||
| 512 | # is logged and not fatal. | |||||||
| 513 | 12 | 18 | my $pid_path = $self->{control} . '.pid'; | |||||
| 514 | 12 | 14 | my $pid_fh; | |||||
| 515 | open($pid_fh, '>', $pid_path) | |||||||
| 516 | 12 10 | 397 345 | && print({$pid_fh} "$$\n") | |||||
| 517 | && close($pid_fh) | |||||||
| 518 | or $self->_log("cannot write $pid_path: $!", 'error'); | |||||||
| 519 | ||||||||
| 520 | 12 | 52 | return 1; | |||||
| 521 | } | |||||||
| 522 | ||||||||
| 523 | sub _setup_unix { | |||||||
| 524 | 32 | 245 | my $self = shift; | |||||
| 525 | ||||||||
| 526 | 32 | 170 | if (-e $self->{socket}) { | |||||
| 527 | # Only a socket is removed as a leftover: a path that names anything | |||||||
| 528 | # else is not ours to delete, however it came to be given as one. | |||||||
| 529 | die "$self->{socket} exists and is not a socket; refusing to remove it\n" | |||||||
| 530 | 22 | 176 | unless -S $self->{socket}; | |||||
| 531 | ||||||||
| 532 | 6 | 16 | my $probe = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $self->{socket}); | |||||
| 533 | 6 | 770 | if ($probe) { | |||||
| 534 | 2 | 6 | $self->_close($probe, 'the probe connection'); | |||||
| 535 | 2 | 12 | die "a backend is already listening on $self->{socket}\n"; | |||||
| 536 | } | |||||||
| 537 | unlink $self->{socket} | |||||||
| 538 | 4 | 66 | or die "cannot remove the stale socket $self->{socket}: $!\n"; | |||||
| 539 | } | |||||||
| 540 | ||||||||
| 541 | # Bind with no permission for anyone else, so that there is no moment | |||||||
| 542 | # between bind and the chmod below when the socket is open to the group. | |||||||
| 543 | 12 | 20 | my $old_umask = umask 0177; | |||||
| 544 | my $listener = IO::Socket::UNIX->new( | |||||||
| 545 | Type => SOCK_STREAM, | |||||||
| 546 | Local => $self->{socket}, | |||||||
| 547 | 12 | 99 | Listen => $LISTEN_BACKLOG, | |||||
| 548 | Blocking => 1, | |||||||
| 549 | ); | |||||||
| 550 | 12 | 2548 | my $bind_error = $!; | |||||
| 551 | 12 | 19 | umask $old_umask; | |||||
| 552 | ||||||||
| 553 | 12 | 158 | die "cannot listen on $self->{socket}: $bind_error\n" unless $listener; | |||||
| 554 | ||||||||
| 555 | # Recorded before anything else can fail, so that the failure cleans it up. | |||||||
| 556 | 10 | 14 | $self->{listener} = $listener; | |||||
| 557 | 10 | 11 | $self->{address} = $self->{socket}; | |||||
| 558 | 10 | 11 | $self->{owns_socket} = 1; | |||||
| 559 | 10 | 40 | $self->{owner_pid} = $$; | |||||
| 560 | ||||||||
| 561 | chmod 0600, $self->{socket} | |||||||
| 562 | 10 | 98 | or die "cannot set permissions on $self->{socket}: $!\n"; | |||||
| 563 | ||||||||
| 564 | 10 | 19 | return 1; | |||||
| 565 | } | |||||||
| 566 | ||||||||
| 567 | sub _setup_tcp { | |||||||
| 568 | 20 | 975 | my $self = shift; | |||||
| 569 | ||||||||
| 570 | die "Class::Shared::Backend: no TCP address configured\n" | |||||||
| 571 | 20 | 81 | unless defined $self->{host} && defined $self->{port}; | |||||
| 572 | ||||||||
| 573 | # Loaded only for a TCP listener: a unix socket never pays for TLS, just | |||||||
| 574 | # as it never paid for the digest. | |||||||
| 575 | 16 | 809 | require IO::Socket::SSL; | |||||
| 576 | ||||||||
| 577 | # One context for every connection: the certificates are read and checked | |||||||
| 578 | # once, and each accepted socket starts its handshake against it. | |||||||
| 579 | # The context croaks for a file it cannot use, and only returns false | |||||||
| 580 | # for some other faults, so both are turned into the one message. | |||||||
| 581 | 16 | 57205 | my $context = eval { | |||||
| 582 | IO::Socket::SSL::SSL_Context->new( | |||||||
| 583 | SSL_server => 1, | |||||||
| 584 | SSL_version => $Class::Shared::TLS_VERSIONS, | |||||||
| 585 | SSL_cert_file => $self->{tls_cert}, | |||||||
| 586 | SSL_key_file => $self->{tls_key}, | |||||||
| 587 | SSL_ca_file => $self->{tls_ca}, | |||||||
| 588 | 16 | 161 | SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_PEER() | |||||
| 589 | | IO::Socket::SSL::SSL_VERIFY_FAIL_IF_NO_PEER_CERT(), | |||||||
| 590 | ); | |||||||
| 591 | }; | |||||||
| 592 | ||||||||
| 593 | 16 | 10362 | if (!$context) { | |||||
| 594 | 10 | 14 | my $why = $@; | |||||
| 595 | 10 | 42 | $why =~ s/ at \S+ line \d+\.?\s*\z//; | |||||
| 596 | 10 | 26 | $why =~ s/\s+\z//; | |||||
| 597 | 10 | 22 | $why = IO::Socket::SSL::errstr() || "$!" || 'unknown error' unless length $why; | |||||
| 598 | ||||||||
| 599 | 10 | 46 | die "cannot set up TLS for $self->{host}:$self->{port}: $why\n"; | |||||
| 600 | } | |||||||
| 601 | ||||||||
| 602 | 6 | 10 | $self->{tls_context} = $context; | |||||
| 603 | ||||||||
| 604 | # The listener is plain TCP. The handshake belongs to the connection, where | |||||||
| 605 | # it can be carried a little at a time as that connection becomes ready; in | |||||||
| 606 | # accept() it would stall every client already being served for as long as | |||||||
| 607 | # the newest one stayed silent. | |||||||
| 608 | my $listener = IO::Socket::INET->new( | |||||||
| 609 | LocalAddr => $self->{host}, | |||||||
| 610 | LocalPort => $self->{port}, | |||||||
| 611 | 6 | 37 | Proto => 'tcp', | |||||
| 612 | Listen => $LISTEN_BACKLOG, | |||||||
| 613 | ReuseAddr => 1, | |||||||
| 614 | ) or die "cannot listen on $self->{host}:$self->{port}: $!\n"; | |||||||
| 615 | ||||||||
| 616 | 4 | 783 | $self->{listener} = $listener; | |||||
| 617 | 4 | 9 | $self->{address} = $self->{host} . ':' . $self->{port}; | |||||
| 618 | ||||||||
| 619 | 4 | 6 | return 1; | |||||
| 620 | } | |||||||
| 621 | ||||||||
| 622 | sub _loop { | |||||||
| 623 | 24 | 416 | my $self = shift; | |||||
| 624 | ||||||||
| 625 | 24 2 | 152 44 | local $SIG{TERM} = sub { $self->{stop} = 1 }; | |||||
| 626 | 24 2 | 86 22 | local $SIG{INT} = sub { $self->{stop} = 1 }; | |||||
| 627 | 24 | 76 | local $SIG{HUP} = 'IGNORE'; | |||||
| 628 | 24 | 66 | local $SIG{PIPE} = 'IGNORE'; | |||||
| 629 | ||||||||
| 630 | 24 | 62 | while (!$self->{stop}) { | |||||
| 631 | 197 | 484 | my $rin = ''; | |||||
| 632 | 197 | 130 | my $win = ''; | |||||
| 633 | 197 | 127 | my $handshaking = 0; | |||||
| 634 | 197 | 134 | my $write_deadline; | |||||
| 635 | ||||||||
| 636 | 197 | 345 | vec($rin, fileno($self->{listener}), 1) = 1; | |||||
| 637 | ||||||||
| 638 | 197 197 | 191 288 | for my $client (values %{$self->{clients}}) { | |||||
| 639 | 406 | 431 | my $fd = fileno($client->{fh}); | |||||
| 640 | 406 | 1284 | next unless defined $fd; | |||||
| 641 | ||||||||
| 642 | 402 | 307 | vec($rin, $fd, 1) = 1; | |||||
| 643 | ||||||||
| 644 | 402 | 486 | if ($client->{handshaking}) { | |||||
| 645 | 91 | 56 | $handshaking = 1; | |||||
| 646 | ||||||||
| 647 | # A handshake can want to write as well (TLS 1.3 tickets, a | |||||||
| 648 | # full send buffer), so wait for that only when it asked. | |||||||
| 649 | 91 | 100 | vec($win, $fd, 1) = 1 if $client->{want_write}; | |||||
| 650 | } elsif (length $client->{outbuf}) { | |||||||
| 651 | # A queued reply is waiting for the socket to take it, and has a | |||||||
| 652 | # deadline if it has made no progress yet. | |||||||
| 653 | 4 | 6 | vec($win, $fd, 1) = 1; | |||||
| 654 | ||||||||
| 655 | 4 | 4 | if (defined $client->{stalled_since}) { | |||||
| 656 | 2 | 2 | my $deadline = $client->{stalled_since} + $self->{write_timeout}; | |||||
| 657 | 2 | 6 | $write_deadline = $deadline | |||||
| 658 | if !defined $write_deadline || $deadline < $write_deadline; | |||||||
| 659 | } | |||||||
| 660 | } | |||||||
| 661 | } | |||||||
| 662 | ||||||||
| 663 | # With a handshake in progress, or a queued reply on a deadline, wake up | |||||||
| 664 | # now and then: a peer that never speaks, or one that never reads, would | |||||||
| 665 | # otherwise keep select asleep past the deadline it is on. | |||||||
| 666 | 197 | 208 | my $timeout = $handshaking ? $HANDSHAKE_POLL : undef; | |||||
| 667 | 197 | 132 | my $read_deadline; | |||||
| 668 | 197 197 | 115 204 | for my $client (values %{$self->{clients}}) { | |||||
| 669 | 406 | 345 | my ($deadline) = $self->_read_deadline($client); | |||||
| 670 | 406 | 327 | next unless defined $deadline; | |||||
| 671 | 67 | 95 | $read_deadline = $deadline | |||||
| 672 | if !defined $read_deadline || $deadline < $read_deadline; | |||||||
| 673 | } | |||||||
| 674 | 197 | 200 | if (defined $read_deadline) { | |||||
| 675 | 46 | 57 | my $wait = $read_deadline - Time::HiRes::time(); | |||||
| 676 | 46 | 47 | $wait = 0 if $wait < 0; | |||||
| 677 | 46 | 91 | $timeout = $wait if !defined $timeout || $wait < $timeout; | |||||
| 678 | } | |||||||
| 679 | 197 | 224 | if (defined $write_deadline) { | |||||
| 680 | 2 | 4 | my $wait = $write_deadline - Time::HiRes::time(); | |||||
| 681 | 2 | 4 | $wait = 0 if $wait < 0; | |||||
| 682 | 2 | 6 | $timeout = $wait if !defined $timeout || $wait < $timeout; | |||||
| 683 | } | |||||||
| 684 | ||||||||
| 685 | # After accept() ran out of descriptors the waiting connection keeps the | |||||||
| 686 | # listener readable, so watching it would spin the processor. It is left | |||||||
| 687 | # out of the select for a short while instead. | |||||||
| 688 | 197 | 242 | if (defined $self->{accept_after}) { | |||||
| 689 | 0 | 0 | my $wait = $self->{accept_after} - Time::HiRes::time(); | |||||
| 690 | 0 | 0 | if ($wait > 0) { | |||||
| 691 | 0 | 0 | vec($rin, fileno($self->{listener}), 1) = 0; | |||||
| 692 | 0 | 0 | $timeout = $wait if !defined $timeout || $wait < $timeout; | |||||
| 693 | } else { | |||||||
| 694 | 0 | 0 | delete $self->{accept_after}; | |||||
| 695 | } | |||||||
| 696 | } | |||||||
| 697 | ||||||||
| 698 | 197 | 21263624 | my $ready = select(my $rout = $rin, my $wout = $win, undef, $timeout); | |||||
| 699 | ||||||||
| 700 | 197 | 466 | $self->_expire_handshakes if $handshaking; | |||||
| 701 | 197 | 228 | $self->_expire_writes if defined $write_deadline; | |||||
| 702 | 197 | 310 | $self->_expire_reads(defined $ready && $ready > 0 ? $rout : '') | |||||
| 703 | if defined $read_deadline; | |||||||
| 704 | ||||||||
| 705 | 197 | 478 | next if !defined $ready || $ready <= 0; | |||||
| 706 | ||||||||
| 707 | 196 | 403 | if (vec($rout, fileno($self->{listener}), 1)) { | |||||
| 708 | 55 | 121 | $self->_accept; | |||||
| 709 | } | |||||||
| 710 | ||||||||
| 711 | 196 196 | 153 264 | for my $key (keys %{$self->{clients}}) { | |||||
| 712 | 439 | 384 | my $client = $self->{clients}{$key}; | |||||
| 713 | 439 | 344 | next unless $client; | |||||
| 714 | ||||||||
| 715 | 439 | 531 | my $fd = fileno($client->{fh}); | |||||
| 716 | 439 | 1513 | next unless defined $fd; | |||||
| 717 | ||||||||
| 718 | 435 | 289 | my $readable = vec($rout, $fd, 1); | |||||
| 719 | 435 | 286 | my $writable = vec($wout, $fd, 1); | |||||
| 720 | ||||||||
| 721 | 435 | 340 | if ($client->{handshaking}) { | |||||
| 722 | 121 | 212 | next unless $readable || ($client->{want_write} && $writable); | |||||
| 723 | 64 | 88 | $self->_continue_tls($client); | |||||
| 724 | } else { | |||||||
| 725 | 314 | 474 | next unless $readable || $writable; | |||||
| 726 | ||||||||
| 727 | 85 | 169 | $self->_serve_client($client) if $readable; | |||||
| 728 | 85 | 136 | $self->_flush($client) if $writable && !$client->{closed}; | |||||
| 729 | } | |||||||
| 730 | ||||||||
| 731 | 149 | 389 | last if $self->{stop}; | |||||
| 732 | } | |||||||
| 733 | } | |||||||
| 734 | ||||||||
| 735 | 24 | 267 | return 1; | |||||
| 736 | } | |||||||
| 737 | ||||||||
| 738 | # Drop connections whose handshake has run out of time, so a peer that opens a | |||||||
| 739 | # socket and then says nothing frees its slot again. | |||||||
| 740 | sub _expire_handshakes { | |||||||
| 741 | 79 | 995 | my $self = shift; | |||||
| 742 | ||||||||
| 743 | 79 | 75 | my $now = time; | |||||
| 744 | ||||||||
| 745 | 79 79 | 61 133 | for my $client (values %{$self->{clients}}) { | |||||
| 746 | 194 | 220 | next unless $client->{handshaking}; | |||||
| 747 | 100 | 120 | next if $client->{deadline} > $now; | |||||
| 748 | ||||||||
| 749 | 9 | 9 | $self->_drop_client($client, 'TLS handshake timed out'); | |||||
| 750 | } | |||||||
| 751 | ||||||||
| 752 | 79 | 81 | return 1; | |||||
| 753 | } | |||||||
| 754 | ||||||||
| 755 | # Purpose: keep count of what a client has half sent, and bound the total. | |||||||
| 756 | # Entry: $client has just been read from; $completed is how many whole | |||||||
| 757 | # frames that read finished. | |||||||
| 758 | # Exit status: 1. | |||||||
| 759 | # Side effects: releases an emptied buffer; while the half-sent frames of all | |||||||
| 760 | # clients add up to more than max_buffered_total, drops the | |||||||
| 761 | # client whose frame has been arriving the longest. | |||||||
| 762 | # Why: the oldest is the one to go because a client that is hoarding | |||||||
| 763 | # memory has an old frame, and an honest large request a new one. | |||||||
| 764 | sub _account_inbound { | |||||||
| 765 | 78 | 72 | my ($self, $client, $completed) = @_; | |||||
| 766 | ||||||||
| 767 | 78 | 72 | if (!length $client->{buffer}) { | |||||
| 768 | # Emptying a string keeps its memory, and a frame can be 64 MiB. | |||||||
| 769 | 67 | 73 | undef $client->{buffer}; | |||||
| 770 | 67 | 57 | $client->{buffer} = ''; | |||||
| 771 | 67 67 | 43 70 | delete @{$client}{qw(partial_started partial_progress)}; | |||||
| 772 | 67 | 50 | return 1; | |||||
| 773 | } | |||||||
| 774 | ||||||||
| 775 | 11 | 8 | my $now = Time::HiRes::time(); | |||||
| 776 | 11 | 16 | delete $client->{partial_started} if $completed; | |||||
| 777 | 11 | 24 | $client->{partial_started} //= $now; | |||||
| 778 | 11 | 13 | $client->{partial_progress} = $now; | |||||
| 779 | ||||||||
| 780 | 11 17 11 | 9 18 15 | my @partial = grep { length($_->{buffer} // '') } values %{$self->{clients}}; | |||||
| 781 | 11 | 5 | my $total = 0; | |||||
| 782 | 11 | 14 | $total += length $_->{buffer} for @partial; | |||||
| 783 | ||||||||
| 784 | 11 0 | 16 0 | for my $oldest (sort { ($a->{partial_started} // $now) <=> ($b->{partial_started} // $now) } @partial) { | |||||
| 785 | 5 | 8 | last if $total <= $self->{max_buffered_total}; | |||||
| 786 | ||||||||
| 787 | 0 | 0 | my $held = length $oldest->{buffer}; | |||||
| 788 | 0 | 0 | $total -= $held; | |||||
| 789 | 0 | 0 | $self->_drop_client($oldest, "half-received requests add up to more than the " | |||||
| 790 | . "$self->{max_buffered_total} bytes the backend may hold; this one held $held"); | |||||||
| 791 | } | |||||||
| 792 | ||||||||
| 793 | 11 | 7 | return 1; | |||||
| 794 | } | |||||||
| 795 | ||||||||
| 796 | # Purpose: say by when a client must send something, and why. | |||||||
| 797 | # Entry: $client is a client record. | |||||||
| 798 | # Exit status: (time, reason for dropping it), or () for no limit. | |||||||
| 799 | # Side effects: none. | |||||||
| 800 | sub _read_deadline { | |||||||
| 801 | 545 | 385 | my ($self, $client) = @_; | |||||
| 802 | ||||||||
| 803 | # A TLS handshake has its own deadline. | |||||||
| 804 | 545 | 446 | return () if $client->{handshaking}; | |||||
| 805 | ||||||||
| 806 | my @partial = defined $client->{partial_progress} | |||||||
| 807 | ? ($client->{partial_progress} + $self->{read_timeout}, | |||||||
| 808 | 'a request of which ' . length($client->{buffer}) | |||||||
| 809 | 447 | 446 | . " bytes had arrived made no progress for $self->{read_timeout} second(s)") | |||||
| 810 | : (); | |||||||
| 811 | ||||||||
| 812 | # Until a hello is accepted its deadline stands whatever else arrives, or | |||||||
| 813 | # a hello that never ends would keep its place for ever. | |||||||
| 814 | 447 | 510 | if (!$client->{greeted} && defined $client->{greet_by}) { | |||||
| 815 | 136 | 134 | return @partial if @partial && $partial[0] < $client->{greet_by}; | |||||
| 816 | 136 | 162 | return ($client->{greet_by}, $self->_no_hello_reason); | |||||
| 817 | } | |||||||
| 818 | ||||||||
| 819 | 311 | 210 | return @partial if @partial; | |||||
| 820 | ||||||||
| 821 | # A reply still being written is write_timeout's business. | |||||||
| 822 | return ($client->{last_request} + $self->{idle_timeout}, | |||||||
| 823 | "sent nothing for $self->{idle_timeout} second(s)") | |||||||
| 824 | if $self->{idle_timeout} && defined $client->{last_request} | |||||||
| 825 | 299 | 254 | && !length $client->{outbuf}; | |||||
| 826 | ||||||||
| 827 | 299 | 261 | return (); | |||||
| 828 | } | |||||||
| 829 | ||||||||
| 830 | sub _no_hello_reason { | |||||||
| 831 | 136 | 79 | my $self = shift; | |||||
| 832 | ||||||||
| 833 | 136 | 200 | return "no accepted hello within $self->{handshake_timeout} second(s)"; | |||||
| 834 | } | |||||||
| 835 | ||||||||
| 836 | # Drop connections that have not sent what they should have in time. One that | |||||||
| 837 | # has bytes waiting to be read ($readable) is left alone: the backend may only | |||||||
| 838 | # just have come back from a long call, and those bytes are its progress. | |||||||
| 839 | sub _expire_reads { | |||||||
| 840 | 60 | 4561 | my ($self, $readable) = @_; | |||||
| 841 | ||||||||
| 842 | 60 | 64 | my $now = Time::HiRes::time(); | |||||
| 843 | ||||||||
| 844 | 60 60 | 77 105 | for my $client (values %{$self->{clients}}) { | |||||
| 845 | 139 | 118 | next if $client->{closed}; | |||||
| 846 | 139 | 114 | my ($deadline, $reason) = $self->_read_deadline($client); | |||||
| 847 | 139 | 129 | next unless defined $deadline; | |||||
| 848 | 81 | 96 | next if $deadline > $now; | |||||
| 849 | 7 | 14 | next if length $readable && vec($readable, fileno($client->{fh}), 1); | |||||
| 850 | ||||||||
| 851 | 7 | 21 | $self->_drop_client($client, $reason); | |||||
| 852 | } | |||||||
| 853 | ||||||||
| 854 | 60 | 44 | return 1; | |||||
| 855 | } | |||||||
| 856 | ||||||||
| 857 | # Purpose: keep the log from filling the disk. | |||||||
| 858 | # Entry: max_log_size is a number of bytes, 0 for no limit. | |||||||
| 859 | # Exit status: 1. | |||||||
| 860 | # Side effects: copies a log over the limit to LOG.1 (replacing it) and | |||||||
| 861 | # empties the log. | |||||||
| 862 | # Why: copied and emptied, not renamed: standard output and error of | |||||||
| 863 | # the backend, which the target writes to, hold the file open, and | |||||||
| 864 | # after a rename they would go on filling a file nobody can see. | |||||||
| 865 | # A log that is a symbolic link or a device is left to whoever | |||||||
| 866 | # made it so. | |||||||
| 867 | sub _trim_log { | |||||||
| 868 | 253 | 231 | my $self = shift; | |||||
| 869 | ||||||||
| 870 | 253 | 242 | my $limit = $self->{max_log_size}; | |||||
| 871 | 253 | 569 | return 1 unless $limit && defined $self->{log}; | |||||
| 872 | ||||||||
| 873 | 253 | 2374 | my $path = File::Spec->rel2abs($self->{log}); | |||||
| 874 | 253 | 1951 | return 1 unless lstat($path) && -f _ && -s _ > $limit; | |||||
| 875 | ||||||||
| 876 | 1 | 9 | local ($!, $@); | |||||
| 877 | ||||||||
| 878 | # From here on only this handle is read and emptied. The name may come to | |||||||
| 879 | # mean another file at any moment, so check that what was opened is what the | |||||||
| 880 | # name meant: a plain file, not a link to one. | |||||||
| 881 | 1 | 36 | open(my $log, '+<', $path) or return 1; | |||||
| 882 | 1 | 8 | my @opened = stat($log); | |||||
| 883 | 1 | 3 | my @named = lstat($path); | |||||
| 884 | 1 | 23 | return 1 unless @named && -f _ && $named[0] == $opened[0] && $named[1] == $opened[1]; | |||||
| 885 | ||||||||
| 886 | 1 | 3 | my $old = "$path.1"; | |||||
| 887 | ||||||||
| 888 | # Made anew, owner only, so that nothing already there is written through. | |||||||
| 889 | 1 | 6 | unlink($old); | |||||
| 890 | 1 | 3 | if (sysopen(my $to, $old, O_WRONLY | O_CREAT | O_EXCL, 0600)) { | |||||
| 891 | 1 | 109 | while (sysread($log, my $chunk, $READ_CHUNK)) { | |||||
| 892 | 1 | 23 | last unless syswrite($to, $chunk); | |||||
| 893 | } | |||||||
| 894 | 1 | 4 | close($to); | |||||
| 895 | } | |||||||
| 896 | ||||||||
| 897 | # Emptied even if the copy failed: bounding the disk is the point. | |||||||
| 898 | 1 | 24 | truncate($log, 0); | |||||
| 899 | 1 | 2 | close($log); | |||||
| 900 | ||||||||
| 901 | 1 | 7 | return 1; | |||||
| 902 | } | |||||||
| 903 | ||||||||
| 904 | # Drop connections whose queued reply the socket has stopped taking, so a | |||||||
| 905 | # client that has stopped reading cannot sit on the memory it was allowed. | |||||||
| 906 | sub _expire_writes { | |||||||
| 907 | 20 | 3875 | my $self = shift; | |||||
| 908 | ||||||||
| 909 | 20 | 27 | my $now = Time::HiRes::time(); | |||||
| 910 | ||||||||
| 911 | 20 20 | 39 36 | for my $client (values %{$self->{clients}}) { | |||||
| 912 | 28 | 33 | next if $client->{closed}; | |||||
| 913 | 26 | 31 | next unless length $client->{outbuf}; | |||||
| 914 | 24 | 24 | next unless defined $client->{stalled_since}; | |||||
| 915 | 22 | 31 | next if $client->{stalled_since} + $self->{write_timeout} > $now; | |||||
| 916 | ||||||||
| 917 | $self->_drop_client($client, 'a queued reply of ' . length($client->{outbuf}) | |||||||
| 918 | 11 | 22 | . ' bytes made no progress for ' . $self->{write_timeout} . ' second(s)'); | |||||
| 919 | } | |||||||
| 920 | ||||||||
| 921 | 20 | 24 | return 1; | |||||
| 922 | } | |||||||
| 923 | ||||||||
| 924 | sub _accept { | |||||||
| 925 | 63 | 8206 | my $self = shift; | |||||
| 926 | ||||||||
| 927 | 63 | 221 | my $fh = $self->{listener}->accept; | |||||
| 928 | 63 | 5497 | if (!$fh) { | |||||
| 929 | 2 | 8 | if ($!{EMFILE} || $!{ENFILE} || $!{ENOBUFS} || $!{ENOMEM}) { | |||||
| 930 | # Logged once for each shortage, not once for each attempt. | |||||||
| 931 | $self->_log("cannot accept a connection: $!", 'warn') | |||||||
| 932 | 0 | 0 | unless $self->{accept_failing}++; | |||||
| 933 | 0 | 0 | $self->{accept_after} = Time::HiRes::time() + $ACCEPT_PAUSE; | |||||
| 934 | } | |||||||
| 935 | 2 | 86 | return; | |||||
| 936 | } | |||||||
| 937 | 61 | 72 | delete $self->{accept_failing}; | |||||
| 938 | ||||||||
| 939 | 61 61 | 47 139 | if (keys %{$self->{clients}} >= $self->{max_clients}) { | |||||
| 940 | # A unix client can be told, signed like every other frame. A TCP | |||||||
| 941 | # client has not handshaken yet, so there is no session to sign one | |||||||
| 942 | # for: it is closed, and the frontend reports a failed connection. | |||||||
| 943 | 6 | 8 | if (!defined $self->{host}) { | |||||
| 944 | my ($bytes) = Class::Shared::Protocol::encode_frame( | |||||||
| 945 | _failure('busy', "backend is serving too many clients ($self->{max_clients})"), | |||||||
| 946 | $self->{token}, | |||||||
| 947 | 4 | 14 | ); | |||||
| 948 | 4 | 12 | Class::Shared::Protocol::write_all($fh, $bytes) if defined $bytes; | |||||
| 949 | } | |||||||
| 950 | ||||||||
| 951 | 6 | 10 | $self->_close($fh, 'a refused connection'); | |||||
| 952 | 6 | 14 | return; | |||||
| 953 | } | |||||||
| 954 | ||||||||
| 955 | # A unix client that stops reading must not hold the loop either, so every | |||||||
| 956 | # accepted socket is non-blocking from here on, TLS or not. Neither step | |||||||
| 957 | # can be skipped: a blocking socket stalls everybody, and one that leaks | |||||||
| 958 | # into an exec'd child outlives its connection. | |||||||
| 959 | 55 | 216 | if (!(fcntl($fh, F_SETFD, FD_CLOEXEC) && defined $fh->blocking(0))) { | |||||
| 960 | 2 | 22 | $self->_log("refused a connection: cannot prepare its socket: $!", 'warn'); | |||||
| 961 | 2 | 8 | $self->_close($fh, 'a refused connection'); | |||||
| 962 | 2 | 10 | return; | |||||
| 963 | } | |||||||
| 964 | ||||||||
| 965 | my $client = { | |||||||
| 966 | fh => $fh, | |||||||
| 967 | buffer => '', | |||||||
| 968 | outbuf => '', | |||||||
| 969 | greeted => 0, | |||||||
| 970 | serial => $self->{next_serial}++, | |||||||
| 971 | objects => {}, | |||||||
| 972 | closed => 0, | |||||||
| 973 | greet_by => Time::HiRes::time() + $self->{handshake_timeout}, | |||||||
| 974 | 53 | 674 | }; | |||||
| 975 | ||||||||
| 976 | 53 | 80 | if (defined $self->{host}) { | |||||
| 977 | 37 | 68 | my $ssl = $self->_start_tls($fh); | |||||
| 978 | ||||||||
| 979 | 37 | 2039 | if (!$ssl) { | |||||
| 980 | 2 | 4 | $self->_log('refused a TLS connection: ' | |||||
| 981 | . (IO::Socket::SSL::errstr() || 'cannot start a handshake'), 'warn'); | |||||||
| 982 | 2 | 12 | $self->_close($fh, 'a refused connection'); | |||||
| 983 | 2 | 10 | return; | |||||
| 984 | } | |||||||
| 985 | ||||||||
| 986 | # TODO: Data Flow Anomaly - DD: for TLS, fh was defined with the plain socket and is redefined unread | |||||||
| 987 | 35 | 44 | $client->{fh} = $ssl; | |||||
| 988 | 35 | 39 | $client->{handshaking} = 1; | |||||
| 989 | 35 | 28 | $client->{want_write} = 0; | |||||
| 990 | 35 | 58 | $client->{deadline} = time + $self->{handshake_timeout}; | |||||
| 991 | } | |||||||
| 992 | ||||||||
| 993 | 51 | 102 | $self->{clients}{ fileno($client->{fh}) } = $client; | |||||
| 994 | ||||||||
| 995 | 51 | 51 | return 1; | |||||
| 996 | } | |||||||
| 997 | ||||||||
| 998 | # Give an accepted socket its TLS layer but do not perform the handshake here: | |||||||
| 999 | # accept_SSL() is called from the select loop as the socket becomes ready, so a | |||||||
| 1000 | # silent peer holds one pending handshake instead of the whole backend. | |||||||
| 1001 | sub _start_tls { | |||||||
| 1002 | 37 | 3373 | my ($self, $fh) = @_; | |||||
| 1003 | ||||||||
| 1004 | # _accept has already made it non-blocking; start_SSL keeps that. | |||||||
| 1005 | return IO::Socket::SSL->start_SSL( | |||||||
| 1006 | $fh, | |||||||
| 1007 | SSL_server => 1, | |||||||
| 1008 | SSL_startHandshake => 0, | |||||||
| 1009 | SSL_reuse_ctx => $self->{tls_context}, | |||||||
| 1010 | 37 | 181 | ); | |||||
| 1011 | } | |||||||
| 1012 | ||||||||
| 1013 | # One step of a pending handshake. Returns nothing; the client either becomes | |||||||
| 1014 | # an ordinary connection, waits for the next readiness, or is dropped. | |||||||
| 1015 | sub _continue_tls { | |||||||
| 1016 | 80 | 7326 | my ($self, $client) = @_; | |||||
| 1017 | ||||||||
| 1018 | 80 | 63 | my $fh = $client->{fh}; | |||||
| 1019 | ||||||||
| 1020 | 80 | 112 | if ($fh->accept_SSL) { | |||||
| 1021 | 24 | 10331 | $client->{handshaking} = 0; | |||||
| 1022 | 24 | 23 | $client->{want_write} = 0; | |||||
| 1023 | 24 | 20 | delete $client->{deadline}; | |||||
| 1024 | # The time to say hello starts once there is a channel to say it on. | |||||||
| 1025 | 24 | 50 | $client->{greet_by} = Time::HiRes::time() + $self->{handshake_timeout}; | |||||
| 1026 | ||||||||
| 1027 | # The socket stays non-blocking: a frame, or the TLS record carrying | |||||||
| 1028 | # it, that arrives in pieces waits in this client's buffer while the | |||||||
| 1029 | # loop serves everybody else. | |||||||
| 1030 | 24 | 27 | return 1; | |||||
| 1031 | } | |||||||
| 1032 | ||||||||
| 1033 | # A failed handshake reblesses the socket back to the plain class it was | |||||||
| 1034 | # upgraded from, so the handle can no longer answer TLS questions. Ask | |||||||
| 1035 | # the TLS layer for the last error instead. | |||||||
| 1036 | 68 68 68 56 56 | 148742 72 116535 38724 80 | my $error = do { no warnings 'once'; $IO::Socket::SSL::SSL_ERROR }; | |||||
| 1037 | ||||||||
| 1038 | 56 | 142 | if (defined $error && $error == IO::Socket::SSL::SSL_WANT_READ()) { | |||||
| 1039 | 33 | 36 | $client->{want_write} = 0; | |||||
| 1040 | 33 | 39 | return 1; | |||||
| 1041 | } | |||||||
| 1042 | ||||||||
| 1043 | 23 | 49 | if (defined $error && $error == IO::Socket::SSL::SSL_WANT_WRITE()) { | |||||
| 1044 | 2 | 4 | $client->{want_write} = 1; | |||||
| 1045 | 2 | 2 | return 1; | |||||
| 1046 | } | |||||||
| 1047 | ||||||||
| 1048 | 21 | 27 | $self->_log('refused a TLS connection: ' | |||||
| 1049 | . (IO::Socket::SSL::errstr() || 'handshake failed'), 'warn'); | |||||||
| 1050 | 21 | 72 | $self->_drop_client($client, 'TLS handshake failed'); | |||||
| 1051 | ||||||||
| 1052 | 21 | 20 | return; | |||||
| 1053 | } | |||||||
| 1054 | ||||||||
| 1055 | # True when a failed read or write means "not yet", not "gone": a non-blocking | |||||||
| 1056 | # socket with nothing to give (or no room to take), or a TLS layer waiting for | |||||||
| 1057 | # the other direction. The errno it looks at is the one the call that just | |||||||
| 1058 | # failed produced, never one left over from before it: the caller clears $!. | |||||||
| 1059 | sub _would_block { | |||||||
| 1060 | 52 | 5244 | my ($self, $fh, $direction) = @_; | |||||
| 1061 | ||||||||
| 1062 | 52 | 59 | $direction = 'read' unless defined $direction; | |||||
| 1063 | ||||||||
| 1064 | 52 | 114 | return 1 if $!{EAGAIN} || $!{EWOULDBLOCK}; | |||||
| 1065 | ||||||||
| 1066 | 38 | 439 | my $want = "want_$direction"; | |||||
| 1067 | 38 | 149 | return 1 if $fh->can($want) && $fh->$want; | |||||
| 1068 | ||||||||
| 1069 | # A write can be waiting on a TLS layer that has to read something first. | |||||||
| 1070 | 28 | 80 | return 1 if $direction eq 'write' && $fh->can('want_read') && $fh->want_read; | |||||
| 1071 | ||||||||
| 1072 | 25 | 39 | return 0; | |||||
| 1073 | } | |||||||
| 1074 | ||||||||
| 1075 | sub _serve_client { | |||||||
| 1076 | 113 | 2173 | my ($self, $client) = @_; | |||||
| 1077 | ||||||||
| 1078 | # errno outlives a call, and a TLS read can fail for its own reasons | |||||||
| 1079 | # without touching it, so clear it and let only this sysread supply the | |||||||
| 1080 | # EAGAIN that means "not yet". Otherwise a genuine TLS error could be | |||||||
| 1081 | # mistaken for half a frame and the client would be kept rather than | |||||||
| 1082 | # dropped. | |||||||
| 1083 | 113 | 119 | $! = 0; | |||||
| 1084 | ||||||||
| 1085 | 113 | 440 | my $read = sysread($client->{fh}, my $chunk, $READ_CHUNK); | |||||
| 1086 | ||||||||
| 1087 | 113 | 2234 | if (!defined $read) { | |||||
| 1088 | # Half a frame is not a fault: keep what has arrived and come back | |||||||
| 1089 | # when the rest does. The buffer is per client, so a slow sender | |||||||
| 1090 | # only ever delays itself. | |||||||
| 1091 | 5 | 6 | return 1 if $self->_would_block($client->{fh}); | |||||
| 1092 | ||||||||
| 1093 | 2 | 20 | $self->_drop_client($client, 'read error: ' . ($! || 'unknown error')); | |||||
| 1094 | 2 | 6 | return; | |||||
| 1095 | } | |||||||
| 1096 | ||||||||
| 1097 | 108 | 116 | if ($read == 0) { | |||||
| 1098 | 17 | 32 | $self->_drop_client($client, 'client disconnected'); | |||||
| 1099 | 17 | 22 | return; | |||||
| 1100 | } | |||||||
| 1101 | ||||||||
| 1102 | 91 | 132 | $client->{buffer} .= $chunk; | |||||
| 1103 | 91 | 70 | my $completed = 0; | |||||
| 1104 | ||||||||
| 1105 | 91 | 55 | while (1) { | |||||
| 1106 | # With a token, take_frame checks the frame's digest before it | |||||||
| 1107 | # thaws anything, so an unauthenticated peer never gets as far as | |||||||
| 1108 | # Storable. | |||||||
| 1109 | my ($status, $message, $protocol_error) | |||||||
| 1110 | = Class::Shared::Protocol::take_frame(\$client->{buffer}, $self->{token}, | |||||||
| 1111 | 156 73 | 497 143 | sub { $self->_survives_thaw($_[0]) }); | |||||
| 1112 | ||||||||
| 1113 | 156 | 295 | if ($status == 0) { | |||||
| 1114 | 72 | 60 | last; | |||||
| 1115 | } | |||||||
| 1116 | ||||||||
| 1117 | 84 | 80 | $completed++ if $status > 0; | |||||
| 1118 | ||||||||
| 1119 | 84 | 78 | if ($status < 0) { | |||||
| 1120 | 11 | 16 | $self->_send($client, _failure('protocol', $protocol_error)); | |||||
| 1121 | 11 | 21 | $self->_drop_client($client, $protocol_error); | |||||
| 1122 | 11 | 44 | last; | |||||
| 1123 | } | |||||||
| 1124 | ||||||||
| 1125 | 73 73 | 46 97 | my $response = eval { $self->_dispatch($client, $message) }; | |||||
| 1126 | 73 | 124 | if ($@) { | |||||
| 1127 | 2 | 2 | my $internal = $@; | |||||
| 1128 | 2 | 10 | $internal =~ s/\s+\z//; | |||||
| 1129 | 2 | 4 | $self->_log("internal error while handling a request: $internal", 'error'); | |||||
| 1130 | 2 | 6 | $response = _failure('internal', $internal); | |||||
| 1131 | } | |||||||
| 1132 | ||||||||
| 1133 | 73 | 132 | $self->_send($client, $response) if defined $response; | |||||
| 1134 | ||||||||
| 1135 | 73 | 82 | last if $client->{closed}; | |||||
| 1136 | 71 | 149 | last if $self->{stop}; | |||||
| 1137 | } | |||||||
| 1138 | ||||||||
| 1139 | # _expire_reads spares a connection with bytes waiting, so one that never | |||||||
| 1140 | # stops sending is held to its hello deadline here, once they are read. | |||||||
| 1141 | $self->_drop_client($client, $self->_no_hello_reason) | |||||||
| 1142 | if !$client->{closed} && !$client->{greeted} | |||||||
| 1143 | && defined $client->{greet_by} | |||||||
| 1144 | 91 | 251 | && $client->{greet_by} <= Time::HiRes::time(); | |||||
| 1145 | ||||||||
| 1146 | 91 | 170 | $client->{last_request} = Time::HiRes::time() if $completed; | |||||
| 1147 | 91 | 150 | $self->_account_inbound($client, $completed) unless $client->{closed}; | |||||
| 1148 | 91 | 129 | $self->_trim_log; | |||||
| 1149 | ||||||||
| 1150 | 91 | 76 | return 1; | |||||
| 1151 | } | |||||||
| 1152 | ||||||||
| 1153 | # Purpose: say whether a request can be thawed without killing us. | |||||||
| 1154 | # Entry: $body is an authenticated Storable image. | |||||||
| 1155 | # Exit status: 1 if it is safe to thaw here, 0 if not. | |||||||
| 1156 | # Side effects: for a body over $THAW_UNCHECKED bytes, forks and waits. | |||||||
| 1157 | # Why: Storable::thaw calls itself for each level of nesting and has | |||||||
| 1158 | # no limit it can be relied on to apply, so a few hundred | |||||||
| 1159 | # kilobytes of nested arrays overflow the C stack. That is a | |||||||
| 1160 | # segmentation fault, which eval cannot catch, and every shared | |||||||
| 1161 | # object would be lost with the process. A child with the same | |||||||
| 1162 | # stack finds out first. An ordinary failure to thaw is not its | |||||||
| 1163 | # business: only the child dying is. | |||||||
| 1164 | sub _survives_thaw { | |||||||
| 1165 | 75 | 265 | my ($self, $body) = @_; | |||||
| 1166 | ||||||||
| 1167 | 75 | 197 | return 1 if length($body) <= $THAW_UNCHECKED; | |||||
| 1168 | ||||||||
| 1169 | 2 | 8 | require POSIX; | |||||
| 1170 | 2 | 8 | local ($!, $?, $@); | |||||
| 1171 | 2 | 18 | local $SIG{CHLD} = 'DEFAULT'; | |||||
| 1172 | ||||||||
| 1173 | 2 | 5978 | my $pid = fork; | |||||
| 1174 | 2 | 110 | if (!defined $pid) { | |||||
| 1175 | 0 | 0 | $self->_log("refused a request: cannot fork to check it: $!", 'warn'); | |||||
| 1176 | 0 | 0 | return 0; | |||||
| 1177 | } | |||||||
| 1178 | ||||||||
| 1179 | 2 | 51 | if (!$pid) { | |||||
| 1180 | 0 | 0 | local $SIG{ALRM} = 'DEFAULT'; | |||||
| 1181 | 0 | 0 | local $SIG{SEGV} = 'DEFAULT'; | |||||
| 1182 | 0 | 0 | alarm $THAW_TRIAL_TIMEOUT; | |||||
| 1183 | ||||||||
| 1184 | # A hostile request must not be able to fill the disk with core | |||||||
| 1185 | # files, each as large as the backend. | |||||||
| 1186 | 0 | 0 | if (open(my $filter, '>', '/proc/self/coredump_filter')) { | |||||
| 1187 | 0 0 | 0 0 | print {$filter} '0'; | |||||
| 1188 | 0 | 0 | close($filter); | |||||
| 1189 | } | |||||||
| 1190 | 0 | 0 | chdir('/'); | |||||
| 1191 | ||||||||
| 1192 | # Held until the exit, so that no DESTROY runs in this copy. | |||||||
| 1193 | 0 0 | 0 0 | my $held = eval { Storable::thaw($body) }; | |||||
| 1194 | 0 | 0 | POSIX::_exit(0); | |||||
| 1195 | } | |||||||
| 1196 | ||||||||
| 1197 | 2 | 6570 | 1 while waitpid($pid, 0) == -1 && $!{EINTR}; | |||||
| 1198 | ||||||||
| 1199 | 2 | 110 | return $? == 0 ? 1 : 0; | |||||
| 1200 | } | |||||||
| 1201 | ||||||||
| 1202 | # The connection owns its objects: when it goes, they go, and the target's | |||||||
| 1203 | # DESTROY runs here rather than being lost with a dead client. | |||||||
| 1204 | sub _drop_client { | |||||||
| 1205 | 70 | 3386 | my ($self, $client, $reason) = @_; | |||||
| 1206 | ||||||||
| 1207 | 70 | 92 | return 1 if $client->{closed}; | |||||
| 1208 | ||||||||
| 1209 | 68 | 286 | $self->_log('dropped a client: ' . (defined $reason && length $reason ? $reason : 'no reason given'), 'warn'); | |||||
| 1210 | ||||||||
| 1211 | # Whatever was waiting to be written goes with the connection: there is | |||||||
| 1212 | # nobody left to read it. | |||||||
| 1213 | 68 | 117 | $self->{queued} -= length $client->{outbuf}; | |||||
| 1214 | 68 | 101 | $self->{queued} = 0 if $self->{queued} < 0; | |||||
| 1215 | ||||||||
| 1216 | 68 | 64 | $client->{closed} = 1; | |||||
| 1217 | 68 | 78 | $client->{outbuf} = ''; | |||||
| 1218 | 68 | 69 | $client->{stalled_since} = undef; | |||||
| 1219 | 68 | 51 | undef $client->{buffer}; | |||||
| 1220 | 68 | 51 | $client->{buffer} = ''; | |||||
| 1221 | 68 68 | 53 72 | delete @{$client}{qw(partial_started partial_progress)}; | |||||
| 1222 | ||||||||
| 1223 | 68 | 91 | my $owned = $client->{objects} || {}; | |||||
| 1224 | 68 68 | 51 96 | for my $id (keys %{$owned}) { | |||||
| 1225 | 18 | 54 | delete $self->{objects}{$id}; | |||||
| 1226 | } | |||||||
| 1227 | 68 68 | 74 58 | %{$owned} = (); | |||||
| 1228 | ||||||||
| 1229 | 68 | 81 | my $fd = fileno($client->{fh}); | |||||
| 1230 | 68 | 247 | $self->_close($client->{fh}, 'a client connection'); | |||||
| 1231 | 68 | 2692 | delete $self->{clients}{$fd} if defined $fd; | |||||
| 1232 | ||||||||
| 1233 | 68 | 85 | return 1; | |||||
| 1234 | } | |||||||
| 1235 | ||||||||
| 1236 | sub _send { | |||||||
| 1237 | 82 | 53192 | my ($self, $client, $message) = @_; | |||||
| 1238 | ||||||||
| 1239 | 82 | 129 | return if $client->{closed}; | |||||
| 1240 | ||||||||
| 1241 | 80 | 143 | my ($bytes, $encode_error) = Class::Shared::Protocol::encode_frame($message, $self->{token}); | |||||
| 1242 | ||||||||
| 1243 | 80 | 103 | if (!defined $bytes) { | |||||
| 1244 | 6 | 4 | my $error = $encode_error; | |||||
| 1245 | ($bytes) = Class::Shared::Protocol::encode_frame( | |||||||
| 1246 | _failure('protocol', $error), | |||||||
| 1247 | $self->{token}, | |||||||
| 1248 | 6 | 6 | ); | |||||
| 1249 | ||||||||
| 1250 | # Neither the reply nor the frame saying it could not be sent can be | |||||||
| 1251 | # encoded, so this client will never hear anything: say so here. | |||||||
| 1252 | 6 | 12 | if (!defined $bytes) { | |||||
| 1253 | 4 | 16 | $self->_log("cannot encode a reply: " . ($encode_error || 'unknown error'), 'error'); | |||||
| 1254 | 4 | 12 | return; | |||||
| 1255 | } | |||||||
| 1256 | } | |||||||
| 1257 | ||||||||
| 1258 | # Measure the queues before any of this reply goes out, so the limits are on | |||||||
| 1259 | # what the backend is holding and not on how much of it the kernel happened | |||||||
| 1260 | # to take. | |||||||
| 1261 | 76 | 70 | my $length = length $bytes; | |||||
| 1262 | 76 | 94 | my $queued = length($client->{outbuf}) + $length; | |||||
| 1263 | ||||||||
| 1264 | 76 | 88 | if ($queued > $self->{max_queued}) { | |||||
| 1265 | 4 | 16 | $self->_drop_client($client, "a reply of $length bytes leaves $queued " | |||||
| 1266 | . "waiting to be written, more than the $self->{max_queued} a client may hold"); | |||||||
| 1267 | 4 | 10 | return; | |||||
| 1268 | } | |||||||
| 1269 | ||||||||
| 1270 | # One client's bound is not the process's: a few hundred clients that each | |||||||
| 1271 | # stay under max_queued would still add up to more memory than there is. | |||||||
| 1272 | 72 | 100 | if ($self->{queued} + $length > $self->{max_queued_total}) { | |||||
| 1273 | $self->_drop_client($client, "a reply of $length bytes would leave " | |||||||
| 1274 | 2 | 8 | . ($self->{queued} + $length) . ' queued across all clients, more than ' | |||||
| 1275 | . "the $self->{max_queued_total} the backend may hold"); | |||||||
| 1276 | 2 | 4 | return; | |||||
| 1277 | } | |||||||
| 1278 | ||||||||
| 1279 | # The stall clock belongs to the queue, and it starts with it: this is the | |||||||
| 1280 | # only place a queue begins. _flush restarts it on every write that takes | |||||||
| 1281 | # bytes out and clears it when the queue empties; nothing else sets it, so a | |||||||
| 1282 | # waiting reply can only get older, never fresher. A reply added to a queue | |||||||
| 1283 | # that is already waiting does not get a new deadline. | |||||||
| 1284 | $client->{stalled_since} = Time::HiRes::time() | |||||||
| 1285 | 70 | 144 | unless length $client->{outbuf}; | |||||
| 1286 | ||||||||
| 1287 | 70 | 92 | $client->{outbuf} .= $bytes; | |||||
| 1288 | 70 | 54 | $self->{queued} += $length; | |||||
| 1289 | ||||||||
| 1290 | 70 | 108 | $self->_flush($client); | |||||
| 1291 | ||||||||
| 1292 | 70 | 71 | return; | |||||
| 1293 | } | |||||||
| 1294 | ||||||||
| 1295 | # Write as much of a client's queue as the socket will take right now. What is | |||||||
| 1296 | # left waits for the loop, which asks for writability again rather than | |||||||
| 1297 | # sitting here until the client reads. | |||||||
| 1298 | sub _flush { | |||||||
| 1299 | 88 | 67 | my ($self, $client) = @_; | |||||
| 1300 | ||||||||
| 1301 | 88 | 187 | return if $client->{closed} || !length $client->{outbuf}; | |||||
| 1302 | ||||||||
| 1303 | # errno outlives a call, and a TLS write can fail without touching it. | |||||||
| 1304 | 78 | 78 | $! = 0; | |||||
| 1305 | ||||||||
| 1306 | 78 | 362 | my $written = syswrite($client->{fh}, $client->{outbuf}); | |||||
| 1307 | ||||||||
| 1308 | 78 | 2021 | if (!defined $written) { | |||||
| 1309 | 8 | 16 | if ($self->_would_block($client->{fh}, 'write')) { | |||||
| 1310 | # Nothing went out, so the deadline does not move: a socket that keeps | |||||||
| 1311 | # taking nothing stays on the clock of its last progress instead of | |||||||
| 1312 | # being handed a fresh one every time the loop tries it again. | |||||||
| 1313 | 4 | 38 | return; | |||||
| 1314 | } | |||||||
| 1315 | ||||||||
| 1316 | 4 | 30 | $self->_drop_client($client, 'write error: ' . ($! || 'unknown error')); | |||||
| 1317 | 4 | 10 | return; | |||||
| 1318 | } | |||||||
| 1319 | ||||||||
| 1320 | # A socket that takes nothing and reports no error would keep the fd in the | |||||||
| 1321 | # writable set for ever, spinning the loop on a queue that never shrinks. | |||||||
| 1322 | 70 | 77 | if ($written == 0) { | |||||
| 1323 | 2 | 4 | $self->_drop_client($client, 'write error: peer closed the connection'); | |||||
| 1324 | 2 | 8 | return; | |||||
| 1325 | } | |||||||
| 1326 | ||||||||
| 1327 | 68 | 84 | substr($client->{outbuf}, 0, $written, ''); | |||||
| 1328 | 68 | 64 | $self->{queued} -= $written; | |||||
| 1329 | ||||||||
| 1330 | # Progress, so the clock starts again -- or stops, if there is nothing left | |||||||
| 1331 | # to wait for. _send started it when it made the queue; _expire_writes only | |||||||
| 1332 | # reads it; those two lines and this one are the whole of the rule. | |||||||
| 1333 | 68 | 90 | $client->{stalled_since} = length $client->{outbuf} ? Time::HiRes::time() : undef; | |||||
| 1334 | ||||||||
| 1335 | # As for requests: an emptied queue should not keep a large reply's memory. | |||||||
| 1336 | 68 | 87 | if (!length $client->{outbuf}) { | |||||
| 1337 | 66 | 48 | undef $client->{outbuf}; | |||||
| 1338 | 66 | 67 | $client->{outbuf} = ''; | |||||
| 1339 | } | |||||||
| 1340 | ||||||||
| 1341 | # Anything still queued puts the fd back in the loop's writable set. | |||||||
| 1342 | 68 | 81 | return; | |||||
| 1343 | } | |||||||
| 1344 | ||||||||
| 1345 | # ------------------------------------------------------------- request ops | |||||||
| 1346 | ||||||||
| 1347 | # Purpose: build the reply that says a request failed, so every refusal | |||||||
| 1348 | # has the same shape and a client can rely on ok, kind and error. | |||||||
| 1349 | # Entry: $kind is the machine-readable category (protocol, busy, die, | |||||||
| 1350 | # forbidden, ...); $error is the text for a person. | |||||||
| 1351 | # Exit status: a hash reference { ok => 0, kind => $kind, error => $error }. | |||||||
| 1352 | # Side effects: none. | |||||||
| 1353 | sub _failure { | |||||||
| 1354 | 231 | 1424177 | my ($kind, $error) = @_; | |||||
| 1355 | ||||||||
| 1356 | 231 | 558 | return { ok => 0, kind => $kind, error => $error }; | |||||
| 1357 | } | |||||||
| 1358 | ||||||||
| 1359 | sub _dispatch { | |||||||
| 1360 | 120 | 17562 | my ($self, $client, $message) = @_; | |||||
| 1361 | ||||||||
| 1362 | 120 | 160 | if (ref($message) ne 'HASH') { | |||||
| 1363 | 11 | 12 | return _failure('protocol', 'request is not a hash reference'); | |||||
| 1364 | } | |||||||
| 1365 | ||||||||
| 1366 | 109 | 140 | my $op = defined $message->{op} ? $message->{op} : ''; | |||||
| 1367 | ||||||||
| 1368 | 109 | 110 | if ($op eq 'hello') { | |||||
| 1369 | 25 | 46 | return $self->_op_hello($client, $message); | |||||
| 1370 | } | |||||||
| 1371 | ||||||||
| 1372 | 84 | 82 | if (!$client->{greeted}) { | |||||
| 1373 | 15 | 18 | return _failure('protocol', 'handshake required'); | |||||
| 1374 | } | |||||||
| 1375 | ||||||||
| 1376 | 69 | 85 | return $self->_op_new($client, $message) if $op eq 'new'; | |||||
| 1377 | 58 | 69 | return $self->_op_call($client, $message) if $op eq 'call'; | |||||
| 1378 | 43 | 72 | return $self->_op_ping if $op eq 'ping'; | |||||
| 1379 | 28 | 34 | return $self->_op_shutdown if $op eq 'shutdown'; | |||||
| 1380 | ||||||||
| 1381 | 21 | 22 | return _failure('protocol', "unknown operation '$op'"); | |||||
| 1382 | } | |||||||
| 1383 | ||||||||
| 1384 | sub _op_hello { | |||||||
| 1385 | 82 | 35190 | my ($self, $client, $message) = @_; | |||||
| 1386 | ||||||||
| 1387 | # One hello per connection. A second would change the class of a | |||||||
| 1388 | # connection that may already hold objects, leaving them of a class the | |||||||
| 1389 | # connection no longer names. | |||||||
| 1390 | return _failure('protocol', 'hello has already been accepted on this connection') | |||||||
| 1391 | 82 | 95 | if $client->{greeted}; | |||||
| 1392 | ||||||||
| 1393 | # Compared as text, not as a number. As a number, "2x" or " 2" would pass | |||||||
| 1394 | # as 2 (and "x" would warn), and a reference would be compared by its | |||||||
| 1395 | # address. The version is written the one way, so only that way is | |||||||
| 1396 | # accepted. | |||||||
| 1397 | 78 | 191 | my $proto = defined $message->{proto} && !ref $message->{proto} ? $message->{proto} : 0; | |||||
| 1398 | ||||||||
| 1399 | 78 | 88 | if ($proto ne $Class::Shared::PROTOCOL_VERSION) { | |||||
| 1400 | 38 | 60 | return _failure('protocol', | |||||
| 1401 | "protocol version mismatch: client speaks $proto, this backend speaks " | |||||||
| 1402 | . $Class::Shared::PROTOCOL_VERSION); | |||||||
| 1403 | } | |||||||
| 1404 | ||||||||
| 1405 | # A client may name the class it wants here, and then this connection is | |||||||
| 1406 | # for objects of that class. A client that names none is welcome too: that | |||||||
| 1407 | # is how the admin commands ask a backend how it is without asking for | |||||||
| 1408 | # anything to be loaded. | |||||||
| 1409 | 40 | 35 | my $wanted = $message->{class}; | |||||
| 1410 | ||||||||
| 1411 | 40 | 80 | if (defined $wanted && length $wanted) { | |||||
| 1412 | 29 29 15 | 25 52 12 | my $valid = eval { Class::Shared::validate_class($wanted); 1 }; | |||||
| 1413 | 29 | 28 | if (!$valid) { | |||||
| 1414 | 14 | 16 | my $error = $@ || 'bad class name'; | |||||
| 1415 | 14 | 42 | $error =~ s/\s+\z//; | |||||
| 1416 | 14 | 16 | return _failure('protocol', $error); | |||||
| 1417 | } | |||||||
| 1418 | ||||||||
| 1419 | 15 | 36 | my ($loaded, $load_error) = $self->_load_class($wanted); | |||||
| 1420 | 15 | 31 | return _failure('unknown_class', $load_error) | |||||
| 1421 | unless $loaded; | |||||||
| 1422 | ||||||||
| 1423 | 13 | 13 | $client->{class} = $wanted; | |||||
| 1424 | } | |||||||
| 1425 | ||||||||
| 1426 | 24 | 26 | $client->{greeted} = 1; | |||||
| 1427 | ||||||||
| 1428 | return { | |||||||
| 1429 | ok => 1, | |||||||
| 1430 | class => $client->{class}, | |||||||
| 1431 | 24 | 121 | pid => $$, | |||||
| 1432 | proto => $Class::Shared::PROTOCOL_VERSION, | |||||||
| 1433 | version => $Class::Shared::VERSION, | |||||||
| 1434 | }; | |||||||
| 1435 | } | |||||||
| 1436 | ||||||||
| 1437 | sub _op_new { | |||||||
| 1438 | 38 | 10484 | my ($self, $client, $message) = @_; | |||||
| 1439 | ||||||||
| 1440 | 38 | 537 | my $class = $client->{class}; | |||||
| 1441 | 38 | 42 | return _failure('protocol', $NO_CLASS_ERROR) unless defined $class; | |||||
| 1442 | ||||||||
| 1443 | 36 | 29 | my $args = $message->{args}; | |||||
| 1444 | 36 | 36 | $args = [] unless defined $args; | |||||
| 1445 | ||||||||
| 1446 | 36 | 41 | return _failure('protocol', 'new: args must be an array reference') | |||||
| 1447 | unless ref($args) eq 'ARRAY'; | |||||||
| 1448 | ||||||||
| 1449 | 28 28 | 21 37 | my $held = keys %{$self->{objects}}; | |||||
| 1450 | 28 | 34 | if ($held >= $self->{max_objects}) { | |||||
| 1451 | 2 | 6 | return _failure('busy', "this backend already holds $held objects, its limit"); | |||||
| 1452 | } | |||||||
| 1453 | ||||||||
| 1454 | 26 | 11 | my $object; | |||||
| 1455 | 26 26 26 | 73 19 65 | my ($built, $error, $timed_out) = $self->_limited(sub { $object = $class->new(@{$args}) }); | |||||
| 1456 | 26 | 41 | return $self->_timed_out("$class->new") if $timed_out; | |||||
| 1457 | 26 | 29 | return _failure('die', $error) unless $built; | |||||
| 1458 | ||||||||
| 1459 | 22 | 24 | return _failure('protocol', "$class->new did not return an object") unless ref($object); | |||||
| 1460 | ||||||||
| 1461 | 20 | 23 | my $id = $self->{next_id}++; | |||||
| 1462 | ||||||||
| 1463 | $self->{objects}{$id} = { | |||||||
| 1464 | object => $object, | |||||||
| 1465 | owner => $client->{serial}, | |||||||
| 1466 | 20 | 48 | }; | |||||
| 1467 | 20 | 20 | $client->{objects}{$id} = 1; | |||||
| 1468 | 20 | 16 | $self->{constructed}++; | |||||
| 1469 | ||||||||
| 1470 | 20 | 52 | return { ok => 1, id => $id, class => $class }; | |||||
| 1471 | } | |||||||
| 1472 | ||||||||
| 1473 | sub _op_call { | |||||||
| 1474 | 126 | 9026 | my ($self, $client, $message) = @_; | |||||
| 1475 | ||||||||
| 1476 | 126 | 80 | my $class = $client->{class}; | |||||
| 1477 | 126 | 110 | return _failure('protocol', $NO_CLASS_ERROR) unless defined $class; | |||||
| 1478 | ||||||||
| 1479 | 124 | 89 | my $id = $message->{id}; | |||||
| 1480 | 124 | 376 | return _failure('protocol', 'call: no object id') | |||||
| 1481 | unless defined $id && $id =~ /\A\d+\z/a; # /a: ASCII digits only, as object ids are | |||||||
| 1482 | ||||||||
| 1483 | 106 | 79 | my $entry = $self->{objects}{$id}; | |||||
| 1484 | 106 | 90 | return _failure('unknown_object', | |||||
| 1485 | "no object #$id here; it may have been released or its client has gone") | |||||||
| 1486 | unless $entry; | |||||||
| 1487 | ||||||||
| 1488 | return _failure('forbidden', "object #$id belongs to another connection") | |||||||
| 1489 | 102 | 83 | unless $entry->{owner} == $client->{serial}; | |||||
| 1490 | ||||||||
| 1491 | 100 | 98 | my $object = $entry->{object}; | |||||
| 1492 | ||||||||
| 1493 | 100 | 90 | my $method = $message->{method}; | |||||
| 1494 | 100 | 162 | return _failure('protocol', 'call: no method name') | |||||
| 1495 | unless defined $method && length $method; | |||||||
| 1496 | ||||||||
| 1497 | 96 | 49 | my $args = $message->{args}; | |||||
| 1498 | 96 | 73 | $args = [] unless defined $args; | |||||
| 1499 | 96 | 95 | return _failure('protocol', 'call: args must be an array reference') | |||||
| 1500 | unless ref($args) eq 'ARRAY'; | |||||||
| 1501 | ||||||||
| 1502 | 92 | 49 | my $want = $message->{want}; | |||||
| 1503 | 92 | 67 | $want = 'scalar' unless defined $want; | |||||
| 1504 | 92 | 153 | return _failure('protocol', "call: unknown calling context '$want'") | |||||
| 1505 | unless $want =~ /\A(?:list|scalar|void)\z/; | |||||||
| 1506 | ||||||||
| 1507 | # A method is a plain name. A qualified one ("Other::Package::function") | |||||||
| 1508 | # would be looked up in that package, so a client could call any function | |||||||
| 1509 | # of any loaded module with the object as its first argument, and that | |||||||
| 1510 | # includes ones that write files. can and isa are plain names too. | |||||||
| 1511 | 84 | 108 | return _failure('forbidden', "call: '$method' is not a plain method name") | |||||
| 1512 | unless $method =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/; | |||||||
| 1513 | ||||||||
| 1514 | 70 | 150 | if ($method eq 'new' or $method eq 'DESTROY' or $method eq 'AUTOLOAD') { | |||||
| 1515 | 6 | 8 | return _failure('forbidden', "cannot call $method() through Class::Shared"); | |||||
| 1516 | } | |||||||
| 1517 | ||||||||
| 1518 | # can() and isa() are answered locally as booleans: the code reference | |||||||
| 1519 | # that can() normally returns cannot cross the wire. | |||||||
| 1520 | 64 | 93 | if ($method eq 'can' or $method eq 'isa') { | |||||
| 1521 | 12 | 6 | my $name = $args->[0]; | |||||
| 1522 | ||||||||
| 1523 | # No name is not a class or method the object has; passing undef on | |||||||
| 1524 | # would only make perl warn about it. | |||||||
| 1525 | 12 | 16 | return { ok => 1, result => [0] } unless defined $name; | |||||
| 1526 | ||||||||
| 1527 | 10 10 | 8 26 | my $answer = eval { $object->$method($name) ? 1 : 0 }; | |||||
| 1528 | 10 | 12 | return _failure('die', "$@") if $@; | |||||
| 1529 | 10 | 28 | return { ok => 1, result => [$answer] }; | |||||
| 1530 | } | |||||||
| 1531 | ||||||||
| 1532 | # Asked of the object: a factory's new() may return another class. | |||||||
| 1533 | 52 | 84 | my $target = Scalar::Util::blessed($object) ? $object : $class; | |||||
| 1534 | 52 | 139 | if (!$target->can($method) && !$target->can('AUTOLOAD')) { | |||||
| 1535 | 4 | 6 | return _failure('unknown_method', "$class has no method '$method'"); | |||||
| 1536 | } | |||||||
| 1537 | ||||||||
| 1538 | 48 | 17 | my @result; | |||||
| 1539 | my ($ok, $call_error, $call_timed_out) = $self->_limited(sub { | |||||||
| 1540 | 48 | 67 | if ($want eq 'list') { | |||||
| 1541 | 12 12 | 8 16 | @result = $object->$method(@{$args}); | |||||
| 1542 | } elsif ($want eq 'void') { | |||||||
| 1543 | 4 4 | 2 8 | $object->$method(@{$args}); | |||||
| 1544 | 4 | 4 | @result = (); | |||||
| 1545 | } else { | |||||||
| 1546 | 32 32 | 23 56 | my $scalar = $object->$method(@{$args}); | |||||
| 1547 | 30 | 87 | @result = ($scalar); | |||||
| 1548 | } | |||||||
| 1549 | 48 | 109 | }); | |||||
| 1550 | ||||||||
| 1551 | 48 | 94 | return $self->_timed_out($method) if $call_timed_out; | |||||
| 1552 | 48 | 47 | return _failure('die', $call_error) unless $ok; | |||||
| 1553 | ||||||||
| 1554 | 46 | 27 | $self->{calls}++; | |||||
| 1555 | ||||||||
| 1556 | 46 | 166 | return { ok => 1, result => [@result] }; | |||||
| 1557 | } | |||||||
| 1558 | ||||||||
| 1559 | # Purpose: run one call to a target, stopping it if it takes too long. | |||||||
| 1560 | # Entry: $code is a code reference; call_timeout is a number of | |||||||
| 1561 | # seconds, 0 for no limit. | |||||||
| 1562 | # Exit status: ($ok, $error, $timed_out): $ok is true if $code returned; | |||||||
| 1563 | # $error is what it died with; $timed_out is true if the limit | |||||||
| 1564 | # ended it. | |||||||
| 1565 | # Side effects: uses SIGALRM and the process's one alarm timer for the | |||||||
| 1566 | # length of the call, and leaves it off afterwards. | |||||||
| 1567 | # Why: the backend serves one request at a time, so a call that does | |||||||
| 1568 | # not return holds every client. Perl handles a signal between | |||||||
| 1569 | # two operations, so a call that is inside one long operation | |||||||
| 1570 | # (a system call, a regular expression, an XS function) is | |||||||
| 1571 | # stopped when that operation ends, not before. | |||||||
| 1572 | sub _limited { | |||||||
| 1573 | 88 | 3438 | my ($self, $code) = @_; | |||||
| 1574 | ||||||||
| 1575 | 88 | 81 | my $limit = $self->{call_timeout}; | |||||
| 1576 | 88 | 57 | my $timed_out = 0; | |||||
| 1577 | 88 | 48 | my ($ok, $error); | |||||
| 1578 | ||||||||
| 1579 | { | |||||||
| 1580 | 88 88 | 50 86 | local $@; | |||||
| 1581 | 88 6 6 | 421 4000210 72 | local $SIG{ALRM} = sub { $timed_out = 1; die "call timed out\n" }; | |||||
| 1582 | ||||||||
| 1583 | 88 | 305 | Time::HiRes::alarm($limit) if $limit; | |||||
| 1584 | ||||||||
| 1585 | # The timer is switched off inside the eval as well, so that it cannot | |||||||
| 1586 | # fire in the gap between the call returning and the line after it. | |||||||
| 1587 | 88 88 76 74 | 60 80 4402985 63 | $ok = eval { $code->(); Time::HiRes::alarm(0) if $limit; 1 }; | |||||
| 1588 | 88 | 88 | $error = "$@"; | |||||
| 1589 | ||||||||
| 1590 | 88 | 475 | Time::HiRes::alarm(0) if $limit; | |||||
| 1591 | } | |||||||
| 1592 | ||||||||
| 1593 | # A target that caught the timeout and carried on has still overrun it. | |||||||
| 1594 | 88 | 89 | $ok = 0 if $timed_out; | |||||
| 1595 | ||||||||
| 1596 | 88 | 181 | return ($ok ? 1 : 0, $error, $timed_out); | |||||
| 1597 | } | |||||||
| 1598 | ||||||||
| 1599 | # Purpose: the reply, and the log line, for a call that was stopped. | |||||||
| 1600 | # Entry: $what names the call (a method, or CLASS->new). | |||||||
| 1601 | # Exit status: a failure reply of kind 'timeout'. | |||||||
| 1602 | # Side effects: logs one line. | |||||||
| 1603 | sub _timed_out { | |||||||
| 1604 | 2 | 1134 | my ($self, $what) = @_; | |||||
| 1605 | ||||||||
| 1606 | 2 | 6 | my $message = "$what took longer than call_timeout ($self->{call_timeout} seconds) and was stopped"; | |||||
| 1607 | 2 | 4 | $self->_log($message); | |||||
| 1608 | ||||||||
| 1609 | 2 | 10 | return _failure('timeout', $message); | |||||
| 1610 | } | |||||||
| 1611 | ||||||||
| 1612 | sub _op_ping { | |||||||
| 1613 | 20 | 6034 | my $self = shift; | |||||
| 1614 | ||||||||
| 1615 | return { | |||||||
| 1616 | ok => 1, | |||||||
| 1617 | 20 | 58 | classes => [sort keys %{$self->{classes}}], | |||||
| 1618 | queued => $self->{queued}, | |||||||
| 1619 | max_queued_total => $self->{max_queued_total}, | |||||||
| 1620 | pid => $$, | |||||||
| 1621 | proto => $Class::Shared::PROTOCOL_VERSION, | |||||||
| 1622 | version => $Class::Shared::VERSION, | |||||||
| 1623 | address => $self->{address}, | |||||||
| 1624 | calls => $self->{calls}, | |||||||
| 1625 | 20 | 26 | objects => scalar(keys %{$self->{objects}}), | |||||
| 1626 | constructed => $self->{constructed}, | |||||||
| 1627 | 20 | 129 | clients => scalar(keys %{$self->{clients}}), | |||||
| 1628 | started => $self->{started}, | |||||||
| 1629 | uptime => time - $self->{started}, | |||||||
| 1630 | 20 | 18 | }; | |||||
| 1631 | } | |||||||
| 1632 | ||||||||
| 1633 | sub _op_shutdown { | |||||||
| 1634 | 8 | 7 | my $self = shift; | |||||
| 1635 | ||||||||
| 1636 | 8 | 17 | $self->_log('shutdown requested'); | |||||
| 1637 | 8 | 28 | $self->{stop} = 1; | |||||
| 1638 | ||||||||
| 1639 | 8 | 16 | return { ok => 1, message => 'shutting down' }; | |||||
| 1640 | } | |||||||
| 1641 | ||||||||
| 1642 | # ---------------------------------------------------------------- plumbing | |||||||
| 1643 | ||||||||
| 1644 | sub _cleanup { | |||||||
| 1645 | 56 | 1099 | my $self = shift; | |||||
| 1646 | ||||||||
| 1647 | 56 | 124 | return if $self->{cleaned}; | |||||
| 1648 | 54 | 64 | $self->{cleaned} = 1; | |||||
| 1649 | ||||||||
| 1650 | 54 | 78 | if ($self->{listener}) { | |||||
| 1651 | 7 | 18 | $self->_close($self->{listener}, 'the listener'); | |||||
| 1652 | 7 | 14 | $self->{listener} = undef; | |||||
| 1653 | } | |||||||
| 1654 | ||||||||
| 1655 | 54 | 102 | $self->_unlink($self->{socket}) if $self->{owns_socket}; | |||||
| 1656 | ||||||||
| 1657 | 54 54 | 45 140 | for my $client (values %{$self->{clients}}) { | |||||
| 1658 | # A reply that was queued when the backend stopped, such as the one | |||||||
| 1659 | # that asked it to stop, gets one last chance to go out. | |||||||
| 1660 | 10 | 181 | $self->_flush($client) unless $client->{closed}; | |||||
| 1661 | 10 | 15 | $self->_close($client->{fh}, 'a client connection') unless $client->{closed}; | |||||
| 1662 | } | |||||||
| 1663 | ||||||||
| 1664 | # Every object the backend still holds is destroyed here, once, in the | |||||||
| 1665 | # process that created them. | |||||||
| 1666 | 54 54 | 336 109 | %{$self->{objects}} = (); | |||||
| 1667 | 54 54 | 65 139 | %{$self->{clients}} = (); | |||||
| 1668 | ||||||||
| 1669 | # Without the lock the pid file belongs to some other backend. | |||||||
| 1670 | 54 | 140 | if ($self->{lock}) { | |||||
| 1671 | 27 | 88 | $self->_unlink($self->{control} . '.pid'); | |||||
| 1672 | 27 | 421 | flock($self->{lock}, LOCK_UN) | |||||
| 1673 | or $self->_log("cannot release the lock: $!", 'error'); | |||||||
| 1674 | 27 | 94 | $self->_close($self->{lock}, 'the lock file'); | |||||
| 1675 | 27 | 51 | $self->{lock} = undef; | |||||
| 1676 | } | |||||||
| 1677 | ||||||||
| 1678 | 54 | 114 | return 1; | |||||
| 1679 | } | |||||||
| 1680 | ||||||||
| 1681 | sub _daemonize { | |||||||
| 1682 | 11 | 3323 | my $self = shift; | |||||
| 1683 | ||||||||
| 1684 | 11 | 15815 | my $pid = fork; | |||||
| 1685 | 11 | 510 | die "cannot fork: $!\n" unless defined $pid; | |||||
| 1686 | ||||||||
| 1687 | 11 | 236 | if ($pid) { | |||||
| 1688 | # The intermediate child's status is not ours to report: the real | |||||||
| 1689 | # backend reports through the log. waitpid only stops it being left | |||||||
| 1690 | # as a zombie, and fails harmlessly if SIGCHLD is ignored. | |||||||
| 1691 | 7 | 17298 | waitpid($pid, 0); | |||||
| 1692 | 7 | 612 | exit 0; | |||||
| 1693 | } | |||||||
| 1694 | ||||||||
| 1695 | 4 | 127 | require POSIX; | |||||
| 1696 | 4 | 286 | POSIX::setsid() | |||||
| 1697 | or die "cannot start a new session: $!\n"; | |||||||
| 1698 | ||||||||
| 1699 | 4 | 4206 | my $second = fork; | |||||
| 1700 | 4 | 210 | POSIX::_exit(0) if !defined $second || $second > 0; | |||||
| 1701 | ||||||||
| 1702 | 4 | 126 | umask 077; | |||||
| 1703 | ||||||||
| 1704 | 4 | 209 | my ($detached, $detach_error) = Class::Shared::detach_standard_streams($self->{log}); | |||||
| 1705 | 4 | 29 | die "$detach_error\n" unless $detached; | |||||
| 1706 | ||||||||
| 1707 | # The logger names this process in every line, and this is a new one. | |||||||
| 1708 | 4 | 14 | $self->{logger} = undef; | |||||
| 1709 | ||||||||
| 1710 | 4 | 31 | return 1; | |||||
| 1711 | } | |||||||
| 1712 | ||||||||
| 1713 | # Purpose: close a handle and log it if the close fails, so that a failure | |||||||
| 1714 | # is seen once, in the log, instead of being lost. | |||||||
| 1715 | # Entry: $fh is an open handle; $what names it in the message. | |||||||
| 1716 | # Exit status: 1 on success, 0 on failure. | |||||||
| 1717 | # Side effects: closes $fh; may write to the log. | |||||||
| 1718 | sub _close { | |||||||
| 1719 | 130 | 341 | my ($self, $fh, $what) = @_; | |||||
| 1720 | ||||||||
| 1721 | 130 | 917 | return 1 if close($fh); | |||||
| 1722 | ||||||||
| 1723 | 9 | 347 | $self->_log("cannot close $what: " . ($! || 'unknown error'), 'error'); | |||||
| 1724 | ||||||||
| 1725 | 9 | 34 | return 0; | |||||
| 1726 | } | |||||||
| 1727 | ||||||||
| 1728 | # Purpose: remove a file this backend made. A file that is already gone | |||||||
| 1729 | # is what was wanted, so only a real failure is logged. | |||||||
| 1730 | # Entry: $path names the file. | |||||||
| 1731 | # Exit status: 1 if the file is gone afterwards, 0 if it could not be removed. | |||||||
| 1732 | # Side effects: unlinks $path; may write to the log. | |||||||
| 1733 | sub _unlink { | |||||||
| 1734 | 44 | 85 | my ($self, $path) = @_; | |||||
| 1735 | ||||||||
| 1736 | 44 | 876 | return 1 if unlink($path) || $!{ENOENT}; | |||||
| 1737 | ||||||||
| 1738 | 6 | 104 | $self->_log("cannot remove $path: $!", 'error'); | |||||
| 1739 | ||||||||
| 1740 | 6 | 16 | return 0; | |||||
| 1741 | } | |||||||
| 1742 | ||||||||
| 1743 | # Purpose: write one line to the backend's log, through Log::Abstraction. | |||||||
| 1744 | # Entry: $message is the text; $level is a Log::Abstraction level name | |||||||
| 1745 | # ('info' if left out; 'warn' and 'error' for trouble). | |||||||
| 1746 | # Exit status: 1 if the line was handed to the logger, 0 if there is no logger | |||||||
| 1747 | # (the log could not be set up). | |||||||
| 1748 | # Side effects: makes the logger on first use, and again in a new process; | |||||||
| 1749 | # appends to the log file. A failure to log is not reported | |||||||
| 1750 | # anywhere, because the log is where reports go. | |||||||
| 1751 | sub _log { | |||||||
| 1752 | 160 | 3464 | my ($self, $message, $level) = @_; | |||||
| 1753 | ||||||||
| 1754 | 160 | 240 | $level = 'info' unless defined $level; | |||||
| 1755 | ||||||||
| 1756 | 160 | 354 | $self->_trim_log; | |||||
| 1757 | ||||||||
| 1758 | # Some of what is logged is text a client chose (the reason a call died, a | |||||||
| 1759 | # name it asked for). An escape character in it would act on the terminal | |||||||
| 1760 | # of whoever reads the log, so each run of control characters becomes one | |||||||
| 1761 | # space. A new line and a tab are kept: the logger indents the line after | |||||||
| 1762 | # a new line, so it cannot pass for an entry of its own. | |||||||
| 1763 | 160 | 380 | $message =~ s/[\x00-\x08\x0B-\x1F\x7F]+/ /g if defined $message; | |||||
| 1764 | ||||||||
| 1765 | # One logger per process. The line starts with the pid so that the | |||||||
| 1766 | # processes that share a log (the one that spawned the backend, and the | |||||||
| 1767 | # backend) can be told apart, and the pid is part of the format, so a | |||||||
| 1768 | # logger inherited across fork() would name the wrong process. | |||||||
| 1769 | 160 | 410 | if (!defined $self->{logger} || $self->{logger_pid} != $$) { | |||||
| 1770 | # Premise 1: new() always sets log, to the default if it was not given, | |||||||
| 1771 | # so there is nothing to fall back on here. Premise 2: Log::Abstraction | |||||||
| 1772 | # takes a logger that is false in Perl to mean "no logger", and "0" is a | |||||||
| 1773 | # valid file name that is false. Premise 3: an absolute path is never | |||||||
| 1774 | # false. Conclusion: the path is made absolute, which names the same | |||||||
| 1775 | # file as before (a relative path was always opened from the directory | |||||||
| 1776 | # in force at the time) and cannot be mistaken for "no logger". | |||||||
| 1777 | 86 | 287 | my $path = File::Spec->rel2abs($self->{log}); | |||||
| 1778 | ||||||||
| 1779 | 86 | 188 | $self->{logger} = eval { | |||||
| 1780 | 86 | 888 | Log::Abstraction->new( | |||||
| 1781 | logger => $path, | |||||||
| 1782 | level => 'info', | |||||||
| 1783 | format => "[$$] %timestamp% %message%", | |||||||
| 1784 | ); | |||||||
| 1785 | }; | |||||||
| 1786 | 86 | 12518 | $self->{logger_pid} = $$; | |||||
| 1787 | } | |||||||
| 1788 | ||||||||
| 1789 | 160 | 273 | return 0 unless defined $self->{logger}; | |||||
| 1790 | ||||||||
| 1791 | # Log::Abstraction keeps a message to one entry by putting a tab after | |||||||
| 1792 | # each line break, so nothing in a message can pass for a new log line. | |||||||
| 1793 | 159 159 157 | 185 886 83083 | return eval { $self->{logger}->$level($message); 1 } ? 1 : 0; | |||||
| 1794 | } | |||||||
| 1795 | ||||||||
| 1796 | 1; | |||||||
| 1797 | ||||||||