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