]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
solver: rewrite to use Qspawn->psgi_qx and pi-httpd.async
[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 -C), $self->{wt_dir},
218                         qw(update-index -z --index-info) ];
219         my $qsp = PublicInbox::Qspawn->new($cmd, undef, $rdr);
220         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
221                 my ($bref) = @_;
222                 if (my $err = $qsp->{err}) {
223                         ERR($self, "git update-index error: $err");
224                 }
225                 dbg($self, "index prepared:\n" .
226                         "$mode_a $oid_full\t" . git_quote($path_a));
227                 next_step($self); # onto do_git_apply
228         });
229 }
230
231 # pure Perl "git init"
232 sub do_git_init_wt ($) {
233         my ($self) = @_;
234         my $wt = File::Temp->newdir('solver.wt-XXXXXXXX', TMPDIR => 1);
235         my $dir = $self->{wt_dir} = $wt->dirname;
236
237         foreach ('', qw(objects refs objects/info refs/heads)) {
238                 mkdir("$dir/.git/$_") or die "mkdir $_: $!";
239         }
240         open my $fh, '>', "$dir/.git/config" or die "open .git/config: $!";
241         print $fh <<'EOF' or die "print .git/config $!";
242 [core]
243         repositoryFormatVersion = 0
244         filemode = true
245         bare = false
246         fsyncObjectfiles = false
247         logAllRefUpdates = false
248 EOF
249         close $fh or die "close .git/config: $!";
250
251         open $fh, '>', "$dir/.git/HEAD" or die "open .git/HEAD: $!";
252         print $fh "ref: refs/heads/master\n" or die "print .git/HEAD: $!";
253         close $fh or die "close .git/HEAD: $!";
254
255         my $f = '.git/objects/info/alternates';
256         open $fh, '>', "$dir/$f" or die "open: $f: $!";
257         print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
258                 die "print $f: $!";
259         close $fh or die "close: $f: $!";
260         my $wt_git = $self->{wt_git} = PublicInbox::Git->new("$dir/.git");
261         $wt_git->{-wt} = $wt;
262         prepare_index($self);
263 }
264
265 sub extract_old_mode ($) {
266         my ($di) = @_;
267         if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
268                 return $1;
269         }
270         '100644';
271 }
272
273 sub do_step ($) {
274         my ($self) = @_;
275         eval {
276                 # step 1: resolve blobs to patches in the todo queue
277                 if (my $want = pop @{$self->{todo}}) {
278                         # this populates {patches} and {todo}
279                         resolve_patch($self, $want);
280
281                 # step 2: then we instantiate a working tree once
282                 # the todo queue is finally empty:
283                 } elsif (!defined($self->{wt_git})) {
284                         do_git_init_wt($self);
285
286                 # step 3: apply each patch in the stack
287                 } elsif (scalar @{$self->{patches}}) {
288                         do_git_apply($self);
289
290                 # step 4: execute the user-supplied callback with
291                 # our result: (which may be undef)
292                 # Other steps may call user_cb to terminate prematurely
293                 # on error
294                 } elsif (my $ucb = delete($self->{user_cb})) {
295                         $ucb->($self->{found}->{$self->{oid_want}});
296                 } else {
297                         die 'about to call user_cb twice'; # Oops :x
298                 }
299         }; # eval
300         my $err = $@;
301         if ($err) {
302                 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
303                 dbg($self, "E: $err");
304                 my $ucb = delete($self->{user_cb});
305                 eval { $ucb->($err) } if $ucb;
306         }
307 }
308
309 sub step_cb ($) {
310         my ($self) = @_;
311         sub { do_step($self) };
312 }
313
314 sub next_step ($) {
315         my ($self) = @_;
316         # if outside of public-inbox-httpd, caller is expected to be
317         # looping step_cb, anyways
318         my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
319         # PublicInbox::HTTPD::Async->new
320         $async->(undef, step_cb($self));
321 }
322
323 sub mark_found ($$$) {
324         my ($self, $oid, $found_info) = @_;
325         $self->{found}->{$oid} = $found_info;
326 }
327
328 sub parse_ls_files ($$$$) {
329         my ($self, $qsp, $bref, $di) = @_;
330         if (my $err = $qsp->{err}) {
331                 die "git ls-files error: $err";
332         }
333
334         my ($line, @extra) = split(/\0/, $$bref);
335         scalar(@extra) and die "BUG: extra files in index: <",
336                                 join('> <', @extra), ">";
337
338         my ($info, $file) = split(/\t/, $line, 2);
339         my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
340         if ($file ne $di->{path_b}) {
341                 die
342 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
343         }
344
345         my $wt_git = $self->{wt_git} or die 'no git working tree';
346         my (undef, undef, $size) = $wt_git->check($oid_b_full);
347         defined($size) or die "check $oid_b_full failed";
348
349         dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
350         my $created = [ $wt_git, $oid_b_full, 'blob', $size, $di ];
351         mark_found($self, $di->{oid_b}, $created);
352         next_step($self); # onto the next patch
353 }
354
355 sub start_ls_files ($$) {
356         my ($self, $di) = @_;
357         my $cmd = [qw(git -C), $self->{wt_dir}, qw(ls-files -s -z)];
358         my $qsp = PublicInbox::Qspawn->new($cmd);
359         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
360                 my ($bref) = @_;
361                 eval { parse_ls_files($self, $qsp, $bref, $di) };
362                 ERR($self, $@) if $@;
363         });
364 }
365
366 sub do_git_apply ($) {
367         my ($self) = @_;
368
369         my $di = shift @{$self->{patches}} or die 'empty {patches}';
370         my $tmp = delete $di->{tmp} or die 'no tmp ', di_url($self, $di);
371         $tmp->flush or die "tmp->flush failed: $!";
372         sysseek($tmp, 0, SEEK_SET) or die "sysseek(tmp) failed: $!";
373
374         my $i = ++$self->{nr};
375         dbg($self, "\napplying [$i/$self->{tot}] " . di_url($self, $di) .
376                 "\n" . join('', @{$di->{hdr_lines}}));
377
378         # we need --ignore-whitespace because some patches are CRLF
379         my $cmd = [ qw(git -C), $self->{wt_dir},
380                     qw(apply --cached --ignore-whitespace
381                        --whitespace=warn --verbose) ];
382         my $rdr = { 0 => fileno($tmp), 2 => 1 };
383         my $qsp = PublicInbox::Qspawn->new($cmd, undef, $rdr);
384         $qsp->psgi_qx($self->{psgi_env}, undef, sub {
385                 my ($bref) = @_;
386                 close $tmp;
387                 dbg($self, $$bref);
388                 if (my $err = $qsp->{err}) {
389                         ERR($self, "git apply error: $err");
390                 }
391                 eval { start_ls_files($self, $di) };
392                 ERR($self, $@) if $@;
393         });
394 }
395
396 sub di_url ($$) {
397         my ($self, $di) = @_;
398         # note: we don't pass the PSGI env unconditionally, here,
399         # different inboxes can have different HTTP_HOST on the same instance.
400         my $ibx = $di->{ibx};
401         my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
402         my $url = $ibx->base_url($env);
403         my $mid = $di->{smsg}->{mid};
404         defined($url) ? "$url$mid/" : "<$mid>";
405 }
406
407 sub resolve_patch ($$) {
408         my ($self, $want) = @_;
409
410         if (scalar(@{$self->{patches}}) > $self->{max_patch}) {
411                 die "Aborting, too many steps to $self->{oid_want}";
412         }
413
414         # see if we can find the blob in an existing git repo:
415         my $cur_want = $want->{oid_b};
416         if (my $existing = solve_existing($self, $want)) {
417                 dbg($self, "found $cur_want in " .
418                         join("\n", $existing->[0]->pub_urls));
419
420                 if ($cur_want eq $self->{oid_want}) { # all done!
421                         eval { delete($self->{user_cb})->($existing) };
422                         die "E: $@" if $@;
423                         return;
424                 }
425                 mark_found($self, $cur_want, $existing);
426                 return next_step($self); # onto patch application
427         }
428
429         # scan through inboxes to look for emails which results in
430         # the oid we want:
431         my $di;
432         foreach my $ibx (@{$self->{inboxes}}) {
433                 $di = find_extract_diff($self, $ibx, $want) or next;
434
435                 unshift @{$self->{patches}}, $di;
436                 dbg($self, "found $cur_want in ".di_url($self, $di));
437
438                 # good, we can find a path to the oid we $want, now
439                 # lets see if we need to apply more patches:
440                 my $src = $di->{oid_a};
441
442                 unless ($src =~ /\A0+\z/) {
443                         # we have to solve it using another oid, fine:
444                         my $job = { oid_b => $src, path_b => $di->{path_a} };
445                         push @{$self->{todo}}, $job;
446                 }
447                 return next_step($self); # onto the next todo item
448         }
449         dbg($self, "could not find $cur_want");
450         eval { delete($self->{user_cb})->(undef) }; # not found! :<
451         die "E: $@" if $@;
452 }
453
454 # this API is designed to avoid creating self-referential structures;
455 # so user_cb never references the SolverGit object
456 sub new {
457         my ($class, $ibx, $user_cb) = @_;
458
459         bless {
460                 gits => $ibx->{-repo_objs},
461                 user_cb => $user_cb,
462                 max_patch => 100,
463
464                 # TODO: config option for searching related inboxes
465                 inboxes => [ $ibx ],
466         }, $class;
467 }
468
469 # recreate $oid_want using $hints
470 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
471 # with found object, or undef if nothing was found
472 # Calls {user_cb} with a string error on fatal errors
473 sub solve ($$$$$) {
474         my ($self, $env, $out, $oid_want, $hints) = @_;
475
476         # should we even get here? Probably not, but somebody
477         # could be manually typing URLs:
478         return (delete $self->{user_cb})->(undef) if $oid_want =~ /\A0+\z/;
479
480         $self->{oid_want} = $oid_want;
481         $self->{out} = $out;
482         $self->{psgi_env} = $env;
483         $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
484         $self->{patches} = []; # [ $di, $di, ... ]
485         $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
486
487         dbg($self, "solving $oid_want ...");
488         my $step_cb = step_cb($self);
489         if (my $async = $env->{'pi-httpd.async'}) {
490                 # PublicInbox::HTTPD::Async->new
491                 $async->(undef, $step_cb);
492         } else {
493                 $step_cb->() while $self->{user_cb};
494         }
495 }
496
497 1;