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 File::Temp 0.19 ();
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;
107 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
108 # change it back to LF:
109 my $cte = $part->header('Content-Transfer-Encoding') || '';
110 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
114 state $LF = qr!\r?\n!;
115 state $FN = qr!(?:("?[^/\n]+/[^\r\n]+)|/dev/null)!;
117 $s =~ m!( # $1 start header lines we save for debugging:
119 # everything before ^index is optional, but we don't
120 # want to match ^(old|copy|rename|deleted|...) unless
121 # we match /^diff --git/ first:
122 (?: # begin optional stuff:
124 # try to get the pre-and-post filenames as $2 and $3
125 (?:^diff\x20--git\x20$FN\x20$FN$LF)
128 (?:^old mode\x20(100644|120000|100755)$LF)?
131 (?:^(?:copy|rename|deleted|dissimilarity|similarity).*$LF)?
133 # new mode (possibly new file) ($5)
134 (?:^new\x20(?:file\x20)?mode\x20(100644|120000|100755)$LF)?
137 (?:^(?:copy|rename|deleted|dissimilarity|similarity).*$LF)?
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\-\\][^\r\n]*|)$LF)+
162 my $path_a = $2 // $10;
163 my $path_b = $3 // $11;
166 $di->{mode_a} = $5 // $8 // $4; # new (file) // unchanged // old
169 # don't care for leading 'a/' and 'b/'
170 my (undef, @a) = split(m{/}, git_unquote($path_a));
171 my (undef, @b) = split(m{/}, git_unquote($path_b));
173 # get rid of path-traversal attempts and junk patches:
174 # it's junk at best, an attack attempt at worse:
175 state $bad_component = { map { $_ => 1 } ('', '.', '..') };
176 foreach (@a, @b) { return if $bad_component->{$_} }
178 $di->{path_a} = join('/', @a);
179 $di->{path_b} = join('/', @b);
181 utf8::encode($hdr_lines);
182 utf8::encode($patch);
183 my $path = ++$self->{tot};
185 open(my $tmp, '>', $self->{tmp}->dirname . "/$path") or
187 print $tmp $hdr_lines, $patch or die "print(tmp): $!";
188 close $tmp or die "close(tmp): $!";
190 # for debugging/diagnostics:
193 $di->{hdr_lines} = $hdr_lines;
198 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
200 # ".." appears in path names, which confuses Xapian into treating
201 # it as a range query. So we split on ".." since Xapian breaks
202 # on punctuation anyways:
203 sub filename_query ($) {
204 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
207 sub find_extract_diffs ($$$) {
208 my ($self, $ibx, $want) = @_;
209 my $srch = $ibx->search or return;
211 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
212 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
214 my $q = "dfpost:$post";
215 my $pre = $want->{oid_a};
216 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
219 $pre = '[a-f0-9]{7}'; # for $re below
222 my $path_b = $want->{path_b};
223 if (path_searchable($path_b)) {
224 $q .= filename_query($path_b);
226 my $path_a = $want->{path_a};
227 if (path_searchable($path_a) && $path_a ne $path_b) {
228 $q .= filename_query($path_a);
232 my $msgs = $srch->query($q, { relevance => 1 });
235 foreach my $smsg (@$msgs) {
236 $ibx->smsg_mime($smsg) or next;
237 my $mime = delete $smsg->{mime};
238 msg_iter($mime, \&extract_diff,
239 [$self, $diffs, $pre, $post, $ibx, $smsg]);
241 @$diffs ? $diffs : undef;
244 sub update_index_result ($$) {
245 my ($bref, $self) = @_;
246 my ($qsp, $msg) = delete @$self{qw(-qsp -msg)};
247 if (my $err = $qsp->{err}) {
248 ERR($self, "git update-index error: $err");
251 next_step($self); # onto do_git_apply
254 sub prepare_index ($) {
256 my $patches = $self->{patches};
259 my $di = $patches->[0] or die 'no patches';
260 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
261 my $existing = $self->{found}->{$oid_a};
263 # no index creation for added files
264 $oid_a =~ /\A0+\z/ and return next_step($self);
266 die "BUG: $oid_a not not found" unless $existing;
268 my $oid_full = $existing->[1];
269 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
270 my $mode_a = $di->{mode_a} // '100644';
272 my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
273 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
274 $in->flush or die "flush: $!";
275 sysseek($in, 0, 0) or die "seek: $!";
277 dbg($self, 'preparing index');
278 my $rdr = { 0 => $in };
279 my $cmd = [ qw(git update-index -z --index-info) ];
280 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
281 $path_a = git_quote($path_a);
282 $self->{-qsp} = $qsp;
283 $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
284 $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
287 # pure Perl "git init"
288 sub do_git_init ($) {
290 my $dir = $self->{tmp}->dirname;
291 my $git_dir = "$dir/git";
293 foreach ('', qw(objects refs objects/info refs/heads)) {
294 mkdir("$git_dir/$_") or die "mkdir $_: $!";
296 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
297 print $fh <<'EOF' or die "print git/config $!";
299 repositoryFormatVersion = 0
302 fsyncObjectfiles = false
303 logAllRefUpdates = false
305 close $fh or die "close git/config: $!";
307 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
308 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
309 close $fh or die "close git/HEAD: $!";
311 my $f = 'objects/info/alternates';
312 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
313 foreach my $git (@{$self->{gits}}) {
314 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
316 close $fh or die "close: $f: $!";
317 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
318 $tmp_git->{-tmp} = $self->{tmp};
321 GIT_INDEX_FILE => "$git_dir/index",
323 prepare_index($self);
328 my ($found, $oid_want) = @$self{qw(found oid_want)};
329 if (my $exists = $found->{$oid_want}) {
330 return done($self, $exists);
333 # let git disambiguate if oid_want was too short,
334 # but long enough to be unambiguous:
335 my $tmp_git = $self->{tmp_git};
336 if (my @res = $tmp_git->check($oid_want)) {
337 return done($self, $found->{$res[0]});
339 if (my $err = $tmp_git->last_check_err) {
348 # step 1: resolve blobs to patches in the todo queue
349 if (my $want = pop @{$self->{todo}}) {
350 # this populates {patches} and {todo}
351 resolve_patch($self, $want);
353 # step 2: then we instantiate a working tree once
354 # the todo queue is finally empty:
355 } elsif (!defined($self->{tmp_git})) {
358 # step 3: apply each patch in the stack
359 } elsif (scalar @{$self->{patches}}) {
362 # step 4: execute the user-supplied callback with
363 # our result: (which may be undef)
364 # Other steps may call user_cb to terminate prematurely
366 } elsif (exists $self->{user_cb}) {
369 die 'about to call user_cb twice'; # Oops :x
374 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
375 dbg($self, "E: $err");
376 eval { done($self, $err) };
382 # if outside of public-inbox-httpd, caller is expected to be
383 # looping event_step, anyways
384 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
385 # PublicInbox::HTTPD::Async->new
386 $async->(undef, undef, $self);
389 sub mark_found ($$$) {
390 my ($self, $oid, $found_info) = @_;
391 my $found = $self->{found};
392 $found->{$oid} = $found_info;
393 my $oid_cur = $found_info->[1];
394 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
395 $found->{$oid_cur} = $found_info;
400 sub parse_ls_files ($$) {
401 my ($self, $bref) = @_;
402 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
403 if (my $err = $qsp->{err}) {
404 die "git ls-files error: $err";
407 my ($line, @extra) = split(/\0/, $$bref);
408 scalar(@extra) and die "BUG: extra files in index: <",
409 join('> <', @extra), ">";
411 my ($info, $file) = split(/\t/, $line, 2);
412 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
413 if ($file ne $di->{path_b}) {
415 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
418 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
419 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
420 defined($size) or die "check $oid_b_full failed";
422 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
423 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
424 mark_found($self, $di->{oid_b}, $created);
425 next_step($self); # onto the next patch
428 sub ls_files_result {
429 my ($bref, $self) = @_;
430 eval { parse_ls_files($self, $bref) };
431 ERR($self, $@) if $@;
434 sub oids_same_ish ($$) {
435 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
438 sub skip_identical ($$$) {
439 my ($self, $patches, $cur_oid_b) = @_;
440 while (my $nxt = $patches->[0]) {
441 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
442 dbg($self, 'skipping '.di_url($self, $nxt).
451 sub apply_result ($$) {
452 my ($bref, $self) = @_;
453 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
455 my $patches = $self->{patches};
456 if (my $err = $qsp->{err}) {
457 my $msg = "git apply error: $err";
458 my $nxt = $patches->[0];
459 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
461 dbg($self, 'trying '.di_url($self, $nxt));
462 return do_git_apply($self);
467 skip_identical($self, $patches, $di->{oid_b});
470 my @cmd = qw(git ls-files -s -z);
471 $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
472 $self->{-cur_di} = $di;
473 $self->{-qsp} = $qsp;
474 $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
477 sub do_git_apply ($) {
479 my $dn = $self->{tmp}->dirname;
480 my $patches = $self->{patches};
482 # we need --ignore-whitespace because some patches are CRLF
483 my @cmd = (qw(git apply --cached --ignore-whitespace
484 --unidiff-zero --whitespace=warn --verbose));
485 my $len = length(join(' ', @cmd));
486 my $total = $self->{tot};
487 my $di; # keep track of the last one for "git ls-files"
491 my $i = ++$self->{nr};
492 $di = shift @$patches;
493 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
494 "\n" . $di->{hdr_lines});
496 $len += length($path) + 1;
498 $prv_oid_b = $di->{oid_b};
499 } while (@$patches && $len < $ARG_SIZE_MAX &&
500 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
502 my $opt = { 2 => 1, -C => $dn };
503 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
504 $self->{-cur_di} = $di;
505 $self->{-qsp} = $qsp;
506 $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
510 my ($self, $di) = @_;
511 # note: we don't pass the PSGI env unconditionally, here,
512 # different inboxes can have different HTTP_HOST on the same instance.
513 my $ibx = $di->{ibx};
514 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
515 my $url = $ibx->base_url($env);
516 my $mid = $di->{smsg}->{mid};
517 defined($url) ? "$url$mid/" : "<$mid>";
520 sub resolve_patch ($$) {
521 my ($self, $want) = @_;
523 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
524 die "Aborting, too many steps to $self->{oid_want}";
527 # see if we can find the blob in an existing git repo:
528 my $cur_want = $want->{oid_b};
529 if ($self->{seen_oid}->{$cur_want}++) {
530 die "Loop detected solving $cur_want\n";
532 if (my $existing = solve_existing($self, $want)) {
533 my ($found_git, undef, $type, undef) = @$existing;
534 dbg($self, "found $cur_want in " .
535 join("\n", $found_git->pub_urls($self->{psgi_env})));
537 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
538 eval { done($self, $existing) };
542 mark_found($self, $cur_want, $existing);
543 return next_step($self); # onto patch application
546 # scan through inboxes to look for emails which results in
548 foreach my $ibx (@{$self->{inboxes}}) {
549 my $diffs = find_extract_diffs($self, $ibx, $want) or next;
551 unshift @{$self->{patches}}, @$diffs;
552 dbg($self, "found $cur_want in ".
553 join("\n\t", map { di_url($self, $_) } @$diffs));
555 # good, we can find a path to the oid we $want, now
556 # lets see if we need to apply more patches:
557 my $di = $diffs->[0];
558 my $src = $di->{oid_a};
560 unless ($src =~ /\A0+\z/) {
561 # we have to solve it using another oid, fine:
562 my $job = { oid_b => $src, path_b => $di->{path_a} };
563 push @{$self->{todo}}, $job;
565 return next_step($self); # onto the next todo item
567 if (length($cur_want) > $OID_MIN) {
569 dbg($self, "retrying $want->{oid_b} as $cur_want");
570 $want->{oid_b} = $cur_want;
571 push @{$self->{todo}}, $want;
572 return next_step($self); # retry with shorter abbrev
575 dbg($self, "could not find $cur_want");
576 eval { done($self, undef) };
580 # this API is designed to avoid creating self-referential structures;
581 # so user_cb never references the SolverGit object
583 my ($class, $ibx, $user_cb, $uarg) = @_;
586 gits => $ibx->{-repo_objs},
589 # -cur_di, -qsp, -msg => temporary fields for Qspawn callbacks
591 # TODO: config option for searching related inboxes
596 # recreate $oid_want using $hints
597 # hints keys: path_a, path_b, oid_a
598 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
599 # with found object, or undef if nothing was found
600 # Calls {user_cb} with a string error on fatal errors
602 my ($self, $env, $out, $oid_want, $hints) = @_;
604 # should we even get here? Probably not, but somebody
605 # could be manually typing URLs:
606 return done($self, undef) if $oid_want =~ /\A0+\z/;
608 $self->{oid_want} = $oid_want;
610 $self->{seen_oid} = {};
612 $self->{psgi_env} = $env;
613 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
614 $self->{patches} = []; # [ $di, $di, ... ]
615 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
616 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
618 dbg($self, "solving $oid_want ...");
619 if (my $async = $env->{'pi-httpd.async'}) {
620 # PublicInbox::HTTPD::Async->new
621 $async->(undef, undef, $self);
623 event_step($self) while $self->{user_cb};