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