]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LEI.pm
lei: query: ensure pager exit is instantaneous
[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_STREAM pack_sockaddr_un);
15 use Errno qw(EAGAIN ECONNREFUSED ENOENT);
16 use POSIX ();
17 use IO::Handle ();
18 use Sys::Syslog qw(syslog openlog);
19 use PublicInbox::Config;
20 use PublicInbox::Syscall qw(SFD_NONBLOCK EPOLLIN EPOLLONESHOT);
21 use PublicInbox::Sigfd;
22 use PublicInbox::DS qw(now dwaitpid);
23 use PublicInbox::Spawn qw(spawn run_die popen_rd);
24 use PublicInbox::OnDestroy;
25 use Text::Wrap qw(wrap);
26 use File::Path qw(mkpath);
27 use File::Spec;
28 our $quit = \&CORE::exit;
29 my $recv_cmd;
30 my $GLP = Getopt::Long::Parser->new;
31 $GLP->configure(qw(gnu_getopt no_ignore_case auto_abbrev));
32 my $GLP_PASS = Getopt::Long::Parser->new;
33 $GLP_PASS->configure(qw(gnu_getopt no_ignore_case auto_abbrev pass_through));
34
35 our %PATH2CFG; # persistent for socket daemon
36
37 # TBD: this is a documentation mechanism to show a subcommand
38 # (may) pass options through to another command:
39 sub pass_through { $GLP_PASS }
40
41 my $OPT;
42 sub opt_dash ($$) {
43         my ($spec, $re_str) = @_; # 'limit|n=i', '([0-9]+)'
44         my ($key) = ($spec =~ m/\A([a-z]+)/g);
45         my $cb = sub { # Getopt::Long "<>" catch-all handler
46                 my ($arg) = @_;
47                 if ($arg =~ /\A-($re_str)\z/) {
48                         $OPT->{$key} = $1;
49                 } elsif ($arg eq '--') { # "--" arg separator, ignore first
50                         push @{$OPT->{-argv}}, $arg if $OPT->{'--'}++;
51                 # lone (single) dash is handled elsewhere
52                 } elsif (substr($arg, 0, 1) eq '-') {
53                         if ($OPT->{'--'}) {
54                                 push @{$OPT->{-argv}}, $arg;
55                         } else {
56                                 die "bad argument: $arg\n";
57                         }
58                 } else {
59                         push @{$OPT->{-argv}}, $arg;
60                 }
61         };
62         ($spec, '<>' => $cb, $GLP_PASS) # for Getopt::Long
63 }
64
65 sub _store_path ($) {
66         my ($env) = @_;
67         File::Spec->rel2abs(($env->{XDG_DATA_HOME} //
68                 ($env->{HOME} // '/nonexistent').'/.local/share')
69                 .'/lei/store', $env->{PWD});
70 }
71
72 sub _config_path ($) {
73         my ($env) = @_;
74         File::Spec->rel2abs(($env->{XDG_CONFIG_HOME} //
75                 ($env->{HOME} // '/nonexistent').'/.config')
76                 .'/lei/config', $env->{PWD});
77 }
78
79 # TODO: generate shell completion + help using %CMD and %OPTDESC
80 # command => [ positional_args, 1-line description, Getopt::Long option spec ]
81 our %CMD = ( # sorted in order of importance/use:
82 'q' => [ 'SEARCH_TERMS...', 'search for messages matching terms', qw(
83         save-as=s output|mfolder|o=s format|f=s dedupe|d=s thread|t augment|a
84         sort|s=s reverse|r offset=i remote local! external! pretty
85         since|after=s until|before=s), opt_dash('limit|n=i', '[0-9]+') ],
86
87 'show' => [ 'MID|OID', 'show a given object (Message-ID or object ID)',
88         qw(type=s solve! format|f=s dedupe|d=s thread|t remote local!),
89         pass_through('git show') ],
90
91 'add-external' => [ 'URL_OR_PATHNAME',
92         'add/set priority of a publicinbox|extindex for extra matches',
93         qw(boost=i quiet|q) ],
94 'ls-external' => [ '[FILTER...]', 'list publicinbox|extindex locations',
95         qw(format|f=s z|0 local remote quiet|q) ],
96 'forget-external' => [ '{URL_OR_PATHNAME|--prune}',
97         'exclude further results from a publicinbox|extindex',
98         qw(prune quiet|q) ],
99
100 'ls-query' => [ '[FILTER...]', 'list saved search queries',
101                 qw(name-only format|f=s z) ],
102 'rm-query' => [ 'QUERY_NAME', 'remove a saved search' ],
103 'mv-query' => [ qw(OLD_NAME NEW_NAME), 'rename a saved search' ],
104
105 'plonk' => [ '--thread|--from=IDENT',
106         'exclude mail matching From: or thread from non-Message-ID searches',
107         qw(stdin| thread|t from|f=s mid=s oid=s) ],
108 'mark' => [ 'MESSAGE_FLAGS...',
109         'set/unset flags on message(s) from stdin',
110         qw(stdin| oid=s exact by-mid|mid:s) ],
111 'forget' => [ '[--stdin|--oid=OID|--by-mid=MID]',
112         "exclude message(s) on stdin from `q' search results",
113         qw(stdin| oid=s exact by-mid|mid:s quiet|q) ],
114
115 'purge-mailsource' => [ '{URL_OR_PATHNAME|--all}',
116         'remove imported messages from IMAP, Maildirs, and MH',
117         qw(exact! all jobs:i indexed) ],
118
119 # code repos are used for `show' to solve blobs from patch mails
120 'add-coderepo' => [ 'PATHNAME', 'add or set priority of a git code repo',
121         qw(boost=i) ],
122 'ls-coderepo' => [ '[FILTER_TERMS...]',
123                 'list known code repos', qw(format|f=s z) ],
124 'forget-coderepo' => [ 'PATHNAME',
125         'stop using repo to solve blobs from patches',
126         qw(prune) ],
127
128 'add-watch' => [ '[URL_OR_PATHNAME]',
129                 'watch for new messages and flag changes',
130         qw(import! flags! interval=s recursive|r exclude=s include=s) ],
131 'ls-watch' => [ '[FILTER...]', 'list active watches with numbers and status',
132                 qw(format|f=s z) ],
133 'pause-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote) ],
134 'resume-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote) ],
135 'forget-watch' => [ '{WATCH_NUMBER|--prune}', 'stop and forget a watch',
136         qw(prune) ],
137
138 'import' => [ '{URL_OR_PATHNAME|--stdin}',
139         'one-shot import/update from URL or filesystem',
140         qw(stdin| offset=i recursive|r exclude=s include=s !flags),
141         ],
142
143 'config' => [ '[...]', sub {
144                 'git-config(1) wrapper for '._config_path($_[0]);
145         }, qw(config-file|system|global|file|f=s), # for conflict detection
146         pass_through('git config') ],
147 'init' => [ '[PATHNAME]', sub {
148                 'initialize storage, default: '._store_path($_[0]);
149         }, qw(quiet|q) ],
150 'daemon-kill' => [ '[-SIGNAL]', 'signal the lei-daemon',
151         opt_dash('signal|s=s', '[0-9]+|(?:[A-Z][A-Z0-9]+)') ],
152 'daemon-pid' => [ '', 'show the PID of the lei-daemon' ],
153 'help' => [ '[SUBCOMMAND]', 'show help' ],
154
155 # XXX do we need this?
156 # 'git' => [ '[ANYTHING...]', 'git(1) wrapper', pass_through('git') ],
157
158 'reorder-local-store-and-break-history' => [ '[REFNAME]',
159         'rewrite git history in an attempt to improve compression',
160         'gc!' ],
161
162 # internal commands are prefixed with '_'
163 '_complete' => [ '[...]', 'internal shell completion helper',
164                 pass_through('everything') ],
165 ); # @CMD
166
167 # switch descriptions, try to keep consistent across commands
168 # $spec: Getopt::Long option specification
169 # $spec => [@ALLOWED_VALUES (default is first), $description],
170 # $spec => $description
171 # "$SUB_COMMAND TAB $spec" => as above
172 my $stdin_formats = [ 'IN|auto|raw|mboxrd|mboxcl2|mboxcl|mboxo',
173                 'specify message input format' ];
174 my $ls_format = [ 'OUT|plain|json|null', 'listing output format' ];
175
176 my %OPTDESC = (
177 'help|h' => 'show this built-in help',
178 'quiet|q' => 'be quiet',
179 'solve!' => 'do not attempt to reconstruct blobs from emails',
180 'save-as=s' => ['NAME', 'save a search terms by given name'],
181
182 'type=s' => [ 'any|mid|git', 'disambiguate type' ],
183
184 'dedupe|d=s' => ['STRAT|content|oid|mid|none',
185                 'deduplication strategy'],
186 'show   thread|t' => 'display entire thread a message belongs to',
187 'q      thread|t' =>
188         'return all messages in the same thread as the actual match(es)',
189 'augment|a' => 'augment --output destination instead of clobbering',
190
191 'output|o=s' => [ 'DEST',
192         "destination (e.g. `/path/to/Maildir', or `-' for stdout)" ],
193
194 'show   format|f=s' => [ 'OUT|plain|raw|html|mboxrd|mboxcl2|mboxcl',
195                         'message/object output format' ],
196 'mark   format|f=s' => $stdin_formats,
197 'forget format|f=s' => $stdin_formats,
198 'q      format|f=s' => [ 'OUT|maildir|mboxrd|mboxcl2|mboxcl|html|oid|json',
199                 'specify output format, default depends on --output'],
200 'ls-query       format|f=s' => $ls_format,
201 'ls-external    format|f=s' => $ls_format,
202
203 'limit|n=i@' => ['NUM', 'limit on number of matches (default: 10000)' ],
204 'offset=i' => ['OFF', 'search result offset (default: 0)'],
205
206 'sort|s=s' => [ 'VAL|received,relevance,docid',
207                 "order of results `--output'-dependent"],
208 'reverse|r' => [ 'reverse search results' ], # like sort(1)
209
210 'boost=i' => 'increase/decrease priority of results (default: 0)',
211
212 'local' => 'limit operations to the local filesystem',
213 'local!' => 'exclude results from the local filesystem',
214 'remote' => 'limit operations to those requiring network access',
215 'remote!' => 'prevent operations requiring network access',
216
217 'mid=s' => 'specify the Message-ID of a message',
218 'oid=s' => 'specify the git object ID of a message',
219
220 'recursive|r' => 'scan directories/mailboxes/newsgroups recursively',
221 'exclude=s' => 'exclude mailboxes/newsgroups based on pattern',
222 'include=s' => 'include mailboxes/newsgroups based on pattern',
223
224 'exact' => 'operate on exact header matches only',
225 'exact!' => 'rely on content match instead of exact header matches',
226
227 'by-mid|mid:s' => [ 'MID', 'match only by Message-ID, ignoring contents' ],
228 'jobs:i' => 'set parallelism level',
229
230 # xargs, env, use "-0", git(1) uses "-z".  We support z|0 everywhere
231 'z|0' => 'use NUL \\0 instead of newline (CR) to delimit lines',
232
233 'signal|s=s' => [ 'SIG', 'signal to send lei-daemon (default: TERM)' ],
234 ); # %OPTDESC
235
236 my %CONFIG_KEYS = (
237         'leistore.dir' => 'top-level storage location',
238 );
239
240 sub x_it ($$) { # pronounced "exit"
241         my ($self, $code) = @_;
242         $self->{1}->autoflush(1); # make sure client sees stdout before exit
243         if (my $sig = ($code & 127)) {
244                 kill($sig, $self->{pid} // $$);
245         } else {
246                 $code >>= 8;
247                 if (my $sock = $self->{sock}) {
248                         say $sock "exit=$code";
249                 } else { # for oneshot
250                         $quit->($code);
251                 }
252         }
253 }
254
255 sub puts ($;@) { print { shift->{1} } map { "$_\n" } @_ }
256
257 sub out ($;@) { print { shift->{1} } @_ }
258
259 sub err ($;@) {
260         print { shift->{2} } @_, (substr($_[-1], -1, 1) eq "\n" ? () : "\n");
261 }
262
263 sub qerr ($;@) { $_[0]->{opt}->{quiet} or err(shift, @_) }
264
265 sub fail ($$;$) {
266         my ($self, $buf, $exit_code) = @_;
267         err($self, $buf);
268         x_it($self, ($exit_code // 1) << 8);
269         undef;
270 }
271
272 # usage: local %SIG = (%SIG, $lei->atfork_child_wq($wq));
273 sub atfork_child_wq {
274         my ($self, $wq) = @_;
275         $self->{sock} //= $wq->{0};
276         $self->{$_} //= $wq->{$_} for (0..2);
277         my $oldpipe = $SIG{PIPE};
278         (
279                 __WARN__ => sub { err($self, @_) },
280                 PIPE => sub {
281                         $self->x_it(141);
282                         $oldpipe->() if ref($oldpipe) eq 'CODE';
283                 }
284         );
285 }
286
287 # usage: ($lei, @io) = $lei->atfork_prepare_wq($wq);
288 sub atfork_prepare_wq {
289         my ($self, $wq) = @_;
290         if ($wq->wq_workers) {
291                 my $ret = bless { %$self }, ref($self);
292                 my $in = delete $ret->{0};
293                 ($ret, delete($ret->{sock}) // $in, delete @$ret{1, 2});
294         } else {
295                 ($self, ($self->{sock} // $self->{0}), @$self{1, 2});
296         }
297 }
298
299 sub _help ($;$) {
300         my ($self, $errmsg) = @_;
301         my $cmd = $self->{cmd} // 'COMMAND';
302         my @info = @{$CMD{$cmd} // [ '...', '...' ]};
303         my @top = ($cmd, shift(@info) // ());
304         my $cmd_desc = shift(@info);
305         $cmd_desc = $cmd_desc->($self->{env}) if ref($cmd_desc) eq 'CODE';
306         my @opt_desc;
307         my $lpad = 2;
308         for my $sw (grep { !ref } @info) { # ("prio=s", "z", $GLP_PASS)
309                 my $desc = $OPTDESC{"$cmd\t$sw"} // $OPTDESC{$sw} // next;
310                 my $arg_vals = '';
311                 ($arg_vals, $desc) = @$desc if ref($desc) eq 'ARRAY';
312
313                 # lower-case is a keyword (e.g. `content', `oid'),
314                 # ALL_CAPS is a string description (e.g. `PATH')
315                 if ($desc !~ /default/ && $arg_vals =~ /\b([a-z]+)[,\|]/) {
316                         $desc .= "\ndefault: `$1'";
317                 }
318                 my (@vals, @s, @l);
319                 my $x = $sw;
320                 if ($x =~ s/!\z//) { # solve! => --no-solve
321                         $x = "no-$x";
322                 } elsif ($x =~ s/:.+//) { # optional args: $x = "mid:s"
323                         @vals = (' [', undef, ']');
324                 } elsif ($x =~ s/=.+//) { # required arg: $x = "type=s"
325                         @vals = (' ', undef);
326                 } # else: no args $x = 'thread|t'
327                 for (split(/\|/, $x)) { # help|h
328                         length($_) > 1 ? push(@l, "--$_") : push(@s, "-$_");
329                 }
330                 if (!scalar(@vals)) { # no args 'thread|t'
331                 } elsif ($arg_vals =~ s/\A([A-Z_]+)\b//) { # "NAME"
332                         $vals[1] = $1;
333                 } else {
334                         $vals[1] = uc(substr($l[0], 2)); # "--type" => "TYPE"
335                 }
336                 if ($arg_vals =~ /([,\|])/) {
337                         my $sep = $1;
338                         my @allow = split(/\Q$sep\E/, $arg_vals);
339                         my $must = $sep eq '|' ? 'Must' : 'Can';
340                         @allow = map { "`$_'" } @allow;
341                         my $last = pop @allow;
342                         $desc .= "\n$must be one of: " .
343                                 join(', ', @allow) . " or $last";
344                 }
345                 my $lhs = join(', ', @s, @l) . join('', @vals);
346                 if ($x =~ /\|\z/) { # "stdin|" or "clear|"
347                         $lhs =~ s/\A--/- , --/;
348                 } else {
349                         $lhs =~ s/\A--/    --/; # pad if no short options
350                 }
351                 $lpad = length($lhs) if length($lhs) > $lpad;
352                 push @opt_desc, $lhs, $desc;
353         }
354         my $msg = $errmsg ? "E: $errmsg\n" : '';
355         $msg .= <<EOF;
356 usage: lei @top
357   $cmd_desc
358
359 EOF
360         $lpad += 2;
361         local $Text::Wrap::columns = 78 - $lpad;
362         my $padding = ' ' x ($lpad + 2);
363         while (my ($lhs, $rhs) = splice(@opt_desc, 0, 2)) {
364                 $msg .= '  '.pack("A$lpad", $lhs);
365                 $rhs = wrap('', '', $rhs);
366                 $rhs =~ s/\n/\n$padding/sg; # LHS pad continuation lines
367                 $msg .= $rhs;
368                 $msg .= "\n";
369         }
370         print { $self->{$errmsg ? 2 : 1} } $msg;
371         x_it($self, $errmsg ? 1 << 8 : 0); # stderr => failure
372         undef;
373 }
374
375 sub optparse ($$$) {
376         my ($self, $cmd, $argv) = @_;
377         $self->{cmd} = $cmd;
378         $OPT = $self->{opt} = {};
379         my $info = $CMD{$cmd} // [ '[...]' ];
380         my ($proto, undef, @spec) = @$info;
381         my $glp = ref($spec[-1]) eq ref($GLP) ? pop(@spec) : $GLP;
382         push @spec, qw(help|h);
383         my $lone_dash;
384         if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
385                 $lone_dash = $spec[0];
386                 $OPT->{$spec[0]} = \(my $var);
387                 push @spec, '' => \$var;
388         }
389         $glp->getoptionsfromarray($argv, $OPT, @spec) or
390                 return _help($self, "bad arguments or options for $cmd");
391         return _help($self) if $OPT->{help};
392
393         push @$argv, @{$OPT->{-argv}} if defined($OPT->{-argv});
394
395         # "-" aliases "stdin" or "clear"
396         $OPT->{$lone_dash} = ${$OPT->{$lone_dash}} if defined $lone_dash;
397
398         my $i = 0;
399         my $POS_ARG = '[A-Z][A-Z0-9_]+';
400         my ($err, $inf);
401         my @args = split(/ /, $proto);
402         for my $var (@args) {
403                 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
404                         $inf = defined($argv->[$i]) and last;
405                         $var =~ s/\.\.\.\z//;
406                         $err = "$var not supplied";
407                 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
408                         $argv->[$i++] // ($err = "$var not supplied");
409                 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
410                         $inf = 1;
411                         last;
412                 } elsif ($var =~ /\A\[-?$POS_ARG\]\z/) { # one optional arg
413                         $i++;
414                 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
415                         my @or = split(/\|/, $var);
416                         my $ok;
417                         for my $o (@or) {
418                                 if ($o =~ /\A--([a-z0-9\-]+)/) {
419                                         $ok = defined($OPT->{$1});
420                                         last;
421                                 } elsif (defined($argv->[$i])) {
422                                         $ok = 1;
423                                         $i++;
424                                         last;
425                                 } # else continue looping
426                         }
427                         my $last = pop @or;
428                         $err = join(', ', @or) . " or $last must be set";
429                 } else {
430                         warn "BUG: can't parse `$var' in $proto";
431                 }
432                 last if $err;
433         }
434         if (!$inf && scalar(@$argv) > scalar(@args)) {
435                 $err //= 'too many arguments';
436         }
437         $err ? fail($self, "usage: lei $cmd $proto\nE: $err") : 1;
438 }
439
440 sub dispatch {
441         my ($self, $cmd, @argv) = @_;
442         local $SIG{__WARN__} = sub { err($self, @_) };
443         return _help($self, 'no command given') unless defined($cmd);
444         my $func = "lei_$cmd";
445         $func =~ tr/-/_/;
446         if (my $cb = __PACKAGE__->can($func)) {
447                 optparse($self, $cmd, \@argv) or return;
448                 $cb->($self, @argv);
449         } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
450                 my $opt = {};
451                 $GLP->getoptionsfromarray([$cmd, @argv], $opt, qw(help|h)) or
452                         return _help($self, 'bad arguments or options');
453                 _help($self);
454         } else {
455                 fail($self, "`$cmd' is not an lei command");
456         }
457 }
458
459 sub _lei_cfg ($;$) {
460         my ($self, $creat) = @_;
461         my $f = _config_path($self->{env});
462         my @st = stat($f);
463         my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
464         if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
465                 return ($self->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
466         }
467         if (!@st) {
468                 unless ($creat) {
469                         delete $self->{cfg};
470                         return;
471                 }
472                 my (undef, $cfg_dir, undef) = File::Spec->splitpath($f);
473                 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
474                 open my $fh, '>>', $f or die "open($f): $!\n";
475                 @st = stat($fh) or die "fstat($f): $!\n";
476                 $cur_st = pack('dd', $st[10], $st[7]);
477                 qerr($self, "I: $f created") if $self->{cmd} ne 'config';
478         }
479         my $cfg = PublicInbox::Config::git_config_dump($f);
480         $cfg->{-st} = $cur_st;
481         $cfg->{'-f'} = $f;
482         $self->{cfg} = $PATH2CFG{$f} = $cfg;
483 }
484
485 sub _lei_store ($;$) {
486         my ($self, $creat) = @_;
487         my $cfg = _lei_cfg($self, $creat);
488         $cfg->{-lei_store} //= do {
489                 require PublicInbox::LeiStore;
490                 my $dir = $cfg->{'leistore.dir'};
491                 $dir //= _store_path($self->{env}) if $creat;
492                 return unless $dir;
493                 PublicInbox::LeiStore->new($dir, { creat => $creat });
494         };
495 }
496
497 sub lei_show {
498         my ($self, @argv) = @_;
499 }
500
501 sub lei_mark {
502         my ($self, @argv) = @_;
503 }
504
505 sub lei_config {
506         my ($self, @argv) = @_;
507         $self->{opt}->{'config-file'} and return fail $self,
508                 "config file switches not supported by `lei config'";
509         my $env = $self->{env};
510         delete local $env->{GIT_CONFIG};
511         my $cfg = _lei_cfg($self, 1);
512         my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
513         my %rdr = map { $_ => $self->{$_} } (0..2);
514         run_die($cmd, $env, \%rdr);
515 }
516
517 sub lei_init {
518         my ($self, $dir) = @_;
519         my $cfg = _lei_cfg($self, 1);
520         my $cur = $cfg->{'leistore.dir'};
521         my $env = $self->{env};
522         $dir //= _store_path($env);
523         $dir = File::Spec->rel2abs($dir, $env->{PWD}); # PWD is symlink-aware
524         my @cur = stat($cur) if defined($cur);
525         $cur = File::Spec->canonpath($cur // $dir);
526         my @dir = stat($dir);
527         my $exists = "I: leistore.dir=$cur already initialized" if @dir;
528         if (@cur) {
529                 if ($cur eq $dir) {
530                         _lei_store($self, 1)->done;
531                         return qerr($self, $exists);
532                 }
533
534                 # some folks like symlinks and bind mounts :P
535                 if (@dir && "$cur[0] $cur[1]" eq "$dir[0] $dir[1]") {
536                         lei_config($self, 'leistore.dir', $dir);
537                         _lei_store($self, 1)->done;
538                         return qerr($self, "$exists (as $cur)");
539                 }
540                 return fail($self, <<"");
541 E: leistore.dir=$cur already initialized and it is not $dir
542
543         }
544         lei_config($self, 'leistore.dir', $dir);
545         _lei_store($self, 1)->done;
546         $exists //= "I: leistore.dir=$dir newly initialized";
547         return qerr($self, $exists);
548 }
549
550 sub lei_daemon_pid { puts shift, $$ }
551
552 sub lei_daemon_kill {
553         my ($self) = @_;
554         my $sig = $self->{opt}->{signal} // 'TERM';
555         kill($sig, $$) or fail($self, "kill($sig, $$): $!");
556 }
557
558 sub lei_help { _help($_[0]) }
559
560 # Shell completion helper.  Used by lei-completion.bash and hopefully
561 # other shells.  Try to do as much here as possible to avoid redundancy
562 # and improve maintainability.
563 sub lei__complete {
564         my ($self, @argv) = @_; # argv = qw(lei and any other args...)
565         shift @argv; # ignore "lei", the entire command is sent
566         @argv or return puts $self, grep(!/^_/, keys %CMD), qw(--help -h);
567         my $cmd = shift @argv;
568         my $info = $CMD{$cmd} // do { # filter matching commands
569                 @argv or puts $self, grep(/\A\Q$cmd\E/, keys %CMD);
570                 return;
571         };
572         my ($proto, undef, @spec) = @$info;
573         my $cur = pop @argv;
574         my $re = defined($cur) ? qr/\A\Q$cur\E/ : qr/./;
575         if (substr($cur // '-', 0, 1) eq '-') { # --switches
576                 # gross special case since the only git-config options
577                 # Consider moving to a table if we need more special cases
578                 # we use Getopt::Long for are the ones we reject, so these
579                 # are the ones we don't reject:
580                 if ($cmd eq 'config') {
581                         puts $self, grep(/$re/, keys %CONFIG_KEYS);
582                         @spec = qw(add z|null get get-all unset unset-all
583                                 replace-all get-urlmatch
584                                 remove-section rename-section
585                                 name-only list|l edit|e
586                                 get-color-name get-colorbool);
587                         # fall-through
588                 }
589                 # TODO: arg support
590                 puts $self, grep(/$re/, map { # generate short/long names
591                         my $eq = '';
592                         if (s/=.+\z//) { # required arg, e.g. output|o=i
593                                 $eq = '=';
594                         } elsif (s/:.+\z//) { # optional arg, e.g. mid:s
595                         } else { # negation: solve! => no-solve|solve
596                                 s/\A(.+)!\z/no-$1|$1/;
597                         }
598                         map {
599                                 length > 1 ? "--$_$eq" : "-$_"
600                         } split(/\|/, $_, -1) # help|h
601                 } grep { $OPTDESC{"$cmd\t$_"} || $OPTDESC{$_} } @spec);
602         } elsif ($cmd eq 'config' && !@argv && !$CONFIG_KEYS{$cur}) {
603                 puts $self, grep(/$re/, keys %CONFIG_KEYS);
604         }
605         # TODO: URLs, pathnames, OIDs, MIDs, etc...  See optparse() for
606         # proto parsing.
607 }
608
609 sub reap_exec { # dwaitpid callback
610         my ($self, $pid) = @_;
611         x_it($self, $?);
612 }
613
614 sub lei_git { # support passing through random git commands
615         my ($self, @argv) = @_;
616         my %rdr = map { $_ => $self->{$_} } (0..2);
617         my $pid = spawn(['git', @argv], $self->{env}, \%rdr);
618         dwaitpid($pid, \&reap_exec, $self);
619 }
620
621 # caller needs to "-t $self->{1}" to check if tty
622 sub start_pager {
623         my ($self) = @_;
624         my $env = $self->{env};
625         my $fh = popen_rd([qw(git var GIT_PAGER)], $env);
626         chomp(my $pager = <$fh> // '');
627         close($fh) or warn "`git var PAGER' error: \$?=$?";
628         return if $pager eq 'cat' || $pager eq '';
629         $env->{LESS} //= 'FRX';
630         $env->{LV} //= '-c';
631         $env->{COLUMNS} //= 80; # TODO TIOCGWINSZ
632         $env->{MORE} //= 'FRX' if $^O eq 'freebsd';
633         pipe(my ($r, $wpager)) or return warn "pipe: $!";
634         my $rdr = { 0 => $r, 1 => $self->{1}, 2 => $self->{2} };
635         $self->{1} = $wpager;
636         $self->{2} = $wpager if -t $self->{2};
637         my $pid = spawn([$pager], $env, $rdr);
638         $env->{GIT_PAGER_IN_USE} = 'true'; # we may spawn git
639         [ $pid, @$rdr{1, 2} ];
640 }
641
642 sub accept_dispatch { # Listener {post_accept} callback
643         my ($sock) = @_; # ignore other
644         $sock->blocking(1);
645         $sock->autoflush(1);
646         my $self = bless { sock => $sock }, __PACKAGE__;
647         vec(my $rin = '', fileno($sock), 1) = 1;
648         # `say $sock' triggers "die" in lei(1)
649         my $buf;
650         if (select(my $rout = $rin, undef, undef, 1)) {
651                 my @fds = $recv_cmd->($sock, $buf, 4096 * 33); # >MAX_ARG_STRLEN
652                 if (scalar(@fds) == 3) {
653                         my $i = 0;
654                         for my $rdr (qw(<&= >&= >&=)) {
655                                 my $fd = shift(@fds);
656                                 if (open(my $fh, $rdr, $fd)) {
657                                         $self->{$i++} = $fh;
658                                 }  else {
659                                         say $sock "open($rdr$fd) (FD=$i): $!";
660                                         return;
661                                 }
662                         }
663                 } else {
664                         say $sock "recv_cmd failed: $!";
665                         return;
666                 }
667         } else {
668                 say $sock "timed out waiting to recv FDs";
669                 return;
670         }
671         $self->{2}->autoflush(1); # keep stdout buffered until x_it|DESTROY
672         # $ENV_STR = join('', map { "\0$_=$ENV{$_}" } keys %ENV);
673         # $buf = "$$\0$argc\0".join("\0", @ARGV).$ENV_STR."\0\0";
674         if (substr($buf, -2, 2, '') ne "\0\0") { # s/\0\0\z//
675                 say $sock "request command truncated";
676                 return;
677         }
678         my ($client_pid, $argc, @argv) = split(/\0/, $buf, -1);
679         undef $buf;
680         my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
681         if (chdir($env{PWD})) {
682                 local %ENV = %env;
683                 $self->{env} = \%env;
684                 $self->{pid} = $client_pid + 0;
685                 eval { dispatch($self, @argv) };
686                 say $sock $@ if $@;
687         } else {
688                 say $sock "chdir($env{PWD}): $!"; # implicit close
689         }
690 }
691
692 # for long-running results
693 sub event_step {
694         my ($self) = @_;
695         local %ENV = %{$self->{env}};
696         eval {}; # TODO
697         if ($@) {
698                 say { $self->{sock} } $@;
699                 $self->close; # PublicInbox::DS::close
700         }
701 }
702
703 sub noop {}
704
705 our $oldset; sub oldset { $oldset }
706
707 # lei(1) calls this when it can't connect
708 sub lazy_start {
709         my ($path, $errno, $nfd) = @_;
710         if ($errno == ECONNREFUSED) {
711                 unlink($path) or die "unlink($path): $!";
712         } elsif ($errno != ENOENT) {
713                 $! = $errno; # allow interpolation to stringify in die
714                 die "connect($path): $!";
715         }
716         umask(077) // die("umask(077): $!");
717         socket(my $l, AF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
718         bind($l, pack_sockaddr_un($path)) or die "bind($path): $!";
719         listen($l, 1024) or die "listen: $!";
720         my @st = stat($path) or die "stat($path): $!";
721         my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
722         pipe(my ($eof_r, $eof_w)) or die "pipe: $!";
723         local $oldset = PublicInbox::DS::block_signals();
724         if ($nfd == 1) {
725                 require PublicInbox::CmdIPC1;
726                 $recv_cmd = PublicInbox::CmdIPC1->can('recv_cmd1');
727         } elsif ($nfd == 4) {
728                 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4') // do {
729                         require PublicInbox::CmdIPC4;
730                         PublicInbox::CmdIPC4->can('recv_cmd4');
731                 };
732         }
733         $recv_cmd or die <<"";
734 (Socket::MsgHdr || IO::FDPass || Inline::C) missing/unconfigured (nfd=$nfd);
735
736         require PublicInbox::Listener;
737         require PublicInbox::EOFpipe;
738         (-p STDOUT) or die "E: stdout must be a pipe\n";
739         open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!";
740         POSIX::setsid() > 0 or die "setsid: $!";
741         my $pid = fork // die "fork: $!";
742         return if $pid;
743         $0 = "lei-daemon $path";
744         local %PATH2CFG;
745         $_->blocking(0) for ($l, $eof_r, $eof_w);
746         $l = PublicInbox::Listener->new($l, \&accept_dispatch, $l);
747         my $exit_code;
748         local $quit = sub {
749                 $exit_code //= shift;
750                 my $listener = $l or exit($exit_code);
751                 unlink($path) if defined($path);
752                 # closing eof_w triggers \&noop wakeup
753                 $eof_w = $l = $path = undef;
754                 $listener->close; # DS::close
755                 PublicInbox::DS->SetLoopTimeout(1000);
756         };
757         PublicInbox::EOFpipe->new($eof_r, \&noop, undef);
758         my $sig = {
759                 CHLD => \&PublicInbox::DS::enqueue_reap,
760                 QUIT => $quit,
761                 INT => $quit,
762                 TERM => $quit,
763                 HUP => \&noop,
764                 USR1 => \&noop,
765                 USR2 => \&noop,
766         };
767         my $sigfd = PublicInbox::Sigfd->new($sig, SFD_NONBLOCK);
768         local %SIG = (%SIG, %$sig) if !$sigfd;
769         local $SIG{PIPE} = 'IGNORE';
770         if ($sigfd) { # TODO: use inotify/kqueue to detect unlinked sockets
771                 PublicInbox::DS->SetLoopTimeout(5000);
772         } else {
773                 # wake up every second to accept signals if we don't
774                 # have signalfd or IO::KQueue:
775                 PublicInbox::DS::sig_setmask($oldset);
776                 PublicInbox::DS->SetLoopTimeout(1000);
777         }
778         PublicInbox::DS->SetPostLoopCallback(sub {
779                 my ($dmap, undef) = @_;
780                 if (@st = defined($path) ? stat($path) : ()) {
781                         if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
782                                 warn "$path dev/ino changed, quitting\n";
783                                 $path = undef;
784                         }
785                 } elsif (defined($path)) {
786                         warn "stat($path): $!, quitting ...\n";
787                         undef $path; # don't unlink
788                         $quit->();
789                 }
790                 return 1 if defined($path);
791                 my $now = now();
792                 my $n = 0;
793                 for my $s (values %$dmap) {
794                         $s->can('busy') or next;
795                         if ($s->busy($now)) {
796                                 ++$n;
797                         } else {
798                                 $s->close;
799                         }
800                 }
801                 $n; # true: continue, false: stop
802         });
803
804         # STDIN was redirected to /dev/null above, closing STDERR and
805         # STDOUT will cause the calling `lei' client process to finish
806         # reading the <$daemon> pipe.
807         openlog($path, 'pid', 'user');
808         local $SIG{__WARN__} = sub { syslog('warning', "@_") };
809         my $on_destroy = PublicInbox::OnDestroy->new($$, sub {
810                 syslog('crit', "$@") if $@;
811         });
812         open STDERR, '>&STDIN' or die "redirect stderr failed: $!";
813         open STDOUT, '>&STDIN' or die "redirect stdout failed: $!";
814         # $daemon pipe to `lei' closed, main loop begins:
815         PublicInbox::DS->EventLoop;
816         @$on_destroy = (); # cancel on_destroy if we get here
817         exit($exit_code // 0);
818 }
819
820 # for users w/o IO::FDPass
821 sub oneshot {
822         my ($main_pkg) = @_;
823         my $exit = $main_pkg->can('exit'); # caller may override exit()
824         local $quit = $exit if $exit;
825         local %PATH2CFG;
826         umask(077) // die("umask(077): $!");
827         dispatch((bless {
828                 0 => *STDIN{GLOB},
829                 1 => *STDOUT{GLOB},
830                 2 => *STDERR{GLOB},
831                 env => \%ENV
832         }, __PACKAGE__), @ARGV);
833 }
834
835 # ensures stdout hits the FS before sock disconnects so a client
836 # can immediately reread it
837 sub DESTROY {
838         my ($self) = @_;
839         $self->{1}->autoflush(1);
840 }
841
842 1;