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>
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;
11 use parent qw(PublicInbox::DS PublicInbox::LeiExternal
12 PublicInbox::LeiQuery);
14 use Socket qw(AF_UNIX SOCK_SEQPACKET MSG_EOR pack_sockaddr_un);
15 use Errno qw(EPIPE EAGAIN EINTR ECONNREFUSED ENOENT ECONNRESET);
17 use POSIX qw(strftime);
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 Text::Wrap qw(wrap);
27 use Time::HiRes qw(stat); # ctime comparisons for config cache
28 use File::Path qw(mkpath);
30 our $quit = \&CORE::exit;
31 our ($current_lei, $errors_log, $listener);
32 my ($recv_cmd, $send_cmd);
33 my $GLP = Getopt::Long::Parser->new;
34 $GLP->configure(qw(gnu_getopt no_ignore_case auto_abbrev));
35 my $GLP_PASS = Getopt::Long::Parser->new;
36 $GLP_PASS->configure(qw(gnu_getopt no_ignore_case auto_abbrev pass_through));
38 our %PATH2CFG; # persistent for socket daemon
40 # TBD: this is a documentation mechanism to show a subcommand
41 # (may) pass options through to another command:
42 sub pass_through { $GLP_PASS }
46 my ($spec, $re_str) = @_; # 'limit|n=i', '([0-9]+)'
47 my ($key) = ($spec =~ m/\A([a-z]+)/g);
48 my $cb = sub { # Getopt::Long "<>" catch-all handler
50 if ($arg =~ /\A-($re_str)\z/) {
52 } elsif ($arg eq '--') { # "--" arg separator, ignore first
53 push @{$OPT->{-argv}}, $arg if $OPT->{'--'}++;
54 # lone (single) dash is handled elsewhere
55 } elsif (substr($arg, 0, 1) eq '-') {
57 push @{$OPT->{-argv}}, $arg;
59 die "bad argument: $arg\n";
62 push @{$OPT->{-argv}}, $arg;
65 ($spec, '<>' => $cb, $GLP_PASS) # for Getopt::Long
70 return $p if index($p, '/') == 0; # already absolute
71 my $pwd = $self->{env}->{PWD};
73 my $cwd = $self->{3} // getcwd() // die "getcwd(PWD=$pwd): $!";
74 if (my @st_pwd = stat($pwd)) {
75 my @st_cwd = stat($cwd) or die "stat($cwd): $!";
76 "@st_pwd[1,0]" eq "@st_cwd[1,0]" or
77 $self->{env}->{PWD} = $pwd = $cwd;
78 } else { # PWD was invalid
79 delete $self->{env}->{PWD};
83 $pwd //= $self->{env}->{PWD} = getcwd() // die "getcwd(PWD=$pwd): $!";
84 File::Spec->rel2abs($p, $pwd);
89 rel2abs($self, ($self->{env}->{XDG_DATA_HOME} //
90 ($self->{env}->{HOME} // '/nonexistent').'/.local/share')
94 sub _config_path ($) {
96 rel2abs($self, ($self->{env}->{XDG_CONFIG_HOME} //
97 ($self->{env}->{HOME} // '/nonexistent').'/.config')
102 # TODO: drop underscore variants everywhere, they're undocumented
103 qw(fsync|sync! jobs|j=i indexlevel|index-level|L=s compact+
104 max_size|max-size=s sequential_shard|sequential-shard
105 batch_size|batch-size=s skip-docdata quiet|q verbose|v+)
108 # TODO: generate shell completion + help using %CMD and %OPTDESC
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 thread|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-cmd|mua=s no-torsocks torsocks=s verbose|v+ quiet|q
116 received-after=s received-before=s sent-after=s sent-since=s),
117 PublicInbox::LeiQuery::curl_opt(), opt_dash('limit|n=i', '[0-9]+') ],
119 'show' => [ 'MID|OID', 'show a given object (Message-ID or object ID)',
120 qw(type=s solve! format|f=s dedupe|d=s thread|t remote local!),
121 pass_through('git show') ],
123 'add-external' => [ 'URL_OR_PATHNAME',
124 'add/set priority of a publicinbox|extindex for extra matches',
125 qw(boost=i c=s@ mirror=s no-torsocks torsocks=s inbox-version=i),
126 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' => [ 'URL_OR_PATHNAME...|--prune',
130 'exclude further results from a publicinbox|extindex',
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' ],
138 'plonk' => [ '--thread|--from=IDENT',
139 'exclude mail matching From: or thread from non-Message-ID searches',
140 qw(stdin| thread|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) ],
148 'purge-mailsource' => [ 'URL_OR_PATHNAME|--all',
149 'remove imported messages from IMAP, Maildirs, and MH',
150 qw(exact! all jobs:i indexed) ],
152 # code repos are used for `show' to solve blobs from patch mails
153 'add-coderepo' => [ 'PATHNAME', 'add or set priority of a git code repo',
155 'ls-coderepo' => [ '[FILTER_TERMS...]',
156 'list known code repos', qw(format|f=s z) ],
157 'forget-coderepo' => [ 'PATHNAME',
158 'stop using repo to solve blobs from patches',
161 'add-watch' => [ '[URL_OR_PATHNAME]',
162 'watch for new messages and flag changes',
163 qw(import! kw|keywords|flags! interval=s recursive|r
164 exclude=s include=s) ],
165 'ls-watch' => [ '[FILTER...]', 'list active watches with numbers and status',
167 'pause-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote) ],
168 'resume-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote) ],
169 'forget-watch' => [ '{WATCH_NUMBER|--prune}', 'stop and forget a watch',
172 'import' => [ 'URLS_OR_PATHNAMES...|--stdin',
173 'one-time import/update from URL or filesystem',
174 qw(stdin| offset=i recursive|r exclude=s include|I=s
175 format|f=s kw|keywords|flags!),
178 'config' => [ '[...]', sub {
179 'git-config(1) wrapper for '._config_path($_[0]);
180 }, qw(config-file|system|global|file|f=s), # for conflict detection
181 pass_through('git config') ],
182 'init' => [ '[PATHNAME]', sub {
183 'initialize storage, default: '._store_path($_[0]);
185 'daemon-kill' => [ '[-SIGNAL]', 'signal the lei-daemon',
186 opt_dash('signal|s=s', '[0-9]+|(?:[A-Z][A-Z0-9]+)') ],
187 'daemon-pid' => [ '', 'show the PID of the lei-daemon' ],
188 'help' => [ '[SUBCOMMAND]', 'show help' ],
190 # XXX do we need this?
191 # 'git' => [ '[ANYTHING...]', 'git(1) wrapper', pass_through('git') ],
193 'reorder-local-store-and-break-history' => [ '[REFNAME]',
194 'rewrite git history in an attempt to improve compression',
197 # internal commands are prefixed with '_'
198 '_complete' => [ '[...]', 'internal shell completion helper',
199 pass_through('everything') ],
202 # switch descriptions, try to keep consistent across commands
203 # $spec: Getopt::Long option specification
204 # $spec => [@ALLOWED_VALUES (default is first), $description],
205 # $spec => $description
206 # "$SUB_COMMAND TAB $spec" => as above
207 my $stdin_formats = [ 'MAIL_FORMAT|eml|mboxrd|mboxcl2|mboxcl|mboxo',
208 'specify message input format' ];
209 my $ls_format = [ 'OUT|plain|json|null', 'listing output format' ];
212 'help|h' => 'show this built-in help',
213 'quiet|q' => 'be quiet',
214 'globoff|g' => "do not match locations using '*?' wildcards and '[]' ranges",
215 'verbose|v+' => 'be more verbose',
216 'solve!' => 'do not attempt to reconstruct blobs from emails',
217 'torsocks=s' => ['auto|no|yes',
218 'whether or not to wrap git and curl commands with torsocks'],
219 'no-torsocks' => 'alias for --torsocks=no',
220 'save-as=s' => ['NAME', 'save a search terms by given name'],
222 'type=s' => [ 'any|mid|git', 'disambiguate type' ],
224 'dedupe|d=s' => ['STRAT|content|oid|mid|none',
225 'deduplication strategy'],
226 'show thread|t' => 'display entire thread a message belongs to',
228 'return all messages in the same thread as the actual match(es)',
229 'augment|a' => 'augment --output destination instead of clobbering',
231 'output|mfolder|o=s' => [ 'DEST',
232 "destination (e.g. `/path/to/Maildir', or `-' for stdout)" ],
233 'mua-cmd|mua=s' => [ 'COMMAND',
234 "MUA to run on --output Maildir or mbox (e.g. `mutt -f %f'" ],
236 'show format|f=s' => [ 'OUT|plain|raw|html|mboxrd|mboxcl2|mboxcl',
237 'message/object output format' ],
238 'mark format|f=s' => $stdin_formats,
239 'forget format|f=s' => $stdin_formats,
241 'OUT|maildir|mboxrd|mboxcl2|mboxcl|mboxo|html|json|jsonl|concatjson',
242 'specify output format, default depends on --output'],
243 'q exclude=s@' => [ 'URL_OR_PATHNAME',
244 'exclude specified external(s) from search' ],
245 'q include|I=s@' => [ 'URL_OR_PATHNAME',
246 'include specified external(s) in search' ],
247 'q only=s@' => [ 'URL_OR_PATHNAME',
248 'only use specified external(s) for search' ],
250 'q jobs=s' => [ '[SEARCH_JOBS][,WRITER_JOBS]',
251 'control number of search and writer jobs' ],
253 'import format|f=s' => $stdin_formats,
255 'ls-query format|f=s' => $ls_format,
256 'ls-external format|f=s' => $ls_format,
258 'limit|n=i@' => ['NUM', 'limit on number of matches (default: 10000)' ],
259 'offset=i' => ['OFF', 'search result offset (default: 0)'],
261 'sort|s=s' => [ 'VAL|received,relevance,docid',
262 "order of results `--output'-dependent"],
263 'reverse|r' => [ 'reverse search results' ], # like sort(1)
265 'boost=i' => 'increase/decrease priority of results (default: 0)',
267 'local' => 'limit operations to the local filesystem',
268 'local!' => 'exclude results from the local filesystem',
269 'remote' => 'limit operations to those requiring network access',
270 'remote!' => 'prevent operations requiring network access',
272 'mid=s' => 'specify the Message-ID of a message',
273 'oid=s' => 'specify the git object ID of a message',
275 'recursive|r' => 'scan directories/mailboxes/newsgroups recursively',
276 'exclude=s' => 'exclude mailboxes/newsgroups based on pattern',
277 'include=s' => 'include mailboxes/newsgroups based on pattern',
279 'exact' => 'operate on exact header matches only',
280 'exact!' => 'rely on content match instead of exact header matches',
282 'by-mid|mid:s' => [ 'MID', 'match only by Message-ID, ignoring contents' ],
283 'jobs:i' => 'set parallelism level',
285 'kw|keywords|flags!' => 'disable/enable importing flags',
287 # xargs, env, use "-0", git(1) uses "-z". We support z|0 everywhere
288 'z|0' => 'use NUL \\0 instead of newline (CR) to delimit lines',
290 'signal|s=s' => [ 'SIG', 'signal to send lei-daemon (default: TERM)' ],
294 'leistore.dir' => 'top-level storage location',
297 my @WQ_KEYS = qw(lxs l2m imp mrr); # internal workers
299 # pronounced "exit": x_it(1 << 8) => exit(1); x_it(13) => SIGPIPE
301 my ($self, $code) = @_;
302 # make sure client sees stdout before exit
303 $self->{1}->autoflush(1) if $self->{1};
304 dump_and_clear_log();
305 if (my $s = $self->{pkt_op_p} // $self->{sock}) {
306 send($s, "x_it $code", MSG_EOR);
307 } elsif ($self->{oneshot}) {
308 # don't want to end up using $? from child processes
309 for my $f (@WQ_KEYS) {
310 my $wq = delete $self->{$f} or next;
313 # cleanup anything that has tempfiles
314 delete @$self{qw(ovv dedupe)};
315 if (my $signum = ($code & 127)) { # usually SIGPIPE (13)
316 $SIG{PIPE} = 'DEFAULT'; # $SIG{$signum} doesn't work
318 sleep(1) while 1; # wait for signal
322 } # else ignore if client disconnected
327 my $err = $self->{2} // ($self->{pgr} // [])->[2] // *STDERR{GLOB};
328 my @eor = (substr($_[-1]//'', -1, 1) eq "\n" ? () : ("\n"));
329 print $err @_, @eor and return;
330 my $old_err = delete $self->{2};
331 close($old_err) if $! == EPIPE && $old_err;
332 $err = $self->{2} = ($self->{pgr} // [])->[2] // *STDERR{GLOB};
333 print $err @_, @eor or print STDERR @_, @eor;
336 sub qerr ($;@) { $_[0]->{opt}->{quiet} or err(shift, @_) }
338 sub fail_handler ($;$$) {
339 my ($lei, $code, $io) = @_;
340 for my $f (@WQ_KEYS) {
341 my $wq = delete $lei->{$f} or next;
342 $wq->wq_wait_old($lei) if $wq->wq_kill_old; # lei-daemon
344 close($io) if $io; # needed to avoid warnings on SIGPIPE
345 $lei->x_it($code // (1 >> 8));
348 sub sigpipe_handler { # handles SIGPIPE from @WQ_KEYS workers
349 fail_handler($_[0], 13, delete $_[0]->{1});
353 my ($self, $buf, $exit_code) = @_;
354 err($self, $buf) if defined $buf;
355 # calls fail_handler:
356 send($self->{pkt_op_p}, '!', MSG_EOR) if $self->{pkt_op_p};
357 x_it($self, ($exit_code // 1) << 8);
363 return if print { $self->{1} // return } @_; # likely
364 return note_sigpipe($self, 1) if $! == EPIPE;
365 my $err = "error writing to stdout: $!";
370 sub puts ($;@) { out(shift, map { "$_\n" } @_) }
372 sub child_error { # passes non-fatal curl exit codes to user
373 my ($self, $child_error, $msg) = @_; # child_error is $?
374 $self->err($msg) if $msg;
375 if (my $s = $self->{pkt_op_p} // $self->{sock}) {
376 # send to the parent lei-daemon or to lei(1) client
377 send($s, "child_error $child_error", MSG_EOR);
378 } elsif (!$PublicInbox::DS::in_loop) {
379 $self->{child_error} = $child_error;
380 } # else noop if client disconnected
383 sub note_sigpipe { # triggers sigpipe_handler
384 my ($self, $fd) = @_;
385 close(delete($self->{$fd})); # explicit close silences Perl warning
386 send($self->{pkt_op_p}, '|', MSG_EOR) if $self->{pkt_op_p};
390 sub lei_atfork_child {
391 my ($self, $persist) = @_;
392 # we need to explicitly close things which are on stack
394 my @io = delete @$self{0,1,2};
395 unless ($self->{oneshot}) {
401 for (delete @$self{qw(3 sock old_1 au_done)}) {
402 close($_) if defined($_);
404 if (my $op_c = delete $self->{pkt_op_c}) {
405 close(delete $op_c->{sock});
407 if (my $pgr = delete $self->{pgr}) {
408 close($_) for (@$pgr[1,2]);
410 close $listener if $listener;
414 $quit = \&CORE::exit;
415 $current_lei = $persist ? undef : $self; # for SIG{__WARN__}
419 my ($self, $errmsg) = @_;
420 my $cmd = $self->{cmd} // 'COMMAND';
421 my @info = @{$CMD{$cmd} // [ '...', '...' ]};
422 my @top = ($cmd, shift(@info) // ());
423 my $cmd_desc = shift(@info);
424 $cmd_desc = $cmd_desc->($self) if ref($cmd_desc) eq 'CODE';
427 for my $sw (grep { !ref } @info) { # ("prio=s", "z", $GLP_PASS)
428 my $desc = $OPTDESC{"$cmd\t$sw"} // $OPTDESC{$sw} // next;
430 ($arg_vals, $desc) = @$desc if ref($desc) eq 'ARRAY';
432 # lower-case is a keyword (e.g. `content', `oid'),
433 # ALL_CAPS is a string description (e.g. `PATH')
434 if ($desc !~ /default/ && $arg_vals =~ /\b([a-z]+)[,\|]/) {
435 $desc .= "\ndefault: `$1'";
439 if ($x =~ s/!\z//) { # solve! => --no-solve
440 $x =~ s/(\A|\|)/$1no-/g
441 } elsif ($x =~ s/:.+//) { # optional args: $x = "mid:s"
442 @vals = (' [', undef, ']');
443 } elsif ($x =~ s/=.+//) { # required arg: $x = "type=s"
444 @vals = (' ', undef);
445 } # else: no args $x = 'thread|t'
446 for (split(/\|/, $x)) { # help|h
447 length($_) > 1 ? push(@l, "--$_") : push(@s, "-$_");
449 if (!scalar(@vals)) { # no args 'thread|t'
450 } elsif ($arg_vals =~ s/\A([A-Z_]+)\b//) { # "NAME"
453 $vals[1] = uc(substr($l[0], 2)); # "--type" => "TYPE"
455 if ($arg_vals =~ /([,\|])/) {
457 my @allow = split(/\Q$sep\E/, $arg_vals);
458 my $must = $sep eq '|' ? 'Must' : 'Can';
459 @allow = map { "`$_'" } @allow;
460 my $last = pop @allow;
461 $desc .= "\n$must be one of: " .
462 join(', ', @allow) . " or $last";
464 my $lhs = join(', ', @s, @l) . join('', @vals);
465 if ($x =~ /\|\z/) { # "stdin|" or "clear|"
466 $lhs =~ s/\A--/- , --/;
468 $lhs =~ s/\A--/ --/; # pad if no short options
470 $lpad = length($lhs) if length($lhs) > $lpad;
471 push @opt_desc, $lhs, $desc;
473 my $msg = $errmsg ? "E: $errmsg\n" : '';
480 local $Text::Wrap::columns = 78 - $lpad;
481 my $padding = ' ' x ($lpad + 2);
482 while (my ($lhs, $rhs) = splice(@opt_desc, 0, 2)) {
483 $msg .= ' '.pack("A$lpad", $lhs);
484 $rhs = wrap('', '', $rhs);
485 $rhs =~ s/\n/\n$padding/sg; # LHS pad continuation lines
489 my $out = $self->{$errmsg ? 2 : 1};
490 start_pager($self) if -t $out;
492 x_it($self, $errmsg ? 1 << 8 : 0); # stderr => failure
497 my ($self, $cmd, $argv) = @_;
499 $OPT = $self->{opt} = {};
500 my $info = $CMD{$cmd} // [ '[...]' ];
501 my ($proto, undef, @spec) = @$info;
502 my $glp = ref($spec[-1]) eq ref($GLP) ? pop(@spec) : $GLP;
503 push @spec, qw(help|h);
505 if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
506 $lone_dash = $spec[0];
507 $OPT->{$spec[0]} = \(my $var);
508 push @spec, '' => \$var;
510 $glp->getoptionsfromarray($argv, $OPT, @spec) or
511 return _help($self, "bad arguments or options for $cmd");
512 return _help($self) if $OPT->{help};
514 push @$argv, @{$OPT->{-argv}} if defined($OPT->{-argv});
516 # "-" aliases "stdin" or "clear"
517 $OPT->{$lone_dash} = ${$OPT->{$lone_dash}} if defined $lone_dash;
520 my $POS_ARG = '[A-Z][A-Z0-9_]+';
522 my @args = split(/ /, $proto);
523 for my $var (@args) {
524 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
525 $inf = defined($argv->[$i]) and last;
526 $var =~ s/\.\.\.\z//;
527 $err = "$var not supplied";
528 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
529 $argv->[$i++] // ($err = "$var not supplied");
530 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
533 } elsif ($var =~ /\A\[-?$POS_ARG\]\z/) { # one optional arg
535 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
536 $inf = 1 if index($var, '...') > 0;
537 my @or = split(/\|/, $var);
540 if ($o =~ /\A--([a-z0-9\-]+)/) {
541 $ok = defined($OPT->{$1});
543 } elsif (defined($argv->[$i])) {
547 } # else continue looping
551 $err = join(', ', @or) . " or $last must be set";
553 warn "BUG: can't parse `$var' in $proto";
557 if (!$inf && scalar(@$argv) > scalar(@args)) {
558 $err //= 'too many arguments';
560 $err ? fail($self, "usage: lei $cmd $proto\nE: $err") : 1;
564 my ($self, $cmd, @argv) = @_;
565 local $current_lei = $self; # for __WARN__
566 dump_and_clear_log("from previous run\n");
567 return _help($self, 'no command given') unless defined($cmd);
568 my $func = "lei_$cmd";
570 if (my $cb = __PACKAGE__->can($func)) {
571 optparse($self, $cmd, \@argv) or return;
573 } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
575 $GLP->getoptionsfromarray([$cmd, @argv], $opt, qw(help|h)) or
576 return _help($self, 'bad arguments or options');
579 fail($self, "`$cmd' is not an lei command");
584 my ($self, $creat) = @_;
585 my $f = _config_path($self);
587 my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
588 if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
589 return ($self->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
596 my (undef, $cfg_dir, undef) = File::Spec->splitpath($f);
597 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
598 open my $fh, '>>', $f or die "open($f): $!\n";
599 @st = stat($fh) or die "fstat($f): $!\n";
600 $cur_st = pack('dd', $st[10], $st[7]);
601 qerr($self, "I: $f created") if $self->{cmd} ne 'config';
603 my $cfg = PublicInbox::Config::git_config_dump($f);
604 $cfg->{-st} = $cur_st;
606 $self->{cfg} = $PATH2CFG{$f} = $cfg;
609 sub _lei_store ($;$) {
610 my ($self, $creat) = @_;
611 my $cfg = _lei_cfg($self, $creat);
612 $cfg->{-lei_store} //= do {
613 require PublicInbox::LeiStore;
614 my $dir = $cfg->{'leistore.dir'};
615 $dir //= $creat ? _store_path($self) : return;
616 PublicInbox::LeiStore->new($dir, { creat => $creat });
621 my ($self, @argv) = @_;
625 my ($self, @argv) = @_;
629 my ($self, @argv) = @_;
630 my $env = $self->{env};
631 delete local $env->{GIT_CONFIG};
632 delete local $ENV{GIT_CONFIG};
633 my $cfg = _lei_cfg($self, 1);
634 my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
635 my %rdr = map { $_ => $self->{$_} } (0..2);
636 waitpid(spawn($cmd, $env, \%rdr), 0);
640 my ($self, @argv) = @_;
641 $self->{opt}->{'config-file'} and return fail $self,
642 "config file switches not supported by `lei config'";
644 x_it($self, $?) if $?;
648 require PublicInbox::LeiImport;
649 PublicInbox::LeiImport->call(@_);
653 my ($self, $dir) = @_;
654 my $cfg = _lei_cfg($self, 1);
655 my $cur = $cfg->{'leistore.dir'};
656 $dir //= _store_path($self);
657 $dir = rel2abs($self, $dir);
658 my @cur = stat($cur) if defined($cur);
659 $cur = File::Spec->canonpath($cur // $dir);
660 my @dir = stat($dir);
661 my $exists = "I: leistore.dir=$cur already initialized" if @dir;
664 _lei_store($self, 1)->done;
665 return qerr($self, $exists);
668 # some folks like symlinks and bind mounts :P
669 if (@dir && "@cur[1,0]" eq "@dir[1,0]") {
670 lei_config($self, 'leistore.dir', $dir);
671 _lei_store($self, 1)->done;
672 return qerr($self, "$exists (as $cur)");
674 return fail($self, <<"");
675 E: leistore.dir=$cur already initialized and it is not $dir
678 lei_config($self, 'leistore.dir', $dir);
679 _lei_store($self, 1)->done;
680 $exists //= "I: leistore.dir=$dir newly initialized";
681 return qerr($self, $exists);
684 sub lei_daemon_pid { puts shift, $$ }
686 sub lei_daemon_kill {
688 my $sig = $self->{opt}->{signal} // 'TERM';
689 kill($sig, $$) or fail($self, "kill($sig, $$): $!");
692 sub lei_help { _help($_[0]) }
694 # Shell completion helper. Used by lei-completion.bash and hopefully
695 # other shells. Try to do as much here as possible to avoid redundancy
696 # and improve maintainability.
698 my ($self, @argv) = @_; # argv = qw(lei and any other args...)
699 shift @argv; # ignore "lei", the entire command is sent
700 @argv or return puts $self, grep(!/^_/, keys %CMD), qw(--help -h);
701 my $cmd = shift @argv;
702 my $info = $CMD{$cmd} // do { # filter matching commands
703 @argv or puts $self, grep(/\A\Q$cmd\E/, keys %CMD);
706 my ($proto, undef, @spec) = @$info;
708 my $re = defined($cur) ? qr/\A\Q$cur\E/ : qr/./;
709 if (substr($cur // '-', 0, 1) eq '-') { # --switches
710 # gross special case since the only git-config options
711 # Consider moving to a table if we need more special cases
712 # we use Getopt::Long for are the ones we reject, so these
713 # are the ones we don't reject:
714 if ($cmd eq 'config') {
715 puts $self, grep(/$re/, keys %CONFIG_KEYS);
716 @spec = qw(add z|null get get-all unset unset-all
717 replace-all get-urlmatch
718 remove-section rename-section
719 name-only list|l edit|e
720 get-color-name get-colorbool);
723 puts $self, grep(/$re/, map { # generate short/long names
724 if (s/[:=].+\z//) { # req/optional args, e.g output|o=i
725 } elsif (s/\+\z//) { # verbose|v+
727 # negation: solve! => no-solve|solve
728 s/([\w\-]+)/$1|no-$1/g
731 my $x = length > 1 ? "--$_" : "-$_";
732 $x eq $cur ? () : $x;
733 } split(/\|/, $_, -1) # help|h
734 } grep { $OPTDESC{"$cmd\t$_"} || $OPTDESC{$_} } @spec);
735 } elsif ($cmd eq 'config' && !@argv && !$CONFIG_KEYS{$cur}) {
736 puts $self, grep(/$re/, keys %CONFIG_KEYS);
739 # switch args (e.g. lei q -f mbox<TAB>)
740 if (($argv[-1] // $cur // '') =~ /\A--?([\w\-]+)\z/) {
741 my $opt = quotemeta $1;
743 my $v = $OPTDESC{$_};
744 my @v = ref($v) ? split(/\|/, $v->[0]) : ();
745 # get rid of ALL CAPS placeholder (e.g "OUT")
746 # (TODO: completion for external paths)
747 shift(@v) if uc($v[0]) eq $v[0];
749 } grep(/\A(?:$cmd\t|)(?:[\w-]+\|)*$opt\b/, keys %OPTDESC);
752 if (my $sub = $self->can("_complete_$cmd")) {
753 puts $self, $sub->($self, @argv, $cur);
755 # TODO: URLs, pathnames, OIDs, MIDs, etc... See optparse() for
760 my ($argv, $env) = @_;
761 my $argc = scalar @$argv;
762 my $buf = 'exec '.join("\0", scalar(@$argv), @$argv);
763 while (my ($k, $v) = each %$env) { $buf .= "\0$k=$v" };
769 my $mua = $self->{opt}->{'mua-cmd'} // return;
770 my $mfolder = $self->{ovv}->{dst};
771 my (@cmd, $replaced);
772 if ($mua =~ /\A(?:mutt|mailx|mail|neomutt)\z/) {
774 # TODO: help wanted: other common FOSS MUAs
776 require Text::ParseWords;
777 my @cmd = Text::ParseWords::shellwords($mua);
778 # mutt uses '%f' for open-hook with compressed mbox, we follow
779 @cmd = map { $_ eq '%f' ? ($replaced = $mfolder) : $_ } @cmd;
781 push @cmd, $mfolder unless defined($replaced);
782 if (my $sock = $self->{sock}) { # lei(1) client process runs it
783 send($sock, exec_buf(\@cmd, {}), MSG_EOR);
784 } elsif ($self->{oneshot}) {
785 $self->{"mua.pid.$self.$$"} = spawn(\@cmd);
787 delete $self->{-progress};
790 # caller needs to "-t $self->{1}" to check if tty
793 my $env = $self->{env};
794 my $fh = popen_rd([qw(git var GIT_PAGER)], $env);
795 chomp(my $pager = <$fh> // '');
796 close($fh) or warn "`git var PAGER' error: \$?=$?";
797 return if $pager eq 'cat' || $pager eq '';
799 my $new_env = { LESS => 'FRX', LV => '-c', COLUMNS => 80 };
800 $new_env->{MORE} = 'FRX' if $^O eq 'freebsd';
801 pipe(my ($r, $wpager)) or return warn "pipe: $!";
802 my $rdr = { 0 => $r, 1 => $self->{1}, 2 => $self->{2} };
803 my $pgr = [ undef, @$rdr{1, 2} ];
804 if (my $sock = $self->{sock}) { # lei(1) process runs it
805 delete @$new_env{keys %$env}; # only set iff unset
806 my $fds = [ map { fileno($_) } @$rdr{0..2} ];
807 $send_cmd->($sock, $fds, exec_buf([$pager], $new_env), MSG_EOR);
808 } elsif ($self->{oneshot}) {
809 $pgr->[0] = spawn([$pager], $new_env, $rdr);
810 $pgr->[3] = $$; # ew'll reap it
812 die 'BUG: start_pager w/o socket';
814 $self->{1} = $wpager;
815 $self->{2} = $wpager if -t $self->{2};
816 $env->{GIT_PAGER_IN_USE} = 'true'; # we may spawn git
822 my $pgr = delete($self->{pgr}) or return;
823 $self->{2} = $pgr->[2];
824 # do not restore original stdout, just close it so we error out
825 close(delete($self->{1})) if $self->{1};
827 dwaitpid($pid) if $pid && ($pgr->[3] // 0) == $$;
830 sub accept_dispatch { # Listener {post_accept} callback
831 my ($sock) = @_; # ignore other
833 my $self = bless { sock => $sock }, __PACKAGE__;
834 vec(my $rvec = '', fileno($sock), 1) = 1;
835 select($rvec, undef, undef, 60) or
836 return send($sock, 'timed out waiting to recv FDs', MSG_EOR);
837 my @fds = $recv_cmd->($sock, my $buf, 4096 * 33); # >MAX_ARG_STRLEN
838 if (scalar(@fds) == 4) {
840 my $fd = shift(@fds);
841 open($self->{$i}, '+<&=', $fd) and next;
842 send($sock, "open(+<&=$fd) (FD=$i): $!", MSG_EOR);
845 my $msg = "recv_cmd failed: $!";
847 return send($sock, $msg, MSG_EOR);
849 $self->{2}->autoflush(1); # keep stdout buffered until x_it|DESTROY
850 # $ENV_STR = join('', map { "\0$_=$ENV{$_}" } keys %ENV);
851 # $buf = "$argc\0".join("\0", @ARGV).$ENV_STR."\0\0";
852 substr($buf, -2, 2, '') eq "\0\0" or # s/\0\0\z//
853 return send($sock, 'request command truncated', MSG_EOR);
854 my ($argc, @argv) = split(/\0/, $buf, -1);
856 my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
857 if (chdir($self->{3})) {
859 $self->{env} = \%env;
860 eval { dispatch($self, @argv) };
861 send($sock, $@, MSG_EOR) if $@;
863 send($sock, "fchdir: $!", MSG_EOR); # implicit close
869 delete $self->{-progress};
870 for my $f (@WQ_KEYS) {
871 my $wq = delete $self->{$f} or next;
874 } elsif ($wq->wq_kill_old) {
875 $wq->wq_wait_old($self);
878 close(delete $self->{1}) if $self->{1}; # may reap_compress
879 $self->close if $self->{sock}; # PublicInbox::DS::close
882 # for long-running results
885 local %ENV = %{$self->{env}};
886 my $sock = $self->{sock};
887 local $current_lei = $self;
889 while (my @fds = $recv_cmd->($sock, my $buf, 4096)) {
890 if (scalar(@fds) == 1 && !defined($fds[0])) {
891 return if $! == EAGAIN;
893 last if $! == ECONNRESET;
897 open my $rfh, '+<&=', $fd;
899 die "unrecognized client signal: $buf";
904 eval { $self->fail($err) };
909 sub event_step_init {
911 if (my $sock = $self->{sock}) { # using DS->EventLoop
912 $self->SUPER::new($sock, EPOLLIN|EPOLLET);
918 our $oldset; sub oldset { $oldset }
920 sub dump_and_clear_log {
921 if (defined($errors_log) && -s STDIN && seek(STDIN, 0, SEEK_SET)) {
923 unshift(@pfx, "$errors_log ") if @pfx;
924 warn @pfx, do { local $/; <STDIN> };
925 truncate(STDIN, 0) or warn "ftruncate ($errors_log): $!";
929 # lei(1) calls this when it can't connect
931 my ($path, $errno, $narg) = @_;
932 if ($errno == ECONNREFUSED) {
933 unlink($path) or die "unlink($path): $!";
934 } elsif ($errno != ENOENT) {
935 $! = $errno; # allow interpolation to stringify in die
936 die "connect($path): $!";
938 if (eval { require BSD::Resource }) {
939 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
940 my ($s, $h) = BSD::Resource::getrlimit($NOFILE);
941 BSD::Resource::setrlimit($NOFILE, $h, $h) if $s < $h;
943 umask(077) // die("umask(077): $!");
945 socket($listener, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
946 bind($listener, pack_sockaddr_un($path)) or die "bind($path): $!";
947 listen($listener, 1024) or die "listen: $!";
948 my @st = stat($path) or die "stat($path): $!";
949 my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
950 local $oldset = PublicInbox::DS::block_signals();
952 $send_cmd = PublicInbox::Spawn->can('send_cmd4');
953 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4') // do {
954 require PublicInbox::CmdIPC4;
955 $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4');
956 PublicInbox::CmdIPC4->can('recv_cmd4');
959 $recv_cmd or die <<"";
960 (Socket::MsgHdr || Inline::C) missing/unconfigured (narg=$narg);
962 require PublicInbox::Listener;
963 require PublicInbox::EOFpipe;
964 (-p STDOUT) or die "E: stdout must be a pipe\n";
966 ($errors_log) = ($path =~ m!\A(.+?/)[^/]+\z!);
967 $errors_log .= 'errors.log';
968 open(STDIN, '+>>', $errors_log) or die "open($errors_log): $!";
970 dump_and_clear_log("from previous daemon process:\n");
971 POSIX::setsid() > 0 or die "setsid: $!";
972 my $pid = fork // die "fork: $!";
974 $0 = "lei-daemon $path";
976 $listener->blocking(0);
978 my $pil = PublicInbox::Listener->new($listener, \&accept_dispatch);
980 pipe(my ($eof_r, $eof_w)) or die "pipe: $!";
981 PublicInbox::EOFpipe->new($eof_r, \&noop, undef);
983 $exit_code //= shift;
984 my $lis = $pil or exit($exit_code);
985 # closing eof_w triggers \&noop wakeup
986 $listener = $eof_w = $pil = $path = undef;
987 $lis->close; # DS::close
988 PublicInbox::DS->SetLoopTimeout(1000);
992 CHLD => \&PublicInbox::DS::enqueue_reap,
1000 my $sigfd = PublicInbox::Sigfd->new($sig, SFD_NONBLOCK);
1001 local @SIG{keys %$sig} = values(%$sig) unless $sigfd;
1003 local $SIG{PIPE} = 'IGNORE';
1004 if ($sigfd) { # TODO: use inotify/kqueue to detect unlinked sockets
1006 PublicInbox::DS->SetLoopTimeout(5000);
1008 # wake up every second to accept signals if we don't
1009 # have signalfd or IO::KQueue:
1010 PublicInbox::DS::sig_setmask($oldset);
1011 PublicInbox::DS->SetLoopTimeout(1000);
1013 PublicInbox::DS->SetPostLoopCallback(sub {
1014 my ($dmap, undef) = @_;
1015 if (@st = defined($path) ? stat($path) : ()) {
1016 if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
1017 warn "$path dev/ino changed, quitting\n";
1020 } elsif (defined($path)) { # ENOENT is common
1021 warn "stat($path): $!, quitting ...\n" if $! != ENOENT;
1025 return 1 if defined($path);
1028 for my $s (values %$dmap) {
1029 $s->can('busy') or next;
1030 if ($s->busy($now)) {
1036 $n; # true: continue, false: stop
1039 # STDIN was redirected to /dev/null above, closing STDERR and
1040 # STDOUT will cause the calling `lei' client process to finish
1041 # reading the <$daemon> pipe.
1042 local $SIG{__WARN__} = sub {
1043 $current_lei ? err($current_lei, @_) : warn(
1044 strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time))," $$ ", @_);
1046 open STDERR, '>&STDIN' or die "redirect stderr failed: $!";
1047 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!";
1048 # $daemon pipe to `lei' closed, main loop begins:
1049 PublicInbox::DS->EventLoop;
1050 exit($exit_code // 0);
1053 # for users w/o Socket::Msghdr installed or Inline::C enabled
1055 my ($main_pkg) = @_;
1056 my $exit = $main_pkg->can('exit'); # caller may override exit()
1057 local $quit = $exit if $exit;
1059 umask(077) // die("umask(077): $!");
1067 dispatch($self, @ARGV);
1068 x_it($self, $self->{child_error}) if $self->{child_error};
1071 # ensures stdout hits the FS before sock disconnects so a client
1072 # can immediately reread it
1075 $self->{1}->autoflush(1) if $self->{1};
1077 if (my $mua_pid = delete $self->{"mua.pid.$self.$$"}) {
1078 waitpid($mua_pid, 0);