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