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 print $tmp @$hdr_lines or die "print(tmp): $!";
130 # for debugging/diagnostics:
133 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
134 last if $tmp; # got our blob, done!
136 my ($path_a, $path_b) = ($1, $2);
138 # diff header lines won't have \r because git
139 # will quote them, but Email::MIME gives CRLF
140 # for quoted-printable:
143 # don't care for leading 'a/' and 'b/'
144 my (undef, @a) = split(m{/}, git_unquote($path_a));
145 my (undef, @b) = split(m{/}, git_unquote($path_b));
147 # get rid of path-traversal attempts and junk patches:
149 return if $bad_component{$_};
152 $di->{path_a} = join('/', @a);
153 $di->{path_b} = join('/', @b);
156 print $tmp $l or die "print(tmp): $!";
157 } elsif ($hdr_lines) {
158 push @$hdr_lines, $l;
159 if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
164 return undef unless $tmp;
165 close $tmp or die "close(tmp): $!";
169 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
171 sub find_extract_diff ($$$) {
172 my ($self, $ibx, $want) = @_;
173 my $srch = $ibx->search or return;
175 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
176 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
178 my $q = "dfpost:$post";
179 my $pre = $want->{oid_a};
180 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
183 $pre = '[a-f0-9]{7}'; # for $re below
186 my $path_b = $want->{path_b};
187 if (path_searchable($path_b)) {
188 $q .= qq{ dfn:"$path_b"};
190 my $path_a = $want->{path_a};
191 if (path_searchable($path_a) && $path_a ne $path_b) {
192 $q .= qq{ dfn:"$path_a"};
196 my $msgs = $srch->query($q, { relevance => 1 });
197 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
200 foreach my $smsg (@$msgs) {
201 $ibx->smsg_mime($smsg) or next;
202 msg_iter(delete($smsg->{mime}), sub {
203 $di ||= extract_diff($self, $_[0], $re, $ibx, $smsg);
209 sub prepare_index ($) {
211 my $patches = $self->{patches};
214 my $di = $patches->[0] or die 'no patches';
215 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
216 my $existing = $self->{found}->{$oid_a};
218 # no index creation for added files
219 $oid_a =~ /\A0+\z/ and return next_step($self);
221 die "BUG: $oid_a not not found" unless $existing;
223 my $oid_full = $existing->[1];
224 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
225 my $mode_a = $di->{mode_a} || extract_old_mode($di);
227 open my $in, '+>', undef or die "open: $!";
228 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
229 $in->flush or die "flush: $!";
230 sysseek($in, 0, 0) or die "seek: $!";
232 dbg($self, 'preparing index');
233 my $rdr = { 0 => fileno($in) };
234 my $cmd = [ qw(git update-index -z --index-info) ];
235 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
236 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
238 if (my $err = $qsp->{err}) {
239 ERR($self, "git update-index error: $err");
241 dbg($self, "index prepared:\n" .
242 "$mode_a $oid_full\t" . git_quote($path_a));
243 next_step($self); # onto do_git_apply
247 # pure Perl "git init"
248 sub do_git_init ($) {
250 my $dir = $self->{tmp}->dirname;
251 my $git_dir = "$dir/git";
253 foreach ('', qw(objects refs objects/info refs/heads)) {
254 mkdir("$git_dir/$_") or die "mkdir $_: $!";
256 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
257 print $fh <<'EOF' or die "print git/config $!";
259 repositoryFormatVersion = 0
262 fsyncObjectfiles = false
263 logAllRefUpdates = false
265 close $fh or die "close git/config: $!";
267 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
268 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
269 close $fh or die "close git/HEAD: $!";
271 my $f = 'objects/info/alternates';
272 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
273 print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
275 close $fh or die "close: $f: $!";
276 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
277 $tmp_git->{-tmp} = $self->{tmp};
280 GIT_INDEX_FILE => "$git_dir/index",
282 prepare_index($self);
285 sub extract_old_mode ($) {
287 if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
296 # step 1: resolve blobs to patches in the todo queue
297 if (my $want = pop @{$self->{todo}}) {
298 # this populates {patches} and {todo}
299 resolve_patch($self, $want);
301 # step 2: then we instantiate a working tree once
302 # the todo queue is finally empty:
303 } elsif (!defined($self->{tmp_git})) {
306 # step 3: apply each patch in the stack
307 } elsif (scalar @{$self->{patches}}) {
310 # step 4: execute the user-supplied callback with
311 # our result: (which may be undef)
312 # Other steps may call user_cb to terminate prematurely
314 } elsif (my $ucb = delete($self->{user_cb})) {
315 $ucb->($self->{found}->{$self->{oid_want}});
317 die 'about to call user_cb twice'; # Oops :x
322 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
323 dbg($self, "E: $err");
324 my $ucb = delete($self->{user_cb});
325 eval { $ucb->($err) } if $ucb;
331 sub { do_step($self) };
336 # if outside of public-inbox-httpd, caller is expected to be
337 # looping step_cb, anyways
338 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
339 # PublicInbox::HTTPD::Async->new
340 $async->(undef, step_cb($self));
343 sub mark_found ($$$) {
344 my ($self, $oid, $found_info) = @_;
345 $self->{found}->{$oid} = $found_info;
348 sub parse_ls_files ($$$$) {
349 my ($self, $qsp, $bref, $di) = @_;
350 if (my $err = $qsp->{err}) {
351 die "git ls-files error: $err";
354 my ($line, @extra) = split(/\0/, $$bref);
355 scalar(@extra) and die "BUG: extra files in index: <",
356 join('> <', @extra), ">";
358 my ($info, $file) = split(/\t/, $line, 2);
359 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
360 if ($file ne $di->{path_b}) {
362 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
365 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
366 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
367 defined($size) or die "check $oid_b_full failed";
369 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
370 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
371 mark_found($self, $di->{oid_b}, $created);
372 next_step($self); # onto the next patch
375 sub start_ls_files ($$) {
376 my ($self, $di) = @_;
377 my $cmd = [qw(git ls-files -s -z)];
378 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
379 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
381 eval { parse_ls_files($self, $qsp, $bref, $di) };
382 ERR($self, $@) if $@;
386 sub do_git_apply ($) {
388 my $dn = $self->{tmp}->dirname;
389 my $patches = $self->{patches};
391 # we need --ignore-whitespace because some patches are CRLF
392 my @cmd = qw(git apply --cached --ignore-whitespace
393 --whitespace=warn --verbose);
394 my $len = length(join(' ', @cmd));
395 my $total = $self->{tot};
396 my $di; # keep track of the last one for "git ls-files"
399 my $i = ++$self->{nr};
400 $di = shift @$patches;
401 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
402 "\n" . join('', @{$di->{hdr_lines}}));
403 my $pn = $total + 1 - $i;
404 my $path = "$dn/$pn";
405 $len += length($path) + 1;
407 } while (@$patches && $len < $ARG_SIZE_MAX);
409 my $rdr = { 2 => 1 };
410 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
411 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
414 if (my $err = $qsp->{err}) {
415 ERR($self, "git apply error: $err");
417 eval { start_ls_files($self, $di) };
418 ERR($self, $@) if $@;
423 my ($self, $di) = @_;
424 # note: we don't pass the PSGI env unconditionally, here,
425 # different inboxes can have different HTTP_HOST on the same instance.
426 my $ibx = $di->{ibx};
427 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
428 my $url = $ibx->base_url($env);
429 my $mid = $di->{smsg}->{mid};
430 defined($url) ? "$url$mid/" : "<$mid>";
433 sub resolve_patch ($$) {
434 my ($self, $want) = @_;
436 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
437 die "Aborting, too many steps to $self->{oid_want}";
440 # see if we can find the blob in an existing git repo:
441 my $cur_want = $want->{oid_b};
442 if (my $existing = solve_existing($self, $want)) {
443 dbg($self, "found $cur_want in " .
444 join("\n", $existing->[0]->pub_urls));
446 if ($cur_want eq $self->{oid_want}) { # all done!
447 eval { delete($self->{user_cb})->($existing) };
451 mark_found($self, $cur_want, $existing);
452 return next_step($self); # onto patch application
455 # scan through inboxes to look for emails which results in
458 foreach my $ibx (@{$self->{inboxes}}) {
459 $di = find_extract_diff($self, $ibx, $want) or next;
461 unshift @{$self->{patches}}, $di;
462 dbg($self, "found $cur_want in ".di_url($self, $di));
464 # good, we can find a path to the oid we $want, now
465 # lets see if we need to apply more patches:
466 my $src = $di->{oid_a};
468 unless ($src =~ /\A0+\z/) {
469 # we have to solve it using another oid, fine:
470 my $job = { oid_b => $src, path_b => $di->{path_a} };
471 push @{$self->{todo}}, $job;
473 return next_step($self); # onto the next todo item
475 dbg($self, "could not find $cur_want");
476 eval { delete($self->{user_cb})->(undef) }; # not found! :<
480 # this API is designed to avoid creating self-referential structures;
481 # so user_cb never references the SolverGit object
483 my ($class, $ibx, $user_cb) = @_;
486 gits => $ibx->{-repo_objs},
489 # TODO: config option for searching related inboxes
494 # recreate $oid_want using $hints
495 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
496 # with found object, or undef if nothing was found
497 # Calls {user_cb} with a string error on fatal errors
499 my ($self, $env, $out, $oid_want, $hints) = @_;
501 # should we even get here? Probably not, but somebody
502 # could be manually typing URLs:
503 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
505 $self->{oid_want} = $oid_want;
508 $self->{psgi_env} = $env;
509 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
510 $self->{patches} = []; # [ $di, $di, ... ]
511 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
512 $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
514 dbg($self, "solving $oid_want ...");
515 my $step_cb = step_cb($self);
516 if (my $async = $env->{'pi-httpd.async'}) {
517 # PublicInbox::HTTPD::Async->new
518 $async->(undef, $step_cb);
520 $step_cb->() while $self->{user_cb};