]> Sergey Matveev's repositories - public-inbox.git/blob - script/lei
lei: FD-passing and IPC basics
[public-inbox.git] / script / lei
1 #!perl -w
2 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict;
5 use v5.10.1;
6 use Cwd qw(cwd);
7 use IO::Socket::UNIX;
8
9 if (eval { require IO::FDPass; 1 }) { # use daemon to reduce load time
10         my $path = do {
11                 my $runtime_dir = ($ENV{XDG_RUNTIME_DIR} // '') . '/lei';
12                 if ($runtime_dir eq '/lei') {
13                         require File::Spec;
14                         $runtime_dir = File::Spec->tmpdir."/lei-$<";
15                 }
16                 unless (-d $runtime_dir && -w _) {
17                         require File::Path;
18                         File::Path::mkpath($runtime_dir, 0, 0700);
19                 }
20                 "$runtime_dir/sock";
21         };
22         my $sock = IO::Socket::UNIX->new(Peer => $path, Type => SOCK_STREAM);
23         unless ($sock) { # start the daemon if not started
24                 my $err = $!;
25                 require PublicInbox::LeiDaemon;
26                 $err = PublicInbox::LeiDaemon::lazy_start($path, $err);
27                 # try connecting again anyways, unlink+bind may be racy
28                 $sock = IO::Socket::UNIX->new(Peer => $path,
29                                                 Type => SOCK_STREAM) // die
30                         "connect($path): $! (bind($path): $err)";
31         }
32         my $pwd = $ENV{PWD};
33         my $cwd = cwd();
34         if ($pwd) { # prefer ENV{PWD} if it's a symlink to real cwd
35                 my @st_cwd = stat($cwd) or die "stat(cwd=$cwd): $!\n";
36                 my @st_pwd = stat($pwd);
37                 # make sure st_dev/st_ino match for {PWD} to be valid
38                 $pwd = $cwd if (!@st_pwd || $st_pwd[1] != $st_cwd[1] ||
39                                         $st_pwd[0] != $st_cwd[0]);
40         } else {
41                 $pwd = $cwd;
42         }
43         local $ENV{PWD} = $pwd;
44         $sock->autoflush(1);
45         IO::FDPass::send(fileno($sock), $_) for (0..2);
46         my $buf = "$$\0\0>" . join("]\0[", @ARGV) . "\0\0>";
47         while (my ($k, $v) = each %ENV) { $buf .= "$k=$v\0" }
48         $buf .= "\0\0";
49         print $sock $buf or die "print(sock, buf): $!";
50         local $/ = "\n";
51         while (my $line = <$sock>) {
52                 $line =~ /\Aexit=([0-9]+)\n\z/ and exit($1 + 0);
53                 die $line;
54         }
55 } else { # for systems lacking IO::FDPass
56         require PublicInbox::LeiDaemon;
57         PublicInbox::LeiDaemon::oneshot();
58 }