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