]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
solvergit: do not solve blobs twice
[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::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);
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
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.
33 my $MAX_PATCH = 9999;
34
35 # di = diff info / a hashref with information about a diff ($di):
36 # {
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
46 # }
47
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 } ('', '.', '..');
51
52 sub dbg ($$) {
53         print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
54 }
55
56 sub ERR ($$) {
57         my ($self, $err) = @_;
58         print { $self->{out} } $err, "\n";
59         my $ucb = delete($self->{user_cb});
60         eval { $ucb->($err) } if $ucb;
61         die $err;
62 }
63
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) ];
73                 }
74
75                 next if length($oid_b) == 40;
76
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);
81
82                 # TODO: do something with the ambiguous array?
83                 # push @ambiguous, [ $git, @oids ];
84
85                 dbg($self, "`$oid_b' ambiguous in " .
86                                 join("\n\t", $git->pub_urls) . "\n" .
87                                 join('', map { "$_ blob\n" } @oids));
88         }
89         scalar(@ambiguous) ? \@ambiguous : undef;
90 }
91
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/...
96         my $tmp;
97         my $ct = $part->content_type || 'text/plain';
98         my ($s, undef) = msg_part_text($part, $ct);
99         defined $s or return;
100         my $di = {};
101
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") {
106                 $s =~ s/\r\n/\n/sg;
107         }
108
109         foreach my $l (split(/^/m, $s)) {
110                 if ($l =~ $re) {
111                         $di->{oid_a} = $1;
112                         $di->{oid_b} = $2;
113                         if (defined($3)) {
114                                 my $mode_a = $3;
115                                 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
116                                         $di->{mode_a} = $mode_a;
117                                 }
118                         }
119
120
121                         # start writing the diff out to a tempfile
122                         my $pn = ++$self->{tot};
123                         open($tmp, '>', $self->{tmp}->dirname . "/$pn") or
124                                                         die "open(tmp): $!";
125
126                         push @$hdr_lines, $l;
127                         $di->{hdr_lines} = $hdr_lines;
128                         print $tmp @$hdr_lines or die "print(tmp): $!";
129
130                         # for debugging/diagnostics:
131                         $di->{ibx} = $ibx;
132                         $di->{smsg} = $smsg;
133                 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
134                         last if $tmp; # got our blob, done!
135
136                         my ($path_a, $path_b) = ($1, $2);
137
138                         # diff header lines won't have \r because git
139                         # will quote them, but Email::MIME gives CRLF
140                         # for quoted-printable:
141                         $path_b =~ tr/\r//d;
142
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));
146
147                         # get rid of path-traversal attempts and junk patches:
148                         foreach (@a, @b) {
149                                 return if $bad_component{$_};
150                         }
151
152                         $di->{path_a} = join('/', @a);
153                         $di->{path_b} = join('/', @b);
154                         $hdr_lines = [ $l ];
155                 } elsif ($tmp) {
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)$/) {
160                                 $di->{mode_a} = $1;
161                         }
162                 }
163         }
164         return undef unless $tmp;
165         close $tmp or die "close(tmp): $!";
166         $di;
167 }
168
169 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
170
171 sub find_extract_diff ($$$) {
172         my ($self, $ibx, $want) = @_;
173         my $srch = $ibx->search or return;
174
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";
177
178         my $q = "dfpost:$post";
179         my $pre = $want->{oid_a};
180         if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
181                 $q .= " dfpre:$pre";
182         } else {
183                 $pre = '[a-f0-9]{7}'; # for $re below
184         }
185
186         my $path_b = $want->{path_b};
187         if (path_searchable($path_b)) {
188                 $q .= qq{ dfn:"$path_b"};
189
190                 my $path_a = $want->{path_a};
191                 if (path_searchable($path_a) && $path_a ne $path_b) {
192                         $q .= qq{ dfn:"$path_a"};
193                 }
194         }
195
196         my $msgs = $srch->query($q, { relevance => 1 });
197         my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
198
199         my $di;
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);
204                 });
205                 return $di if $di;
206         }
207 }
208
209 sub prepare_index ($) {
210         my ($self) = @_;
211         my $patches = $self->{patches};
212         $self->{nr} = 0;
213
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};
217
218         # no index creation for added files
219         $oid_a =~ /\A0+\z/ and return next_step($self);
220
221         die "BUG: $oid_a not not found" unless $existing;
222
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);
226
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: $!";
231
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 {
237                 my ($bref) = @_;
238                 if (my $err = $qsp->{err}) {
239                         ERR($self, "git update-index error: $err");
240                 }
241                 dbg($self, "index prepared:\n" .
242                         "$mode_a $oid_full\t" . git_quote($path_a));
243                 next_step($self); # onto do_git_apply
244         });
245 }
246
247 # pure Perl "git init"
248 sub do_git_init ($) {
249         my ($self) = @_;
250         my $dir = $self->{tmp}->dirname;
251         my $git_dir = "$dir/git";
252
253         foreach ('', qw(objects refs objects/info refs/heads)) {
254                 mkdir("$git_dir/$_") or die "mkdir $_: $!";
255         }
256         open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
257         print $fh <<'EOF' or die "print git/config $!";
258 [core]
259         repositoryFormatVersion = 0
260         filemode = true
261         bare = false
262         fsyncObjectfiles = false
263         logAllRefUpdates = false
264 EOF
265         close $fh or die "close git/config: $!";
266
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: $!";
270
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
274                 die "print $f: $!";
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};
278         $self->{git_env} = {
279                 GIT_DIR => $git_dir,
280                 GIT_INDEX_FILE => "$git_dir/index",
281         };
282         prepare_index($self);
283 }
284
285 sub extract_old_mode ($) {
286         my ($di) = @_;
287         if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
288                 return $1;
289         }
290         '100644';
291 }
292
293 sub do_step ($) {
294         my ($self) = @_;
295         eval {
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);
300
301                 # step 2: then we instantiate a working tree once
302                 # the todo queue is finally empty:
303                 } elsif (!defined($self->{tmp_git})) {
304                         do_git_init($self);
305
306                 # step 3: apply each patch in the stack
307                 } elsif (scalar @{$self->{patches}}) {
308                         do_git_apply($self);
309
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
313                 # on error
314                 } elsif (my $ucb = delete($self->{user_cb})) {
315                         $ucb->($self->{found}->{$self->{oid_want}});
316                 } else {
317                         die 'about to call user_cb twice'; # Oops :x
318                 }
319         }; # eval
320         my $err = $@;
321         if ($err) {
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;
326         }
327 }
328
329 sub step_cb ($) {
330         my ($self) = @_;
331         sub { do_step($self) };
332 }
333
334 sub next_step ($) {
335         my ($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));
341 }
342
343 sub mark_found ($$$) {
344         my ($self, $oid, $found_info) = @_;
345         $self->{found}->{$oid} = $found_info;
346 }
347
348 sub parse_ls_files ($$$$) {
349         my ($self, $qsp, $bref, $di) = @_;
350         if (my $err = $qsp->{err}) {
351                 die "git ls-files error: $err";
352         }
353
354         my ($line, @extra) = split(/\0/, $$bref);
355         scalar(@extra) and die "BUG: extra files in index: <",
356                                 join('> <', @extra), ">";
357
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}) {
361                 die
362 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
363         }
364
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";
368
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
373 }
374
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 {
380                 my ($bref) = @_;
381                 eval { parse_ls_files($self, $qsp, $bref, $di) };
382                 ERR($self, $@) if $@;
383         });
384 }
385
386 sub do_git_apply ($) {
387         my ($self) = @_;
388         my $dn = $self->{tmp}->dirname;
389         my $patches = $self->{patches};
390
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"
397
398         do {
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;
406                 push @cmd, $path;
407         } while (@$patches && $len < $ARG_SIZE_MAX);
408
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 {
412                 my ($bref) = @_;
413                 dbg($self, $$bref);
414                 if (my $err = $qsp->{err}) {
415                         ERR($self, "git apply error: $err");
416                 }
417                 eval { start_ls_files($self, $di) };
418                 ERR($self, $@) if $@;
419         });
420 }
421
422 sub di_url ($$) {
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>";
431 }
432
433 sub resolve_patch ($$) {
434         my ($self, $want) = @_;
435
436         if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
437                 die "Aborting, too many steps to $self->{oid_want}";
438         }
439
440         # see if we can find the blob in an existing git repo:
441         my $cur_want = $want->{oid_b};
442         if ($self->{seen_oid}->{$cur_want}++) {
443                 die "Loop detected solving $cur_want\n";
444         }
445         if (my $existing = solve_existing($self, $want)) {
446                 dbg($self, "found $cur_want in " .
447                         join("\n", $existing->[0]->pub_urls));
448
449                 if ($cur_want eq $self->{oid_want}) { # all done!
450                         eval { delete($self->{user_cb})->($existing) };
451                         die "E: $@" if $@;
452                         return;
453                 }
454                 mark_found($self, $cur_want, $existing);
455                 return next_step($self); # onto patch application
456         }
457
458         # scan through inboxes to look for emails which results in
459         # the oid we want:
460         my $di;
461         foreach my $ibx (@{$self->{inboxes}}) {
462                 $di = find_extract_diff($self, $ibx, $want) or next;
463
464                 unshift @{$self->{patches}}, $di;
465                 dbg($self, "found $cur_want in ".di_url($self, $di));
466
467                 # good, we can find a path to the oid we $want, now
468                 # lets see if we need to apply more patches:
469                 my $src = $di->{oid_a};
470
471                 unless ($src =~ /\A0+\z/) {
472                         # we have to solve it using another oid, fine:
473                         my $job = { oid_b => $src, path_b => $di->{path_a} };
474                         push @{$self->{todo}}, $job;
475                 }
476                 return next_step($self); # onto the next todo item
477         }
478         dbg($self, "could not find $cur_want");
479         eval { delete($self->{user_cb})->(undef) }; # not found! :<
480         die "E: $@" if $@;
481 }
482
483 # this API is designed to avoid creating self-referential structures;
484 # so user_cb never references the SolverGit object
485 sub new {
486         my ($class, $ibx, $user_cb) = @_;
487
488         bless {
489                 gits => $ibx->{-repo_objs},
490                 user_cb => $user_cb,
491
492                 # TODO: config option for searching related inboxes
493                 inboxes => [ $ibx ],
494         }, $class;
495 }
496
497 # recreate $oid_want using $hints
498 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
499 # with found object, or undef if nothing was found
500 # Calls {user_cb} with a string error on fatal errors
501 sub solve ($$$$$) {
502         my ($self, $env, $out, $oid_want, $hints) = @_;
503
504         # should we even get here? Probably not, but somebody
505         # could be manually typing URLs:
506         return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
507
508         $self->{oid_want} = $oid_want;
509         $self->{out} = $out;
510         $self->{seen_oid} = {};
511         $self->{tot} = 0;
512         $self->{psgi_env} = $env;
513         $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
514         $self->{patches} = []; # [ $di, $di, ... ]
515         $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
516         $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
517
518         dbg($self, "solving $oid_want ...");
519         my $step_cb = step_cb($self);
520         if (my $async = $env->{'pi-httpd.async'}) {
521                 # PublicInbox::HTTPD::Async->new
522                 $async->(undef, $step_cb);
523         } else {
524                 $step_cb->() while $self->{user_cb};
525         }
526 }
527
528 1;