File Coverage

File:bin/class-shared
Coverage:85.5%

linestmtbranpathcondsubpodtimecode
1#!/usr/bin/perl
2
3
89
89
89
173862
71
1384
use strict;
4
89
89
89
119
49
1840
use warnings;
5
6
89
89
89
26683
413265
146
use Getopt::Long qw(GetOptions);
7
89
89
89
21222
778578
194
use IO::Socket::UNIX;
8
89
89
89
15302
60
6807
use Socket qw(SOCK_STREAM);
9
10
89
89
89
22926
120
811
use Class::Shared ();
11
89
89
89
17308
107
2428669
use Class::Shared::Protocol ();
12
13
89
3559366
our $VERSION = $Class::Shared::VERSION;
14
15
89
93
my $program = 'class-shared';
16
17
89
443
my %opt = (
18        dir        => undef,
19        socket     => undef,
20        listen     => undef,
21        host       => undef,
22        port       => undef,
23        token_file => undef,
24        tls_cert   => undef,
25        tls_key    => undef,
26        tls_ca     => undef,
27        tls_fingerprint => undef,
28        log        => undef,
29        foreground => 0,
30        max_memory => undef,
31        help       => 0,
32        version    => 0,
33);
34
35# Kept for start --max-memory, which runs the command again with the same words.
36
89
141
my @command_line = @ARGV;
37
38my $options_ok = GetOptions(
39        'dir=s'        => \$opt{dir},
40        'socket=s'     => \$opt{socket},
41        'listen=s'     => \$opt{listen},
42        'host=s'       => \$opt{host},
43        'port=i'       => \$opt{port},
44        'token-file=s' => \$opt{token_file},
45        'tls-cert=s'   => \$opt{tls_cert},
46        'tls-key=s'    => \$opt{tls_key},
47        'tls-ca=s'     => \$opt{tls_ca},
48        'tls-fingerprint=s' => \$opt{tls_fingerprint},
49        'log=s'        => \$opt{log},
50        'foreground|f' => \$opt{foreground},
51        'max-memory=i' => \$opt{max_memory},
52        'help|h'       => \$opt{help},
53        'version|V'    => \$opt{version},
54
89
476
);
55
56
89
63161
usage(2) unless $options_ok;
57
58
88
134
if ($opt{version}) {
59
1
5
        out("$program $VERSION\n");
60
1
0
        exit 0;
61}
62
63
87
127
my $command = shift(@ARGV) || 'help';
64
65
87
231
if ($opt{help} || $command eq 'help') {
66
3
3
        usage(0);
67}
68
69
84
158
if ($command eq 'start') {
70
19
22
        start();
71} elsif ($command eq 'status') {
72
31
38
        status();
73} elsif ($command eq 'stop') {
74
26
32
        stop();
75} elsif ($command eq 'path') {
76
6
8
        show_path();
77} else {
78        # The exit status is the report if standard error is gone.
79
2
29
        print STDERR "$program: unknown command '$command'\n";
80
2
2
        usage(2);
81}
82
83
33
486
exit 0;
84
85# ---------------------------------------------------------------- commands
86
87sub start {
88
19
37
        my ($host, $port) = tcp_endpoint();
89
90
14
67
        limit_memory() if defined $opt{max_memory};
91
92
12
12
12
15
4371
50
        eval { require Class::Shared::Backend; 1 }
93                or fatal("cannot load Class::Shared::Backend: $@");
94
95
12
26
        my $backend = eval {
96                Class::Shared::Backend->new(
97                        socket    => defined $host ? undef : socket_path_for(),
98                        host      => $host,
99                        port      => $port,
100                        token     => token(),
101                        tls_options($host, 'server'),
102                        dir       => $opt{dir},
103                        log       => $opt{log},
104
12
43
                        daemonize => $opt{foreground} ? 0 : 1,
105                );
106        };
107
108
10
31
        if (!$backend) {
109
1
2
                my $error = $@ || 'unknown error';
110
1
3
                $error =~ s/\s+\z//;
111
1
2
                $error =~ s/\AClass::Shared::Backend->new: //;
112
1
1
                fatal($error);
113        }
114
115
9
9
4
6
15
7
        my $ok = eval { $backend->run; 1 };
116
4
8
        if (!$ok) {
117
0
0
                my $error = $@ || 'unknown error';
118
0
0
                $error =~ s/\s+\z//;
119
0
0
                fatal($error);
120        }
121
122
4
14
        return;
123}
124
125sub status {
126
31
64
        my ($response, $error) = talk({ op => 'ping' });
127
25
1220
        fatal($error) unless $response;
128
16
25
        fatal($response->{error} || 'the backend refused the request') unless $response->{ok};
129
130        out(sprintf "pid %d, version %s, protocol %d, %d object(s), %d call(s), up %d second(s)\n",
131                $response->{pid},
132                $response->{version},
133                $response->{proto},
134                $response->{objects},
135                $response->{calls},
136
16
102
                $response->{uptime});
137
138
16
17
        my $classes = $response->{classes};
139
16
26
        $classes = [] unless ref($classes) eq 'ARRAY';
140
141
16
16
11
20
35
28
        out(sprintf "classes: %s\n", (@{$classes} ? join(', ', @{$classes}) : 'none'));
142
16
32
        out(sprintf "address: %s\n", $response->{address});
143
16
31
        out(sprintf "clients: %d\n", $response->{clients});
144
145        # What the memory bound is holding: the bytes waiting to be written to all
146        # clients, against the ceiling that decides when a reply is refused.
147
16
57
        out(sprintf "queued:  %d of %d byte(s)\n", $response->{queued}, $response->{max_queued_total});
148
149
16
28
        out(sprintf "log:     %s\n", log_path_for());
150
151
16
61
        return;
152}
153
154sub stop {
155
26
58
        my ($response, $error) = talk({ op => 'shutdown' });
156
23
236
        fatal($error) unless $response;
157
9
17
        fatal($response->{error} || 'the backend refused to shut down') unless $response->{ok};
158
159
9
16
        wait_for_exit();
160
161
9
14
        out("stopped\n");
162
163
9
12
        return;
164}
165
166sub show_path {
167        fatal('path only makes sense for a unix socket; use --host/--port for TCP')
168
6
23
                if defined $opt{listen} || defined $opt{host} || defined $opt{port};
169
170
6
9
        out(socket_path_for() . "\n");
171
172
4
5
        return;
173}
174
175# ---------------------------------------------------------------- plumbing
176
177# Cap the memory of this process, and so of the backend it becomes, by running
178# the command again under the shell's ulimit.  Perl has no call of its own for
179# this, and the cap keeps a target class that allocates without end from taking
180# the machine with it.  Every word is passed as an argument, never as shell text.
181sub limit_memory {
182
3
9
        my $mib = $opt{max_memory};
183
3
10
        fatal("--max-memory wants a number of MiB above 0, not '$mib'") unless $mib > 0;
184
185        # The second time round the cap is in place.  The mark is removed so that
186        # nothing the backend starts believes it is capped.
187
2
12
        return if delete $ENV{CLASS_SHARED_MEMORY_CAPPED};
188
189        # Elsewhere ulimit -v is accepted and ignored, which would be worse than
190        # saying so.
191
1
3
        fatal("--max-memory is not enforced on this system ($^O)")
192                unless $^O eq 'linux' || $^O eq 'freebsd';
193
194
1
4
        local $ENV{CLASS_SHARED_MEMORY_CAPPED} = 1;
195        exec('/bin/sh', '-c', 'ulimit -v "$1" && shift && exec "$@"', 'sh',
196
1
16
16
3
9
7
                $mib * 1024, $^X, (map { "-I$_" } grep { !ref } @INC), $0, @command_line)
197                or fatal("cannot limit memory: $!");
198
199
0
0
        return;
200}
201
202# --listen tcp:HOST:PORT, or --host and --port; otherwise a unix socket.
203sub tcp_endpoint {
204
102
138
        my ($host, $port) = ($opt{host}, $opt{port});
205
206
102
137
        if (defined $opt{listen}) {
207
11
22
                fatal("--listen and --host/--port are alternatives; give one")
208                        if defined $host || defined $port;
209
210                # /a: a port is ASCII digits; without it \d takes digits of other scripts
211                # when the argument has been decoded (perl -CA).
212
11
32
                if ($opt{listen} =~ /\Atcp:(.+):(\d+)\z/a) {
213
8
14
                        ($host, $port) = ($1, $2);
214                } elsif ($opt{listen} =~ /\Aunix:(.+)\z/) {
215
0
0
                        $opt{socket} = $1;
216                } else {
217
3
5
                        fatal("--listen wants tcp:HOST:PORT or unix:PATH, not '$opt{listen}'");
218                }
219        }
220
221
99
206
        fatal('a TCP listener needs both --host and --port')
222                if defined $host xor defined $port;
223
224        fatal('use either --socket or --host/--port, not both')
225
98
253
                if defined $host && defined $opt{socket} && length $opt{socket};
226
227
95
124
        return ($host, $port);
228}
229
230sub socket_path_for {
231        # Both can die (a path too long for a socket, a perl without unix sockets);
232        # say so the way every other command-line error is said, not with a raw die
233        # whose exit status is whatever errno happened to hold.
234
76
55
        my $path = eval {
235                defined $opt{socket} && length $opt{socket}
236                        ? Class::Shared::check_socket_path($opt{socket})
237
76
221
                        : Class::Shared::socket_path($opt{dir});
238        };
239
76
95
        fatal($@ || 'cannot work out the socket path') unless defined $path;
240
241
75
116
        return $path;
242}
243
244sub log_path_for {
245
16
29
        return $opt{log} if defined $opt{log} && length $opt{log};
246
247
16
25
        return socket_path_for() . '.log';
248}
249
250sub token {
251
67
180
        return undef unless defined $opt{token_file} && length $opt{token_file};
252
253        # A unix socket is mode 0600 in a directory only its owner can write to, so
254        # the kernel has already decided who may connect.
255
17
16
        my ($host) = tcp_endpoint();
256
17
28
        fatal("a unix socket needs no token: $Class::Shared::UNIX_TRUST_REASON")
257                unless defined $host;
258
259
15
15
40
29
        return or_fatal(sub { Class::Shared::read_secret($opt{token_file}) });
260}
261
262sub tls_options {
263
63
72
        my ($host, $role) = @_;
264
265
63
252
57
264
        my %tls = map { $_ => $opt{$_} } qw(tls_cert tls_key tls_ca tls_fingerprint);
266
267
63
118
        if (!defined $host) {
268                fatal("a unix socket needs no TLS: $Class::Shared::UNIX_TRUST_REASON")
269
45
180
45
171
                        if grep { defined $tls{$_} && length $tls{$_} } keys %tls;
270
45
85
                return ();
271        }
272
273
18
24
        if ($role eq 'server') {
274                fatal('--tls-fingerprint is for clients: a listener verifies its clients '
275                        . 'with --tls-ca')
276
4
8
                        if defined $tls{tls_fingerprint} && length $tls{tls_fingerprint};
277
278                fatal('a TCP listener needs --tls-cert, --tls-key and --tls-ca: without them '
279                        . 'the traffic would be readable to anyone who can route to it')
280
4
12
4
22
                        if grep { !defined $tls{$_} || !length $tls{$_} } qw(tls_cert tls_key tls_ca);
281
282
3
3
                delete $tls{tls_fingerprint};
283
284
3
16
                return %tls;
285        }
286
287        fatal('a TCP client needs --tls-cert and --tls-key: the backend verifies its '
288                . 'clients and will not accept one it cannot verify')
289
14
28
10
53
                if grep { !defined $tls{$_} || !length $tls{$_} } qw(tls_cert tls_key);
290
291
13
27
        my $has_ca  = defined $tls{tls_ca} && length $tls{tls_ca};
292
13
16
        my $has_pin = defined $tls{tls_fingerprint} && length $tls{tls_fingerprint};
293
294
13
17
        fatal('a TCP client needs --tls-ca or --tls-fingerprint: without one it cannot '
295                . 'verify the backend')
296                unless $has_ca || $has_pin;
297
298
13
24
        fatal('give --tls-ca or --tls-fingerprint, not both: a CA and a pin are '
299                . 'alternatives')
300                if $has_ca && $has_pin;
301
302
12
12
        if ($has_pin) {
303                $tls{tls_fingerprint} = or_fatal(
304
4
4
8
7
                        sub { Class::Shared::normalise_fingerprint($tls{tls_fingerprint}) });
305        } else {
306
8
8
                delete $tls{tls_fingerprint};
307        }
308
309
10
29
        return %tls;
310}
311
312# A helper that dies is reported like every other error, with exit status 1: a
313# raw die would exit with whatever errno held, which can look like a usage error.
314sub or_fatal {
315
19
16
        my ($code) = @_;
316
317
19
19
10
13
        my $value = eval { $code->() };
318
19
29
        fatal($@) unless defined $value;
319
320
15
21
        return $value;
321}
322
323sub talk {
324
57
53
        my ($request) = @_;
325
326
57
68
        my ($host, $port) = tcp_endpoint();
327
55
89
        my $secret = token();
328
52
88
        my %tls = tls_options($host, 'client');
329
330
48
38
        my ($sock, $where);
331
332
48
48
        if (defined $host) {
333
10
3844
                require IO::Socket::SSL;
334
335
10
332726
                $where = "$host:$port";
336                $sock = IO::Socket::SSL->new(
337                        PeerAddr => $host,
338                        PeerPort => $port,
339                        Proto    => 'tcp',
340                        Timeout  => 5,
341                        Class::Shared::client_tls_options(
342                                cert        => $tls{tls_cert},
343                                key         => $tls{tls_key},
344                                ca          => $tls{tls_ca},
345                                fingerprint => $tls{tls_fingerprint},
346
10
43
                        ),
347                );
348
349
10
68250
                if (!$sock) {
350
2
5
                        my $why = IO::Socket::SSL::errstr();
351
2
15
                        $why = "$!" unless defined $why && length $why;
352
2
9
                        return (undef, "no backend at $where: TLS failed: $why");
353                }
354        } else {
355
38
57
                $where = socket_path_for();
356
357                # What the backend sends back is thawed, so it has to be ours.  A
358                # missing socket is left to the connect below to describe.
359
38
266
                if (-e $where) {
360
23
66
                        my ($safe, $why) = Class::Shared::_check_endpoint($where);
361
23
29
                        return (undef, "no backend at $where: will not connect: $why") unless $safe;
362                }
363
364
37
143
                $sock = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $where);
365
37
5164
                return (undef, "no backend at $where: $!") unless $sock;
366        }
367
368
30
160
        my ($hello, $hello_error) = exchange($sock, {
369                op    => 'hello',
370                proto => $Class::Shared::PROTOCOL_VERSION,
371                pid   => $$,
372        }, $secret);
373
374
30
88
        if (!$hello) {
375
4
8
                close_connection($sock);
376
377                # Over TLS a backend that will not accept this certificate drops the
378                # connection during the handshake: the stream closes before a reply,
379                # which says nothing about certificates unless we name it.
380
4
28
                if (defined $host && defined $hello_error
381                        && $hello_error =~ /closed by peer|read failed|write failed/)
382                {
383                        return (undef,
384
1
3
                                "handshake failed: the backend refused this client's certificate: "
385                                . 'check that --tls-cert and --tls-key are a certificate it accepts, '
386                                . "and that --tls-ca is the CA it trusts for clients (detail: $hello_error)");
387                }
388
389                # A backend with a token will not let a frame it cannot authenticate
390                # through, and it signs its replies too, so a caller with no token
391                # cannot read them: all it sees is a Storable complaint about bytes
392                # that are not an image.  Lead with the likely reason and keep the
393                # complaint underneath, for when the cause was something else.
394
3
6
                if (!defined $secret) {
395                        return (undef,
396
2
6
                                'handshake failed: this backend may require a token; '
397                                . "pass --token-file with its secret\n"
398                                . "detail: $hello_error");
399                }
400
401
1
3
                return (undef, "handshake failed: $hello_error");
402        }
403
404
26
45
        if (!$hello->{ok}) {
405
1
3
                close_connection($sock);
406
1
7
                return (undef, $hello->{error} || 'the backend refused the handshake');
407        }
408
409
25
44
        my ($response, $error) = exchange($sock, $request, $secret);
