File Coverage

File:blib/lib/Class/Shared/Frontend.pm
Coverage:92.2%

linestmtbranpathcondsubpodtimecode
1package Class::Shared::Frontend;
2
3
68
68
68
156181
46
1357
use strict;
4
68
68
68
141
45
1208
use warnings;
5
6
68
68
68
108
36
568
use Carp ();
7
68
68
68
104
50
4262
use Fcntl qw(:flock O_RDWR O_CREAT);
8
68
68
68
121
59
427
use File::Spec ();
9
68
68
68
81
77
542
use Scalar::Util ();
10
68
68
68
334
1603
2238
use Socket qw(AF_UNIX SOCK_STREAM pack_sockaddr_un);
11
12
68
68
68
100
76
336
use Class::Shared ();
13
68
68
68
4657
73
128775
use Class::Shared::Protocol ();
14
15our $VERSION = '0.001.0';
16
17# Seconds to wait for a backend to start up and answer.
18our $DEFAULT_TIMEOUT = 10;
19
20# How long shared_shutdown waits, in seconds, for the socket to disappear.
21our $SHUTDOWN_WAIT = 5;
22
23# The descriptors a freshly forked backend closes.  Everything from 3 up belongs
24# to the client that forked it, and a daemon must not keep a client's sockets or
25# locks open.
26our $FIRST_INHERITED_FD = 3;
27our $LAST_INHERITED_FD  = 1023;
28
29our $AUTOLOAD;
30
31my %KNOWN_OPTION = map { $_ => 1 } qw(
32        class ctor socket dir host port token token_file autostart timeout log
33        tls_cert tls_key tls_ca tls_fingerprint
34);
35
36# One frontend stands for one object.  The object itself lives in the backend,
37# together with every other object of the same class; the class is loaded there
38# once, however many objects and processes there are.
39sub new {
40
1929
27684607
        my $class = shift;
41
42
1929
1290
        my $target;
43        # An undef first argument is "no class name": it is taken as the target so
44        # that the check below reports it, instead of warning on the lookup.
45
1929
9758
        if (@_ && !ref $_[0] && (!defined $_[0] || !exists $KNOWN_OPTION{$_[0]})) {
46
1861
1617
                $target = shift @_;
47        }
48
49
1929
1385
        my %opt;
50
1929
3303
        if (@_ == 1 && ref($_[0]) eq 'HASH') {
51
23
23
19
28
                %opt = %{ $_[0] };
52        } elsif (@_) {
53
1806
1892
                die "Class::Shared::Frontend->new: expected key/value options\n" if @_ % 2;
54
1780
3484
                %opt = @_;
55        }
56
57
1903
1965
        $target = delete $opt{class} if defined $opt{class};
58
59
1903
3786
        for my $key (sort keys %opt) {
60                die "Class::Shared::Frontend->new: unknown option '$key'\n"
61
4328
3667
                        unless exists $KNOWN_OPTION{$key};
62        }
63
64
1866
3771
        die "Class::Shared::Frontend->new: no class name given\n"
65                unless defined $target && length $target;
66
67
1793
4352
        Class::Shared::validate_class($target);
68
69
1691
2543
        if (defined $opt{ctor} && ref($opt{ctor}) ne 'ARRAY') {
70
27
97
                die "Class::Shared::Frontend->new: ctor must be an array ref\n";
71        }
72
73
1664
3745
        my $transport = (defined $opt{host} || defined $opt{port}) ? 'tcp' : 'unix';
74
75        # A unix socket is mode 0600 in a directory only its owner can write to, so
76        # the kernel has already decided who may connect: a token would add 32 bytes
77        # to every frame and buy nothing.
78        die "Class::Shared::Frontend->new: a unix socket needs no token: "
79                . "$Class::Shared::UNIX_TRUST_REASON\n"
80                if $transport eq 'unix'
81
1664
3606
                        && (defined $opt{token} || defined $opt{token_file});
82
83        die "Class::Shared::Frontend->new: a unix socket needs no TLS: "
84                . "$Class::Shared::UNIX_TRUST_REASON\n"
85                if $transport eq 'unix'
86
1613
5236
2978
5784
                        && grep { defined $opt{$_} && length $opt{$_} }
87                                qw(tls_cert tls_key tls_ca tls_fingerprint);
88
89        # Two sources of one secret: picking one would hide a mistake in the other.
90        die "Class::Shared::Frontend->new: give token or token_file, not both\n"
91
1549
2071
                if defined $opt{token} && defined $opt{token_file};
92
93        my $token = defined $opt{token_file}
94                ? Class::Shared::read_secret($opt{token_file})
95
1534
1521
                : $opt{token};
96
97
1528
1388
        if ($transport eq 'tcp') {
98                die "Class::Shared::Frontend->new: a TCP backend needs both host and port\n"
99
283
690
                        unless defined $opt{host} && defined $opt{port};
100
101                # A port is a whole number in the range the network stack accepts.
102                # Checked before anything is read or connected, so a typo is reported
103                # as a typo rather than as a failure to reach the backend.
104
242
1068
                if ($opt{port} !~ /\A[0-9]+\z/ || $opt{port} < 1 || $opt{port} > 65535) {
105
15
43
                        die "Class::Shared::Frontend->new: port must be a whole number from 1 to 65535\n";
106                }
107                die "Class::Shared::Frontend->new: use either socket or host/port, not both\n"
108
227
320
                        if defined $opt{socket};
109
110                # Verification is not optional, and neither is proving who we are:
111                # tls_cert/tls_key are the certificate the backend will accept from
112                # this client, and tls_ca or tls_fingerprint says how to be sure the
113                # backend is the one we meant.
114                die "Class::Shared::Frontend->new: a TCP backend needs tls_cert and tls_key: "
115                        . "the backend will not accept a client it cannot verify\n"
116
207
414
261
856
                        if grep { !defined $opt{$_} || !length $opt{$_} } qw(tls_cert tls_key);
117
118                die "Class::Shared::Frontend->new: a TCP backend needs tls_ca or "
119                        . "tls_fingerprint: without one it cannot verify the backend\n"
120                        unless (defined $opt{tls_ca} && length $opt{tls_ca})
121
140
452
                                || (defined $opt{tls_fingerprint} && length $opt{tls_fingerprint});
122
123                die "Class::Shared::Frontend->new: give tls_ca or tls_fingerprint, "
124                        . "not both: a CA and a pin are alternatives\n"
125                        if (defined $opt{tls_ca} && length $opt{tls_ca})
126
112
436
                                && (defined $opt{tls_fingerprint} && length $opt{tls_fingerprint});
127        }
128
129        my $socket_path = $transport eq 'unix'
130                ? (defined $opt{socket} && length $opt{socket}
131                        ? Class::Shared::check_socket_path($opt{socket})
132
1342
4364
                        : Class::Shared::socket_path($opt{dir}))
133                : undef;
134
135        my $self = bless {
136                class       => $target,
137                transport   => $transport,
138                socket_path => $socket_path,
139                host        => $opt{host},
140                port        => $opt{port},
141                token       => $token,
142                tls_cert    => $opt{tls_cert},
143                tls_key     => $opt{tls_key},
144                tls_ca      => $opt{tls_ca},
145                tls_fingerprint => (defined $opt{tls_fingerprint} && length $opt{tls_fingerprint})
146                        ? Class::Shared::normalise_fingerprint($opt{tls_fingerprint})
147                        : undef,
148                ctor        => $opt{ctor} || [],
149                autostart   => exists $opt{autostart} ? $opt{autostart} : 1,
150                timeout     => defined $opt{timeout} ? $opt{timeout} : $DEFAULT_TIMEOUT,
151                # Only a unix backend is ever started from here, so only it has a log.
152                log         => defined $opt{log} && length $opt{log} ? $opt{log}
153
1325
15326
                        : $transport eq 'unix' ? "$socket_path.log" : undef,
154                sock        => undef,
155                pid         => undef,
156                id          => undef,
157                last_error  => undef,
158        }, $class;
159
160
1319
2719
        $self->_connect;
161
162
504
3054
        return $self;
163}
164
165# ---------------------------------------------------------------- accessors
166
167
69
16713
sub shared_class { $_[0]->{class} }
168
169# The unix socket in use, or undef when talking to a TCP backend.
170
91
2117716
sub shared_socket_path { $_[0]->{socket_path} }
171
172# A socket path or host:port, whichever this frontend talks to.
173sub shared_address {
174
890
4006
        my $self = shift;
175        return $self->{transport} eq 'tcp'
176                ? $self->{host} . ':' . $self->{port}
177
890
2799
                : $self->{socket_path};
178}
179
180# Process id of the backend, and the id of this object inside it.
181
236
11419
sub shared_pid { $_[0]->{pid} }
182
97
8687
sub shared_id  { $_[0]->{id} }
183
184
115
25397
sub shared_connected { defined $_[0]->{sock} ? 1 : 0 }
185
186
47
1201
sub shared_last_error { $_[0]->{last_error} }
187
188# Explicit dispatch, for method names that clash with the accessors above
189# (or with new()).
190sub shared_call {
191
145
45126
        my $self = shift;
192
145
135
        my $method = shift;
193
194
145
498
        die "Class::Shared::Frontend->shared_call: no method name given\n"
195                unless defined $method && length $method;
196
197
111
175
        return $self->_invoke_as_called($method, \@_);
198}
199
200sub shared_status {
201
164
2569307
        my $self = shift;
202
203
164
562
        return $self->_request({ op => 'ping' });
204}
205
206# Close the connection.  The object goes with it: the backend destroys
207# everything a connection created when that connection goes away, which is
208# also what happens if this process dies without closing anything.
209sub shared_close {
210
512
32280
        my $self = shift;
211
212
512
802
        return 0 unless $self->{sock};
213
214        # The state is cleared whether or not the close worked: the connection is
215        # unusable either way, and a caller must not be left holding half of one.
216        # It is cleared first: a failed close carps, and Carp calls can() on the
217        # objects in the call stack, which would otherwise send a request down the
218        # handle that is being closed.
219
476
469
        my $sock = $self->{sock};
220
476
453
        $self->{sock} = undef;
221
476
383
        $self->{id} = undef;
222
476
511
        $self->{pid} = undef;
223
476
819
        $self->_close($sock, 'the connection to the backend');
224
225
476
3968
        return 1;
226}
227
228sub DESTROY {
229
1562
40963801
        my $self = shift;
230
1562
1916
        $self->shared_close if $self->{sock};
231
1562
8305
        return;
232}
233
234# Ask the backend to stop.  That destroys every object it holds, including
235# other clients' objects, so it is an administrative operation, not something
236# a normal client does.
237sub shared_shutdown {
238        # Evals below must not leave their errors in the caller's $@.
239
214
3874965
        local $@;
240
214
265
        my $self = shift;
241
242
214
436
        return 0 unless $self->{sock};
243
244
194
194
195
668
        my $response = eval { $self->_request({ op => 'shutdown' }) };
245
194
1048
        my $error = $@;
246
247
194
506
        $self->shared_close;
248
249
194
889
        if ($self->{transport} eq 'unix') {
250
181
238
                my $deadline = time + $SHUTDOWN_WAIT;
251
181
2083
                while (-e $self->{socket_path} && time < $deadline) {
252
1240
2293
                        Class::Shared::poll_pause();
253                }
254        }
255
256
194
596
        die $error if $error;
257
258
182
960
        return $response->{ok} ? 1 : 0;
259}
260
261# ------------------------------------------------------------- dispatching
262
263sub AUTOLOAD {
264
642
583277
        my $self = shift;
265
266
642
595
        my $method = $AUTOLOAD;
267
642
2181
        $method =~ s/\A.*:://;
268
269
642
910
        return if $method eq 'DESTROY';
270
271
636
672
        die "Class::Shared::Frontend: '$method' called on something that is not a Class::Shared::Frontend object\n"
272                unless ref $self;
273
274
623
1211
        return $self->_invoke_as_called($method, \@_);
275}
276
277# can() and isa() are inherited from UNIVERSAL, which would answer for the
278# frontend rather than for the class it stands in for, so both are overridden.
279sub can {
280        # Evals below must not leave their errors in the caller's $@.
281
188
13581
        local $@;
282
188
283
        my ($self, $method) = @_;
283
284
188
273
        return UNIVERSAL::can($self, $method) unless ref $self;
285
161
204
        return undef unless defined $method;
286
287        # The frontend's own methods are answered locally and honestly.
288
154
471
        my $local = UNIVERSAL::can('Class::Shared::Frontend', $method);
289
154
195
        return $local if $local;
290
291
124
108
        my $response = eval {
292
124
9527
                $self->_request({
293                        op     => 'call',
294                        method => 'can',
295                        args   => [$method],
296                        want   => 'scalar',
297                });
298        };
299
300
124
843
        return undef unless $response && $response->{ok};
301
85
454
        return undef unless ref($response->{result}) eq 'ARRAY' && $response->{result}[0];
302
303        # Answer the way can() normally does: with something callable.
304        return sub {
305
40
14120
                shift if @_ && ref($_[0])
306                        && Scalar::Util::refaddr($_[0]) == Scalar::Util::refaddr($self);
307
308
40
63
                return $self->_invoke_as_called($method, \@_);
309
34
200
        };
310}
311
312sub isa {
313        # Evals below must not leave their errors in the caller's $@.
314
154
10855
        local $@;
315
154
172
        my ($self, $class) = @_;
316
317
154
203
        return UNIVERSAL::isa($self, $class) unless ref $self;
318
319        # UNIVERSAL::isa warns about an undefined class; no class is not a parent.
320
135
134
        return 0 unless defined $class;
321
322
122
309
        return 1 if $class eq 'Class::Shared::Frontend' or $class eq 'UNIVERSAL';
323
324
74
41
        my $response = eval {
325
74
156
                $self->_request({
326                        op     => 'call',
327                        method => 'isa',
328                        args   => [$class],
329                        want   => 'scalar',
330                });
331        };
332
333
74
245
        return 0 unless $response && $response->{ok};
334
335
56
209
        return ref($response->{result}) eq 'ARRAY' && $response->{result}[0] ? 1 : 0;
336}
337
338# Purpose:       Run $method in the backend in the context this routine's own
339#                caller used, so list, scalar and void calls behave as if the
340#                target object were local.  Three entry points need exactly this.
341# Entry:         $self is a connected frontend; $args is an array ref.
342# Exit status:   the call's results, shaped by the caller's context; dies as
343#                _invoke does.
344# Side effects:  one round trip to the backend.  Called as the last expression
345#                of its caller (return $self->_invoke_as_called(...)) so that
346#                wantarray here is the caller's context.
347sub _invoke_as_called {
348
784
22862
        my ($self, $method, $args) = @_;
349
350
784
781
        my $want = wantarray;
351
784
1097
        my $context = $want ? 'list' : defined($want) ? 'scalar' : 'void';
352
353
784
884
        my $result = $self->_invoke($method, $args, $context);
354
355
610
89
843
303
        return @{$result} if $context eq 'list';
356
521
488
        return if $context eq 'void';
357
411
1941
        return $result->[0];
358}
359
360sub _invoke {
361
715
10432
        my ($self, $method, $args, $context) = @_;
362
363
715
2264
        my $response = $self->_request({
364                op     => 'call',
365                method => $method,
366                args   => $args,
367                want   => $context,
368        });
369
370
644
1279
        if (!$response->{ok}) {
371
119
147
                my $error = $response->{error};
372
119
397
                $error = "Class::Shared: the backend for '$self->{class}' rejected '$method'"
373                        unless defined $error && length $error;
374
375                # Thrown again with its original text (see the POD): without a final
376                # new line die would add this file and line to it.
377
119
335
                $error .= "\n" unless $error =~ /\n\z/;
378
119
573
                die $error;
379        }
380
381
525
424
        my $result = $response->{result};
382
525
578
        return [] unless ref($result) eq 'ARRAY';
383
384
502
605
        return $result;
385}
386
387# --------------------------------------------------------------- transport
388
389sub _connect {
390
1255
8704
        my $self = shift;
391
392
1255
2125
        my $sock = $self->_greet;
393
394
1245
1506
        if (!$sock) {
395
957
1275
                my $reason = $self->{last_error} || 'no backend';
396
397                die "Class::Shared: cannot reach a backend at "
398                        . $self->shared_address . ": $reason\n"
399
957
1812
                        unless $self->{autostart} && $self->{transport} eq 'unix';
400
401
230
631
                $sock = $self->_spawn_backend;
402
403                die "Class::Shared: could not start a backend: "
404
185
448
                        . ($self->{last_error} || 'timed out')
405                        . ' (socket ' . $self->shared_address . ", log $self->{log})\n"
406                        unless $sock;
407        }
408
409
426
400
        $self->{sock} = $sock;
410
411
426
771
        $self->_create_object;
412
413
410
289
        return $self;
414}
415
416sub _open {
417
7335
26256
        my $self = shift;
418
419
7335
13456
        if ($self->{transport} eq 'tcp') {
420                # Loaded only here, so a client of a unix socket still runs none of
421                # this.  Verification is mandatory: a certificate that does not chain
422                # to tls_ca and name this backend, or whose digest is not the pinned
423                # one, is not a connection.
424
80
399
                require IO::Socket::SSL;
425
426                my $sock = IO::Socket::SSL->new(
427                        PeerAddr => $self->{host},
428                        PeerPort => $self->{port},
429                        Proto    => 'tcp',
430                        Timeout  => $self->{timeout},
431                        Class::Shared::client_tls_options(
432                                cert        => $self->{tls_cert},
433                                key         => $self->{tls_key},
434                                ca          => $self->{tls_ca},
435                                fingerprint => $self->{tls_fingerprint},
436
80
303
                        ),
437                );
438
439
80
363087
                if (!$sock) {
440
57
114
                        my $why = IO::Socket::SSL::errstr();
441
57
334
                        $why = "$!" unless defined $why && length $why;
442
57
93
                        $self->{last_error} = "cannot connect to " . $self->shared_address
443                                . " over TLS: $why";
444                }
445
446
80
111
                return $sock;
447        }
448
449
7255
10352
        my $path = $self->{socket_path};
450
451        # TODO: Data Flow Anomaly - DD: redefined unread by each later failure, and cleared unread by _greet on success
452
7255
9060
        $self->{last_error} = "no socket at $path";
453
7255
47341
        return undef unless -S $path;
454
455        # Whatever comes back over this socket is thawed, so it must be ours: a
456        # directory another user can write to, or a socket another user made, would
457        # let that user answer every call and read every argument.
458
606
2208
        my ($safe, $why) = Class::Shared::_check_endpoint($path);
459
606
3596
        if (!$safe) {
460
19
20
                $self->{last_error} = "will not connect to $path: $why";
461
19
25
                return undef;
462        }
463
464        # The built-in socket and connect, not IO::Socket::UNIX: that module brings
465        # IO::Socket, IO::Socket::INET and IO::Handle with it, about 1.2 MB and 16
466        # ms in every process that talks to the backend, for a handle that is only
467        # ever given to sysread, syswrite and close.
468
587
394
        my $sock;
469
587
22844
        if (!socket($sock, AF_UNIX, SOCK_STREAM, 0)
470                || !connect($sock, pack_sockaddr_un($path))) {
471
24
246
                $self->{last_error} = "cannot connect to $path: $!";
472
24
207
                return undef;
473        }
474
475
563
984
        return $sock;
476}
477
478sub _greet {
479
7316
20862
        my $self = shift;
480
481
7316
13206
        my $sock = $self->_open;
482
7316
13177
        return undef unless $sock;
483
484        my ($response, $error) = $self->_roundtrip($sock, {
485                op    => 'hello',
486                proto => $Class::Shared::PROTOCOL_VERSION,
487                class => $self->{class},
488                pid   => $$,
489
614
7405
        }, $self->{timeout});
490
491
614
1138
        if (!defined $response) {
492
157
885
                $self->_close($sock, 'a failed handshake');
493
494
157
1224
                $self->{last_error} = 'handshake failed: ' . $self->_first_exchange_failed($error);
495
157
312
                return undef;
496        }
497
498
457
557
        if (!$response->{ok}) {
499
36
88
                $self->_close($sock, 'a refused handshake');
500
36
380
                die 'Class::Shared: ' . ($response->{error} || 'the backend refused the handshake') . "\n";
501        }
502
503
421
701
        $self->{pid} = $response->{pid};
504
421
284
        $self->{last_error} = undef;
505
506
421
794
        return $sock;
507}
508
509# Say what a failed first exchange most likely means.  Over TLS a backend that
510# will not accept this client's certificate drops the connection during the
511# handshake, before it can answer: from here that is a stream closing at once,
512# and calling it "connection closed by peer" hides the one thing that would fix
513# it.  A backend that accepted the certificate but not the token does answer,
514# with a frame this side cannot read, so that case keeps the token wording.
515sub _first_exchange_failed {
516
242
17802
        my ($self, $error) = @_;
517
518
242
380
        $error = 'no reason was given' unless defined $error;
519
520
242
791
        if ($self->{transport} eq 'tcp' && defined $error
521                && $error =~ /closed by peer|read failed|write failed/)
522        {
523
40
29
                my $hint = "the backend refused this client's certificate: check that "
524                        . 'tls_cert and tls_key are a certificate it accepts, and that tls_ca '
525                        . 'holds the CA it trusts for clients';
526
527
40
70
                return "$hint (detail: $error)";
528        }
529
530        # A silent backend is more likely busy with another client's method than
531        # in need of a token, and saying so is what lets the person decide to wait.
532
202
643
        return "$error (the backend may be busy running another client's method; "
533                . 'try again, or raise timeout)' if $error =~ /timed out/;
534
535
189
490
        return $error if defined $self->{token};
536
537
174
363
        return "$error (this backend may require a token)";
538}
539
540sub _create_object {
541
450
9316
        my $self = shift;
542
543
450
1750
        my $response = $self->_request({ op => 'new', args => $self->{ctor} }, $self->{timeout});
544
545
436
909
        if (!$response->{ok}) {
546
32
96
                my $error = $response->{error} || 'the backend gave no reason';
547
32
88
                $error =~ s/\s+\z//;
548
32
54
                $self->shared_close;
549
32
134
                die "Class::Shared: could not construct $self->{class}: $error\n";
550        }
551
552
404
452
        $self->{id} = $response->{id};
553
554
404
429
        return $self;
555}
556
557sub _request {
558
1519
12259
        my ($self, $message, $wait) = @_;
559
560
1519
2550
        $message->{id} = $self->{id} if ($message->{op} || '') eq 'call';
561
562        die "Class::Shared: this frontend has no connection to a backend for '$self->{class}'; "
563
1519
1991
                . "its object is gone\n" unless $self->{sock};
564
565
1451
34032
        my ($response, $error) = $self->_roundtrip($self->{sock}, $message, $wait);
566
567
1451
1457
        if (!defined $response) {
568
81
304
                $error = 'no reason was given' unless defined $error && length $error;
569
81
168
                $self->shared_close;
570
81
90
                $self->{last_error} = $error;
571
81
784
                die "Class::Shared: lost the backend for '$self->{class}': $error\n";
572        }
573
574
1370
1676
        return $response;
575}
576
577sub _roundtrip {
578
2044
9324
        my ($self, $sock, $message, $wait) = @_;
579
580        # With a token every frame is signed, and the backend checks the digest
581        # before it thaws: this is what stops the request bytes from being code.
582
2044
4103
        my ($bytes, $encode_error) = Class::Shared::Protocol::encode_frame($message, $self->{token});
583
2044
2066
        if (!defined $bytes) {
584
21
32
                return (undef, $encode_error);
585        }
586
587
2023
2611
        my ($ok, $write_error) = Class::Shared::Protocol::write_all($sock, $bytes);
588
2023
7008
        if (!$ok) {
589                # A full backend says so and closes without waiting for the hello, so
590                # the write can fail with its refusal already here to be read.  Nothing
591                # but a refusal counts: a request that was not sent has no other answer.
592                # The timeout is 0 because a backend sends it before it closes, and a
593                # write can fail for other reasons with nothing on the way.
594
140
321
                if (($message->{op} || '') eq 'hello') {
595
110
421
                        my ($refusal) = Class::Shared::Protocol::read_frame($sock, 0, $self->{token});
596
110
343
                        return ($refusal) if ref($refusal) eq 'HASH' && !$refusal->{ok};
597                }
598
599
138
247
                return (undef, $write_error);
600        }
601
602        my ($response, $read_error)
603
1883
3047
                = Class::Shared::Protocol::read_frame($sock, $wait, $self->{token});
604
1883
3174
        return (undef, $read_error) unless defined $response;
605
606
1806
1868
        if (ref($response) ne 'HASH') {
607
27
60
                return (undef, 'malformed response from the backend');
608        }
609
610
1779
1798
        return ($response);
611}
612
613# ------------------------------------------------------------ spawning
614
615# Purpose:       close a handle and say so if it fails, because a failed close
616#                can mean data was lost or a lock was not released.
617# Entry:         $fh is an open handle; $what names it for the message.
618# Exit status:   1 on success, 0 on failure.
619# Side effects:  closes $fh; carps on failure.
620sub _close {
621
1138
11488
        my ($self, $fh, $what) = @_;
622
623
1138
9011
        return 1 if close($fh);
624
625
21
827
        Carp::carp("Class::Shared::Frontend: cannot close $what: $!");
626
627
21
184
        return 0;
628}
629
630sub _spawn_backend {
631        # Evals below must not leave their errors in the caller's $@.
632
260
15776
        local $@;
633
260
239
        my $self = shift;
634
635
260
371
        my $path = $self->{socket_path};
636
260
548
        my $dir  = Class::Shared::dir_of($path);
637
638
260
654
        my ($dir_ok, $dir_error) = Class::Shared::ensure_dir($dir);
639
260
433
        if (!$dir_ok) {
640
25
50
                $self->{last_error} = $dir_error;
641
25
81
                return undef;
642        }
643
644
235
307
        my $lock_path = $path . '.spawn';
645
235
164
        my $lock;
646
235
6998
        if (!sysopen($lock, $lock_path, O_RDWR | O_CREAT, 0600)) {
647
18
191
                $self->{last_error} = "cannot open $lock_path: $!";
648
18
45
                return undef;
649        }
650
217
1283
        if (!flock($lock, LOCK_EX)) {
651
0
0
                $self->{last_error} = "cannot lock $lock_path: $!";
652
0
0
                $self->_close($lock, $lock_path);
653
0
0
                return undef;
654        }
655
656        # Somebody else may have started it while we waited for the lock.
657
217
217
272
354
        if (my $sock = eval { $self->_greet }) {
658
6
24
                $self->_close($lock, $lock_path);
659
6
24
                return $sock;
660        }
661
211
836
        $self->_refused($lock, $lock_path, $@);
662
663        # We hold the lock, so a socket that will not answer is a leftover.
664        # Only a socket is removed as a leftover: a path that names anything else
665        # is not ours to delete, whatever the caller meant by it.
666
211
513
        my $state = $self->_remove_stale($path);
667
211
371
        if (!$state) {
668
15
21
                $self->_close($lock, $lock_path);
669
15
57
                return undef;
670        }
671
672        # A backend that is running but slow to answer is waited for, not replaced.
673
196
699
        if ($state ne 'running' && !$self->_fork_backend($lock)) {
674
0
0
                $self->_close($lock, $lock_path);
675
0
0
                return undef;
676        }
677
678
158
563
        my $deadline = time + $self->{timeout};
679
158
414
        my $sock;
680
681
158
1085
        while (time <= $deadline) {
682
7027
7027
10503
18739
                my $greeted = eval { $self->_greet };
683
7027
13442
                if (my $handshake_error = $@) {
684
12
204
                        $self->_refused($lock, $lock_path, $handshake_error);
685
0
0
                        $handshake_error =~ s/\s+\z//;
686
0
0
                        $self->{last_error} = $handshake_error;
687                }
688
7015
8183
                if ($greeted) {
689
138
103
                        $sock = $greeted;
690
138
189
                        last;
691                }
692
693                # A backend that is stopping removes its socket before it releases its
694                # lock.  Once the lock is free nobody is coming back to answer, so one
695                # has to be started after all.
696
6877
9645
                if ($state eq 'running') {
697
80
268
                        $state = $self->_remove_stale($path);
698
80
217
                        last unless $state;
699
80
284
                        if ($state ne 'running' && !$self->_fork_backend($lock)) {
700
0
0
                                last;
701                        }
702                }
703
6876
11473
                Class::Shared::poll_pause();
704        }
705
706
145
509
        $self->_close($lock, $lock_path);
707
708        $self->{last_error} = "a backend is running at $path but did not answer: "
709
145
439
                . ($self->{last_error} // 'no reason was given')
710                if !$sock && ($state // '') eq 'running';
711
712
145
1810
        return $sock;
713}
714
715# Purpose:       start one backend in the background.
716# Entry:         the spawn lock is held on $lock.
717# Exit status:   1 once it has been started (not once it is ready), 0 with
718#                last_error set if it could not be.
719# Side effects:  forks, and waits for the intermediate child.
720sub _fork_backend {
721
195
228
        my ($self, $lock) = @_;
722
723
195
377271
        my $pid = fork;
724
195
5315
        if (!defined $pid) {
725
0
0
                $self->{last_error} = "fork failed: $!";
726
0
0
                return 0;
727        }
728
729
195
2004
        if ($pid == 0) {
730
39
1966
                $self->_exec_backend($lock);
731                # not reached
732        }
733
734        # The first child only forks the daemon and exits; waiting for it stops it
735        # being left as a zombie.  Its status says nothing about the backend, which
736        # is judged by whether it answers, and waitpid fails harmlessly when
737        # SIGCHLD is ignored.
738
156
429661
        waitpid($pid, 0);
739
740
156
6234
        return 1;
741}
742
743# Purpose:       remove the socket a dead backend left, and only that.
744# Entry:         $path is the socket path; the spawn lock is held.
745# Exit status:   'running' if a backend owns the path, 'clear' if nothing is in
746#                the way of a new one, undef (with last_error set) otherwise.
747# Side effects:  may unlink $path.
748# Why:           silence is not death: a backend busy with a long method does
749#                not answer.  A running backend holds a lock on PATH.owner, so
750#                the lock tells the two apart.  It is held while unlinking, so a
751#                backend starting at this moment waits and keeps its new socket.
752sub _remove_stale {
753
291
421
        my ($self, $path) = @_;
754
755
291
297
        my $owner_path = "$path.owner";
756
291
208
        my $owner;
757
291
5954
        if (!sysopen($owner, $owner_path, O_RDWR | O_CREAT, 0600)) {
758
0
0
                $self->{last_error} = "cannot open $owner_path: $!";
759
0
0
                return undef;
760        }
761
762
291
676
        my $state = 'running';
763
291
978
        if (flock($owner, LOCK_SH | LOCK_NB)) {
764
210
267
                $state = 'clear';
765
210
1831
                if (-e $path && !-S $path) {
766
9
16
                        $self->{last_error} = "$path exists and is not a socket; refusing to remove it";
767
9
13
                        $state = undef;
768                } elsif (-e $path && !unlink($path)) {
769
6
60
                        $self->{last_error} = "cannot remove the stale socket $path: $!";
770
6
18
                        $state = undef;
771                }
772        }
773
291
679
        $self->_close($owner, $owner_path);
774
775
291
772
        return $state;
776}
777
778# Purpose:       pass on a refusal that a running backend gave to the handshake.
779# Entry:         $error is what _greet died with ('' if it did not die).
780# Exit status:   returns if there is nothing to pass on; otherwise dies.
781# Side effects:  releases the start lock first.
782# Why:           a backend that answers "cannot load CLASS" is alive and has
783#                given its final answer.  Retrying until the timeout wastes
784#                the time, and replacing its socket would be wrong.
785sub _refused {
786
223
672
        my ($self, $lock, $lock_path, $error) = @_;
787
788
223
1148
        return unless defined $error && $error =~ /\AClass::Shared: /;
789
790
12
93
        $self->_close($lock, $lock_path);
791
12
195
        die $error;
792}
793
794# Runs in the freshly forked child; never returns.  There is nobody to report
795# a failure to here: the streams are not redirected yet, and the parent only
796# sees whether a backend answers.  So every step that must work is checked, and
797# a failure ends the child with status 127, after which the parent reports that
798# no backend started and points at the log.
799sub _exec_backend {
800
42
9862561
        my ($self, $lock) = @_;
801
802
42
1424
        require POSIX;
803
804
42
978
        if ($lock) {
805
40
1450
                close($lock) or POSIX::_exit(127);
806        }
807
808
42
1858
        POSIX::setsid() or POSIX::_exit(127);
809
810        # Double fork so the daemon is reaped by init, not by the client.
811
42
56544
        my $pid = fork;
812
42
2722
        POSIX::_exit(0) if !defined $pid || $pid > 0;
813
814        # Most of these numbers are not open descriptors, so POSIX::close failing
815        # with EBADF is the expected answer and is not an error.
816
42
1391
        for my $fd ($FIRST_INHERITED_FD .. $LAST_INHERITED_FD) {
817
42882
47644
                POSIX::close($fd);
818        }
819
820
42
1379
        my ($detached) = Class::Shared::detach_standard_streams($self->{log});
821
42
436
        POSIX::_exit(127) unless $detached;
822
823
42
476
467
2561
        my @inc = grep { defined($_) && !ref($_) && length($_) } @INC;
824
825        # Under -T perl will not exec with a tainted argument or a PATH it cannot
826        # vouch for, and it counts the name of the perl itself ($^X) as tainted.
827        # All are untainted here, at the one place they are used, and only under -T
828        # so that nothing changes for anyone else.  The names are only refused if
829        # they hold a NUL, which would end them early.  PATH keeps the entries that
830        # are absolute directories no one but the owner can write to, and perl
831        # insists on that: it refuses to exec at all while PATH names a directory
832        # others can write to (a CI runner's PATH usually does), because a program
833        # put there would be run in place of the one meant.  A relative or empty
834        # entry would make the child look in the current directory.
835
42
281
        my ($perl, $socket, $log) = ($^X, $self->{socket_path}, $self->{log});
836
42
695
        if (${^TAINT}) {
837
0
0
                ($perl)   = $perl   =~ /\A([^\0]+)\z/ or POSIX::_exit(127);
838
0
0
                ($socket) = $socket =~ /\A([^\0]+)\z/ or POSIX::_exit(127);
839
0
0
                ($log)    = $log    =~ /\A([^\0]+)\z/ or POSIX::_exit(127);
840
841                # The capture untaints each entry; the filetests need no untainting.
842
0
0
                my @safe = grep { -d $_ && !((stat _)[2] & 0022) }
843
0
0
0
0
                        map { m{\A(/[^\0]*)\z} ? $1 : () } split /:/, ($ENV{PATH} // '');
844
0
0
                $ENV{PATH} = @safe ? join(':', @safe) : '/usr/bin:/bin';
845
0
0
                delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
846        }
847
848
68
68
68
217
56
4695
        no warnings 'exec';    # exec() does not return when it works
849        exec(
850                $perl,
851
42
475
145
854
                (map { ('-I', $_) } @inc),
852                '-MClass::Shared::Backend',
853                '-e',
854                'Class::Shared::Backend->new(socket => $ARGV[0], log => $ARGV[1])->run()',
855                $socket,
856                $log,
857        );
858
859
0
        POSIX::_exit(127);
860}
861
8621;
863