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_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.
38 my $ANY = qr![^\r\n]+!;
39 my $MODE = '100644|120000|100755';
40 my $FN = qr!(?:("?[^/\n]+/[^\r\n]+)|/dev/null)!;
41 my %BAD_COMPONENT = ('' => 1, '.' => 1, '..' => 1);
43 # di = diff info / a hashref with information about a diff ($di):
45 # oid_a => abbreviated pre-image oid,
46 # oid_b => abbreviated post-image oid,
47 # tmp => anonymous file handle with the diff,
48 # hdr_lines => string of various header lines for mode information
49 # mode_a => original mode of oid_a (string, not integer),
50 # ibx => PublicInbox::Inbox object containing the diff
51 # smsg => PublicInbox::Smsg object containing diff
52 # path_a => pre-image path
53 # path_b => post-image path
54 # n => numeric path of the patch (relative to worktree)
58 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
62 my ($self, $res) = @_;
63 my $ucb = delete($self->{user_cb}) or return;
64 $ucb->($res, $self->{uarg});
68 my ($self, $err) = @_;
69 print { $self->{out} } $err, "\n";
70 eval { done($self, $err) };
74 # look for existing objects already in git repos
75 sub solve_existing ($$) {
76 my ($self, $want) = @_;
77 my $oid_b = $want->{oid_b};
78 my $have_hints = scalar keys %$want > 1;
79 my @ambiguous; # Array of [ git, $oids]
80 foreach my $git (@{$self->{gits}}) {
81 my ($oid_full, $type, $size) = $git->check($oid_b);
82 if (defined($type) && (!$have_hints || $type eq 'blob')) {
83 return [ $git, $oid_full, $type, int($size) ];
86 next if length($oid_b) == 40;
88 # parse stderr of "git cat-file --batch-check"
89 my $err = $git->last_check_err;
90 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
91 next unless scalar(@oids);
93 # TODO: do something with the ambiguous array?
94 # push @ambiguous, [ $git, @oids ];
96 dbg($self, "`$oid_b' ambiguous in " .
97 join("\n\t", $git->pub_urls($self->{psgi_env}))
99 join('', map { "$_ blob\n" } @oids));
101 scalar(@ambiguous) ? \@ambiguous : undef;
104 sub extract_diff ($$) {
106 my ($self, $diffs, $pre, $post, $ibx, $smsg) = @$arg;
107 my ($part) = @$p; # ignore $depth and @idx;
108 my $ct = $part->content_type || 'text/plain';
109 my ($s, undef) = msg_part_text($part, $ct);
110 defined $s or return;
112 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
113 # change it back to LF:
114 my $cte = $part->header('Content-Transfer-Encoding') || '';
115 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
120 $s =~ m!( # $1 start header lines we save for debugging:
122 # everything before ^index is optional, but we don't
123 # want to match ^(old|copy|rename|deleted|...) unless
124 # we match /^diff --git/ first:
125 (?: # begin optional stuff:
127 # try to get the pre-and-post filenames as $2 and $3
128 (?:^diff\x20--git\x20$FN\x20$FN$LF)
130 (?:^(?: # pass all this to git-apply:
132 (?:old\x20mode\x20($MODE))
134 # new mode (possibly new file) ($5)
135 (?:new\x20(?:file\x20)?mode\x20($MODE))
137 (?:(?:copy|rename|deleted|
138 dissimilarity|similarity)$ANY)
141 )? # end of optional stuff, everything below is required
143 # match the pre and post-image OIDs as $6 $7
144 ^index\x20(${pre}[a-f0-9]*)\.\.(${post}[a-f0-9]*)
145 # mode if unchanged $8
146 (?:\x20(100644|120000|100755))?$LF
147 ) # end of header lines ($1)
148 ( # $9 is the patch body
149 # "--- a/foo.c" sets pre-filename ($10) in case
153 # "+++ b/foo.c" sets post-filename ($11) in case
157 # the meat of the diff, including "^\\No newline ..."
158 # We also allow for totally blank lines w/o leading spaces,
159 # because git-apply(1) handles that case, too
160 (?:^(?:[\@\+\x20\-\\][^\n]*|)$LF)+
167 mode_a => $5 // $8 // $4, # new (file) // unchanged // old
169 my $path_a = $2 // $10;
170 my $path_b = $3 // $11;
173 # don't care for leading 'a/' and 'b/'
174 my (undef, @a) = split(m{/}, git_unquote($path_a)) if defined($path_a);
175 my (undef, @b) = split(m{/}, git_unquote($path_b));
177 # get rid of path-traversal attempts and junk patches:
178 # it's junk at best, an attack attempt at worse:
179 foreach (@a, @b) { return if $BAD_COMPONENT{$_} }
181 $di->{path_a} = join('/', @a) if @a;
182 $di->{path_b} = join('/', @b);
184 my $path = ++$self->{tot};
186 open(my $tmp, '>:utf8', $self->{tmp}->dirname . "/$path") or
188 print $tmp $di->{hdr_lines}, $patch or die "print(tmp): $!";
189 close $tmp or die "close(tmp): $!";
191 # for debugging/diagnostics:
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 my $eml = $ibx->smsg_eml($smsg) or next;
237 $eml->each_part(\&extract_diff,
238 [$self, $diffs, $pre, $post, $ibx, $smsg], 1);
240 @$diffs ? $diffs : 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 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, 0) 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 print $fh <<'EOF' or die "print git/config $!";
298 repositoryFormatVersion = 0
301 fsyncObjectfiles = false
302 logAllRefUpdates = false
304 close $fh or die "close git/config: $!";
306 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
307 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
308 close $fh or die "close git/HEAD: $!";
310 my $f = 'objects/info/alternates';
311 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
312 foreach my $git (@{$self->{gits}}) {
313 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
315 close $fh or die "close: $f: $!";
316 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
317 $tmp_git->{-tmp} = $self->{tmp};
320 GIT_INDEX_FILE => "$git_dir/index",
322 prepare_index($self);
327 my ($found, $oid_want) = @$self{qw(found oid_want)};
328 if (my $exists = $found->{$oid_want}) {
329 return done($self, $exists);
332 # let git disambiguate if oid_want was too short,
333 # but long enough to be unambiguous:
334 my $tmp_git = $self->{tmp_git};
335 if (my @res = $tmp_git->check($oid_want)) {
336 return done($self, $found->{$res[0]});
338 if (my $err = $tmp_git->last_check_err) {
347 # step 1: resolve blobs to patches in the todo queue
348 if (my $want = pop @{$self->{todo}}) {
349 # this populates {patches} and {todo}
350 resolve_patch($self, $want);
352 # step 2: then we instantiate a working tree once
353 # the todo queue is finally empty:
354 } elsif (!defined($self->{tmp_git})) {
357 # step 3: apply each patch in the stack
358 } elsif (scalar @{$self->{patches}}) {
361 # step 4: execute the user-supplied callback with
362 # our result: (which may be undef)
363 # Other steps may call user_cb to terminate prematurely
365 } elsif (exists $self->{user_cb}) {
368 die 'about to call user_cb twice'; # Oops :x
373 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
374 dbg($self, "E: $err");
375 eval { done($self, $err) };
381 # if outside of public-inbox-httpd, caller is expected to be
382 # looping event_step, anyways
383 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
384 # PublicInbox::HTTPD::Async->new
385 $async->(undef, undef, $self);
388 sub mark_found ($$$) {
389 my ($self, $oid, $found_info) = @_;
390 my $found = $self->{found};
391 $found->{$oid} = $found_info;
392 my $oid_cur = $found_info->[1];
393 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
394 $found->{$oid_cur} = $found_info;
399 sub parse_ls_files ($$) {
400 my ($self, $bref) = @_;
401 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
402 if (my $err = $qsp->{err}) {
403 die "git ls-files error: $err";
406 my ($line, @extra) = split(/\0/, $$bref);
407 scalar(@extra) and die "BUG: extra files in index: <",
408 join('> <', @extra), ">";
410 my ($info, $file) = split(/\t/, $line, 2);
411 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
412 if ($file ne $di->{path_b}) {
414 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
417 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
418 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
419 defined($size) or die "check $oid_b_full failed";
421 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
422 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
423 mark_found($self, $di->{oid_b}, $created);
424 next_step($self); # onto the next patch
427 sub ls_files_result {
428 my ($bref, $self) = @_;
429 eval { parse_ls_files($self, $bref) };
430 ERR($self, $@) if $@;
433 sub oids_same_ish ($$) {
434 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
437 sub skip_identical ($$$) {
438 my ($self, $patches, $cur_oid_b) = @_;
439 while (my $nxt = $patches->[0]) {
440 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
441 dbg($self, 'skipping '.di_url($self, $nxt).
450 sub apply_result ($$) {
451 my ($bref, $self) = @_;
452 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
454 my $patches = $self->{patches};
455 if (my $err = $qsp->{err}) {
456 my $msg = "git apply error: $err";
457 my $nxt = $patches->[0];
458 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
460 dbg($self, 'trying '.di_url($self, $nxt));
461 return do_git_apply($self);
466 skip_identical($self, $patches, $di->{oid_b});
469 my @cmd = qw(git ls-files -s -z);
470 $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
471 $self->{-cur_di} = $di;
472 $self->{-qsp} = $qsp;
473 $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
476 sub do_git_apply ($) {
478 my $dn = $self->{tmp}->dirname;
479 my $patches = $self->{patches};
481 # we need --ignore-whitespace because some patches are CRLF
482 my @cmd = (qw(git apply --cached --ignore-whitespace
483 --unidiff-zero --whitespace=warn --verbose));
484 my $len = length(join(' ', @cmd));
485 my $total = $self->{tot};
486 my $di; # keep track of the last one for "git ls-files"
490 my $i = ++$self->{nr};
491 $di = shift @$patches;
492 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
493 "\n" . $di->{hdr_lines});
495 $len += length($path) + 1;
497 $prv_oid_b = $di->{oid_b};
498 } while (@$patches && $len < $ARG_SIZE_MAX &&
499 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
501 my $opt = { 2 => 1, -C => $dn, quiet => 1 };
502 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
503 $self->{-cur_di} = $di;
504 $self->{-qsp} = $qsp;
505 $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
509 my ($self, $di) = @_;
510 # note: we don't pass the PSGI env unconditionally, here,
511 # different inboxes can have different HTTP_HOST on the same instance.
512 my $ibx = $di->{ibx};
513 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
514 my $url = $ibx->base_url($env);
515 my $mid = $di->{smsg}->{mid};
516 defined($url) ? "$url$mid/" : "<$mid>";
519 sub resolve_patch ($$) {
520 my ($self, $want) = @_;
522 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
523 die "Aborting, too many steps to $self->{oid_want}";
526 # see if we can find the blob in an existing git repo:
527 my $cur_want = $want->{oid_b};
528 if ($self->{seen_oid}->{$cur_want}++) {
529 die "Loop detected solving $cur_want\n";
531 if (my $existing = solve_existing($self, $want)) {
532 my ($found_git, undef, $type, undef) = @$existing;
533 dbg($self, "found $cur_want in " .
535 $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 (note: `oid_b' is NOT a hint)
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};