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_SEQPACKET MSG_EOR pack_sockaddr_un);
7 use Errno qw(EINTR ECONNRESET);
8 use PublicInbox::CmdIPC4;
11 my $recv_cmd = PublicInbox::CmdIPC4->can('recv_cmd4');
12 my $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4') // do {
13 require PublicInbox::Spawn; # takes ~50ms even if built *sigh*
14 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
15 PublicInbox::Spawn->can('send_cmd4');
20 my $flags = $sig ? POSIX::WNOHANG() : 0;
21 while (waitpid(-1, $flags) > 0) {}
25 my ($fds, $argc, @argv) = @_;
26 my @old = (*STDIN{IO}, *STDOUT{IO}, *STDERR{IO});
29 open(my $tmpfh, '+<&=', $fd) or die "open +<&=$fd: $!";
30 push @rdr, shift(@old), $tmpfh;
32 require POSIX; # WNOHANG
33 $SIG{CHLD} = \&sigchld;
34 my $pid = fork // die "fork: $!";
36 my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
37 while (my ($old_io, $tmpfh) = splice(@rdr, 0, 2)) {
38 open $old_io, '+<&', $tmpfh or die "open +<&=: $!";
42 die "exec: @argv: $!";
46 if ($send_cmd && eval {
48 my $runtime_dir = ($ENV{XDG_RUNTIME_DIR} // '') . '/lei';
49 if ($runtime_dir eq '/lei') {
51 $runtime_dir = File::Spec->tmpdir."/lei-$<";
53 unless (-d $runtime_dir) {
55 File::Path::mkpath($runtime_dir, 0, 0700);
57 "$runtime_dir/$narg.seq.sock";
59 my $addr = pack_sockaddr_un($path);
60 socket($sock, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
61 unless (connect($sock, $addr)) { # start the daemon if not started
62 local $ENV{PERL5LIB} = join(':', @INC);
63 open(my $daemon, '-|', $^X, qw[-MPublicInbox::LEI
64 -E PublicInbox::LEI::lazy_start(@ARGV)],
65 $path, $! + 0, $narg) or die "popen: $!";
66 while (<$daemon>) { warn $_ } # EOF when STDERR is redirected
67 close($daemon) or warn <<"";
68 lei-daemon could not start, exited with \$?=$?
70 # try connecting again anyways, unlink+bind may be racy
71 connect($sock, $addr) or die <<"";
72 connect($path): $! (after attempted daemon start)
73 Falling back to (slow) one-shot mode
77 }) { # (Socket::MsgHdr|Inline::C), $sock, $pwd are all available:
78 open my $dh, '<', '.' or die "open(.) $!";
79 my $buf = join("\0", scalar(@ARGV), @ARGV);
80 while (my ($k, $v) = each %ENV) { $buf .= "\0$k=$v" }
82 $send_cmd->($sock, [ 0, 1, 2, fileno($dh) ], $buf, MSG_EOR);
85 my (@fds) = $recv_cmd->($sock, $buf, 4096 * 33);
86 if (scalar(@fds) == 1 && !defined($fds[0])) {
87 last if $! == ECONNRESET;
92 if ($buf =~ /\Ax_it ([0-9]+)\z/) {
95 } elsif ($buf =~ /\Achild_error ([0-9]+)\z/) {
97 } elsif ($buf =~ /\Aexec (.+)\z/) {
98 exec_cmd(\@fds, split(/\0/, $1));
105 if (my $sig = ($x_it_code & 127)) {
109 exit($x_it_code >> 8);
110 } else { # for systems lacking Socket::MsgHdr or Inline::C
112 require PublicInbox::LEI;
113 PublicInbox::LEI::oneshot(__PACKAGE__);