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