2 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
6 use Socket qw(AF_UNIX SOCK_STREAM pack_sockaddr_un);
7 use PublicInbox::CmdIPC4;
9 my $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4') // do {
10 require PublicInbox::CmdIPC1; # 2nd choice
12 PublicInbox::CmdIPC1->can('send_cmd1');
14 require PublicInbox::Spawn; # takes ~50ms even if built *sigh*
16 PublicInbox::Spawn->can('send_cmd4');
20 if ($send_cmd && eval {
22 my $runtime_dir = ($ENV{XDG_RUNTIME_DIR} // '') . '/lei';
23 if ($runtime_dir eq '/lei') {
25 $runtime_dir = File::Spec->tmpdir."/lei-$<";
27 unless (-d $runtime_dir) {
29 File::Path::mkpath($runtime_dir, 0, 0700);
31 "$runtime_dir/$narg.sock";
33 my $addr = pack_sockaddr_un($path);
34 socket($sock, AF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
35 unless (connect($sock, $addr)) { # start the daemon if not started
36 local $ENV{PERL5LIB} = join(':', @INC);
37 open(my $daemon, '-|', $^X, qw[-MPublicInbox::LEI
38 -E PublicInbox::LEI::lazy_start(@ARGV)],
39 $path, $! + 0, $narg) or die "popen: $!";
40 while (<$daemon>) { warn $_ } # EOF when STDERR is redirected
41 close($daemon) or warn <<"";
42 lei-daemon could not start, exited with \$?=$?
44 # try connecting again anyways, unlink+bind may be racy
45 connect($sock, $addr) or die <<"";
46 connect($path): $! (after attempted daemon start)
47 Falling back to (slow) one-shot mode
51 $pwd = $ENV{PWD} // '';
52 my $cwd = Cwd::fastcwd() // die "fastcwd(PWD=$pwd): $!";
53 if ($pwd ne $cwd) { # prefer ENV{PWD} if it's a symlink to real cwd
54 my @st_cwd = stat($cwd) or die "stat(cwd=$cwd): $!";
55 my @st_pwd = stat($pwd); # PWD invalid, use cwd
56 # make sure st_dev/st_ino match for {PWD} to be valid
57 $pwd = $cwd if (!@st_pwd || $st_pwd[1] != $st_cwd[1] ||
58 $st_pwd[0] != $st_cwd[0]);
63 }) { # (Socket::MsgHdr|IO::FDPass|Inline::C), $sock, $pwd are all available:
64 local $ENV{PWD} = $pwd;
65 my $buf = join("\0", $$, scalar(@ARGV), @ARGV);
66 while (my ($k, $v) = each %ENV) { $buf .= "\0$k=$v" }
69 $| = 1; # unbuffer selected $sock
70 $send_cmd->($sock, 0, 1, 2, $buf, 0);
71 while ($buf = <$sock>) {
72 $buf =~ /\Aexit=([0-9]+)\n\z/ and exit($1 + 0);
75 } else { # for systems lacking Socket::MsgHdr, IO::FDPass or Inline::C
77 require PublicInbox::LEI;
78 PublicInbox::LEI::oneshot(__PACKAGE__);