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