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 # POSIX requires _POSIX_ARG_MAX >= 4096, and xargs is required to
22 # subtract 2048 bytes. We also don't factor in environment variable
24 use POSIX qw(sysconf _SC_ARG_MAX);
25 my $ARG_SIZE_MAX = (sysconf(_SC_ARG_MAX) || 4096) - 2048;
27 # di = diff info / a hashref with information about a diff ($di):
29 # oid_a => abbreviated pre-image oid,
30 # oid_b => abbreviated post-image oid,
31 # tmp => anonymous file handle with the diff,
32 # hdr_lines => arrayref of various header lines for mode information
33 # mode_a => original mode of oid_a (string, not integer),
34 # ibx => PublicInbox::Inbox object containing the diff
35 # smsg => PublicInbox::SearchMsg object containing diff
36 # path_a => pre-image path
37 # path_b => post-image path
40 # don't bother if somebody sends us a patch with these path components,
41 # it's junk at best, an attack attempt at worse:
42 my %bad_component = map { $_ => 1 } ('', '.', '..');
45 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
49 my ($self, $err) = @_;
50 print { $self->{out} } $err, "\n";
51 my $ucb = delete($self->{user_cb});
52 eval { $ucb->($err) } if $ucb;
56 # look for existing blobs already in git repos
57 sub solve_existing ($$) {
58 my ($self, $want) = @_;
59 my $oid_b = $want->{oid_b};
60 my @ambiguous; # Array of [ git, $oids]
61 foreach my $git (@{$self->{gits}}) {
62 my ($oid_full, $type, $size) = $git->check($oid_b);
63 if (defined($type) && $type eq 'blob') {
64 return [ $git, $oid_full, $type, int($size) ];
67 next if length($oid_b) == 40;
69 # parse stderr of "git cat-file --batch-check"
70 my $err = $git->last_check_err;
71 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
72 next unless scalar(@oids);
74 # TODO: do something with the ambiguous array?
75 # push @ambiguous, [ $git, @oids ];
77 dbg($self, "`$oid_b' ambiguous in " .
78 join("\n\t", $git->pub_urls) . "\n" .
79 join('', map { "$_ blob\n" } @oids));
81 scalar(@ambiguous) ? \@ambiguous : undef;
84 sub extract_diff ($$$$$) {
85 my ($self, $p, $re, $ibx, $smsg) = @_;
86 my ($part) = @$p; # ignore $depth and @idx;
87 my $hdr_lines; # diff --git a/... b/...
89 my $ct = $part->content_type || 'text/plain';
90 my ($s, undef) = msg_part_text($part, $ct);
94 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
95 # change it back to LF:
96 my $cte = $part->header('Content-Transfer-Encoding') || '';
97 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
101 foreach my $l (split(/^/m, $s)) {
107 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
108 $di->{mode_a} = $mode_a;
113 # start writing the diff out to a tempfile
114 my $pn = ++$self->{tot};
115 open($tmp, '>', $self->{tmp}->dirname . "/$pn") or
118 push @$hdr_lines, $l;
119 $di->{hdr_lines} = $hdr_lines;
120 print $tmp @$hdr_lines or die "print(tmp): $!";
122 # for debugging/diagnostics:
125 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
126 last if $tmp; # got our blob, done!
128 my ($path_a, $path_b) = ($1, $2);
130 # diff header lines won't have \r because git
131 # will quote them, but Email::MIME gives CRLF
132 # for quoted-printable:
135 # don't care for leading 'a/' and 'b/'
136 my (undef, @a) = split(m{/}, git_unquote($path_a));
137 my (undef, @b) = split(m{/}, git_unquote($path_b));
139 # get rid of path-traversal attempts and junk patches:
141 return if $bad_component{$_};
144 $di->{path_a} = join('/', @a);
145 $di->{path_b} = join('/', @b);
148 print $tmp $l or die "print(tmp): $!";
149 } elsif ($hdr_lines) {
150 push @$hdr_lines, $l;
151 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
156 return undef unless $tmp;
157 close $tmp or die "close(tmp): $!";
161 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
163 sub find_extract_diff ($$$) {
164 my ($self, $ibx, $want) = @_;
165 my $srch = $ibx->search or return;
167 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
168 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
170 my $q = "dfpost:$post";
171 my $pre = $want->{oid_a};
172 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
175 $pre = '[a-f0-9]{7}'; # for $re below
178 my $path_b = $want->{path_b};
179 if (path_searchable($path_b)) {
180 $q .= qq{ dfn:"$path_b"};
182 my $path_a = $want->{path_a};
183 if (path_searchable($path_a) && $path_a ne $path_b) {
184 $q .= qq{ dfn:"$path_a"};
188 my $msgs = $srch->query($q, { relevance => 1 });
189 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
192 foreach my $smsg (@$msgs) {
193 $ibx->smsg_mime($smsg) or next;
194 msg_iter(delete($smsg->{mime}), sub {
195 $di ||= extract_diff($self, $_[0], $re, $ibx, $smsg);
201 sub prepare_index ($) {
203 my $patches = $self->{patches};
206 my $di = $patches->[0] or die 'no patches';
207 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
208 my $existing = $self->{found}->{$oid_a};
210 # no index creation for added files
211 $oid_a =~ /\A0+\z/ and return next_step($self);
213 die "BUG: $oid_a not not found" unless $existing;
215 my $oid_full = $existing->[1];
216 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
217 my $mode_a = $di->{mode_a} || extract_old_mode($di);
219 open my $in, '+>', undef or die "open: $!";
220 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
221 $in->flush or die "flush: $!";
222 sysseek($in, 0, 0) or die "seek: $!";
224 dbg($self, 'preparing index');
225 my $rdr = { 0 => fileno($in) };
226 my $cmd = [ qw(git update-index -z --index-info) ];
227 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
228 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
230 if (my $err = $qsp->{err}) {
231 ERR($self, "git update-index error: $err");
233 dbg($self, "index prepared:\n" .
234 "$mode_a $oid_full\t" . git_quote($path_a));
235 next_step($self); # onto do_git_apply
239 # pure Perl "git init"
240 sub do_git_init ($) {
242 my $dir = $self->{tmp}->dirname;
243 my $git_dir = "$dir/git";
245 foreach ('', qw(objects refs objects/info refs/heads)) {
246 mkdir("$git_dir/$_") or die "mkdir $_: $!";
248 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
249 print $fh <<'EOF' or die "print git/config $!";
251 repositoryFormatVersion = 0
254 fsyncObjectfiles = false
255 logAllRefUpdates = false
257 close $fh or die "close git/config: $!";
259 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
260 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
261 close $fh or die "close git/HEAD: $!";
263 my $f = 'objects/info/alternates';
264 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
265 print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
267 close $fh or die "close: $f: $!";
268 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
269 $tmp_git->{-tmp} = $self->{tmp};
272 GIT_INDEX_FILE => "$git_dir/index",
274 prepare_index($self);
277 sub extract_old_mode ($) {
279 if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
288 # step 1: resolve blobs to patches in the todo queue
289 if (my $want = pop @{$self->{todo}}) {
290 # this populates {patches} and {todo}
291 resolve_patch($self, $want);
293 # step 2: then we instantiate a working tree once
294 # the todo queue is finally empty:
295 } elsif (!defined($self->{tmp_git})) {
298 # step 3: apply each patch in the stack
299 } elsif (scalar @{$self->{patches}}) {
302 # step 4: execute the user-supplied callback with
303 # our result: (which may be undef)
304 # Other steps may call user_cb to terminate prematurely
306 } elsif (my $ucb = delete($self->{user_cb})) {
307 $ucb->($self->{found}->{$self->{oid_want}});
309 die 'about to call user_cb twice'; # Oops :x
314 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
315 dbg($self, "E: $err");
316 my $ucb = delete($self->{user_cb});
317 eval { $ucb->($err) } if $ucb;
323 sub { do_step($self) };
328 # if outside of public-inbox-httpd, caller is expected to be
329 # looping step_cb, anyways
330 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
331 # PublicInbox::HTTPD::Async->new
332 $async->(undef, step_cb($self));
335 sub mark_found ($$$) {
336 my ($self, $oid, $found_info) = @_;
337 $self->{found}->{$oid} = $found_info;
340 sub parse_ls_files ($$$$) {
341 my ($self, $qsp, $bref, $di) = @_;
342 if (my $err = $qsp->{err}) {
343 die "git ls-files error: $err";
346 my ($line, @extra) = split(/\0/, $$bref);
347 scalar(@extra) and die "BUG: extra files in index: <",
348 join('> <', @extra), ">";
350 my ($info, $file) = split(/\t/, $line, 2);
351 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
352 if ($file ne $di->{path_b}) {
354 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
357 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
358 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
359 defined($size) or die "check $oid_b_full failed";
361 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
362 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
363 mark_found($self, $di->{oid_b}, $created);
364 next_step($self); # onto the next patch
367 sub start_ls_files ($$) {
368 my ($self, $di) = @_;
369 my $cmd = [qw(git ls-files -s -z)];
370 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
371 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
373 eval { parse_ls_files($self, $qsp, $bref, $di) };
374 ERR($self, $@) if $@;
378 sub do_git_apply ($) {
380 my $dn = $self->{tmp}->dirname;
381 my $patches = $self->{patches};
383 # we need --ignore-whitespace because some patches are CRLF
384 my @cmd = qw(git apply --cached --ignore-whitespace
385 --whitespace=warn --verbose);
386 my $len = length(join(' ', @cmd));
387 my $total = $self->{tot};
388 my $di; # keep track of the last one for "git ls-files"
391 my $i = ++$self->{nr};
392 $di = shift @$patches;
393 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
394 "\n" . join('', @{$di->{hdr_lines}}));
395 my $pn = $total + 1 - $i;
396 my $path = "$dn/$pn";
397 $len += length($path) + 1;
399 } while (@$patches && $len < $ARG_SIZE_MAX);
401 my $rdr = { 2 => 1 };
402 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
403 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
406 if (my $err = $qsp->{err}) {
407 ERR($self, "git apply error: $err");
409 eval { start_ls_files($self, $di) };
410 ERR($self, $@) if $@;
415 my ($self, $di) = @_;
416 # note: we don't pass the PSGI env unconditionally, here,
417 # different inboxes can have different HTTP_HOST on the same instance.
418 my $ibx = $di->{ibx};
419 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
420 my $url = $ibx->base_url($env);
421 my $mid = $di->{smsg}->{mid};
422 defined($url) ? "$url$mid/" : "<$mid>";
425 sub resolve_patch ($$) {
426 my ($self, $want) = @_;
428 if (scalar(@{$self->{patches}}) > $self->{max_patch}) {
429 die "Aborting, too many steps to $self->{oid_want}";
432 # see if we can find the blob in an existing git repo:
433 my $cur_want = $want->{oid_b};
434 if (my $existing = solve_existing($self, $want)) {
435 dbg($self, "found $cur_want in " .
436 join("\n", $existing->[0]->pub_urls));
438 if ($cur_want eq $self->{oid_want}) { # all done!
439 eval { delete($self->{user_cb})->($existing) };
443 mark_found($self, $cur_want, $existing);
444 return next_step($self); # onto patch application
447 # scan through inboxes to look for emails which results in
450 foreach my $ibx (@{$self->{inboxes}}) {
451 $di = find_extract_diff($self, $ibx, $want) or next;
453 unshift @{$self->{patches}}, $di;
454 dbg($self, "found $cur_want in ".di_url($self, $di));
456 # good, we can find a path to the oid we $want, now
457 # lets see if we need to apply more patches:
458 my $src = $di->{oid_a};
460 unless ($src =~ /\A0+\z/) {
461 # we have to solve it using another oid, fine:
462 my $job = { oid_b => $src, path_b => $di->{path_a} };
463 push @{$self->{todo}}, $job;
465 return next_step($self); # onto the next todo item
467 dbg($self, "could not find $cur_want");
468 eval { delete($self->{user_cb})->(undef) }; # not found! :<
472 # this API is designed to avoid creating self-referential structures;
473 # so user_cb never references the SolverGit object
475 my ($class, $ibx, $user_cb) = @_;
478 gits => $ibx->{-repo_objs},
482 # TODO: config option for searching related inboxes
487 # recreate $oid_want using $hints
488 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
489 # with found object, or undef if nothing was found
490 # Calls {user_cb} with a string error on fatal errors
492 my ($self, $env, $out, $oid_want, $hints) = @_;
494 # should we even get here? Probably not, but somebody
495 # could be manually typing URLs:
496 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
498 $self->{oid_want} = $oid_want;
501 $self->{psgi_env} = $env;
502 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
503 $self->{patches} = []; # [ $di, $di, ... ]
504 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
505 $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
507 dbg($self, "solving $oid_want ...");
508 my $step_cb = step_cb($self);
509 if (my $async = $env->{'pi-httpd.async'}) {
510 # PublicInbox::HTTPD::Async->new
511 $async->(undef, $step_cb);
513 $step_cb->() while $self->{user_cb};