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