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 PublicInbox::Git qw(git_unquote git_quote);
16 use PublicInbox::Spawn qw(spawn popen_rd);
17 use PublicInbox::MsgIter qw(msg_iter msg_part_text);
18 use URI::Escape qw(uri_escape_utf8);
20 # don't bother if somebody sends us a patch with these path components,
21 # it's junk at best, an attack attempt at worse:
22 my %bad_component = map { $_ => 1 } ('', '.', '..');
25 my ($class, $gits, $inboxes) = @_;
32 # look for existing blobs already in git repos
33 sub solve_existing ($$$) {
34 my ($self, $out, $want) = @_;
35 my $oid_b = $want->{oid_b};
36 my @ambiguous; # Array of [ git, $oids]
37 foreach my $git (@{$self->{gits}}) {
38 my ($oid_full, $type, $size) = $git->check($oid_b);
39 if (defined($type) && $type eq 'blob') {
40 return [ $git, $oid_full, $type, int($size) ];
43 next if length($oid_b) == 40;
45 # parse stderr of "git cat-file --batch-check"
46 my $err = $git->last_check_err;
47 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
48 next unless scalar(@oids);
50 # TODO: do something with the ambiguous array?
51 # push @ambiguous, [ $git, @oids ];
53 print $out "`$oid_b' ambiguous in ",
54 join("\n", $git->pub_urls), "\n",
55 join('', map { "$_ blob\n" } @oids), "\n";
57 scalar(@ambiguous) ? \@ambiguous : undef;
60 # returns a hashref with information about a diff:
62 # oid_a => abbreviated pre-image oid,
63 # oid_b => abbreviated post-image oid,
64 # tmp => anonymous file handle with the diff,
65 # hdr_lines => arrayref of various header lines for mode information
66 # mode_a => original mode of oid_a (string, not integer),
67 # ibx => PublicInbox::Inbox object containing the diff
68 # smsg => PublicInbox::SearchMsg object containing diff
69 # path_a => pre-image path
70 # path_b => post-image path
72 sub extract_diff ($$$$) {
73 my ($p, $re, $ibx, $smsg) = @_;
74 my ($part) = @$p; # ignore $depth and @idx;
75 my $hdr_lines; # diff --git a/... b/...
77 my $ct = $part->content_type || 'text/plain';
78 my ($s, undef) = msg_part_text($part, $ct);
81 foreach my $l (split(/^/m, $s)) {
87 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
88 $di->{mode_a} = $mode_a;
92 # start writing the diff out to a tempfile
93 open($tmp, '+>', undef) or die "open(tmp): $!";
97 $di->{hdr_lines} = $hdr_lines;
98 print $tmp @$hdr_lines, $l or die "print(tmp): $!";
100 # for debugging/diagnostics:
103 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
104 return $di if $tmp; # got our blob, done!
106 my ($path_a, $path_b) = ($1, $2);
108 # don't care for leading 'a/' and 'b/'
109 my (undef, @a) = split(m{/}, git_unquote($path_a));
110 my (undef, @b) = split(m{/}, git_unquote($path_b));
112 # get rid of path-traversal attempts and junk patches:
114 return if $bad_component{$_};
117 $di->{path_a} = join('/', @a);
118 $di->{path_b} = join('/', @b);
121 print $tmp $l or die "print(tmp): $!";
122 } elsif ($hdr_lines) {
123 push @$hdr_lines, $l;
124 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
132 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
134 sub find_extract_diff ($$$) {
135 my ($self, $ibx, $want) = @_;
136 my $srch = $ibx->search or return;
138 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
139 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
141 my $q = "dfpost:$post";
142 my $pre = $want->{oid_a};
143 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
146 $pre = '[a-f0-9]{7}'; # for $re below
149 my $path_b = $want->{path_b};
150 if (path_searchable($path_b)) {
151 $q .= qq{ dfn:"$path_b"};
153 my $path_a = $want->{path_a};
154 if (path_searchable($path_a) && $path_a ne $path_b) {
155 $q .= qq{ dfn:"$path_a"};
159 my $msgs = $srch->query($q, { relevance => 1 });
160 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
163 foreach my $smsg (@$msgs) {
164 $ibx->smsg_mime($smsg) or next;
165 msg_iter(delete($smsg->{mime}), sub {
166 $di ||= extract_diff($_[0], $re, $ibx, $smsg);
172 # pure Perl "git init"
173 sub do_git_init_wt ($) {
175 my $wt = File::Temp->newdir('solver.wt-XXXXXXXX', TMPDIR => 1);
176 my $dir = $wt->dirname;
178 foreach ('', qw(objects refs objects/info refs/heads)) {
179 mkdir("$dir/.git/$_") or die "mkdir $_: $!";
181 open my $fh, '>', "$dir/.git/config" or die "open .git/config: $!";
182 print $fh <<'EOF' or die "print .git/config $!";
184 repositoryFormatVersion = 0
187 fsyncObjectfiles = false
188 logAllRefUpdates = false
190 close $fh or die "close .git/config: $!";
192 open $fh, '>', "$dir/.git/HEAD" or die "open .git/HEAD: $!";
193 print $fh "ref: refs/heads/master\n" or die "print .git/HEAD: $!";
194 close $fh or die "close .git/HEAD: $!";
196 my $f = '.git/objects/info/alternates';
197 open $fh, '>', "$dir/$f" or die "open: $f: $!";
198 print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
200 close $fh or die "close: $f: $!";
204 sub extract_old_mode ($) {
206 if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
213 my ($pid, $msg) = @_;
214 waitpid($pid, 0) == $pid or die "waitpid($msg): $!";
215 $? == 0 or die "$msg failed: $?";
218 sub prepare_index ($$$$) {
219 my ($out, $wt_dir, $existing, $di) = @_;
220 my $oid_full = $existing->[1];
222 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
223 my $mode_a = $di->{mode_a} || extract_old_mode($di);
224 my @git = (qw(git -C), $wt_dir);
226 pipe($r, $w) or die "pipe: $!";
227 my $rdr = { 0 => fileno($r) };
228 my $pid = spawn([@git, qw(update-index -z --index-info)], {}, $rdr);
229 close $r or die "close pipe(r): $!";
230 print $w "$mode_a $oid_full\t$path_a\0" or die "print update-index: $!";
232 close $w or die "close update-index: $!";
233 reap($pid, 'update-index -z --index-info');
235 print $out "index prepared:\n",
236 "$mode_a $oid_full\t", git_quote($path_a), "\n";
239 sub do_apply ($$$$) {
240 my ($out, $wt_git, $wt_dir, $di) = @_;
242 my $tmp = delete $di->{tmp} or die "BUG: no tmp ", di_url($di);
243 $tmp->flush or die "tmp->flush failed: $!";
244 $out->flush or die "err->flush failed: $!";
245 sysseek($tmp, 0, SEEK_SET) or die "sysseek(tmp) failed: $!";
247 defined(my $err_fd = fileno($out)) or die "fileno(out): $!";
248 my $rdr = { 0 => fileno($tmp), 1 => $err_fd, 2 => $err_fd };
249 my $cmd = [ qw(git -C), $wt_dir,
250 qw(apply --cached --whitespace=warn --verbose) ];
251 reap(spawn($cmd, undef, $rdr), 'apply');
254 my $rd = popen_rd([qw(git -C), $wt_dir, qw(ls-files -s -z)]);
256 defined(my $line = <$rd>) or die "failed to read ls-files: $!";
257 chomp $line or die "no trailing \\0 in [$line] from ls-files";
259 my ($info, $file) = split(/\t/, $line, 2);
260 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
262 defined($line = <$rd>) and die "extra files in index: $line";
263 close $rd or die "close ls-files: $?";
265 $file eq $di->{path_b} or
266 die "index mismatch: file=$file != path_b=$di->{path_b}";
268 my (undef, undef, $size) = $wt_git->check($oid_b_full);
270 defined($size) or die "failed to read_size from $oid_b_full";
272 print $out "$mode_b $oid_b_full\t$file\n";
273 [ $wt_git, $oid_b_full, 'blob', $size, $di ];
278 # note: we don't pass the PSGI env here, different inboxes
279 # can have different HTTP_HOST on the same instance.
280 my $url = $di->{ibx}->base_url;
281 my $mid = $di->{smsg}->{mid};
282 defined($url) ? "<$url$mid/>" : "<$mid>";
285 sub apply_patches ($$$$$) {
286 my ($self, $out, $wt, $found, $patches) = @_;
287 my $wt_dir = $wt->dirname;
288 my $wt_git = PublicInbox::Git->new("$wt_dir/.git");
289 $wt_git->{-wt} = $wt;
292 my $tot = scalar @$patches;
294 foreach my $di (@$patches) {
296 my $oid_a = $di->{oid_a};
297 my $existing = $found->{$oid_a};
298 my $empty_oid = $oid_a =~ /\A0+\z/;
300 if ($empty_oid && $i != 1) {
301 die "empty oid at [$i/$tot] ", di_url($di);
303 if (!$existing && !$empty_oid) {
304 die "missing $oid_a at [$i/$tot] ", di_url($di);
307 # prepare the worktree for patch application:
308 if ($i == 1 && $existing) {
309 prepare_index($out, $wt_dir, $existing, $di);
312 print $out "\napplying [$i/$tot] ", di_url($di), "\n",
313 join('', @{$di->{hdr_lines}}), "\n"
314 or die "print \$out failed: $!";
317 $found->{$di->{oid_b}} = do_apply($out, $wt_git, $wt_dir, $di);
321 sub dump_found ($$) {
322 my ($out, $found) = @_;
323 foreach my $oid (sort keys %$found) {
324 my ($git, $oid, undef, undef, $di) = @{$found->{$oid}};
325 my $loc = $di ? di_url($di) : $git->src_blob_url($oid);
326 print $out "$oid from $loc\n";
330 sub dump_patches ($$) {
331 my ($out, $patches) = @_;
332 my $tot = scalar(@$patches);
334 foreach my $di (@$patches) {
336 print $out "[$i/$tot] ", di_url($di), "\n";
341 # Returns a 2-element array ref: [ PublicInbox::Git object, oid_full ]
342 # or undef if nothing was found.
344 my ($self, $out, $oid_b, $hints) = @_;
346 # should we even get here? Probably not, but somebody
347 # could be manually typing URLs:
348 return if $oid_b =~ /\A0+\z/;
350 my $req = { %$hints, oid_b => $oid_b };
352 my $found = {}; # { abbrev => [ ::Git, oid_full, type, size, $di ] }
353 my $patches = []; # [ array of $di hashes ]
355 my $max = $self->{max_steps} || 200;
358 while (defined(my $want = pop @todo)) {
359 # see if we can find the blob in an existing git repo:
360 if (my $existing = solve_existing($self, $out, $want)) {
361 my $want_oid = $want->{oid_b};
362 if ($want_oid eq $oid_b) { # DONE!
363 my @pub_urls = $existing->[0]->pub_urls;
364 print $out "found $want_oid in ",
365 join("\n", @pub_urls),"\n";
369 $found->{$want_oid} = $existing;
370 next; # ok, one blob resolved, more to go?
373 # scan through inboxes to look for emails which results in
375 foreach my $ibx (@{$self->{inboxes}}) {
376 my $di = find_extract_diff($self, $ibx, $want) or next;
378 unshift @$patches, $di;
380 # good, we can find a path to the oid we $want, now
381 # lets see if we need to apply more patches:
382 my $src = $di->{oid_a};
383 if ($src !~ /\A0+\z/) {
384 if (++$steps > $max) {
386 "Aborting, too many steps to $oid_b\n";
391 # we have to solve it using another oid, fine:
394 path_b => $di->{path_a},
398 last; # onto the next @todo item
402 unless (scalar(@$patches)) {
403 print $out "no patch(es) for $oid_b\n";
404 dump_found($out, $found);
408 # reconstruct the oid_b blob using patches we found:
410 my $wt = do_git_init_wt($self);
411 apply_patches($self, $out, $wt, $found, $patches);
414 print $out "E: $@\nfound: ";
415 dump_found($out, $found);
416 print $out "patches: ";
417 dump_patches($out, $patches);