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