1 # Copyright (C) 2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # "Solve" blobs which don't exist in git code repositories by
5 # searching inboxes for post-image blobs.
7 # this emits a lot of debugging/tracing information which may be
8 # publically viewed over HTTP(S). Be careful not to expose
9 # local filesystem layouts in the process.
10 package PublicInbox::SolverGit;
14 use Fcntl qw(SEEK_SET);
15 use File::Path qw(make_path);
16 use PublicInbox::Git qw(git_unquote);
17 use PublicInbox::Spawn qw(spawn popen_rd);
18 use PublicInbox::MsgIter qw(msg_iter msg_part_text);
19 use URI::Escape qw(uri_escape_utf8);
21 # don't bother if somebody sends us a patch with these path components,
22 # it's junk at best, an attack attempt at worse:
23 my %bad_component = map { $_ => 1 } ('', '.', '..');
26 my ($class, $gits, $inboxes) = @_;
33 # look for existing blobs already in git repos
34 sub solve_existing ($$) {
35 my ($self, $want) = @_;
36 foreach my $git (@{$self->{gits}}) {
37 my ($oid_full, $type, $size) = $git->check($want->{oid_b});
38 if (defined($type) && $type eq 'blob') {
39 return [ $git, $oid_full, $type, int($size) ];
45 # returns a hashref with information about a diff:
47 # oid_a => abbreviated pre-image oid,
48 # oid_b => abbreviated post-image oid,
49 # tmp => anonymous file handle with the diff,
50 # hdr_lines => arrayref of various header lines for mode information
51 # mode_a => original mode of oid_a (string, not integer),
52 # ibx => PublicInbox::Inbox object containing the diff
53 # smsg => PublicInbox::SearchMsg object containing diff
54 # path_a => pre-image path
55 # path_b => post-image path
57 sub extract_diff ($$$$) {
58 my ($p, $re, $ibx, $smsg) = @_;
59 my ($part) = @$p; # ignore $depth and @idx;
60 my $hdr_lines; # diff --git a/... b/...
62 my $ct = $part->content_type || 'text/plain';
63 my ($s, undef) = msg_part_text($part, $ct);
66 foreach my $l (split(/^/m, $s)) {
71 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
72 $di->{mode_a} = $mode_a;
75 # start writing the diff out to a tempfile
76 open($tmp, '+>', undef) or die "open(tmp): $!";
78 $di->{hdr_lines} = $hdr_lines;
80 print $tmp @$hdr_lines, $l or die "print(tmp): $!";
82 # for debugging/diagnostics:
85 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
86 return $di if $tmp; # got our blob, done!
88 my ($path_a, $path_b) = ($1, $2);
90 # don't care for leading 'a/' and 'b/'
91 my (undef, @a) = split(m{/}, git_unquote($path_a));
92 my (undef, @b) = split(m{/}, git_unquote($path_b));
94 # get rid of path-traversal attempts and junk patches:
96 return if $bad_component{$_};
99 $di->{path_a} = join('/', @a);
100 $di->{path_b} = join('/', @b);
103 print $tmp $l or die "print(tmp): $!";
104 } elsif ($hdr_lines) {
105 push @$hdr_lines, $l;
111 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
113 sub find_extract_diff ($$$) {
114 my ($self, $ibx, $want) = @_;
115 my $srch = $ibx->search or return;
117 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
118 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
120 my $q = "dfpost:$post";
121 my $pre = $want->{oid_a};
122 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
125 $pre = '[a-f0-9]{7}'; # for $re below
128 my $path_b = $want->{path_b};
129 if (path_searchable($path_b)) {
130 $q .= qq{ dfn:"$path_b"};
132 my $path_a = $want->{path_a};
133 if (path_searchable($path_a) && $path_a ne $path_b) {
134 $q .= qq{ dfn:"$path_a"};
138 my $msgs = $srch->query($q, { relevance => 1 });
139 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
142 foreach my $smsg (@$msgs) {
143 $ibx->smsg_mime($smsg) or next;
144 msg_iter(delete($smsg->{mime}), sub {
145 $di ||= extract_diff($_[0], $re, $ibx, $smsg);
151 # pure Perl "git init"
152 sub do_git_init_wt ($) {
154 my $wt = File::Temp->newdir('solver.wt-XXXXXXXX', TMPDIR => 1);
155 my $dir = $wt->dirname;
157 foreach (qw(objects/info refs/heads)) {
158 make_path("$dir/.git/$_") or die "make_path $_: $!";
160 open my $fh, '>', "$dir/.git/config" or die "open .git/config: $!";
161 print $fh <<'EOF' or die "print .git/config $!";
163 repositoryFormatVersion = 0
166 fsyncObjectfiles = false
167 logAllRefUpdates = false
169 close $fh or die "close .git/config: $!";
171 open $fh, '>', "$dir/.git/HEAD" or die "open .git/HEAD: $!";
172 print $fh "ref: refs/heads/master\n" or die "print .git/HEAD: $!";
173 close $fh or die "close .git/HEAD: $!";
175 my $f = '.git/objects/info/alternates';
176 open $fh, '>', "$dir/$f" or die "open: $f: $!";
177 foreach my $git (@{$self->{gits}}) {
178 print $fh "$git->{git_dir}/objects\n" or die "print $f: $!";
180 close $fh or die "close: $f: $!";
184 sub extract_old_mode ($) {
186 if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
193 my ($pid, $msg) = @_;
194 waitpid($pid, 0) == $pid or die "waitpid($msg): $!";
195 $? == 0 or die "$msg failed: $?";
198 sub prepare_wt ($$$) {
199 my ($wt_dir, $existing, $di) = @_;
200 my $oid_full = $existing->[1];
202 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
203 my $mode_a = $di->{mode_a} || extract_old_mode($di);
204 my @git = (qw(git -C), $wt_dir);
206 pipe($r, $w) or die "pipe: $!";
207 my $rdr = { 0 => fileno($r) };
208 my $pid = spawn([@git, qw(update-index -z --index-info)], {}, $rdr);
209 close $r or die "close pipe(r): $!";
210 print $w "$mode_a $oid_full\t$path_a\0" or die "print update-index: $!";
211 close $w or die "close update-index: $!";
212 reap($pid, 'update-index -z --index-info');
214 $pid = spawn([@git, qw(checkout-index -a -f -u)]);
215 reap($pid, 'checkout-index -a -f -u');
218 sub do_apply ($$$$) {
219 my ($out, $wt_git, $wt_dir, $di) = @_;
221 my $tmp = delete $di->{tmp} or die "BUG: no tmp ", di_info($di);
222 $tmp->flush or die "tmp->flush failed: $!";
223 $out->flush or die "err->flush failed: $!";
224 sysseek($tmp, 0, SEEK_SET) or die "sysseek(tmp) failed: $!";
226 defined(my $err_fd = fileno($out)) or die "fileno(out): $!";
227 my $rdr = { 0 => fileno($tmp), 1 => $err_fd, 2 => $err_fd };
228 my $cmd = [ qw(git -C), $wt_dir,
229 qw(apply --whitespace=warn -3 --verbose) ];
230 reap(spawn($cmd, undef, $rdr), 'apply');
233 my $rd = popen_rd([qw(git -C), $wt_dir, qw(ls-files -s -z)]);
235 defined(my $line = <$rd>) or die "failed to read ls-files: $!";
236 chomp $line or die "no trailing \\0 in [$line] from ls-files";
238 my ($info, $file) = split(/\t/, $line, 2);
239 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
241 defined($line = <$rd>) and die "extra files in index: $line";
242 close $rd or die "close ls-files: $?";
244 $file eq $di->{path_b} or
245 die "index mismatch: file=$file != path_b=$di->{path_b}";
246 my $abs_path = "$wt_dir/$file";
247 -r $abs_path or die "WT_DIR/$file not readable";
250 print $out "OK $mode_b $oid_b_full $stage\t$file\n";
251 [ $wt_git, $oid_b_full, 'blob', $size, $di ];
256 # note: we don't pass the PSGI env here, different inboxes
257 # can have different HTTP_HOST on the same instance.
258 my $url = $di->{ibx}->base_url;
259 my $mid = $di->{smsg}->{mid};
260 defined($url) ? "<$url/$mid/>" : "<$mid>";
263 sub apply_patches ($$$$$) {
264 my ($self, $out, $wt, $found, $patches) = @_;
265 my $wt_dir = $wt->dirname;
266 my $wt_git = PublicInbox::Git->new("$wt_dir/.git");
267 $wt_git->{-wt} = $wt;
270 my $tot = scalar @$patches;
272 foreach my $di (@$patches) {
274 my $oid_a = $di->{oid_a};
275 my $existing = $found->{$oid_a};
276 my $empty_oid = $oid_a =~ /\A0+\z/;
278 if ($empty_oid && $i != 0) {
279 die "empty oid at [$i/$tot] ", di_url($di);
281 if (!$existing && !$empty_oid) {
282 die "missing $oid_a at [$i/$tot] ", di_url($di);
285 # prepare the worktree for patch application:
286 if ($i == 1 && $existing) {
287 prepare_wt($wt_dir, $existing, $di);
289 unless (-f "$wt_dir/$di->{path_a}") {
290 die "missing $di->{path_a} at [$i/$tot] ", di_url($di);
293 print $out "applying [$i/$tot] ", di_url($di), "\n",
294 join('', @{$di->{hdr_lines}}), "\n"
295 or die "print \$out failed: $!";
298 $found->{$di->{oid_b}} = do_apply($out, $wt_git, $wt_dir, $di);
302 sub dump_found ($$) {
303 my ($out, $found) = @_;
304 foreach my $oid (sort keys %$found) {
305 my ($git, $oid, $di) = @{$found->{$oid}};
306 my $loc = $di ? di_info($di) : $git->src_blob_url($oid);
307 print $out "$oid from $loc\n";
311 sub dump_patches ($$) {
312 my ($out, $patches) = @_;
313 my $tot = scalar(@$patches);
315 foreach my $di (@$patches) {
317 print $out "[$i/$tot] ", di_url($di), "\n";
322 # Returns a 2-element array ref: [ PublicInbox::Git object, oid_full ]
323 # or undef if nothing was found.
325 my ($self, $out, $oid_b, $hints) = @_;
327 # should we even get here? Probably not, but somebody
328 # could be manually typing URLs:
329 return if $oid_b =~ /\A0+\z/;
331 my $req = { %$hints, oid_b => $oid_b };
333 my $found = {}; # { oid_abbrev => [ PublicInbox::Git, oid_full, $di ] }
334 my $patches = []; # [ array of $di hashes ]
336 my $max = $self->{max_steps} || 200;
339 while (defined(my $want = pop @todo)) {
340 # see if we can find the blob in an existing git repo:
341 if (my $existing = solve_existing($self, $want)) {
342 my $want_oid = $want->{oid_b};
343 return $existing if $want_oid eq $oid_b; # DONE!
345 $found->{$want_oid} = $existing;
346 next; # ok, one blob resolved, more to go?
349 # scan through inboxes to look for emails which results in
351 foreach my $ibx (@{$self->{inboxes}}) {
352 my $di = find_extract_diff($self, $ibx, $want) or next;
354 unshift @$patches, $di;
356 # good, we can find a path to the oid we $want, now
357 # lets see if we need to apply more patches:
358 my $src = $di->{oid_a};
359 if ($src !~ /\A0+\z/) {
360 if (++$steps > $max) {
362 "Aborting, too many steps to $oid_b\n";
367 # we have to solve it using another oid, fine:
370 path_b => $di->{path_a},
374 last; # onto the next @todo item
378 unless (scalar(@$patches)) {
379 print $out "no patch(es) for $oid_b\n";
380 dump_found($out, $found);
384 # reconstruct the oid_b blob using patches we found:
386 my $wt = do_git_init_wt($self);
387 apply_patches($self, $out, $wt, $found, $patches);
390 print $out "E: $@\nfound: ";
391 dump_found($out, $found);
392 print $out "patches: ";
393 dump_patches($out, $patches);