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