]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
lei_mirror: drop git <1.8.5 support
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use v5.12;
7 use parent qw(PublicInbox::IPC);
8 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
9 use IO::Compress::Gzip qw(gzip $GzipError);
10 use PublicInbox::Spawn qw(popen_rd spawn run_die);
11 use File::Path ();
12 use File::Temp ();
13 use File::Spec ();
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
15 use Carp qw(croak);
16 use URI;
17 use PublicInbox::Config;
18 use PublicInbox::Inbox;
19 use PublicInbox::LeiCurl;
20 use PublicInbox::OnDestroy;
21 use Digest::SHA qw(sha256_hex);
22
23 our $LIVE; # pid => callback
24
25 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
26         my ($arg, $pid) = @_;
27         my ($mrr, $lei) = @$arg;
28         my $f = "$mrr->{dst}/mirror.done";
29         if ($?) {
30                 $lei->child_error($?);
31         } elsif (!$mrr->{dry_run} && !unlink($f)) {
32                 warn("unlink($f): $!\n") unless $!{ENOENT};
33         } else {
34                 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
35                         require PublicInbox::LeiAddExternal;
36                         PublicInbox::LeiAddExternal::_finish_add_external(
37                                                         $lei, $mrr->{dst});
38                 }
39                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
40         }
41         $lei->dclose;
42 }
43
44 # for old installations without manifest.js.gz
45 sub try_scrape {
46         my ($self, $fallback_manifest) = @_;
47         my $uri = URI->new($self->{src});
48         my $lei = $self->{lei};
49         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
50         my $cmd = $curl->for_uri($lei, $uri, qw(-f --compressed));
51         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
52         my $fh = popen_rd($cmd, undef, $opt);
53         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
54         close($fh) or return $lei->child_error($?, "@$cmd failed");
55
56         # we grep with URL below, we don't want Subject/From headers
57         # making us clone random URLs.  This assumes remote instances
58         # prior to public-inbox 1.7.0
59         # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
60         my @html = split(/<hr>/, $html);
61         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
62         if (!@urls && $fallback_manifest) {
63                 warn <<EOM;
64 W: failed to extract URLs from $uri, trying manifest.js.gz...
65 EOM
66                 return start_clone_url($self);
67         }
68         my $url = $uri->as_string;
69         chop($url) eq '/' or die "BUG: $uri not canonicalized";
70
71         # since this is for old instances w/o manifest.js.gz, try v1 first
72         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
73         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
74                 my %v2_epochs = map {
75                         my ($n) = (m!/([0-9]+)\z!);
76                         $n => [ URI->new($_), '' ]
77                 } @v2_urls; # uniq
78                 clone_v2_prep($self, \%v2_epochs);
79                 delete local $lei->{opt}->{epoch};
80                 clone_all($self);
81                 return;
82         }
83
84         # filter out common URLs served by WWW (e.g /$MSGID/T/)
85         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
86                         grep(m!\A\Q$url\E/*\z!, @urls)) {
87                 die <<"";
88 E: confused by scraping <$uri>, did you mean <$url>?
89
90         }
91         @urls and die <<"";
92 E: confused by scraping <$uri>, got ambiguous results:
93 @urls
94
95         die "E: scraping <$uri> revealed nothing\n";
96 }
97
98 sub clone_cmd {
99         my ($lei, $opt) = @_;
100         my @cmd = qw(git);
101         $opt->{$_} = $lei->{$_} for (0..2);
102         # we support "-c $key=$val" for arbitrary git config options
103         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
104         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
105         push @cmd, qw(clone --mirror);
106         push @cmd, '-q' if $lei->{opt}->{quiet} ||
107                         ($lei->{opt}->{jobs} // 1) > 1;
108         push @cmd, '-v' if $lei->{opt}->{verbose};
109         # XXX any other options to support?
110         # --reference is tricky with multiple epochs, but handled
111         # automatically if using manifest.js.gz
112         @cmd;
113 }
114
115 sub ft_rename ($$$;$) {
116         my ($ft, $dst, $open_mode, $fh) = @_;
117         my @st = stat($fh // $dst);
118         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
119         chmod($mode, $ft) or croak "E: chmod($ft): $!";
120         require File::Copy;
121         File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
122         $ft->unlink_on_destroy(0);
123 }
124
125 sub do_reap ($;$) {
126         my ($self, $jobs) = @_;
127         $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
128         $jobs = 1 if $jobs < 1;
129         while (keys(%$LIVE) >= $jobs) {
130                 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
131                 if (my $x = delete $LIVE->{$pid}) {
132                         my $cb = shift @$x;
133                         $cb->(@$x) if $cb;
134                 } else {
135                         warn "reaped unknown PID=$pid ($?)\n";
136                 }
137         }
138 }
139
140 sub _get_txt_start { # non-fatal
141         my ($self, $endpoint, $fini) = @_;
142         my $uri = URI->new($self->{cur_src} // $self->{src});
143         my $lei = $self->{lei};
144         my $path = $uri->path;
145         chop($path) eq '/' or die "BUG: $uri not canonicalized";
146         $uri->path("$path/$endpoint");
147         my $f = (split(m!/!, $endpoint))[-1];
148         my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
149         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
150         my $cmd = $self->{curl}->for_uri($lei, $uri, qw(-f --compressed -R -o),
151                                         $ft->filename);
152         do_reap($self);
153         $lei->qerr("# @$cmd");
154         return if $self->{dry_run};
155         $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
156         $LIVE->{spawn($cmd, undef, $opt)} =
157                         [ \&_get_txt_done, $self, $endpoint, $fini ];
158 }
159
160 sub _get_txt_done { # returns true on error (non-fatal), undef on success
161         my ($self, $endpoint) = @_;
162         my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
163         my $cerr = $?;
164         $? = 0; # don't influence normal lei exit
165         return warn("$uri missing\n") if ($cerr >> 8) == 22;
166         return warn("# @$cmd failed (non-fatal)\n") if $cerr;
167         seek($fh, SEEK_SET, 0) or die "seek: $!";
168         $self->{"mtime.$endpoint"} = (stat($fh))[9];
169         local $/;
170         $self->{"txt.$endpoint"} = <$fh>;
171         undef; # success
172 }
173
174 sub _write_inbox_config {
175         my ($self) = @_;
176         my $buf = delete($self->{'txt._/text/config/raw'}) // return;
177         my $dst = $self->{cur_dst} // $self->{dst};
178         my $f = "$dst/inbox.config.example";
179         open my $fh, '>', $f or die "open($f): $!";
180         print $fh $buf or die "print: $!";
181         chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
182         my $mtime = delete $self->{'mtime._/text/config/raw'};
183         $fh->flush or die "flush($f): $!";
184         if (defined $mtime) {
185                 utime($mtime, $mtime, $fh) or die "utime($f): $!";
186         }
187         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
188         my $ibx = $self->{ibx} = {};
189         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
190                 for (qw(address newsgroup nntpmirror)) {
191                         $ibx->{$_} = $cfg->{"$sec.$_"};
192                 }
193         }
194 }
195
196 sub set_description ($) {
197         my ($self) = @_;
198         my $dst = $self->{cur_dst} // $self->{dst};
199         my $f = "$dst/description";
200         open my $fh, '+>>', $f or die "open($f): $!";
201         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
202         my $d = do { local $/; <$fh> } // die "read($f): $!";
203         chomp(my $orig = $d);
204         while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
205                         $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
206                 $d = delete($self->{'txt.description'});
207         }
208         $d //= 'mirror of '.($self->{cur_src} // $self->{src});
209         chomp $d;
210         return if $d eq $orig;
211         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
212         truncate($fh, 0) or die "truncate($f): $!";
213         print $fh $d, "\n" or die "print($f): $!";
214         close $fh or die "close($f): $!";
215 }
216
217 sub index_cloned_inbox {
218         my ($self, $iv) = @_;
219         my $lei = $self->{lei};
220
221         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
222         # lei is useless without Xapian + SQLite
223         if ($lei->{cmd} ne 'public-inbox-clone') {
224                 require PublicInbox::InboxWritable;
225                 require PublicInbox::Admin;
226                 my $ibx = delete($self->{ibx}) // {
227                         address => [ 'lei@example.com' ],
228                         version => $iv,
229                 };
230                 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
231                 PublicInbox::Inbox->new($ibx);
232                 PublicInbox::InboxWritable->new($ibx);
233                 my $opt = {};
234                 for my $sw ($lei->index_opt) {
235                         my ($k) = ($sw =~ /\A([\w-]+)/);
236                         $opt->{$k} = $lei->{opt}->{$k};
237                 }
238                 # force synchronous dwaitpid for v2:
239                 local $PublicInbox::DS::in_loop = 0;
240                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
241                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
242                 local %ENV = (%ENV, %$env) if $env;
243                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
244                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
245         }
246         return if defined $self->{cur_dst}; # one of many repos to clone
247         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
248 }
249
250 sub run_reap {
251         my ($lei, $cmd, $opt) = @_;
252         $lei->qerr("# @$cmd");
253         waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
254         my $ret = $?;
255         $? = 0; # don't let it influence normal exit
256         $ret;
257 }
258
259 sub start_clone {
260         my ($self, $cmd, $opt, $fini) = @_;
261         do_reap($self);
262         $self->{lei}->qerr("# @$cmd");
263         return if $self->{dry_run};
264         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
265 }
266
267 sub fetch_args ($$) {
268         my ($lei, $opt) = @_;
269         my @cmd; # (git --git-dir=...) to be added by caller
270         $opt->{$_} = $lei->{$_} for (0..2);
271         # we support "-c $key=$val" for arbitrary git config options
272         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
273         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
274         push @cmd, 'fetch';
275         push @cmd, '-q' if $lei->{opt}->{quiet} ||
276                         ($lei->{opt}->{jobs} // 1) > 1;
277         push @cmd, '-v' if $lei->{opt}->{verbose};
278         @cmd;
279 }
280
281 sub upr { # feed `git update-ref --stdin -z' verbosely
282         my ($lei, $w, $op, $ref, $oid) = @_;
283         $lei->qerr("# $op $ref $oid") if $lei->{opt}->{verbose};
284         print $w "$op $ref\0$oid\0" or die "print(w): $!";
285 }
286
287 sub fgrp_update {
288         my ($fgrp) = @_;
289         my $srcfh = delete $fgrp->{srcfh} or return;
290         my $dstfh = delete $fgrp->{dstfh} or return;
291         seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
292         seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
293         my %src = map { chomp; split(/\0/) } (<$srcfh>);
294         close $srcfh;
295         my %dst = map { chomp; split(/\0/) } (<$dstfh>);
296         close $dstfh;
297         pipe(my ($r, $w)) or die "pipe: $!";
298         my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
299                 qw(update-ref --stdin -z) ];
300         my $lei = $fgrp->{lei};
301         $lei->qerr("# @$cmd");
302         my $opt = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
303         my $pid = spawn($cmd, undef, $opt);
304         close $r or die "close(r): $!";
305         for my $ref (keys %dst) {
306                 my $new = delete $src{$ref};
307                 my $old = $dst{$ref};
308                 if (defined $new) {
309                         upr($lei, $w, 'update', $ref, $new) if $new ne $old;
310                 } else {
311                         upr($lei, $w, 'delete', $ref, $old);
312                 }
313         }
314         while (my ($ref, $oid) = each %src) {
315                 upr($lei, $w, 'create', $ref, $oid);
316         }
317         close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
318         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $cmd ];
319         do_reap($fgrp);
320 }
321
322 sub pack_refs {
323         my ($self, $git_dir) = @_;
324         do_reap($self);
325         my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
326         $self->{lei}->qerr("# @$cmd");
327         my $opt = { 1 => $self->{lei}->{1}, 2 => $self->{lei}->{2} };
328         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd ];
329 }
330
331 sub fgrp_fetched {
332         my ($fgrp) = @_;
333         return if $fgrp->{dry_run} || !$LIVE;
334         my $rn = $fgrp->{-remote};
335         my %opt = map { $_ => $fgrp->{lei}->{$_} } (0..2);
336         pack_refs($fgrp, $fgrp->{-osdir}); # objstore refs always packed
337
338         my $update_ref = PublicInbox::OnDestroy->new($$, \&fgrp_update, $fgrp);
339
340         my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
341                 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
342                 "refs/remotes/$rn/" ];
343         do_reap($fgrp);
344         open($fgrp->{srcfh}, '+>', undef) or die "open(src): $!";
345         $fgrp->{lei}->qerr("# @$src >SRC");
346         my $pid = spawn($src, undef, { %opt, 1 => $fgrp->{srcfh} });
347         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $src, $update_ref ];
348
349         my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
350                 '--format=%(refname)%00%(objectname)' ];
351         do_reap($fgrp);
352         open($fgrp->{dstfh}, '+>', undef) or die "open(dst): $!";
353         $fgrp->{lei}->qerr("# @$dst >DST");
354         $pid = spawn($dst, undef, { %opt, 1 => $fgrp->{dstfh} });
355         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $dst, $update_ref ];
356 }
357
358 sub fgrp_fetch {
359         my ($fgrp, $fini) = @_;
360         my $cmd = [ @{$fgrp->{-torsocks}}, 'git', "--git-dir=$fgrp->{-osdir}",
361                         fetch_args($fgrp->{lei}, my $opt = {}), '--no-tags',
362                         $fgrp->{-remote} ];
363         $fgrp->{-fini} = $fini;
364         do_reap($fgrp);
365         $fgrp->{lei}->qerr("# @$cmd");
366         return if $fgrp->{dry_run};
367         my $fgrp_fini = PublicInbox::OnDestroy->new($$, \&fgrp_fetched, $fgrp);
368         my $pid = spawn($cmd, undef, $opt);
369         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $cmd, $fgrp_fini ];
370 }
371
372 # keep this idempotent for future use by public-inbox-fetch
373 sub forkgroup_prep {
374         my ($self, $uri) = @_;
375         $self->{-ent} // return;
376         my $os = $self->{-objstore} // return;
377         my $fg = $self->{-ent}->{forkgroup} // return;
378         my $dir = "$os/$fg.git";
379         my @cmd = ('git', "--git-dir=$dir", 'config');
380         my $opt = +{ map { $_ => $self->{lei}->{$_} } (0..2) };
381         if (!-d $dir) {
382                 PublicInbox::Import::init_bare($dir);
383                 for ('repack.useDeltaIslands=true',
384                                 'pack.island=refs/remotes/([^/]+)/') {
385                         run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
386                 }
387         }
388         my $key = $self->{-key} // die 'BUG: no -key';
389         my ($bn) = ($key =~ m{/([a-z0-9_,;=!\+\{\}\|][^/]*)(?:\.git)?\z}i);
390         my $rn = "$bn-".substr(sha256_hex($key), 0, 16);
391         # --no-tags is required to avoid conflicts
392         for ("url=$uri", "fetch=+refs/*:refs/remotes/$rn/*",
393                         'tagopt=--no-tags') {
394                 my @kv = split(/=/, $_, 2);
395                 $kv[0] = "remote.$rn.$kv[0]";
396                 run_die([@cmd, @kv], undef, $opt);
397         }
398         $self->{-do_pack_refs} = 1; # likely coderepo
399         if (!-d $self->{cur_dst}) {
400                 my $alt = File::Spec->rel2abs("$dir/objects");
401                 PublicInbox::Import::init_bare($self->{cur_dst});
402                 my $o = "$self->{cur_dst}/objects";
403                 my $f = "$o/info/alternates";
404                 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
405                 open my $fh, '+>>', $f or die "open($f): $!";
406                 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
407                 chomp(my @cur = <$fh>);
408                 if (!grep(/\A\Q$l\E\z/, @cur)) {
409                         say $fh $l or die "say($f): $!";
410                 }
411                 close $fh or die "close($f): $!";
412                 $f = "$self->{cur_dst}/config";
413                 open $fh, '+>>', $f or die "open:($f): $!";
414                 print $fh <<EOM or die "print($f): $!";
415 ; rely on the "$rn" remote in the
416 ; $fg fork group for fetches
417 ; only uncomment the following iff you detach from fork groups
418 ; [remote "origin"]
419 ;       url = $uri
420 ;       fetch = +refs/*:refs/*
421 ;       mirror = true
422 EOM
423                 close $fh or die "close($f): $!";
424         }
425         bless { %$self, -osdir => $dir, -remote => $rn }, __PACKAGE__;
426 }
427
428 sub clone_v1 {
429         my ($self, $nohang) = @_;
430         my $lei = $self->{lei};
431         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
432         my $uri = URI->new($self->{cur_src} // $self->{src});
433         defined($lei->{opt}->{epoch}) and
434                 die "$uri is a v1 inbox, --epoch is not supported\n";
435         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
436         my $dst = $self->{cur_dst} // $self->{dst};
437         my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
438         my $cmd = [ @{$self->{-torsocks}}, clone_cmd($lei, my $opt = {}),
439                 "$uri", $dst ];
440         my $fgrp = forkgroup_prep($self, $uri);
441         if (!defined($fgrp) && defined($self->{-ent})) {
442                 if (defined(my $ref = $self->{-ent}->{reference})) {
443                         -e "$self->{dst}$ref" and
444                                 push @$cmd, '--reference', "$self->{dst}$ref";
445                 }
446         }
447         $fgrp ? fgrp_fetch($fgrp, $fini) :
448                 start_clone($self, $cmd, $opt, $fini);
449
450         if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
451                                 /\A(?:always|v1)\z/s) {
452                 _get_txt_start($self, '_/text/config/raw', $fini);
453         }
454
455         my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
456         $self->{'txt.description'} = $d if defined $d;
457         (!defined($d) && !$nohang) and
458                 _get_txt_start($self, 'description', $fini);
459
460         $nohang or do_reap($self, 1); # for non-manifest clone
461 }
462
463 sub parse_epochs ($$) {
464         my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
465         $opt_epochs // return; # undef => all epochs
466         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
467         undef($lo) if ($lo // '') eq '';
468         my $re = qr/\A~?[0-9]+\z/;
469         if (@extra || (($lo // '0') !~ $re) ||
470                         (($hi // '0') !~ $re) ||
471                         !(grep(defined, $lo, $hi))) {
472                 die <<EOM;
473 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
474 EOM
475         }
476         my @n = sort { $a <=> $b } keys %$v2_epochs;
477         for (grep(defined, $lo, $hi)) {
478                 if (/\A[0-9]+\z/) {
479                         $_ > $n[-1] and die
480 "`$_' exceeds maximum available epoch ($n[-1])\n";
481                         $_ < $n[0] and die
482 "`$_' is lower than minimum available epoch ($n[0])\n";
483                 } elsif (/\A~([0-9]+)/) {
484                         my $off = -$1 - 1;
485                         $n[$off] // die "`$_' is out of range\n";
486                         $_ = $n[$off];
487                 } else { die "`$_' not understood\n" }
488         }
489         defined($lo) && defined($hi) && $lo > $hi and die
490 "low value (`$lo') exceeds high (`$hi')\n";
491         $lo //= $n[0] if $dotdot;
492         $hi //= $n[-1] if $dotdot;
493         $hi //= $lo;
494         my $want = {};
495         for ($lo..$hi) {
496                 if (defined $v2_epochs->{$_}) {
497                         $want->{$_} = 1;
498                 } else {
499                         warn
500 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
501                 }
502         }
503         $want
504 }
505
506 sub init_placeholder ($$$) {
507         my ($src, $edst, $ent) = @_;
508         PublicInbox::Import::init_bare($edst);
509         my $f = "$edst/config";
510         open my $fh, '>>', $f or die "open($f): $!";
511         print $fh <<EOM or die "print($f): $!";
512 [remote "origin"]
513         url = $src
514         fetch = +refs/*:refs/*
515         mirror = true
516
517 ; This git epoch was created read-only and "public-inbox-fetch"
518 ; will not fetch updates for it unless write permission is added.
519 ; Hint: chmod +w $edst
520 EOM
521         if (defined($ent->{owner})) {
522                 print $fh <<EOM or die "print($f): $!";
523 [gitweb]
524         owner = $ent->{owner}
525 EOM
526         }
527         close $fh or die "close($f): $!";
528         my %map = (head => 'HEAD', description => undef);
529         while (my ($key, $fn) = each %map) {
530                 my $val = $ent->{$key} // next;
531                 $fn //= $key;
532                 $fn = "$edst/$fn";
533                 open $fh, '>', $fn or die "open($fn): $!";
534                 print $fh $val, "\n" or die "print($fn): $!";
535                 close $fh or die "close($fn): $!";
536         }
537 }
538
539 sub reap_cmd { # async, called via SIGCHLD
540         my ($self, $cmd) = @_;
541         my $cerr = $?;
542         $? = 0; # don't let it influence normal exit
543         if ($cerr) {
544                 kill('TERM', keys %$LIVE);
545                 $self->{lei}->child_error($cerr, "@$cmd failed");
546         }
547 }
548
549 sub v1_done { # called via OnDestroy
550         my ($self) = @_;
551         return if $self->{dry_run} || !$LIVE;
552         _write_inbox_config($self);
553         my $dst = $self->{cur_dst} // $self->{dst};
554         if (defined(my $o = $self->{-ent} ? $self->{-ent}->{owner} : undef)) {
555                 run_die([qw(git config -f), "$dst/config", 'gitweb.owner', $o]);
556         }
557         my $o = "$dst/objects";
558         if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
559                 my $base = File::Spec->rel2abs($o);
560                 my @l = <$fh>;
561                 my $ft;
562                 for (@l) {
563                         next unless m!\A/!;
564                         $_ = File::Spec->abs2rel($_, $base);
565                         $ft //= File::Temp->new(TEMPLATE => '.XXXX',
566                                                 DIR => "$o/info");
567                 }
568                 if ($ft) {
569                         print $ft @l or die "print($ft): $!";
570                         $ft->flush or die "flush($ft): $!";
571                         ft_rename($ft, $fn, 0666, $fh);
572                 }
573         }
574         pack_refs($self, $dst) if delete $self->{-do_pack_refs};
575         eval { set_description($self) };
576         warn $@ if $@;
577         return if ($self->{-is_epoch} ||
578                 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
579         write_makefile($dst, 1);
580         index_cloned_inbox($self, 1);
581 }
582
583 sub v2_done { # called via OnDestroy
584         my ($self) = @_;
585         return if $self->{dry_run} || !$LIVE;
586         my $dst = $self->{cur_dst} // $self->{dst};
587         require PublicInbox::Lock;
588         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
589         my $lck = $lk->lock_for_scope($$);
590         _write_inbox_config($self);
591         require PublicInbox::MultiGit;
592         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
593         $mg->fill_alternates;
594         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
595         for my $edst (@{delete($self->{-read_only}) // []}) {
596                 my @st = stat($edst) or die "stat($edst): $!";
597                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
598         }
599         write_makefile($dst, 2);
600         undef $lck; # unlock
601         eval { set_description($self) };
602         warn $@ if $@;
603         index_cloned_inbox($self, 2);
604 }
605
606 sub clone_v2_prep ($$;$) {
607         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
608         my $lei = $self->{lei};
609         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
610         my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
611         $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
612         my $dst = $self->{cur_dst} // $self->{dst};
613         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
614         my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
615         delete $task->{todo}; # $self->{todo} still exists
616         my (@skip, $desc);
617         my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
618         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
619                 my ($uri, $key) = @{$v2_epochs->{$nr}};
620                 my $src = $uri->as_string;
621                 my $edst = $dst;
622                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
623 failed to extract epoch number from $src
624
625                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
626                 $edst .= "/git/$nr.git";
627                 my $ent;
628                 if ($m) {
629                         $ent = $m->{$key} //
630                                 die("BUG: `$key' not in manifest.js.gz");
631                         if (defined(my $d = $ent->{description})) {
632                                 $d =~ s/ \[epoch [0-9]+\]\z//s;
633                                 $desc = $d;
634                         }
635                 }
636                 if (!$want || $want->{$nr}) {
637                         my $etask = bless { %$task, -key => $key }, __PACKAGE__;
638                         $etask->{-ent} = $ent; # may have {reference}
639                         $etask->{cur_src} = $src;
640                         $etask->{cur_dst} = $edst;
641                         $etask->{-is_epoch} = $fini;
642                         my $ref = $ent->{reference} // '';
643                         push @{$self->{todo}->{$ref}}, $etask;
644                         $self->{any_want}->{$key} = 1;
645                 } else { # create a placeholder so users only need to chmod +w
646                         init_placeholder($src, $edst, $ent);
647                         push @{$task->{-read_only}}, $edst;
648                         push @skip, $key;
649                 }
650         }
651         # filter out the epochs we skipped
652         $self->{-culled_manifest} = 1 if $m && delete(@$m{@skip});
653
654         (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
655
656         $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
657                 _get_txt_start($task, '_/text/config/raw', $fini);
658
659         defined($desc) ? ($task->{'txt.description'} = $desc) :
660                 _get_txt_start($task, 'description', $fini);
661 }
662
663 sub decode_manifest ($$$) {
664         my ($fh, $fn, $uri) = @_;
665         my $js;
666         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
667         gunzip(\$gz => \$js, MultiStream => 1) or
668                 die "gunzip($uri): $GunzipError\n";
669         my $m = eval { PublicInbox::Config->json->decode($js) };
670         die "$uri: error decoding `$js': $@\n" if $@;
671         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
672         $m;
673 }
674
675 sub multi_inbox ($$$) {
676         my ($self, $path, $m) = @_;
677         my $incl = $self->{lei}->{opt}->{include};
678         my $excl = $self->{lei}->{opt}->{exclude};
679
680         # assuming everything not v2 is v1, for now
681         my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
682         my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
683         my $v2 = {};
684
685         for (@v2_epochs) {
686                 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
687                 push @{$v2->{$1}}, $_;
688         }
689         my $n = scalar(keys %$v2) + scalar(@v1);
690         my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
691         if (defined $incl) {
692                 my $re = '(?:'.join('\\z|', map {
693                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
694                         } @$incl).'\\z)';
695                 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
696                 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
697                 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
698                 @v1 = grep(/$re/, @v1);
699         }
700         if (defined $excl) {
701                 my $re = '(?:'.join('\\z|', map {
702                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
703                         } @$excl).'\\z)';
704                 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
705                 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
706                 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
707                 @v1 = grep(!/$re/, @v1);
708         }
709         my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
710         $ret->{v1} = \@v1 if @v1;
711         $ret->{v2} = $v2 if keys %$v2;
712         $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
713                                 join("\n\t", sort @orig)
714                         : "Nothing available to clone\n";
715         my $path_pfx = '';
716
717         # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
718         if (@v2_epochs) {
719                 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
720                                 @v2_epochs) == @v2_epochs) {
721                         $$path =~ s!\A(/[^/]+)/!/! or last;
722                         $path_pfx .= $1;
723                 }
724         } elsif (@v1) {
725                 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
726                         $path_pfx .= $1;
727                 }
728         }
729         ($path_pfx, $n, $ret);
730 }
731
732 sub clone_all {
733         my ($self, $m) = @_;
734         my $todo = delete $self->{todo};
735         my $nodep = delete $todo->{''};
736
737         # do not download unwanted deps
738         my $any_want = delete $self->{any_want};
739         my @unwanted = grep { !$any_want->{$_} } keys %$todo;
740         my @nodep = delete(@$todo{@unwanted});
741         push(@$nodep, @$_) for @nodep;
742
743         # handle no-dependency repos, first
744         for (@$nodep) {
745                 clone_v1($_, 1);
746                 return if $self->{lei}->{child_error};
747         }
748         # resolve references, deepest, first:
749         while (scalar keys %$todo) {
750                 for my $x (keys %$todo) {
751                         my ($nr, $nxt);
752                         # resolve multi-level references
753                         while ($m && defined($nxt = $m->{$x}->{reference})) {
754                                 exists($todo->{$nxt}) or last;
755                                 die <<EOM if ++$nr > 1000;
756 E: dependency loop detected (`$x' => `$nxt')
757 EOM
758                                 $x = $nxt;
759                         }
760                         my $y = delete $todo->{$x} // next; # already done
761                         for (@$y) {
762                                 clone_v1($_, 1);
763                                 return if $self->{lei}->{child_error};
764                         }
765                         last; # restart %$todo iteration
766                 }
767         }
768         do_reap($self, 1);
769 }
770
771 sub dump_manifest ($$) {
772         my ($m, $ft) = @_;
773         # write the smaller manifest if epochs were skipped so
774         # users won't have to delete manifest if they +w an
775         # epoch they no longer want to skip
776         my $json = PublicInbox::Config->json->encode($m);
777         my $mtime = (stat($ft))[9];
778         seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
779         truncate($ft, 0) or die "truncate($ft): $!";
780         gzip(\$json => $ft) or die "gzip($ft): $GzipError";
781         $ft->flush or die "flush($ft): $!";
782         utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
783 }
784
785 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
786 sub try_manifest {
787         my ($self) = @_;
788         my $uri = URI->new($self->{src});
789         my $lei = $self->{lei};
790         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
791         my $path = $uri->path;
792         chop($path) eq '/' or die "BUG: $uri not canonicalized";
793         $uri->path($path . '/manifest.js.gz');
794         my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX',
795                                 UNLINK => 1, TMPDIR => 1, SUFFIX => '.tmp');
796         my $cmd = $curl->for_uri($lei, $uri, qw(-f -R -o), $ft->filename);
797         my %opt = map { $_ => $lei->{$_} } (0..2);
798         my $cerr = run_reap($lei, $cmd, \%opt);
799         if ($cerr) {
800                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
801                 return $lei->child_error($cerr, "@$cmd failed");
802         }
803         my $m = eval { decode_manifest($ft, $ft, $uri) };
804         if ($@) {
805                 warn $@;
806                 return try_scrape($self);
807         }
808         my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
809         return $lei->child_error(1, $multi) if !ref($multi);
810         my $v2 = delete $multi->{v2};
811         local $self->{todo} = {};
812         if ($v2) {
813                 for my $name (sort keys %$v2) {
814                         my $epochs = delete $v2->{$name};
815                         my %v2_epochs = map {
816                                 $uri->path($n > 1 ? $path_pfx.$path.$_
817                                                 : $path_pfx.$_);
818                                 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
819                                 $e // die "no [0-9]+\.git in `$uri'";
820                                 $e => [ $uri->clone, $_ ];
821                         } @$epochs;
822                         ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
823                                 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
824                         local $self->{cur_src} = $1;
825                         local $self->{cur_dst} = $self->{dst};
826                         if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
827                                                         git/[0-9]+\.git\z!x) {
828                                 $self->{cur_dst} .= "/$1";
829                         }
830                         index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
831 E: `$self->{cur_dst}' must not contain newline
832 EOM
833                         clone_v2_prep($self, \%v2_epochs, $m);
834                         return if $self->{lei}->{child_error};
835                 }
836         }
837         if (my $v1 = delete $multi->{v1}) {
838                 my $p = $path_pfx.$path;
839                 chop($p) if substr($p, -1, 1) eq '/';
840                 $uri->path($p);
841                 for my $name (@$v1) {
842                         my $task = bless { %$self }, __PACKAGE__;
843                         $task->{-ent} = $m->{$name} //
844                                         die("BUG: no `$name' in manifest");
845                         $task->{cur_src} = "$uri";
846                         $task->{cur_dst} = $task->{dst};
847                         $task->{-key} = $name;
848                         if ($n > 1) {
849                                 $task->{cur_dst} .= $name;
850                                 $task->{cur_src} .= $name;
851                         }
852                         index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
853 E: `$task->{cur_dst}' must not contain newline
854 EOM
855                         $task->{cur_src} .= '/';
856                         my $dep = $task->{-ent}->{reference} // '';
857                         push @{$self->{todo}->{$dep}}, $task; # for clone_all
858                         $self->{any_want}->{$name} = 1;
859                 }
860         }
861         delete local $lei->{opt}->{epoch} if defined($v2);
862         clone_all($self, $m);
863         return if $self->{lei}->{child_error} || $self->{dry_run};
864
865         # set by clone_v2_prep/-I/--exclude
866         dump_manifest($m => $ft) if delete $self->{-culled_manifest};
867         ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
868         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
869 }
870
871 sub start_clone_url {
872         my ($self) = @_;
873         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
874         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
875 }
876
877 sub do_mirror { # via wq_io_do or public-inbox-clone
878         my ($self) = @_;
879         my $lei = $self->{lei};
880         umask($lei->{client_umask}) if defined $lei->{client_umask};
881         eval {
882                 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
883                 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
884 --inbox-config must be one of `always', `v2', `v1', or `never'
885
886                 if (defined(my $os = $lei->{opt}->{objstore})) {
887                         $os = 'objstore' if $os eq ''; # --objstore w/o args
888                         $os = "$self->{dst}/$os" if $os !~ m!\A/!;
889                         $self->{-objstore} = $os;
890                 }
891                 local $LIVE;
892                 my $iv = $lei->{opt}->{'inbox-version'} //
893                         return start_clone_url($self);
894                 return clone_v1($self) if $iv == 1;
895                 die "bad --inbox-version=$iv\n" if $iv != 2;
896                 die <<EOM if $self->{src} !~ m!://!;
897 cloning local v2 inboxes not supported
898 EOM
899                 try_scrape($self, 1);
900         };
901         $lei->fail($@) if $@;
902 }
903
904 sub start {
905         my ($cls, $lei, $src, $dst) = @_;
906         my $self = bless { src => $src, dst => $dst }, $cls;
907         $lei->request_umask;
908         my ($op_c, $ops) = $lei->workers_start($self, 1);
909         $lei->{wq1} = $self;
910         $self->wq_io_do('do_mirror', []);
911         $self->wq_close;
912         $lei->wait_wq_events($op_c, $ops);
913 }
914
915 sub ipc_atfork_child {
916         my ($self) = @_;
917         $self->{lei}->_lei_atfork_child;
918         $self->SUPER::ipc_atfork_child;
919 }
920
921 sub write_makefile {
922         my ($dir, $ibx_ver) = @_;
923         my $f = "$dir/Makefile";
924         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
925                 print $fh <<EOM or die "print($f) $!";
926 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
927 # manpage for more information on the format.  This Makefile is
928 # intended as a familiar wrapper for users unfamiliar with
929 # public-inbox-* commands.
930 #
931 # See the respective manpages for public-inbox-fetch(1),
932 # public-inbox-index(1), etc for more information on
933 # some of the commands used by this Makefile.
934 #
935 # This Makefile will not be modified nor read by public-inbox,
936 # so you may edit it freely with your own convenience targets
937 # and notes.  public-inbox-fetch will recreate it if removed.
938 EOM
939                 print $fh <<'EOM' or die "print($f): $!";
940 # the default target:
941 help :
942         @echo Common targets:
943         @echo '    make fetch        - fetch from remote git repostorie(s)'
944         @echo '    make update       - fetch and update index '
945         @echo
946         @echo Rarely needed targets:
947         @echo '    make reindex      - may be needed for new features/bugfixes'
948         @echo '    make compact      - rewrite Xapian storage to save space'
949         @echo '    make index        - initial index after clone
950
951 fetch :
952         public-inbox-fetch
953 update :
954         @if ! public-inbox-fetch --exit-code; \
955         then \
956                 c=$$?; \
957                 test $$c -eq 127 && exit 0; \
958                 exit $$c; \
959         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
960         then \
961                 public-inbox-index; \
962         else \
963                 echo 'public-inbox index not initialized'; \
964                 echo 'see public-inbox-index(1) man page'; \
965         fi
966 index :
967         public-inbox-index
968 reindex :
969         public-inbox-index --reindex
970 compact :
971         public-inbox-compact
972
973 .PHONY : help fetch update index reindex compact
974 EOM
975                 close $fh or die "close($f): $!";
976         } else {
977                 die "open($f): $!" unless $!{EEXIST};
978         }
979 }
980
981 1;