]> Sergey Matveev's repositories - public-inbox.git/blob - script/lei
lei: use send() perlop for signals
[public-inbox.git] / script / lei
1 #!perl -w
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>
4 use strict;
5 use v5.10.1;
6 use Socket qw(AF_UNIX SOCK_SEQPACKET MSG_EOR pack_sockaddr_un);
7 use PublicInbox::CmdIPC4;
8 my $narg = 5;
9 my $sock;
10 my $recv_cmd = PublicInbox::CmdIPC4->can('recv_cmd4');
11 my $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4') // do {
12         my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
13                         $ENV{XDG_CACHE_HOME} //
14                         ( ($ENV{HOME} // '/nonexistent').'/.cache' )
15                         ).'/public-inbox/inline-c';
16         if (!-d $inline_dir) {
17                 require File::Path;
18                 File::Path::make_path($inline_dir);
19         }
20         require PublicInbox::Spawn; # takes ~50ms even if built *sigh*
21         $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
22         PublicInbox::Spawn->can('send_cmd4');
23 } // die 'please install Inline::C or Socket::MsgHdr';
24
25 my %pids;
26 my $sigchld = sub {
27         my $flags = scalar(@_) ? POSIX::WNOHANG() : 0;
28         for my $pid (keys %pids) {
29                 delete($pids{$pid}) if waitpid($pid, $flags) == $pid;
30         }
31 };
32 my @parent;
33 my $exec_cmd = sub {
34         my ($fds, $argc, @argv) = @_;
35         my $parent = $$;
36         require POSIX;
37         my @old = (*STDIN{IO}, *STDOUT{IO}, *STDERR{IO});
38         my @rdr;
39         for my $fd (@$fds) {
40                 open(my $newfh, '+<&=', $fd) or die "open +<&=$fd: $!";
41                 push @rdr, shift(@old), $newfh;
42         }
43         my $do_exec = sub {
44                 my @non_std; # ex. $op_p from lei_edit_search
45                 while (my ($io, $newfh) = splice(@rdr, 0, 2)) {
46                         my $old_io = !!$io;
47                         open $io, '+<&', $newfh or die "open +<&=: $!";
48                         push @non_std, $io unless $old_io;
49                 }
50                 if (@non_std) {
51                         require Fcntl;
52                         fcntl($_, Fcntl::F_SETFD(), 0) for @non_std;
53                 }
54                 my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
55                 @ENV{keys %env} = values %env;
56                 umask 077;
57                 exec(@argv);
58                 warn "exec: @argv: $!\n";
59                 POSIX::_exit(1);
60         };
61         $SIG{CHLD} = $sigchld;
62         my $pid = fork // die "fork: $!";
63         if ($pid == 0) {
64                 $do_exec->() if $fds->[1]; # git-credential, pager
65
66                 # parent backgrounds on MUA
67                 POSIX::setsid() > 0 or die "setsid: $!";
68                 @parent = ($parent);
69                 return; # continue $recv_cmd in background
70         }
71         if ($fds->[1]) {
72                 $pids{$pid} = undef;
73         } else {
74                 $do_exec->(); # MUA reuses stdout
75         }
76 };
77
78 my $runtime_dir = ($ENV{XDG_RUNTIME_DIR} // '') . '/lei';
79 if ($runtime_dir eq '/lei') {
80         require File::Spec;
81         $runtime_dir = File::Spec->tmpdir."/lei-$<";
82 }
83 unless (-d $runtime_dir) {
84         require File::Path;
85         File::Path::make_path($runtime_dir, { mode => 0700 });
86 }
87 my $path = "$runtime_dir/$narg.seq.sock";
88 my $addr = pack_sockaddr_un($path);
89 socket($sock, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
90 unless (connect($sock, $addr)) { # start the daemon if not started
91         local $ENV{PERL5LIB} = join(':', @INC);
92         open(my $daemon, '-|', $^X, qw[-MPublicInbox::LEI
93                 -E PublicInbox::LEI::lazy_start(@ARGV)],
94                 $path, $! + 0, $narg) or die "popen: $!";
95         while (<$daemon>) { warn $_ } # EOF when STDERR is redirected
96         close($daemon) or warn <<"";
97 lei-daemon could not start, exited with \$?=$?
98
99         # try connecting again anyways, unlink+bind may be racy
100         connect($sock, $addr) or die <<"";
101 connect($path): $! (after attempted daemon start)
102
103 }
104 # (Socket::MsgHdr|Inline::C), $sock are all available:
105 open my $dh, '<', '.' or die "open(.) $!";
106 my $buf = join("\0", scalar(@ARGV), @ARGV);
107 while (my ($k, $v) = each %ENV) { $buf .= "\0$k=$v" }
108 $buf .= "\0\0";
109 $send_cmd->($sock, [0, 1, 2, fileno($dh)], $buf, MSG_EOR) or die "sendmsg: $!";
110 $SIG{TSTP} = sub { send($sock, 'STOP', MSG_EOR); kill 'STOP', $$ };
111 $SIG{CONT} = sub { send($sock, 'CONT', MSG_EOR) };
112
113 my $x_it_code = 0;
114 while (1) {
115         my (@fds) = $recv_cmd->($sock, my $buf, 4096 * 33);
116         if (scalar(@fds) == 1 && !defined($fds[0])) {
117                 next if $!{EINTR};
118                 die "recvmsg: $!";
119         }
120         last if $buf eq '';
121         if ($buf =~ /\Aexec (.+)\z/) {
122                 $exec_cmd->(\@fds, split(/\0/, $1));
123         } elsif ($buf eq '-WINCH') {
124                 kill($buf, @parent); # for MUA
125         } elsif ($buf eq 'umask') {
126                 send($sock, 'u'.pack('V', umask), MSG_EOR) or die "send: $!"
127         } elsif ($buf =~ /\Ax_it ([0-9]+)\z/) {
128                 $x_it_code ||= $1 + 0;
129                 last;
130         } elsif ($buf =~ /\Achild_error ([0-9]+)\z/) {
131                 $x_it_code ||= $1 + 0;
132         } elsif ($buf eq 'wait') {
133                 $sigchld->();
134         } else {
135                 $sigchld->();
136                 die $buf;
137         }
138 }
139 $sigchld->();
140 if (my $sig = ($x_it_code & 127)) {
141         kill $sig, $$;
142         sleep(1) while 1; # no self-pipe/signalfd, here, so we loop
143 }
144 exit($x_it_code >> 8);