]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LEI.pm
lei: support pass-through for `lei config'
[public-inbox.git] / lib / PublicInbox / LEI.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Backend for `lei' (local email interface).  Unlike the C10K-oriented
5 # PublicInbox::Daemon, this is designed exclusively to handle trusted
6 # local clients with read/write access to the FS and use as many
7 # system resources as the local user has access to.
8 package PublicInbox::LEI;
9 use strict;
10 use v5.10.1;
11 use parent qw(PublicInbox::DS);
12 use Getopt::Long ();
13 use Errno qw(EAGAIN ECONNREFUSED ENOENT);
14 use POSIX qw(setsid);
15 use IO::Socket::UNIX;
16 use IO::Handle ();
17 use Sys::Syslog qw(syslog openlog);
18 use PublicInbox::Config;
19 use PublicInbox::Syscall qw($SFD_NONBLOCK EPOLLIN EPOLLONESHOT);
20 use PublicInbox::Sigfd;
21 use PublicInbox::DS qw(now);
22 use PublicInbox::Spawn qw(spawn);
23 use Text::Wrap qw(wrap);
24 use File::Path qw(mkpath);
25 use File::Spec;
26 our $quit = \&CORE::exit;
27 my $GLP = Getopt::Long::Parser->new;
28 $GLP->configure(qw(gnu_getopt no_ignore_case auto_abbrev));
29 my $GLP_PASS = Getopt::Long::Parser->new;
30 $GLP_PASS->configure(qw(gnu_getopt no_ignore_case auto_abbrev pass_through));
31
32 our %PATH2CFG; # persistent for socket daemon
33
34 # TBD: this is a documentation mechanism to show a subcommand
35 # (may) pass options through to another command:
36 sub pass_through { $GLP_PASS }
37
38 # TODO: generate shell completion + help using %CMD and %OPTDESC
39 # command => [ positional_args, 1-line description, Getopt::Long option spec ]
40 our %CMD = ( # sorted in order of importance/use:
41 'query' => [ 'SEARCH_TERMS...', 'search for messages matching terms', qw(
42         save-as=s output|o=s format|f=s dedupe|d=s thread|t augment|a
43         limit|n=i sort|s=s@ reverse|r offset=i remote local! extinbox!
44         since|after=s until|before=s) ],
45
46 'show' => [ 'MID|OID', 'show a given object (Message-ID or object ID)',
47         qw(type=s solve! format|f=s dedupe|d=s thread|t remote local!),
48         pass_through('git show') ],
49
50 'add-extinbox' => [ 'URL_OR_PATHNAME',
51         'add/set priority of a publicinbox|extindex for extra matches',
52         qw(prio=i) ],
53 'ls-extinbox' => [ '[FILTER...]', 'list publicinbox|extindex locations',
54         qw(format|f=s z local remote) ],
55 'forget-extinbox' => [ '{URL_OR_PATHNAME|--prune}',
56         'exclude further results from a publicinbox|extindex',
57         qw(prune) ],
58
59 'ls-query' => [ '[FILTER...]', 'list saved search queries',
60                 qw(name-only format|f=s z) ],
61 'rm-query' => [ 'QUERY_NAME', 'remove a saved search' ],
62 'mv-query' => [ qw(OLD_NAME NEW_NAME), 'rename a saved search' ],
63
64 'plonk' => [ '--thread|--from=IDENT',
65         'exclude mail matching From: or thread from non-Message-ID searches',
66         qw(stdin| thread|t from|f=s mid=s oid=s) ],
67 'mark' => [ 'MESSAGE_FLAGS...',
68         'set/unset flags on message(s) from stdin',
69         qw(stdin| oid=s exact by-mid|mid:s) ],
70 'forget' => [ '[--stdin|--oid=OID|--by-mid=MID]',
71         'exclude message(s) on stdin from query results',
72         qw(stdin| oid=s exact by-mid|mid:s quiet|q) ],
73
74 'purge-mailsource' => [ '{URL_OR_PATHNAME|--all}',
75         'remove imported messages from IMAP, Maildirs, and MH',
76         qw(exact! all jobs:i indexed) ],
77
78 # code repos are used for `show' to solve blobs from patch mails
79 'add-coderepo' => [ 'PATHNAME', 'add or set priority of a git code repo',
80         qw(prio=i) ],
81 'ls-coderepo' => [ '[FILTER_TERMS...]',
82                 'list known code repos', qw(format|f=s z) ],
83 'forget-coderepo' => [ 'PATHNAME',
84         'stop using repo to solve blobs from patches',
85         qw(prune) ],
86
87 'add-watch' => [ '[URL_OR_PATHNAME]',
88                 'watch for new messages and flag changes',
89         qw(import! flags! interval=s recursive|r exclude=s include=s) ],
90 'ls-watch' => [ '[FILTER...]', 'list active watches with numbers and status',
91                 qw(format|f=s z) ],
92 'pause-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote) ],
93 'resume-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote) ],
94 'forget-watch' => [ '{WATCH_NUMBER|--prune}', 'stop and forget a watch',
95         qw(prune) ],
96
97 'import' => [ '{URL_OR_PATHNAME|--stdin}',
98         'one-shot import/update from URL or filesystem',
99         qw(stdin| limit|n=i offset=i recursive|r exclude=s include=s !flags),
100         ],
101
102 'config' => [ '[...]', 'git-config(1) wrapper for ~/.config/lei/config',
103         qw(config-file|system|global|file|f=s), # conflict detection
104         pass_through('git config') ],
105 'init' => [ '[PATHNAME]',
106         'initialize storage, default: ~/.local/share/lei/store',
107         qw(quiet|q) ],
108 'daemon-stop' => [ '', 'stop the lei-daemon' ],
109 'daemon-pid' => [ '', 'show the PID of the lei-daemon' ],
110 'daemon-env' => [ '[NAME=VALUE...]', 'set, unset, or show daemon environment',
111         qw(clear| unset|u=s@ z|0) ],
112 'help' => [ '[SUBCOMMAND]', 'show help' ],
113
114 # XXX do we need this?
115 # 'git' => [ '[ANYTHING...]', 'git(1) wrapper', pass_through('git') ],
116
117 'reorder-local-store-and-break-history' => [ '[REFNAME]',
118         'rewrite git history in an attempt to improve compression',
119         'gc!' ]
120 ); # @CMD
121
122 # switch descriptions, try to keep consistent across commands
123 # $spec: Getopt::Long option specification
124 # $spec => [@ALLOWED_VALUES (default is first), $description],
125 # $spec => $description
126 # "$SUB_COMMAND TAB $spec" => as above
127 my $stdin_formats = [ 'IN|auto|raw|mboxrd|mboxcl2|mboxcl|mboxo',
128                 'specify message input format' ];
129 my $ls_format = [ 'OUT|plain|json|null', 'listing output format' ];
130
131 my %OPTDESC = (
132 'help|h' => 'show this built-in help',
133 'quiet|q' => 'be quiet',
134 'solve!' => 'do not attempt to reconstruct blobs from emails',
135 'save-as=s' => ['NAME', 'save a search terms by given name'],
136
137 'type=s' => [ 'any|mid|git', 'disambiguate type' ],
138
139 'dedupe|d=s' => ['STRAT|content|oid|mid',
140                 'deduplication strategy'],
141 'show   thread|t' => 'display entire thread a message belongs to',
142 'query  thread|t' =>
143         'return all messages in the same thread as the actual match(es)',
144 'augment|a' => 'augment --output destination instead of clobbering',
145
146 'output|o=s' => [ 'DEST',
147         "destination (e.g. `/path/to/Maildir', or `-' for stdout)" ],
148
149 'show   format|f=s' => [ 'OUT|plain|raw|html|mboxrd|mboxcl2|mboxcl',
150                         'message/object output format' ],
151 'mark   format|f=s' => $stdin_formats,
152 'forget format|f=s' => $stdin_formats,
153 'query  format|f=s' => [ 'OUT|maildir|mboxrd|mboxcl2|mboxcl|html|oid',
154                 'specify output format, default depends on --output'],
155 'ls-query       format|f=s' => $ls_format,
156 'ls-extinbox    format|f=s' => $ls_format,
157
158 'limit|n=i' => ['NUM',
159         'limit on number of matches (default: 10000)' ],
160 'offset=i' => ['OFF', 'search result offset (default: 0)'],
161
162 'sort|s=s@' => [ 'VAL|internaldate,date,relevance,docid',
163                 "order of results `--output'-dependent"],
164
165 'prio=i' => 'priority of query source',
166
167 'local' => 'limit operations to the local filesystem',
168 'local!' => 'exclude results from the local filesystem',
169 'remote' => 'limit operations to those requiring network access',
170 'remote!' => 'prevent operations requiring network access',
171
172 'mid=s' => 'specify the Message-ID of a message',
173 'oid=s' => 'specify the git object ID of a message',
174
175 'recursive|r' => 'scan directories/mailboxes/newsgroups recursively',
176 'exclude=s' => 'exclude mailboxes/newsgroups based on pattern',
177 'include=s' => 'include mailboxes/newsgroups based on pattern',
178
179 'exact' => 'operate on exact header matches only',
180 'exact!' => 'rely on content match instead of exact header matches',
181
182 'by-mid|mid:s' => [ 'MID', 'match only by Message-ID, ignoring contents' ],
183 'jobs:i' => 'set parallelism level',
184
185 # xargs, env, use "-0", git(1) uses "-z".  Should we support z|0 everywhere?
186 'z' => 'use NUL \\0 instead of newline (CR) to delimit lines',
187 'z|0' => 'use NUL \\0 instead of newline (CR) to delimit lines',
188
189 # note: no "--ignore-environment" / "-i" support like env(1) since that
190 # is one-shot and this is for a persistent daemon:
191 'clear|' => 'clear the daemon environment',
192 'unset|u=s@' => ['NAME',
193         'unset matching NAME, may be specified multiple times'],
194 ); # %OPTDESC
195
196 sub x_it ($$) { # pronounced "exit"
197         my ($client, $code) = @_;
198         if (my $sig = ($code & 127)) {
199                 kill($sig, $client->{pid} // $$);
200         } else {
201                 $code >>= 8;
202                 if (my $sock = $client->{sock}) {
203                         say $sock "exit=$code";
204                 } else { # for oneshot
205                         $quit->($code);
206                 }
207         }
208 }
209
210 sub emit {
211         my ($client, $channel) = @_; # $buf = $_[2]
212         print { $client->{$channel} } $_[2] or die "print FD[$channel]: $!";
213 }
214
215 sub err {
216         my ($client, $buf) = @_;
217         $buf .= "\n" unless $buf =~ /\n\z/s;
218         emit($client, 2, $buf);
219 }
220
221 sub qerr { $_[0]->{opt}->{quiet} or err(@_) }
222
223 sub fail ($$;$) {
224         my ($client, $buf, $exit_code) = @_;
225         err($client, $buf);
226         x_it($client, ($exit_code // 1) << 8);
227         undef;
228 }
229
230 sub _help ($;$) {
231         my ($client, $errmsg) = @_;
232         my $cmd = $client->{cmd} // 'COMMAND';
233         my @info = @{$CMD{$cmd} // [ '...', '...' ]};
234         my @top = ($cmd, shift(@info) // ());
235         my $cmd_desc = shift(@info);
236         my @opt_desc;
237         my $lpad = 2;
238         for my $sw (grep { !ref($_) } @info) { # ("prio=s", "z", $GLP_PASS)
239                 my $desc = $OPTDESC{"$cmd\t$sw"} // $OPTDESC{$sw} // next;
240                 my $arg_vals = '';
241                 ($arg_vals, $desc) = @$desc if ref($desc) eq 'ARRAY';
242
243                 # lower-case is a keyword (e.g. `content', `oid'),
244                 # ALL_CAPS is a string description (e.g. `PATH')
245                 if ($desc !~ /default/ && $arg_vals =~ /\b([a-z]+)[,\|]/) {
246                         $desc .= "\ndefault: `$1'";
247                 }
248                 my (@vals, @s, @l);
249                 my $x = $sw;
250                 if ($x =~ s/!\z//) { # solve! => --no-solve
251                         $x = "no-$x";
252                 } elsif ($x =~ s/:.+//) { # optional args: $x = "mid:s"
253                         @vals = (' [', undef, ']');
254                 } elsif ($x =~ s/=.+//) { # required arg: $x = "type=s"
255                         @vals = (' ', undef);
256                 } # else: no args $x = 'thread|t'
257                 for (split(/\|/, $x)) { # help|h
258                         length($_) > 1 ? push(@l, "--$_") : push(@s, "-$_");
259                 }
260                 if (!scalar(@vals)) { # no args 'thread|t'
261                 } elsif ($arg_vals =~ s/\A([A-Z_]+)\b//) { # "NAME"
262                         $vals[1] = $1;
263                 } else {
264                         $vals[1] = uc(substr($l[0], 2)); # "--type" => "TYPE"
265                 }
266                 if ($arg_vals =~ /([,\|])/) {
267                         my $sep = $1;
268                         my @allow = split(/\Q$sep\E/, $arg_vals);
269                         my $must = $sep eq '|' ? 'Must' : 'Can';
270                         @allow = map { "`$_'" } @allow;
271                         my $last = pop @allow;
272                         $desc .= "\n$must be one of: " .
273                                 join(', ', @allow) . " or $last";
274                 }
275                 my $lhs = join(', ', @s, @l) . join('', @vals);
276                 if ($x =~ /\|\z/) { # "stdin|" or "clear|"
277                         $lhs =~ s/\A--/- , --/;
278                 } else {
279                         $lhs =~ s/\A--/    --/; # pad if no short options
280                 }
281                 $lpad = length($lhs) if length($lhs) > $lpad;
282                 push @opt_desc, $lhs, $desc;
283         }
284         my $msg = $errmsg ? "E: $errmsg\n" : '';
285         $msg .= <<EOF;
286 usage: lei @top
287   $cmd_desc
288
289 EOF
290         $lpad += 2;
291         local $Text::Wrap::columns = 78 - $lpad;
292         my $padding = ' ' x ($lpad + 2);
293         while (my ($lhs, $rhs) = splice(@opt_desc, 0, 2)) {
294                 $msg .= '  '.pack("A$lpad", $lhs);
295                 $rhs = wrap('', '', $rhs);
296                 $rhs =~ s/\n/\n$padding/sg; # LHS pad continuation lines
297                 $msg .= $rhs;
298                 $msg .= "\n";
299         }
300         my $channel = $errmsg ? 2 : 1;
301         emit($client, $channel, $msg);
302         x_it($client, $errmsg ? 1 << 8 : 0); # stderr => failure
303         undef;
304 }
305
306 sub optparse ($$$) {
307         my ($client, $cmd, $argv) = @_;
308         $client->{cmd} = $cmd;
309         my $opt = $client->{opt} = {};
310         my $info = $CMD{$cmd} // [ '[...]', '(undocumented command)' ];
311         my ($proto, $desc, @spec) = @$info;
312         my $glp = ref($spec[-1]) ? pop(@spec) : $GLP; # or $GLP_PASS
313         push @spec, qw(help|h);
314         my $lone_dash;
315         if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
316                 $lone_dash = $spec[0];
317                 $opt->{$spec[0]} = \(my $var);
318                 push @spec, '' => \$var;
319         }
320         $glp->getoptionsfromarray($argv, $opt, @spec) or
321                 return _help($client, "bad arguments or options for $cmd");
322         return _help($client) if $opt->{help};
323
324         # "-" aliases "stdin" or "clear"
325         $opt->{$lone_dash} = ${$opt->{$lone_dash}} if defined $lone_dash;
326
327         my $i = 0;
328         my $POS_ARG = '[A-Z][A-Z0-9_]+';
329         my ($err, $inf);
330         my @args = split(/ /, $proto);
331         for my $var (@args) {
332                 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
333                         $inf = defined($argv->[$i]) and last;
334                         $var =~ s/\.\.\.\z//;
335                         $err = "$var not supplied";
336                 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
337                         $argv->[$i++] // ($err = "$var not supplied");
338                 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
339                         $inf = 1;
340                         last;
341                 } elsif ($var =~ /\A\[$POS_ARG\]\z/) { # one optional arg
342                         $i++;
343                 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
344                         my @or = split(/\|/, $var);
345                         my $ok;
346                         for my $o (@or) {
347                                 if ($o =~ /\A--([a-z0-9\-]+)/) {
348                                         $ok = defined($opt->{$1});
349                                         last;
350                                 } elsif (defined($argv->[$i])) {
351                                         $ok = 1;
352                                         $i++;
353                                         last;
354                                 } # else continue looping
355                         }
356                         my $last = pop @or;
357                         $err = join(', ', @or) . " or $last must be set";
358                 } else {
359                         warn "BUG: can't parse `$var' in $proto";
360                 }
361                 last if $err;
362         }
363         # warn "inf=$inf ".scalar(@$argv). ' '.scalar(@args)."\n";
364         if (!$inf && scalar(@$argv) > scalar(@args)) {
365                 $err //= 'too many arguments';
366         }
367         $err ? fail($client, "usage: lei $cmd $proto\nE: $err") : 1;
368 }
369
370 sub dispatch {
371         my ($client, $cmd, @argv) = @_;
372         local $SIG{__WARN__} = sub { err($client, "@_") };
373         local $SIG{__DIE__} = 'DEFAULT';
374         return _help($client, 'no command given') unless defined($cmd);
375         my $func = "lei_$cmd";
376         $func =~ tr/-/_/;
377         if (my $cb = __PACKAGE__->can($func)) {
378                 optparse($client, $cmd, \@argv) or return;
379                 $cb->($client, @argv);
380         } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
381                 my $opt = {};
382                 $GLP->getoptionsfromarray([$cmd, @argv], $opt, qw(help|h)) or
383                         return _help($client, 'bad arguments or options');
384                 _help($client);
385         } else {
386                 fail($client, "`$cmd' is not an lei command");
387         }
388 }
389
390 sub _lei_cfg ($;$) {
391         my ($client, $creat) = @_;
392         my $env = $client->{env};
393         my $cfg_dir = File::Spec->canonpath(( $env->{XDG_CONFIG_HOME} //
394                         ($env->{HOME} // '/nonexistent').'/.config').'/lei');
395         my $f = "$cfg_dir/config";
396         my @st = stat($f);
397         my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
398         if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
399                 return ($client->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
400         }
401         if (!@st) {
402                 unless ($creat) {
403                         delete $client->{cfg};
404                         return;
405                 }
406                 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
407                 open my $fh, '>>', $f or die "open($f): $!\n";
408                 @st = stat($fh) or die "fstat($f): $!\n";
409                 $cur_st = pack('dd', $st[10], $st[7]);
410                 qerr($client, "I: $f created") if $client->{cmd} ne 'config';
411         }
412         my $cfg = PublicInbox::Config::git_config_dump($f);
413         $cfg->{-st} = $cur_st;
414         $cfg->{'-f'} = $f;
415         $client->{cfg} = $PATH2CFG{$f} = $cfg;
416 }
417
418 sub _lei_store ($;$) {
419         my ($client, $creat) = @_;
420         my $cfg = _lei_cfg($client, $creat);
421         $cfg->{-lei_store} //= do {
422                 require PublicInbox::LeiStore;
423                 PublicInbox::SearchIdx::load_xapian_writable();
424                 defined(my $dir = $cfg->{'leistore.dir'}) or return;
425                 PublicInbox::LeiStore->new($dir, { creat => $creat });
426         };
427 }
428
429 sub lei_show {
430         my ($client, @argv) = @_;
431 }
432
433 sub lei_query {
434         my ($client, @argv) = @_;
435 }
436
437 sub lei_mark {
438         my ($client, @argv) = @_;
439 }
440
441 sub lei_config {
442         my ($client, @argv) = @_;
443         $client->{opt}->{'config-file'} and return fail $client,
444                 "config file switches not supported by `lei config'";
445         my $env = $client->{env};
446         delete local $env->{GIT_CONFIG};
447         my $cfg = _lei_cfg($client, 1);
448         my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
449         my %rdr = map { $_ => $client->{$_} } (0..2);
450         require PublicInbox::Import;
451         PublicInbox::Import::run_die($cmd, $env, \%rdr);
452 }
453
454 sub lei_init {
455         my ($client, $dir) = @_;
456         my $cfg = _lei_cfg($client, 1);
457         my $cur = $cfg->{'leistore.dir'};
458         my $env = $client->{env};
459         $dir //= ( $env->{XDG_DATA_HOME} //
460                 ($env->{HOME} // '/nonexistent').'/.local/share'
461                 ) . '/lei/store';
462         $dir = File::Spec->rel2abs($dir, $env->{PWD}); # PWD is symlink-aware
463         my @cur = stat($cur) if defined($cur);
464         $cur = File::Spec->canonpath($cur) if $cur;
465         my @dir = stat($dir);
466         my $exists = "I: leistore.dir=$cur already initialized" if @dir;
467         if (@cur) {
468                 if ($cur eq $dir) {
469                         _lei_store($client, 1)->done;
470                         return qerr($client, $exists);
471                 }
472
473                 # some folks like symlinks and bind mounts :P
474                 if (@dir && "$cur[0] $cur[1]" eq "$dir[0] $dir[1]") {
475                         lei_config($client, 'leistore.dir', $dir);
476                         _lei_store($client, 1)->done;
477                         return qerr($client, "$exists (as $cur)");
478                 }
479                 return fail($client, <<"");
480 E: leistore.dir=$cur already initialized and it is not $dir
481
482         }
483         lei_config($client, 'leistore.dir', $dir);
484         _lei_store($client, 1)->done;
485         $exists //= "I: leistore.dir=$dir newly initialized";
486         return qerr($client, $exists);
487 }
488
489 sub lei_daemon_pid { emit($_[0], 1, "$$\n") }
490
491 sub lei_daemon_stop { $quit->(0) }
492
493 sub lei_daemon_env {
494         my ($client, @argv) = @_;
495         my $opt = $client->{opt};
496         if (defined $opt->{clear}) {
497                 %ENV = ();
498         } elsif (my $u = $opt->{unset}) {
499                 delete @ENV{@$u};
500         }
501         if (@argv) {
502                 %ENV = (%ENV, map { split(/=/, $_, 2) } @argv);
503         } elsif (!defined($opt->{clear}) && !$opt->{unset}) {
504                 my $eor = $opt->{z} ? "\0" : "\n";
505                 my $buf = '';
506                 while (my ($k, $v) = each %ENV) { $buf .= "$k=$v$eor" }
507                 emit($client, 1, $buf)
508         }
509 }
510
511 sub lei_help { _help($_[0]) }
512
513 sub reap_exec { # dwaitpid callback
514         my ($client, $pid) = @_;
515         x_it($client, $?);
516 }
517
518 sub lei_git { # support passing through random git commands
519         my ($client, @argv) = @_;
520         my %rdr = map { $_ => $client->{$_} } (0..2);
521         my $pid = spawn(['git', @argv], $client->{env}, \%rdr);
522         PublicInbox::DS::dwaitpid($pid, \&reap_exec, $client);
523 }
524
525 sub accept_dispatch { # Listener {post_accept} callback
526         my ($sock) = @_; # ignore other
527         $sock->blocking(1);
528         $sock->autoflush(1);
529         my $client = { sock => $sock };
530         vec(my $rin = '', fileno($sock), 1) = 1;
531         # `say $sock' triggers "die" in lei(1)
532         for my $i (0..2) {
533                 if (select(my $rout = $rin, undef, undef, 1)) {
534                         my $fd = IO::FDPass::recv(fileno($sock));
535                         if ($fd >= 0) {
536                                 my $rdr = ($fd == 0 ? '<&=' : '>&=');
537                                 if (open(my $fh, $rdr, $fd)) {
538                                         $client->{$i} = $fh;
539                                 } else {
540                                         say $sock "open($rdr$fd) (FD=$i): $!";
541                                         return;
542                                 }
543                         } else {
544                                 say $sock "recv FD=$i: $!";
545                                 return;
546                         }
547                 } else {
548                         say $sock "timed out waiting to recv FD=$i";
549                         return;
550                 }
551         }
552         # $ARGV_STR = join("]\0[", @ARGV);
553         # $ENV_STR = join('', map { "$_=$ENV{$_}\0" } keys %ENV);
554         # $line = "$$\0\0>$ARGV_STR\0\0>$ENV_STR\0\0";
555         my ($client_pid, $argv, $env) = do {
556                 local $/ = "\0\0\0"; # yes, 3 NULs at EOL, not 2
557                 chomp(my $line = <$sock>);
558                 split(/\0\0>/, $line, 3);
559         };
560         my %env = map { split(/=/, $_, 2) } split(/\0/, $env);
561         if (chdir($env{PWD})) {
562                 $client->{env} = \%env;
563                 $client->{pid} = $client_pid;
564                 eval { dispatch($client, split(/\]\0\[/, $argv)) };
565                 say $sock $@ if $@;
566         } else {
567                 say $sock "chdir($env{PWD}): $!"; # implicit close
568         }
569 }
570
571 sub noop {}
572
573 # lei(1) calls this when it can't connect
574 sub lazy_start {
575         my ($path, $err) = @_;
576         if ($err == ECONNREFUSED) {
577                 unlink($path) or die "unlink($path): $!";
578         } elsif ($err != ENOENT) {
579                 die "connect($path): $!";
580         }
581         require IO::FDPass;
582         umask(077) // die("umask(077): $!");
583         my $l = IO::Socket::UNIX->new(Local => $path,
584                                         Listen => 1024,
585                                         Type => SOCK_STREAM) or
586                 $err = $!;
587         $l or return die "bind($path): $err";
588         my @st = stat($path) or die "stat($path): $!";
589         my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
590         pipe(my ($eof_r, $eof_w)) or die "pipe: $!";
591         my $oldset = PublicInbox::Sigfd::block_signals();
592         my $pid = fork // die "fork: $!";
593         return if $pid;
594         openlog($path, 'pid', 'user');
595         local $SIG{__DIE__} = sub {
596                 syslog('crit', "@_");
597                 exit $! if $!;
598                 exit $? >> 8 if $? >> 8;
599                 exit 255;
600         };
601         local $SIG{__WARN__} = sub { syslog('warning', "@_") };
602         open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!\n";
603         open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
604         open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
605         setsid();
606         $pid = fork // die "fork: $!";
607         return if $pid;
608         $0 = "lei-daemon $path";
609         local %PATH2CFG;
610         require PublicInbox::Listener;
611         require PublicInbox::EOFpipe;
612         $l->blocking(0);
613         $eof_w->blocking(0);
614         $eof_r->blocking(0);
615         my $listener = PublicInbox::Listener->new($l, \&accept_dispatch, $l);
616         my $exit_code;
617         local $quit = sub {
618                 $exit_code //= shift;
619                 my $tmp = $listener or exit($exit_code);
620                 unlink($path) if defined($path);
621                 syswrite($eof_w, '.');
622                 $l = $listener = $path = undef;
623                 $tmp->close if $tmp; # DS::close
624                 PublicInbox::DS->SetLoopTimeout(1000);
625         };
626         PublicInbox::EOFpipe->new($eof_r, sub {}, undef);
627         my $sig = {
628                 CHLD => \&PublicInbox::DS::enqueue_reap,
629                 QUIT => $quit,
630                 INT => $quit,
631                 TERM => $quit,
632                 HUP => \&noop,
633                 USR1 => \&noop,
634                 USR2 => \&noop,
635         };
636         my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK);
637         local %SIG = (%SIG, %$sig) if !$sigfd;
638         if ($sigfd) { # TODO: use inotify/kqueue to detect unlinked sockets
639                 PublicInbox::DS->SetLoopTimeout(5000);
640         } else {
641                 # wake up every second to accept signals if we don't
642                 # have signalfd or IO::KQueue:
643                 PublicInbox::Sigfd::sig_setmask($oldset);
644                 PublicInbox::DS->SetLoopTimeout(1000);
645         }
646         PublicInbox::DS->SetPostLoopCallback(sub {
647                 my ($dmap, undef) = @_;
648                 if (@st = defined($path) ? stat($path) : ()) {
649                         if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
650                                 warn "$path dev/ino changed, quitting\n";
651                                 $path = undef;
652                         }
653                 } elsif (defined($path)) {
654                         warn "stat($path): $!, quitting ...\n";
655                         undef $path; # don't unlink
656                         $quit->();
657                 }
658                 return 1 if defined($path);
659                 my $now = now();
660                 my $n = 0;
661                 for my $s (values %$dmap) {
662                         $s->can('busy') or next;
663                         if ($s->busy($now)) {
664                                 ++$n;
665                         } else {
666                                 $s->close;
667                         }
668                 }
669                 $n; # true: continue, false: stop
670         });
671         PublicInbox::DS->EventLoop;
672         exit($exit_code // 0);
673 }
674
675 # for users w/o IO::FDPass
676 sub oneshot {
677         my ($main_pkg) = @_;
678         my $exit = $main_pkg->can('exit'); # caller may override exit()
679         local $quit = $exit if $exit;
680         local %PATH2CFG;
681         umask(077) // die("umask(077): $!");
682         dispatch({
683                 0 => *STDIN{IO},
684                 1 => *STDOUT{IO},
685                 2 => *STDERR{IO},
686                 env => \%ENV
687         }, @ARGV);
688 }
689
690 1;