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 PublicInbox::Qspawn;
19 use URI::Escape qw(uri_escape_utf8);
21 # di = diff info / a hashref with information about a diff ($di):
23 # oid_a => abbreviated pre-image oid,
24 # oid_b => abbreviated post-image oid,
25 # tmp => anonymous file handle with the diff,
26 # hdr_lines => arrayref of various header lines for mode information
27 # mode_a => original mode of oid_a (string, not integer),
28 # ibx => PublicInbox::Inbox object containing the diff
29 # smsg => PublicInbox::SearchMsg object containing diff
30 # path_a => pre-image path
31 # path_b => post-image path
34 # don't bother if somebody sends us a patch with these path components,
35 # it's junk at best, an attack attempt at worse:
36 my %bad_component = map { $_ => 1 } ('', '.', '..');
39 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
43 my ($self, $err) = @_;
44 print { $self->{out} } $err, "\n";
45 my $ucb = delete($self->{user_cb});
46 eval { $ucb->($err) } if $ucb;
50 # look for existing blobs already in git repos
51 sub solve_existing ($$) {
52 my ($self, $want) = @_;
53 my $oid_b = $want->{oid_b};
54 my @ambiguous; # Array of [ git, $oids]
55 foreach my $git (@{$self->{gits}}) {
56 my ($oid_full, $type, $size) = $git->check($oid_b);
57 if (defined($type) && $type eq 'blob') {
58 return [ $git, $oid_full, $type, int($size) ];
61 next if length($oid_b) == 40;
63 # parse stderr of "git cat-file --batch-check"
64 my $err = $git->last_check_err;
65 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
66 next unless scalar(@oids);
68 # TODO: do something with the ambiguous array?
69 # push @ambiguous, [ $git, @oids ];
71 dbg($self, "`$oid_b' ambiguous in " .
72 join("\n\t", $git->pub_urls) . "\n" .
73 join('', map { "$_ blob\n" } @oids));
75 scalar(@ambiguous) ? \@ambiguous : undef;
78 sub extract_diff ($$$$) {
79 my ($p, $re, $ibx, $smsg) = @_;
80 my ($part) = @$p; # ignore $depth and @idx;
81 my $hdr_lines; # diff --git a/... b/...
83 my $ct = $part->content_type || 'text/plain';
84 my ($s, undef) = msg_part_text($part, $ct);
88 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
89 # change it back to LF:
90 my $cte = $part->header('Content-Transfer-Encoding') || '';
91 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
95 foreach my $l (split(/^/m, $s)) {
101 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
102 $di->{mode_a} = $mode_a;
106 # start writing the diff out to a tempfile
107 open($tmp, '+>', undef) or die "open(tmp): $!";
110 push @$hdr_lines, $l;
111 $di->{hdr_lines} = $hdr_lines;
112 print $tmp @$hdr_lines or die "print(tmp): $!";
114 # for debugging/diagnostics:
117 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
118 return $di if $tmp; # got our blob, done!
120 my ($path_a, $path_b) = ($1, $2);
122 # diff header lines won't have \r because git
123 # will quote them, but Email::MIME gives CRLF
124 # for quoted-printable:
127 # don't care for leading 'a/' and 'b/'
128 my (undef, @a) = split(m{/}, git_unquote($path_a));
129 my (undef, @b) = split(m{/}, git_unquote($path_b));
131 # get rid of path-traversal attempts and junk patches:
133 return if $bad_component{$_};
136 $di->{path_a} = join('/', @a);
137 $di->{path_b} = join('/', @b);
140 print $tmp $l or die "print(tmp): $!";
141 } elsif ($hdr_lines) {
142 push @$hdr_lines, $l;
143 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
151 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
153 sub find_extract_diff ($$$) {
154 my ($self, $ibx, $want) = @_;
155 my $srch = $ibx->search or return;
157 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
158 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
160 my $q = "dfpost:$post";
161 my $pre = $want->{oid_a};
162 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
165 $pre = '[a-f0-9]{7}'; # for $re below
168 my $path_b = $want->{path_b};
169 if (path_searchable($path_b)) {
170 $q .= qq{ dfn:"$path_b"};
172 my $path_a = $want->{path_a};
173 if (path_searchable($path_a) && $path_a ne $path_b) {
174 $q .= qq{ dfn:"$path_a"};
178 my $msgs = $srch->query($q, { relevance => 1 });
179 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
182 foreach my $smsg (@$msgs) {
183 $ibx->smsg_mime($smsg) or next;
184 msg_iter(delete($smsg->{mime}), sub {
185 $di ||= extract_diff($_[0], $re, $ibx, $smsg);
191 sub prepare_index ($) {
193 my $patches = $self->{patches};
195 $self->{tot} = scalar @$patches;
197 my $di = $patches->[0] or die 'no patches';
198 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
199 my $existing = $self->{found}->{$oid_a};
201 # no index creation for added files
202 $oid_a =~ /\A0+\z/ and return next_step($self);
204 die "BUG: $oid_a not not found" unless $existing;
206 my $oid_full = $existing->[1];
207 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
208 my $mode_a = $di->{mode_a} || extract_old_mode($di);
210 open my $in, '+>', undef or die "open: $!";
211 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
212 $in->flush or die "flush: $!";
213 sysseek($in, 0, 0) or die "seek: $!";
215 dbg($self, 'preparing index');
216 my $rdr = { 0 => fileno($in) };
217 my $cmd = [ qw(git update-index -z --index-info) ];
218 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
219 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
221 if (my $err = $qsp->{err}) {
222 ERR($self, "git update-index error: $err");
224 dbg($self, "index prepared:\n" .
225 "$mode_a $oid_full\t" . git_quote($path_a));
226 next_step($self); # onto do_git_apply
230 # pure Perl "git init"
231 sub do_git_init ($) {
233 my $dir = $self->{tmp}->dirname;
234 my $git_dir = "$dir/git";
236 foreach ('', qw(objects refs objects/info refs/heads)) {
237 mkdir("$git_dir/$_") or die "mkdir $_: $!";
239 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
240 print $fh <<'EOF' or die "print git/config $!";
242 repositoryFormatVersion = 0
245 fsyncObjectfiles = false
246 logAllRefUpdates = false
248 close $fh or die "close git/config: $!";
250 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
251 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
252 close $fh or die "close git/HEAD: $!";
254 my $f = 'objects/info/alternates';
255 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
256 print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
258 close $fh or die "close: $f: $!";
259 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
260 $tmp_git->{-tmp} = $self->{tmp};
263 GIT_INDEX_FILE => "$git_dir/index",
265 prepare_index($self);
268 sub extract_old_mode ($) {
270 if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
279 # step 1: resolve blobs to patches in the todo queue
280 if (my $want = pop @{$self->{todo}}) {
281 # this populates {patches} and {todo}
282 resolve_patch($self, $want);
284 # step 2: then we instantiate a working tree once
285 # the todo queue is finally empty:
286 } elsif (!defined($self->{tmp_git})) {
289 # step 3: apply each patch in the stack
290 } elsif (scalar @{$self->{patches}}) {
293 # step 4: execute the user-supplied callback with
294 # our result: (which may be undef)
295 # Other steps may call user_cb to terminate prematurely
297 } elsif (my $ucb = delete($self->{user_cb})) {
298 $ucb->($self->{found}->{$self->{oid_want}});
300 die 'about to call user_cb twice'; # Oops :x
305 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
306 dbg($self, "E: $err");
307 my $ucb = delete($self->{user_cb});
308 eval { $ucb->($err) } if $ucb;
314 sub { do_step($self) };
319 # if outside of public-inbox-httpd, caller is expected to be
320 # looping step_cb, anyways
321 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
322 # PublicInbox::HTTPD::Async->new
323 $async->(undef, step_cb($self));
326 sub mark_found ($$$) {
327 my ($self, $oid, $found_info) = @_;
328 $self->{found}->{$oid} = $found_info;
331 sub parse_ls_files ($$$$) {
332 my ($self, $qsp, $bref, $di) = @_;
333 if (my $err = $qsp->{err}) {
334 die "git ls-files error: $err";
337 my ($line, @extra) = split(/\0/, $$bref);
338 scalar(@extra) and die "BUG: extra files in index: <",
339 join('> <', @extra), ">";
341 my ($info, $file) = split(/\t/, $line, 2);
342 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
343 if ($file ne $di->{path_b}) {
345 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
348 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
349 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
350 defined($size) or die "check $oid_b_full failed";
352 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
353 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
354 mark_found($self, $di->{oid_b}, $created);
355 next_step($self); # onto the next patch
358 sub start_ls_files ($$) {
359 my ($self, $di) = @_;
360 my $cmd = [qw(git ls-files -s -z)];
361 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
362 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
364 eval { parse_ls_files($self, $qsp, $bref, $di) };
365 ERR($self, $@) if $@;
369 sub do_git_apply ($) {
372 my $di = shift @{$self->{patches}} or die 'empty {patches}';
373 my $tmp = delete $di->{tmp} or die 'no tmp ', di_url($self, $di);
374 $tmp->flush or die "tmp->flush failed: $!";
375 sysseek($tmp, 0, SEEK_SET) or die "sysseek(tmp) failed: $!";
377 my $i = ++$self->{nr};
378 dbg($self, "\napplying [$i/$self->{tot}] " . di_url($self, $di) .
379 "\n" . join('', @{$di->{hdr_lines}}));
381 # we need --ignore-whitespace because some patches are CRLF
382 my $cmd = [ qw(git apply --cached --ignore-whitespace
383 --whitespace=warn --verbose) ];
384 my $rdr = { 0 => fileno($tmp), 2 => 1 };
385 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
386 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
390 if (my $err = $qsp->{err}) {
391 ERR($self, "git apply error: $err");
393 eval { start_ls_files($self, $di) };
394 ERR($self, $@) if $@;
399 my ($self, $di) = @_;
400 # note: we don't pass the PSGI env unconditionally, here,
401 # different inboxes can have different HTTP_HOST on the same instance.
402 my $ibx = $di->{ibx};
403 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
404 my $url = $ibx->base_url($env);
405 my $mid = $di->{smsg}->{mid};
406 defined($url) ? "$url$mid/" : "<$mid>";
409 sub resolve_patch ($$) {
410 my ($self, $want) = @_;
412 if (scalar(@{$self->{patches}}) > $self->{max_patch}) {
413 die "Aborting, too many steps to $self->{oid_want}";
416 # see if we can find the blob in an existing git repo:
417 my $cur_want = $want->{oid_b};
418 if (my $existing = solve_existing($self, $want)) {
419 dbg($self, "found $cur_want in " .
420 join("\n", $existing->[0]->pub_urls));
422 if ($cur_want eq $self->{oid_want}) { # all done!
423 eval { delete($self->{user_cb})->($existing) };
427 mark_found($self, $cur_want, $existing);
428 return next_step($self); # onto patch application
431 # scan through inboxes to look for emails which results in
434 foreach my $ibx (@{$self->{inboxes}}) {
435 $di = find_extract_diff($self, $ibx, $want) or next;
437 unshift @{$self->{patches}}, $di;
438 dbg($self, "found $cur_want in ".di_url($self, $di));
440 # good, we can find a path to the oid we $want, now
441 # lets see if we need to apply more patches:
442 my $src = $di->{oid_a};
444 unless ($src =~ /\A0+\z/) {
445 # we have to solve it using another oid, fine:
446 my $job = { oid_b => $src, path_b => $di->{path_a} };
447 push @{$self->{todo}}, $job;
449 return next_step($self); # onto the next todo item
451 dbg($self, "could not find $cur_want");
452 eval { delete($self->{user_cb})->(undef) }; # not found! :<
456 # this API is designed to avoid creating self-referential structures;
457 # so user_cb never references the SolverGit object
459 my ($class, $ibx, $user_cb) = @_;
462 gits => $ibx->{-repo_objs},
466 # TODO: config option for searching related inboxes
471 # recreate $oid_want using $hints
472 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
473 # with found object, or undef if nothing was found
474 # Calls {user_cb} with a string error on fatal errors
476 my ($self, $env, $out, $oid_want, $hints) = @_;
478 # should we even get here? Probably not, but somebody
479 # could be manually typing URLs:
480 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
482 $self->{oid_want} = $oid_want;
484 $self->{psgi_env} = $env;
485 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
486 $self->{patches} = []; # [ $di, $di, ... ]
487 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
488 $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
490 dbg($self, "solving $oid_want ...");
491 my $step_cb = step_cb($self);
492 if (my $async = $env->{'pi-httpd.async'}) {
493 # PublicInbox::HTTPD::Async->new
494 $async->(undef, $step_cb);
496 $step_cb->() while $self->{user_cb};