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