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