]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
80bb0a178fb540f507a596246574a45416846872
[public-inbox.git] / lib / PublicInbox / SolverGit.pm
1 # Copyright (C) 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 # publicly 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 v5.10.1;
13 use File::Temp 0.19 (); # 0.19 for ->newdir
14 use Fcntl qw(SEEK_SET);
15 use PublicInbox::Git qw(git_unquote git_quote);
16 use PublicInbox::MsgIter qw(msg_part_text);
17 use PublicInbox::Qspawn;
18 use PublicInbox::Tmpfile;
19 use PublicInbox::GitAsyncCat;
20 use PublicInbox::Eml;
21 use URI::Escape qw(uri_escape_utf8);
22
23 # POSIX requires _POSIX_ARG_MAX >= 4096, and xargs is required to
24 # subtract 2048 bytes.  We also don't factor in environment variable
25 # headroom into this.
26 use POSIX qw(sysconf _SC_ARG_MAX);
27 my $ARG_SIZE_MAX = (sysconf(_SC_ARG_MAX) || 4096) - 2048;
28 my $OID_MIN = 7;
29
30 # By default, "git format-patch" generates filenames with a four-digit
31 # prefix, so that means 9999 patch series are OK, right? :>
32 # Maybe we can make this configurable, main concern is disk space overhead
33 # for uncompressed patch fragments.  Aside from space, public-inbox-httpd
34 # is otherwise unaffected by having many patches, here, as it can share
35 # work fairly.  Other PSGI servers may have trouble, though.
36 my $MAX_PATCH = 9999;
37
38 my $LF = qr!\r?\n!;
39 my $ANY = qr![^\r\n]+!;
40 my $MODE = '100644|120000|100755';
41 my $FN = qr!(?:("?[^/\n]+/[^\r\n]+)|/dev/null)!;
42 my %BAD_COMPONENT = ('' => 1, '.' => 1, '..' => 1);
43
44 # di = diff info / a hashref with information about a diff ($di):
45 # {
46 #       oid_a => abbreviated pre-image oid,
47 #       oid_b => abbreviated post-image oid,
48 #       tmp => anonymous file handle with the diff,
49 #       hdr_lines => string of various header lines for mode information
50 #       mode_a => original mode of oid_a (string, not integer),
51 #       ibx => PublicInbox::Inbox object containing the diff
52 #       smsg => PublicInbox::Smsg object containing diff
53 #       path_a => pre-image path
54 #       path_b => post-image path
55 #       n => numeric path of the patch (relative to worktree)
56 # }
57
58 sub dbg ($$) {
59         print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
60 }
61
62 sub done ($$) {
63         my ($self, $res) = @_;
64         my $ucb = delete($self->{user_cb}) or return;
65         $ucb->($res, $self->{uarg});
66 }
67
68 sub ERR ($$) {
69         my ($self, $err) = @_;
70         print { $self->{out} } $err, "\n";
71         eval { done($self, $err) };
72         die $err;
73 }
74
75 # look for existing objects already in git repos, returns arrayref
76 # if found, number of remaining git coderepos to try if not.
77 sub solve_existing ($$) {
78         my ($self, $want) = @_;
79         my $try = $want->{try_gits} //= [ @{$self->{gits}} ]; # array copy
80         my $git = shift @$try or die 'BUG {try_gits} empty';
81         my $oid_b = $want->{oid_b};
82         my ($oid_full, $type, $size) = $git->check($oid_b);
83
84         if ($oid_b eq ($oid_full // '') || (defined($type) &&
85 -                               (!$self->{have_hints} || $type eq 'blob'))) {
86                 delete $want->{try_gits};
87                 return [ $git, $oid_full, $type, int($size) ]; # done, success
88         }
89
90         # TODO: deal with 40-char "abbreviations" with future SHA-256 git
91         return scalar(@$try) if length($oid_b) >= 40;
92
93         # parse stderr of "git cat-file --batch-check"
94         my $err = $git->last_check_err;
95         my (@oids) = ($err =~ /\b([a-f0-9]{40,})\s+blob\b/g);
96         return scalar(@$try) unless scalar(@oids);
97
98         # TODO: do something with the ambiguous array?
99         # push @ambiguous, [ $git, @oids ];
100
101         dbg($self, "`$oid_b' ambiguous in " .
102                         join("\n\t", $git->pub_urls($self->{psgi_env}))
103                         . "\n" .
104                         join('', map { "$_ blob\n" } @oids));
105         scalar(@$try);
106 }
107
108 sub _tmp {
109         $_[0]->{tmp} //=
110                 File::Temp->newdir("solver.$_[0]->{oid_want}-XXXX", TMPDIR => 1);
111 }
112
113 sub extract_diff ($$) {
114         my ($p, $arg) = @_;
115         my ($self, $want, $smsg) = @$arg;
116         my ($part) = @$p; # ignore $depth and @idx;
117         my $ct = $part->content_type || 'text/plain';
118         my $post = $want->{oid_b};
119         my $pre = $want->{oid_a};
120         if (!defined($pre) || $pre !~ /\A[a-f0-9]+\z/) {
121                 $pre = '[a-f0-9]{7}'; # for RE below
122         }
123
124         # Email::MIME::Encodings forces QP to be CRLF upon decoding,
125         # change it back to LF:
126         my $cte = $part->header('Content-Transfer-Encoding') || '';
127         my ($s, undef) = msg_part_text($part, $ct);
128         defined $s or return;
129         delete $part->{bdy};
130         if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
131                 $s =~ s/\r\n/\n/sg;
132         }
133         $s =~ m!( # $1 start header lines we save for debugging:
134
135                 # everything before ^index is optional, but we don't
136                 # want to match ^(old|copy|rename|deleted|...) unless
137                 # we match /^diff --git/ first:
138                 (?: # begin optional stuff:
139
140                 # try to get the pre-and-post filenames as $2 and $3
141                 (?:^diff\x20--git\x20$FN\x20$FN$LF)
142
143                 (?:^(?: # pass all this to git-apply:
144                         # old mode $4
145                         (?:old\x20mode\x20($MODE))
146                         |
147                         # new mode (possibly new file) ($5)
148                         (?:new\x20(?:file\x20)?mode\x20($MODE))
149                         |
150                         (?:(?:copy|rename|deleted|
151                                 dissimilarity|similarity)$ANY)
152                 )$LF)*
153
154                 )? # end of optional stuff, everything below is required
155
156                 # match the pre and post-image OIDs as $6 $7
157                 ^index\x20(${pre}[a-f0-9]*)\.\.(${post}[a-f0-9]*)
158                         # mode if unchanged $8
159                         (?:\x20(100644|120000|100755))?$LF
160         ) # end of header lines ($1)
161         ( # $9 is the patch body
162                 # "--- a/foo.c" sets pre-filename ($10) in case
163                 # $2 is missing
164                 (?:^---\x20$FN$LF)
165
166                 # "+++ b/foo.c" sets post-filename ($11) in case
167                 # $3 is missing
168                 (?:^\+{3}\x20$FN$LF)
169
170                 # the meat of the diff, including "^\\No newline ..."
171                 # We also allow for totally blank lines w/o leading spaces,
172                 # because git-apply(1) handles that case, too
173                 (?:^(?:[\@\+\x20\-\\][^\n]*|)$LF)+
174         )!smx or return;
175         undef $s; # free memory
176
177         my $di = {
178                 hdr_lines => $1,
179                 oid_a => $6,
180                 oid_b => $7,
181                 mode_a => $5 // $8 // $4, # new (file) // unchanged // old
182         };
183         my $path_a = $2 // $10;
184         my $path_b = $3 // $11;
185         my $patch = $9;
186
187         # don't care for leading 'a/' and 'b/'
188         my (undef, @a) = split(m{/}, git_unquote($path_a)) if defined($path_a);
189         my (undef, @b) = split(m{/}, git_unquote($path_b));
190
191         # get rid of path-traversal attempts and junk patches:
192         # it's junk at best, an attack attempt at worse:
193         foreach (@a, @b) { return if $BAD_COMPONENT{$_} }
194
195         $di->{path_a} = join('/', @a) if @a;
196         $di->{path_b} = join('/', @b);
197
198         my $path = ++$self->{tot};
199         $di->{n} = $path;
200         my $f = _tmp($self)->dirname."/$path";
201         open(my $tmp, '>:utf8', $f) or die "open($f): $!";
202         print $tmp $di->{hdr_lines}, $patch or die "print(tmp): $!";
203         close $tmp or die "close(tmp): $!";
204
205         # for debugging/diagnostics:
206         $di->{ibx} = $want->{cur_ibx};
207         $di->{smsg} = $smsg;
208
209         push @{$self->{tmp_diffs}}, $di;
210 }
211
212 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
213
214 # ".." appears in path names, which confuses Xapian into treating
215 # it as a range query.  So we split on ".." since Xapian breaks
216 # on punctuation anyways:
217 sub filename_query ($) {
218         join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
219 }
220
221 sub find_smsgs ($$$) {
222         my ($self, $ibx, $want) = @_;
223         my $srch = $ibx->isrch or return;
224
225         my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
226         $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
227
228         my $q = "dfpost:$post";
229         my $pre = $want->{oid_a};
230         if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
231                 $q .= " dfpre:$pre";
232         }
233
234         my $path_b = $want->{path_b};
235         if (path_searchable($path_b)) {
236                 $q .= filename_query($path_b);
237
238                 my $path_a = $want->{path_a};
239                 if (path_searchable($path_a) && $path_a ne $path_b) {
240                         $q .= filename_query($path_a);
241                 }
242         }
243         my $mset = $srch->mset($q, { relevance => 1 });
244         $mset->size ? $srch->mset_to_smsg($ibx, $mset) : undef;
245 }
246
247 sub update_index_result ($$) {
248         my ($bref, $self) = @_;
249         my ($qsp_err, $msg) = delete @$self{qw(-qsp_err -msg)};
250         ERR($self, "git update-index error:$qsp_err") if $qsp_err;
251         dbg($self, $msg);
252         next_step($self); # onto do_git_apply
253 }
254
255 sub prepare_index ($) {
256         my ($self) = @_;
257         my $patches = $self->{patches};
258         $self->{nr} = 0;
259
260         my $di = $patches->[0] or die 'no patches';
261         my $oid_a = $di->{oid_a} or die '{oid_a} unset';
262         my $existing = $self->{found}->{$oid_a};
263
264         # no index creation for added files
265         $oid_a =~ /\A0+\z/ and return next_step($self);
266
267         die "BUG: $oid_a not found" unless $existing;
268
269         my $oid_full = $existing->[1];
270         my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
271         my $mode_a = $di->{mode_a} // '100644';
272
273         my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
274         print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
275         $in->flush or die "flush: $!";
276         sysseek($in, 0, SEEK_SET) or die "seek: $!";
277
278         dbg($self, 'preparing index');
279         my $rdr = { 0 => $in };
280         my $cmd = [ qw(git update-index -z --index-info) ];
281         my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
282         $path_a = git_quote($path_a);
283         $qsp->{qsp_err} = \($self->{-qsp_err} = '');
284         $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
285         $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
286 }
287
288 # pure Perl "git init"
289 sub do_git_init ($) {
290         my ($self) = @_;
291         my $git_dir = _tmp($self)->dirname.'/git';
292
293         foreach ('', qw(objects refs objects/info refs/heads)) {
294                 mkdir("$git_dir/$_") or die "mkdir $_: $!";
295         }
296         open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
297         my $first = $self->{gits}->[0];
298         my $fmt = $first->object_format;
299         my $v = defined($$fmt) ? 1 : 0;
300         print $fh <<EOF or die "print git/config $!";
301 [core]
302         repositoryFormatVersion = $v
303         filemode = true
304         bare = false
305         logAllRefUpdates = false
306 EOF
307         print $fh <<EOM if defined($$fmt);
308 [extensions]
309         objectformat = $$fmt
310 EOM
311         close $fh or die "close git/config: $!";
312
313         open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
314         print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
315         close $fh or die "close git/HEAD: $!";
316
317         my $f = 'objects/info/alternates';
318         open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
319         foreach my $git (@{$self->{gits}}) {
320                 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
321         }
322         close $fh or die "close: $f: $!";
323         my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
324         $tmp_git->{-tmp} = $self->{tmp};
325         $self->{git_env} = {
326                 GIT_DIR => $git_dir,
327                 GIT_INDEX_FILE => "$git_dir/index",
328                 GIT_TEST_FSYNC => 0, # undocumented git env
329         };
330         prepare_index($self);
331 }
332
333 sub do_finish ($) {
334         my ($self) = @_;
335         my ($found, $oid_want) = @$self{qw(found oid_want)};
336         if (my $exists = $found->{$oid_want}) {
337                 return done($self, $exists);
338         }
339
340         # let git disambiguate if oid_want was too short,
341         # but long enough to be unambiguous:
342         my $tmp_git = $self->{tmp_git};
343         if (my @res = $tmp_git->check($oid_want)) {
344                 return done($self, $found->{$res[0]});
345         }
346         if (my $err = $tmp_git->last_check_err) {
347                 dbg($self, $err);
348         }
349         done($self, undef);
350 }
351
352 sub event_step ($) {
353         my ($self) = @_;
354         eval {
355                 # step 1: resolve blobs to patches in the todo queue
356                 if (my $want = pop @{$self->{todo}}) {
357                         # this populates {patches} and {todo}
358                         resolve_patch($self, $want);
359
360                 # step 2: then we instantiate a working tree once
361                 # the todo queue is finally empty:
362                 } elsif (!defined($self->{tmp_git})) {
363                         do_git_init($self);
364
365                 # step 3: apply each patch in the stack
366                 } elsif (scalar @{$self->{patches}}) {
367                         do_git_apply($self);
368
369                 # step 4: execute the user-supplied callback with
370                 # our result: (which may be undef)
371                 # Other steps may call user_cb to terminate prematurely
372                 # on error
373                 } elsif (exists $self->{user_cb}) {
374                         do_finish($self);
375                 } else {
376                         die 'about to call user_cb twice'; # Oops :x
377                 }
378         }; # eval
379         my $err = $@;
380         if ($err) {
381                 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
382                 dbg($self, "E: $err");
383                 eval { done($self, $err) };
384         }
385 }
386
387 sub next_step ($) {
388         my ($self) = @_;
389         # if outside of public-inbox-httpd, caller is expected to be
390         # looping event_step, anyways
391         my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
392         # PublicInbox::HTTPD::Async->new
393         $async->(undef, undef, $self);
394 }
395
396 sub mark_found ($$$) {
397         my ($self, $oid, $found_info) = @_;
398         my $found = $self->{found};
399         $found->{$oid} = $found_info;
400         my $oid_cur = $found_info->[1];
401         while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
402                 $found->{$oid_cur} = $found_info;
403                 chop($oid_cur);
404         }
405 }
406
407 sub parse_ls_files ($$) {
408         my ($self, $bref) = @_;
409         my ($qsp_err, $di) = delete @$self{qw(-qsp_err -cur_di)};
410         die "git ls-files -s -z error:$qsp_err" if $qsp_err;
411
412         my @ls = split(/\0/, $$bref);
413         my ($line, @extra) = grep(/\t\Q$di->{path_b}\E\z/, @ls);
414         scalar(@extra) and die "BUG: extra files in index: <",
415                                 join('> <', $line, @extra), ">";
416         $line // die "no \Q$di->{path_b}\E in <",join('> <', @ls), '>';
417         my ($info, $file) = split(/\t/, $line, 2);
418         my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
419         $file eq $di->{path_b} or die
420 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
421
422         my $tmp_git = $self->{tmp_git} or die 'no git working tree';
423         my (undef, undef, $size) = $tmp_git->check($oid_b_full);
424         defined($size) or die "check $oid_b_full failed";
425
426         dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
427         my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
428         mark_found($self, $di->{oid_b}, $created);
429         next_step($self); # onto the next patch
430 }
431
432 sub ls_files_result {
433         my ($bref, $self) = @_;
434         eval { parse_ls_files($self, $bref) };
435         ERR($self, $@) if $@;
436 }
437
438 sub oids_same_ish ($$) {
439         (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
440 }
441
442 sub skip_identical ($$$) {
443         my ($self, $patches, $cur_oid_b) = @_;
444         while (my $nxt = $patches->[0]) {
445                 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
446                         dbg($self, 'skipping '.di_url($self, $nxt).
447                                 " for $cur_oid_b");
448                         shift @$patches;
449                 } else {
450                         return;
451                 }
452         }
453 }
454
455 sub apply_result ($$) {
456         my ($bref, $self) = @_;
457         my ($qsp_err, $di) = delete @$self{qw(-qsp_err -cur_di)};
458         dbg($self, $$bref);
459         my $patches = $self->{patches};
460         if ($qsp_err) {
461                 my $msg = "git apply error:$qsp_err";
462                 my $nxt = $patches->[0];
463                 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
464                         dbg($self, $msg);
465                         dbg($self, 'trying '.di_url($self, $nxt));
466                         return do_git_apply($self);
467                 } else {
468                         ERR($self, $msg);
469                 }
470         } else {
471                 skip_identical($self, $patches, $di->{oid_b});
472         }
473
474         my @cmd = qw(git ls-files -s -z);
475         my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
476         $self->{-cur_di} = $di;
477         $qsp->{qsp_err} = \($self->{-qsp_err} = '');
478         $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
479 }
480
481 sub do_git_apply ($) {
482         my ($self) = @_;
483         my $patches = $self->{patches};
484
485         # we need --ignore-whitespace because some patches are CRLF
486         my @cmd = (qw(git apply --cached --ignore-whitespace
487                         --unidiff-zero --whitespace=warn --verbose));
488         my $len = length(join(' ', @cmd));
489         my $di; # keep track of the last one for "git ls-files"
490         my $prv_oid_b;
491
492         do {
493                 my $i = ++$self->{nr};
494                 $di = shift @$patches;
495                 dbg($self, "\napplying [$i/$self->{nr_p}] " .
496                         di_url($self, $di) . "\n" . $di->{hdr_lines});
497                 my $path = $di->{n};
498                 $len += length($path) + 1;
499                 push @cmd, $path;
500                 $prv_oid_b = $di->{oid_b};
501         } while (@$patches && $len < $ARG_SIZE_MAX &&
502                  !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
503
504         my $opt = { 2 => 1, -C => _tmp($self)->dirname, quiet => 1 };
505         my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
506         $self->{-cur_di} = $di;
507         $qsp->{qsp_err} = \($self->{-qsp_err} = '');
508         $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
509 }
510
511 sub di_url ($$) {
512         my ($self, $di) = @_;
513         # note: we don't pass the PSGI env unconditionally, here,
514         # different inboxes can have different HTTP_HOST on the same instance.
515         my $ibx = $di->{ibx};
516         my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
517         my $url = $ibx->base_url($env);
518         my $mid = $di->{smsg}->{mid};
519         defined($url) ? "$url$mid/" : "<$mid>";
520 }
521
522 sub retry_current {
523         my ($self, $want) = @_;
524         push @{$self->{todo}}, $want;
525         next_step($self); # retry solve_existing
526 }
527
528 sub try_harder ($$) {
529         my ($self, $want) = @_;
530
531         # do we have more inboxes to try?
532         return retry_current($self, $want) if scalar @{$want->{try_ibxs}};
533
534         my $cur_want = $want->{oid_b};
535         if (length($cur_want) > $OID_MIN) { # maybe a shorter OID will work
536                 delete $want->{try_ibxs}; # drop empty arrayref
537                 chop($cur_want);
538                 dbg($self, "retrying $want->{oid_b} as $cur_want");
539                 $want->{oid_b} = $cur_want;
540                 return retry_current($self, $want); # retry with shorter abbrev
541         }
542
543         dbg($self, "could not find $cur_want");
544         eval { done($self, undef) };
545         die "E: $@" if $@;
546 }
547
548 sub extract_diffs_done {
549         my ($self, $want) = @_;
550
551         delete $want->{try_smsgs};
552         delete $want->{cur_ibx};
553
554         my $diffs = delete $self->{tmp_diffs};
555         if (scalar @$diffs) {
556                 unshift @{$self->{patches}}, @$diffs;
557                 my %seen; # List::Util::uniq requires Perl 5.26+ :<
558                 my @u = grep { !$seen{$_}++ } map { di_url($self, $_) } @$diffs;
559                 dbg($self, "found $want->{oid_b} in " .  join(" ||\n\t", @u));
560                 ++$self->{nr_p};
561
562                 # good, we can find a path to the oid we $want, now
563                 # lets see if we need to apply more patches:
564                 my $di = $diffs->[0];
565                 my $src = $di->{oid_a};
566
567                 unless ($src =~ /\A0+\z/) {
568                         # we have to solve it using another oid, fine:
569                         my $job = { oid_b => $src, path_b => $di->{path_a} };
570                         push @{$self->{todo}}, $job;
571                 }
572                 return next_step($self); # onto the next todo item
573         }
574         try_harder($self, $want);
575 }
576
577 sub extract_diff_async {
578         my ($bref, $oid, $type, $size, $x) = @_;
579         my ($self, $want, $smsg) = @$x;
580         if (defined($oid)) {
581                 $smsg->{blob} eq $oid or
582                                 ERR($self, "BUG: $smsg->{blob} != $oid");
583                 PublicInbox::Eml->new($bref)->each_part(\&extract_diff, $x, 1);
584         }
585
586         scalar(@{$want->{try_smsgs}}) ? retry_current($self, $want)
587                                         : extract_diffs_done($self, $want);
588 }
589
590 sub resolve_patch ($$) {
591         my ($self, $want) = @_;
592
593         my $cur_want = $want->{oid_b};
594         if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
595                 die "Aborting, too many steps to $self->{oid_want}";
596         }
597
598         if (my $msgs = $want->{try_smsgs}) {
599                 my $smsg = shift @$msgs;
600                 if ($self->{psgi_env}->{'pi-httpd.async'}) {
601                         return ibx_async_cat($want->{cur_ibx}, $smsg->{blob},
602                                                 \&extract_diff_async,
603                                                 [$self, $want, $smsg]);
604                 } else {
605                         if (my $eml = $want->{cur_ibx}->smsg_eml($smsg)) {
606                                 $eml->each_part(\&extract_diff,
607                                                 [ $self, $want, $smsg ], 1);
608                         }
609                 }
610
611                 return scalar(@$msgs) ? retry_current($self, $want)
612                                         : extract_diffs_done($self, $want);
613         }
614
615         # see if we can find the blob in an existing git repo:
616         if (!$want->{try_ibxs} && $self->{seen_oid}->{$cur_want}++) {
617                 die "Loop detected solving $cur_want\n";
618         }
619         $want->{try_ibxs} //= [ @{$self->{inboxes}} ]; # array copy
620         my $existing = solve_existing($self, $want);
621         if (ref $existing) {
622                 my ($found_git, undef, $type, undef) = @$existing;
623                 dbg($self, "found $cur_want in " .
624                         join(" ||\n\t",
625                                 $found_git->pub_urls($self->{psgi_env})));
626
627                 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
628                         eval { done($self, $existing) };
629                         die "E: $@" if $@;
630                         return;
631                 }
632                 mark_found($self, $cur_want, $existing);
633                 return next_step($self); # onto patch application
634         } elsif ($existing > 0) {
635                 return retry_current($self, $want);
636         } else { # $existing == 0: we may retry if inbox scan (below) fails
637                 delete $want->{try_gits};
638         }
639
640         # scan through inboxes to look for emails which results in
641         # the oid we want:
642         my $ibx = shift(@{$want->{try_ibxs}}) or return done($self, undef);
643         if (my $msgs = find_smsgs($self, $ibx, $want)) {
644                 $want->{try_smsgs} = $msgs;
645                 $want->{cur_ibx} = $ibx;
646                 $self->{tmp_diffs} = [];
647                 return retry_current($self, $want);
648         }
649         try_harder($self, $want);
650 }
651
652 # this API is designed to avoid creating self-referential structures;
653 # so user_cb never references the SolverGit object
654 sub new {
655         my ($class, $ibx, $user_cb, $uarg) = @_;
656
657         bless { # $ibx is undef if coderepo only (see WwwCoderepo)
658                 gits => $ibx ? $ibx->{-repo_objs} : undef,
659                 user_cb => $user_cb,
660                 uarg => $uarg,
661                 # -cur_di, -qsp_err, -msg => temp fields for Qspawn callbacks
662
663                 # TODO: config option for searching related inboxes
664                 inboxes => $ibx ? [ $ibx ] : [],
665         }, $class;
666 }
667
668 # recreate $oid_want using $hints
669 # hints keys: path_a, path_b, oid_a (note: `oid_b' is NOT a hint)
670 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
671 # with found object, or undef if nothing was found
672 # Calls {user_cb} with a string error on fatal errors
673 sub solve ($$$$$) {
674         my ($self, $env, $out, $oid_want, $hints) = @_;
675
676         # should we even get here? Probably not, but somebody
677         # could be manually typing URLs:
678         return done($self, undef) if $oid_want =~ /\A0+\z/;
679
680         $self->{oid_want} = $oid_want;
681         $self->{out} = $out;
682         $self->{seen_oid} = {};
683         $self->{tot} = $self->{nr_p} = 0;
684         $self->{psgi_env} = $env;
685         $self->{have_hints} = 1 if scalar keys %$hints;
686         $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
687         $self->{patches} = []; # [ $di, $di, ... ]
688         $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
689
690         dbg($self, "solving $oid_want ...");
691         if (my $async = $env->{'pi-httpd.async'}) {
692                 # PublicInbox::HTTPD::Async->new
693                 $async->(undef, undef, $self);
694         } else {
695                 event_step($self) while $self->{user_cb};
696         }
697 }
698
699 1;