]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
solver: restore diagnostics and deal with CRLF
[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 URI::Escape qw(uri_escape_utf8);
19
20 # don't bother if somebody sends us a patch with these path components,
21 # it's junk at best, an attack attempt at worse:
22 my %bad_component = map { $_ => 1 } ('', '.', '..');
23
24 sub new {
25         my ($class, $gits, $inboxes) = @_;
26         bless {
27                 gits => $gits,
28                 inboxes => $inboxes,
29         }, $class;
30 }
31
32 # look for existing blobs already in git repos
33 sub solve_existing ($$$) {
34         my ($self, $out, $want) = @_;
35         my $oid_b = $want->{oid_b};
36         my @ambiguous; # Array of [ git, $oids]
37         foreach my $git (@{$self->{gits}}) {
38                 my ($oid_full, $type, $size) = $git->check($oid_b);
39                 if (defined($type) && $type eq 'blob') {
40                         return [ $git, $oid_full, $type, int($size) ];
41                 }
42
43                 next if length($oid_b) == 40;
44
45                 # parse stderr of "git cat-file --batch-check"
46                 my $err = $git->last_check_err;
47                 my (@oids) = ($err =~ /\b([a-f0-9]{40})\s+blob\b/g);
48                 next unless scalar(@oids);
49
50                 # TODO: do something with the ambiguous array?
51                 # push @ambiguous, [ $git, @oids ];
52
53                 print $out "`$oid_b' ambiguous in ",
54                                 join("\n", $git->pub_urls), "\n",
55                                 join('', map { "$_ blob\n" } @oids), "\n";
56         }
57         scalar(@ambiguous) ? \@ambiguous : undef;
58 }
59
60 # returns a hashref with information about a diff ($di):
61 # {
62 #       oid_a => abbreviated pre-image oid,
63 #       oid_b => abbreviated post-image oid,
64 #       tmp => anonymous file handle with the diff,
65 #       hdr_lines => arrayref of various header lines for mode information
66 #       mode_a => original mode of oid_a (string, not integer),
67 #       ibx => PublicInbox::Inbox object containing the diff
68 #       smsg => PublicInbox::SearchMsg object containing diff
69 #       path_a => pre-image path
70 #       path_b => post-image path
71 # }
72 sub extract_diff ($$$$) {
73         my ($p, $re, $ibx, $smsg) = @_;
74         my ($part) = @$p; # ignore $depth and @idx;
75         my $hdr_lines; # diff --git a/... b/...
76         my $tmp;
77         my $ct = $part->content_type || 'text/plain';
78         my ($s, undef) = msg_part_text($part, $ct);
79         defined $s or return;
80         my $di = {};
81         foreach my $l (split(/^/m, $s)) {
82                 if ($l =~ $re) {
83                         $di->{oid_a} = $1;
84                         $di->{oid_b} = $2;
85                         if (defined($3)) {
86                                 my $mode_a = $3;
87                                 if ($mode_a =~ /\A(?:100644|120000|100755)\z/) {
88                                         $di->{mode_a} = $mode_a;
89                                 }
90                         }
91
92                         # start writing the diff out to a tempfile
93                         open($tmp, '+>', undef) or die "open(tmp): $!";
94                         $di->{tmp} = $tmp;
95
96                         push @$hdr_lines, $l;
97                         $di->{hdr_lines} = $hdr_lines;
98                         print $tmp @$hdr_lines, $l or die "print(tmp): $!";
99
100                         # for debugging/diagnostics:
101                         $di->{ibx} = $ibx;
102                         $di->{smsg} = $smsg;
103                 } elsif ($l =~ m!\Adiff --git ("?a/.+) ("?b/.+)$!) {
104                         return $di if $tmp; # got our blob, done!
105
106                         my ($path_a, $path_b) = ($1, $2);
107
108                         # diff header lines won't have \r because git
109                         # will quote them, but Email::MIME gives CRLF
110                         # for quoted-printable:
111                         $path_b =~ tr/\r//d;
112
113                         # don't care for leading 'a/' and 'b/'
114                         my (undef, @a) = split(m{/}, git_unquote($path_a));
115                         my (undef, @b) = split(m{/}, git_unquote($path_b));
116
117                         # get rid of path-traversal attempts and junk patches:
118                         foreach (@a, @b) {
119                                 return if $bad_component{$_};
120                         }
121
122                         $di->{path_a} = join('/', @a);
123                         $di->{path_b} = join('/', @b);
124                         $hdr_lines = [ $l ];
125                 } elsif ($tmp) {
126                         print $tmp $l or die "print(tmp): $!";
127                 } elsif ($hdr_lines) {
128                         push @$hdr_lines, $l;
129                         if ($l =~ /\Anew file mode (100644|120000|100755)$/) {
130                                 $di->{mode_a} = $1;
131                         }
132                 }
133         }
134         $tmp ? $di : undef;
135 }
136
137 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
138
139 sub find_extract_diff ($$$) {
140         my ($self, $ibx, $want) = @_;
141         my $srch = $ibx->search or return;
142
143         my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
144         $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
145
146         my $q = "dfpost:$post";
147         my $pre = $want->{oid_a};
148         if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
149                 $q .= " dfpre:$pre";
150         } else {
151                 $pre = '[a-f0-9]{7}'; # for $re below
152         }
153
154         my $path_b = $want->{path_b};
155         if (path_searchable($path_b)) {
156                 $q .= qq{ dfn:"$path_b"};
157
158                 my $path_a = $want->{path_a};
159                 if (path_searchable($path_a) && $path_a ne $path_b) {
160                         $q .= qq{ dfn:"$path_a"};
161                 }
162         }
163
164         my $msgs = $srch->query($q, { relevance => 1 });
165         my $re = qr/\Aindex ($pre[a-f0-9]*)\.\.($post[a-f0-9]*)(?: (\d+))?/;
166
167         my $di;
168         foreach my $smsg (@$msgs) {
169                 $ibx->smsg_mime($smsg) or next;
170                 msg_iter(delete($smsg->{mime}), sub {
171                         $di ||= extract_diff($_[0], $re, $ibx, $smsg);
172                 });
173                 return $di if $di;
174         }
175 }
176
177 # pure Perl "git init"
178 sub do_git_init_wt ($) {
179         my ($self) = @_;
180         my $wt = File::Temp->newdir('solver.wt-XXXXXXXX', TMPDIR => 1);
181         my $dir = $wt->dirname;
182
183         foreach ('', qw(objects refs objects/info refs/heads)) {
184                 mkdir("$dir/.git/$_") or die "mkdir $_: $!";
185         }
186         open my $fh, '>', "$dir/.git/config" or die "open .git/config: $!";
187         print $fh <<'EOF' or die "print .git/config $!";
188 [core]
189         repositoryFormatVersion = 0
190         filemode = true
191         bare = false
192         fsyncObjectfiles = false
193         logAllRefUpdates = false
194 EOF
195         close $fh or die "close .git/config: $!";
196
197         open $fh, '>', "$dir/.git/HEAD" or die "open .git/HEAD: $!";
198         print $fh "ref: refs/heads/master\n" or die "print .git/HEAD: $!";
199         close $fh or die "close .git/HEAD: $!";
200
201         my $f = '.git/objects/info/alternates';
202         open $fh, '>', "$dir/$f" or die "open: $f: $!";
203         print($fh (map { "$_->{git_dir}/objects\n" } @{$self->{gits}})) or
204                 die "print $f: $!";
205         close $fh or die "close: $f: $!";
206         $wt;
207 }
208
209 sub extract_old_mode ($) {
210         my ($di) = @_;
211         if (grep(/\Aold mode (100644|100755|120000)$/, @{$di->{hdr_lines}})) {
212                 return $1;
213         }
214         '100644';
215 }
216
217 sub reap ($$) {
218         my ($pid, $msg) = @_;
219         waitpid($pid, 0) == $pid or die "waitpid($msg): $!";
220         $? == 0 or die "$msg failed: $?";
221 }
222
223 sub prepare_index ($$$$) {
224         my ($out, $wt_dir, $existing, $di) = @_;
225         my $oid_full = $existing->[1];
226         my ($r, $w);
227         my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
228         my $mode_a = $di->{mode_a} || extract_old_mode($di);
229
230         # unlike git-apply(1), this only gets called once in a patch
231         # series and happens too quickly to be worth making async:
232         pipe($r, $w) or die "pipe: $!";
233         my $rdr = { 0 => fileno($r) };
234         my $pid = spawn([qw(git -C), $wt_dir,
235                          qw(update-index -z --index-info)], undef, $rdr);
236         close $r or die "close pipe(r): $!";
237         print $w "$mode_a $oid_full\t$path_a\0" or die "print update-index: $!";
238
239         close $w or die "close update-index: $!";
240         reap($pid, 'update-index -z --index-info');
241
242         print $out "index prepared:\n",
243                 "$mode_a $oid_full\t", git_quote($path_a), "\n";
244 }
245
246 sub do_apply_begin ($$$) {
247         my ($out, $wt_dir, $di) = @_;
248
249         my $tmp = delete $di->{tmp} or die "BUG: no tmp ", di_url($di);
250         $tmp->flush or die "tmp->flush failed: $!";
251         $out->flush or die "err->flush failed: $!";
252         sysseek($tmp, 0, SEEK_SET) or die "sysseek(tmp) failed: $!";
253
254         defined(my $err_fd = fileno($out)) or die "fileno(out): $!";
255         my $rdr = { 0 => fileno($tmp), 1 => $err_fd, 2 => $err_fd };
256
257         # we need --ignore-whitespace because some patches are CRLF
258         my $cmd = [ qw(git -C), $wt_dir,
259                     qw(apply --cached --ignore-whitespace
260                        --whitespace=warn --verbose) ];
261         spawn($cmd, undef, $rdr);
262 }
263
264 sub do_apply_continue ($$) {
265         my ($wt_dir, $apply_pid) = @_;
266         reap($apply_pid, 'apply');
267         popen_rd([qw(git -C), $wt_dir, qw(ls-files -s -z)]);
268 }
269
270 sub do_apply_end ($$$$) {
271         my ($out, $wt_git, $rd, $di) = @_;
272
273         local $/ = "\0";
274         defined(my $line = <$rd>) or die "failed to read ls-files: $!";
275         chomp $line or die "no trailing \\0 in [$line] from ls-files";
276
277         my ($info, $file) = split(/\t/, $line, 2);
278         my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
279
280         defined($line = <$rd>) and die "extra files in index: $line";
281         close $rd or die "close ls-files: $?";
282
283         $file eq $di->{path_b} or
284                 die "index mismatch: file=$file != path_b=$di->{path_b}";
285
286         my (undef, undef, $size) = $wt_git->check($oid_b_full);
287
288         defined($size) or die "failed to read_size from $oid_b_full";
289
290         print $out "$mode_b $oid_b_full\t$file\n";
291         [ $wt_git, $oid_b_full, 'blob', $size, $di ];
292 }
293
294 sub di_url ($) {
295         my ($di) = @_;
296         # note: we don't pass the PSGI env here, different inboxes
297         # can have different HTTP_HOST on the same instance.
298         my $url = $di->{ibx}->base_url;
299         my $mid = $di->{smsg}->{mid};
300         defined($url) ? "$url$mid/" : "<$mid>";
301 }
302
303 # reconstruct the oid_b blob using patches we found:
304 sub apply_patches_cb ($$$$$) {
305         my ($self, $out, $found, $patches, $oid_b) = @_;
306
307         my $tot = scalar(@$patches) or return sub {
308                 print $out "no patch(es) for $oid_b\n";
309                 undef;
310         };
311
312         my $wt = do_git_init_wt($self);
313         my $wt_dir = $wt->dirname;
314         my $wt_git = PublicInbox::Git->new("$wt_dir/.git");
315         $wt_git->{-wt} = $wt;
316
317         my $cur = 0;
318         my ($apply_pid, $rd, $di);
319
320         # returns an empty string if in progress, undef if not found,
321         # or the final [ ::Git, oid_full, type, size, $di ] arrayref
322         # if found
323         sub {
324                 if ($rd) {
325                         $found->{$di->{oid_b}} =
326                                         do_apply_end($out, $wt_git, $rd, $di);
327                         $rd = undef;
328                         # continue to shift @$patches
329                 } elsif ($apply_pid) {
330                         $rd = do_apply_continue($wt_dir, $apply_pid);
331                         $apply_pid = undef;
332                         return ''; # $rd => do_apply_ned
333                 }
334
335                 # may return undef here
336                 $di = shift @$patches or return $found->{$oid_b};
337
338                 my $i = ++$cur;
339                 my $oid_a = $di->{oid_a};
340                 my $existing = $found->{$oid_a};
341                 my $empty_oid = $oid_a =~ /\A0+\z/;
342
343                 if ($empty_oid && $i != 1) {
344                         die "empty oid at [$i/$tot] ", di_url($di);
345                 }
346                 if (!$existing && !$empty_oid) {
347                         die "missing $oid_a at [$i/$tot] ", di_url($di);
348                 }
349
350                 # prepare the worktree for patch application:
351                 if ($i == 1 && $existing) {
352                         prepare_index($out, $wt_dir, $existing, $di);
353                 }
354
355                 print $out "\napplying [$i/$tot] ", di_url($di), "\n",
356                            join('', @{$di->{hdr_lines}}), "\n"
357                         or die "print \$out failed: $!";
358
359                 # begin the patch application patch!
360                 $apply_pid = do_apply_begin($out, $wt_dir, $di);
361                 # next call to this callback will call do_apply_continue
362                 '';
363         }
364 }
365
366 # recreate $oid_b
367 # Returns an array ref: [ ::Git object, oid_full, type, size, di ]
368 # or undef if nothing was found.
369 #
370 # TODO: complete the migration of this and ViewVCS into an evented
371 # model for fairness
372 sub solve ($$$$) {
373         my ($self, $out, $oid_b, $hints) = @_;
374
375         # should we even get here? Probably not, but somebody
376         # could be manually typing URLs:
377         return if $oid_b =~ /\A0+\z/;
378
379         my $req = { %$hints, oid_b => $oid_b };
380         my @todo = ($req);
381         my $found = {}; # { abbrev => [ ::Git, oid_full, type, size, $di ] }
382         my $patches = []; # [ array of $di hashes ]
383         my $max = $self->{max_patches} || 200;
384         my $apply_cb;
385         my $cb = sub {
386                 my $want = pop @todo;
387                 unless ($want) {
388                         $apply_cb ||= apply_patches_cb($self, $out, $found,
389                                                        $patches, $oid_b);
390                         return $apply_cb->();
391                 }
392
393                 if (scalar(@$patches) > $max) {
394                         print $out "Aborting, too many steps to $oid_b\n";
395                         return;
396                 }
397                 # see if we can find the blob in an existing git repo:
398                 my $want_oid = $want->{oid_b};
399                 if (my $existing = solve_existing($self, $out, $want)) {
400                         print $out "found $want_oid in ",
401                                 join("\n", $existing->[0]->pub_urls), "\n";
402
403                         return $existing if $want_oid eq $oid_b; # DONE!
404                         $found->{$want_oid} = $existing;
405                         return ''; # ok, one blob resolved, more to go?
406                 }
407
408                 # scan through inboxes to look for emails which results in
409                 # the oid we want:
410                 my $di;
411                 foreach my $ibx (@{$self->{inboxes}}) {
412                         $di = find_extract_diff($self, $ibx, $want) or next;
413
414                         unshift @$patches, $di;
415                         print $out "found $want_oid in ",di_url($di),"\n";
416
417                         # good, we can find a path to the oid we $want, now
418                         # lets see if we need to apply more patches:
419                         my $src = $di->{oid_a};
420
421                         last if $src =~ /\A0+\z/;
422
423                         # we have to solve it using another oid, fine:
424                         my $job = { oid_b => $src, path_b => $di->{path_a} };
425                         push @todo, $job;
426                         last; # onto the next @todo item
427                 }
428                 unless ($di) {
429                         print $out "$want_oid could not be found\n";
430                         return;
431                 }
432                 ''; # continue onto next @todo item;
433         };
434
435         while (1) {
436                 my $ret = eval { $cb->() };
437                 unless (defined($ret)) {
438                         print $out "E: $@\n" if $@;
439                         return;
440                 }
441                 return $ret if ref($ret);
442                 # $ret == ''; so continue looping here
443         }
444 }
445
446 1;