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