1 # Copyright (C) 2019-2020 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;
14 use File::Temp 0.19 (); # 0.19 for ->newdir
15 use Fcntl qw(SEEK_SET);
16 use PublicInbox::Git qw(git_unquote git_quote);
17 use PublicInbox::MsgIter qw(msg_iter msg_part_text);
18 use PublicInbox::Qspawn;
19 use PublicInbox::Tmpfile;
20 use URI::Escape qw(uri_escape_utf8);
22 # POSIX requires _POSIX_ARG_MAX >= 4096, and xargs is required to
23 # subtract 2048 bytes. We also don't factor in environment variable
25 use POSIX qw(sysconf _SC_ARG_MAX);
26 my $ARG_SIZE_MAX = (sysconf(_SC_ARG_MAX) || 4096) - 2048;
29 # By default, "git format-patch" generates filenames with a four-digit
30 # prefix, so that means 9999 patch series are OK, right? :>
31 # Maybe we can make this configurable, main concern is disk space overhead
32 # for uncompressed patch fragments. Aside from space, public-inbox-httpd
33 # is otherwise unaffected by having many patches, here, as it can share
34 # work fairly. Other PSGI servers may have trouble, though.
37 # di = diff info / a hashref with information about a diff ($di):
39 # oid_a => abbreviated pre-image oid,
40 # oid_b => abbreviated post-image oid,
41 # tmp => anonymous file handle with the diff,
42 # hdr_lines => string of various header lines for mode information
43 # mode_a => original mode of oid_a (string, not integer),
44 # ibx => PublicInbox::Inbox object containing the diff
45 # smsg => PublicInbox::SearchMsg object containing diff
46 # path_a => pre-image path
47 # path_b => post-image path
48 # n => numeric path of the patch (relative to worktree)
52 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
56 my ($self, $res) = @_;
57 my $ucb = delete($self->{user_cb}) or return;
58 $ucb->($res, $self->{uarg});
62 my ($self, $err) = @_;
63 print { $self->{out} } $err, "\n";
64 eval { done($self, $err) };
68 # look for existing objects already in git repos
69 sub solve_existing ($$) {
70 my ($self, $want) = @_;
71 my $oid_b = $want->{oid_b};
72 my $have_hints = scalar keys %$want > 1;
73 my @ambiguous; # Array of [ git, $oids]
74 foreach my $git (@{$self->{gits}}) {
75 my ($oid_full, $type, $size) = $git->check($oid_b);
76 if (defined($type) && (!$have_hints || $type eq 'blob')) {
77 return [ $git, $oid_full, $type, int($size) ];
80 next if length($oid_b) == 40;
82 # parse stderr of "git cat-file --batch-check"
83 my $err = $git->last_check_err;
84 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
85 next unless scalar(@oids);
87 # TODO: do something with the ambiguous array?
88 # push @ambiguous, [ $git, @oids ];
90 dbg($self, "`$oid_b' ambiguous in " .
91 join("\n\t", $git->pub_urls($self->{psgi_env}))
93 join('', map { "$_ blob\n" } @oids));
95 scalar(@ambiguous) ? \@ambiguous : undef;
98 sub extract_diff ($$) {
100 my ($self, $diffs, $pre, $post, $ibx, $smsg) = @$arg;
101 my ($part) = @$p; # ignore $depth and @idx;
102 my $ct = $part->content_type || 'text/plain';
103 my ($s, undef) = msg_part_text($part, $ct);
104 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 state $LF = qr!\r?\n!;
114 state $ANY = qr![^\r\n]+!;
115 state $MODE = '100644|120000|100755';
116 state $FN = qr!(?:("?[^/\n]+/[^\r\n]+)|/dev/null)!;
118 $s =~ m!( # $1 start header lines we save for debugging:
120 # everything before ^index is optional, but we don't
121 # want to match ^(old|copy|rename|deleted|...) unless
122 # we match /^diff --git/ first:
123 (?: # begin optional stuff:
125 # try to get the pre-and-post filenames as $2 and $3
126 (?:^diff\x20--git\x20$FN\x20$FN$LF)
128 (?:^(?: # pass all this to git-apply:
130 (?:old\x20mode\x20($MODE))
132 # new mode (possibly new file) ($5)
133 (?:new\x20(?:file\x20)?mode\x20($MODE))
135 (?:(?:copy|rename|deleted|
136 dissimilarity|similarity)$ANY)
139 )? # end of optional stuff, everything below is required
141 # match the pre and post-image OIDs as $6 $7
142 ^index\x20(${pre}[a-f0-9]*)\.\.(${post}[a-f0-9]*)
143 # mode if unchanged $8
144 (?:\x20(100644|120000|100755))?$LF
145 ) # end of header lines ($1)
146 ( # $9 is the patch body
147 # "--- a/foo.c" sets pre-filename ($10) in case
151 # "+++ b/foo.c" sets post-filename ($11) in case
155 # the meat of the diff, including "^\\No newline ..."
156 # We also allow for totally blank lines w/o leading spaces,
157 # because git-apply(1) handles that case, too
158 (?:^(?:[\@\+\x20\-\\][^\n]*|)$LF)+
165 mode_a => $5 // $8 // $4, # new (file) // unchanged // old
167 my $path_a = $2 // $10;
168 my $path_b = $3 // $11;
171 # don't care for leading 'a/' and 'b/'
172 my (undef, @a) = split(m{/}, git_unquote($path_a)) if defined($path_a);
173 my (undef, @b) = split(m{/}, git_unquote($path_b));
175 # get rid of path-traversal attempts and junk patches:
176 # it's junk at best, an attack attempt at worse:
177 state $bad_component = { map { $_ => 1 } ('', '.', '..') };
178 foreach (@a, @b) { return if $bad_component->{$_} }
180 $di->{path_a} = join('/', @a) if @a;
181 $di->{path_b} = join('/', @b);
183 my $path = ++$self->{tot};
185 open(my $tmp, '>:utf8', $self->{tmp}->dirname . "/$path") or
187 print $tmp $di->{hdr_lines}, $patch or die "print(tmp): $!";
188 close $tmp or die "close(tmp): $!";
190 # for debugging/diagnostics:
197 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
199 # ".." appears in path names, which confuses Xapian into treating
200 # it as a range query. So we split on ".." since Xapian breaks
201 # on punctuation anyways:
202 sub filename_query ($) {
203 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
206 sub find_extract_diffs ($$$) {
207 my ($self, $ibx, $want) = @_;
208 my $srch = $ibx->search or return;
210 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
211 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
213 my $q = "dfpost:$post";
214 my $pre = $want->{oid_a};
215 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
218 $pre = '[a-f0-9]{7}'; # for $re below
221 my $path_b = $want->{path_b};
222 if (path_searchable($path_b)) {
223 $q .= filename_query($path_b);
225 my $path_a = $want->{path_a};
226 if (path_searchable($path_a) && $path_a ne $path_b) {
227 $q .= filename_query($path_a);
231 my $msgs = $srch->query($q, { relevance => 1 });
234 foreach my $smsg (@$msgs) {
235 $ibx->smsg_mime($smsg) or next;
236 msg_iter(delete $smsg->{mime}, \&extract_diff,
237 [$self, $diffs, $pre, $post, $ibx, $smsg], 1);
239 @$diffs ? $diffs : undef;
242 sub update_index_result ($$) {
243 my ($bref, $self) = @_;
244 my ($qsp, $msg) = delete @$self{qw(-qsp -msg)};
245 if (my $err = $qsp->{err}) {
246 ERR($self, "git update-index error: $err");
249 next_step($self); # onto do_git_apply
252 sub prepare_index ($) {
254 my $patches = $self->{patches};
257 my $di = $patches->[0] or die 'no patches';
258 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
259 my $existing = $self->{found}->{$oid_a};
261 # no index creation for added files
262 $oid_a =~ /\A0+\z/ and return next_step($self);
264 die "BUG: $oid_a not not found" unless $existing;
266 my $oid_full = $existing->[1];
267 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
268 my $mode_a = $di->{mode_a} // '100644';
270 my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
271 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
272 $in->flush or die "flush: $!";
273 sysseek($in, 0, 0) or die "seek: $!";
275 dbg($self, 'preparing index');
276 my $rdr = { 0 => $in };
277 my $cmd = [ qw(git update-index -z --index-info) ];
278 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
279 $path_a = git_quote($path_a);
280 $self->{-qsp} = $qsp;
281 $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
282 $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
285 # pure Perl "git init"
286 sub do_git_init ($) {
288 my $dir = $self->{tmp}->dirname;
289 my $git_dir = "$dir/git";
291 foreach ('', qw(objects refs objects/info refs/heads)) {
292 mkdir("$git_dir/$_") or die "mkdir $_: $!";
294 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
295 print $fh <<'EOF' or die "print git/config $!";
297 repositoryFormatVersion = 0
300 fsyncObjectfiles = false
301 logAllRefUpdates = false
303 close $fh or die "close git/config: $!";
305 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
306 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
307 close $fh or die "close git/HEAD: $!";
309 my $f = 'objects/info/alternates';
310 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
311 foreach my $git (@{$self->{gits}}) {
312 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
314 close $fh or die "close: $f: $!";
315 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
316 $tmp_git->{-tmp} = $self->{tmp};
319 GIT_INDEX_FILE => "$git_dir/index",
321 prepare_index($self);
326 my ($found, $oid_want) = @$self{qw(found oid_want)};
327 if (my $exists = $found->{$oid_want}) {
328 return done($self, $exists);
331 # let git disambiguate if oid_want was too short,
332 # but long enough to be unambiguous:
333 my $tmp_git = $self->{tmp_git};
334 if (my @res = $tmp_git->check($oid_want)) {
335 return done($self, $found->{$res[0]});
337 if (my $err = $tmp_git->last_check_err) {
346 # step 1: resolve blobs to patches in the todo queue
347 if (my $want = pop @{$self->{todo}}) {
348 # this populates {patches} and {todo}
349 resolve_patch($self, $want);
351 # step 2: then we instantiate a working tree once
352 # the todo queue is finally empty:
353 } elsif (!defined($self->{tmp_git})) {
356 # step 3: apply each patch in the stack
357 } elsif (scalar @{$self->{patches}}) {
360 # step 4: execute the user-supplied callback with
361 # our result: (which may be undef)
362 # Other steps may call user_cb to terminate prematurely
364 } elsif (exists $self->{user_cb}) {
367 die 'about to call user_cb twice'; # Oops :x
372 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
373 dbg($self, "E: $err");
374 eval { done($self, $err) };
380 # if outside of public-inbox-httpd, caller is expected to be
381 # looping event_step, anyways
382 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
383 # PublicInbox::HTTPD::Async->new
384 $async->(undef, undef, $self);
387 sub mark_found ($$$) {
388 my ($self, $oid, $found_info) = @_;
389 my $found = $self->{found};
390 $found->{$oid} = $found_info;
391 my $oid_cur = $found_info->[1];
392 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
393 $found->{$oid_cur} = $found_info;
398 sub parse_ls_files ($$) {
399 my ($self, $bref) = @_;
400 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
401 if (my $err = $qsp->{err}) {
402 die "git ls-files error: $err";
405 my ($line, @extra) = split(/\0/, $$bref);
406 scalar(@extra) and die "BUG: extra files in index: <",
407 join('> <', @extra), ">";
409 my ($info, $file) = split(/\t/, $line, 2);
410 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
411 if ($file ne $di->{path_b}) {
413 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
416 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
417 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
418 defined($size) or die "check $oid_b_full failed";
420 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
421 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
422 mark_found($self, $di->{oid_b}, $created);
423 next_step($self); # onto the next patch
426 sub ls_files_result {
427 my ($bref, $self) = @_;
428 eval { parse_ls_files($self, $bref) };
429 ERR($self, $@) if $@;
432 sub oids_same_ish ($$) {
433 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
436 sub skip_identical ($$$) {
437 my ($self, $patches, $cur_oid_b) = @_;
438 while (my $nxt = $patches->[0]) {
439 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
440 dbg($self, 'skipping '.di_url($self, $nxt).
449 sub apply_result ($$) {
450 my ($bref, $self) = @_;
451 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
453 my $patches = $self->{patches};
454 if (my $err = $qsp->{err}) {
455 my $msg = "git apply error: $err";
456 my $nxt = $patches->[0];
457 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
459 dbg($self, 'trying '.di_url($self, $nxt));
460 return do_git_apply($self);
465 skip_identical($self, $patches, $di->{oid_b});
468 my @cmd = qw(git ls-files -s -z);
469 $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
470 $self->{-cur_di} = $di;
471 $self->{-qsp} = $qsp;
472 $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
475 sub do_git_apply ($) {
477 my $dn = $self->{tmp}->dirname;
478 my $patches = $self->{patches};
480 # we need --ignore-whitespace because some patches are CRLF
481 my @cmd = (qw(git apply --cached --ignore-whitespace
482 --unidiff-zero --whitespace=warn --verbose));
483 my $len = length(join(' ', @cmd));
484 my $total = $self->{tot};
485 my $di; # keep track of the last one for "git ls-files"
489 my $i = ++$self->{nr};
490 $di = shift @$patches;
491 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
492 "\n" . $di->{hdr_lines});
494 $len += length($path) + 1;
496 $prv_oid_b = $di->{oid_b};
497 } while (@$patches && $len < $ARG_SIZE_MAX &&
498 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
500 my $opt = { 2 => 1, -C => $dn, quiet => 1 };
501 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
502 $self->{-cur_di} = $di;
503 $self->{-qsp} = $qsp;
504 $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
508 my ($self, $di) = @_;
509 # note: we don't pass the PSGI env unconditionally, here,
510 # different inboxes can have different HTTP_HOST on the same instance.
511 my $ibx = $di->{ibx};
512 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
513 my $url = $ibx->base_url($env);
514 my $mid = $di->{smsg}->{mid};
515 defined($url) ? "$url$mid/" : "<$mid>";
518 sub resolve_patch ($$) {
519 my ($self, $want) = @_;
521 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
522 die "Aborting, too many steps to $self->{oid_want}";
525 # see if we can find the blob in an existing git repo:
526 my $cur_want = $want->{oid_b};
527 if ($self->{seen_oid}->{$cur_want}++) {
528 die "Loop detected solving $cur_want\n";
530 if (my $existing = solve_existing($self, $want)) {
531 my ($found_git, undef, $type, undef) = @$existing;
532 dbg($self, "found $cur_want in " .
534 $found_git->pub_urls($self->{psgi_env})));
536 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
537 eval { done($self, $existing) };
541 mark_found($self, $cur_want, $existing);
542 return next_step($self); # onto patch application
545 # scan through inboxes to look for emails which results in
547 foreach my $ibx (@{$self->{inboxes}}) {
548 my $diffs = find_extract_diffs($self, $ibx, $want) or next;
550 unshift @{$self->{patches}}, @$diffs;
551 dbg($self, "found $cur_want in ".
552 join(" ||\n\t", map { di_url($self, $_) } @$diffs));
554 # good, we can find a path to the oid we $want, now
555 # lets see if we need to apply more patches:
556 my $di = $diffs->[0];
557 my $src = $di->{oid_a};
559 unless ($src =~ /\A0+\z/) {
560 # we have to solve it using another oid, fine:
561 my $job = { oid_b => $src, path_b => $di->{path_a} };
562 push @{$self->{todo}}, $job;
564 return next_step($self); # onto the next todo item
566 if (length($cur_want) > $OID_MIN) {
568 dbg($self, "retrying $want->{oid_b} as $cur_want");
569 $want->{oid_b} = $cur_want;
570 push @{$self->{todo}}, $want;
571 return next_step($self); # retry with shorter abbrev
574 dbg($self, "could not find $cur_want");
575 eval { done($self, undef) };
579 # this API is designed to avoid creating self-referential structures;
580 # so user_cb never references the SolverGit object
582 my ($class, $ibx, $user_cb, $uarg) = @_;
585 gits => $ibx->{-repo_objs},
588 # -cur_di, -qsp, -msg => temporary fields for Qspawn callbacks
590 # TODO: config option for searching related inboxes
595 # recreate $oid_want using $hints
596 # hints keys: path_a, path_b, oid_a
597 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
598 # with found object, or undef if nothing was found
599 # Calls {user_cb} with a string error on fatal errors
601 my ($self, $env, $out, $oid_want, $hints) = @_;
603 # should we even get here? Probably not, but somebody
604 # could be manually typing URLs:
605 return done($self, undef) if $oid_want =~ /\A0+\z/;
607 $self->{oid_want} = $oid_want;
609 $self->{seen_oid} = {};
611 $self->{psgi_env} = $env;
612 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
613 $self->{patches} = []; # [ $di, $di, ... ]
614 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
615 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
617 dbg($self, "solving $oid_want ...");
618 if (my $async = $env->{'pi-httpd.async'}) {
619 # PublicInbox::HTTPD::Async->new
620 $async->(undef, undef, $self);
622 event_step($self) while $self->{user_cb};