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;
27 # By default, "git format-patch" generates filenames with a four-digit
28 # prefix, so that means 9999 patch series are OK, right? :>
29 # Maybe we can make this configurable, main concern is disk space overhead
30 # for uncompressed patch fragments. Aside from space, public-inbox-httpd
31 # is otherwise unaffected by having many patches, here, as it can share
32 # work fairly. Other PSGI servers may have trouble, though.
35 # di = diff info / a hashref with information about a diff ($di):
37 # oid_a => abbreviated pre-image oid,
38 # oid_b => abbreviated post-image oid,
39 # tmp => anonymous file handle with the diff,
40 # hdr_lines => arrayref of various header lines for mode information
41 # mode_a => original mode of oid_a (string, not integer),
42 # ibx => PublicInbox::Inbox object containing the diff
43 # smsg => PublicInbox::SearchMsg object containing diff
44 # path_a => pre-image path
45 # path_b => post-image path
48 # don't bother if somebody sends us a patch with these path components,
49 # it's junk at best, an attack attempt at worse:
50 my %bad_component = map { $_ => 1 } ('', '.', '..');
53 print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
57 my ($self, $err) = @_;
58 print { $self->{out} } $err, "\n";
59 my $ucb = delete($self->{user_cb});
60 eval { $ucb->($err) } if $ucb;
64 # look for existing blobs already in git repos
65 sub solve_existing ($$) {
66 my ($self, $want) = @_;
67 my $oid_b = $want->{oid_b};
68 my @ambiguous; # Array of [ git, $oids]
69 foreach my $git (@{$self->{gits}}) {
70 my ($oid_full, $type, $size) = $git->check($oid_b);
71 if (defined($type) && $type eq 'blob') {
72 return [ $git, $oid_full, $type, int($size) ];
75 next if length($oid_b) == 40;
77 # parse stderr of "git cat-file --batch-check"
78 my $err = $git->last_check_err;
79 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
80 next unless scalar(@oids);
82 # TODO: do something with the ambiguous array?
83 # push @ambiguous, [ $git, @oids ];
85 dbg($self, "`$oid_b' ambiguous in " .
86 join("\n\t", $git->pub_urls) . "\n" .
87 join('', map { "$_ blob\n" } @oids));
89 scalar(@ambiguous) ? \@ambiguous : undef;
92 sub extract_diff ($$$$$) {
93 my ($self, $p, $re, $ibx, $smsg) = @_;
94 my ($part) = @$p; # ignore $depth and @idx;
95 my $hdr_lines; # diff --git a/... b/...
97 my $ct = $part->content_type || 'text/plain';
98 my ($s, undef) = msg_part_text($part, $ct);
102 # Email::MIME::Encodings forces QP to be CRLF upon decoding,
103 # change it back to LF:
104 my $cte = $part->header('Content-Transfer-Encoding') || '';
105 if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
109 foreach my $l (split(/^/m, $s)) {
115 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
116 $di->{mode_a} = $mode_a;
121 # start writing the diff out to a tempfile
122 my $pn = ++$self->{tot};
123 open($tmp, '>', $self->{tmp}->dirname . "/$pn") or
126 push @$hdr_lines, $l;
127 $di->{hdr_lines} = $hdr_lines;
128 utf8::encode($_) for @$hdr_lines;
129 print $tmp @$hdr_lines or die "print(tmp): $!";
131 # for debugging/diagnostics:
134 } elsif ($l =~ m!\Adiff --git ("?[^/]+/.+) ("?[^/]+/.+)$!) {
135 last if $tmp; # got our blob, done!
137 my ($path_a, $path_b) = ($1, $2);
139 # diff header lines won't have \r because git
140 # will quote them, but Email::MIME gives CRLF
141 # for quoted-printable:
144 # don't care for leading 'a/' and 'b/'
145 my (undef, @a) = split(m{/}, git_unquote($path_a));
146 my (undef, @b) = split(m{/}, git_unquote($path_b));
148 # get rid of path-traversal attempts and junk patches:
150 return if $bad_component{$_};
153 $di->{path_a} = join('/', @a);
154 $di->{path_b} = join('/', @b);
158 print $tmp $l or die "print(tmp): $!";
159 } elsif ($hdr_lines) {
160 push @$hdr_lines, $l;
161 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
166 return undef unless $tmp;
167 close $tmp or die "close(tmp): $!";
171 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
173 sub find_extract_diff ($$$) {
174 my ($self, $ibx, $want) = @_;
175 my $srch = $ibx->search or return;
177 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
178 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
180 my $q = "dfpost:$post";
181 my $pre = $want->{oid_a};
182 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
185 $pre = '[a-f0-9]{7}'; # for $re below
188 my $path_b = $want->{path_b};
189 if (path_searchable($path_b)) {
190 $q .= qq{ dfn:"$path_b"};
192 my $path_a = $want->{path_a};
193 if (path_searchable($path_a) && $path_a ne $path_b) {
194 $q .= qq{ dfn:"$path_a"};
198 my $msgs = $srch->query($q, { relevance => 1 });
199 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
202 foreach my $smsg (@$msgs) {
203 $ibx->smsg_mime($smsg) or next;
204 msg_iter(delete($smsg->{mime}), sub {
205 $di ||= extract_diff($self, $_[0], $re, $ibx, $smsg);
211 sub prepare_index ($) {
213 my $patches = $self->{patches};
216 my $di = $patches->[0] or die 'no patches';
217 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
218 my $existing = $self->{found}->{$oid_a};
220 # no index creation for added files
221 $oid_a =~ /\A0+\z/ and return next_step($self);
223 die "BUG: $oid_a not not found" unless $existing;
225 my $oid_full = $existing->[1];
226 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
227 my $mode_a = $di->{mode_a} || extract_old_mode($di);
229 open my $in, '+>', undef or die "open: $!";
230 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
231 $in->flush or die "flush: $!";
232 sysseek($in, 0, 0) or die "seek: $!";
234 dbg($self, 'preparing index');
235 my $rdr = { 0 => fileno($in) };
236 my $cmd = [ qw(git update-index -z --index-info) ];
237 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
238 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
240 if (my $err = $qsp->{err}) {
241 ERR($self, "git update-index error: $err");
243 dbg($self, "index prepared:\n" .
244 "$mode_a $oid_full\t" . git_quote($path_a));
245 next_step($self); # onto do_git_apply
249 # pure Perl "git init"
250 sub do_git_init ($) {
252 my $dir = $self->{tmp}->dirname;
253 my $git_dir = "$dir/git";
255 foreach ('', qw(objects refs objects/info refs/heads)) {
256 mkdir("$git_dir/$_") or die "mkdir $_: $!";
258 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
259 print $fh <<'EOF' or die "print git/config $!";
261 repositoryFormatVersion = 0
264 fsyncObjectfiles = false
265 logAllRefUpdates = false
267 close $fh or die "close git/config: $!";
269 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
270 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
271 close $fh or die "close git/HEAD: $!";
273 my $f = 'objects/info/alternates';
274 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
275 foreach my $git (@{$self->{gits}}) {
276 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
278 close $fh or die "close: $f: $!";
279 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
280 $tmp_git->{-tmp} = $self->{tmp};
283 GIT_INDEX_FILE => "$git_dir/index",
285 prepare_index($self);
288 sub extract_old_mode ($) {
290 if (join('', @{$di->{hdr_lines}}) =~
291 /^old mode (100644|100755|120000)\b/) {
300 # step 1: resolve blobs to patches in the todo queue
301 if (my $want = pop @{$self->{todo}}) {
302 # this populates {patches} and {todo}
303 resolve_patch($self, $want);
305 # step 2: then we instantiate a working tree once
306 # the todo queue is finally empty:
307 } elsif (!defined($self->{tmp_git})) {
310 # step 3: apply each patch in the stack
311 } elsif (scalar @{$self->{patches}}) {
314 # step 4: execute the user-supplied callback with
315 # our result: (which may be undef)
316 # Other steps may call user_cb to terminate prematurely
318 } elsif (my $ucb = delete($self->{user_cb})) {
319 $ucb->($self->{found}->{$self->{oid_want}});
321 die 'about to call user_cb twice'; # Oops :x
326 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
327 dbg($self, "E: $err");
328 my $ucb = delete($self->{user_cb});
329 eval { $ucb->($err) } if $ucb;
335 sub { do_step($self) };
340 # if outside of public-inbox-httpd, caller is expected to be
341 # looping step_cb, anyways
342 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
343 # PublicInbox::HTTPD::Async->new
344 $async->(undef, step_cb($self));
347 sub mark_found ($$$) {
348 my ($self, $oid, $found_info) = @_;
349 $self->{found}->{$oid} = $found_info;
352 sub parse_ls_files ($$$$) {
353 my ($self, $qsp, $bref, $di) = @_;
354 if (my $err = $qsp->{err}) {
355 die "git ls-files error: $err";
358 my ($line, @extra) = split(/\0/, $$bref);
359 scalar(@extra) and die "BUG: extra files in index: <",
360 join('> <', @extra), ">";
362 my ($info, $file) = split(/\t/, $line, 2);
363 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
364 if ($file ne $di->{path_b}) {
366 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
369 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
370 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
371 defined($size) or die "check $oid_b_full failed";
373 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
374 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
375 mark_found($self, $di->{oid_b}, $created);
376 next_step($self); # onto the next patch
379 sub start_ls_files ($$) {
380 my ($self, $di) = @_;
381 my $cmd = [qw(git ls-files -s -z)];
382 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
383 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
385 eval { parse_ls_files($self, $qsp, $bref, $di) };
386 ERR($self, $@) if $@;
390 sub do_git_apply ($) {
392 my $dn = $self->{tmp}->dirname;
393 my $patches = $self->{patches};
395 # we need --ignore-whitespace because some patches are CRLF
396 my @cmd = (qw(git -C), $dn, qw(apply --cached --ignore-whitespace
397 --whitespace=warn --verbose));
398 my $len = length(join(' ', @cmd));
399 my $total = $self->{tot};
400 my $di; # keep track of the last one for "git ls-files"
403 my $i = ++$self->{nr};
404 $di = shift @$patches;
405 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
406 "\n" . join('', @{$di->{hdr_lines}}));
407 my $path = $total + 1 - $i;
408 $len += length($path) + 1;
410 } while (@$patches && $len < $ARG_SIZE_MAX);
412 my $rdr = { 2 => 1 };
413 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
414 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
417 if (my $err = $qsp->{err}) {
418 ERR($self, "git apply error: $err");
420 eval { start_ls_files($self, $di) };
421 ERR($self, $@) if $@;
426 my ($self, $di) = @_;
427 # note: we don't pass the PSGI env unconditionally, here,
428 # different inboxes can have different HTTP_HOST on the same instance.
429 my $ibx = $di->{ibx};
430 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
431 my $url = $ibx->base_url($env);
432 my $mid = $di->{smsg}->{mid};
433 defined($url) ? "$url$mid/" : "<$mid>";
436 sub resolve_patch ($$) {
437 my ($self, $want) = @_;
439 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
440 die "Aborting, too many steps to $self->{oid_want}";
443 # see if we can find the blob in an existing git repo:
444 my $cur_want = $want->{oid_b};
445 if ($self->{seen_oid}->{$cur_want}++) {
446 die "Loop detected solving $cur_want\n";
448 if (my $existing = solve_existing($self, $want)) {
449 dbg($self, "found $cur_want in " .
450 join("\n", $existing->[0]->pub_urls));
452 if ($cur_want eq $self->{oid_want}) { # all done!
453 eval { delete($self->{user_cb})->($existing) };
457 mark_found($self, $cur_want, $existing);
458 return next_step($self); # onto patch application
461 # scan through inboxes to look for emails which results in
464 foreach my $ibx (@{$self->{inboxes}}) {
465 $di = find_extract_diff($self, $ibx, $want) or next;
467 unshift @{$self->{patches}}, $di;
468 dbg($self, "found $cur_want in ".di_url($self, $di));
470 # good, we can find a path to the oid we $want, now
471 # lets see if we need to apply more patches:
472 my $src = $di->{oid_a};
474 unless ($src =~ /\A0+\z/) {
475 # we have to solve it using another oid, fine:
476 my $job = { oid_b => $src, path_b => $di->{path_a} };
477 push @{$self->{todo}}, $job;
479 return next_step($self); # onto the next todo item
481 dbg($self, "could not find $cur_want");
482 eval { delete($self->{user_cb})->(undef) }; # not found! :<
486 # this API is designed to avoid creating self-referential structures;
487 # so user_cb never references the SolverGit object
489 my ($class, $ibx, $user_cb) = @_;
492 gits => $ibx->{-repo_objs},
495 # TODO: config option for searching related inboxes
500 # recreate $oid_want using $hints
501 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
502 # with found object, or undef if nothing was found
503 # Calls {user_cb} with a string error on fatal errors
505 my ($self, $env, $out, $oid_want, $hints) = @_;
507 # should we even get here? Probably not, but somebody
508 # could be manually typing URLs:
509 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
511 $self->{oid_want} = $oid_want;
513 $self->{seen_oid} = {};
515 $self->{psgi_env} = $env;
516 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
517 $self->{patches} = []; # [ $di, $di, ... ]
518 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
519 $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
521 dbg($self, "solving $oid_want ...");
522 my $step_cb = step_cb($self);
523 if (my $async = $env->{'pi-httpd.async'}) {
524 # PublicInbox::HTTPD::Async->new
525 $async->(undef, $step_cb);
527 $step_cb->() while $self->{user_cb};