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