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, $err) = @_;
60 print { $self->{out} } $err, "\n";
61 my $ucb = delete($self->{user_cb});
62 eval { $ucb->($err) } if $ucb;
66 # look for existing objects already in git repos
67 sub solve_existing ($$) {
68 my ($self, $want) = @_;
69 my $oid_b = $want->{oid_b};
70 my $have_hints = scalar keys %$want > 1;
71 my @ambiguous; # Array of [ git, $oids]
72 foreach my $git (@{$self->{gits}}) {
73 my ($oid_full, $type, $size) = $git->check($oid_b);
74 if (defined($type) && (!$have_hints || $type eq 'blob')) {
75 return [ $git, $oid_full, $type, int($size) ];
78 next if length($oid_b) == 40;
80 # parse stderr of "git cat-file --batch-check"
81 my $err = $git->last_check_err;
82 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
83 next unless scalar(@oids);
85 # TODO: do something with the ambiguous array?
86 # push @ambiguous, [ $git, @oids ];
88 dbg($self, "`$oid_b' ambiguous in " .
89 join("\n\t", $git->pub_urls($self->{psgi_env}))
91 join('', map { "$_ blob\n" } @oids));
93 scalar(@ambiguous) ? \@ambiguous : undef;
96 sub extract_diff ($$$$$) {
97 my ($self, $p, $re, $ibx, $smsg) = @_;
98 my ($part) = @$p; # ignore $depth and @idx;
99 my $hdr_lines; # diff --git a/... b/...
101 my $ct = $part->content_type || 'text/plain';
102 my ($s, undef) = msg_part_text($part, $ct);
103 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 foreach my $l (split(/^/m, $s)) {
119 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
120 $di->{mode_a} = $mode_a;
125 # start writing the diff out to a tempfile
126 my $path = ++$self->{tot};
128 open($tmp, '>', $self->{tmp}->dirname . "/$path") or
131 push @$hdr_lines, $l;
132 $di->{hdr_lines} = $hdr_lines;
133 utf8::encode($_) for @$hdr_lines;
134 print $tmp @$hdr_lines or die "print(tmp): $!";
136 # for debugging/diagnostics:
139 } elsif ($l =~ m!\Adiff --git ("?[^/]+/.+) ("?[^/]+/.+)$!) {
140 last if $tmp; # got our blob, done!
142 my ($path_a, $path_b) = ($1, $2);
144 # diff header lines won't have \r because git
145 # will quote them, but Email::MIME gives CRLF
146 # for quoted-printable:
149 # don't care for leading 'a/' and 'b/'
150 my (undef, @a) = split(m{/}, git_unquote($path_a));
151 my (undef, @b) = split(m{/}, git_unquote($path_b));
153 # get rid of path-traversal attempts and junk patches:
155 return if $bad_component{$_};
158 $di->{path_a} = join('/', @a);
159 $di->{path_b} = join('/', @b);
163 print $tmp $l or die "print(tmp): $!";
164 } elsif ($hdr_lines) {
165 push @$hdr_lines, $l;
166 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
171 return undef unless $tmp;
172 close $tmp or die "close(tmp): $!";
176 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
178 # ".." appears in path names, which confuses Xapian into treating
179 # it as a range query. So we split on ".." since Xapian breaks
180 # on punctuation anyways:
181 sub filename_query ($) {
182 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
185 sub find_extract_diffs ($$$) {
186 my ($self, $ibx, $want) = @_;
187 my $srch = $ibx->search or return;
189 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
190 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
192 my $q = "dfpost:$post";
193 my $pre = $want->{oid_a};
194 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
197 $pre = '[a-f0-9]{7}'; # for $re below
200 my $path_b = $want->{path_b};
201 if (path_searchable($path_b)) {
202 $q .= filename_query($path_b);
204 my $path_a = $want->{path_a};
205 if (path_searchable($path_a) && $path_a ne $path_b) {
206 $q .= filename_query($path_a);
210 my $msgs = $srch->query($q, { relevance => 1 });
211 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: ([0-9]+))?/;
214 foreach my $smsg (@$msgs) {
215 $ibx->smsg_mime($smsg) or next;
216 msg_iter(delete($smsg->{mime}), sub {
217 my $di = extract_diff($self, $_[0], $re, $ibx, $smsg);
218 push @di, $di if defined($di);
224 sub update_index_result ($$) {
225 my ($bref, $self) = @_;
226 my ($qsp, $msg) = delete @$self{qw(-qsp -msg)};
227 if (my $err = $qsp->{err}) {
228 ERR($self, "git update-index error: $err");
231 next_step($self); # onto do_git_apply
234 sub prepare_index ($) {
236 my $patches = $self->{patches};
239 my $di = $patches->[0] or die 'no patches';
240 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
241 my $existing = $self->{found}->{$oid_a};
243 # no index creation for added files
244 $oid_a =~ /\A0+\z/ and return next_step($self);
246 die "BUG: $oid_a not not found" unless $existing;
248 my $oid_full = $existing->[1];
249 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
250 my $mode_a = $di->{mode_a} || extract_old_mode($di);
252 my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
253 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
254 $in->flush or die "flush: $!";
255 sysseek($in, 0, 0) or die "seek: $!";
257 dbg($self, 'preparing index');
258 my $rdr = { 0 => fileno($in), -hold => $in };
259 my $cmd = [ qw(git update-index -z --index-info) ];
260 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
261 $path_a = git_quote($path_a);
262 $self->{-qsp} = $qsp;
263 $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
264 $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
267 # pure Perl "git init"
268 sub do_git_init ($) {
270 my $dir = $self->{tmp}->dirname;
271 my $git_dir = "$dir/git";
273 foreach ('', qw(objects refs objects/info refs/heads)) {
274 mkdir("$git_dir/$_") or die "mkdir $_: $!";
276 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
277 print $fh <<'EOF' or die "print git/config $!";
279 repositoryFormatVersion = 0
282 fsyncObjectfiles = false
283 logAllRefUpdates = false
285 close $fh or die "close git/config: $!";
287 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
288 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
289 close $fh or die "close git/HEAD: $!";
291 my $f = 'objects/info/alternates';
292 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
293 foreach my $git (@{$self->{gits}}) {
294 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
296 close $fh or die "close: $f: $!";
297 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
298 $tmp_git->{-tmp} = $self->{tmp};
301 GIT_INDEX_FILE => "$git_dir/index",
303 prepare_index($self);
306 sub extract_old_mode ($) {
308 if (join('', @{$di->{hdr_lines}}) =~
309 /^old mode (100644|100755|120000)\b/) {
316 my ($self, $user_cb) = @_;
317 my $found = $self->{found};
318 my $oid_want = $self->{oid_want};
319 if (my $exists = $found->{$oid_want}) {
320 return $user_cb->($exists);
323 # let git disambiguate if oid_want was too short,
324 # but long enough to be unambiguous:
325 my $tmp_git = $self->{tmp_git};
326 if (my @res = $tmp_git->check($oid_want)) {
327 return $user_cb->($found->{$res[0]});
329 if (my $err = $tmp_git->last_check_err) {
338 # step 1: resolve blobs to patches in the todo queue
339 if (my $want = pop @{$self->{todo}}) {
340 # this populates {patches} and {todo}
341 resolve_patch($self, $want);
343 # step 2: then we instantiate a working tree once
344 # the todo queue is finally empty:
345 } elsif (!defined($self->{tmp_git})) {
348 # step 3: apply each patch in the stack
349 } elsif (scalar @{$self->{patches}}) {
352 # step 4: execute the user-supplied callback with
353 # our result: (which may be undef)
354 # Other steps may call user_cb to terminate prematurely
356 } elsif (my $user_cb = delete($self->{user_cb})) {
357 do_finish($self, $user_cb);
359 die 'about to call user_cb twice'; # Oops :x
364 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
365 dbg($self, "E: $err");
366 my $ucb = delete($self->{user_cb});
367 eval { $ucb->($err) } if $ucb;
373 # if outside of public-inbox-httpd, caller is expected to be
374 # looping event_step, anyways
375 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
376 # PublicInbox::HTTPD::Async->new
377 $async->(undef, undef, $self);
380 sub mark_found ($$$) {
381 my ($self, $oid, $found_info) = @_;
382 my $found = $self->{found};
383 $found->{$oid} = $found_info;
384 my $oid_cur = $found_info->[1];
385 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
386 $found->{$oid_cur} = $found_info;
391 sub parse_ls_files ($$) {
392 my ($self, $bref) = @_;
393 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
394 if (my $err = $qsp->{err}) {
395 die "git ls-files error: $err";
398 my ($line, @extra) = split(/\0/, $$bref);
399 scalar(@extra) and die "BUG: extra files in index: <",
400 join('> <', @extra), ">";
402 my ($info, $file) = split(/\t/, $line, 2);
403 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
404 if ($file ne $di->{path_b}) {
406 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
409 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
410 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
411 defined($size) or die "check $oid_b_full failed";
413 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
414 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
415 mark_found($self, $di->{oid_b}, $created);
416 next_step($self); # onto the next patch
419 sub ls_files_result {
420 my ($bref, $self) = @_;
421 eval { parse_ls_files($self, $bref) };
422 ERR($self, $@) if $@;
425 sub oids_same_ish ($$) {
426 (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
429 sub skip_identical ($$$) {
430 my ($self, $patches, $cur_oid_b) = @_;
431 while (my $nxt = $patches->[0]) {
432 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
433 dbg($self, 'skipping '.di_url($self, $nxt).
442 sub apply_result ($$) {
443 my ($bref, $self) = @_;
444 my ($qsp, $di) = delete @$self{qw(-qsp -cur_di)};
446 my $patches = $self->{patches};
447 if (my $err = $qsp->{err}) {
448 my $msg = "git apply error: $err";
449 my $nxt = $patches->[0];
450 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
452 dbg($self, 'trying '.di_url($self, $nxt));
457 skip_identical($self, $patches, $di->{oid_b});
460 my @cmd = qw(git ls-files -s -z);
461 $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
462 $self->{-cur_di} = $di;
463 $self->{-qsp} = $qsp;
464 $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
467 sub do_git_apply ($) {
469 my $dn = $self->{tmp}->dirname;
470 my $patches = $self->{patches};
472 # we need --ignore-whitespace because some patches are CRLF
473 my @cmd = (qw(git -C), $dn, qw(apply --cached --ignore-whitespace
474 --unidiff-zero --whitespace=warn --verbose));
475 my $len = length(join(' ', @cmd));
476 my $total = $self->{tot};
477 my $di; # keep track of the last one for "git ls-files"
481 my $i = ++$self->{nr};
482 $di = shift @$patches;
483 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
484 "\n" . join('', @{$di->{hdr_lines}}));
486 $len += length($path) + 1;
488 $prv_oid_b = $di->{oid_b};
489 } while (@$patches && $len < $ARG_SIZE_MAX &&
490 !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
492 my $rdr = { 2 => 1 };
493 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
494 $self->{-cur_di} = $di;
495 $self->{-qsp} = $qsp;
496 $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
500 my ($self, $di) = @_;
501 # note: we don't pass the PSGI env unconditionally, here,
502 # different inboxes can have different HTTP_HOST on the same instance.
503 my $ibx = $di->{ibx};
504 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
505 my $url = $ibx->base_url($env);
506 my $mid = $di->{smsg}->{mid};
507 defined($url) ? "$url$mid/" : "<$mid>";
510 sub resolve_patch ($$) {
511 my ($self, $want) = @_;
513 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
514 die "Aborting, too many steps to $self->{oid_want}";
517 # see if we can find the blob in an existing git repo:
518 my $cur_want = $want->{oid_b};
519 if ($self->{seen_oid}->{$cur_want}++) {
520 die "Loop detected solving $cur_want\n";
522 if (my $existing = solve_existing($self, $want)) {
523 my ($found_git, undef, $type, undef) = @$existing;
524 dbg($self, "found $cur_want in " .
525 join("\n", $found_git->pub_urls($self->{psgi_env})));
527 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
528 eval { delete($self->{user_cb})->($existing) };
532 mark_found($self, $cur_want, $existing);
533 return next_step($self); # onto patch application
536 # scan through inboxes to look for emails which results in
538 foreach my $ibx (@{$self->{inboxes}}) {
539 my $diffs = find_extract_diffs($self, $ibx, $want) or next;
541 unshift @{$self->{patches}}, @$diffs;
542 dbg($self, "found $cur_want in ".
543 join("\n\t", map { di_url($self, $_) } @$diffs));
545 # good, we can find a path to the oid we $want, now
546 # lets see if we need to apply more patches:
547 my $di = $diffs->[0];
548 my $src = $di->{oid_a};
550 unless ($src =~ /\A0+\z/) {
551 # we have to solve it using another oid, fine:
552 my $job = { oid_b => $src, path_b => $di->{path_a} };
553 push @{$self->{todo}}, $job;
555 return next_step($self); # onto the next todo item
557 if (length($cur_want) > $OID_MIN) {
559 dbg($self, "retrying $want->{oid_b} as $cur_want");
560 $want->{oid_b} = $cur_want;
561 push @{$self->{todo}}, $want;
562 return next_step($self); # retry with shorter abbrev
565 dbg($self, "could not find $cur_want");
566 eval { delete($self->{user_cb})->(undef) }; # not found! :<
570 # this API is designed to avoid creating self-referential structures;
571 # so user_cb never references the SolverGit object
573 my ($class, $ibx, $user_cb) = @_;
576 gits => $ibx->{-repo_objs},
578 # -cur_di, -qsp, -msg => temporary fields for Qspawn callbacks
580 # TODO: config option for searching related inboxes
585 # recreate $oid_want using $hints
586 # hints keys: path_a, path_b, oid_a
587 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
588 # with found object, or undef if nothing was found
589 # Calls {user_cb} with a string error on fatal errors
591 my ($self, $env, $out, $oid_want, $hints) = @_;
593 # should we even get here? Probably not, but somebody
594 # could be manually typing URLs:
595 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
597 $self->{oid_want} = $oid_want;
599 $self->{seen_oid} = {};
601 $self->{psgi_env} = $env;
602 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
603 $self->{patches} = []; # [ $di, $di, ... ]
604 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
605 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
607 dbg($self, "solving $oid_want ...");
608 if (my $async = $env->{'pi-httpd.async'}) {
609 # PublicInbox::HTTPD::Async->new
610 $async->(undef, undef, $self);
612 event_step($self) while $self->{user_cb};