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