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