]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
solvergit: deal with false-positive dfpost: results
[public-inbox.git] / lib / PublicInbox / SolverGit.pm
1 # Copyright (C) 2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "Solve" blobs which don't exist in git code repositories by
5 # searching inboxes for post-image blobs.
6
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;
11 use strict;
12 use warnings;
13 use File::Temp qw();
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);
20
21 # POSIX requires _POSIX_ARG_MAX >= 4096, and xargs is required to
22 # subtract 2048 bytes.  We also don't factor in environment variable
23 # headroom into this.
24 use POSIX qw(sysconf _SC_ARG_MAX);
25 my $ARG_SIZE_MAX = (sysconf(_SC_ARG_MAX) || 4096) - 2048;
26 my $OID_MIN = 7;
27
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.
34 my $MAX_PATCH = 9999;
35
36 # di = diff info / a hashref with information about a diff ($di):
37 # {
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)
48 # }
49
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 } ('', '.', '..');
53
54 sub dbg ($$) {
55         print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
56 }
57
58 sub ERR ($$) {
59         my ($self, $err) = @_;
60         print { $self->{out} } $err, "\n";
61         my $ucb = delete($self->{user_cb});
62         eval { $ucb->($err) } if $ucb;
63         die $err;
64 }
65
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) ];
76                 }
77
78                 next if length($oid_b) == 40;
79
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);
84
85                 # TODO: do something with the ambiguous array?
86                 # push @ambiguous, [ $git, @oids ];
87
88                 dbg($self, "`$oid_b' ambiguous in " .
89                                 join("\n\t", $git->pub_urls($self->{psgi_env}))
90                                 . "\n" .
91                                 join('', map { "$_ blob\n" } @oids));
92         }
93         scalar(@ambiguous) ? \@ambiguous : undef;
94 }
95
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/...
100         my $tmp;
101         my $ct = $part->content_type || 'text/plain';
102         my ($s, undef) = msg_part_text($part, $ct);
103         defined $s or return;
104         my $di = {};
105
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") {
110                 $s =~ s/\r\n/\n/sg;
111         }
112
113         foreach my $l (split(/^/m, $s)) {
114                 if ($l =~ $re) {
115                         $di->{oid_a} = $1;
116                         $di->{oid_b} = $2;
117                         if (defined($3)) {
118                                 my $mode_a = $3;
119                                 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
120                                         $di->{mode_a} = $mode_a;
121                                 }
122                         }
123
124
125                         # start writing the diff out to a tempfile
126                         my $path = ++$self->{tot};
127                         $di->{n} = $path;
128                         open($tmp, '>', $self->{tmp}->dirname . "/$path") or
129                                                         die "open(tmp): $!";
130
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): $!";
135
136                         # for debugging/diagnostics:
137                         $di->{ibx} = $ibx;
138                         $di->{smsg} = $smsg;
139                 } elsif ($l =~ m!\Adiff --git ("?[^/]+/.+) ("?[^/]+/.+)$!) {
140                         last if $tmp; # got our blob, done!
141
142                         my ($path_a, $path_b) = ($1, $2);
143
144                         # diff header lines won't have \r because git
145                         # will quote them, but Email::MIME gives CRLF
146                         # for quoted-printable:
147                         $path_b =~ tr/\r//d;
148
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));
152
153                         # get rid of path-traversal attempts and junk patches:
154                         foreach (@a, @b) {
155                                 return if $bad_component{$_};
156                         }
157
158                         $di->{path_a} = join('/', @a);
159                         $di->{path_b} = join('/', @b);
160                         $hdr_lines = [ $l ];
161                 } elsif ($tmp) {
162                         utf8::encode($l);
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)$/) {
167                                 $di->{mode_a} = $1;
168                         }
169                 }
170         }
171         return undef unless $tmp;
172         close $tmp or die "close(tmp): $!";
173         $di;
174 }
175
176 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
177
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]));
183 }
184
185 sub find_extract_diffs ($$$) {
186         my ($self, $ibx, $want) = @_;
187         my $srch = $ibx->search or return;
188
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";
191
192         my $q = "dfpost:$post";
193         my $pre = $want->{oid_a};
194         if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
195                 $q .= " dfpre:$pre";
196         } else {
197                 $pre = '[a-f0-9]{7}'; # for $re below
198         }
199
200         my $path_b = $want->{path_b};
201         if (path_searchable($path_b)) {
202                 $q .= filename_query($path_b);
203
204                 my $path_a = $want->{path_a};
205                 if (path_searchable($path_a) && $path_a ne $path_b) {
206                         $q .= filename_query($path_a);
207                 }
208         }
209
210         my $msgs = $srch->query($q, { relevance => 1 });
211         my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: ([0-9]+))?/;
212
213         my @di;
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);
219                 });
220         }
221         @di ? \@di : undef;
222 }
223
224 sub prepare_index ($) {
225         my ($self) = @_;
226         my $patches = $self->{patches};
227         $self->{nr} = 0;
228
229         my $di = $patches->[0] or die 'no patches';
230         my $oid_a = $di->{oid_a} or die '{oid_a} unset';
231         my $existing = $self->{found}->{$oid_a};
232
233         # no index creation for added files
234         $oid_a =~ /\A0+\z/ and return next_step($self);
235
236         die "BUG: $oid_a not not found" unless $existing;
237
238         my $oid_full = $existing->[1];
239         my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
240         my $mode_a = $di->{mode_a} || extract_old_mode($di);
241
242         my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
243         print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
244         $in->flush or die "flush: $!";
245         sysseek($in, 0, 0) or die "seek: $!";
246
247         dbg($self, 'preparing index');
248         my $rdr = { 0 => fileno($in), -hold => $in };
249         my $cmd = [ qw(git update-index -z --index-info) ];
250         my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
251         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
252                 my ($bref) = @_;
253                 if (my $err = $qsp->{err}) {
254                         ERR($self, "git update-index error: $err");
255                 }
256                 dbg($self, "index prepared:\n" .
257                         "$mode_a $oid_full\t" . git_quote($path_a));
258                 next_step($self); # onto do_git_apply
259         });
260 }
261
262 # pure Perl "git init"
263 sub do_git_init ($) {
264         my ($self) = @_;
265         my $dir = $self->{tmp}->dirname;
266         my $git_dir = "$dir/git";
267
268         foreach ('', qw(objects refs objects/info refs/heads)) {
269                 mkdir("$git_dir/$_") or die "mkdir $_: $!";
270         }
271         open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
272         print $fh <<'EOF' or die "print git/config $!";
273 [core]
274         repositoryFormatVersion = 0
275         filemode = true
276         bare = false
277         fsyncObjectfiles = false
278         logAllRefUpdates = false
279 EOF
280         close $fh or die "close git/config: $!";
281
282         open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
283         print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
284         close $fh or die "close git/HEAD: $!";
285
286         my $f = 'objects/info/alternates';
287         open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
288         foreach my $git (@{$self->{gits}}) {
289                 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
290         }
291         close $fh or die "close: $f: $!";
292         my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
293         $tmp_git->{-tmp} = $self->{tmp};
294         $self->{git_env} = {
295                 GIT_DIR => $git_dir,
296                 GIT_INDEX_FILE => "$git_dir/index",
297         };
298         prepare_index($self);
299 }
300
301 sub extract_old_mode ($) {
302         my ($di) = @_;
303         if (join('', @{$di->{hdr_lines}}) =~
304                         /^old mode (100644|100755|120000)\b/) {
305                 return $1;
306         }
307         '100644';
308 }
309
310 sub do_finish ($$) {
311         my ($self, $user_cb) = @_;
312         my $found = $self->{found};
313         my $oid_want = $self->{oid_want};
314         if (my $exists = $found->{$oid_want}) {
315                 return $user_cb->($exists);
316         }
317
318         # let git disambiguate if oid_want was too short,
319         # but long enough to be unambiguous:
320         my $tmp_git = $self->{tmp_git};
321         if (my @res = $tmp_git->check($oid_want)) {
322                 return $user_cb->($found->{$res[0]});
323         }
324         if (my $err = $tmp_git->last_check_err) {
325                 dbg($self, $err);
326         }
327         $user_cb->(undef);
328 }
329
330 sub do_step ($) {
331         my ($self) = @_;
332         eval {
333                 # step 1: resolve blobs to patches in the todo queue
334                 if (my $want = pop @{$self->{todo}}) {
335                         # this populates {patches} and {todo}
336                         resolve_patch($self, $want);
337
338                 # step 2: then we instantiate a working tree once
339                 # the todo queue is finally empty:
340                 } elsif (!defined($self->{tmp_git})) {
341                         do_git_init($self);
342
343                 # step 3: apply each patch in the stack
344                 } elsif (scalar @{$self->{patches}}) {
345                         do_git_apply($self);
346
347                 # step 4: execute the user-supplied callback with
348                 # our result: (which may be undef)
349                 # Other steps may call user_cb to terminate prematurely
350                 # on error
351                 } elsif (my $user_cb = delete($self->{user_cb})) {
352                         do_finish($self, $user_cb);
353                 } else {
354                         die 'about to call user_cb twice'; # Oops :x
355                 }
356         }; # eval
357         my $err = $@;
358         if ($err) {
359                 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
360                 dbg($self, "E: $err");
361                 my $ucb = delete($self->{user_cb});
362                 eval { $ucb->($err) } if $ucb;
363         }
364 }
365
366 sub step_cb ($) {
367         my ($self) = @_;
368         sub { do_step($self) };
369 }
370
371 sub next_step ($) {
372         my ($self) = @_;
373         # if outside of public-inbox-httpd, caller is expected to be
374         # looping step_cb, anyways
375         my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
376         # PublicInbox::HTTPD::Async->new
377         $async->(undef, step_cb($self));
378 }
379
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;
387                 chop($oid_cur);
388         }
389 }
390
391 sub parse_ls_files ($$$$) {
392         my ($self, $qsp, $bref, $di) = @_;
393         if (my $err = $qsp->{err}) {
394                 die "git ls-files error: $err";
395         }
396
397         my ($line, @extra) = split(/\0/, $$bref);
398         scalar(@extra) and die "BUG: extra files in index: <",
399                                 join('> <', @extra), ">";
400
401         my ($info, $file) = split(/\t/, $line, 2);
402         my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
403         if ($file ne $di->{path_b}) {
404                 die
405 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
406         }
407
408         my $tmp_git = $self->{tmp_git} or die 'no git working tree';
409         my (undef, undef, $size) = $tmp_git->check($oid_b_full);
410         defined($size) or die "check $oid_b_full failed";
411
412         dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
413         my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
414         mark_found($self, $di->{oid_b}, $created);
415         next_step($self); # onto the next patch
416 }
417
418 sub start_ls_files ($$) {
419         my ($self, $di) = @_;
420         my $cmd = [qw(git ls-files -s -z)];
421         my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
422         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
423                 my ($bref) = @_;
424                 eval { parse_ls_files($self, $qsp, $bref, $di) };
425                 ERR($self, $@) if $@;
426         });
427 }
428
429 sub oids_same_ish ($$) {
430         (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
431 }
432
433 sub skip_identical ($$$) {
434         my ($self, $patches, $cur_oid_b) = @_;
435         while (my $nxt = $patches->[0]) {
436                 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
437                         dbg($self, 'skipping '.di_url($self, $nxt).
438                                 " for $cur_oid_b");
439                         shift @$patches;
440                 } else {
441                         return;
442                 }
443         }
444 }
445
446 sub do_git_apply ($) {
447         my ($self) = @_;
448         my $dn = $self->{tmp}->dirname;
449         my $patches = $self->{patches};
450
451         # we need --ignore-whitespace because some patches are CRLF
452         my @cmd = (qw(git -C), $dn, qw(apply --cached --ignore-whitespace
453                         --whitespace=warn --verbose));
454         my $len = length(join(' ', @cmd));
455         my $total = $self->{tot};
456         my $di; # keep track of the last one for "git ls-files"
457         my $prv_oid_b;
458
459         do {
460                 my $i = ++$self->{nr};
461                 $di = shift @$patches;
462                 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
463                         "\n" . join('', @{$di->{hdr_lines}}));
464                 my $path = $di->{n};
465                 $len += length($path) + 1;
466                 push @cmd, $path;
467                 $prv_oid_b = $di->{oid_b};
468         } while (@$patches && $len < $ARG_SIZE_MAX &&
469                  !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
470
471         my $rdr = { 2 => 1 };
472         my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
473         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
474                 my ($bref) = @_;
475                 dbg($self, $$bref);
476                 if (my $err = $qsp->{err}) {
477                         my $msg = "git apply error: $err";
478                         my $nxt = $patches->[0];
479                         if ($nxt && oids_same_ish($nxt->{oid_b}, $prv_oid_b)) {
480                                 dbg($self, $msg);
481                                 dbg($self, 'trying '.di_url($self, $nxt));
482                         } else {
483                                 ERR($self, $msg);
484                         }
485                 } else {
486                         skip_identical($self, $patches, $di->{oid_b});
487                 }
488                 eval { start_ls_files($self, $di) };
489                 ERR($self, $@) if $@;
490         });
491 }
492
493 sub di_url ($$) {
494         my ($self, $di) = @_;
495         # note: we don't pass the PSGI env unconditionally, here,
496         # different inboxes can have different HTTP_HOST on the same instance.
497         my $ibx = $di->{ibx};
498         my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
499         my $url = $ibx->base_url($env);
500         my $mid = $di->{smsg}->{mid};
501         defined($url) ? "$url$mid/" : "<$mid>";
502 }
503
504 sub resolve_patch ($$) {
505         my ($self, $want) = @_;
506
507         if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
508                 die "Aborting, too many steps to $self->{oid_want}";
509         }
510
511         # see if we can find the blob in an existing git repo:
512         my $cur_want = $want->{oid_b};
513         if ($self->{seen_oid}->{$cur_want}++) {
514                 die "Loop detected solving $cur_want\n";
515         }
516         if (my $existing = solve_existing($self, $want)) {
517                 my ($found_git, undef, $type, undef) = @$existing;
518                 dbg($self, "found $cur_want in " .
519                         join("\n", $found_git->pub_urls($self->{psgi_env})));
520
521                 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
522                         eval { delete($self->{user_cb})->($existing) };
523                         die "E: $@" if $@;
524                         return;
525                 }
526                 mark_found($self, $cur_want, $existing);
527                 return next_step($self); # onto patch application
528         }
529
530         # scan through inboxes to look for emails which results in
531         # the oid we want:
532         foreach my $ibx (@{$self->{inboxes}}) {
533                 my $diffs = find_extract_diffs($self, $ibx, $want) or next;
534
535                 unshift @{$self->{patches}}, @$diffs;
536                 dbg($self, "found $cur_want in ".
537                         join("\n\t", map { di_url($self, $_) } @$diffs));
538
539                 # good, we can find a path to the oid we $want, now
540                 # lets see if we need to apply more patches:
541                 my $di = $diffs->[0];
542                 my $src = $di->{oid_a};
543
544                 unless ($src =~ /\A0+\z/) {
545                         # we have to solve it using another oid, fine:
546                         my $job = { oid_b => $src, path_b => $di->{path_a} };
547                         push @{$self->{todo}}, $job;
548                 }
549                 return next_step($self); # onto the next todo item
550         }
551         if (length($cur_want) > $OID_MIN) {
552                 chop($cur_want);
553                 dbg($self, "retrying $want->{oid_b} as $cur_want");
554                 $want->{oid_b} = $cur_want;
555                 push @{$self->{todo}}, $want;
556                 return next_step($self); # retry with shorter abbrev
557         }
558
559         dbg($self, "could not find $cur_want");
560         eval { delete($self->{user_cb})->(undef) }; # not found! :<
561         die "E: $@" if $@;
562 }
563
564 # this API is designed to avoid creating self-referential structures;
565 # so user_cb never references the SolverGit object
566 sub new {
567         my ($class, $ibx, $user_cb) = @_;
568
569         bless {
570                 gits => $ibx->{-repo_objs},
571                 user_cb => $user_cb,
572
573                 # TODO: config option for searching related inboxes
574                 inboxes => [ $ibx ],
575         }, $class;
576 }
577
578 # recreate $oid_want using $hints
579 # hints keys: path_a, path_b, oid_a
580 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
581 # with found object, or undef if nothing was found
582 # Calls {user_cb} with a string error on fatal errors
583 sub solve ($$$$$) {
584         my ($self, $env, $out, $oid_want, $hints) = @_;
585
586         # should we even get here? Probably not, but somebody
587         # could be manually typing URLs:
588         return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
589
590         $self->{oid_want} = $oid_want;
591         $self->{out} = $out;
592         $self->{seen_oid} = {};
593         $self->{tot} = 0;
594         $self->{psgi_env} = $env;
595         $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
596         $self->{patches} = []; # [ $di, $di, ... ]
597         $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
598         $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXXXXXX", TMPDIR => 1);
599
600         dbg($self, "solving $oid_want ...");
601         my $step_cb = step_cb($self);
602         if (my $async = $env->{'pi-httpd.async'}) {
603                 # PublicInbox::HTTPD::Async->new
604                 $async->(undef, $step_cb);
605         } else {
606                 $step_cb->() while $self->{user_cb};
607         }
608 }
609
610 1;