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 -C), $self->{wt_dir},
218 qw(update-index -z --index-info) ];
219 my $qsp = PublicInbox::Qspawn->new($cmd, undef, $rdr);
220 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
222 if (my $err = $qsp->{err}) {
223 ERR($self, "git update-index error: $err");
225 dbg($self, "index prepared:\n" .
226 "$mode_a $oid_full\t" . git_quote($path_a));
227 next_step($self); # onto do_git_apply
231 # pure Perl "git init"
232 sub do_git_init_wt ($) {
234 my $wt = File::Temp->newdir('solver.wt-XXXXXXXX', TMPDIR => 1);
235 my $dir = $self->{wt_dir} = $wt->dirname;
237 foreach ('', qw(objects refs objects/info refs/heads)) {
238 mkdir("$dir/.git/$_") or die "mkdir $_: $!";
240 open my $fh, '>', "$dir/.git/config" or die "open .git/config: $!";
241 print $fh <<'EOF' or die "print .git/config $!";
243 repositoryFormatVersion = 0
246 fsyncObjectfiles = false
247 logAllRefUpdates = false
249 close $fh or die "close .git/config: $!";
251 open $fh, '>', "$dir/.git/HEAD" or die "open .git/HEAD: $!";
252 print $fh "ref: refs/heads/master\n" or die "print .git/HEAD: $!";
253 close $fh or die "close .git/HEAD: $!";
255 my $f = '.git/objects/info/alternates';
256 open $fh, '>', "$dir/$f" or die "open: $f: $!";
257 print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
259 close $fh or die "close: $f: $!";
260 my $wt_git = $self->{wt_git} = PublicInbox::Git->new("$dir/.git");
261 $wt_git->{-wt} = $wt;
262 prepare_index($self);
265 sub extract_old_mode ($) {
267 if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
276 # step 1: resolve blobs to patches in the todo queue
277 if (my $want = pop @{$self->{todo}}) {
278 # this populates {patches} and {todo}
279 resolve_patch($self, $want);
281 # step 2: then we instantiate a working tree once
282 # the todo queue is finally empty:
283 } elsif (!defined($self->{wt_git})) {
284 do_git_init_wt($self);
286 # step 3: apply each patch in the stack
287 } elsif (scalar @{$self->{patches}}) {
290 # step 4: execute the user-supplied callback with
291 # our result: (which may be undef)
292 # Other steps may call user_cb to terminate prematurely
294 } elsif (my $ucb = delete($self->{user_cb})) {
295 $ucb->($self->{found}->{$self->{oid_want}});
297 die 'about to call user_cb twice'; # Oops :x
302 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
303 dbg($self, "E: $err");
304 my $ucb = delete($self->{user_cb});
305 eval { $ucb->($err) } if $ucb;
311 sub { do_step($self) };
316 # if outside of public-inbox-httpd, caller is expected to be
317 # looping step_cb, anyways
318 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
319 # PublicInbox::HTTPD::Async->new
320 $async->(undef, step_cb($self));
323 sub mark_found ($$$) {
324 my ($self, $oid, $found_info) = @_;
325 $self->{found}->{$oid} = $found_info;
328 sub parse_ls_files ($$$$) {
329 my ($self, $qsp, $bref, $di) = @_;
330 if (my $err = $qsp->{err}) {
331 die "git ls-files error: $err";
334 my ($line, @extra) = split(/\0/, $$bref);
335 scalar(@extra) and die "BUG: extra files in index: <",
336 join('> <', @extra), ">";
338 my ($info, $file) = split(/\t/, $line, 2);
339 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
340 if ($file ne $di->{path_b}) {
342 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
345 my $wt_git = $self->{wt_git} or die 'no git working tree';
346 my (undef, undef, $size) = $wt_git->check($oid_b_full);
347 defined($size) or die "check $oid_b_full failed";
349 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
350 my $created = [ $wt_git, $oid_b_full, 'blob', $size, $di ];
351 mark_found($self, $di->{oid_b}, $created);
352 next_step($self); # onto the next patch
355 sub start_ls_files ($$) {
356 my ($self, $di) = @_;
357 my $cmd = [qw(git -C), $self->{wt_dir}, qw(ls-files -s -z)];
358 my $qsp = PublicInbox::Qspawn->new($cmd);
359 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
361 eval { parse_ls_files($self, $qsp, $bref, $di) };
362 ERR($self, $@) if $@;
366 sub do_git_apply ($) {
369 my $di = shift @{$self->{patches}} or die 'empty {patches}';
370 my $tmp = delete $di->{tmp} or die 'no tmp ', di_url($self, $di);
371 $tmp->flush or die "tmp->flush failed: $!";
372 sysseek($tmp, 0, SEEK_SET) or die "sysseek(tmp) failed: $!";
374 my $i = ++$self->{nr};
375 dbg($self, "\napplying [$i/$self->{tot}] " . di_url($self, $di) .
376 "\n" . join('', @{$di->{hdr_lines}}));
378 # we need --ignore-whitespace because some patches are CRLF
379 my $cmd = [ qw(git -C), $self->{wt_dir},
380 qw(apply --cached --ignore-whitespace
381 --whitespace=warn --verbose) ];
382 my $rdr = { 0 => fileno($tmp), 2 => 1 };
383 my $qsp = PublicInbox::Qspawn->new($cmd, undef, $rdr);
384 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
388 if (my $err = $qsp->{err}) {
389 ERR($self, "git apply error: $err");
391 eval { start_ls_files($self, $di) };
392 ERR($self, $@) if $@;
397 my ($self, $di) = @_;
398 # note: we don't pass the PSGI env unconditionally, here,
399 # different inboxes can have different HTTP_HOST on the same instance.
400 my $ibx = $di->{ibx};
401 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
402 my $url = $ibx->base_url($env);
403 my $mid = $di->{smsg}->{mid};
404 defined($url) ? "$url$mid/" : "<$mid>";
407 sub resolve_patch ($$) {
408 my ($self, $want) = @_;
410 if (scalar(@{$self->{patches}}) > $self->{max_patch}) {
411 die "Aborting, too many steps to $self->{oid_want}";
414 # see if we can find the blob in an existing git repo:
415 my $cur_want = $want->{oid_b};
416 if (my $existing = solve_existing($self, $want)) {
417 dbg($self, "found $cur_want in " .
418 join("\n", $existing->[0]->pub_urls));
420 if ($cur_want eq $self->{oid_want}) { # all done!
421 eval { delete($self->{user_cb})->($existing) };
425 mark_found($self, $cur_want, $existing);
426 return next_step($self); # onto patch application
429 # scan through inboxes to look for emails which results in
432 foreach my $ibx (@{$self->{inboxes}}) {
433 $di = find_extract_diff($self, $ibx, $want) or next;
435 unshift @{$self->{patches}}, $di;
436 dbg($self, "found $cur_want in ".di_url($self, $di));
438 # good, we can find a path to the oid we $want, now
439 # lets see if we need to apply more patches:
440 my $src = $di->{oid_a};
442 unless ($src =~ /\A0+\z/) {
443 # we have to solve it using another oid, fine:
444 my $job = { oid_b => $src, path_b => $di->{path_a} };
445 push @{$self->{todo}}, $job;
447 return next_step($self); # onto the next todo item
449 dbg($self, "could not find $cur_want");
450 eval { delete($self->{user_cb})->(undef) }; # not found! :<
454 # this API is designed to avoid creating self-referential structures;
455 # so user_cb never references the SolverGit object
457 my ($class, $ibx, $user_cb) = @_;
460 gits => $ibx->{-repo_objs},
464 # TODO: config option for searching related inboxes
469 # recreate $oid_want using $hints
470 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
471 # with found object, or undef if nothing was found
472 # Calls {user_cb} with a string error on fatal errors
474 my ($self, $env, $out, $oid_want, $hints) = @_;
476 # should we even get here? Probably not, but somebody
477 # could be manually typing URLs:
478 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
480 $self->{oid_want} = $oid_want;
482 $self->{psgi_env} = $env;
483 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
484 $self->{patches} = []; # [ $di, $di, ... ]
485 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
487 dbg($self, "solving $oid_want ...");
488 my $step_cb = step_cb($self);
489 if (my $async = $env->{'pi-httpd.async'}) {
490 # PublicInbox::HTTPD::Async->new
491 $async->(undef, $step_cb);
493 $step_cb->() while $self->{user_cb};