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