]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
Merge remote-tracking branch 'origin/master' into lorelei
[public-inbox.git] / lib / PublicInbox / Git.pm
1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: GPLv2 or later <https://www.gnu.org/licenses/gpl-2.0.txt>
3 #
4 # Used to read files from a git repository without excessive forking.
5 # Used in our web interfaces as well as our -nntpd server.
6 # This is based on code in Git.pm which is GPLv2+, but modified to avoid
7 # dependence on environment variables for compatibility with mod_perl.
8 # There are also API changes to simplify our usage and data set.
9 package PublicInbox::Git;
10 use strict;
11 use v5.10.1;
12 use parent qw(Exporter);
13 use POSIX ();
14 use IO::Handle; # ->autoflush
15 use Errno qw(EINTR EAGAIN);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
17 use File::Spec ();
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
22 use Carp qw(croak);
23 use Digest::SHA ();
24 our @EXPORT_OK = qw(git_unquote git_quote);
25 our $PIPE_BUFSIZ = 65536; # Linux default
26 our $in_cleanup;
27 our $RDTIMEO = 60_000; # milliseconds
28
29 use constant MAX_INFLIGHT =>
30         (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
31         /
32         65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
33
34 my %GIT_ESC = (
35         a => "\a",
36         b => "\b",
37         f => "\f",
38         n => "\n",
39         r => "\r",
40         t => "\t",
41         v => "\013",
42         '"' => '"',
43         '\\' => '\\',
44 );
45 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
46
47
48 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
49 sub git_unquote ($) {
50         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
51         $_[0] = $1;
52         $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
53         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
54         $_[0];
55 }
56
57 sub git_quote ($) {
58         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
59                       '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
60                 return qq{"$_[0]"};
61         }
62         $_[0];
63 }
64
65 sub new {
66         my ($class, $git_dir) = @_;
67         # may contain {-tmp} field for File::Temp::Dir
68         bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
69 }
70
71 sub git_path ($$) {
72         my ($self, $path) = @_;
73         $self->{-git_path}->{$path} ||= do {
74                 local $/ = "\n";
75                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
76
77                 # git prior to 2.5.0 did not understand --git-path
78                 if ($str eq "--git-path\n$path") {
79                         $str = "$self->{git_dir}/$path";
80                 }
81                 $str;
82         };
83 }
84
85 sub alternates_changed {
86         my ($self) = @_;
87         my $alt = git_path($self, 'objects/info/alternates');
88         my @st = stat($alt) or return 0;
89
90         # can't rely on 'q' on some 32-bit builds, but `d' works
91         my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
92         return 0 if $self->{alt_st} eq $st;
93         $self->{alt_st} = $st; # always a true value
94 }
95
96 sub last_check_err {
97         my ($self) = @_;
98         my $fh = $self->{err_c} or return;
99         sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
100         defined(sysread($fh, my $buf, -s $fh)) or
101                         $self->fail("sysread failed: $!");
102         $buf;
103 }
104
105 sub _bidi_pipe {
106         my ($self, $batch, $in, $out, $pid, $err) = @_;
107         if ($self->{$pid}) {
108                 if (defined $err) { # "err_c"
109                         my $fh = $self->{$err};
110                         sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
111                         truncate($fh, 0) or $self->fail("truncate failed: $!");
112                 }
113                 return;
114         }
115         my ($out_r, $out_w);
116         pipe($out_r, $out_w) or $self->fail("pipe failed: $!");
117         my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
118                         qw(-c core.abbrev=40 cat-file), $batch);
119         my $redir = { 0 => $out_r };
120         if ($err) {
121                 my $id = "git.$self->{git_dir}$batch.err";
122                 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
123                 $self->{$err} = $fh;
124                 $redir->{2} = $fh;
125         }
126         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
127         $self->{$pid} = $p;
128         $out_w->autoflush(1);
129         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
130                 fcntl($out_w, 1031, 4096);
131                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
132         }
133         $self->{$out} = $out_w;
134         $self->{$in} = $in_r;
135 }
136
137 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
138
139 sub my_read ($$$) {
140         my ($fh, $rbuf, $len) = @_;
141         my $left = $len - length($$rbuf);
142         my $r;
143         while ($left > 0) {
144                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
145                 if ($r) {
146                         $left -= $r;
147                 } elsif (defined($r)) { # EOF
148                         return 0;
149                 } else {
150                         next if ($! == EAGAIN and poll_in($fh));
151                         next if $! == EINTR; # may be set by sysread or poll_in
152                         return; # unrecoverable error
153                 }
154         }
155         \substr($$rbuf, 0, $len, '');
156 }
157
158 sub my_readline ($$) {
159         my ($fh, $rbuf) = @_;
160         while (1) {
161                 if ((my $n = index($$rbuf, "\n")) >= 0) {
162                         return substr($$rbuf, 0, $n + 1, '');
163                 }
164                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
165                                                                 and next;
166
167                 # return whatever's left on EOF
168                 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
169
170                 next if ($! == EAGAIN and poll_in($fh));
171                 next if $! == EINTR; # may be set by sysread or poll_in
172                 return; # unrecoverable error
173         }
174 }
175
176 sub cat_async_retry ($$$$$) {
177         my ($self, $inflight, $req, $cb, $arg) = @_;
178
179         # {inflight} may be non-existent, but if it isn't we delete it
180         # here to prevent cleanup() from waiting:
181         delete $self->{inflight};
182         cleanup($self);
183
184         $self->{inflight} = $inflight;
185         batch_prepare($self);
186         my $buf = "$req\n";
187         for (my $i = 0; $i < @$inflight; $i += 3) {
188                 $buf .= "$inflight->[$i]\n";
189         }
190         print { $self->{out} } $buf or $self->fail("write error: $!");
191         unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
192
193         cat_async_step($self, $inflight); # take one step
194 }
195
196 sub cat_async_step ($$) {
197         my ($self, $inflight) = @_;
198         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
199         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
200         my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
201         my ($bref, $oid, $type, $size);
202         my $head = my_readline($self->{in}, $rbuf);
203         # ->fail may be called via Gcf2Client.pm
204         if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
205                 ($oid, $type, $size) = ($1, $2, $3 + 0);
206                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
207                         $self->fail(defined($bref) ? 'read EOF' : "read: $!");
208                 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
209         } elsif ($head =~ s/ missing\n//s) {
210                 $oid = $head;
211                 # ref($req) indicates it's already been retried
212                 # -gcf2 retries internally, so it never hits this path:
213                 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
214                         return cat_async_retry($self, $inflight,
215                                                 $req, $cb, $arg);
216                 }
217                 $type = 'missing';
218                 $oid = ref($req) ? $$req : $req if $oid eq '';
219         } else {
220                 my $err = $! ? " ($!)" : '';
221                 $self->fail("bad result from async cat-file: $head$err");
222         }
223         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
224         eval { $cb->($bref, $oid, $type, $size, $arg) };
225         warn "E: $oid: $@\n" if $@;
226 }
227
228 sub cat_async_wait ($) {
229         my ($self) = @_;
230         my $inflight = $self->{inflight} or return;
231         while (scalar(@$inflight)) {
232                 cat_async_step($self, $inflight);
233         }
234 }
235
236 sub batch_prepare ($) {
237         _bidi_pipe($_[0], qw(--batch in out pid));
238 }
239
240 sub _cat_file_cb {
241         my ($bref, undef, undef, $size, $result) = @_;
242         @$result = ($bref, $size);
243 }
244
245 sub cat_file {
246         my ($self, $oid, $sizeref) = @_;
247         my $result = [];
248         cat_async($self, $oid, \&_cat_file_cb, $result);
249         cat_async_wait($self);
250         $$sizeref = $result->[1] if $sizeref;
251         $result->[0];
252 }
253
254 sub check_async_step ($$) {
255         my ($self, $inflight_c) = @_;
256         die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
257         my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
258         my $rbuf = delete($self->{chk_rbuf}) // \(my $new = '');
259         chomp(my $line = my_readline($self->{in_c}, $rbuf));
260         my ($hex, $type, $size) = split(/ /, $line);
261
262         # Future versions of git.git may have type=ambiguous, but for now,
263         # we must handle 'dangling' below (and maybe some other oddball
264         # stuff):
265         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
266         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
267                 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
268                 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
269         }
270         $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
271         eval { $cb->($hex, $type, $size, $arg, $self) };
272         warn "E: check($req) $@\n" if $@;
273 }
274
275 sub check_async_wait ($) {
276         my ($self) = @_;
277         my $inflight_c = $self->{inflight_c} or return;
278         while (scalar(@$inflight_c)) {
279                 check_async_step($self, $inflight_c);
280         }
281 }
282
283 sub check_async_begin ($) {
284         my ($self) = @_;
285         cleanup($self) if alternates_changed($self);
286         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
287         die 'BUG: already in async check' if $self->{inflight_c};
288         $self->{inflight_c} = [];
289 }
290
291 sub check_async ($$$$) {
292         my ($self, $oid, $cb, $arg) = @_;
293         my $inflight_c = $self->{inflight_c} // check_async_begin($self);
294         while (scalar(@$inflight_c) >= MAX_INFLIGHT) {
295                 check_async_step($self, $inflight_c);
296         }
297         print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
298         push(@$inflight_c, $oid, $cb, $arg);
299 }
300
301 sub _check_cb { # check_async callback
302         my ($hex, $type, $size, $result) = @_;
303         @$result = ($hex, $type, $size);
304 }
305
306 sub check {
307         my ($self, $oid) = @_;
308         my $result = [];
309         check_async($self, $oid, \&_check_cb, $result);
310         check_async_wait($self);
311         my ($hex, $type, $size) = @$result;
312
313         # Future versions of git.git may show 'ambiguous', but for now,
314         # we must handle 'dangling' below (and maybe some other oddball
315         # stuff):
316         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
317         return if $type eq 'missing' || $type eq 'ambiguous';
318         return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
319         ($hex, $type, $size);
320 }
321
322 sub _destroy {
323         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
324         delete @$self{($rbuf, $in, $out)};
325         delete $self->{$err} if $err; # `err_c'
326
327         # GitAsyncCat::event_step may delete {pid}
328         my $p = delete $self->{$pid} or return;
329
330         # PublicInbox::DS may not be loaded
331         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
332         waitpid($p, 0) if $@; # wait synchronously if not in event loop
333 }
334
335 sub cat_async_abort ($) {
336         my ($self) = @_;
337         if (my $inflight = $self->{inflight}) {
338                 while (@$inflight) {
339                         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
340                         $req =~ s/ .*//; # drop git_dir for Gcf2Client
341                         eval { $cb->(undef, $req, undef, undef, $arg) };
342                         warn "E: $req: $@ (in abort)\n" if $@;
343                 }
344                 delete $self->{cat_rbuf};
345                 delete $self->{inflight};
346         }
347         cleanup($self);
348 }
349
350 sub fail { # may be augmented in subclasses
351         my ($self, $msg) = @_;
352         cat_async_abort($self);
353         croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
354 }
355
356 sub popen {
357         my ($self, @cmd) = @_;
358         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
359         popen_rd(\@cmd);
360 }
361
362 sub qx {
363         my ($self, @cmd) = @_;
364         my $fh = $self->popen(@cmd);
365         local $/ = wantarray ? "\n" : undef;
366         <$fh>;
367 }
368
369 # check_async and cat_async may trigger the other, so ensure they're
370 # both completely done by using this:
371 sub async_wait_all ($) {
372         my ($self) = @_;
373         while (scalar(@{$self->{inflight_c} // []}) ||
374                         scalar(@{$self->{inflight} // []})) {
375                 $self->check_async_wait;
376                 $self->cat_async_wait;
377         }
378 }
379
380 # returns true if there are pending "git cat-file" processes
381 sub cleanup {
382         my ($self) = @_;
383         local $in_cleanup = 1;
384         delete $self->{async_cat};
385         async_wait_all($self);
386         delete $self->{inflight};
387         delete $self->{inflight_c};
388         _destroy($self, qw(cat_rbuf in out pid));
389         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
390         !!($self->{pid} || $self->{pid_c});
391 }
392
393
394 # assuming a well-maintained repo, this should be a somewhat
395 # accurate estimation of its size
396 # TODO: show this in the WWW UI as a hint to potential cloners
397 sub packed_bytes {
398         my ($self) = @_;
399         my $n = 0;
400         my $pack_dir = git_path($self, 'objects/pack');
401         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
402                 $n += -s $p;
403         }
404         $n
405 }
406
407 sub DESTROY { cleanup(@_) }
408
409 sub local_nick ($) {
410         my ($self) = @_;
411         my $ret = '???';
412         # don't show full FS path, basename should be OK:
413         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
414                 $ret = "/path/to/$1";
415         }
416         wantarray ? ($ret) : $ret;
417 }
418
419 sub host_prefix_url ($$) {
420         my ($env, $url) = @_;
421         return $url if index($url, '//') >= 0;
422         my $scheme = $env->{'psgi.url_scheme'};
423         my $host_port = $env->{HTTP_HOST} //
424                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
425         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
426 }
427
428 sub pub_urls {
429         my ($self, $env) = @_;
430         if (my $urls = $self->{cgit_url}) {
431                 return map { host_prefix_url($env, $_) } @$urls;
432         }
433         local_nick($self);
434 }
435
436 sub cat_async_begin {
437         my ($self) = @_;
438         cleanup($self) if $self->alternates_changed;
439         $self->batch_prepare;
440         die 'BUG: already in async' if $self->{inflight};
441         $self->{inflight} = [];
442 }
443
444 sub cat_async ($$$;$) {
445         my ($self, $oid, $cb, $arg) = @_;
446         my $inflight = $self->{inflight} // cat_async_begin($self);
447         while (scalar(@$inflight) >= MAX_INFLIGHT) {
448                 cat_async_step($self, $inflight);
449         }
450         print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
451         push(@$inflight, $oid, $cb, $arg);
452 }
453
454 sub async_prefetch {
455         my ($self, $oid, $cb, $arg) = @_;
456         if (my $inflight = $self->{inflight}) {
457                 # we could use MAX_INFLIGHT here w/o the halving,
458                 # but lets not allow one client to monopolize a git process
459                 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
460                         print { $self->{out} } $oid, "\n" or
461                                                 $self->fail("write error: $!");
462                         return push(@$inflight, $oid, $cb, $arg);
463                 }
464         }
465         undef;
466 }
467
468 sub extract_cmt_time {
469         my ($bref, undef, undef, undef, $modified) = @_;
470
471         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
472                 my $cmt_time = $1 + 0;
473                 $$modified = $cmt_time if $cmt_time > $$modified;
474         }
475 }
476
477 # returns the modified time of a git repo, same as the "modified" field
478 # of a grokmirror manifest
479 sub modified ($) {
480         my ($self) = @_;
481         my $modified = 0;
482         my $fh = popen($self, qw(rev-parse --branches));
483         local $/ = "\n";
484         while (my $oid = <$fh>) {
485                 chomp $oid;
486                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
487         }
488         cat_async_wait($self);
489         $modified || time;
490 }
491
492 # for grokmirror, which doesn't read gitweb.description
493 # templates/hooks--update.sample and git-multimail in git.git
494 # only match "Unnamed repository", not the full contents of
495 # templates/this--description in git.git
496 sub manifest_entry {
497         my ($self, $epoch, $default_desc) = @_;
498         my ($fh, $pid) = $self->popen('show-ref');
499         my $dig = Digest::SHA->new(1);
500         while (read($fh, my $buf, 65536)) {
501                 $dig->add($buf);
502         }
503         close $fh;
504         waitpid($pid, 0);
505         return if $?; # empty, uninitialized git repo
506         my $git_dir = $self->{git_dir};
507         my $ent = {
508                 fingerprint => $dig->hexdigest,
509                 reference => undef,
510                 modified => modified($self),
511         };
512         chomp(my $owner = $self->qx('config', 'gitweb.owner'));
513         utf8::decode($owner);
514         $ent->{owner} = $owner eq '' ? undef : $owner;
515         my $desc = '';
516         if (open($fh, '<', "$git_dir/description")) {
517                 local $/ = "\n";
518                 chomp($desc = <$fh>);
519                 utf8::decode($desc);
520         }
521         $desc = 'Unnamed repository' if $desc eq '';
522         if (defined $epoch && $desc =~ /\AUnnamed repository/) {
523                 $desc = "$default_desc [epoch $epoch]";
524         }
525         $ent->{description} = $desc;
526         if (open($fh, '<', "$git_dir/objects/info/alternates")) {
527                 # n.b.: GitPython doesn't seem to handle comments or C-quoted
528                 # strings like native git does; and we don't for now, either.
529                 local $/ = "\n";
530                 chomp(my @alt = <$fh>);
531
532                 # grokmirror only supports 1 alternate for "reference",
533                 if (scalar(@alt) == 1) {
534                         my $objdir = "$git_dir/objects";
535                         my $ref = File::Spec->rel2abs($alt[0], $objdir);
536                         $ref =~ s!/[^/]+/?\z!!; # basename
537                         $ent->{reference} = $ref;
538                 }
539         }
540         $ent;
541 }
542
543 1;
544 __END__
545 =pod
546
547 =head1 NAME
548
549 PublicInbox::Git - git wrapper
550
551 =head1 VERSION
552
553 version 1.0
554
555 =head1 SYNOPSIS
556
557         use PublicInbox::Git;
558         chomp(my $git_dir = `git rev-parse --git-dir`);
559         $git_dir or die "GIT_DIR= must be specified\n";
560         my $git = PublicInbox::Git->new($git_dir);
561
562 =head1 DESCRIPTION
563
564 Unstable API outside of the L</new> method.
565 It requires L<git(1)> to be installed.
566
567 =head1 METHODS
568
569 =cut
570
571 =head2 new
572
573         my $git = PublicInbox::Git->new($git_dir);
574
575 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
576 This is the only public API method we support.  Everything else
577 in this module is subject to change.
578
579 =head1 SEE ALSO
580
581 L<Git>, L<PublicInbox::Import>
582
583 =head1 CONTACT
584
585 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
586
587 The mail archives are hosted at L<https://public-inbox.org/meta/>
588
589 =head1 COPYRIGHT
590
591 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
592
593 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
594
595 =cut