File Coverage

File:blib/lib/Class/Shared.pm
Coverage:95.6%

linestmtbranpathcondsubpodtimecode
1package Class::Shared;
2
3
163
163
163
5963616
120
2167
use strict;
4
163
163
163
252
106
2899
use warnings;
5
6
163
163
163
297
134
854
use File::Basename ();
7
163
163
163
204
125
1131
use File::Spec ();
8
9# version->declare here alone: this is VERSION_FROM, and with it MakeMaker
10# writes 0.001.0 into META; a plain dotted string becomes v0.001.0 there.
11
163
163
163
20840
96398
380
use version; our $VERSION = version->declare('0.001.0');
12
13# Bumped whenever the wire protocol changes in an incompatible way.  2 added
14# the HMAC-SHA-256 digest every frame carries when a token is in use.
15our $PROTOCOL_VERSION = 2;
16
17# Longest unix(7) path we are prepared to generate.  The kernel limit is
18# 107 characters plus the terminator; leaving headroom keeps us portable.
19our $MAX_SOCKET_PATH = 100;
20
21# How often the loops that wait for a socket or a lock look again, in seconds.
22# One value, so every wait in the distribution polls at the same rate.
23our $POLL_INTERVAL = 0.02;
24
25# Why a unix socket takes neither a token nor TLS.  It is quoted by the backend,
26# the frontend and the command line, so they cannot word it differently.
27our $UNIX_TRUST_REASON = 'its mode 0600 file already decides who may connect';
28
29# The protocol versions a TLS connection may use, in IO::Socket::SSL's own
30# notation: TLS 1.2 and later.  SSL 2 and 3 and TLS 1.0 and 1.1 are broken or
31# deprecated (RFC 8996), and left to its defaults the library would still
32# offer them to a peer that asked.  Used by both ends so that they agree.
33our $TLS_VERSIONS = 'SSLv23:!SSLv3:!SSLv2:!TLSv1:!TLSv1_1';
34
35# Parts of a class name are joined by "::".  The characters of a part never
36# include ":", so a part can only end where "::" or the end begins, and there
37# is only one way to match any name.
38#
39# The name is checked in two flat steps, not by one pattern that repeats a
40# group once per part: perl 5.26 stops a repeated group at 32766 repeats
41# ("Complex regular subexpression recursion limit"), so a long but valid
42# name would die there.  Step one matches only the allowed characters, and its
43# capture is what is returned, so it is untainted.  Step two checks each part.
44# The classes are written out, not \w, so that no non-ASCII letter is accepted.
45my $CLASS_CHARS_RE = qr/ \A ( [A-Za-z0-9_:]++ ) \z /x;
46my $CLASS_PART_RE  = qr/ \A [A-Za-z_] [A-Za-z0-9_]*+ \z /x;
47
48 - 287
=head1 NAME

Class::Shared - Keep one instance of a class and let other processes call it

=head1 SYNOPSIS

The usual way to use this distribution is through L<Class::Shared::Frontend>.
Each example below is a different real-world pattern.

    # 1. The simplest case: share one class between many processes.
    use Class::Shared::Frontend;

    my $simple = Class::Shared::Frontend->new('Class::Simple');

    $simple->foo('hello');          # runs in the shared backend
    print $simple->foo(), "\n";     # prints "hello"

    # 2. Give the class its constructor arguments.  They are used once, when
    #    the object is made, and must be plain data (no code references).
    my $logger = Class::Shared::Frontend->new('My::Logger',
        ctor => [ level => 'debug', file => '/var/log/app.log' ],
    );

    my @all = $logger->lines();     # list context is kept
    my $n   = $logger->lines();     # scalar context is kept too

    # 3. Use a backend on another machine, over TLS with client certificates.
    my $remote = Class::Shared::Frontend->new('Class::Simple',
        host       => 'classhost.example.com',
        port       => 7000,
        tls_ca     => 'ca.pem',
        tls_cert   => 'client.pem',
        tls_key    => 'client-key.pem',
        token_file => '/etc/class-shared/token',
    );

    # 4. Look after the backend yourself, from the shell.
    #      class-shared start        # start it in the background
    #      class-shared status       # ask what it is doing
    #      class-shared stop         # ask it to stop

    # 5. Use the helper functions to write your own client.
    use Class::Shared ();

    my $dir = Class::Shared::default_dir();
    my ($ok, $why) = Class::Shared::ensure_dir($dir);
    die "cannot use $dir: $why" unless $ok;

    my $socket = Class::Shared::socket_path($dir);

