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