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