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