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