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