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