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