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