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;
13 use File::Temp 0.19 ();
14 use Fcntl qw(SEEK_SET);
15 use PublicInbox::Git qw(git_unquote git_quote);
16 use PublicInbox::MsgIter qw(msg_iter msg_part_text);
17 use PublicInbox::Qspawn;
18 use PublicInbox::Tmpfile;
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;
28 # By default, "git format-patch" generates filenames with a four-digit
29 # prefix, so that means 9999 patch series are OK, right? :>
30 # Maybe we can make this configurable, main concern is disk space overhead
31 # for uncompressed patch fragments. Aside from space, public-inbox-httpd
32 # is otherwise unaffected by having many patches, here, as it can share
33 # work fairly. Other PSGI servers may have trouble, though.
36 # di = diff info / a hashref with information about a diff ($di):
38 # oid_a => abbreviated pre-image oid,
39 # oid_b => abbreviated post-image oid,
40 # tmp => anonymous file handle with the diff,
41 # hdr_lines => arrayref of various header lines for mode information
42 # mode_a => original mode of oid_a (string, not integer),
43 # ibx => PublicInbox::Inbox object containing the diff
44 # smsg => PublicInbox::SearchMsg object containing diff
45 # path_a => pre-image path
46 # path_b => post-image path
47 # n => numeric path of the patch (relative to worktree)
50 # don't bother if somebody sends us a patch with these path components,
51 # it's junk at best, an attack attempt at worse:
52 my %bad_component = map { $_ => 1 } ('', '.', '..');
55 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
59 my ($self, $err) = @_;
60 print { $self->{out} } $err, "\n";
61 my $ucb = delete($self->{user_cb});
62 eval { $ucb->($err) } if $ucb;
66 # look for existing objects already in git repos
67 sub solve_existing ($$) {
68 my ($self, $want) = @_;
69 my $oid_b = $want->{oid_b};
70 my $have_hints = scalar keys %$want > 1;
71 my @ambiguous; # Array of [ git, $oids]
72 foreach my $git (@{$self->{gits}}) {
73 my ($oid_full, $type, $size) = $git->check($oid_b);
74 if (defined($type) && (!$have_hints || $type eq 'blob')) {
75 return [ $git, $oid_full, $type, int($size) ];
78 next if length($oid_b) == 40;
80 # parse stderr of "git cat-file --batch-check"
81 my $err = $git->last_check_err;
82 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
83 next unless scalar(@oids);
85 # TODO: do something with the ambiguous array?
86 # push @ambiguous, [ $git, @oids ];
88 dbg($self, "`$oid_b' ambiguous in " .
89 join("\n\t", $git->pub_urls($self->{psgi_env}))
91 join('', map { "$_ blob\n" } @oids));
93 scalar(@ambiguous) ? \@ambiguous : undef;
96 sub extract_diff ($$$$$) {
97 my ($self, $p, $re, $ibx, $smsg) = @_;
98 my ($part) = @$p; # ignore $depth and @idx;
99 my $hdr_lines; # diff --git a/... b/...
101 my $ct = $part->content_type || 'text/plain';
102 my ($s, undef) = msg_part_text($part, $ct);
103 defined $s or return;
106 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
107 # change it back to LF:
108 my $cte = $part->header('Content-Transfer-Encoding') || '';
109 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
113 foreach my $l (split(/^/m, $s)) {
119 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
120 $di->{mode_a} = $mode_a;
125 # start writing the diff out to a tempfile
126 my $path = ++$self->{tot};
128 open($tmp, '>', $self->{tmp}->dirname . "/$path") or
131 push @$hdr_lines, $l;
132 $di->{hdr_lines} = $hdr_lines;
133 utf8::encode($_) for @$hdr_lines;
134 print $tmp @$hdr_lines or die "print(tmp): $!";
136 # for debugging/diagnostics:
139 } elsif ($l =~ m!\Adiff --git ("?[^/]+/.+) ("?[^/]+/.+)$!) {
140 last if $tmp; # got our blob, done!
142 my ($path_a, $path_b) = ($1, $2);
144 # diff header lines won't have \r because git
145 # will quote them, but Email::MIME gives CRLF
146 # for quoted-printable:
149 # don't care for leading 'a/' and 'b/'
150 my (undef, @a) = split(m{/}, git_unquote($path_a));
151 my (undef, @b) = split(m{/}, git_unquote($path_b));
153 # get rid of path-traversal attempts and junk patches:
155 return if $bad_component{$_};
158 $di->{path_a} = join('/', @a);
159 $di->{path_b} = join('/', @b);
163 print $tmp $l or die "print(tmp): $!";
164 } elsif ($hdr_lines) {
165 push @$hdr_lines, $l;
166 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
171 return undef unless $tmp;
172 close $tmp or die "close(tmp): $!";
176 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
178 # ".." appears in path names, which confuses Xapian into treating
179 # it as a range query. So we split on ".." since Xapian breaks
180 # on punctuation anyways:
181 sub filename_query ($) {
182 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
185 sub find_extract_diffs ($$$) {
186 my ($self, $ibx, $want) = @_;
187 my $srch = $ibx->search or return;
189 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
190 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
192 my $q = "dfpost:$post";
193 my $pre = $want->{oid_a};
194 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
197 $pre = '[a-f0-9]{7}'; # for $re below
200 my $path_b = $want->{path_b};
201 if (path_searchable($path_b)) {
202 $q .= filename_query($path_b);
204 my $path_a = $want->{path_a};
205 if (path_searchable($path_a) && $path_a ne $path_b) {
206 $q .= filename_query($path_a);
210 my $msgs = $srch->query($q, { relevance => 1 });
211 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: ([0-9]+))?/;
214 foreach my $smsg (@$msgs) {
215 $ibx->smsg_mime($smsg) or next;
216 msg_iter(delete($smsg->{mime}), sub {
217 my $di = extract_diff($self, $_[0], $re, $ibx, $smsg);
218 push @di, $di if defined($di);
224 sub prepare_index ($) {
226 my $patches = $self->{patches};
229 my $di = $patches->[0] or die 'no patches';
230 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
231 my $existing = $self->{found}->{$oid_a};
233 # no index creation for added files
234 $oid_a =~ /\A0+\z/ and return next_step($self);
236 die "BUG: $oid_a not not found" unless $existing;
238 my $oid_full = $existing->[1];
239 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
240 my $mode_a = $di->{mode_a} || extract_old_mode($di);
242 my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
243 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
244 $in->flush or die "flush: $!";
245 sysseek($in, 0, 0) or die "seek: $!";
247 dbg($self, 'preparing index');
248 my $rdr = { 0 => fileno($in), -hold => $in };
249 my $cmd = [ qw(git update-index -z --index-info) ];
250 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
251 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
253 if (my $err = $qsp->{err}) {
254 ERR($self, "git update-index error: $err");
256 dbg($self, "index prepared:\n" .
257 "$mode_a $oid_full\t" . git_quote($path_a));
258 next_step($self); # onto do_git_apply
262 # pure Perl "git init"
263 sub do_git_init ($) {
265 my $dir = $self->{tmp}->dirname;
266 my $git_dir = "$dir/git";
268 foreach ('', qw(objects refs objects/info refs/heads)) {
269 mkdir("$git_dir/$_") or die "mkdir $_: $!";
271 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
272 print $fh <<'EOF' or die "print git/config $!";
274 repositoryFormatVersion = 0
277 fsyncObjectfiles = false
278 logAllRefUpdates = false
280 close $fh or die "close git/config: $!";
282 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
283 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
284 close $fh or die "close git/HEAD: $!";
286 my $f = 'objects/info/alternates';
287 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
288 foreach my $git (@{$self->{gits}}) {
289 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
291 close $fh or die "close: $f: $!";
292 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
293 $tmp_git->{-tmp} = $self->{tmp};
296 GIT_INDEX_FILE => "$git_dir/index",
298 prepare_index($self);
301 sub extract_old_mode ($) {
303 if (join('', @{$di->{hdr_lines}}) =~
304 /^old mode (100644|100755|120000)\b/) {
311 my ($self, $user_cb) = @_;
312 my $found = $self->{found};
313 my $oid_want = $self->{oid_want};
314 if (my $exists = $found->{$oid_want}) {
315 return $user_cb->($exists);
318 # let git disambiguate if oid_want was too short,
319 # but long enough to be unambiguous:
320 my $tmp_git = $self->{tmp_git};
321 if (my @res = $tmp_git->check($oid_want)) {
322 return $user_cb->($found->{$res[0]});
324 if (my $err = $tmp_git->last_check_err) {
333 # step 1: resolve blobs to patches in the todo queue
334 if (my $want = pop @{$self->{todo}}) {
335 # this populates {patches} and {todo}
336 resolve_patch($self, $want);
338 # step 2: then we instantiate a working tree once
339 # the todo queue is finally empty:
340 } elsif (!defined($self->{tmp_git})) {
343 # step 3: apply each patch in the stack
344 } elsif (scalar @{$self->{patches}}) {
347 # step 4: execute the user-supplied callback with
348 # our result: (which may be undef)
349 # Other steps may call user_cb to terminate prematurely
351 } elsif (my $user_cb = delete($self->{user_cb})) {
352 do_finish($self, $user_cb);
354 die 'about to call user_cb twice'; # Oops :x
359 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
360 dbg($self, "E: $err");
361 my $ucb = delete($self->{user_cb});
362 eval { $ucb->($err) } if $ucb;
368 sub { do_step($self) };
373 # if outside of public-inbox-httpd, caller is expected to be
374 # looping step_cb, anyways
375 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
376 # PublicInbox::HTTPD::Async->new
377 $async->(undef, step_cb($self));
380 sub mark_found ($$$) {
381 my ($self, $oid, $found_info) = @_;
382 my $found = $self->{found};
383 $found->{$oid} = $found_info;
384 my $oid_cur = $found_info->[1];
385 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
386 $found->{$oid_cur} = $found_info;
391 sub parse_ls_files ($$$$) {
392 my ($self, $qsp, $bref, $di) = @_;
393 if (my $err = $qsp->{err}) {
394 die "git ls-files error: $err";
397 my ($line, @extra) = split(/\0/, $$bref);
398 scalar(@extra) and die "BUG: extra files in index: <",
399 join('> <', @extra), ">";
401 my ($info, $file) = split(/\t/, $line, 2);
402 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
403 if ($file ne $di->{path_b}) {
405 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
408 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
409 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
410 defined($size) or die "check $oid_b_full failed";
412 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
413 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
414 mark_found($self, $di->{oid_b}, $created);
415 next_step($self); # onto the next patch
418 sub start_ls_files ($$) {
419 my ($self, $di) = @_;
420 my $cmd = [qw(git ls-files -s -z)];
421 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
422 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
424 eval { parse_ls_files($self, $qsp, $bref, $di) };
425 ERR($self, $@) if $@;
429 sub oids_same_ish ($$) {
430 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
433 sub skip_identical ($$$) {
434 my ($self, $patches, $cur_oid_b) = @_;
435 while (my $nxt = $patches->[0]) {
436 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
437 dbg($self, 'skipping '.di_url($self, $nxt).
446 sub do_git_apply ($) {
448 my $dn = $self->{tmp}->dirname;
449 my $patches = $self->{patches};
451 # we need --ignore-whitespace because some patches are CRLF
452 my @cmd = (qw(git -C), $dn, qw(apply --cached --ignore-whitespace
453 --unidiff-zero --whitespace=warn --verbose));
454 my $len = length(join(' ', @cmd));
455 my $total = $self->{tot};
456 my $di; # keep track of the last one for "git ls-files"
460 my $i = ++$self->{nr};
461 $di = shift @$patches;
462 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
463 "\n" . join('', @{$di->{hdr_lines}}));
465 $len += length($path) + 1;
467 $prv_oid_b = $di->{oid_b};
468 } while (@$patches && $len < $ARG_SIZE_MAX &&
469 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
471 my $rdr = { 2 => 1 };
472 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
473 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
476 if (my $err = $qsp->{err}) {
477 my $msg = "git apply error: $err";
478 my $nxt = $patches->[0];
479 if ($nxt && oids_same_ish($nxt->{oid_b}, $prv_oid_b)) {
481 dbg($self, 'trying '.di_url($self, $nxt));
486 skip_identical($self, $patches, $di->{oid_b});
488 eval { start_ls_files($self, $di) };
489 ERR($self, $@) if $@;
494 my ($self, $di) = @_;
495 # note: we don't pass the PSGI env unconditionally, here,
496 # different inboxes can have different HTTP_HOST on the same instance.
497 my $ibx = $di->{ibx};
498 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
499 my $url = $ibx->base_url($env);
500 my $mid = $di->{smsg}->{mid};
501 defined($url) ? "$url$mid/" : "<$mid>";
504 sub resolve_patch ($$) {
505 my ($self, $want) = @_;
507 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
508 die "Aborting, too many steps to $self->{oid_want}";
511 # see if we can find the blob in an existing git repo:
512 my $cur_want = $want->{oid_b};
513 if ($self->{seen_oid}->{$cur_want}++) {
514 die "Loop detected solving $cur_want\n";
516 if (my $existing = solve_existing($self, $want)) {
517 my ($found_git, undef, $type, undef) = @$existing;
518 dbg($self, "found $cur_want in " .
519 join("\n", $found_git->pub_urls($self->{psgi_env})));
521 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
522 eval { delete($self->{user_cb})->($existing) };
526 mark_found($self, $cur_want, $existing);
527 return next_step($self); # onto patch application
530 # scan through inboxes to look for emails which results in
532 foreach my $ibx (@{$self->{inboxes}}) {
533 my $diffs = find_extract_diffs($self, $ibx, $want) or next;
535 unshift @{$self->{patches}}, @$diffs;
536 dbg($self, "found $cur_want in ".
537 join("\n\t", map { di_url($self, $_) } @$diffs));
539 # good, we can find a path to the oid we $want, now
540 # lets see if we need to apply more patches:
541 my $di = $diffs->[0];
542 my $src = $di->{oid_a};
544 unless ($src =~ /\A0+\z/) {
545 # we have to solve it using another oid, fine:
546 my $job = { oid_b => $src, path_b => $di->{path_a} };
547 push @{$self->{todo}}, $job;
549 return next_step($self); # onto the next todo item
551 if (length($cur_want) > $OID_MIN) {
553 dbg($self, "retrying $want->{oid_b} as $cur_want");
554 $want->{oid_b} = $cur_want;
555 push @{$self->{todo}}, $want;
556 return next_step($self); # retry with shorter abbrev
559 dbg($self, "could not find $cur_want");
560 eval { delete($self->{user_cb})->(undef) }; # not found! :<
564 # this API is designed to avoid creating self-referential structures;
565 # so user_cb never references the SolverGit object
567 my ($class, $ibx, $user_cb) = @_;
570 gits => $ibx->{-repo_objs},
573 # TODO: config option for searching related inboxes
578 # recreate $oid_want using $hints
579 # hints keys: path_a, path_b, oid_a
580 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
581 # with found object, or undef if nothing was found
582 # Calls {user_cb} with a string error on fatal errors
584 my ($self, $env, $out, $oid_want, $hints) = @_;
586 # should we even get here? Probably not, but somebody
587 # could be manually typing URLs:
588 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
590 $self->{oid_want} = $oid_want;
592 $self->{seen_oid} = {};
594 $self->{psgi_env} = $env;
595 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
596 $self->{patches} = []; # [ $di, $di, ... ]
597 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
598 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
600 dbg($self, "solving $oid_want ...");
601 my $step_cb = step_cb($self);
602 if (my $async = $env->{'pi-httpd.async'}) {
603 # PublicInbox::HTTPD::Async->new
604 $async->(undef, $step_cb);
606 $step_cb->() while $self->{user_cb};