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