410
25
56
        close_connection($sock);
411
412
25
31
        return (undef, $error) unless $response;
413
414
25
115
        return ($response);
415}
416
417sub exchange {
418
55
64
        my ($sock, $request, $secret) = @_;
419
420
55
139
        my ($bytes, $encode_error) = Class::Shared::Protocol::encode_frame($request, $secret);
421
55
63
        return (undef, "cannot encode the request: $encode_error") unless defined $bytes;
422
423
55
500723
        my ($ok, $write_error) = Class::Shared::Protocol::write_all($sock, $bytes);
424
55
85
        if (!$ok) {
425                # A full backend says so and closes without waiting for the hello, so
426                # the write can fail with its refusal already here to be read.  Do not
427                # wait for one: a write can fail with nothing on the way.
428
2
6
                if ($request->{op} eq 'hello') {
429
2
400
                        my ($refusal) = Class::Shared::Protocol::read_frame($sock, 0, $secret);
430
2
817
                        return ($refusal) if ref($refusal) eq 'HASH' && !$refusal->{ok};
431                }
432
433
1
2
                return (undef, "cannot send the request: $write_error");
434        }
435
436
53
77
        my ($response, $read_error) = Class::Shared::Protocol::read_frame($sock, undef, $secret);
437
53
61
        return (undef, "cannot read the response: $read_error") unless defined $response;
438
439
50
79
        return ($response);
440}
441
442sub wait_for_exit {
443
9
12
        my ($host) = tcp_endpoint();
444
9
13
        return if defined $host;
445
446
8
4
        my $socket = socket_path_for();
447
8
9
        my $deadline = time + 5;
448
449
8
77
        while (-e $socket && time < $deadline) {
450
2
2
                Class::Shared::poll_pause();
451        }
452
453
8
26
        fatal("the backend asked to shut down but $socket is still there") if -e $socket;
454
455
8
12
        return;
456}
457
458# Write to standard output and stop if that fails: a status report that went
459# nowhere, because the pipe it was sent down has closed, must not look like
460# success.
461sub out {
462
111
91
        my ($text) = @_;
463
464        # Flushed here, because a buffered print only reports a full disk or a
465        # closed pipe when the buffer is finally written, which is after the
466        # program has decided it succeeded.
467
111
1002
        (print {*STDOUT} $text and STDOUT->flush)
468
111
1
1
58
30
0
                or do { print STDERR "$program: cannot write to standard output: $!\n"; exit 1 };
469
470
110
106
        return;
471}
472
473# A connection that will not close cleanly is worth a warning, but is never a
474# reason to lose the answer already in hand.
475sub close_connection {
476
30
32
        my ($sock) = @_;
477
478
30
237
        close($sock) or print STDERR "$program: warning: cannot close the connection: $!\n";
479
480
30
1409
        return;
481}
482
483sub fatal {
484
42
53
        my ($message) = @_;
485
42
43
        $message = '' unless defined $message;
486
42
119
        $message =~ s/\s+\z//;
487        # If standard error is gone there is nowhere left to say so, and the exit
488        # status is the report.
489
42
593
        print STDERR "$program: $message\n";
490
42
102
        exit 1;
491}
492
493sub usage {
494
6
6
        my ($status) = @_;
495
496        # As in fatal(): the exit status is the report if standard error is gone.
497
6
56
        print STDERR <<"USAGE";
498usage: $program <command> [options]
499
500Commands:
501  start     run the backend (in the background unless -f)
502  status    ask a running backend what it is doing
503  stop      ask a running backend to shut down, destroying its objects
504  path      print the unix socket path
505
506Options:
507  --dir DIR        directory for the socket, lock and log (default:
508                   \$CLASS_SHARED_DIR, then \$XDG_RUNTIME_DIR/class-shared, then
509                   /run/user/\$uid/class-shared, then the system temp directory)
510  --socket PATH    use an explicit unix socket path
511  --listen ADDR    tcp:HOST:PORT to serve remote clients
512  --host HOST      TCP address, with --port
513  --port PORT      TCP port, with --host
514  --token-file F   the shared secret; TCP only, and required there
515  --tls-cert FILE  this side's certificate; TCP only, and required there
516  --tls-key FILE   the private key for --tls-cert; TCP only
517  --tls-ca FILE    the CA that signs the other side's certificate; TCP only
518  --tls-fingerprint HEX
519                   pin the backend's SHA-256 fingerprint instead of a CA; the
520                   client commands only
521  --log PATH       backend log file (default: SOCKET.log)
522  -f, --foreground stay in the foreground (start)
523  --max-memory MIB cap the backend's memory (start; Linux and FreeBSD)
524  -h, --help       this message
525  -V, --version    print the version
526
527Examples:
528  $program start  -f
529  $program status
530  $program start  --listen tcp:0.0.0.0:7000 \\
531                  --token-file /etc/class-shared/token \\
532                  --tls-cert /etc/class-shared/server.pem \\
533                  --tls-key /etc/class-shared/server-key.pem \\
534                  --tls-ca /etc/class-shared/clients-ca.pem
535USAGE
536
537
6
        exit $status;
538}
539