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 Fcntl qw(SEEK_SET);
15 use PublicInbox::Git qw(git_unquote git_quote);
16 use PublicInbox::Spawn qw(spawn popen_rd);
17 use PublicInbox::MsgIter qw(msg_iter msg_part_text);
18 use PublicInbox::Qspawn;
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
49 # don't bother if somebody sends us a patch with these path components,
50 # it's junk at best, an attack attempt at worse:
51 my %bad_component = map { $_ => 1 } ('', '.', '..');
54 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
58 my ($self, $err) = @_;
59 print { $self->{out} } $err, "\n";
60 my $ucb = delete($self->{user_cb});
61 eval { $ucb->($err) } if $ucb;
65 # look for existing objects already in git repos
66 sub solve_existing ($$) {
67 my ($self, $want) = @_;
68 my $oid_b = $want->{oid_b};
69 my $have_hints = scalar keys %$want > 1;
70 my @ambiguous; # Array of [ git, $oids]
71 foreach my $git (@{$self->{gits}}) {
72 my ($oid_full, $type, $size) = $git->check($oid_b);
73 if (defined($type) && (!$have_hints || $type eq 'blob')) {
74 return [ $git, $oid_full, $type, int($size) ];
77 next if length($oid_b) == 40;
79 # parse stderr of "git cat-file --batch-check"
80 my $err = $git->last_check_err;
81 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
82 next unless scalar(@oids);
84 # TODO: do something with the ambiguous array?
85 # push @ambiguous, [ $git, @oids ];
87 dbg($self, "`$oid_b' ambiguous in " .
88 join("\n\t", $git->pub_urls($self->{psgi_env}))
90 join('', map { "$_ blob\n" } @oids));
92 scalar(@ambiguous) ? \@ambiguous : undef;
95 sub extract_diff ($$$$$) {
96 my ($self, $p, $re, $ibx, $smsg) = @_;
97 my ($part) = @$p; # ignore $depth and @idx;
98 my $hdr_lines; # diff --git a/... b/...
100 my $ct = $part->content_type || 'text/plain';
101 my ($s, undef) = msg_part_text($part, $ct);
102 defined $s or return;
105 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
106 # change it back to LF:
107 my $cte = $part->header('Content-Transfer-Encoding') || '';
108 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
112 foreach my $l (split(/^/m, $s)) {
118 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
119 $di->{mode_a} = $mode_a;
124 # start writing the diff out to a tempfile
125 my $pn = ++$self->{tot};
126 open($tmp, '>', $self->{tmp}->dirname . "/$pn") or
129 push @$hdr_lines, $l;
130 $di->{hdr_lines} = $hdr_lines;
131 utf8::encode($_) for @$hdr_lines;
132 print $tmp @$hdr_lines or die "print(tmp): $!";
134 # for debugging/diagnostics:
137 } elsif ($l =~ m!\Adiff --git ("?[^/]+/.+) ("?[^/]+/.+)$!) {
138 last if $tmp; # got our blob, done!
140 my ($path_a, $path_b) = ($1, $2);
142 # diff header lines won't have \r because git
143 # will quote them, but Email::MIME gives CRLF
144 # for quoted-printable:
147 # don't care for leading 'a/' and 'b/'
148 my (undef, @a) = split(m{/}, git_unquote($path_a));
149 my (undef, @b) = split(m{/}, git_unquote($path_b));
151 # get rid of path-traversal attempts and junk patches:
153 return if $bad_component{$_};
156 $di->{path_a} = join('/', @a);
157 $di->{path_b} = join('/', @b);
161 print $tmp $l or die "print(tmp): $!";
162 } elsif ($hdr_lines) {
163 push @$hdr_lines, $l;
164 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
169 return undef unless $tmp;
170 close $tmp or die "close(tmp): $!";
174 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
176 # ".." appears in path names, which confuses Xapian into treating
177 # it as a range query. So we split on ".." since Xapian breaks
178 # on punctuation anyways:
179 sub filename_query ($) {
180 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
183 sub find_extract_diff ($$$) {
184 my ($self, $ibx, $want) = @_;
185 my $srch = $ibx->search or return;
187 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
188 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
190 my $q = "dfpost:$post";
191 my $pre = $want->{oid_a};
192 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
195 $pre = '[a-f0-9]{7}'; # for $re below
198 my $path_b = $want->{path_b};
199 if (path_searchable($path_b)) {
200 $q .= filename_query($path_b);
202 my $path_a = $want->{path_a};
203 if (path_searchable($path_a) && $path_a ne $path_b) {
204 $q .= filename_query($path_a);
208 my $msgs = $srch->query($q, { relevance => 1 });
209 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: ([0-9]+))?/;
212 foreach my $smsg (@$msgs) {
213 $ibx->smsg_mime($smsg) or next;
214 msg_iter(delete($smsg->{mime}), sub {
215 $di ||= extract_diff($self, $_[0], $re, $ibx, $smsg);
221 sub prepare_index ($) {
223 my $patches = $self->{patches};
226 my $di = $patches->[0] or die 'no patches';
227 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
228 my $existing = $self->{found}->{$oid_a};
230 # no index creation for added files
231 $oid_a =~ /\A0+\z/ and return next_step($self);
233 die "BUG: $oid_a not not found" unless $existing;
235 my $oid_full = $existing->[1];
236 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
237 my $mode_a = $di->{mode_a} || extract_old_mode($di);
239 open my $in, '+>', undef or die "open: $!";
240 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
241 $in->flush or die "flush: $!";
242 sysseek($in, 0, 0) or die "seek: $!";
244 dbg($self, 'preparing index');
245 my $rdr = { 0 => fileno($in) };
246 my $cmd = [ qw(git update-index -z --index-info) ];
247 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
248 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
250 if (my $err = $qsp->{err}) {
251 ERR($self, "git update-index error: $err");
253 dbg($self, "index prepared:\n" .
254 "$mode_a $oid_full\t" . git_quote($path_a));
255 next_step($self); # onto do_git_apply
259 # pure Perl "git init"
260 sub do_git_init ($) {
262 my $dir = $self->{tmp}->dirname;
263 my $git_dir = "$dir/git";
265 foreach ('', qw(objects refs objects/info refs/heads)) {
266 mkdir("$git_dir/$_") or die "mkdir $_: $!";
268 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
269 print $fh <<'EOF' or die "print git/config $!";
271 repositoryFormatVersion = 0
274 fsyncObjectfiles = false
275 logAllRefUpdates = false
277 close $fh or die "close git/config: $!";
279 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
280 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
281 close $fh or die "close git/HEAD: $!";
283 my $f = 'objects/info/alternates';
284 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
285 foreach my $git (@{$self->{gits}}) {
286 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
288 close $fh or die "close: $f: $!";
289 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
290 $tmp_git->{-tmp} = $self->{tmp};
293 GIT_INDEX_FILE => "$git_dir/index",
295 prepare_index($self);
298 sub extract_old_mode ($) {
300 if (join('', @{$di->{hdr_lines}}) =~
301 /^old mode (100644|100755|120000)\b/) {
308 my ($self, $user_cb) = @_;
309 my $found = $self->{found};
310 my $oid_want = $self->{oid_want};
311 if (my $exists = $found->{$oid_want}) {
312 return $user_cb->($exists);
315 # let git disambiguate if oid_want was too short,
316 # but long enough to be unambiguous:
317 my $tmp_git = $self->{tmp_git};
318 if (my @res = $tmp_git->check($oid_want)) {
319 return $user_cb->($found->{$res[0]});
321 if (my $err = $tmp_git->last_check_err) {
330 # step 1: resolve blobs to patches in the todo queue
331 if (my $want = pop @{$self->{todo}}) {
332 # this populates {patches} and {todo}
333 resolve_patch($self, $want);
335 # step 2: then we instantiate a working tree once
336 # the todo queue is finally empty:
337 } elsif (!defined($self->{tmp_git})) {
340 # step 3: apply each patch in the stack
341 } elsif (scalar @{$self->{patches}}) {
344 # step 4: execute the user-supplied callback with
345 # our result: (which may be undef)
346 # Other steps may call user_cb to terminate prematurely
348 } elsif (my $user_cb = delete($self->{user_cb})) {
349 do_finish($self, $user_cb);
351 die 'about to call user_cb twice'; # Oops :x
356 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
357 dbg($self, "E: $err");
358 my $ucb = delete($self->{user_cb});
359 eval { $ucb->($err) } if $ucb;
365 sub { do_step($self) };
370 # if outside of public-inbox-httpd, caller is expected to be
371 # looping step_cb, anyways
372 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
373 # PublicInbox::HTTPD::Async->new
374 $async->(undef, step_cb($self));
377 sub mark_found ($$$) {
378 my ($self, $oid, $found_info) = @_;
379 my $found = $self->{found};
380 $found->{$oid} = $found_info;
381 my $oid_cur = $found_info->[1];
382 while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
383 $found->{$oid_cur} = $found_info;
388 sub parse_ls_files ($$$$) {
389 my ($self, $qsp, $bref, $di) = @_;
390 if (my $err = $qsp->{err}) {
391 die "git ls-files error: $err";
394 my ($line, @extra) = split(/\0/, $$bref);
395 scalar(@extra) and die "BUG: extra files in index: <",
396 join('> <', @extra), ">";
398 my ($info, $file) = split(/\t/, $line, 2);
399 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
400 if ($file ne $di->{path_b}) {
402 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
405 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
406 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
407 defined($size) or die "check $oid_b_full failed";
409 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
410 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
411 mark_found($self, $di->{oid_b}, $created);
412 next_step($self); # onto the next patch
415 sub start_ls_files ($$) {
416 my ($self, $di) = @_;
417 my $cmd = [qw(git ls-files -s -z)];
418 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
419 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
421 eval { parse_ls_files($self, $qsp, $bref, $di) };
422 ERR($self, $@) if $@;
426 sub do_git_apply ($) {
428 my $dn = $self->{tmp}->dirname;
429 my $patches = $self->{patches};
431 # we need --ignore-whitespace because some patches are CRLF
432 my @cmd = (qw(git -C), $dn, qw(apply --cached --ignore-whitespace
433 --whitespace=warn --verbose));
434 my $len = length(join(' ', @cmd));
435 my $total = $self->{tot};
436 my $di; # keep track of the last one for "git ls-files"
439 my $i = ++$self->{nr};
440 $di = shift @$patches;
441 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
442 "\n" . join('', @{$di->{hdr_lines}}));
443 my $path = $total + 1 - $i;
444 $len += length($path) + 1;
446 } while (@$patches && $len < $ARG_SIZE_MAX);
448 my $rdr = { 2 => 1 };
449 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
450 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
453 if (my $err = $qsp->{err}) {
454 ERR($self, "git apply error: $err");
456 eval { start_ls_files($self, $di) };
457 ERR($self, $@) if $@;
462 my ($self, $di) = @_;
463 # note: we don't pass the PSGI env unconditionally, here,
464 # different inboxes can have different HTTP_HOST on the same instance.
465 my $ibx = $di->{ibx};
466 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
467 my $url = $ibx->base_url($env);
468 my $mid = $di->{smsg}->{mid};
469 defined($url) ? "$url$mid/" : "<$mid>";
472 sub resolve_patch ($$) {
473 my ($self, $want) = @_;
475 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
476 die "Aborting, too many steps to $self->{oid_want}";
479 # see if we can find the blob in an existing git repo:
480 my $cur_want = $want->{oid_b};
481 if ($self->{seen_oid}->{$cur_want}++) {
482 die "Loop detected solving $cur_want\n";
484 if (my $existing = solve_existing($self, $want)) {
485 my ($found_git, undef, $type, undef) = @$existing;
486 dbg($self, "found $cur_want in " .
487 join("\n", $found_git->pub_urls($self->{psgi_env})));
489 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
490 eval { delete($self->{user_cb})->($existing) };
494 mark_found($self, $cur_want, $existing);
495 return next_step($self); # onto patch application
498 # scan through inboxes to look for emails which results in
501 foreach my $ibx (@{$self->{inboxes}}) {
502 $di = find_extract_diff($self, $ibx, $want) or next;
504 unshift @{$self->{patches}}, $di;
505 dbg($self, "found $cur_want in ".di_url($self, $di));
507 # good, we can find a path to the oid we $want, now
508 # lets see if we need to apply more patches:
509 my $src = $di->{oid_a};
511 unless ($src =~ /\A0+\z/) {
512 # we have to solve it using another oid, fine:
513 my $job = { oid_b => $src, path_b => $di->{path_a} };
514 push @{$self->{todo}}, $job;
516 return next_step($self); # onto the next todo item
518 if (length($cur_want) > $OID_MIN) {
520 dbg($self, "retrying $want->{oid_b} as $cur_want");
521 $want->{oid_b} = $cur_want;
522 push @{$self->{todo}}, $want;
523 return next_step($self); # retry with shorter abbrev
526 dbg($self, "could not find $cur_want");
527 eval { delete($self->{user_cb})->(undef) }; # not found! :<
531 # this API is designed to avoid creating self-referential structures;
532 # so user_cb never references the SolverGit object
534 my ($class, $ibx, $user_cb) = @_;
537 gits => $ibx->{-repo_objs},
540 # TODO: config option for searching related inboxes
545 # recreate $oid_want using $hints
546 # hints keys: path_a, path_b, oid_a
547 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
548 # with found object, or undef if nothing was found
549 # Calls {user_cb} with a string error on fatal errors
551 my ($self, $env, $out, $oid_want, $hints) = @_;
553 # should we even get here? Probably not, but somebody
554 # could be manually typing URLs:
555 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
557 $self->{oid_want} = $oid_want;
559 $self->{seen_oid} = {};
561 $self->{psgi_env} = $env;
562 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
563 $self->{patches} = []; # [ $di, $di, ... ]
564 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
565 $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
567 dbg($self, "solving $oid_want ...");
568 my $step_cb = step_cb($self);
569 if (my $async = $env->{'pi-httpd.async'}) {
570 # PublicInbox::HTTPD::Async->new
571 $async->(undef, $step_cb);
573 $step_cb->() while $self->{user_cb};