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