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::Lock;
26 use Time::HiRes qw(stat); # ctime comparisons for config cache
27 use File::Path qw(mkpath);
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));
37 our %PATH2CFG; # persistent for socket daemon
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 }
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
49 if ($arg =~ /\A-($re_str)\z/) {
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 '-') {
56 push @{$OPT->{-argv}}, $arg;
58 die "bad argument: $arg\n";
61 push @{$OPT->{-argv}}, $arg;
64 ($spec, '<>' => $cb, $GLP_PASS) # for Getopt::Long
69 return $p if index($p, '/') == 0; # already absolute
70 my $pwd = $self->{env}->{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};
82 $pwd //= $self->{env}->{PWD} = getcwd() // die "getcwd(PWD=$pwd): $!";
83 File::Spec->rel2abs($p, $pwd);
88 rel2abs($self, ($self->{env}->{XDG_DATA_HOME} //
89 ($self->{env}->{HOME} // '/nonexistent').'/.local/share')
93 sub _config_path ($) {
95 rel2abs($self, ($self->{env}->{XDG_CONFIG_HOME} //
96 ($self->{env}->{HOME} // '/nonexistent').'/.config')
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)
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|
116 alert=s@ mua=s no-torsocks torsocks=s verbose|v+ quiet|q C=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 threads|t remote local! C=s@),
121 pass_through('git show') ],
123 'add-external' => [ 'LOCATION',
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 qw(quiet|q verbose|v+ C=s@),
127 index_opt(), PublicInbox::LeiQuery::curl_opt() ],
128 'ls-external' => [ '[FILTER]', 'list publicinbox|extindex locations',
129 qw(format|f=s z|0 globoff|g invert-match|v local remote C=s@) ],
130 'forget-external' => [ 'LOCATION...|--prune',
131 'exclude further results from a publicinbox|extindex',
132 qw(prune quiet|q C=s@) ],
134 'ls-query' => [ '[FILTER...]', 'list saved search queries',
135 qw(name-only format|f=s z C=s@) ],
136 'rm-query' => [ 'QUERY_NAME', 'remove a saved search', qw(C=s@) ],
137 'mv-query' => [ qw(OLD_NAME NEW_NAME), 'rename a saved search', qw(C=s@) ],
139 'plonk' => [ '--threads|--from=IDENT',
140 'exclude mail matching From: or threads from non-Message-ID searches',
141 qw(stdin| threads|t from|f=s mid=s oid=s C=s@) ],
142 'mark' => [ 'MESSAGE_FLAGS...',
143 'set/unset keywords on message(s) from stdin',
144 qw(stdin| oid=s exact by-mid|mid:s C=s@) ],
145 'forget' => [ '[--stdin|--oid=OID|--by-mid=MID]',
146 "exclude message(s) on stdin from `q' search results",
147 qw(stdin| oid=s exact by-mid|mid:s quiet|q C=s@) ],
149 'purge-mailsource' => [ 'LOCATION|--all',
150 'remove imported messages from IMAP, Maildirs, and MH',
151 qw(exact! all jobs:i indexed C=s@) ],
153 # code repos are used for `show' to solve blobs from patch mails
154 'add-coderepo' => [ 'DIRNAME', 'add or set priority of a git code repo',
156 'ls-coderepo' => [ '[FILTER_TERMS...]',
157 'list known code repos', qw(format|f=s z C=s@) ],
158 'forget-coderepo' => [ 'DIRNAME',
159 'stop using repo to solve blobs from patches',
162 'add-watch' => [ 'LOCATION', 'watch for new messages and flag changes',
163 qw(import! kw|keywords|flags! interval=s recursive|r
164 exclude=s include=s C=s@) ],
165 'ls-watch' => [ '[FILTER...]', 'list active watches with numbers and status',
166 qw(format|f=s z C=s@) ],
167 'pause-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote C=s@) ],
168 'resume-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote C=s@) ],
169 'forget-watch' => [ '{WATCH_NUMBER|--prune}', 'stop and forget a watch',
172 'import' => [ 'LOCATION...|--stdin',
173 'one-time import/update from URL or filesystem',
174 qw(stdin| offset=i recursive|r exclude=s include|I=s
175 in-format|F=s kw|keywords|flags! C=s@),
177 'convert' => [ 'LOCATION...|--stdin',
178 'one-time conversion from URL or filesystem to another format',
179 qw(stdin| in-format|F=s out-format|f=s output|mfolder|o=s quiet|q
180 kw|keywords|flags! C=s@),
182 'config' => [ '[...]', sub {
183 'git-config(1) wrapper for '._config_path($_[0]);
184 }, qw(config-file|system|global|file|f=s), # for conflict detection
185 qw(C=s@), pass_through('git config') ],
186 'init' => [ '[DIRNAME]', sub {
187 "initialize storage, default: "._store_path($_[0]);
188 }, qw(quiet|q C=s@) ],
189 'daemon-kill' => [ '[-SIGNAL]', 'signal the lei-daemon',
190 # "-C DIR" conflicts with -CHLD, here, and chdir makes no sense, here
191 opt_dash('signal|s=s', '[0-9]+|(?:[A-Z][A-Z0-9]+)') ],
192 'daemon-pid' => [ '', 'show the PID of the lei-daemon' ],
193 'help' => [ '[SUBCOMMAND]', 'show help' ],
195 # XXX do we need this?
196 # 'git' => [ '[ANYTHING...]', 'git(1) wrapper', pass_through('git') ],
198 'reorder-local-store-and-break-history' => [ '[REFNAME]',
199 'rewrite git history in an attempt to improve compression',
202 # internal commands are prefixed with '_'
203 '_complete' => [ '[...]', 'internal shell completion helper',
204 pass_through('everything') ],
207 # switch descriptions, try to keep consistent across commands
208 # $spec: Getopt::Long option specification
209 # $spec => [@ALLOWED_VALUES (default is first), $description],
210 # $spec => $description
211 # "$SUB_COMMAND TAB $spec" => as above
212 my $stdin_formats = [ 'MAIL_FORMAT|eml|mboxrd|mboxcl2|mboxcl|mboxo',
213 'specify message input format' ];
214 my $ls_format = [ 'OUT|plain|json|null', 'listing output format' ];
216 # we use \x{a0} (non-breaking SP) to avoid wrapping in PublicInbox::LeiHelp
218 'help|h' => 'show this built-in help',
219 'C=s@' => [ 'DIR', 'chdir to specify to directory' ],
220 'quiet|q' => 'be quiet',
221 'globoff|g' => "do not match locations using '*?' wildcards ".
222 "and\xa0'[]'\x{a0}ranges",
223 'verbose|v+' => 'be more verbose',
224 'solve!' => 'do not attempt to reconstruct blobs from emails',
225 'torsocks=s' => ['VAL|auto|no|yes',
226 'whether or not to wrap git and curl commands with torsocks'],
227 'no-torsocks' => 'alias for --torsocks=no',
228 'save-as=s' => ['NAME', 'save a search terms by given name'],
229 'import-remote!' => 'do not memoize remote messages into local store',
231 'type=s' => [ 'any|mid|git', 'disambiguate type' ],
233 'dedupe|d=s' => ['STRATEGY|content|oid|mid|none',
234 'deduplication strategy'],
235 'show threads|t' => 'display entire thread a message belongs to',
237 'return all messages in the same threads as the actual match(es)',
238 'alert=s@' => ['CMD,:WINCH,:bell,<any command>',
239 'run command(s) or perform ops when done writing to output ' .
240 '(default: ":WINCH,:bell" with --mua and Maildir/IMAP output, ' .
241 'nothing otherwise)' ],
243 'augment|a' => 'augment --output destination instead of clobbering',
245 'output|mfolder|o=s' => [ 'MFOLDER',
246 "destination (e.g.\xa0`/path/to/Maildir', ".
247 "or\xa0`-'\x{a0}for\x{a0}stdout)" ],
249 "MUA to run on --output Maildir or mbox (e.g.\xa0`mutt\xa0-f\xa0%f')" ],
251 'show format|f=s' => [ 'OUT|plain|raw|html|mboxrd|mboxcl2|mboxcl',
252 'message/object output format' ],
253 'mark format|f=s' => $stdin_formats,
254 'forget format|f=s' => $stdin_formats,
256 'add-external inbox-version=i' => [ 'NUM|1|2',
257 'force a public-inbox version with --mirror'],
258 'add-external mirror=s' => [ 'URL', 'mirror a public-inbox'],
260 # public-inbox-index options
261 'add-external jobs|j=i' => 'set parallelism when indexing after --mirror',
262 'fsync!' => 'speed up indexing after --mirror, risk index corruption',
263 'compact' => 'run compact index after mirroring',
264 'indexlevel|L=s' => [ 'LEVEL|full|medium|basic',
265 "indexlevel with --mirror (default: full)" ],
266 'max_size|max-size=s' => [ 'SIZE',
267 'do not index messages larger than SIZE (default: infinity)' ],
268 'batch_size|batch-size=s' => [ 'SIZE',
269 'flush changes to OS after given number of bytes (default: 1m)' ],
270 'sequential_shard|sequential-shard' =>
271 'index Xapian shards sequentially for slow storage',
273 'drop compatibility w/ public-inbox <1.6 to save ~1.5% space',
276 'OUT|maildir|mboxrd|mboxcl2|mboxcl|mboxo|html|json|jsonl|concatjson',
277 'specify output format, default depends on --output'],
278 'q exclude=s@' => [ 'LOCATION',
279 'exclude specified external(s) from search' ],
280 'q include|I=s@' => [ 'LOCATION',
281 'include specified external(s) in search' ],
282 'q only=s@' => [ 'LOCATION',
283 'only use specified external(s) for search' ],
285 'q jobs=s' => [ '[SEARCH_JOBS][,WRITER_JOBS]',
286 'control number of search and writer jobs' ],
288 'import format|f=s' => $stdin_formats,
290 'ls-query format|f=s' => $ls_format,
291 'ls-external format|f=s' => $ls_format,
293 'limit|n=i@' => ['NUM', 'limit on number of matches (default: 10000)' ],
294 'offset=i' => ['OFF', 'search result offset (default: 0)'],
296 'sort|s=s' => [ 'VAL|received|relevance|docid',
297 "order of results is `--output'-dependent"],
298 'reverse|r' => 'reverse search results', # like sort(1)
300 'boost=i' => 'increase/decrease priority of results (default: 0)',
302 'local' => 'limit operations to the local filesystem',
303 'local!' => 'exclude results from the local filesystem',
304 'remote' => 'limit operations to those requiring network access',
305 'remote!' => 'prevent operations requiring network access',
307 'mid=s' => 'specify the Message-ID of a message',
308 'oid=s' => 'specify the git object ID of a message',
310 'recursive|r' => 'scan directories/mailboxes/newsgroups recursively',
311 'exclude=s' => 'exclude mailboxes/newsgroups based on pattern',
312 'include=s' => 'include mailboxes/newsgroups based on pattern',
314 'exact' => 'operate on exact header matches only',
315 'exact!' => 'rely on content match instead of exact header matches',
317 'by-mid|mid:s' => [ 'MID', 'match only by Message-ID, ignoring contents' ],
319 'kw|keywords|flags!' => 'disable/enable importing flags',
321 # xargs, env, use "-0", git(1) uses "-z". We support z|0 everywhere
322 'z|0' => 'use NUL \\0 instead of newline (CR) to delimit lines',
324 'signal|s=s' => [ 'SIG', 'signal to send lei-daemon (default: TERM)' ],
328 'leistore.dir' => 'top-level storage location',
331 my @WQ_KEYS = qw(lxs l2m imp mrr cnv); # internal workers
333 # pronounced "exit": x_it(1 << 8) => exit(1); x_it(13) => SIGPIPE
335 my ($self, $code) = @_;
336 # make sure client sees stdout before exit
337 $self->{1}->autoflush(1) if $self->{1};
338 dump_and_clear_log();
339 if (my $s = $self->{pkt_op_p} // $self->{sock}) {
340 send($s, "x_it $code", MSG_EOR);
341 } elsif ($self->{oneshot}) {
342 # don't want to end up using $? from child processes
343 for my $f (@WQ_KEYS) {
344 my $wq = delete $self->{$f} or next;
347 # cleanup anything that has tempfiles or open file handles
349 delete @$self{qw(ovv dedupe sto cfg)};
350 if (my $signum = ($code & 127)) { # usually SIGPIPE (13)
351 $SIG{PIPE} = 'DEFAULT'; # $SIG{$signum} doesn't work
353 sleep(1) while 1; # wait for signal
357 } # else ignore if client disconnected
362 my $err = $self->{2} // ($self->{pgr} // [])->[2] // *STDERR{GLOB};
363 my @eor = (substr($_[-1]//'', -1, 1) eq "\n" ? () : ("\n"));
364 print $err @_, @eor and return;
365 my $old_err = delete $self->{2};
366 close($old_err) if $! == EPIPE && $old_err;
367 $err = $self->{2} = ($self->{pgr} // [])->[2] // *STDERR{GLOB};
368 print $err @_, @eor or print STDERR @_, @eor;
371 sub qerr ($;@) { $_[0]->{opt}->{quiet} or err(shift, @_) }
373 sub fail_handler ($;$$) {
374 my ($lei, $code, $io) = @_;
375 for my $f (@WQ_KEYS) {
376 my $wq = delete $lei->{$f} or next;
377 $wq->wq_wait_old(undef, $lei) if $wq->wq_kill_old; # lei-daemon
379 close($io) if $io; # needed to avoid warnings on SIGPIPE
380 x_it($lei, $code // (1 << 8));
383 sub sigpipe_handler { # handles SIGPIPE from @WQ_KEYS workers
384 fail_handler($_[0], 13, delete $_[0]->{1});
387 # PublicInbox::OnDestroy callback for SIGINT to take out the entire pgid
390 dwaitpid($pgid) if kill('-INT', $pgid);
394 my ($self, $buf, $exit_code) = @_;
395 err($self, $buf) if defined $buf;
396 # calls fail_handler:
397 send($self->{pkt_op_p}, '!', MSG_EOR) if $self->{pkt_op_p};
398 x_it($self, ($exit_code // 1) << 8);
402 sub check_input_format ($;$) {
403 my ($self, $files) = @_;
404 my $opt_key = 'in-format';
405 my $fmt = $self->{opt}->{$opt_key};
407 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
408 return fail($self, "--$opt_key unset for $err");
410 return 1 if $fmt eq 'eml';
411 # XXX: should this handle {gz,bz2,xz}? that's currently in LeiToMail
412 require PublicInbox::MboxReader;
413 PublicInbox::MboxReader->can($fmt) ||
414 fail($self, "--$opt_key=$fmt unrecognized");
419 return if print { $self->{1} // return } @_; # likely
420 return note_sigpipe($self, 1) if $! == EPIPE;
421 my $err = "error writing to stdout: $!";
426 sub puts ($;@) { out(shift, map { "$_\n" } @_) }
428 sub child_error { # passes non-fatal curl exit codes to user
429 my ($self, $child_error, $msg) = @_; # child_error is $?
430 $self->err($msg) if $msg;
431 if (my $s = $self->{pkt_op_p} // $self->{sock}) {
432 # send to the parent lei-daemon or to lei(1) client
433 send($s, "child_error $child_error", MSG_EOR);
434 } elsif (!$PublicInbox::DS::in_loop) {
435 $self->{child_error} = $child_error;
436 } # else noop if client disconnected
439 sub note_sigpipe { # triggers sigpipe_handler
440 my ($self, $fd) = @_;
441 close(delete($self->{$fd})); # explicit close silences Perl warning
442 send($self->{pkt_op_p}, '|', MSG_EOR) if $self->{pkt_op_p};
446 sub lei_atfork_child {
447 my ($self, $persist) = @_;
448 # we need to explicitly close things which are on stack
450 my @io = delete @$self{qw(0 1 2 sock)};
451 unless ($self->{oneshot}) {
457 delete @$self{qw(cnv)};
458 for (delete @$self{qw(3 old_1 au_done)}) {
459 close($_) if defined($_);
461 if (my $op_c = delete $self->{pkt_op_c}) {
462 close(delete $op_c->{sock});
464 if (my $pgr = delete $self->{pgr}) {
465 close($_) for (@$pgr[1,2]);
467 close $listener if $listener;
471 $quit = \&CORE::exit;
472 $current_lei = $persist ? undef : $self; # for SIG{__WARN__}
476 my ($lei, $wq, $ident, $jobs, $ops) = @_;
478 '!' => [ $lei->can('fail_handler'), $lei ],
479 '|' => [ $lei->can('sigpipe_handler'), $lei ],
480 'x_it' => [ $lei->can('x_it'), $lei ],
481 'child_error' => [ $lei->can('child_error'), $lei ],
484 require PublicInbox::PktOp;
485 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
486 $wq->wq_workers_start($ident, $jobs, $lei->oldset, { lei => $lei });
487 delete $lei->{pkt_op_p};
488 my $op = delete $lei->{pkt_op_c};
489 $lei->event_step_init;
490 # oneshot needs $op, daemon-mode uses DS->EventLoop to handle $op
491 $lei->{oneshot} ? $op : undef;
495 require PublicInbox::LeiHelp;
496 PublicInbox::LeiHelp::call($_[0], $_[1], \%CMD, \%OPTDESC);
500 my ($self, $cmd, $argv) = @_;
501 # allow _complete --help to complete, not show help
502 return 1 if substr($cmd, 0, 1) eq '_';
504 $OPT = $self->{opt} //= {};
505 my $info = $CMD{$cmd} // [ '[...]' ];
506 my ($proto, undef, @spec) = @$info;
507 my $glp = ref($spec[-1]) eq ref($GLP) ? pop(@spec) : $GLP;
508 push @spec, qw(help|h);
510 if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
511 $lone_dash = $spec[0];
512 $OPT->{$spec[0]} = \(my $var);
513 push @spec, '' => \$var;
515 $glp->getoptionsfromarray($argv, $OPT, @spec) or
516 return _help($self, "bad arguments or options for $cmd");
517 return _help($self) if $OPT->{help};
519 push @$argv, @{$OPT->{-argv}} if defined($OPT->{-argv});
521 # "-" aliases "stdin" or "clear"
522 $OPT->{$lone_dash} = ${$OPT->{$lone_dash}} if defined $lone_dash;
525 my $POS_ARG = '[A-Z][A-Z0-9_]+';
527 my @args = split(/ /, $proto);
528 for my $var (@args) {
529 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
530 $inf = defined($argv->[$i]) and last;
531 $var =~ s/\.\.\.\z//;
532 $err = "$var not supplied";
533 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
534 $argv->[$i++] // ($err = "$var not supplied");
535 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
538 } elsif ($var =~ /\A\[-?$POS_ARG\]\z/) { # one optional arg
540 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
541 $inf = 1 if index($var, '...') > 0;
542 my @or = split(/\|/, $var);
545 if ($o =~ /\A--([a-z0-9\-]+)/) {
546 $ok = defined($OPT->{$1});
548 } elsif (defined($argv->[$i])) {
552 } # else continue looping
556 $err = join(', ', @or) . " or $last must be set";
558 warn "BUG: can't parse `$var' in $proto";
562 if (!$inf && scalar(@$argv) > scalar(@args)) {
563 $err //= 'too many arguments';
565 $err ? fail($self, "usage: lei $cmd $proto\nE: $err") : 1;
569 my ($self, $cmd, @argv) = @_;
570 local $current_lei = $self; # for __WARN__
571 dump_and_clear_log("from previous run\n");
572 return _help($self, 'no command given') unless defined($cmd);
573 while ($cmd eq '-C') { # do not support Getopt bundling for this
574 my $d = shift(@argv) // return fail($self, '-C DIRECTORY');
575 push @{$self->{opt}->{C}}, $d;
576 $cmd = shift(@argv) // return _help($self, 'no command given');
578 my $func = "lei_$cmd";
580 if (my $cb = __PACKAGE__->can($func)) {
581 optparse($self, $cmd, \@argv) or return;
582 if (my $chdir = $self->{opt}->{C}) {
583 for my $d (@$chdir) {
584 next if $d eq ''; # same as git(1)
585 chdir $d or return fail($self, "cd $d: $!");
589 } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
590 $GLP->getoptionsfromarray([$cmd, @argv], {}, qw(help|h C=s@))
591 or return _help($self, 'bad arguments or options');
594 fail($self, "`$cmd' is not an lei command");
599 my ($self, $creat) = @_;
600 my $f = _config_path($self);
602 my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
603 if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
604 return ($self->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
609 return bless {}, 'PublicInbox::Config';
611 my (undef, $cfg_dir, undef) = File::Spec->splitpath($f);
612 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
613 open my $fh, '>>', $f or die "open($f): $!\n";
614 @st = stat($fh) or die "fstat($f): $!\n";
615 $cur_st = pack('dd', $st[10], $st[7]);
616 qerr($self, "# $f created") if $self->{cmd} ne 'config';
618 my $cfg = PublicInbox::Config::git_config_dump($f);
619 bless $cfg, 'PublicInbox::Config';
620 $cfg->{-st} = $cur_st;
622 $self->{cfg} = $PATH2CFG{$f} = $cfg;
625 sub _lei_store ($;$) {
626 my ($self, $creat) = @_;
627 my $cfg = _lei_cfg($self, $creat);
628 $cfg->{-lei_store} //= do {
629 require PublicInbox::LeiStore;
630 my $dir = $cfg->{'leistore.dir'};
631 $dir //= $creat ? _store_path($self) : return;
632 PublicInbox::LeiStore->new($dir, { creat => $creat });
637 my ($self, @argv) = @_;
641 my ($self, @argv) = @_;
645 my ($self, @argv) = @_;
646 my %env = (%{$self->{env}}, GIT_CONFIG => undef);
647 my $cfg = _lei_cfg($self, 1);
648 my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
649 my %rdr = map { $_ => $self->{$_} } (0..2);
650 waitpid(spawn($cmd, \%env, \%rdr), 0);
654 my ($self, @argv) = @_;
655 $self->{opt}->{'config-file'} and return fail $self,
656 "config file switches not supported by `lei config'";
658 x_it($self, $?) if $?;
662 require PublicInbox::LeiImport;
663 PublicInbox::LeiImport->call(@_);
667 require PublicInbox::LeiConvert;
668 PublicInbox::LeiConvert->call(@_);
672 my ($self, $dir) = @_;
673 my $cfg = _lei_cfg($self, 1);
674 my $cur = $cfg->{'leistore.dir'};
675 $dir //= _store_path($self);
676 $dir = rel2abs($self, $dir);
677 my @cur = stat($cur) if defined($cur);
678 $cur = File::Spec->canonpath($cur // $dir);
679 my @dir = stat($dir);
680 my $exists = "# leistore.dir=$cur already initialized" if @dir;
683 _lei_store($self, 1)->done;
684 return qerr($self, $exists);
687 # some folks like symlinks and bind mounts :P
688 if (@dir && "@cur[1,0]" eq "@dir[1,0]") {
689 lei_config($self, 'leistore.dir', $dir);
690 _lei_store($self, 1)->done;
691 return qerr($self, "$exists (as $cur)");
693 return fail($self, <<"");
694 E: leistore.dir=$cur already initialized and it is not $dir
697 lei_config($self, 'leistore.dir', $dir);
698 _lei_store($self, 1)->done;
699 $exists //= "# leistore.dir=$dir newly initialized";
700 return qerr($self, $exists);
703 sub lei_daemon_pid { puts shift, $$ }
705 sub lei_daemon_kill {
707 my $sig = $self->{opt}->{signal} // 'TERM';
708 kill($sig, $$) or fail($self, "kill($sig, $$): $!");
711 sub lei_help { _help($_[0]) }
713 # Shell completion helper. Used by lei-completion.bash and hopefully
714 # other shells. Try to do as much here as possible to avoid redundancy
715 # and improve maintainability.
717 my ($self, @argv) = @_; # argv = qw(lei and any other args...)
718 shift @argv; # ignore "lei", the entire command is sent
719 @argv or return puts $self, grep(!/^_/, keys %CMD), qw(--help -h -C);
720 my $cmd = shift @argv;
721 my $info = $CMD{$cmd} // do { # filter matching commands
722 @argv or puts $self, grep(/\A\Q$cmd\E/, keys %CMD);
725 my ($proto, undef, @spec) = @$info;
727 my $re = defined($cur) ? qr/\A\Q$cur\E/ : qr/./;
728 if (substr($cur // '-', 0, 1) eq '-') { # --switches
729 # gross special case since the only git-config options
730 # Consider moving to a table if we need more special cases
731 # we use Getopt::Long for are the ones we reject, so these
732 # are the ones we don't reject:
733 if ($cmd eq 'config') {
734 puts $self, grep(/$re/, keys %CONFIG_KEYS);
735 @spec = qw(add z|null get get-all unset unset-all
736 replace-all get-urlmatch
737 remove-section rename-section
738 name-only list|l edit|e
739 get-color-name get-colorbool);
742 # generate short/long names from Getopt::Long specs
743 puts $self, grep(/$re/, qw(--help -h -C), map {
744 if (s/[:=].+\z//) { # req/optional args, e.g output|o=i
745 } elsif (s/\+\z//) { # verbose|v+
747 # negation: solve! => no-solve|solve
748 s/([\w\-]+)/$1|no-$1/g
751 my $x = length > 1 ? "--$_" : "-$_";
752 $x eq $cur ? () : $x;
753 } grep(!/_/, split(/\|/, $_, -1)) # help|h
754 } grep { $OPTDESC{"$cmd\t$_"} || $OPTDESC{$_} } @spec);
755 } elsif ($cmd eq 'config' && !@argv && !$CONFIG_KEYS{$cur}) {
756 puts $self, grep(/$re/, keys %CONFIG_KEYS);
759 # switch args (e.g. lei q -f mbox<TAB>)
760 if (($argv[-1] // $cur // '') =~ /\A--?([\w\-]+)\z/) {
761 my $opt = quotemeta $1;
763 my $v = $OPTDESC{$_};
764 my @v = ref($v) ? split(/\|/, $v->[0]) : ();
765 # get rid of ALL CAPS placeholder (e.g "OUT")
766 # (TODO: completion for external paths)
767 shift(@v) if uc($v[0]) eq $v[0];
769 } grep(/\A(?:$cmd\t|)(?:[\w-]+\|)*$opt\b/, keys %OPTDESC);
772 if (my $sub = $self->can("_complete_$cmd")) {
773 puts $self, $sub->($self, @argv, $cur);
775 # TODO: URLs, pathnames, OIDs, MIDs, etc... See optparse() for
780 my ($argv, $env) = @_;
781 my $argc = scalar @$argv;
782 my $buf = 'exec '.join("\0", scalar(@$argv), @$argv);
783 while (my ($k, $v) = each %$env) { $buf .= "\0$k=$v" };
789 my $mua = $self->{opt}->{mua} // return;
790 my $mfolder = $self->{ovv}->{dst};
791 my (@cmd, $replaced);
792 if ($mua =~ /\A(?:mutt|mailx|mail|neomutt)\z/) {
794 # TODO: help wanted: other common FOSS MUAs
796 require Text::ParseWords;
797 @cmd = Text::ParseWords::shellwords($mua);
798 # mutt uses '%f' for open-hook with compressed mbox, we follow
799 @cmd = map { $_ eq '%f' ? ($replaced = $mfolder) : $_ } @cmd;
801 push @cmd, $mfolder unless defined($replaced);
802 if (my $sock = $self->{sock}) { # lei(1) client process runs it
803 send($sock, exec_buf(\@cmd, {}), MSG_EOR);
804 } elsif ($self->{oneshot}) {
805 $self->{"pid.$self.$$"}->{spawn(\@cmd)} = \@cmd;
807 if ($self->{lxs} && $self->{au_done}) { # kick wait_startq
808 syswrite($self->{au_done}, 'q' x ($self->{lxs}->{jobs} // 0));
810 $self->{opt}->{quiet} = 1;
811 delete $self->{-progress};
812 delete $self->{opt}->{verbose};
815 sub send_exec_cmd { # tell script/lei to execute a command
816 my ($self, $io, $cmd, $env) = @_;
817 my $sock = $self->{sock} // die 'lei client gone';
818 my $fds = [ map { fileno($_) } @$io ];
819 $send_cmd->($sock, $fds, exec_buf($cmd, $env), MSG_EOR);
822 sub poke_mua { # forces terminal MUAs to wake up and hopefully notice new mail
824 my $alerts = $self->{opt}->{alert} // return;
825 while (my $op = shift(@$alerts)) {
826 if ($op eq ':WINCH') {
827 # hit the process group that started the MUA
829 send($self->{sock}, '-WINCH', MSG_EOR);
830 } elsif ($self->{oneshot}) {
833 } elsif ($op eq ':bell') {
835 } elsif ($op =~ /(?<!\\),/) { # bare ',' (not ',,')
836 push @$alerts, split(/(?<!\\),/, $op);
837 } elsif ($op =~ m!\A([/a-z0-9A-Z].+)!) {
838 my $cmd = $1; # run an arbitrary command
839 require Text::ParseWords;
840 $cmd = [ Text::ParseWords::shellwords($cmd) ];
841 if (my $s = $self->{sock}) {
842 send($s, exec_buf($cmd, {}), MSG_EOR);
843 } elsif ($self->{oneshot}) {
844 $self->{"pid.$self.$$"}->{spawn($cmd)} = $cmd;
847 err($self, "W: unsupported --alert=$op"); # non-fatal
852 # caller needs to "-t $self->{1}" to check if tty
855 my $fh = popen_rd([qw(git var GIT_PAGER)]);
856 chomp(my $pager = <$fh> // '');
857 close($fh) or warn "`git var PAGER' error: \$?=$?";
858 return if $pager eq 'cat' || $pager eq '';
859 my $new_env = { LESS => 'FRX', LV => '-c' };
860 $new_env->{MORE} = 'FRX' if $^O eq 'freebsd';
861 pipe(my ($r, $wpager)) or return warn "pipe: $!";
862 my $rdr = { 0 => $r, 1 => $self->{1}, 2 => $self->{2} };
863 my $pgr = [ undef, @$rdr{1, 2} ];
864 my $env = $self->{env};
865 if ($self->{sock}) { # lei(1) process runs it
866 delete @$new_env{keys %$env}; # only set iff unset
867 send_exec_cmd($self, [ @$rdr{0..2} ], [$pager], $new_env);
868 } elsif ($self->{oneshot}) {
870 $self->{"pid.$self.$$"}->{spawn($cmd, $new_env, $rdr)} = $cmd;
872 die 'BUG: start_pager w/o socket';
874 $self->{1} = $wpager;
875 $self->{2} = $wpager if -t $self->{2};
876 $env->{GIT_PAGER_IN_USE} = 'true'; # we may spawn git
882 my $pgr = delete($self->{pgr}) or return;
883 $self->{2} = $pgr->[2];
884 # do not restore original stdout, just close it so we error out
885 close(delete($self->{1})) if $self->{1};
888 sub accept_dispatch { # Listener {post_accept} callback
889 my ($sock) = @_; # ignore other
891 my $self = bless { sock => $sock }, __PACKAGE__;
892 vec(my $rvec = '', fileno($sock), 1) = 1;
893 select($rvec, undef, undef, 60) or
894 return send($sock, 'timed out waiting to recv FDs', MSG_EOR);
895 # (4096 * 33) >MAX_ARG_STRLEN
896 my @fds = $recv_cmd->($sock, my $buf, 4096 * 33) or return; # EOF
897 if (scalar(@fds) == 4) {
899 my $fd = shift(@fds);
900 open($self->{$i}, '+<&=', $fd) and next;
901 send($sock, "open(+<&=$fd) (FD=$i): $!", MSG_EOR);
903 } elsif (!defined($fds[0])) {
904 warn(my $msg = "recv_cmd failed: $!");
905 return send($sock, $msg, MSG_EOR);
909 $self->{2}->autoflush(1); # keep stdout buffered until x_it|DESTROY
910 # $ENV_STR = join('', map { "\0$_=$ENV{$_}" } keys %ENV);
911 # $buf = "$argc\0".join("\0", @ARGV).$ENV_STR."\0\0";
912 substr($buf, -2, 2, '') eq "\0\0" or # s/\0\0\z//
913 return send($sock, 'request command truncated', MSG_EOR);
914 my ($argc, @argv) = split(/\0/, $buf, -1);
916 my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
917 if (chdir($self->{3})) {
919 $self->{env} = \%env;
920 eval { dispatch($self, @argv) };
921 send($sock, $@, MSG_EOR) if $@;
923 send($sock, "fchdir: $!", MSG_EOR); # implicit close
929 delete $self->{-progress};
930 for my $f (@WQ_KEYS) {
931 my $wq = delete $self->{$f} or next;
933 $wq->wq_close(0, undef, $self);
934 } elsif ($wq->wq_kill_old) {
935 $wq->wq_wait_old(undef, $self);
938 close(delete $self->{1}) if $self->{1}; # may reap_compress
939 $self->close if $self->{sock}; # PublicInbox::DS::close
942 # for long-running results
945 local %ENV = %{$self->{env}};
946 my $sock = $self->{sock};
947 local $current_lei = $self;
949 while (my @fds = $recv_cmd->($sock, my $buf, 4096)) {
950 if (scalar(@fds) == 1 && !defined($fds[0])) {
951 return if $! == EAGAIN;
953 last if $! == ECONNRESET;
957 open my $rfh, '+<&=', $fd;
959 die "unrecognized client signal: $buf";
964 eval { $self->fail($err) };
969 sub event_step_init {
971 return if $self->{-event_init_done}++;
972 if (my $sock = $self->{sock}) { # using DS->EventLoop
973 $self->SUPER::new($sock, EPOLLIN|EPOLLET);
979 our $oldset; sub oldset { $oldset }
981 sub dump_and_clear_log {
982 if (defined($errors_log) && -s STDIN && seek(STDIN, 0, SEEK_SET)) {
984 unshift(@pfx, "$errors_log ") if @pfx;
985 warn @pfx, do { local $/; <STDIN> };
986 truncate(STDIN, 0) or warn "ftruncate ($errors_log): $!";
990 # lei(1) calls this when it can't connect
992 my ($path, $errno, $narg) = @_;
993 local ($errors_log, $listener);
994 ($errors_log) = ($path =~ m!\A(.+?/)[^/]+\z!);
995 $errors_log .= 'errors.log';
996 my $addr = pack_sockaddr_un($path);
997 my $lk = bless { lock_path => $errors_log }, 'PublicInbox::Lock';
999 socket($listener, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
1000 if ($errno == ECONNREFUSED || $errno == ENOENT) {
1001 return if connect($listener, $addr); # another process won
1002 if ($errno == ECONNREFUSED && -S $path) {
1003 unlink($path) or die "unlink($path): $!";
1006 $! = $errno; # allow interpolation to stringify in die
1007 die "connect($path): $!";
1009 umask(077) // die("umask(077): $!");
1010 bind($listener, $addr) or die "bind($path): $!";
1011 listen($listener, 1024) or die "listen: $!";
1014 my @st = stat($path) or die "stat($path): $!";
1015 my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
1016 local $oldset = PublicInbox::DS::block_signals();
1018 $send_cmd = PublicInbox::Spawn->can('send_cmd4');
1019 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4') // do {
1020 require PublicInbox::CmdIPC4;
1021 $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4');
1022 PublicInbox::CmdIPC4->can('recv_cmd4');
1025 $recv_cmd or die <<"";
1026 (Socket::MsgHdr || Inline::C) missing/unconfigured (narg=$narg);
1028 require PublicInbox::Listener;
1029 require PublicInbox::EOFpipe;
1030 (-p STDOUT) or die "E: stdout must be a pipe\n";
1031 open(STDIN, '+>>', $errors_log) or die "open($errors_log): $!";
1032 STDIN->autoflush(1);
1033 dump_and_clear_log("from previous daemon process:\n");
1034 POSIX::setsid() > 0 or die "setsid: $!";
1035 my $pid = fork // die "fork: $!";
1037 $0 = "lei-daemon $path";
1039 $listener->blocking(0);
1041 my $pil = PublicInbox::Listener->new($listener, \&accept_dispatch);
1043 pipe(my ($eof_r, $eof_w)) or die "pipe: $!";
1044 PublicInbox::EOFpipe->new($eof_r, \&noop, undef);
1046 $exit_code //= shift;
1047 my $lis = $pil or exit($exit_code);
1048 # closing eof_w triggers \&noop wakeup
1049 $listener = $eof_w = $pil = $path = undef;
1050 $lis->close; # DS::close
1051 PublicInbox::DS->SetLoopTimeout(1000);
1055 CHLD => \&PublicInbox::DS::enqueue_reap,
1063 my $sigfd = PublicInbox::Sigfd->new($sig, SFD_NONBLOCK);
1064 local @SIG{keys %$sig} = values(%$sig) unless $sigfd;
1066 local $SIG{PIPE} = 'IGNORE';
1067 if ($sigfd) { # TODO: use inotify/kqueue to detect unlinked sockets
1069 PublicInbox::DS->SetLoopTimeout(5000);
1071 # wake up every second to accept signals if we don't
1072 # have signalfd or IO::KQueue:
1073 PublicInbox::DS::sig_setmask($oldset);
1074 PublicInbox::DS->SetLoopTimeout(1000);
1076 PublicInbox::DS->SetPostLoopCallback(sub {
1077 my ($dmap, undef) = @_;
1078 if (@st = defined($path) ? stat($path) : ()) {
1079 if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
1080 warn "$path dev/ino changed, quitting\n";
1083 } elsif (defined($path)) { # ENOENT is common
1084 warn "stat($path): $!, quitting ...\n" if $! != ENOENT;
1088 return 1 if defined($path);
1091 for my $s (values %$dmap) {
1092 $s->can('busy') or next;
1093 if ($s->busy($now)) {
1099 $n; # true: continue, false: stop
1102 # STDIN was redirected to /dev/null above, closing STDERR and
1103 # STDOUT will cause the calling `lei' client process to finish
1104 # reading the <$daemon> pipe.
1105 local $SIG{__WARN__} = sub {
1106 $current_lei ? err($current_lei, @_) : warn(
1107 strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time))," $$ ", @_);
1109 open STDERR, '>&STDIN' or die "redirect stderr failed: $!";
1110 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!";
1111 # $daemon pipe to `lei' closed, main loop begins:
1112 PublicInbox::DS->EventLoop;
1113 exit($exit_code // 0);
1116 sub busy { 1 } # prevent daemon-shutdown if client is connected
1118 # for users w/o Socket::Msghdr installed or Inline::C enabled
1120 my ($main_pkg) = @_;
1121 my $exit = $main_pkg->can('exit'); # caller may override exit()
1122 local $quit = $exit if $exit;
1124 umask(077) // die("umask(077): $!");
1132 dispatch($self, @ARGV);
1133 x_it($self, $self->{child_error}) if $self->{child_error};
1136 # ensures stdout hits the FS before sock disconnects so a client
1137 # can immediately reread it
1140 $self->{1}->autoflush(1) if $self->{1};
1143 my $oneshot_pids = delete $self->{"pid.$self.$$"} or return;
1144 waitpid($_, 0) for keys %$oneshot_pids;
1145 $? = $err if $err; # preserve ->fail or ->x_it code