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