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