]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
solver: reduce "git apply" invocations
[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 # di = diff info / a hashref with information about a diff ($di):
28 # {
29 #       oid_a => abbreviated pre-image oid,
30 #       oid_b => abbreviated post-image oid,
31 #       tmp => anonymous file handle with the diff,
32 #       hdr_lines => arrayref of various header lines for mode information
33 #       mode_a => original mode of oid_a (string, not integer),
34 #       ibx => PublicInbox::Inbox object containing the diff
35 #       smsg => PublicInbox::SearchMsg object containing diff
36 #       path_a => pre-image path
37 #       path_b => post-image path
38 # }
39
40 # don't bother if somebody sends us a patch with these path components,
41 # it's junk at best, an attack attempt at worse:
42 my %bad_component = map { $_ => 1 } ('', '.', '..');
43
44 sub dbg ($$) {
45         print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
46 }
47
48 sub ERR ($$) {
49         my ($self, $err) = @_;
50         print { $self->{out} } $err, "\n";
51         my $ucb = delete($self->{user_cb});
52         eval { $ucb->($err) } if $ucb;
53         die $err;
54 }
55
56 # look for existing blobs already in git repos
57 sub solve_existing ($$) {
58         my ($self, $want) = @_;
59         my $oid_b = $want->{oid_b};
60         my @ambiguous; # Array of [ git, $oids]
61         foreach my $git (@{$self->{gits}}) {
62                 my ($oid_full, $type, $size) = $git->check($oid_b);
63                 if (defined($type) && $type eq 'blob') {
64                         return [ $git, $oid_full, $type, int($size) ];
65                 }
66
67                 next if length($oid_b) == 40;
68
69                 # parse stderr of "git cat-file --batch-check"
70                 my $err = $git->last_check_err;
71                 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
72                 next unless scalar(@oids);
73
74                 # TODO: do something with the ambiguous array?
75                 # push @ambiguous, [ $git, @oids ];
76
77                 dbg($self, "`$oid_b' ambiguous in " .
78                                 join("\n\t", $git->pub_urls) . "\n" .
79                                 join('', map { "$_ blob\n" } @oids));
80         }
81         scalar(@ambiguous) ? \@ambiguous : undef;
82 }
83
84 sub extract_diff ($$$$$) {
85         my ($self, $p, $re, $ibx, $smsg) = @_;
86         my ($part) = @$p; # ignore $depth and @idx;
87         my $hdr_lines; # diff --git a/... b/...
88         my $tmp;
89         my $ct = $part->content_type || 'text/plain';
90         my ($s, undef) = msg_part_text($part, $ct);
91         defined $s or return;
92         my $di = {};
93
94         # Email::MIME::Encodings forces QP to be CRLF upon decoding,
95         # change it back to LF:
96         my $cte = $part->header('Content-Transfer-Encoding') || '';
97         if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
98                 $s =~ s/\r\n/\n/sg;
99         }
100
101         foreach my $l (split(/^/m, $s)) {
102                 if ($l =~ $re) {
103                         $di->{oid_a} = $1;
104                         $di->{oid_b} = $2;
105                         if (defined($3)) {
106                                 my $mode_a = $3;
107                                 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
108                                         $di->{mode_a} = $mode_a;
109                                 }
110                         }
111
112
113                         # start writing the diff out to a tempfile
114                         my $pn = ++$self->{tot};
115                         open($tmp, '>', $self->{tmp}->dirname . "/$pn") or
116                                                         die "open(tmp): $!";
117
118                         push @$hdr_lines, $l;
119                         $di->{hdr_lines} = $hdr_lines;
120                         print $tmp @$hdr_lines or die "print(tmp): $!";
121
122                         # for debugging/diagnostics:
123                         $di->{ibx} = $ibx;
124                         $di->{smsg} = $smsg;
125                 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
126                         last if $tmp; # got our blob, done!
127
128                         my ($path_a, $path_b) = ($1, $2);
129
130                         # diff header lines won't have \r because git
131                         # will quote them, but Email::MIME gives CRLF
132                         # for quoted-printable:
133                         $path_b =~ tr/\r//d;
134
135                         # don't care for leading 'a/' and 'b/'
136                         my (undef, @a) = split(m{/}, git_unquote($path_a));
137                         my (undef, @b) = split(m{/}, git_unquote($path_b));
138
139                         # get rid of path-traversal attempts and junk patches:
140                         foreach (@a, @b) {
141                                 return if $bad_component{$_};
142                         }
143
144                         $di->{path_a} = join('/', @a);
145                         $di->{path_b} = join('/', @b);
146                         $hdr_lines = [ $l ];
147                 } elsif ($tmp) {
148                         print $tmp $l or die "print(tmp): $!";
149                 } elsif ($hdr_lines) {
150                         push @$hdr_lines, $l;
151                         if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
152                                 $di->{mode_a} = $1;
153                         }
154                 }
155         }
156         return undef unless $tmp;
157         close $tmp or die "close(tmp): $!";
158         $di;
159 }
160
161 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
162
163 sub find_extract_diff ($$$) {
164         my ($self, $ibx, $want) = @_;
165         my $srch = $ibx->search or return;
166
167         my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
168         $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
169
170         my $q = "dfpost:$post";
171         my $pre = $want->{oid_a};
172         if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
173                 $q .= " dfpre:$pre";
174         } else {
175                 $pre = '[a-f0-9]{7}'; # for $re below
176         }
177
178         my $path_b = $want->{path_b};
179         if (path_searchable($path_b)) {
180                 $q .= qq{ dfn:"$path_b"};
181
182                 my $path_a = $want->{path_a};
183                 if (path_searchable($path_a) && $path_a ne $path_b) {
184                         $q .= qq{ dfn:"$path_a"};
185                 }
186         }
187
188         my $msgs = $srch->query($q, { relevance => 1 });
189         my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
190
191         my $di;
192         foreach my $smsg (@$msgs) {
193                 $ibx->smsg_mime($smsg) or next;
194                 msg_iter(delete($smsg->{mime}), sub {
195                         $di ||= extract_diff($self, $_[0], $re, $ibx, $smsg);
196                 });
197                 return $di if $di;
198         }
199 }
200
201 sub prepare_index ($) {
202         my ($self) = @_;
203         my $patches = $self->{patches};
204         $self->{nr} = 0;
205
206         my $di = $patches->[0] or die 'no patches';
207         my $oid_a = $di->{oid_a} or die '{oid_a} unset';
208         my $existing = $self->{found}->{$oid_a};
209
210         # no index creation for added files
211         $oid_a =~ /\A0+\z/ and return next_step($self);
212
213         die "BUG: $oid_a not not found" unless $existing;
214
215         my $oid_full = $existing->[1];
216         my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
217         my $mode_a = $di->{mode_a} || extract_old_mode($di);
218
219         open my $in, '+>', undef or die "open: $!";
220         print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
221         $in->flush or die "flush: $!";
222         sysseek($in, 0, 0) or die "seek: $!";
223
224         dbg($self, 'preparing index');
225         my $rdr = { 0 => fileno($in) };
226         my $cmd = [ qw(git update-index -z --index-info) ];
227         my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
228         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
229                 my ($bref) = @_;
230                 if (my $err = $qsp->{err}) {
231                         ERR($self, "git update-index error: $err");
232                 }
233                 dbg($self, "index prepared:\n" .
234                         "$mode_a $oid_full\t" . git_quote($path_a));
235                 next_step($self); # onto do_git_apply
236         });
237 }
238
239 # pure Perl "git init"
240 sub do_git_init ($) {
241         my ($self) = @_;
242         my $dir = $self->{tmp}->dirname;
243         my $git_dir = "$dir/git";
244
245         foreach ('', qw(objects refs objects/info refs/heads)) {
246                 mkdir("$git_dir/$_") or die "mkdir $_: $!";
247         }
248         open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
249         print $fh <<'EOF' or die "print git/config $!";
250 [core]
251         repositoryFormatVersion = 0
252         filemode = true
253         bare = false
254         fsyncObjectfiles = false
255         logAllRefUpdates = false
256 EOF
257         close $fh or die "close git/config: $!";
258
259         open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
260         print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
261         close $fh or die "close git/HEAD: $!";
262
263         my $f = 'objects/info/alternates';
264         open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
265         print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
266                 die "print $f: $!";
267         close $fh or die "close: $f: $!";
268         my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
269         $tmp_git->{-tmp} = $self->{tmp};
270         $self->{git_env} = {
271                 GIT_DIR => $git_dir,
272                 GIT_INDEX_FILE => "$git_dir/index",
273         };
274         prepare_index($self);
275 }
276
277 sub extract_old_mode ($) {
278         my ($di) = @_;
279         if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
280                 return $1;
281         }
282         '100644';
283 }
284
285 sub do_step ($) {
286         my ($self) = @_;
287         eval {
288                 # step 1: resolve blobs to patches in the todo queue
289                 if (my $want = pop @{$self->{todo}}) {
290                         # this populates {patches} and {todo}
291                         resolve_patch($self, $want);
292
293                 # step 2: then we instantiate a working tree once
294                 # the todo queue is finally empty:
295                 } elsif (!defined($self->{tmp_git})) {
296                         do_git_init($self);
297
298                 # step 3: apply each patch in the stack
299                 } elsif (scalar @{$self->{patches}}) {
300                         do_git_apply($self);
301
302                 # step 4: execute the user-supplied callback with
303                 # our result: (which may be undef)
304                 # Other steps may call user_cb to terminate prematurely
305                 # on error
306                 } elsif (my $ucb = delete($self->{user_cb})) {
307                         $ucb->($self->{found}->{$self->{oid_want}});
308                 } else {
309                         die 'about to call user_cb twice'; # Oops :x
310                 }
311         }; # eval
312         my $err = $@;
313         if ($err) {
314                 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
315                 dbg($self, "E: $err");
316                 my $ucb = delete($self->{user_cb});
317                 eval { $ucb->($err) } if $ucb;
318         }
319 }
320
321 sub step_cb ($) {
322         my ($self) = @_;
323         sub { do_step($self) };
324 }
325
326 sub next_step ($) {
327         my ($self) = @_;
328         # if outside of public-inbox-httpd, caller is expected to be
329         # looping step_cb, anyways
330         my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
331         # PublicInbox::HTTPD::Async->new
332         $async->(undef, step_cb($self));
333 }
334
335 sub mark_found ($$$) {
336         my ($self, $oid, $found_info) = @_;
337         $self->{found}->{$oid} = $found_info;
338 }
339
340 sub parse_ls_files ($$$$) {
341         my ($self, $qsp, $bref, $di) = @_;
342         if (my $err = $qsp->{err}) {
343                 die "git ls-files error: $err";
344         }
345
346         my ($line, @extra) = split(/\0/, $$bref);
347         scalar(@extra) and die "BUG: extra files in index: <",
348                                 join('> <', @extra), ">";
349
350         my ($info, $file) = split(/\t/, $line, 2);
351         my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
352         if ($file ne $di->{path_b}) {
353                 die
354 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
355         }
356
357         my $tmp_git = $self->{tmp_git} or die 'no git working tree';
358         my (undef, undef, $size) = $tmp_git->check($oid_b_full);
359         defined($size) or die "check $oid_b_full failed";
360
361         dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
362         my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
363         mark_found($self, $di->{oid_b}, $created);
364         next_step($self); # onto the next patch
365 }
366
367 sub start_ls_files ($$) {
368         my ($self, $di) = @_;
369         my $cmd = [qw(git ls-files -s -z)];
370         my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env});
371         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
372                 my ($bref) = @_;
373                 eval { parse_ls_files($self, $qsp, $bref, $di) };
374                 ERR($self, $@) if $@;
375         });
376 }
377
378 sub do_git_apply ($) {
379         my ($self) = @_;
380         my $dn = $self->{tmp}->dirname;
381         my $patches = $self->{patches};
382
383         # we need --ignore-whitespace because some patches are CRLF
384         my @cmd = qw(git apply --cached --ignore-whitespace
385                         --whitespace=warn --verbose);
386         my $len = length(join(' ', @cmd));
387         my $total = $self->{tot};
388         my $di; # keep track of the last one for "git ls-files"
389
390         do {
391                 my $i = ++$self->{nr};
392                 $di = shift @$patches;
393                 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
394                         "\n" . join('', @{$di->{hdr_lines}}));
395                 my $pn = $total + 1 - $i;
396                 my $path = "$dn/$pn";
397                 $len += length($path) + 1;
398                 push @cmd, $path;
399         } while (@$patches && $len < $ARG_SIZE_MAX);
400
401         my $rdr = { 2 => 1 };
402         my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $rdr);
403         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
404                 my ($bref) = @_;
405                 dbg($self, $$bref);
406                 if (my $err = $qsp->{err}) {
407                         ERR($self, "git apply error: $err");
408                 }
409                 eval { start_ls_files($self, $di) };
410                 ERR($self, $@) if $@;
411         });
412 }
413
414 sub di_url ($$) {
415         my ($self, $di) = @_;
416         # note: we don't pass the PSGI env unconditionally, here,
417         # different inboxes can have different HTTP_HOST on the same instance.
418         my $ibx = $di->{ibx};
419         my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
420         my $url = $ibx->base_url($env);
421         my $mid = $di->{smsg}->{mid};
422         defined($url) ? "$url$mid/" : "<$mid>";
423 }
424
425 sub resolve_patch ($$) {
426         my ($self, $want) = @_;
427
428         if (scalar(@{$self->{patches}}) > $self->{max_patch}) {
429                 die "Aborting, too many steps to $self->{oid_want}";
430         }
431
432         # see if we can find the blob in an existing git repo:
433         my $cur_want = $want->{oid_b};
434         if (my $existing = solve_existing($self, $want)) {
435                 dbg($self, "found $cur_want in " .
436                         join("\n", $existing->[0]->pub_urls));
437
438                 if ($cur_want eq $self->{oid_want}) { # all done!
439                         eval { delete($self->{user_cb})->($existing) };
440                         die "E: $@" if $@;
441                         return;
442                 }
443                 mark_found($self, $cur_want, $existing);
444                 return next_step($self); # onto patch application
445         }
446
447         # scan through inboxes to look for emails which results in
448         # the oid we want:
449         my $di;
450         foreach my $ibx (@{$self->{inboxes}}) {
451                 $di = find_extract_diff($self, $ibx, $want) or next;
452
453                 unshift @{$self->{patches}}, $di;
454                 dbg($self, "found $cur_want in ".di_url($self, $di));
455
456                 # good, we can find a path to the oid we $want, now
457                 # lets see if we need to apply more patches:
458                 my $src = $di->{oid_a};
459
460                 unless ($src =~ /\A0+\z/) {
461                         # we have to solve it using another oid, fine:
462                         my $job = { oid_b => $src, path_b => $di->{path_a} };
463                         push @{$self->{todo}}, $job;
464                 }
465                 return next_step($self); # onto the next todo item
466         }
467         dbg($self, "could not find $cur_want");
468         eval { delete($self->{user_cb})->(undef) }; # not found! :<
469         die "E: $@" if $@;
470 }
471
472 # this API is designed to avoid creating self-referential structures;
473 # so user_cb never references the SolverGit object
474 sub new {
475         my ($class, $ibx, $user_cb) = @_;
476
477         bless {
478                 gits => $ibx->{-repo_objs},
479                 user_cb => $user_cb,
480                 max_patch => 100,
481
482                 # TODO: config option for searching related inboxes
483                 inboxes => [ $ibx ],
484         }, $class;
485 }
486
487 # recreate $oid_want using $hints
488 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
489 # with found object, or undef if nothing was found
490 # Calls {user_cb} with a string error on fatal errors
491 sub solve ($$$$$) {
492         my ($self, $env, $out, $oid_want, $hints) = @_;
493
494         # should we even get here? Probably not, but somebody
495         # could be manually typing URLs:
496         return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
497
498         $self->{oid_want} = $oid_want;
499         $self->{out} = $out;
500         $self->{tot} = 0;
501         $self->{psgi_env} = $env;
502         $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
503         $self->{patches} = []; # [ $di, $di, ... ]
504         $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
505         $self->{tmp} = File::Temp->newdir('solver.tmp-XXXXXXXX', TMPDIR => 1);
506
507         dbg($self, "solving $oid_want ...");
508         my $step_cb = step_cb($self);
509         if (my $async = $env->{'pi-httpd.async'}) {
510                 # PublicInbox::HTTPD::Async->new
511                 $async->(undef, $step_cb);
512         } else {
513                 $step_cb->() while $self->{user_cb};
514         }
515 }
516
517 1;