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