]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LEI.pm
8cd95ac2543c5fe35e1e19bbe4cfd8120bfd95ca
[public-inbox.git] / lib / PublicInbox / LEI.pm
1 # Copyright (C) 2020-2021 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 PublicInbox::LeiExternal
12         PublicInbox::LeiQuery);
13 use Getopt::Long ();
14 use Socket qw(AF_UNIX SOCK_SEQPACKET MSG_EOR pack_sockaddr_un);
15 use Errno qw(EPIPE EAGAIN EINTR ECONNREFUSED ENOENT ECONNRESET);
16 use Cwd qw(getcwd);
17 use POSIX qw(strftime);
18 use IO::Handle ();
19 use Fcntl qw(SEEK_SET);
20 use PublicInbox::Config;
21 use PublicInbox::Syscall qw(SFD_NONBLOCK EPOLLIN EPOLLET);
22 use PublicInbox::Sigfd;
23 use PublicInbox::DS qw(now dwaitpid);
24 use PublicInbox::Spawn qw(spawn popen_rd);
25 use PublicInbox::Lock;
26 use Time::HiRes qw(stat); # ctime comparisons for config cache
27 use File::Path qw(mkpath);
28 use File::Spec;
29 our $quit = \&CORE::exit;
30 our ($current_lei, $errors_log, $listener);
31 my ($recv_cmd, $send_cmd);
32 my $GLP = Getopt::Long::Parser->new;
33 $GLP->configure(qw(gnu_getopt no_ignore_case auto_abbrev));
34 my $GLP_PASS = Getopt::Long::Parser->new;
35 $GLP_PASS->configure(qw(gnu_getopt no_ignore_case auto_abbrev pass_through));
36
37 our %PATH2CFG; # persistent for socket daemon
38
39 # TBD: this is a documentation mechanism to show a subcommand
40 # (may) pass options through to another command:
41 sub pass_through { $GLP_PASS }
42
43 my $OPT;
44 sub opt_dash ($$) {
45         my ($spec, $re_str) = @_; # 'limit|n=i', '([0-9]+)'
46         my ($key) = ($spec =~ m/\A([a-z]+)/g);
47         my $cb = sub { # Getopt::Long "<>" catch-all handler
48                 my ($arg) = @_;
49                 if ($arg =~ /\A-($re_str)\z/) {
50                         $OPT->{$key} = $1;
51                 } elsif ($arg eq '--') { # "--" arg separator, ignore first
52                         push @{$OPT->{-argv}}, $arg if $OPT->{'--'}++;
53                 # lone (single) dash is handled elsewhere
54                 } elsif (substr($arg, 0, 1) eq '-') {
55                         if ($OPT->{'--'}) {
56                                 push @{$OPT->{-argv}}, $arg;
57                         } else {
58                                 die "bad argument: $arg\n";
59                         }
60                 } else {
61                         push @{$OPT->{-argv}}, $arg;
62                 }
63         };
64         ($spec, '<>' => $cb, $GLP_PASS) # for Getopt::Long
65 }
66
67 sub rel2abs ($$) {
68         my ($self, $p) = @_;
69         return $p if index($p, '/') == 0; # already absolute
70         my $pwd = $self->{env}->{PWD};
71         if (defined $pwd) {
72                 my $cwd = $self->{3} // getcwd() // die "getcwd(PWD=$pwd): $!";
73                 if (my @st_pwd = stat($pwd)) {
74                         my @st_cwd = stat($cwd) or die "stat($cwd): $!";
75                         "@st_pwd[1,0]" eq "@st_cwd[1,0]" or
76                                 $self->{env}->{PWD} = $pwd = $cwd;
77                 } else { # PWD was invalid
78                         delete $self->{env}->{PWD};
79                         undef $pwd;
80                 }
81         }
82         $pwd //= $self->{env}->{PWD} = getcwd() // die "getcwd(PWD=$pwd): $!";
83         File::Spec->rel2abs($p, $pwd);
84 }
85
86 sub _store_path ($) {
87         my ($self) = @_;
88         rel2abs($self, ($self->{env}->{XDG_DATA_HOME} //
89                 ($self->{env}->{HOME} // '/nonexistent').'/.local/share')
90                 .'/lei/store');
91 }
92
93 sub _config_path ($) {
94         my ($self) = @_;
95         rel2abs($self, ($self->{env}->{XDG_CONFIG_HOME} //
96                 ($self->{env}->{HOME} // '/nonexistent').'/.config')
97                 .'/lei/config');
98 }
99
100 sub index_opt {
101         # TODO: drop underscore variants everywhere, they're undocumented
102         qw(fsync|sync! jobs|j=i indexlevel|L=s compact
103         max_size|max-size=s sequential_shard|sequential-shard
104         batch_size|batch-size=s skip-docdata)
105 }
106
107 # we generate shell completion + help using %CMD and %OPTDESC,
108 # see lei__complete() and PublicInbox::LeiHelp
109 # command => [ positional_args, 1-line description, Getopt::Long option spec ]
110 our %CMD = ( # sorted in order of importance/use:
111 'q' => [ '--stdin|SEARCH_TERMS...', 'search for messages matching terms', qw(
112         save-as=s output|mfolder|o=s format|f=s dedupe|d=s threads|t augment|a
113         sort|s=s reverse|r offset=i remote! local! external! pretty
114         include|I=s@ exclude=s@ only=s@ jobs|j=s globoff|g stdin|
115         alert=s@ mua=s no-torsocks torsocks=s verbose|v+ quiet|q C=s@),
116         PublicInbox::LeiQuery::curl_opt(), opt_dash('limit|n=i', '[0-9]+') ],
117
118 'show' => [ 'MID|OID', 'show a given object (Message-ID or object ID)',
119         qw(type=s solve! format|f=s dedupe|d=s threads|t remote local! C=s@),
120         pass_through('git show') ],
121
122 'add-external' => [ 'LOCATION',
123         'add/set priority of a publicinbox|extindex for extra matches',
124         qw(boost=i c=s@ mirror=s no-torsocks torsocks=s inbox-version=i),
125         qw(quiet|q verbose|v+ C=s@),
126         index_opt(), PublicInbox::LeiQuery::curl_opt() ],
127 'ls-external' => [ '[FILTER]', 'list publicinbox|extindex locations',
128         qw(format|f=s z|0 globoff|g invert-match|v local remote C=s@) ],
129 'forget-external' => [ 'LOCATION...|--prune',
130         'exclude further results from a publicinbox|extindex',
131         qw(prune quiet|q C=s@) ],
132
133 'ls-query' => [ '[FILTER...]', 'list saved search queries',
134                 qw(name-only format|f=s z C=s@) ],
135 'rm-query' => [ 'QUERY_NAME', 'remove a saved search', qw(C=s@) ],
136 'mv-query' => [ qw(OLD_NAME NEW_NAME), 'rename a saved search', qw(C=s@) ],
137
138 'plonk' => [ '--threads|--from=IDENT',
139         'exclude mail matching From: or threads from non-Message-ID searches',
140         qw(stdin| threads|t from|f=s mid=s oid=s C=s@) ],
141 'mark' => [ 'MESSAGE_FLAGS...',
142         'set/unset keywords on message(s) from stdin',
143         qw(stdin| oid=s exact by-mid|mid:s C=s@) ],
144 'forget' => [ '[--stdin|--oid=OID|--by-mid=MID]',
145         "exclude message(s) on stdin from `q' search results",
146         qw(stdin| oid=s exact by-mid|mid:s quiet|q C=s@) ],
147
148 'purge-mailsource' => [ 'LOCATION|--all',
149         'remove imported messages from IMAP, Maildirs, and MH',
150         qw(exact! all jobs:i indexed C=s@) ],
151
152 # code repos are used for `show' to solve blobs from patch mails
153 'add-coderepo' => [ 'DIRNAME', 'add or set priority of a git code repo',
154         qw(boost=i C=s@) ],
155 'ls-coderepo' => [ '[FILTER_TERMS...]',
156                 'list known code repos', qw(format|f=s z C=s@) ],
157 'forget-coderepo' => [ 'DIRNAME',
158         'stop using repo to solve blobs from patches',
159         qw(prune C=s@) ],
160
161 'add-watch' => [ 'LOCATION', 'watch for new messages and flag changes',
162         qw(import! kw|keywords|flags! interval=s recursive|r
163         exclude=s include=s C=s@) ],
164 'ls-watch' => [ '[FILTER...]', 'list active watches with numbers and status',
165                 qw(format|f=s z C=s@) ],
166 'pause-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote C=s@) ],
167 'resume-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote C=s@) ],
168 'forget-watch' => [ '{WATCH_NUMBER|--prune}', 'stop and forget a watch',
169         qw(prune C=s@) ],
170
171 'import' => [ 'LOCATION...|--stdin',
172         'one-time import/update from URL or filesystem',
173         qw(stdin| offset=i recursive|r exclude=s include|I=s
174         format|f=s kw|keywords|flags! C=s@),
175         ],
176 'convert' => [ 'LOCATION...|--stdin',
177         'one-time conversion from URL or filesystem to another format',
178         qw(stdin| in-format|F=s out-format|f=s output|mfolder|o=s quiet|q
179         kw|keywords|flags! C=s@),
180         ],
181 'config' => [ '[...]', sub {
182                 'git-config(1) wrapper for '._config_path($_[0]);
183         }, qw(config-file|system|global|file|f=s), # for conflict detection
184          qw(C=s@), pass_through('git config') ],
185 'init' => [ '[DIRNAME]', sub {
186         "initialize storage, default: "._store_path($_[0]);
187         }, qw(quiet|q C=s@) ],
188 'daemon-kill' => [ '[-SIGNAL]', 'signal the lei-daemon',
189         # "-C DIR" conflicts with -CHLD, here, and chdir makes no sense, here
190         opt_dash('signal|s=s', '[0-9]+|(?:[A-Z][A-Z0-9]+)') ],
191 'daemon-pid' => [ '', 'show the PID of the lei-daemon' ],
192 'help' => [ '[SUBCOMMAND]', 'show help' ],
193
194 # XXX do we need this?
195 # 'git' => [ '[ANYTHING...]', 'git(1) wrapper', pass_through('git') ],
196
197 'reorder-local-store-and-break-history' => [ '[REFNAME]',
198         'rewrite git history in an attempt to improve compression',
199         qw(gc! C=s@) ],
200
201 # internal commands are prefixed with '_'
202 '_complete' => [ '[...]', 'internal shell completion helper',
203                 pass_through('everything') ],
204 ); # @CMD
205
206 # switch descriptions, try to keep consistent across commands
207 # $spec: Getopt::Long option specification
208 # $spec => [@ALLOWED_VALUES (default is first), $description],
209 # $spec => $description
210 # "$SUB_COMMAND TAB $spec" => as above
211 my $stdin_formats = [ 'MAIL_FORMAT|eml|mboxrd|mboxcl2|mboxcl|mboxo',
212                         'specify message input format' ];
213 my $ls_format = [ 'OUT|plain|json|null', 'listing output format' ];
214
215 # we use \x{a0} (non-breaking SP) to avoid wrapping in PublicInbox::LeiHelp
216 my %OPTDESC = (
217 'help|h' => 'show this built-in help',
218 'C=s@' => [ 'DIR', 'chdir to specify to directory' ],
219 'quiet|q' => 'be quiet',
220 'globoff|g' => "do not match locations using '*?' wildcards ".
221                 "and\xa0'[]'\x{a0}ranges",
222 'verbose|v+' => 'be more verbose',
223 'solve!' => 'do not attempt to reconstruct blobs from emails',
224 'torsocks=s' => ['VAL|auto|no|yes',
225                 'whether or not to wrap git and curl commands with torsocks'],
226 'no-torsocks' => 'alias for --torsocks=no',
227 'save-as=s' => ['NAME', 'save a search terms by given name'],
228
229 'type=s' => [ 'any|mid|git', 'disambiguate type' ],
230
231 'dedupe|d=s' => ['STRATEGY|content|oid|mid|none',
232                 'deduplication strategy'],
233 'show   threads|t' => 'display entire thread a message belongs to',
234 'q      threads|t' =>
235         'return all messages in the same threads as the actual match(es)',
236 'alert=s@' => ['CMD,:WINCH,:bell,<any command>',
237         'run command(s) or perform ops when done writing to output ' .
238         '(default: ":WINCH,:bell" with --mua and Maildir/IMAP output, ' .
239         'nothing otherwise)' ],
240
241 'augment|a' => 'augment --output destination instead of clobbering',
242
243 'output|mfolder|o=s' => [ 'MFOLDER',
244         "destination (e.g.\xa0`/path/to/Maildir', ".
245         "or\xa0`-'\x{a0}for\x{a0}stdout)" ],
246 'mua=s' => [ 'CMD',
247         "MUA to run on --output Maildir or mbox (e.g.\xa0`mutt\xa0-f\xa0%f')" ],
248
249 'show   format|f=s' => [ 'OUT|plain|raw|html|mboxrd|mboxcl2|mboxcl',
250                         'message/object output format' ],
251 'mark   format|f=s' => $stdin_formats,
252 'forget format|f=s' => $stdin_formats,
253
254 'add-external   inbox-version=i' => [ 'NUM|1|2',
255                 'force a public-inbox version with --mirror'],
256 'add-external   mirror=s' => [ 'URL', 'mirror a public-inbox'],
257
258 # public-inbox-index options
259 'add-external   jobs|j=i' => 'set parallelism when indexing after --mirror',
260 'fsync!' => 'speed up indexing after --mirror, risk index corruption',
261 'compact' => 'run compact index after mirroring',
262 'indexlevel|L=s' => [ 'LEVEL|full|medium|basic',
263         "indexlevel with --mirror (default: full)" ],
264 'max_size|max-size=s' => [ 'SIZE',
265         'do not index messages larger than SIZE (default: infinity)' ],
266 'batch_size|batch-size=s' => [ 'SIZE',
267         'flush changes to OS after given number of bytes (default: 1m)' ],
268 'sequential_shard|sequential-shard' =>
269         'index Xapian shards sequentially for slow storage',
270 'skip-docdata' =>
271         'drop compatibility w/ public-inbox <1.6 to save ~1.5% space',
272
273 'q      format|f=s' => [
274         'OUT|maildir|mboxrd|mboxcl2|mboxcl|mboxo|html|json|jsonl|concatjson',
275                 'specify output format, default depends on --output'],
276 'q      exclude=s@' => [ 'LOCATION',
277                 'exclude specified external(s) from search' ],
278 'q      include|I=s@' => [ 'LOCATION',
279                 'include specified external(s) in search' ],
280 'q      only=s@' => [ 'LOCATION',
281                 'only use specified external(s) for search' ],
282
283 'q      jobs=s' => [ '[SEARCH_JOBS][,WRITER_JOBS]',
284                 'control number of search and writer jobs' ],
285
286 'import format|f=s' => $stdin_formats,
287
288 'ls-query       format|f=s' => $ls_format,
289 'ls-external    format|f=s' => $ls_format,
290
291 'limit|n=i@' => ['NUM', 'limit on number of matches (default: 10000)' ],
292 'offset=i' => ['OFF', 'search result offset (default: 0)'],
293
294 'sort|s=s' => [ 'VAL|received|relevance|docid',
295                 "order of results is `--output'-dependent"],
296 'reverse|r' => 'reverse search results', # like sort(1)
297
298 'boost=i' => 'increase/decrease priority of results (default: 0)',
299
300 'local' => 'limit operations to the local filesystem',
301 'local!' => 'exclude results from the local filesystem',
302 'remote' => 'limit operations to those requiring network access',
303 'remote!' => 'prevent operations requiring network access',
304
305 'mid=s' => 'specify the Message-ID of a message',
306 'oid=s' => 'specify the git object ID of a message',
307
308 'recursive|r' => 'scan directories/mailboxes/newsgroups recursively',
309 'exclude=s' => 'exclude mailboxes/newsgroups based on pattern',
310 'include=s' => 'include mailboxes/newsgroups based on pattern',
311
312 'exact' => 'operate on exact header matches only',
313 'exact!' => 'rely on content match instead of exact header matches',
314
315 'by-mid|mid:s' => [ 'MID', 'match only by Message-ID, ignoring contents' ],
316
317 'kw|keywords|flags!' => 'disable/enable importing flags',
318
319 # xargs, env, use "-0", git(1) uses "-z".  We support z|0 everywhere
320 'z|0' => 'use NUL \\0 instead of newline (CR) to delimit lines',
321
322 'signal|s=s' => [ 'SIG', 'signal to send lei-daemon (default: TERM)' ],
323 ); # %OPTDESC
324
325 my %CONFIG_KEYS = (
326         'leistore.dir' => 'top-level storage location',
327 );
328
329 my @WQ_KEYS = qw(lxs l2m imp mrr cnv); # internal workers
330
331 # pronounced "exit": x_it(1 << 8) => exit(1); x_it(13) => SIGPIPE
332 sub x_it ($$) {
333         my ($self, $code) = @_;
334         # make sure client sees stdout before exit
335         $self->{1}->autoflush(1) if $self->{1};
336         dump_and_clear_log();
337         if (my $s = $self->{pkt_op_p} // $self->{sock}) {
338                 send($s, "x_it $code", MSG_EOR);
339         } elsif ($self->{oneshot}) {
340                 # don't want to end up using $? from child processes
341                 for my $f (@WQ_KEYS) {
342                         my $wq = delete $self->{$f} or next;
343                         $wq->DESTROY;
344                 }
345                 # cleanup anything that has tempfiles or open file handles
346                 %PATH2CFG = ();
347                 delete @$self{qw(ovv dedupe sto cfg)};
348                 if (my $signum = ($code & 127)) { # usually SIGPIPE (13)
349                         $SIG{PIPE} = 'DEFAULT'; # $SIG{$signum} doesn't work
350                         kill $signum, $$;
351                         sleep(1) while 1; # wait for signal
352                 } else {
353                         $quit->($code >> 8);
354                 }
355         } # else ignore if client disconnected
356 }
357
358 sub err ($;@) {
359         my $self = shift;
360         my $err = $self->{2} // ($self->{pgr} // [])->[2] // *STDERR{GLOB};
361         my @eor = (substr($_[-1]//'', -1, 1) eq "\n" ? () : ("\n"));
362         print $err @_, @eor and return;
363         my $old_err = delete $self->{2};
364         close($old_err) if $! == EPIPE && $old_err;
365         $err = $self->{2} = ($self->{pgr} // [])->[2] // *STDERR{GLOB};
366         print $err @_, @eor or print STDERR @_, @eor;
367 }
368
369 sub qerr ($;@) { $_[0]->{opt}->{quiet} or err(shift, @_) }
370
371 sub fail_handler ($;$$) {
372         my ($lei, $code, $io) = @_;
373         for my $f (@WQ_KEYS) {
374                 my $wq = delete $lei->{$f} or next;
375                 $wq->wq_wait_old(undef, $lei) if $wq->wq_kill_old; # lei-daemon
376         }
377         close($io) if $io; # needed to avoid warnings on SIGPIPE
378         x_it($lei, $code // (1 << 8));
379 }
380
381 sub sigpipe_handler { # handles SIGPIPE from @WQ_KEYS workers
382         fail_handler($_[0], 13, delete $_[0]->{1});
383 }
384
385 # PublicInbox::OnDestroy callback for SIGINT to take out the entire pgid
386 sub sigint_reap {
387         my ($pgid) = @_;
388         dwaitpid($pgid) if kill('-INT', $pgid);
389 }
390
391 sub fail ($$;$) {
392         my ($self, $buf, $exit_code) = @_;
393         err($self, $buf) if defined $buf;
394         # calls fail_handler:
395         send($self->{pkt_op_p}, '!', MSG_EOR) if $self->{pkt_op_p};
396         x_it($self, ($exit_code // 1) << 8);
397         undef;
398 }
399
400 sub check_input_format ($;$$) {
401         my ($self, $files, $opt_key) = @_;
402         $opt_key //= 'format';
403         my $fmt = $self->{opt}->{$opt_key};
404         if (!$fmt) {
405                 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
406                 return fail($self, "--$opt_key unset for $err");
407         }
408         return 1 if $fmt eq 'eml';
409         # XXX: should this handle {gz,bz2,xz}? that's currently in LeiToMail
410         require PublicInbox::MboxReader;
411         PublicInbox::MboxReader->can($fmt) ||
412                                 fail($self, "--$opt_key=$fmt unrecognized");
413 }
414
415 sub out ($;@) {
416         my $self = shift;
417         return if print { $self->{1} // return } @_; # likely
418         return note_sigpipe($self, 1) if $! == EPIPE;
419         my $err = "error writing to stdout: $!";
420         delete $self->{1};
421         fail($self, $err);
422 }
423
424 sub puts ($;@) { out(shift, map { "$_\n" } @_) }
425
426 sub child_error { # passes non-fatal curl exit codes to user
427         my ($self, $child_error, $msg) = @_; # child_error is $?
428         $self->err($msg) if $msg;
429         if (my $s = $self->{pkt_op_p} // $self->{sock}) {
430                 # send to the parent lei-daemon or to lei(1) client
431                 send($s, "child_error $child_error", MSG_EOR);
432         } elsif (!$PublicInbox::DS::in_loop) {
433                 $self->{child_error} = $child_error;
434         } # else noop if client disconnected
435 }
436
437 sub note_sigpipe { # triggers sigpipe_handler
438         my ($self, $fd) = @_;
439         close(delete($self->{$fd})); # explicit close silences Perl warning
440         send($self->{pkt_op_p}, '|', MSG_EOR) if $self->{pkt_op_p};
441         x_it($self, 13);
442 }
443
444 sub lei_atfork_child {
445         my ($self, $persist) = @_;
446         # we need to explicitly close things which are on stack
447         if ($persist) {
448                 my @io = delete @$self{qw(0 1 2 sock)};
449                 unless ($self->{oneshot}) {
450                         close($_) for @io;
451                 }
452         } else {
453                 delete $self->{0};
454         }
455         delete @$self{qw(cnv)};
456         for (delete @$self{qw(3 old_1 au_done)}) {
457                 close($_) if defined($_);
458         }
459         if (my $op_c = delete $self->{pkt_op_c}) {
460                 close(delete $op_c->{sock});
461         }
462         if (my $pgr = delete $self->{pgr}) {
463                 close($_) for (@$pgr[1,2]);
464         }
465         close $listener if $listener;
466         undef $listener;
467         %PATH2CFG = ();
468         undef $errors_log;
469         $quit = \&CORE::exit;
470         $current_lei = $persist ? undef : $self; # for SIG{__WARN__}
471 }
472
473 sub workers_start {
474         my ($lei, $wq, $ident, $jobs, $ops) = @_;
475         $ops = {
476                 '!' => [ $lei->can('fail_handler'), $lei ],
477                 '|' => [ $lei->can('sigpipe_handler'), $lei ],
478                 'x_it' => [ $lei->can('x_it'), $lei ],
479                 'child_error' => [ $lei->can('child_error'), $lei ],
480                 %$ops
481         };
482         require PublicInbox::PktOp;
483         ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
484         $wq->wq_workers_start($ident, $jobs, $lei->oldset, { lei => $lei });
485         delete $lei->{pkt_op_p};
486         my $op = delete $lei->{pkt_op_c};
487         $lei->event_step_init;
488         # oneshot needs $op, daemon-mode uses DS->EventLoop to handle $op
489         $lei->{oneshot} ? $op : undef;
490 }
491
492 sub _help {
493         require PublicInbox::LeiHelp;
494         PublicInbox::LeiHelp::call($_[0], $_[1], \%CMD, \%OPTDESC);
495 }
496
497 sub optparse ($$$) {
498         my ($self, $cmd, $argv) = @_;
499         # allow _complete --help to complete, not show help
500         return 1 if substr($cmd, 0, 1) eq '_';
501         $self->{cmd} = $cmd;
502         $OPT = $self->{opt} //= {};
503         my $info = $CMD{$cmd} // [ '[...]' ];
504         my ($proto, undef, @spec) = @$info;
505         my $glp = ref($spec[-1]) eq ref($GLP) ? pop(@spec) : $GLP;
506         push @spec, qw(help|h);
507         my $lone_dash;
508         if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
509                 $lone_dash = $spec[0];
510                 $OPT->{$spec[0]} = \(my $var);
511                 push @spec, '' => \$var;
512         }
513         $glp->getoptionsfromarray($argv, $OPT, @spec) or
514                 return _help($self, "bad arguments or options for $cmd");
515         return _help($self) if $OPT->{help};
516
517         push @$argv, @{$OPT->{-argv}} if defined($OPT->{-argv});
518
519         # "-" aliases "stdin" or "clear"
520         $OPT->{$lone_dash} = ${$OPT->{$lone_dash}} if defined $lone_dash;
521
522         my $i = 0;
523         my $POS_ARG = '[A-Z][A-Z0-9_]+';
524         my ($err, $inf);
525         my @args = split(/ /, $proto);
526         for my $var (@args) {
527                 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
528                         $inf = defined($argv->[$i]) and last;
529                         $var =~ s/\.\.\.\z//;
530                         $err = "$var not supplied";
531                 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
532                         $argv->[$i++] // ($err = "$var not supplied");
533                 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
534                         $inf = 1;
535                         last;
536                 } elsif ($var =~ /\A\[-?$POS_ARG\]\z/) { # one optional arg
537                         $i++;
538                 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
539                         $inf = 1 if index($var, '...') > 0;
540                         my @or = split(/\|/, $var);
541                         my $ok;
542                         for my $o (@or) {
543                                 if ($o =~ /\A--([a-z0-9\-]+)/) {
544                                         $ok = defined($OPT->{$1});
545                                         last if $ok;
546                                 } elsif (defined($argv->[$i])) {
547                                         $ok = 1;
548                                         $i++;
549                                         last;
550                                 } # else continue looping
551                         }
552                         last if $ok;
553                         my $last = pop @or;
554                         $err = join(', ', @or) . " or $last must be set";
555                 } else {
556                         warn "BUG: can't parse `$var' in $proto";
557                 }
558                 last if $err;
559         }
560         if (!$inf && scalar(@$argv) > scalar(@args)) {
561                 $err //= 'too many arguments';
562         }
563         $err ? fail($self, "usage: lei $cmd $proto\nE: $err") : 1;
564 }
565
566 sub dispatch {
567         my ($self, $cmd, @argv) = @_;
568         local $current_lei = $self; # for __WARN__
569         dump_and_clear_log("from previous run\n");
570         return _help($self, 'no command given') unless defined($cmd);
571         while ($cmd eq '-C') { # do not support Getopt bundling for this
572                 my $d = shift(@argv) // return fail($self, '-C DIRECTORY');
573                 push @{$self->{opt}->{C}}, $d;
574                 $cmd = shift(@argv) // return _help($self, 'no command given');
575         }
576         my $func = "lei_$cmd";
577         $func =~ tr/-/_/;
578         if (my $cb = __PACKAGE__->can($func)) {
579                 optparse($self, $cmd, \@argv) or return;
580                 if (my $chdir = $self->{opt}->{C}) {
581                         for my $d (@$chdir) {
582                                 next if $d eq ''; # same as git(1)
583                                 chdir $d or return fail($self, "cd $d: $!");
584                         }
585                 }
586                 $cb->($self, @argv);
587         } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
588                 $GLP->getoptionsfromarray([$cmd, @argv], {}, qw(help|h C=s@))
589                         or return _help($self, 'bad arguments or options');
590                 _help($self);
591         } else {
592                 fail($self, "`$cmd' is not an lei command");
593         }
594 }
595
596 sub _lei_cfg ($;$) {
597         my ($self, $creat) = @_;
598         my $f = _config_path($self);
599         my @st = stat($f);
600         my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
601         if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
602                 return ($self->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
603         }
604         if (!@st) {
605                 unless ($creat) {
606                         delete $self->{cfg};
607                         return bless {}, 'PublicInbox::Config';
608                 }
609                 my (undef, $cfg_dir, undef) = File::Spec->splitpath($f);
610                 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
611                 open my $fh, '>>', $f or die "open($f): $!\n";
612                 @st = stat($fh) or die "fstat($f): $!\n";
613                 $cur_st = pack('dd', $st[10], $st[7]);
614                 qerr($self, "# $f created") if $self->{cmd} ne 'config';
615         }
616         my $cfg = PublicInbox::Config::git_config_dump($f);
617         bless $cfg, 'PublicInbox::Config';
618         $cfg->{-st} = $cur_st;
619         $cfg->{'-f'} = $f;
620         $self->{cfg} = $PATH2CFG{$f} = $cfg;
621 }
622
623 sub _lei_store ($;$) {
624         my ($self, $creat) = @_;
625         my $cfg = _lei_cfg($self, $creat);
626         $cfg->{-lei_store} //= do {
627                 require PublicInbox::LeiStore;
628                 my $dir = $cfg->{'leistore.dir'};
629                 $dir //= $creat ? _store_path($self) : return;
630                 PublicInbox::LeiStore->new($dir, { creat => $creat });
631         };
632 }
633
634 sub lei_show {
635         my ($self, @argv) = @_;
636 }
637
638 sub lei_mark {
639         my ($self, @argv) = @_;
640 }
641
642 sub _config {
643         my ($self, @argv) = @_;
644         my %env = (%{$self->{env}}, GIT_CONFIG => undef);
645         my $cfg = _lei_cfg($self, 1);
646         my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
647         my %rdr = map { $_ => $self->{$_} } (0..2);
648         waitpid(spawn($cmd, \%env, \%rdr), 0);
649 }
650
651 sub lei_config {
652         my ($self, @argv) = @_;
653         $self->{opt}->{'config-file'} and return fail $self,
654                 "config file switches not supported by `lei config'";
655         _config(@_);
656         x_it($self, $?) if $?;
657 }
658
659 sub lei_import {
660         require PublicInbox::LeiImport;
661         PublicInbox::LeiImport->call(@_);
662 }
663
664 sub lei_convert {
665         require PublicInbox::LeiConvert;
666         PublicInbox::LeiConvert->call(@_);
667 }
668
669 sub lei_init {
670         my ($self, $dir) = @_;
671         my $cfg = _lei_cfg($self, 1);
672         my $cur = $cfg->{'leistore.dir'};
673         $dir //= _store_path($self);
674         $dir = rel2abs($self, $dir);
675         my @cur = stat($cur) if defined($cur);
676         $cur = File::Spec->canonpath($cur // $dir);
677         my @dir = stat($dir);
678         my $exists = "# leistore.dir=$cur already initialized" if @dir;
679         if (@cur) {
680                 if ($cur eq $dir) {
681                         _lei_store($self, 1)->done;
682                         return qerr($self, $exists);
683                 }
684
685                 # some folks like symlinks and bind mounts :P
686                 if (@dir && "@cur[1,0]" eq "@dir[1,0]") {
687                         lei_config($self, 'leistore.dir', $dir);
688                         _lei_store($self, 1)->done;
689                         return qerr($self, "$exists (as $cur)");
690                 }
691                 return fail($self, <<"");
692 E: leistore.dir=$cur already initialized and it is not $dir
693
694         }
695         lei_config($self, 'leistore.dir', $dir);
696         _lei_store($self, 1)->done;
697         $exists //= "# leistore.dir=$dir newly initialized";
698         return qerr($self, $exists);
699 }
700
701 sub lei_daemon_pid { puts shift, $$ }
702
703 sub lei_daemon_kill {
704         my ($self) = @_;
705         my $sig = $self->{opt}->{signal} // 'TERM';
706         kill($sig, $$) or fail($self, "kill($sig, $$): $!");
707 }
708
709 sub lei_help { _help($_[0]) }
710
711 # Shell completion helper.  Used by lei-completion.bash and hopefully
712 # other shells.  Try to do as much here as possible to avoid redundancy
713 # and improve maintainability.
714 sub lei__complete {
715         my ($self, @argv) = @_; # argv = qw(lei and any other args...)
716         shift @argv; # ignore "lei", the entire command is sent
717         @argv or return puts $self, grep(!/^_/, keys %CMD), qw(--help -h -C);
718         my $cmd = shift @argv;
719         my $info = $CMD{$cmd} // do { # filter matching commands
720                 @argv or puts $self, grep(/\A\Q$cmd\E/, keys %CMD);
721                 return;
722         };
723         my ($proto, undef, @spec) = @$info;
724         my $cur = pop @argv;
725         my $re = defined($cur) ? qr/\A\Q$cur\E/ : qr/./;
726         if (substr($cur // '-', 0, 1) eq '-') { # --switches
727                 # gross special case since the only git-config options
728                 # Consider moving to a table if we need more special cases
729                 # we use Getopt::Long for are the ones we reject, so these
730                 # are the ones we don't reject:
731                 if ($cmd eq 'config') {
732                         puts $self, grep(/$re/, keys %CONFIG_KEYS);
733                         @spec = qw(add z|null get get-all unset unset-all
734                                 replace-all get-urlmatch
735                                 remove-section rename-section
736                                 name-only list|l edit|e
737                                 get-color-name get-colorbool);
738                         # fall-through
739                 }
740                 # generate short/long names from Getopt::Long specs
741                 puts $self, grep(/$re/, qw(--help -h -C), map {
742                         if (s/[:=].+\z//) { # req/optional args, e.g output|o=i
743                         } elsif (s/\+\z//) { # verbose|v+
744                         } elsif (s/!\z//) {
745                                 # negation: solve! => no-solve|solve
746                                 s/([\w\-]+)/$1|no-$1/g
747                         }
748                         map {
749                                 my $x = length > 1 ? "--$_" : "-$_";
750                                 $x eq $cur ? () : $x;
751                         } grep(!/_/, split(/\|/, $_, -1)) # help|h
752                 } grep { $OPTDESC{"$cmd\t$_"} || $OPTDESC{$_} } @spec);
753         } elsif ($cmd eq 'config' && !@argv && !$CONFIG_KEYS{$cur}) {
754                 puts $self, grep(/$re/, keys %CONFIG_KEYS);
755         }
756
757         # switch args (e.g. lei q -f mbox<TAB>)
758         if (($argv[-1] // $cur // '') =~ /\A--?([\w\-]+)\z/) {
759                 my $opt = quotemeta $1;
760                 puts $self, map {
761                         my $v = $OPTDESC{$_};
762                         my @v = ref($v) ? split(/\|/, $v->[0]) : ();
763                         # get rid of ALL CAPS placeholder (e.g "OUT")
764                         # (TODO: completion for external paths)
765                         shift(@v) if uc($v[0]) eq $v[0];
766                         @v;
767                 } grep(/\A(?:$cmd\t|)(?:[\w-]+\|)*$opt\b/, keys %OPTDESC);
768         }
769         $cmd =~ tr/-/_/;
770         if (my $sub = $self->can("_complete_$cmd")) {
771                 puts $self, $sub->($self, @argv, $cur);
772         }
773         # TODO: URLs, pathnames, OIDs, MIDs, etc...  See optparse() for
774         # proto parsing.
775 }
776
777 sub exec_buf ($$) {
778         my ($argv, $env) = @_;
779         my $argc = scalar @$argv;
780         my $buf = 'exec '.join("\0", scalar(@$argv), @$argv);
781         while (my ($k, $v) = each %$env) { $buf .= "\0$k=$v" };
782         $buf;
783 }
784
785 sub start_mua {
786         my ($self) = @_;
787         my $mua = $self->{opt}->{mua} // return;
788         my $mfolder = $self->{ovv}->{dst};
789         my (@cmd, $replaced);
790         if ($mua =~ /\A(?:mutt|mailx|mail|neomutt)\z/) {
791                 @cmd = ($mua, '-f');
792         # TODO: help wanted: other common FOSS MUAs
793         } else {
794                 require Text::ParseWords;
795                 @cmd = Text::ParseWords::shellwords($mua);
796                 # mutt uses '%f' for open-hook with compressed mbox, we follow
797                 @cmd = map { $_ eq '%f' ? ($replaced = $mfolder) : $_ } @cmd;
798         }
799         push @cmd, $mfolder unless defined($replaced);
800         if (my $sock = $self->{sock}) { # lei(1) client process runs it
801                 send($sock, exec_buf(\@cmd, {}), MSG_EOR);
802         } elsif ($self->{oneshot}) {
803                 $self->{"pid.$self.$$"}->{spawn(\@cmd)} = \@cmd;
804         }
805         if ($self->{lxs} && $self->{au_done}) { # kick wait_startq
806                 syswrite($self->{au_done}, 'q' x ($self->{lxs}->{jobs} // 0));
807         }
808         $self->{opt}->{quiet} = 1;
809         delete $self->{-progress};
810         delete $self->{opt}->{verbose};
811 }
812
813 sub send_exec_cmd { # tell script/lei to execute a command
814         my ($self, $io, $cmd, $env) = @_;
815         my $sock = $self->{sock} // die 'lei client gone';
816         my $fds = [ map { fileno($_) } @$io ];
817         $send_cmd->($sock, $fds, exec_buf($cmd, $env), MSG_EOR);
818 }
819
820 sub poke_mua { # forces terminal MUAs to wake up and hopefully notice new mail
821         my ($self) = @_;
822         my $alerts = $self->{opt}->{alert} // return;
823         while (my $op = shift(@$alerts)) {
824                 if ($op eq ':WINCH') {
825                         # hit the process group that started the MUA
826                         if ($self->{sock}) {
827                                 send($self->{sock}, '-WINCH', MSG_EOR);
828                         } elsif ($self->{oneshot}) {
829                                 kill('-WINCH', $$);
830                         }
831                 } elsif ($op eq ':bell') {
832                         out($self, "\a");
833                 } elsif ($op =~ /(?<!\\),/) { # bare ',' (not ',,')
834                         push @$alerts, split(/(?<!\\),/, $op);
835                 } elsif ($op =~ m!\A([/a-z0-9A-Z].+)!) {
836                         my $cmd = $1; # run an arbitrary command
837                         require Text::ParseWords;
838                         $cmd = [ Text::ParseWords::shellwords($cmd) ];
839                         if (my $s = $self->{sock}) {
840                                 send($s, exec_buf($cmd, {}), MSG_EOR);
841                         } elsif ($self->{oneshot}) {
842                                 $self->{"pid.$self.$$"}->{spawn($cmd)} = $cmd;
843                         }
844                 } else {
845                         err($self, "W: unsupported --alert=$op"); # non-fatal
846                 }
847         }
848 }
849
850 # caller needs to "-t $self->{1}" to check if tty
851 sub start_pager {
852         my ($self) = @_;
853         my $fh = popen_rd([qw(git var GIT_PAGER)]);
854         chomp(my $pager = <$fh> // '');
855         close($fh) or warn "`git var PAGER' error: \$?=$?";
856         return if $pager eq 'cat' || $pager eq '';
857         my $new_env = { LESS => 'FRX', LV => '-c' };
858         $new_env->{MORE} = 'FRX' if $^O eq 'freebsd';
859         pipe(my ($r, $wpager)) or return warn "pipe: $!";
860         my $rdr = { 0 => $r, 1 => $self->{1}, 2 => $self->{2} };
861         my $pgr = [ undef, @$rdr{1, 2} ];
862         my $env = $self->{env};
863         if ($self->{sock}) { # lei(1) process runs it
864                 delete @$new_env{keys %$env}; # only set iff unset
865                 send_exec_cmd($self, [ @$rdr{0..2} ], [$pager], $new_env);
866         } elsif ($self->{oneshot}) {
867                 my $cmd = [$pager];
868                 $self->{"pid.$self.$$"}->{spawn($cmd, $new_env, $rdr)} = $cmd;
869         } else {
870                 die 'BUG: start_pager w/o socket';
871         }
872         $self->{1} = $wpager;
873         $self->{2} = $wpager if -t $self->{2};
874         $env->{GIT_PAGER_IN_USE} = 'true'; # we may spawn git
875         $self->{pgr} = $pgr;
876 }
877
878 sub stop_pager {
879         my ($self) = @_;
880         my $pgr = delete($self->{pgr}) or return;
881         $self->{2} = $pgr->[2];
882         # do not restore original stdout, just close it so we error out
883         close(delete($self->{1})) if $self->{1};
884 }
885
886 sub accept_dispatch { # Listener {post_accept} callback
887         my ($sock) = @_; # ignore other
888         $sock->autoflush(1);
889         my $self = bless { sock => $sock }, __PACKAGE__;
890         vec(my $rvec = '', fileno($sock), 1) = 1;
891         select($rvec, undef, undef, 60) or
892                 return send($sock, 'timed out waiting to recv FDs', MSG_EOR);
893         # (4096 * 33) >MAX_ARG_STRLEN
894         my @fds = $recv_cmd->($sock, my $buf, 4096 * 33) or return; # EOF
895         if (scalar(@fds) == 4) {
896                 for my $i (0..3) {
897                         my $fd = shift(@fds);
898                         open($self->{$i}, '+<&=', $fd) and next;
899                         send($sock, "open(+<&=$fd) (FD=$i): $!", MSG_EOR);
900                 }
901         } elsif (!defined($fds[0])) {
902                 warn(my $msg = "recv_cmd failed: $!");
903                 return send($sock, $msg, MSG_EOR);
904         } else {
905                 return;
906         }
907         $self->{2}->autoflush(1); # keep stdout buffered until x_it|DESTROY
908         # $ENV_STR = join('', map { "\0$_=$ENV{$_}" } keys %ENV);
909         # $buf = "$argc\0".join("\0", @ARGV).$ENV_STR."\0\0";
910         substr($buf, -2, 2, '') eq "\0\0" or  # s/\0\0\z//
911                 return send($sock, 'request command truncated', MSG_EOR);
912         my ($argc, @argv) = split(/\0/, $buf, -1);
913         undef $buf;
914         my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
915         if (chdir($self->{3})) {
916                 local %ENV = %env;
917                 $self->{env} = \%env;
918                 eval { dispatch($self, @argv) };
919                 send($sock, $@, MSG_EOR) if $@;
920         } else {
921                 send($sock, "fchdir: $!", MSG_EOR); # implicit close
922         }
923 }
924
925 sub dclose {
926         my ($self) = @_;
927         delete $self->{-progress};
928         for my $f (@WQ_KEYS) {
929                 my $wq = delete $self->{$f} or next;
930                 if ($wq->wq_kill) {
931                         $wq->wq_close(0, undef, $self);
932                 } elsif ($wq->wq_kill_old) {
933                         $wq->wq_wait_old(undef, $self);
934                 }
935         }
936         close(delete $self->{1}) if $self->{1}; # may reap_compress
937         $self->close if $self->{sock}; # PublicInbox::DS::close
938 }
939
940 # for long-running results
941 sub event_step {
942         my ($self) = @_;
943         local %ENV = %{$self->{env}};
944         my $sock = $self->{sock};
945         local $current_lei = $self;
946         eval {
947                 while (my @fds = $recv_cmd->($sock, my $buf, 4096)) {
948                         if (scalar(@fds) == 1 && !defined($fds[0])) {
949                                 return if $! == EAGAIN;
950                                 next if $! == EINTR;
951                                 last if $! == ECONNRESET;
952                                 die "recvmsg: $!";
953                         }
954                         for my $fd (@fds) {
955                                 open my $rfh, '+<&=', $fd;
956                         }
957                         die "unrecognized client signal: $buf";
958                 }
959                 dclose($self);
960         };
961         if (my $err = $@) {
962                 eval { $self->fail($err) };
963                 dclose($self);
964         }
965 }
966
967 sub event_step_init {
968         my ($self) = @_;
969         return if $self->{-event_init_done}++;
970         if (my $sock = $self->{sock}) { # using DS->EventLoop
971                 $self->SUPER::new($sock, EPOLLIN|EPOLLET);
972         }
973 }
974
975 sub noop {}
976
977 our $oldset; sub oldset { $oldset }
978
979 sub dump_and_clear_log {
980         if (defined($errors_log) && -s STDIN && seek(STDIN, 0, SEEK_SET)) {
981                 my @pfx = @_;
982                 unshift(@pfx, "$errors_log ") if @pfx;
983                 warn @pfx, do { local $/; <STDIN> };
984                 truncate(STDIN, 0) or warn "ftruncate ($errors_log): $!";
985         }
986 }
987
988 # lei(1) calls this when it can't connect
989 sub lazy_start {
990         my ($path, $errno, $narg) = @_;
991         local ($errors_log, $listener);
992         ($errors_log) = ($path =~ m!\A(.+?/)[^/]+\z!);
993         $errors_log .= 'errors.log';
994         my $addr = pack_sockaddr_un($path);
995         my $lk = bless { lock_path => $errors_log }, 'PublicInbox::Lock';
996         $lk->lock_acquire;
997         socket($listener, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
998         if ($errno == ECONNREFUSED || $errno == ENOENT) {
999                 return if connect($listener, $addr); # another process won
1000                 if ($errno == ECONNREFUSED && -S $path) {
1001                         unlink($path) or die "unlink($path): $!";
1002                 }
1003         } else {
1004                 $! = $errno; # allow interpolation to stringify in die
1005                 die "connect($path): $!";
1006         }
1007         umask(077) // die("umask(077): $!");
1008         bind($listener, $addr) or die "bind($path): $!";
1009         listen($listener, 1024) or die "listen: $!";
1010         $lk->lock_release;
1011         undef $lk;
1012         my @st = stat($path) or die "stat($path): $!";
1013         my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
1014         local $oldset = PublicInbox::DS::block_signals();
1015         if ($narg == 5) {
1016                 $send_cmd = PublicInbox::Spawn->can('send_cmd4');
1017                 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4') // do {
1018                         require PublicInbox::CmdIPC4;
1019                         $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4');
1020                         PublicInbox::CmdIPC4->can('recv_cmd4');
1021                 };
1022         }
1023         $recv_cmd or die <<"";
1024 (Socket::MsgHdr || Inline::C) missing/unconfigured (narg=$narg);
1025
1026         require PublicInbox::Listener;
1027         require PublicInbox::EOFpipe;
1028         (-p STDOUT) or die "E: stdout must be a pipe\n";
1029         open(STDIN, '+>>', $errors_log) or die "open($errors_log): $!";
1030         STDIN->autoflush(1);
1031         dump_and_clear_log("from previous daemon process:\n");
1032         POSIX::setsid() > 0 or die "setsid: $!";
1033         my $pid = fork // die "fork: $!";
1034         return if $pid;
1035         $0 = "lei-daemon $path";
1036         local %PATH2CFG;
1037         $listener->blocking(0);
1038         my $exit_code;
1039         my $pil = PublicInbox::Listener->new($listener, \&accept_dispatch);
1040         local $quit = do {
1041                 pipe(my ($eof_r, $eof_w)) or die "pipe: $!";
1042                 PublicInbox::EOFpipe->new($eof_r, \&noop, undef);
1043                 sub {
1044                         $exit_code //= shift;
1045                         my $lis = $pil or exit($exit_code);
1046                         # closing eof_w triggers \&noop wakeup
1047                         $listener = $eof_w = $pil = $path = undef;
1048                         $lis->close; # DS::close
1049                         PublicInbox::DS->SetLoopTimeout(1000);
1050                 };
1051         };
1052         my $sig = {
1053                 CHLD => \&PublicInbox::DS::enqueue_reap,
1054                 QUIT => $quit,
1055                 INT => $quit,
1056                 TERM => $quit,
1057                 HUP => \&noop,
1058                 USR1 => \&noop,
1059                 USR2 => \&noop,
1060         };
1061         my $sigfd = PublicInbox::Sigfd->new($sig, SFD_NONBLOCK);
1062         local @SIG{keys %$sig} = values(%$sig) unless $sigfd;
1063         undef $sig;
1064         local $SIG{PIPE} = 'IGNORE';
1065         if ($sigfd) { # TODO: use inotify/kqueue to detect unlinked sockets
1066                 undef $sigfd;
1067                 PublicInbox::DS->SetLoopTimeout(5000);
1068         } else {
1069                 # wake up every second to accept signals if we don't
1070                 # have signalfd or IO::KQueue:
1071                 PublicInbox::DS::sig_setmask($oldset);
1072                 PublicInbox::DS->SetLoopTimeout(1000);
1073         }
1074         PublicInbox::DS->SetPostLoopCallback(sub {
1075                 my ($dmap, undef) = @_;
1076                 if (@st = defined($path) ? stat($path) : ()) {
1077                         if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
1078                                 warn "$path dev/ino changed, quitting\n";
1079                                 $path = undef;
1080                         }
1081                 } elsif (defined($path)) { # ENOENT is common
1082                         warn "stat($path): $!, quitting ...\n" if $! != ENOENT;
1083                         undef $path;
1084                         $quit->();
1085                 }
1086                 return 1 if defined($path);
1087                 my $now = now();
1088                 my $n = 0;
1089                 for my $s (values %$dmap) {
1090                         $s->can('busy') or next;
1091                         if ($s->busy($now)) {
1092                                 ++$n;
1093                         } else {
1094                                 $s->close;
1095                         }
1096                 }
1097                 $n; # true: continue, false: stop
1098         });
1099
1100         # STDIN was redirected to /dev/null above, closing STDERR and
1101         # STDOUT will cause the calling `lei' client process to finish
1102         # reading the <$daemon> pipe.
1103         local $SIG{__WARN__} = sub {
1104                 $current_lei ? err($current_lei, @_) : warn(
1105                   strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time))," $$ ", @_);
1106         };
1107         open STDERR, '>&STDIN' or die "redirect stderr failed: $!";
1108         open STDOUT, '>&STDIN' or die "redirect stdout failed: $!";
1109         # $daemon pipe to `lei' closed, main loop begins:
1110         PublicInbox::DS->EventLoop;
1111         exit($exit_code // 0);
1112 }
1113
1114 sub busy { 1 } # prevent daemon-shutdown if client is connected
1115
1116 # for users w/o Socket::Msghdr installed or Inline::C enabled
1117 sub oneshot {
1118         my ($main_pkg) = @_;
1119         my $exit = $main_pkg->can('exit'); # caller may override exit()
1120         local $quit = $exit if $exit;
1121         local %PATH2CFG;
1122         umask(077) // die("umask(077): $!");
1123         my $self = bless {
1124                 oneshot => 1,
1125                 0 => *STDIN{GLOB},
1126                 1 => *STDOUT{GLOB},
1127                 2 => *STDERR{GLOB},
1128                 env => \%ENV
1129         }, __PACKAGE__;
1130         dispatch($self, @ARGV);
1131         x_it($self, $self->{child_error}) if $self->{child_error};
1132 }
1133
1134 # ensures stdout hits the FS before sock disconnects so a client
1135 # can immediately reread it
1136 sub DESTROY {
1137         my ($self) = @_;
1138         $self->{1}->autoflush(1) if $self->{1};
1139         stop_pager($self);
1140         my $err = $?;
1141         my $oneshot_pids = delete $self->{"pid.$self.$$"} or return;
1142         waitpid($_, 0) for keys %$oneshot_pids;
1143         $? = $err if $err; # preserve ->fail or ->x_it code
1144 }
1145
1146 1;