]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
lei add-external --mirror: respect client umask
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) 2021 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 strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::IPC);
9 use PublicInbox::Config;
10 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
11 use IO::Compress::Gzip qw(gzip $GzipError);
12 use PublicInbox::Spawn qw(popen_rd spawn run_die);
13 use File::Temp ();
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
15 use Carp qw(croak);
16
17 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
18         my ($arg, $pid) = @_;
19         my ($mrr, $lei) = @$arg;
20         my $f = "$mrr->{dst}/mirror.done";
21         if ($?) {
22                 $lei->child_error($?);
23         } elsif (!unlink($f)) {
24                 warn("unlink($f): $!\n") unless $!{ENOENT};
25         } else {
26                 if ($lei->{cmd} ne 'public-inbox-clone') {
27                         $lei->lazy_cb('add-external', '_finish_'
28                                         )->($lei, $mrr->{dst});
29                 }
30                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
31         }
32         $lei->dclose;
33 }
34
35 # for old installations without manifest.js.gz
36 sub try_scrape {
37         my ($self) = @_;
38         my $uri = URI->new($self->{src});
39         my $lei = $self->{lei};
40         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
41         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
42         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
43         my $fh = popen_rd($cmd, undef, $opt);
44         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
45         close($fh) or return $lei->child_error($?, "@$cmd failed");
46
47         # we grep with URL below, we don't want Subject/From headers
48         # making us clone random URLs
49         my @html = split(/<hr>/, $html);
50         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
51         my $url = $uri->as_string;
52         chop($url) eq '/' or die "BUG: $uri not canonicalized";
53
54         # since this is for old instances w/o manifest.js.gz, try v1 first
55         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
56         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
57                 my %v2_epochs = map {
58                         my ($n) = (m!/([0-9]+)\z!);
59                         $n => URI->new($_)
60                 } @v2_urls; # uniq
61                 return clone_v2($self, \%v2_epochs);
62         }
63
64         # filter out common URLs served by WWW (e.g /$MSGID/T/)
65         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
66                         grep(m!\A\Q$url\E/*\z!, @urls)) {
67                 die <<"";
68 E: confused by scraping <$uri>, did you mean <$url>?
69
70         }
71         @urls and die <<"";
72 E: confused by scraping <$uri>, got ambiguous results:
73 @urls
74
75         die "E: scraping <$uri> revealed nothing\n";
76 }
77
78 sub clone_cmd {
79         my ($lei, $opt) = @_;
80         my @cmd = qw(git);
81         $opt->{$_} = $lei->{$_} for (0..2);
82         # we support "-c $key=$val" for arbitrary git config options
83         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
84         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
85         push @cmd, qw(clone --mirror);
86         push @cmd, '-q' if $lei->{opt}->{quiet};
87         push @cmd, '-v' if $lei->{opt}->{verbose};
88         # XXX any other options to support?
89         # --reference is tricky with multiple epochs...
90         @cmd;
91 }
92
93 sub ft_rename ($$$) {
94         my ($ft, $dst, $open_mode) = @_;
95         my $fn = $ft->filename;
96         my @st = stat($dst);
97         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
98         chmod($mode, $ft) or croak "E: chmod $fn: $!";
99         rename($fn, $dst) or croak "E: rename($fn => $ft): $!";
100         $ft->unlink_on_destroy(0);
101 }
102
103 sub _get_txt { # non-fatal
104         my ($self, $endpoint, $file, $mode) = @_;
105         my $uri = URI->new($self->{src});
106         my $lei = $self->{lei};
107         my $path = $uri->path;
108         chop($path) eq '/' or die "BUG: $uri not canonicalized";
109         $uri->path("$path/$endpoint");
110         my $ft = File::Temp->new(TEMPLATE => "$file-XXXX", DIR => $self->{dst});
111         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
112         my $cmd = $self->{curl}->for_uri($lei, $uri,
113                                         qw(--compressed -R -o), $ft->filename);
114         my $cerr = run_reap($lei, $cmd, $opt);
115         return "$uri missing" if ($cerr >> 8) == 22;
116         return "# @$cmd failed (non-fatal)" if $cerr;
117         ft_rename($ft, "$self->{dst}/$file", $mode);
118         undef; # success
119 }
120
121 # tries the relatively new /$INBOX/_/text/config/raw endpoint
122 sub _try_config {
123         my ($self) = @_;
124         my $dst = $self->{dst};
125         if (!-d $dst || !mkdir($dst)) {
126                 require File::Path;
127                 File::Path::mkpath($dst);
128                 -d $dst or die "mkpath($dst): $!\n";
129         }
130         my $err = _get_txt($self,
131                         qw(_/text/config/raw inbox.config.example), 0444);
132         return warn($err, "\n") if $err;
133         my $f = "$self->{dst}/inbox.config.example";
134         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
135         my $ibx = $self->{ibx} = {};
136         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
137                 for (qw(address newsgroup nntpmirror)) {
138                         $ibx->{$_} = $cfg->{"$sec.$_"};
139                 }
140         }
141 }
142
143 sub set_description ($) {
144         my ($self) = @_;
145         my $f = "$self->{dst}/description";
146         open my $fh, '+>>', $f or die "open($f): $!";
147         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
148         chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
149         if ($d eq '($INBOX_DIR/description missing)' ||
150                         $d =~ /^Unnamed repository/ || $d !~ /\S/) {
151                 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
152                 truncate($fh, 0) or die "truncate($f): $!";
153                 print $fh "mirror of $self->{src}\n" or die "print($f): $!";
154                 close $fh or die "close($f): $!";
155         }
156 }
157
158 sub index_cloned_inbox {
159         my ($self, $iv) = @_;
160         my $lei = $self->{lei};
161         my $err = _get_txt($self, qw(description description), 0666);
162         warn($err, "\n") if $err; # non fatal
163         eval { set_description($self) };
164         warn $@ if $@;
165
166         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
167         # lei is useless without Xapian + SQLite
168         if ($lei->{cmd} ne 'public-inbox-clone') {
169                 my $ibx = delete($self->{ibx}) // {
170                         address => [ 'lei@example.com' ],
171                         version => $iv,
172                 };
173                 $ibx->{inboxdir} = $self->{dst};
174                 PublicInbox::Inbox->new($ibx);
175                 PublicInbox::InboxWritable->new($ibx);
176                 my $opt = {};
177                 for my $sw ($lei->index_opt) {
178                         my ($k) = ($sw =~ /\A([\w-]+)/);
179                         $opt->{$k} = $lei->{opt}->{$k};
180                 }
181                 # force synchronous dwaitpid for v2:
182                 local $PublicInbox::DS::in_loop = 0;
183                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
184                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
185                 local %ENV = (%ENV, %$env) if $env;
186                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
187                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
188         }
189         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
190 }
191
192 sub run_reap {
193         my ($lei, $cmd, $opt) = @_;
194         $lei->qerr("# @$cmd");
195         $opt->{pgid} = 0 if $lei->{sock};
196         my $pid = spawn($cmd, undef, $opt);
197         my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
198         waitpid($pid, 0) == $pid or die "waitpid @$cmd: $!";
199         @$reap = (); # cancel reap
200         my $ret = $?;
201         $? = 0; # don't let it influence normal exit
202         $ret;
203 }
204
205 sub clone_v1 {
206         my ($self) = @_;
207         my $lei = $self->{lei};
208         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
209         my $uri = URI->new($self->{src});
210         defined($lei->{opt}->{epoch}) and
211                 die "$uri is a v1 inbox, --epoch is not supported\n";
212         my $pfx = $curl->torsocks($lei, $uri) or return;
213         my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
214                         $uri->as_string, $self->{dst} ];
215         my $cerr = run_reap($lei, $cmd, $opt);
216         return $lei->child_error($cerr, "@$cmd failed") if $cerr;
217         _try_config($self);
218         write_makefile($self->{dst}, 1);
219         index_cloned_inbox($self, 1);
220 }
221
222 sub parse_epochs ($$) {
223         my ($opt_epochs, $v2_epochs) = @_; # $epcohs "LOW..HIGH"
224         $opt_epochs // return; # undef => all epochs
225         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
226         undef($lo) if ($lo // '') eq '';
227         my $re = qr/\A~?[0-9]+\z/;
228         if (@extra || (($lo // '0') !~ $re) ||
229                         (($hi // '0') !~ $re) ||
230                         !(grep(defined, $lo, $hi))) {
231                 die <<EOM;
232 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
233 EOM
234         }
235         my @n = sort { $a <=> $b } keys %$v2_epochs;
236         for (grep(defined, $lo, $hi)) {
237                 if (/\A[0-9]+\z/) {
238                         $_ > $n[-1] and die
239 "`$_' exceeds maximum available epoch ($n[-1])\n";
240                         $_ < $n[0] and die
241 "`$_' is lower than minimum available epoch ($n[0])\n";
242                 } elsif (/\A~([0-9]+)/) {
243                         my $off = -$1 - 1;
244                         $n[$off] // die "`$_' is out of range\n";
245                         $_ = $n[$off];
246                 } else { die "`$_' not understood\n" }
247         }
248         defined($lo) && defined($hi) && $lo > $hi and die
249 "low value (`$lo') exceeds high (`$hi')\n";
250         $lo //= $n[0] if $dotdot;
251         $hi //= $n[-1] if $dotdot;
252         $hi //= $lo;
253         my $want = {};
254         for ($lo..$hi) {
255                 if (defined $v2_epochs->{$_}) {
256                         $want->{$_} = 1;
257                 } else {
258                         warn
259 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
260                 }
261         }
262         $want
263 }
264
265 sub init_placeholder ($$) {
266         my ($src, $edst) = @_;
267         PublicInbox::Import::init_bare($edst);
268         my $f = "$edst/config";
269         open my $fh, '>>', $f or die "open($f): $!";
270         print $fh <<EOM or die "print($f): $!";
271 [remote "origin"]
272         url = $src
273         fetch = +refs/*:refs/*
274         mirror = true
275
276 ; This git epoch was created read-only and "public-inbox-fetch"
277 ; will not fetch updates for it unless write permission is added.
278 EOM
279         close $fh or die "close:($f): $!";
280 }
281
282 sub clone_v2 ($$;$) {
283         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
284         my $lei = $self->{lei};
285         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
286         my $pfx = $curl->torsocks($lei, (values %$v2_epochs)[0]) or return;
287         my $dst = $self->{dst};
288         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
289         my (@src_edst, @read_only, @skip_nr);
290         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
291                 my $uri = $v2_epochs->{$nr};
292                 my $src = $uri->as_string;
293                 my $edst = $dst;
294                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
295 failed to extract epoch number from $src
296
297                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
298                 $edst .= "/git/$nr.git";
299                 if (!$want || $want->{$nr}) {
300                         push @src_edst, $src, $edst;
301                 } else { # create a placeholder so users only need to chmod +w
302                         init_placeholder($src, $edst);
303                         push @read_only, $edst;
304                         push @skip_nr, $nr;
305                 }
306         }
307         if (@skip_nr) { # filter out the epochs we skipped
308                 my $re = join('|', @skip_nr);
309                 my @del = grep(m!/git/$re\.git\z!, keys %$m);
310                 delete @$m{@del};
311                 $self->{-culled_manifest} = 1;
312         }
313         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
314         _try_config($self);
315         my $on_destroy = $lk->lock_for_scope($$);
316         my @cmd = clone_cmd($lei, my $opt = {});
317         while (my ($src, $edst) = splice(@src_edst, 0, 2)) {
318                 my $cmd = [ @$pfx, @cmd, $src, $edst ];
319                 my $cerr = run_reap($lei, $cmd, $opt);
320                 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
321         }
322         require PublicInbox::MultiGit;
323         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
324         $mg->fill_alternates;
325         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
326         for my $edst (@read_only) {
327                 my @st = stat($edst) or die "stat($edst): $!";
328                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
329         }
330         write_makefile($self->{dst}, 2);
331         undef $on_destroy; # unlock
332         index_cloned_inbox($self, 2);
333 }
334
335 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
336 sub deduce_epochs ($$) {
337         my ($m, $path) = @_;
338         my ($v1_ent, @v2_epochs);
339         my $path_pfx = '';
340         $path =~ s!/+\z!!;
341         do {
342                 $v1_ent = $m->{$path};
343                 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
344         } while (!defined($v1_ent) && !@v2_epochs &&
345                 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
346         ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
347 }
348
349 sub decode_manifest ($$$) {
350         my ($fh, $fn, $uri) = @_;
351         my $js;
352         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
353         gunzip(\$gz => \$js, MultiStream => 1) or
354                 die "gunzip($uri): $GunzipError\n";
355         my $m = eval { PublicInbox::Config->json->decode($js) };
356         die "$uri: error decoding `$js': $@\n" if $@;
357         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
358         $m;
359 }
360
361 sub try_manifest {
362         my ($self) = @_;
363         my $uri = URI->new($self->{src});
364         my $lei = $self->{lei};
365         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
366         my $path = $uri->path;
367         chop($path) eq '/' or die "BUG: $uri not canonicalized";
368         $uri->path($path . '/manifest.js.gz');
369         my $pdir = $lei->rel2abs($self->{dst});
370         $pdir =~ s!/[^/]+/?\z!!;
371         my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
372                                 UNLINK => 1, DIR => $pdir, SUFFIX => '.tmp');
373         my $fn = $ft->filename;
374         my ($bn) = ($fn =~ m!/([^/]+)\z!);
375         my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $bn);
376         my $opt = { -C => $pdir };
377         $opt->{$_} = $lei->{$_} for (0..2);
378         my $cerr = run_reap($lei, $cmd, $opt);
379         if ($cerr) {
380                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
381                 return $lei->child_error($cerr, "@$cmd failed");
382         }
383         my $m = eval { decode_manifest($ft, $fn, $uri) };
384         if ($@) {
385                 warn $@;
386                 return try_scrape($self);
387         }
388         my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
389         if (@v2_epochs) {
390                 # It may be possible to have v1 + v2 in parallel someday:
391                 warn(<<EOM) if defined $v1_path;
392 # `$v1_path' appears to be a v1 inbox while v2 epochs exist:
393 # @v2_epochs
394 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
395 EOM
396                 my %v2_epochs = map {
397                         $uri->path($path_pfx.$_);
398                         my ($n) = ("$uri" =~ m!/([0-9]+)\.git\z!);
399                         $n => $uri->clone
400                 } @v2_epochs;
401                 clone_v2($self, \%v2_epochs, $m);
402         } elsif (defined $v1_path) {
403                 clone_v1($self);
404         } else {
405                 die "E: confused by <$uri>, possible matches:\n\t",
406                         join(', ', sort keys %$m), "\n";
407         }
408         if (delete $self->{-culled_manifest}) { # set by clone_v2
409                 # write the smaller manifest if epochs were skipped so
410                 # users won't have to delete manifest if they +w an
411                 # epoch they no longer want to skip
412                 my $json = PublicInbox::Config->json->encode($m);
413                 gzip(\$json => $fn) or die "gzip: $GzipError";
414         }
415         ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
416 }
417
418 sub start_clone_url {
419         my ($self) = @_;
420         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
421         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
422 }
423
424 sub do_mirror { # via wq_io_do
425         my ($self) = @_;
426         my $lei = $self->{lei};
427         umask($lei->{client_umask}) if defined $lei->{client_umask};
428         eval {
429                 my $iv = $lei->{opt}->{'inbox-version'};
430                 if (defined $iv) {
431                         return clone_v1($self) if $iv == 1;
432                         return try_scrape($self) if $iv == 2;
433                         die "bad --inbox-version=$iv\n";
434                 }
435                 return start_clone_url($self) if $self->{src} =~ m!://!;
436                 die "TODO: cloning local directories not supported, yet";
437         };
438         $lei->fail($@) if $@;
439 }
440
441 sub start {
442         my ($cls, $lei, $src, $dst) = @_;
443         my $self = bless { src => $src, dst => $dst }, $cls;
444         if ($src =~ m!https?://!) {
445                 require URI;
446                 require PublicInbox::LeiCurl;
447         }
448         require PublicInbox::Lock;
449         require PublicInbox::Inbox;
450         require PublicInbox::Admin;
451         require PublicInbox::InboxWritable;
452         $lei->request_umask;
453         my ($op_c, $ops) = $lei->workers_start($self, 1);
454         $lei->{wq1} = $self;
455         $self->wq_io_do('do_mirror', []);
456         $self->wq_close(1);
457         $lei->wait_wq_events($op_c, $ops);
458 }
459
460 sub ipc_atfork_child {
461         my ($self) = @_;
462         $self->{lei}->_lei_atfork_child;
463         $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
464         $self->SUPER::ipc_atfork_child;
465 }
466
467 sub write_makefile {
468         my ($dir, $ibx_ver) = @_;
469         my $f = "$dir/Makefile";
470         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
471                 print $fh <<EOM or die "print($f) $!";
472 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
473 # manpage for more information on the format.  This Makefile is
474 # intended as a familiar wrapper for users unfamiliar with
475 # public-inbox-* commands.
476 #
477 # See the respective manpages for public-inbox-fetch(1),
478 # public-inbox-index(1), etc for more information on
479 # some of the commands used by this Makefile.
480 #
481 # This Makefile will not be modified nor read by public-inbox,
482 # so you may edit it freely with your own convenience targets
483 # and notes.  public-inbox-fetch will recreate it if removed.
484 EOM
485                 print $fh <<'EOM' or die "print($f): $!";
486 # the default target:
487 help :
488         @echo Common targets:
489         @echo '    make fetch        - fetch from remote git repostorie(s)'
490         @echo '    make update       - fetch and update index '
491         @echo
492         @echo Rarely needed targets:
493         @echo '    make reindex      - may be needed for new features/bugfixes'
494         @echo '    make compact      - rewrite Xapian storage to save space'
495
496 fetch :
497         public-inbox-fetch
498 update :
499         @if ! public-inbox-fetch --exit-code; \
500         then \
501                 c=$$?; \
502                 test $$c -eq 127 && exit 0; \
503                 exit $$c; \
504         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
505         then \
506                 public-inbox-index; \
507         else \
508                 echo 'public-inbox index not initialized'; \
509                 echo 'see public-inbox-index(1) man page'; \
510         fi
511 reindex :
512         public-inbox-index --reindex
513 compact :
514         public-inbox-compact
515
516 .PHONY : help fetch update reindex compact
517 EOM
518                 close $fh or die "close($f): $!";
519         } else {
520                 die "open($f): $!" unless $!{EEXIST};
521         }
522 }
523
524 1;