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