2 # Copyright (C) 2020 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 if (my ($sock, $pwd) = eval {
8 require IO::FDPass; # will try to use a daemon to reduce load time
10 my $runtime_dir = ($ENV{XDG_RUNTIME_DIR} // '') . '/lei';
11 if ($runtime_dir eq '/lei') {
13 $runtime_dir = File::Spec->tmpdir."/lei-$<";
15 unless (-d $runtime_dir) {
17 File::Path::mkpath($runtime_dir, 0, 0700);
21 my $addr = pack_sockaddr_un($path);
22 socket(my $sock, AF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
23 unless (connect($sock, $addr)) { # start the daemon if not started
24 local $ENV{PERL5LIB} = join(':', @INC);
25 open(my $daemon, '-|', $^X, qw[-MPublicInbox::LEI
26 -E PublicInbox::LEI::lazy_start(@ARGV)],
27 $path, $! + 0) or die "popen: $!";
28 while (<$daemon>) { warn $_ } # EOF when STDERR is redirected
29 close($daemon) or warn <<"";
30 lei-daemon could not start, exited with \$?=$?
32 # try connecting again anyways, unlink+bind may be racy
33 unless (connect($sock, $addr)) {
35 connect($path): $! (after attempted daemon start)
36 Falling back to (slow) one-shot mode
41 my $pwd = $ENV{PWD} // '';
42 my $cwd = Cwd::fastcwd() // die "fastcwd(PWD=$pwd): $!";
43 if ($pwd ne $cwd) { # prefer ENV{PWD} if it's a symlink to real cwd
44 my @st_cwd = stat($cwd) or die "stat(cwd=$cwd): $!";
45 my @st_pwd = stat($pwd); # PWD invalid, use cwd
46 # make sure st_dev/st_ino match for {PWD} to be valid
47 $pwd = $cwd if (!@st_pwd || $st_pwd[1] != $st_cwd[1] ||
48 $st_pwd[0] != $st_cwd[0]);
53 }) { # IO::FDPass, $sock, $pwd are all available:
54 local $ENV{PWD} = $pwd;
55 my $buf = "$$\0\0>" . join("]\0[", @ARGV) . "\0\0>";
56 while (my ($k, $v) = each %ENV) { $buf .= "$k=$v\0" }
59 $| = 1; # unbuffer selected $sock
60 IO::FDPass::send(fileno($sock), $_) for (0..2);
61 print $sock $buf or die "print(sock, buf): $!";
62 while ($buf = <$sock>) {
63 $buf =~ /\Aexit=([0-9]+)\n\z/ and exit($1 + 0);
66 } else { # for systems lacking IO::FDPass
67 # don't warn about IO::FDPass since it's not commonly installed
68 warn $@ if $@ && index($@, 'IO::FDPass') < 0;
69 require PublicInbox::LEI;
70 PublicInbox::LEI::oneshot(__PACKAGE__);