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, $res) = @_;
60 my $ucb = delete($self->{user_cb}) or return;
61 $ucb->($res, $self->{uarg});
65 my ($self, $err) = @_;
66 print { $self->{out} } $err, "\n";
67 eval { done($self, $err) };
71 # look for existing objects already in git repos
72 sub solve_existing ($$) {
73 my ($self, $want) = @_;
74 my $oid_b = $want->{oid_b};
75 my $have_hints = scalar keys %$want > 1;
76 my @ambiguous; # Array of [ git, $oids]
77 foreach my $git (@{$self->{gits}}) {
78 my ($oid_full, $type, $size) = $git->check($oid_b);
79 if (defined($type) && (!$have_hints || $type eq 'blob')) {
80 return [ $git, $oid_full, $type, int($size) ];
83 next if length($oid_b) == 40;
85 # parse stderr of "git cat-file --batch-check"
86 my $err = $git->last_check_err;
87 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
88 next unless scalar(@oids);
90 # TODO: do something with the ambiguous array?
91 # push @ambiguous, [ $git, @oids ];
93 dbg($self, "`$oid_b' ambiguous in " .
94 join("\n\t", $git->pub_urls($self->{psgi_env}))
96 join('', map { "$_ blob\n" } @oids));
98 scalar(@ambiguous) ? \@ambiguous : undef;
101 sub extract_diff ($$) {
103 my ($self, $diffs, $re, $ibx, $smsg) = @$arg;
104 my ($part) = @$p; # ignore $depth and @idx;
105 my $hdr_lines; # diff --git a/... b/...
107 my $ct = $part->content_type || 'text/plain';
108 my ($s, undef) = msg_part_text($part, $ct);
109 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") {
119 foreach my $l (split(/^/m, $s)) {
125 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
126 $di->{mode_a} = $mode_a;
131 # start writing the diff out to a tempfile
132 my $path = ++$self->{tot};
134 open($tmp, '>', $self->{tmp}->dirname . "/$path") or
137 push @$hdr_lines, $l;
138 $di->{hdr_lines} = $hdr_lines;
139 utf8::encode($_) for @$hdr_lines;
140 print $tmp @$hdr_lines or die "print(tmp): $!";
142 # for debugging/diagnostics:
145 } elsif ($l =~ m!\Adiff --git ("?[^/]+/.+) ("?[^/]+/.+)$!) {
146 last if $tmp; # got our blob, done!
148 my ($path_a, $path_b) = ($1, $2);
150 # diff header lines won't have \r because git
151 # will quote them, but Email::MIME gives CRLF
152 # for quoted-printable:
155 # don't care for leading 'a/' and 'b/'
156 my (undef, @a) = split(m{/}, git_unquote($path_a));
157 my (undef, @b) = split(m{/}, git_unquote($path_b));
159 # get rid of path-traversal attempts and junk patches:
161 return if $bad_component{$_};
164 $di->{path_a} = join('/', @a);
165 $di->{path_b} = join('/', @b);
169 print $tmp $l or die "print(tmp): $!";
170 } elsif ($hdr_lines) {
171 push @$hdr_lines, $l;
172 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
177 return undef unless $tmp;
178 close $tmp or die "close(tmp): $!";
182 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
184 # ".." appears in path names, which confuses Xapian into treating
185 # it as a range query. So we split on ".." since Xapian breaks
186 # on punctuation anyways:
187 sub filename_query ($) {
188 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
191 sub find_extract_diffs ($$$) {
192 my ($self, $ibx, $want) = @_;
193 my $srch = $ibx->search or return;
195 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
196 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
198 my $q = "dfpost:$post";
199 my $pre = $want->{oid_a};
200 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
203 $pre = '[a-f0-9]{7}'; # for $re below
206 my $path_b = $want->{path_b};
207 if (path_searchable($path_b)) {
208 $q .= filename_query($path_b);
210 my $path_a = $want->{path_a};
211 if (path_searchable($path_a) && $path_a ne $path_b) {
212 $q .= filename_query($path_a);
216 my $msgs = $srch->query($q, { relevance => 1 });
217 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: ([0-9]+))?/;
219 foreach my $smsg (@$msgs) {
220 $ibx->smsg_mime($smsg) or next;
221 my $mime = delete $smsg->{mime};
222 msg_iter($mime, \&extract_diff,
223 [$self, $diffs, $re, $ibx, $smsg]);
225 @$diffs ? $diffs : undef;
228 sub update_index_result ($$) {
229 my ($bref, $self) = @_;
230 my ($qsp, $msg) = delete @$self{qw(-qsp -msg)};
231 if (my $err = $qsp->{err}) {
232 ERR($self, "git update-index error: $err");
235 next_step($self); # onto do_git_apply
238 sub prepare_index ($) {
240 my $patches = $self->{patches};
243 my $di = $patches->[0] or die 'no patches';
244 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
245 my $existing = $self->{found}->{$oid_a};
247 # no index creation for added files
248 $oid_a =~ /\A0+\z/ and return next_step($self);
250 die "BUG: $oid_a not not found" unless $existing;
252 my $oid_full = $existing->[1];
253 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
254 my $mode_a = $di->{mode_a} || extract_old_mode($di);
256 my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
257 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
258 $in->flush or die "flush: $!";
259 sysseek($in, 0, 0) or die "seek: $!";
261 dbg($self, 'preparing index');
262 my $rdr = { 0 => $in };
263 my $cmd = [ qw(git update-index -z --index-info) ];
264 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
265 $path_a = git_quote($path_a);
266 $self->{-qsp} = $qsp;
267 $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
268 $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
271 # pure Perl "git init"
272 sub do_git_init ($) {
274 my $dir = $self->{tmp}->dirname;
275 my $git_dir = "$dir/git";
277 foreach ('', qw(objects refs objects/info refs/heads)) {
278 mkdir("$git_dir/$_") or die "mkdir $_: $!";
280 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
281 print $fh <<'EOF' or die "print git/config $!";
283 repositoryFormatVersion = 0
286 fsyncObjectfiles = false
287 logAllRefUpdates = false
289 close $fh or die "close git/config: $!";
291 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
292 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
293 close $fh or die "close git/HEAD: $!";
295 my $f = 'objects/info/alternates';
296 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
297 foreach my $git (@{$self->{gits}}) {
298 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
300 close $fh or die "close: $f: $!";
301 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
302 $tmp_git->{-tmp} = $self->{tmp};
305 GIT_INDEX_FILE => "$git_dir/index",
307 prepare_index($self);
310 sub extract_old_mode ($) {
312 if (join('', @{$di->{hdr_lines}}) =~
313 /^old mode (100644|100755|120000)\b/) {
321 my ($found, $oid_want) = @$self{qw(found oid_want)};
322 if (my $exists = $found->{$oid_want}) {
323 return done($self, $exists);
326 # let git disambiguate if oid_want was too short,
327 # but long enough to be unambiguous:
328 my $tmp_git = $self->{tmp_git};
329 if (my @res = $tmp_git->check($oid_want)) {
330 return done($self, $found->{$res[0]});
332 if (my $err = $tmp_git->last_check_err) {
341 # step 1: resolve blobs to patches in the todo queue
342 if (my $want = pop @{$self->{todo}}) {
343 # this populates {patches} and {todo}
344 resolve_patch($self, $want);
346 # step 2: then we instantiate a working tree once
347 # the todo queue is finally empty:
348 } elsif (!defined($self->{tmp_git})) {
351 # step 3: apply each patch in the stack
352 } elsif (scalar @{$self->{patches}}) {
355 # step 4: execute the user-supplied callback with
356 # our result: (which may be undef)
357 # Other steps may call user_cb to terminate prematurely
359 } elsif (exists $self->{user_cb}) {
362 die 'about to call user_cb twice'; # Oops :x
367 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
368 dbg($self, "E: $err");
369 eval { done($self, $err) };
375 # if outside of public-inbox-httpd, caller is expected to be
376 # looping event_step, anyways
377 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
378 # PublicInbox::HTTPD::Async->new
379 $async->(undef, undef, $self);
382 sub mark_found ($$$) {
383 my ($self, $oid, $found_info) = @_;
384 my $found = $self->{found};
385 $found->{$oid} = $found_info;
386 my $oid_cur = $found_info->[1];
387 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
388 $found->{$oid_cur} = $found_info;
393 sub parse_ls_files ($$) {
394 my ($self, $bref) = @_;
395 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
396 if (my $err = $qsp->{err}) {
397 die "git ls-files error: $err";
400 my ($line, @extra) = split(/\0/, $$bref);
401 scalar(@extra) and die "BUG: extra files in index: <",
402 join('> <', @extra), ">";
404 my ($info, $file) = split(/\t/, $line, 2);
405 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
406 if ($file ne $di->{path_b}) {
408 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
411 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
412 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
413 defined($size) or die "check $oid_b_full failed";
415 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
416 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
417 mark_found($self, $di->{oid_b}, $created);
418 next_step($self); # onto the next patch
421 sub ls_files_result {
422 my ($bref, $self) = @_;
423 eval { parse_ls_files($self, $bref) };
424 ERR($self, $@) if $@;
427 sub oids_same_ish ($$) {
428 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
431 sub skip_identical ($$$) {
432 my ($self, $patches, $cur_oid_b) = @_;
433 while (my $nxt = $patches->[0]) {
434 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
435 dbg($self, 'skipping '.di_url($self, $nxt).
444 sub apply_result ($$) {
445 my ($bref, $self) = @_;
446 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
448 my $patches = $self->{patches};
449 if (my $err = $qsp->{err}) {
450 my $msg = "git apply error: $err";
451 my $nxt = $patches->[0];
452 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
454 dbg($self, 'trying '.di_url($self, $nxt));
455 return do_git_apply($self);
460 skip_identical($self, $patches, $di->{oid_b});
463 my @cmd = qw(git ls-files -s -z);
464 $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
465 $self->{-cur_di} = $di;
466 $self->{-qsp} = $qsp;
467 $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
470 sub do_git_apply ($) {
472 my $dn = $self->{tmp}->dirname;
473 my $patches = $self->{patches};
475 # we need --ignore-whitespace because some patches are CRLF
476 my @cmd = (qw(git apply --cached --ignore-whitespace
477 --unidiff-zero --whitespace=warn --verbose));
478 my $len = length(join(' ', @cmd));
479 my $total = $self->{tot};
480 my $di; # keep track of the last one for "git ls-files"
484 my $i = ++$self->{nr};
485 $di = shift @$patches;
486 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
487 "\n" . join('', @{$di->{hdr_lines}}));
489 $len += length($path) + 1;
491 $prv_oid_b = $di->{oid_b};
492 } while (@$patches && $len < $ARG_SIZE_MAX &&
493 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
495 my $opt = { 2 => 1, -C => $dn };
496 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
497 $self->{-cur_di} = $di;
498 $self->{-qsp} = $qsp;
499 $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
503 my ($self, $di) = @_;
504 # note: we don't pass the PSGI env unconditionally, here,
505 # different inboxes can have different HTTP_HOST on the same instance.
506 my $ibx = $di->{ibx};
507 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
508 my $url = $ibx->base_url($env);
509 my $mid = $di->{smsg}->{mid};
510 defined($url) ? "$url$mid/" : "<$mid>";
513 sub resolve_patch ($$) {
514 my ($self, $want) = @_;
516 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
517 die "Aborting, too many steps to $self->{oid_want}";
520 # see if we can find the blob in an existing git repo:
521 my $cur_want = $want->{oid_b};
522 if ($self->{seen_oid}->{$cur_want}++) {
523 die "Loop detected solving $cur_want\n";
525 if (my $existing = solve_existing($self, $want)) {
526 my ($found_git, undef, $type, undef) = @$existing;
527 dbg($self, "found $cur_want in " .
528 join("\n", $found_git->pub_urls($self->{psgi_env})));
530 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
531 eval { done($self, $existing) };
535 mark_found($self, $cur_want, $existing);
536 return next_step($self); # onto patch application
539 # scan through inboxes to look for emails which results in
541 foreach my $ibx (@{$self->{inboxes}}) {
542 my $diffs = find_extract_diffs($self, $ibx, $want) or next;
544 unshift @{$self->{patches}}, @$diffs;
545 dbg($self, "found $cur_want in ".
546 join("\n\t", map { di_url($self, $_) } @$diffs));
548 # good, we can find a path to the oid we $want, now
549 # lets see if we need to apply more patches:
550 my $di = $diffs->[0];
551 my $src = $di->{oid_a};
553 unless ($src =~ /\A0+\z/) {
554 # we have to solve it using another oid, fine:
555 my $job = { oid_b => $src, path_b => $di->{path_a} };
556 push @{$self->{todo}}, $job;
558 return next_step($self); # onto the next todo item
560 if (length($cur_want) > $OID_MIN) {
562 dbg($self, "retrying $want->{oid_b} as $cur_want");
563 $want->{oid_b} = $cur_want;
564 push @{$self->{todo}}, $want;
565 return next_step($self); # retry with shorter abbrev
568 dbg($self, "could not find $cur_want");
569 eval { done($self, undef) };
573 # this API is designed to avoid creating self-referential structures;
574 # so user_cb never references the SolverGit object
576 my ($class, $ibx, $user_cb, $uarg) = @_;
579 gits => $ibx->{-repo_objs},
582 # -cur_di, -qsp, -msg => temporary fields for Qspawn callbacks
584 # TODO: config option for searching related inboxes
589 # recreate $oid_want using $hints
590 # hints keys: path_a, path_b, oid_a
591 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
592 # with found object, or undef if nothing was found
593 # Calls {user_cb} with a string error on fatal errors
595 my ($self, $env, $out, $oid_want, $hints) = @_;
597 # should we even get here? Probably not, but somebody
598 # could be manually typing URLs:
599 return done($self, undef) if $oid_want =~ /\A0+\z/;
601 $self->{oid_want} = $oid_want;
603 $self->{seen_oid} = {};
605 $self->{psgi_env} = $env;
606 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
607 $self->{patches} = []; # [ $di, $di, ... ]
608 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
609 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
611 dbg($self, "solving $oid_want ...");
612 if (my $async = $env->{'pi-httpd.async'}) {
613 # PublicInbox::HTTPD::Async->new
614 $async->(undef, undef, $self);
616 event_step($self) while $self->{user_cb};