]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Fetch.pm
fetch: support running as root
[public-inbox.git] / lib / PublicInbox / Fetch.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 # Wrapper to "git fetch" remote public-inboxes
4 package PublicInbox::Fetch;
5 use strict;
6 use v5.10.1;
7 use parent qw(PublicInbox::IPC);
8 use URI ();
9 use PublicInbox::Spawn qw(popen_rd run_die spawn);
10 use PublicInbox::Admin;
11 use PublicInbox::LEI;
12 use PublicInbox::LeiCurl;
13 use PublicInbox::LeiMirror;
14 use File::Temp ();
15 use PublicInbox::Config;
16 use IO::Compress::Gzip qw(gzip $GzipError);
17
18 sub new { bless {}, __PACKAGE__ }
19
20 sub fetch_args ($$) {
21         my ($lei, $opt) = @_;
22         my @cmd; # (git --git-dir=...) to be added by caller
23         $opt->{$_} = $lei->{$_} for (0..2);
24         # we support "-c $key=$val" for arbitrary git config options
25         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
26         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
27         push @cmd, 'fetch';
28         push @cmd, '-q' if $lei->{opt}->{quiet};
29         push @cmd, '-v' if $lei->{opt}->{verbose};
30         @cmd;
31 }
32
33 sub remote_url ($$) {
34         my ($lei, $dir) = @_; # TODO: support non-"origin"?
35         my $cmd = [ qw(git config remote.origin.url) ];
36         my $fh = popen_rd($cmd, undef, { -C => $dir, 2 => $lei->{2} });
37         my $url = <$fh>;
38         close $fh or return;
39         $url =~ s!/*\n!!s;
40         $url;
41 }
42
43 sub do_manifest ($$$) {
44         my ($lei, $dir, $ibx_uri) = @_;
45         my $muri = URI->new("$ibx_uri/manifest.js.gz");
46         my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
47                                 UNLINK => 1, DIR => $dir, SUFFIX => '.tmp');
48         my $fn = $ft->filename;
49         my $mf = "$dir/manifest.js.gz";
50         my $m0; # current manifest.js.gz contents
51         if (open my $fh, '<', $mf) {
52                 $m0 = eval {
53                         PublicInbox::LeiMirror::decode_manifest($fh, $mf, $mf)
54                 };
55                 $lei->err($@) if $@;
56         }
57         my ($bn) = ($fn =~ m!/([^/]+)\z!);
58         my $curl_cmd = $lei->{curl}->for_uri($lei, $muri, qw(-R -o), $bn);
59         my $opt = { -C => $dir };
60         $opt->{$_} = $lei->{$_} for (0..2);
61         my $cerr = PublicInbox::LeiMirror::run_reap($lei, $curl_cmd, $opt);
62         if ($cerr) {
63                 return [ 404, $muri ] if ($cerr >> 8) == 22; # 404 Missing
64                 $lei->child_error($cerr, "@$curl_cmd failed");
65                 return;
66         }
67         my $m1 = eval {
68                 PublicInbox::LeiMirror::decode_manifest($ft, $fn, $muri);
69         } or return [ 404, $muri ];
70         my $mdiff = { %$m1 };
71
72         # filter out unchanged entries.  We check modified, too, since
73         # fingerprints are SHA-1, so there's a teeny chance they'll collide
74         while (my ($k, $v0) = each %{$m0 // {}}) {
75                 my $cur = $m1->{$k} // next;
76                 my $f0 = $v0->{fingerprint} // next;
77                 my $f1 = $cur->{fingerprint} // next;
78                 my $t0 = $v0->{modified} // next;
79                 my $t1 = $cur->{modified} // next;
80                 delete($mdiff->{$k}) if $f0 eq $f1 && $t0 == $t1;
81         }
82         unless (keys %$mdiff) {
83                 $lei->child_error(127 << 8) if $lei->{opt}->{'exit-code'};
84                 return;
85         }
86         my (undef, $v1_path, @v2_epochs) =
87                 PublicInbox::LeiMirror::deduce_epochs($mdiff, $ibx_uri->path);
88         [ 200, $muri, $v1_path, \@v2_epochs, $ft, $mf, $m1 ];
89 }
90
91 sub get_fingerprint2 {
92         my ($git_dir) = @_;
93         require Digest::SHA;
94         my $rd = popen_rd([qw(git show-ref)], undef, { -C => $git_dir });
95         Digest::SHA::sha256(do { local $/; <$rd> });
96 }
97
98 sub writable_dir ($) {
99         my ($dir) = @_;
100         return unless -d $dir && -w _;
101         my @st = stat($dir);
102         $st[2] & 0222; # any writable bits set? (in case of root)
103 }
104
105 sub do_fetch { # main entry point
106         my ($cls, $lei, $cd) = @_;
107         my $ibx_ver;
108         $lei->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
109         my $dir = PublicInbox::Admin::resolve_inboxdir($cd, \$ibx_ver);
110         my ($ibx_uri, @git_dir, @epochs, $mg, @new_epoch, $skip);
111         if ($ibx_ver == 1) {
112                 my $url = remote_url($lei, $dir) //
113                         die "E: $dir missing remote.origin.url\n";
114                 $ibx_uri = URI->new($url);
115         } else { # v2:
116                 require PublicInbox::MultiGit;
117                 $mg = PublicInbox::MultiGit->new($dir, 'all.git', 'git');
118                 @epochs = $mg->git_epochs;
119                 my ($git_url, $epoch);
120                 for my $nr (@epochs) { # try newest epoch, first
121                         my $edir = "$dir/git/$nr.git";
122                         if (!writable_dir($edir)) {
123                                 $skip->{$nr} = 1;
124                                 next;
125                         }
126                         next if defined $git_url;
127                         if (defined(my $url = remote_url($lei, $edir))) {
128                                 $git_url = $url;
129                                 $epoch = $nr;
130                         } else {
131                                 warn "W: $edir missing remote.origin.url\n";
132                                 my $pid = spawn([qw(git config -l)], undef,
133                                         { 1 => $lei->{2}, 2 => $lei->{2} });
134                                 waitpid($pid, 0);
135                                 $lei->child_error($?) if $?;
136                         }
137                 }
138                 @epochs = grep { !$skip->{$_} } @epochs if $skip;
139                 $skip //= {}; # makes code below easier
140                 $git_url or die "Unable to determine git URL\n";
141                 my $inbox_url = $git_url;
142                 $inbox_url =~ s!/git/$epoch(?:\.git)?/?\z!! or
143                         $inbox_url =~ s!/$epoch(?:\.git)?/?\z!! or die <<EOM;
144 Unable to infer inbox URL from <$git_url>
145 EOM
146                 $ibx_uri = URI->new($inbox_url);
147         }
148         PublicInbox::LeiMirror::write_makefile($dir, $ibx_ver);
149         $lei->qerr("# inbox URL: $ibx_uri/");
150         my $res = do_manifest($lei, $dir, $ibx_uri) or return;
151         my ($code, $muri, $v1_path, $v2_epochs, $ft, $mf, $m1) = @$res;
152         if ($code == 404) {
153                 # any pre-manifest.js.gz instances running? Just fetch all
154                 # existing ones and unconditionally try cloning the next
155                 $v2_epochs = [ map { "$dir/git/$_.git" } @epochs ];
156                 if (@epochs) {
157                         my $n = $epochs[-1] + 1;
158                         push @$v2_epochs, "$dir/git/$n.git" if !$skip->{$n};
159                 }
160         } else {
161                 $code == 200 or die "BUG unexpected code $code\n";
162         }
163         my $mculled;
164         if ($ibx_ver == 2) {
165                 defined($v1_path) and warn <<EOM;
166 E: got v1 `$v1_path' when expecting v2 epoch(s) in <$muri>, WTF?
167 EOM
168                 @git_dir = map { "$dir/git/$_.git" } sort { $a <=> $b } map {
169                                 my ($nr) = (m!/([0-9]+)\.git\z!g);
170                                 $skip->{$nr} ? () : $nr;
171                         } @$v2_epochs;
172                 if ($m1 && scalar keys %$skip) {
173                         my $re = join('|', keys %$skip);
174                         my @del = grep(m!/git/$re\.git\z!, keys %$m1);
175                         delete @$m1{@del};
176                         $mculled = 1;
177                 }
178         } else {
179                 $git_dir[0] = $dir;
180         }
181         # n.b. this expects all epochs are from the same host
182         my $torsocks = $lei->{curl}->torsocks($lei, $muri);
183         my $fp2 = $lei->{opt}->{'exit-code'} ? [] : undef;
184         my $xit = 127;
185         for my $d (@git_dir) {
186                 my $cmd;
187                 my $opt = {}; # for spawn
188                 if (-d $d) {
189                         $fp2->[0] = get_fingerprint2($d) if $fp2;
190                         $cmd = [ @$torsocks, 'git', "--git-dir=$d",
191                                 fetch_args($lei, $opt) ];
192                 } else {
193                         my $e_uri = $ibx_uri->clone;
194                         my ($epath) = ($d =~ m!(/git/[0-9]+\.git)\z!);
195                         defined($epath) or
196                                 die "BUG: $d is not an epoch to clone\n";
197                         $e_uri->path($ibx_uri->path.$epath);
198                         $cmd = [ @$torsocks,
199                                 PublicInbox::LeiMirror::clone_cmd($lei, $opt),
200                                 $$e_uri, $d];
201                         push @new_epoch, substr($epath, 5, -4) + 0;
202                         $xit = 0;
203                 }
204                 my $cerr = PublicInbox::LeiMirror::run_reap($lei, $cmd, $opt);
205                 # do not bail on clone failure if we didn't have a manifest
206                 if ($cerr && ($code == 200 || -d $d)) {
207                         $lei->child_error($cerr, "@$cmd failed");
208                         return;
209                 }
210                 if ($fp2 && $xit) {
211                         $fp2->[1] = get_fingerprint2($d);
212                         $xit = 0 if $fp2->[0] ne $fp2->[1];
213                 }
214         }
215         for my $i (@new_epoch) { $mg->epoch_cfg_set($i) }
216         if ($ft) {
217                 my $fn = $ft->filename;
218                 if ($mculled) {
219                         my $json = PublicInbox::Config->json->encode($m1);
220                         gzip(\$json => $fn) or die "gzip: $GzipError";
221                 }
222                 rename($fn, $mf) or die "E: rename($fn, $mf): $!\n";
223                 $ft->unlink_on_destroy(0);
224         }
225         $lei->child_error($xit << 8) if $fp2 && $xit;
226 }
227
228 1;