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