1 # Copyright (C) 2019-2021 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 # publicly 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 (); # 0.19 for ->newdir
14 use Fcntl qw(SEEK_SET);
15 use PublicInbox::Git qw(git_unquote git_quote);
16 use PublicInbox::MsgIter qw(msg_part_text);
17 use PublicInbox::Qspawn;
18 use PublicInbox::Tmpfile;
19 use PublicInbox::GitAsyncCat;
21 use URI::Escape qw(uri_escape_utf8);
23 # POSIX requires _POSIX_ARG_MAX >= 4096, and xargs is required to
24 # subtract 2048 bytes. We also don't factor in environment variable
26 use POSIX qw(sysconf _SC_ARG_MAX);
27 my $ARG_SIZE_MAX = (sysconf(_SC_ARG_MAX) || 4096) - 2048;
30 # By default, "git format-patch" generates filenames with a four-digit
31 # prefix, so that means 9999 patch series are OK, right? :>
32 # Maybe we can make this configurable, main concern is disk space overhead
33 # for uncompressed patch fragments. Aside from space, public-inbox-httpd
34 # is otherwise unaffected by having many patches, here, as it can share
35 # work fairly. Other PSGI servers may have trouble, though.
39 my $ANY = qr![^\r\n]+!;
40 my $MODE = '100644|120000|100755';
41 my $FN = qr!(?:("?[^/\n]+/[^\r\n]+)|/dev/null)!;
42 my %BAD_COMPONENT = ('' => 1, '.' => 1, '..' => 1);
44 # di = diff info / a hashref with information about a diff ($di):
46 # oid_a => abbreviated pre-image oid,
47 # oid_b => abbreviated post-image oid,
48 # tmp => anonymous file handle with the diff,
49 # hdr_lines => string of various header lines for mode information
50 # mode_a => original mode of oid_a (string, not integer),
51 # ibx => PublicInbox::Inbox object containing the diff
52 # smsg => PublicInbox::Smsg object containing diff
53 # path_a => pre-image path
54 # path_b => post-image path
55 # n => numeric path of the patch (relative to worktree)
59 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
63 my ($self, $res) = @_;
64 my $ucb = delete($self->{user_cb}) or return;
65 $ucb->($res, $self->{uarg});
69 my ($self, $err) = @_;
70 print { $self->{out} } $err, "\n";
71 eval { done($self, $err) };
75 # look for existing objects already in git repos, returns arrayref
76 # if found, number of remaining git coderepos to try if not.
77 sub solve_existing ($$) {
78 my ($self, $want) = @_;
79 my $try = $want->{try_gits} //= [ @{$self->{gits}} ]; # array copy
80 my $git = shift @$try or die 'BUG {try_gits} empty';
81 my $oid_b = $want->{oid_b};
82 my ($oid_full, $type, $size) = $git->check($oid_b);
84 # other than {oid_b, try_gits, try_ibxs}
85 my $have_hints = scalar keys %$want > 3;
86 if (defined($type) && (!$have_hints || $type eq 'blob')) {
87 delete $want->{try_gits};
88 return [ $git, $oid_full, $type, int($size) ]; # done, success
91 # TODO: deal with 40-char "abbreviations" with future SHA-256 git
92 return scalar(@$try) if length($oid_b) >= 40;
94 # parse stderr of "git cat-file --batch-check"
95 my $err = $git->last_check_err;
96 my (@oids) = ($err =~ /\b([a-f0-9]{40,})\s+blob\b/g);
97 return scalar(@$try) unless scalar(@oids);
99 # TODO: do something with the ambiguous array?
100 # push @ambiguous, [ $git, @oids ];
102 dbg($self, "`$oid_b' ambiguous in " .
103 join("\n\t", $git->pub_urls($self->{psgi_env}))
105 join('', map { "$_ blob\n" } @oids));
109 sub extract_diff ($$) {
111 my ($self, $want, $smsg) = @$arg;
112 my ($part) = @$p; # ignore $depth and @idx;
113 my $ct = $part->content_type || 'text/plain';
114 my $post = $want->{oid_b};
115 my $pre = $want->{oid_a};
116 if (!defined($pre) || $pre !~ /\A[a-f0-9]+\z/) {
117 $pre = '[a-f0-9]{7}'; # for RE below
120 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
121 # change it back to LF:
122 my $cte = $part->header('Content-Transfer-Encoding') || '';
123 my ($s, undef) = msg_part_text($part, $ct);
124 defined $s or return;
126 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
129 $s =~ m!( # $1 start header lines we save for debugging:
131 # everything before ^index is optional, but we don't
132 # want to match ^(old|copy|rename|deleted|...) unless
133 # we match /^diff --git/ first:
134 (?: # begin optional stuff:
136 # try to get the pre-and-post filenames as $2 and $3
137 (?:^diff\x20--git\x20$FN\x20$FN$LF)
139 (?:^(?: # pass all this to git-apply:
141 (?:old\x20mode\x20($MODE))
143 # new mode (possibly new file) ($5)
144 (?:new\x20(?:file\x20)?mode\x20($MODE))
146 (?:(?:copy|rename|deleted|
147 dissimilarity|similarity)$ANY)
150 )? # end of optional stuff, everything below is required
152 # match the pre and post-image OIDs as $6 $7
153 ^index\x20(${pre}[a-f0-9]*)\.\.(${post}[a-f0-9]*)
154 # mode if unchanged $8
155 (?:\x20(100644|120000|100755))?$LF
156 ) # end of header lines ($1)
157 ( # $9 is the patch body
158 # "--- a/foo.c" sets pre-filename ($10) in case
162 # "+++ b/foo.c" sets post-filename ($11) in case
166 # the meat of the diff, including "^\\No newline ..."
167 # We also allow for totally blank lines w/o leading spaces,
168 # because git-apply(1) handles that case, too
169 (?:^(?:[\@\+\x20\-\\][^\n]*|)$LF)+
171 undef $s; # free memory
177 mode_a => $5 // $8 // $4, # new (file) // unchanged // old
179 my $path_a = $2 // $10;
180 my $path_b = $3 // $11;
183 # don't care for leading 'a/' and 'b/'
184 my (undef, @a) = split(m{/}, git_unquote($path_a)) if defined($path_a);
185 my (undef, @b) = split(m{/}, git_unquote($path_b));
187 # get rid of path-traversal attempts and junk patches:
188 # it's junk at best, an attack attempt at worse:
189 foreach (@a, @b) { return if $BAD_COMPONENT{$_} }
191 $di->{path_a} = join('/', @a) if @a;
192 $di->{path_b} = join('/', @b);
194 my $path = ++$self->{tot};
196 open(my $tmp, '>:utf8', $self->{tmp}->dirname . "/$path") or
198 print $tmp $di->{hdr_lines}, $patch or die "print(tmp): $!";
199 close $tmp or die "close(tmp): $!";
201 # for debugging/diagnostics:
202 $di->{ibx} = $want->{cur_ibx};
205 push @{$self->{tmp_diffs}}, $di;
208 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
210 # ".." appears in path names, which confuses Xapian into treating
211 # it as a range query. So we split on ".." since Xapian breaks
212 # on punctuation anyways:
213 sub filename_query ($) {
214 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
217 sub find_smsgs ($$$) {
218 my ($self, $ibx, $want) = @_;
219 my $srch = $ibx->isrch or return;
221 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
222 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
224 my $q = "dfpost:$post";
225 my $pre = $want->{oid_a};
226 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
230 my $path_b = $want->{path_b};
231 if (path_searchable($path_b)) {
232 $q .= filename_query($path_b);
234 my $path_a = $want->{path_a};
235 if (path_searchable($path_a) && $path_a ne $path_b) {
236 $q .= filename_query($path_a);
239 my $mset = $srch->mset($q, { relevance => 1 });
240 $mset->size ? $srch->mset_to_smsg($ibx, $mset) : undef;
243 sub update_index_result ($$) {
244 my ($bref, $self) = @_;
245 my ($qsp, $msg) = delete @$self{qw(-qsp -msg)};
246 if (my $err = $qsp->{err}) {
247 ERR($self, "git update-index error: $err");
250 next_step($self); # onto do_git_apply
253 sub prepare_index ($) {
255 my $patches = $self->{patches};
258 my $di = $patches->[0] or die 'no patches';
259 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
260 my $existing = $self->{found}->{$oid_a};
262 # no index creation for added files
263 $oid_a =~ /\A0+\z/ and return next_step($self);
265 die "BUG: $oid_a not found" unless $existing;
267 my $oid_full = $existing->[1];
268 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
269 my $mode_a = $di->{mode_a} // '100644';
271 my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
272 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
273 $in->flush or die "flush: $!";
274 sysseek($in, 0, SEEK_SET) or die "seek: $!";
276 dbg($self, 'preparing index');
277 my $rdr = { 0 => $in };
278 my $cmd = [ qw(git update-index -z --index-info) ];
279 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
280 $path_a = git_quote($path_a);
281 $self->{-qsp} = $qsp;
282 $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
283 $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
286 # pure Perl "git init"
287 sub do_git_init ($) {
289 my $dir = $self->{tmp}->dirname;
290 my $git_dir = "$dir/git";
292 foreach ('', qw(objects refs objects/info refs/heads)) {
293 mkdir("$git_dir/$_") or die "mkdir $_: $!";
295 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
296 my $first = $self->{gits}->[0];
297 my $fmt = $first->object_format;
298 my $v = defined($$fmt) ? 1 : 0;
299 print $fh <<EOF or die "print git/config $!";
301 repositoryFormatVersion = $v
304 fsyncObjectfiles = false
305 logAllRefUpdates = false
307 print $fh <<EOM if defined($$fmt);
311 close $fh or die "close git/config: $!";
313 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
314 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
315 close $fh or die "close git/HEAD: $!";
317 my $f = 'objects/info/alternates';
318 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
319 foreach my $git (@{$self->{gits}}) {
320 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
322 close $fh or die "close: $f: $!";
323 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
324 $tmp_git->{-tmp} = $self->{tmp};
327 GIT_INDEX_FILE => "$git_dir/index",
329 prepare_index($self);
334 my ($found, $oid_want) = @$self{qw(found oid_want)};
335 if (my $exists = $found->{$oid_want}) {
336 return done($self, $exists);
339 # let git disambiguate if oid_want was too short,
340 # but long enough to be unambiguous:
341 my $tmp_git = $self->{tmp_git};
342 if (my @res = $tmp_git->check($oid_want)) {
343 return done($self, $found->{$res[0]});
345 if (my $err = $tmp_git->last_check_err) {
354 # step 1: resolve blobs to patches in the todo queue
355 if (my $want = pop @{$self->{todo}}) {
356 # this populates {patches} and {todo}
357 resolve_patch($self, $want);
359 # step 2: then we instantiate a working tree once
360 # the todo queue is finally empty:
361 } elsif (!defined($self->{tmp_git})) {
364 # step 3: apply each patch in the stack
365 } elsif (scalar @{$self->{patches}}) {
368 # step 4: execute the user-supplied callback with
369 # our result: (which may be undef)
370 # Other steps may call user_cb to terminate prematurely
372 } elsif (exists $self->{user_cb}) {
375 die 'about to call user_cb twice'; # Oops :x
380 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
381 dbg($self, "E: $err");
382 eval { done($self, $err) };
388 # if outside of public-inbox-httpd, caller is expected to be
389 # looping event_step, anyways
390 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
391 # PublicInbox::HTTPD::Async->new
392 $async->(undef, undef, $self);
395 sub mark_found ($$$) {
396 my ($self, $oid, $found_info) = @_;
397 my $found = $self->{found};
398 $found->{$oid} = $found_info;
399 my $oid_cur = $found_info->[1];
400 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
401 $found->{$oid_cur} = $found_info;
406 sub parse_ls_files ($$) {
407 my ($self, $bref) = @_;
408 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
409 if (my $err = $qsp->{err}) {
410 die "git ls-files error: $err";
413 my ($line, @extra) = split(/\0/, $$bref);
414 scalar(@extra) and die "BUG: extra files in index: <",
415 join('> <', @extra), ">";
417 my ($info, $file) = split(/\t/, $line, 2);
418 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
419 if ($file ne $di->{path_b}) {
421 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
424 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
425 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
426 defined($size) or die "check $oid_b_full failed";
428 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
429 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
430 mark_found($self, $di->{oid_b}, $created);
431 next_step($self); # onto the next patch
434 sub ls_files_result {
435 my ($bref, $self) = @_;
436 eval { parse_ls_files($self, $bref) };
437 ERR($self, $@) if $@;
440 sub oids_same_ish ($$) {
441 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
444 sub skip_identical ($$$) {
445 my ($self, $patches, $cur_oid_b) = @_;
446 while (my $nxt = $patches->[0]) {
447 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
448 dbg($self, 'skipping '.di_url($self, $nxt).
457 sub apply_result ($$) {
458 my ($bref, $self) = @_;
459 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
461 my $patches = $self->{patches};
462 if (my $err = $qsp->{err}) {
463 my $msg = "git apply error: $err";
464 my $nxt = $patches->[0];
465 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
467 dbg($self, 'trying '.di_url($self, $nxt));
468 return do_git_apply($self);
473 skip_identical($self, $patches, $di->{oid_b});
476 my @cmd = qw(git ls-files -s -z);
477 $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
478 $self->{-cur_di} = $di;
479 $self->{-qsp} = $qsp;
480 $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
483 sub do_git_apply ($) {
485 my $dn = $self->{tmp}->dirname;
486 my $patches = $self->{patches};
488 # we need --ignore-whitespace because some patches are CRLF
489 my @cmd = (qw(git apply --cached --ignore-whitespace
490 --unidiff-zero --whitespace=warn --verbose));
491 my $len = length(join(' ', @cmd));
492 my $total = $self->{tot};
493 my $di; # keep track of the last one for "git ls-files"
497 my $i = ++$self->{nr};
498 $di = shift @$patches;
499 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
500 "\n" . $di->{hdr_lines});
502 $len += length($path) + 1;
504 $prv_oid_b = $di->{oid_b};
505 } while (@$patches && $len < $ARG_SIZE_MAX &&
506 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
508 my $opt = { 2 => 1, -C => $dn, quiet => 1 };
509 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
510 $self->{-cur_di} = $di;
511 $self->{-qsp} = $qsp;
512 $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
516 my ($self, $di) = @_;
517 # note: we don't pass the PSGI env unconditionally, here,
518 # different inboxes can have different HTTP_HOST on the same instance.
519 my $ibx = $di->{ibx};
520 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
521 my $url = $ibx->base_url($env);
522 my $mid = $di->{smsg}->{mid};
523 defined($url) ? "$url$mid/" : "<$mid>";
527 my ($self, $want) = @_;
528 push @{$self->{todo}}, $want;
529 next_step($self); # retry solve_existing
532 sub try_harder ($$) {
533 my ($self, $want) = @_;
535 # do we have more inboxes to try?
536 return retry_current($self, $want) if scalar @{$want->{try_ibxs}};
538 my $cur_want = $want->{oid_b};
539 if (length($cur_want) > $OID_MIN) { # maybe a shorter OID will work
540 delete $want->{try_ibxs}; # drop empty arrayref
542 dbg($self, "retrying $want->{oid_b} as $cur_want");
543 $want->{oid_b} = $cur_want;
544 return retry_current($self, $want); # retry with shorter abbrev
547 dbg($self, "could not find $cur_want");
548 eval { done($self, undef) };
552 sub extract_diffs_done {
553 my ($self, $want) = @_;
555 delete $want->{try_smsgs};
556 delete $want->{cur_ibx};
558 my $diffs = delete $self->{tmp_diffs};
559 if (scalar @$diffs) {
560 unshift @{$self->{patches}}, @$diffs;
561 dbg($self, "found $want->{oid_b} in " . join(" ||\n\t",
562 map { di_url($self, $_) } @$diffs));
564 # good, we can find a path to the oid we $want, now
565 # lets see if we need to apply more patches:
566 my $di = $diffs->[0];
567 my $src = $di->{oid_a};
569 unless ($src =~ /\A0+\z/) {
570 # we have to solve it using another oid, fine:
571 my $job = { oid_b => $src, path_b => $di->{path_a} };
572 push @{$self->{todo}}, $job;
574 return next_step($self); # onto the next todo item
576 try_harder($self, $want);
579 sub extract_diff_async {
580 my ($bref, $oid, $type, $size, $x) = @_;
581 my ($self, $want, $smsg) = @$x;
583 $smsg->{blob} eq $oid or
584 ERR($self, "BUG: $smsg->{blob} != $oid");
585 PublicInbox::Eml->new($bref)->each_part(\&extract_diff, $x, 1);
588 scalar(@{$want->{try_smsgs}}) ? retry_current($self, $want)
589 : extract_diffs_done($self, $want);
592 sub resolve_patch ($$) {
593 my ($self, $want) = @_;
595 my $cur_want = $want->{oid_b};
596 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
597 die "Aborting, too many steps to $self->{oid_want}";
600 if (my $msgs = $want->{try_smsgs}) {
601 my $smsg = shift @$msgs;
602 if ($self->{psgi_env}->{'pi-httpd.async'}) {
603 return ibx_async_cat($want->{cur_ibx}, $smsg->{blob},
604 \&extract_diff_async,
605 [$self, $want, $smsg]);
607 if (my $eml = $want->{cur_ibx}->smsg_eml($smsg)) {
608 $eml->each_part(\&extract_diff,
609 [ $self, $want, $smsg ], 1);
613 return scalar(@$msgs) ? retry_current($self, $want)
614 : extract_diffs_done($self, $want);
617 # see if we can find the blob in an existing git repo:
618 if (!$want->{try_ibxs} && $self->{seen_oid}->{$cur_want}++) {
619 die "Loop detected solving $cur_want\n";
621 $want->{try_ibxs} //= [ @{$self->{inboxes}} ]; # array copy
622 my $existing = solve_existing($self, $want);
624 my ($found_git, undef, $type, undef) = @$existing;
625 dbg($self, "found $cur_want in " .
627 $found_git->pub_urls($self->{psgi_env})));
629 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
630 eval { done($self, $existing) };
634 mark_found($self, $cur_want, $existing);
635 return next_step($self); # onto patch application
636 } elsif ($existing > 0) {
637 return retry_current($self, $want);
638 } else { # $existing == 0: we may retry if inbox scan (below) fails
639 delete $want->{try_gits};
642 # scan through inboxes to look for emails which results in
644 my $ibx = shift(@{$want->{try_ibxs}}) or die 'BUG: {try_ibxs} empty';
645 if (my $msgs = find_smsgs($self, $ibx, $want)) {
646 $want->{try_smsgs} = $msgs;
647 $want->{cur_ibx} = $ibx;
648 $self->{tmp_diffs} = [];
649 return retry_current($self, $want);
651 try_harder($self, $want);
654 # this API is designed to avoid creating self-referential structures;
655 # so user_cb never references the SolverGit object
657 my ($class, $ibx, $user_cb, $uarg) = @_;
660 gits => $ibx->{-repo_objs},
663 # -cur_di, -qsp, -msg => temporary fields for Qspawn callbacks
665 # TODO: config option for searching related inboxes
670 # recreate $oid_want using $hints
671 # hints keys: path_a, path_b, oid_a (note: `oid_b' is NOT a hint)
672 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
673 # with found object, or undef if nothing was found
674 # Calls {user_cb} with a string error on fatal errors
676 my ($self, $env, $out, $oid_want, $hints) = @_;
678 # should we even get here? Probably not, but somebody
679 # could be manually typing URLs:
680 return done($self, undef) if $oid_want =~ /\A0+\z/;
682 $self->{oid_want} = $oid_want;
684 $self->{seen_oid} = {};
686 $self->{psgi_env} = $env;
687 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
688 $self->{patches} = []; # [ $di, $di, ... ]
689 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
690 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXX", TMPDIR => 1);
692 dbg($self, "solving $oid_want ...");
693 if (my $async = $env->{'pi-httpd.async'}) {
694 # PublicInbox::HTTPD::Async->new
695 $async->(undef, undef, $self);
697 event_step($self) while $self->{user_cb};