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 # ".." appears in path names, which confuses Xapian into treating
174 # it as a range query. So we split on ".." since Xapian breaks
175 # on punctuation anyways:
176 sub filename_query ($) {
177 join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
180 sub find_extract_diff ($$$) {
181 my ($self, $ibx, $want) = @_;
182 my $srch = $ibx->search or return;
184 my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
185 $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
187 my $q = "dfpost:$post";
188 my $pre = $want->{oid_a};
189 if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
192 $pre = '[a-f0-9]{7}'; # for $re below
195 my $path_b = $want->{path_b};
196 if (path_searchable($path_b)) {
197 $q .= filename_query($path_b);
199 my $path_a = $want->{path_a};
200 if (path_searchable($path_a) && $path_a ne $path_b) {
201 $q .= filename_query($path_a);
205 my $msgs = $srch->query($q, { relevance => 1 });
206 my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
209 foreach my $smsg (@$msgs) {
210 $ibx->smsg_mime($smsg) or next;
211 msg_iter(delete($smsg->{mime}), sub {
212 $di ||= extract_diff($self, $_[0], $re, $ibx, $smsg);
218 sub prepare_index ($) {
220 my $patches = $self->{patches};
223 my $di = $patches->[0] or die 'no patches';
224 my $oid_a = $di->{oid_a} or die '{oid_a} unset';
225 my $existing = $self->{found}->{$oid_a};
227 # no index creation for added files
228 $oid_a =~ /\A0+\z/ and return next_step($self);
230 die "BUG: $oid_a not not found" unless $existing;
232 my $oid_full = $existing->[1];
233 my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
234 my $mode_a = $di->{mode_a} || extract_old_mode($di);
236 open my $in, '+>', undef or die "open: $!";
237 print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
238 $in->flush or die "flush: $!";
239 sysseek($in, 0, 0) or die "seek: $!";
241 dbg($self, 'preparing index');
242 my $rdr = { 0 => fileno($in) };
243 my $cmd = [ qw(git update-index -z --index-info) ];
244 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
245 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
247 if (my $err = $qsp->{err}) {
248 ERR($self, "git update-index error: $err");
250 dbg($self, "index prepared:\n" .
251 "$mode_a $oid_full\t" . git_quote($path_a));
252 next_step($self); # onto do_git_apply
256 # pure Perl "git init"
257 sub do_git_init ($) {
259 my $dir = $self->{tmp}->dirname;
260 my $git_dir = "$dir/git";
262 foreach ('', qw(objects refs objects/info refs/heads)) {
263 mkdir("$git_dir/$_") or die "mkdir $_: $!";
265 open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
266 print $fh <<'EOF' or die "print git/config $!";
268 repositoryFormatVersion = 0
271 fsyncObjectfiles = false
272 logAllRefUpdates = false
274 close $fh or die "close git/config: $!";
276 open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
277 print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
278 close $fh or die "close git/HEAD: $!";
280 my $f = 'objects/info/alternates';
281 open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
282 foreach my $git (@{$self->{gits}}) {
283 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
285 close $fh or die "close: $f: $!";
286 my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
287 $tmp_git->{-tmp} = $self->{tmp};
290 GIT_INDEX_FILE => "$git_dir/index",
292 prepare_index($self);
295 sub extract_old_mode ($) {
297 if (join('', @{$di->{hdr_lines}}) =~
298 /^old mode (100644|100755|120000)\b/) {
307 # step 1: resolve blobs to patches in the todo queue
308 if (my $want = pop @{$self->{todo}}) {
309 # this populates {patches} and {todo}
310 resolve_patch($self, $want);
312 # step 2: then we instantiate a working tree once
313 # the todo queue is finally empty:
314 } elsif (!defined($self->{tmp_git})) {
317 # step 3: apply each patch in the stack
318 } elsif (scalar @{$self->{patches}}) {
321 # step 4: execute the user-supplied callback with
322 # our result: (which may be undef)
323 # Other steps may call user_cb to terminate prematurely
325 } elsif (my $ucb = delete($self->{user_cb})) {
326 $ucb->($self->{found}->{$self->{oid_want}});
328 die 'about to call user_cb twice'; # Oops :x
333 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
334 dbg($self, "E: $err");
335 my $ucb = delete($self->{user_cb});
336 eval { $ucb->($err) } if $ucb;
342 sub { do_step($self) };
347 # if outside of public-inbox-httpd, caller is expected to be
348 # looping step_cb, anyways
349 my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
350 # PublicInbox::HTTPD::Async->new
351 $async->(undef, step_cb($self));
354 sub mark_found ($$$) {
355 my ($self, $oid, $found_info) = @_;
356 $self->{found}->{$oid} = $found_info;
359 sub parse_ls_files ($$$$) {
360 my ($self, $qsp, $bref, $di) = @_;
361 if (my $err = $qsp->{err}) {
362 die "git ls-files error: $err";
365 my ($line, @extra) = split(/\0/, $$bref);
366 scalar(@extra) and die "BUG: extra files in index: <",
367 join('> <', @extra), ">";
369 my ($info, $file) = split(/\t/, $line, 2);
370 my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
371 if ($file ne $di->{path_b}) {
373 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
376 my $tmp_git = $self->{tmp_git} or die 'no git working tree';
377 my (undef, undef, $size) = $tmp_git->check($oid_b_full);
378 defined($size) or die "check $oid_b_full failed";
380 dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
381 my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
382 mark_found($self, $di->{oid_b}, $created);
383 next_step($self); # onto the next patch
386 sub start_ls_files ($$) {
387 my ($self, $di) = @_;
388 my $cmd = [qw(git ls-files -s -z)];
389 my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
390 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
392 eval { parse_ls_files($self, $qsp, $bref, $di) };
393 ERR($self, $@) if $@;
397 sub do_git_apply ($) {
399 my $dn = $self->{tmp}->dirname;
400 my $patches = $self->{patches};
402 # we need --ignore-whitespace because some patches are CRLF
403 my @cmd = (qw(git -C), $dn, qw(apply --cached --ignore-whitespace
404 --whitespace=warn --verbose));
405 my $len = length(join(' ', @cmd));
406 my $total = $self->{tot};
407 my $di; # keep track of the last one for "git ls-files"
410 my $i = ++$self->{nr};
411 $di = shift @$patches;
412 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
413 "\n" . join('', @{$di->{hdr_lines}}));
414 my $path = $total + 1 - $i;
415 $len += length($path) + 1;
417 } while (@$patches && $len < $ARG_SIZE_MAX);
419 my $rdr = { 2 => 1 };
420 my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
421 $qsp->psgi_qx($self->{psgi_env}, undef, sub {
424 if (my $err = $qsp->{err}) {
425 ERR($self, "git apply error: $err");
427 eval { start_ls_files($self, $di) };
428 ERR($self, $@) if $@;
433 my ($self, $di) = @_;
434 # note: we don't pass the PSGI env unconditionally, here,
435 # different inboxes can have different HTTP_HOST on the same instance.
436 my $ibx = $di->{ibx};
437 my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
438 my $url = $ibx->base_url($env);
439 my $mid = $di->{smsg}->{mid};
440 defined($url) ? "$url$mid/" : "<$mid>";
443 sub resolve_patch ($$) {
444 my ($self, $want) = @_;
446 if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
447 die "Aborting, too many steps to $self->{oid_want}";
450 # see if we can find the blob in an existing git repo:
451 my $cur_want = $want->{oid_b};
452 if ($self->{seen_oid}->{$cur_want}++) {
453 die "Loop detected solving $cur_want\n";
455 if (my $existing = solve_existing($self, $want)) {
456 dbg($self, "found $cur_want in " .
457 join("\n", $existing->[0]->pub_urls));
459 if ($cur_want eq $self->{oid_want}) { # all done!
460 eval { delete($self->{user_cb})->($existing) };
464 mark_found($self, $cur_want, $existing);
465 return next_step($self); # onto patch application
468 # scan through inboxes to look for emails which results in
471 foreach my $ibx (@{$self->{inboxes}}) {
472 $di = find_extract_diff($self, $ibx, $want) or next;
474 unshift @{$self->{patches}}, $di;
475 dbg($self, "found $cur_want in ".di_url($self, $di));
477 # good, we can find a path to the oid we $want, now
478 # lets see if we need to apply more patches:
479 my $src = $di->{oid_a};
481 unless ($src =~ /\A0+\z/) {
482 # we have to solve it using another oid, fine:
483 my $job = { oid_b => $src, path_b => $di->{path_a} };
484 push @{$self->{todo}}, $job;
486 return next_step($self); # onto the next todo item
488 dbg($self, "could not find $cur_want");
489 eval { delete($self->{user_cb})->(undef) }; # not found! :<
493 # this API is designed to avoid creating self-referential structures;
494 # so user_cb never references the SolverGit object
496 my ($class, $ibx, $user_cb) = @_;
499 gits => $ibx->{-repo_objs},
502 # TODO: config option for searching related inboxes
507 # recreate $oid_want using $hints
508 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
509 # with found object, or undef if nothing was found
510 # Calls {user_cb} with a string error on fatal errors
512 my ($self, $env, $out, $oid_want, $hints) = @_;
514 # should we even get here? Probably not, but somebody
515 # could be manually typing URLs:
516 return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
518 $self->{oid_want} = $oid_want;
520 $self->{seen_oid} = {};
522 $self->{psgi_env} = $env;
523 $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
524 $self->{patches} = []; # [ $di, $di, ... ]
525 $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
526 $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
528 dbg($self, "solving $oid_want ...");
529 my $step_cb = step_cb($self);
530 if (my $async = $env->{'pi-httpd.async'}) {
531 # PublicInbox::HTTPD::Async->new
532 $async->(undef, $step_cb);
534 $step_cb->() while $self->{user_cb};