=head1 DESCRIPTION

Perl has no equivalent of a shared library for classes: every process loads
its own copy of F<Class/Simple.pm>, runs its own constructors and keeps its
own state.  For a large class used by many short lived processes that is a lot
of memory and a lot of start up time.

Class::Shared moves the code into one process and lets the others keep a small
proxy: a L<Class::Shared::Frontend> standing in for one object, held by a
L<Class::Shared::Backend> that loaded the class once and does the work.

    client process            singleton backend process
    --------------            -------------------------
    Frontend (object #1)  --socket-->  Class::Shared::Backend
    Frontend (object #2)  --socket-->  |-- Class::Simple (code, loaded once)
    Frontend (object #3)  --socket-->  |-- object #1
                                       |-- object #2
                                       `-- object #3

So there is one copy of the class in the system and as many objects as there are
frontends: C<< Class::Shared::Frontend->new('Class::Simple', ...) >> is one call
to C<< Class::Simple->new(...) >>, in the backend.

The arguments for that constructor go in C<ctor>, as an array reference:
C<ctor =E<gt> [verbose =E<gt> 1]> is
C<< Class::Simple->new(verbose =E<gt> 1) >>.  They are used once, when the
frontend connects and asks the backend for the object, and they travel over the
socket, so they must be plain data -- a code reference cannot be sent.  If the
constructor dies, the frontend's C<new> dies too, naming the class and the error
the backend reported.

L<Class::Shared::Frontend> lists every option this constructor takes.

The frontend never loads the target class, so it stays cheap.  An object lives
as long as the connection that made it; when the frontend goes, the backend
destroys the object, so its C<DESTROY> runs once, in the backend.

One backend serves every class its clients ask for.  A client names the class it
wants in its first message, the handshake, and the backend loads that module
then, once per class, however many clients ask for it.  The backend may be on
this machine (a unix socket, see C<Class::Shared::default_dir>) or on another
one (TCP).

Class::Shared is for Unix-like systems: unix sockets, POSIX directory
permissions and C<fork> are what make a backend reachable, private and
startable.  See L</PLATFORMS>.

This page documents the helper functions that the frontend, the backend and the
command line program share.  Start with L<Class::Shared::Frontend> if you only
want to use a shared class.

=head2 Words used in this documentation

=over 4

=item backend

The one process that loads the class and holds the real objects.

=item frontend

The small stand-in object in your own process.  It forwards each method call to
the backend and gives you back the answer.

=item unix socket

A special file that two programs on the same machine use to talk to each other.
Its file permissions decide who may connect.

=item TCP

The way programs on different machines talk to each other over a network.  Here
it is always protected by TLS.

=item TLS

Encryption for a network connection.  Each side also shows a certificate to
prove who it is.

=item certificate, CA

A certificate is a small file that says "this key belongs to this name".  A CA
(certificate authority) is the organisation, or your own private key pair, that
signs certificates so others can trust them.

=item fingerprint

A short code (SHA-256) that identifies exactly one certificate.  A client can
trust one certificate by its fingerprint instead of trusting a CA.

=item token

A shared secret, kept in a file, that both sides of a TCP connection know.  It
proves that each message came from somebody who has the secret.

=item frame

One message on the wire: a length, then the data.  See
L<Class::Shared::Protocol>.

=item handshake

The first message a client sends.  It names the class the client wants.

=item context

Perl's idea of what the caller wants back from a call: a list, one value, or
nothing (void).  Class::Shared keeps the context you used.

=back

=head1 FUNCTIONS

None is exported.  They are used by the frontend and the backend, and may be
useful when writing your own client.  Call each one with its full name, for
example C<Class::Shared::validate_class($name)>.

A function either returns its answer or, when it cannot, dies with a message
that begins C<Class::Shared:> and ends with a new line.  The one exception is
C<ensure_dir>, which returns a pair so that the reason can be shown to the user.

The schemas in each B<API SPECIFICATION> follow the conventions of
L<Params::Validate::Strict> (for input) and L<Return::Set> (for output).  They
describe the function for people and for tools.  The code does not call those
two modules, and this distribution does not depend on them.

=head2 validate_class

    my $class = Class::Shared::validate_class($class);

Checks that C<$class> looks like a Perl package name, and returns it unchanged.
Use it before you pass a name to C<require> or build a file name from it.

A valid name is one or more words joined by C<::>.  Each word starts with an
English letter or an underscore and then has letters, digits or underscores.
So C<Class::Simple> and C<My_Class2> are valid, and C<2Bad>, C<Foo::> and
C<Foo-Bar> are not.

B<Side effects:> none.

B<Dies> with C<Class::Shared: no class name given> if C<$class> is undef or
empty, and with C<Class::Shared: 'NAME' is not a valid class name> otherwise.
The domains and boundaries these two messages divide are listed under
B<API SPECIFICATION> below, and F<t/domain.t> tests every one of them.

=head3 API SPECIFICATION

=head4 Input

    {
        class => {
            type     => 'string',
            position => 0,
            optional => 0,
            min      => 1,
            matches  => qr/\A[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*\z/,
        },
    }

=head4 Domains

    valid    one or more ASCII words, each starting with a letter or "_" and
             continuing with letters, digits or "_", joined by "::"
    invalid  undef, the empty string, a leading digit in any word, an empty
             word, any other separator, any non-ASCII character

    partition                representative           result
    -------------------------------------------------------------
    one word                 Foo                      accepted
    several words            Foo::Bar::Baz            accepted
    digits and underscores   My_Class2, A::_2         accepted
    length 1                 A, _                     accepted
    empty string             ""                       dies: no class name
    leading digit            2Foo                     dies
    empty word               Foo::, ::Foo, A:::B      dies
    hyphen, space or dot     Foo-Bar, Foo Bar         dies
    non-ASCII letter         "M" + U+00FC + "ller"    dies
    emoji, RTL override      U+1F600, U+202E          dies

    Boundary values: length 0 dies, length 1 is the smallest accepted.  There
    is no maximum: a 40,000 character name is accepted, because the check does
    not repeat a group (perl 5.26 stops a repeated group at 32,766 repeats).
    Only the pattern in this specification can match, so the answer is
    untainted and safe to use as a module name.

=head4 Output

    { type => 'string', matches => qr/\A[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*\z/ }

=cut
288
289sub validate_class {
290
3273
1744436
        my $class = $_[0];
291
292
3273
5613
        die "Class::Shared: no class name given\n"
293                unless defined $class && length $class;
294
295        # The captured copy is returned, not the argument: it is the only text that
296        # has been matched against the pattern, so under taint mode (-T) it is
297        # untainted by the check that proves it safe.
298
3240
47860
        my ($valid) = $class =~ $CLASS_CHARS_RE
299                or die "Class::Shared: '$class' is not a valid class name\n";
300
301        # -1 keeps a trailing empty part, so "A::" and "A:::B" are refused.
302
2849
407345
        foreach my $part (split /::/, $valid, -1) {
303
524749
751320
                $part =~ $CLASS_PART_RE
304                        or die "Class::Shared: '$class' is not a valid class name\n";
305        }
306
307
2081
19263
        return $valid;
308}
309
310 - 362
=head2 read_secret

    my $secret = Class::Shared::read_secret('/etc/class-shared/token');

Reads a shared secret (a token) from a file and returns it.  The whole file is
read as bytes.  White space at the end, including the final new line, is
removed.  White space at the start, and any inside the secret, is kept.

Never put a secret on a command line, where other users can see it.  Give its
file name instead and let this function read it.

B<Side effects:> opens, reads and closes the file.

B<Dies> if no file name is given, if the file cannot be read, if it is larger
than 65536 bytes (which also refuses an endless file such as F</dev/zero>), or
if the secret is empty after the end of it has been trimmed.

=head3 API SPECIFICATION

=head4 Input

    {
        path => { type => 'string', position => 0, optional => 0, min => 1 },
    }

=head4 Domains

    valid    a path to a readable file whose content, after trailing white
             space is removed, is 1 to 65536 bytes
    invalid  undef, the empty path, an unreadable path, a directory, a file
             larger than 65536 bytes, and a file that is empty after trimming

    partition            representative        result
    -----------------------------------------------------------
    1 byte               "a"                   accepted
    trailing white space "secret \r\n"         trimmed
    leading white space  "  secret"            kept
    white space only     "\n\t "               dies: is empty
    0 bytes              ""                    dies: is empty
    65536 bytes          "a" x 65536           accepted
    65537 bytes          "a" x 65537           dies: too large

    Boundary values: 0 bytes dies, 1 byte is the smallest accepted, 65536
    bytes is the largest accepted, 65537 dies.  The size is counted in bytes,
    so the limit is the same for a UTF-8 or a binary secret.  The content is
    returned as bytes, unchanged and not decoded, so an embedded NUL and a
    multibyte character cost exactly what they occupy in the file.

=head4 Output

    { type => 'string', min => 1 }

=cut
363
364# A shared secret for a backend listening on a network socket.  Never pass
365# secrets on a command line: give a file and let the caller read it.
366# The most read_secret accepts, in bytes.  A token is a line of text.
367our $MAX_SECRET = 65536;
368
369sub read_secret {
370
619
103933
        my $path = $_[0];
371
372
619
1252
        die "Class::Shared: no token file given\n" unless defined $path && length $path;
373
374
589
6492
        open(my $fh, '<', $path) or die "Class::Shared: cannot read $path: $!\n";
375
376        # One byte more than is allowed is asked for, and no more: a "file" such as
377        # /dev/zero never ends, and reading it whole would use all the memory.
378
451
414
        my $secret = '';
379
451
511
        while (length($secret) <= $MAX_SECRET) {
380
707
4364
                my $got = read($fh, $secret, $MAX_SECRET + 1 - length($secret), length($secret));
381
382                # Some systems (macOS) let a directory be opened and only fail here.
383
707
1193
                die "Class::Shared: cannot read $path: $!\n" unless defined $got;
384
642
695
                last unless $got;
385        }
386
387
386
1056
        close($fh) or die "Class::Shared: cannot read $path: $!\n";
388
389
386
556
        die "Class::Shared: $path is too large to be a secret (more than $MAX_SECRET bytes)\n"
390                if length($secret) > $MAX_SECRET;
391
392
325
1552
        $secret =~ s/\s+\z//;
393
394
325
568
        die "Class::Shared: $path is empty\n" unless length $secret;
395
396
236
577
        return $secret;
397}
398
399# A SHA-256 fingerprint of a certificate, in the shape IO::Socket::SSL wants
400# for SSL_fingerprint.  Accepts the colon-separated form openssl prints, with
401# or without a "sha256$" prefix, so a pin can be pasted straight from
402# "openssl x509 -fingerprint -sha256".
403my $FINGERPRINT_RE = qr{
404        \A
405        (?: sha256 \$ )?
406        ( (?:[0-9A-Fa-f]{2}:){31}[0-9A-Fa-f]{2} | [0-9A-Fa-f]{64} )
407        \z
408}x;
409
410sub normalise_fingerprint {
411
309
84744
        my $value = $_[0];
412
413
309
785
        die "Class::Shared: no TLS fingerprint given\n"
414                unless defined $value && length $value;
415
416
278
5091
        my ($hex) = $value =~ $FINGERPRINT_RE
417                or die "Class::Shared: '$value' is not a SHA-256 certificate fingerprint: "
418                        . "give 64 hexadecimal digits, optionally colon-separated\n";
419
420
119
307
        $hex =~ s/://g;
421
422
119
331
        return 'sha256$' . lc $hex;
423}
424
425# The TLS options a client hands to IO::Socket::SSL->new, in one place so the
426# frontend and the command line cannot drift apart about what verification
427# means.  IO::Socket::SSL is loaded here rather than at the top of this module:
428# a unix socket never needs any of it.
429sub client_tls_options {
430
162
2380797
        my (%opt) = @_;
431
432
162
389
        require IO::Socket::SSL;
433
434        my %tls = (
435                SSL_version     => $TLS_VERSIONS,
436                SSL_cert_file   => $opt{cert},
437                SSL_key_file    => $opt{key},
438
158
711
                SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_PEER(),
439        );
440
441
158
243
        if (defined $opt{fingerprint}) {
442                # A pin names one exact certificate, so it stands in for both the CA
443                # and the name, and SSL_force_fingerprint makes the digest the only
444                # thing that can accept the peer.
445
36
49
                $tls{SSL_fingerprint}       = $opt{fingerprint};
446
36
44
                $tls{SSL_force_fingerprint} = 1;
447
36
71
                $tls{SSL_verifycn_scheme}   = 'none';
448        } else {
449
122
243
                $tls{SSL_ca_file} = $opt{ca};
450        }
451
452
158
864
        return %tls;
453}
454
455sub dir_of {
456
1125
250421
        my ($path) = @_;
457
1125
187066
        my $dir = File::Basename::dirname($path);
458
1125
2918
        return length $dir ? $dir : '/';
459}
460
461# Sleep for one polling interval.  Used by every loop that waits for something
462# on the file system, so none of them spins and all of them wake at the same
463# rate.  select is the portable sub-second sleep that needs no extra module.
464sub poll_pause {
465
8604
156572254
        select(undef, undef, undef, $POLL_INTERVAL);
466
467
8604
57691
        return;
468}
469
470# Point STDIN at the null device and STDOUT and STDERR at the log, so a
471# background process holds no terminal and its diagnostics land somewhere.  If
472# the log cannot be opened they go to the null device instead: a backend that
473# cannot log should still run.  Returns (1, undef), or (0, $why) if a stream
474# could not be reopened; the caller decides whether that is fatal, because
475# this is used both by the backend and by the forked child that becomes one.
476sub detach_standard_streams {
477
46
347
        my ($log) = @_;
478
479
46
3215
        my $null = File::Spec->devnull;
480
481
46
3459
        open(STDIN, '<', $null) or return (0, "cannot reopen STDIN on $null: $!");
482
483
46
2945
        if (open(my $log_fh, '>>', $log)) {
484
44
1236
                open(STDOUT, '>&', $log_fh) or return (0, "cannot send STDOUT to $log: $!");
485
44
805
                open(STDERR, '>&', $log_fh) or return (0, "cannot send STDERR to $log: $!");
486
44
580
                close($log_fh) or return (0, "cannot close $log: $!");
487        } else {
488
2
40
                open(STDOUT, '>', $null) or return (0, "cannot send STDOUT to $null: $!");
489
2
36
                open(STDERR, '>&', \*STDOUT) or return (0, "cannot send STDERR to $null: $!");
490        }
491
492
46
375
        return (1, undef);
493}
494
495# Where per-user sockets live.  Kept short because the path ends up in a
496# sockaddr_un, and per-user because the socket is a trust boundary.
497sub default_dir {
498
858
53318
        my (%opt) = @_;
499
500
858
662
        my $dir;
501
502
858
4813
        if (defined $opt{dir} && length $opt{dir}) {
503
763
880
                $dir = $opt{dir};
504        } elsif (defined $ENV{CLASS_SHARED_DIR} && length $ENV{CLASS_SHARED_DIR}) {
505
50
60
                $dir = $ENV{CLASS_SHARED_DIR};
506        } elsif (defined $ENV{XDG_RUNTIME_DIR} && length $ENV{XDG_RUNTIME_DIR} && -d $ENV{XDG_RUNTIME_DIR}) {
507
19
116
                $dir = File::Spec->catdir($ENV{XDG_RUNTIME_DIR}, 'class-shared');
508        } elsif (-d "/run/user/$>") {
509
26
169
                $dir = File::Spec->catdir("/run/user/$>", 'class-shared');
510        } else {
511
0
0
                $dir = File::Spec->catdir(File::Spec->tmpdir, "class-shared-$>");
512        }
513
514        # The directory may come from the environment or the caller, both of which
515        # are tainted under -T, and perl refuses to mkdir or open a file in a
516        # tainted path.  A name is not dangerous because of what it says, only
517        # because of what it is used for, and everything made here is checked by
518        # ensure_dir (ours, and closed to others) before anything is trusted in it.
519        # The one thing that is refused outright is a NUL byte, which would end
520        # the name early in the system call and so name a different place.
521
858
3659
        my ($clean) = $dir =~ /\A([^\0]+)\z/
522                or die "Class::Shared: a directory name may not contain a NUL byte\n";
523
524
825
1281
        return $clean;
525}
526
527# Whether this perl can make a unix domain socket, which is what a backend is
528# reached through and what a frontend starts one over.  Probed rather than
529# assumed from $^O: a Cygwin perl is not MSWin32 and has them, and a platform
530# without them is refused whatever it calls itself.  The answer cannot change
531# during a run, so it is asked for once.
532our $UNIX_SOCKETS;
533
534sub _has_unix_sockets {
535
1333
2355076
        return $UNIX_SOCKETS if defined $UNIX_SOCKETS;
536
537
144
148
        $UNIX_SOCKETS = eval {
538                # Both have to work.  A Windows perl 5.26 emulates socketpair, so it
539                # succeeds, but cannot name a unix socket, and pack_sockaddr_un dies.
540                # IO::Socket::UNIX is not required here: it would cost every client
541                # process about 1.2 MB, and the backend and the command load it
542                # themselves when they need it.
543
144
14995
                require Socket;
544
545
144
103332
                Socket::pack_sockaddr_un('probe');
546
547
143
7159
                socketpair(my $reader, my $writer, Socket::AF_UNIX(), Socket::SOCK_STREAM(), 0)
548                        ? 1
549                        : 0;
550        } ? 1 : 0;
551
552
144
255
        return $UNIX_SOCKETS;
553}
554
555# Nothing here can work without unix domain sockets, so say that where it is
556# tried rather than blaming the directory the caller passed: on a platform
557# without them there is no directory that would have helped.  Whether they
558# exist can be given as an argument, so the refusal is exercised by the suite
559# on machines that have them.
560sub _require_unix_sockets {
561
1258
99957
        my ($what, $has_unix_sockets) = @_;
562
563
1258
2063
        $has_unix_sockets = _has_unix_sockets() unless defined $has_unix_sockets;
564
565
1258
1927
        return if $has_unix_sockets;
566
567
49
245
        die "Class::Shared: $what is not available here: this perl has no unix "
568                . "domain sockets, so a backend could neither be reached nor started.  "
569                . "This distribution is Unix-only (see PLATFORMS)\n";
570}
571
572# Create $dir if needed and make sure nobody else can drop a socket in it.
573# Returns (1, undef), or (0, $why_not), as the POD documents.
574sub ensure_dir {
575
515
580497
        my ($dir) = @_;
576
577
515
1795
        die "Class::Shared: no directory given\n" unless defined $dir && length $dir;
578
579
490
821
        _require_unix_sockets('a backend directory');
580
581
476
2198
        if (!-d $dir) {
582                # Losing a race to make it is not a failure; what the winner made is
583                # checked below like any directory that was already there.
584
81
1886
                if (!mkdir($dir, 0700)) {
585
41
356
                        my $why = "$!";
586
41
264
                        return (0, "cannot create $dir: $why") unless -d $dir;
587                }
588        }
589
590
437
692
        return _check_dir($dir);
591}
592
593# Purpose:       say whether $dir is somewhere only this user can put a socket.
594# Entry:         $dir is a directory name; nothing is created.
595# Exit status:   (1, undef) when it is ours and not writable by group or
596#                others, otherwise (0, $why_not).
597# Side effects:  none.
598sub _check_dir {
599
1168
41444
        my ($dir) = @_;
600
601
1168
5471
        my @stat = stat($dir);
602
1168
1801
        return (0, "cannot stat $dir: $!") unless @stat;
603
604
1161
3789
        return (0, "$dir is owned by uid $stat[4], not by uid $>")
605                if $stat[4] != $>;
606
607
1144
1753
        return (0, "$dir is writable by group or others; refusing to use it")
608                if $stat[2] & 0022;
609
610
1015
1675
        return (1, undef);
611}
612
613# Purpose:       decide whether to talk to the socket at $path.  What comes back
614#                over it is thawed by Storable, so a socket made by another user
615#                must never be trusted: it could answer with whatever it likes,
616#                and would be told every argument the client sends.
617# Entry:         $path names a socket that is known to exist.
618# Exit status:   (1, undef) when its directory is safe (see _check_dir) and the
619#                socket is a socket owned by this user, otherwise (0, $why_not).
620# Side effects:  none.
621# Why both:      a safe directory means nobody else could have put the socket
622#                there; the owner check catches a socket that was already there.
623sub _check_endpoint {
624
686
2917019
        my ($path) = @_;
625
626
686
1660
        my ($safe, $why) = _check_dir(dir_of($path));
627
686
1063
        return (0, $why) unless $safe;
628
629
656
2526
        my @stat = stat($path);
630
656
1290
        return (0, "cannot stat $path: $!") unless @stat;
631
632
646
878
        return (0, "$path is not a socket") unless -S _;
633
634
630
1263
        return (0, "$path is owned by uid $stat[4], not by uid $>")
635                if $stat[4] != $>;
636
637
624
1012
        return (1, undef);
638}
639
640# One socket for every class.  The backend behind it is told which class a
641# client wants when that client connects, so the path names no class and one
642# backend can serve as many as are asked for.
643sub socket_path {
644
732
17327012
        my ($dir) = @_;
645
646
732
2027
        _require_unix_sockets('a unix socket');
647
648
718
1495
        $dir = default_dir(dir => $dir);
649
650
712
5668
        return check_socket_path(File::Spec->catfile($dir, 'class-shared.sock'));
651}
652
653# A path that will not fit in a sockaddr_un is silently truncated by the
654# operating system, so a client and a backend could end up on different
655# sockets.  Refuse it instead.  Applies to a path given explicitly as well as
656# one socket_path built.
657sub check_socket_path {
658
2429
78752
        my ($path) = @_;
659
660
2429
4640
        die "Class::Shared: no socket path given\n" unless defined $path && length $path;
661
662
2421
2509
        if (length($path) > $MAX_SOCKET_PATH) {
663
142
486
                die sprintf("Class::Shared: socket path '%s' is %d characters, more than the %d allowed; "
664                        . "set CLASS_SHARED_DIR or pass dir => to a shorter directory\n",
665                        $path, length($path), $MAX_SOCKET_PATH);
666        }
667
668
2279
2806
        return $path;
669}
670
6711;
672