1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: GPLv2 or later <https://www.gnu.org/licenses/gpl-2.0.txt>
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;
12 use parent qw(Exporter);
14 use IO::Handle; # ->autoflush
15 use Errno qw(EINTR EAGAIN);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd which);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
22 use Carp qw(croak carp);
23 use PublicInbox::SHA ();
24 use PublicInbox::DS qw(awaitpid);
25 our @EXPORT_OK = qw(git_unquote git_quote);
26 our $PIPE_BUFSIZ = 65536; # Linux default
28 our $RDTIMEO = 60_000; # milliseconds
29 our $async_warn; # true in read-only daemons
31 # 512: POSIX PIPE_BUF minimum (see pipe(7))
32 # 3: @$inflight is flattened [ $OID, $cb, $arg ]
33 # 65: SHA-256 hex size + "\n" in preparation for git using non-SHA1
35 MAX_INFLIGHT => 512 * 3 / (65 + length('contents ')),
36 BATCH_CMD_VER => (2 << 24 | 36 << 16), # git 2.36+
50 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
52 my $EXE_ST = ''; # pack('dd', st_ctime, st_size);
53 my ($GIT_EXE, $GIT_VER);
55 sub check_git_exe () {
56 $GIT_EXE = which('git') // die "git not found in $ENV{PATH}";
57 my @st = stat($GIT_EXE) or die "stat: $!";
58 my $st = pack('dd', $st[10], $st[7]);
60 my $rd = popen_rd([ $GIT_EXE, '--version' ]);
61 my $v = readline($rd);
62 $v =~ /\b([0-9]+(?:\.[0-9]+){2})/ or die
63 "$GIT_EXE --version output: $v # unparseable";
64 my @v = split(/\./, $1, 3);
65 $GIT_VER = ($v[0] << 24) | ($v[1] << 16) | $v[2];
70 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
72 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
74 $_[0] =~ s!\\([\\"abfnrtv]|[0-3][0-7]{2})!$GIT_ESC{$1}//chr(oct($1))!ge;
79 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
80 '\\'.($ESC_GIT{$1}||sprintf("%03o",ord($1)))/egs) {
87 my ($class, $git_dir) = @_;
89 $git_dir =~ s!/*\z!!s;
90 # may contain {-tmp} field for File::Temp::Dir
91 bless { git_dir => $git_dir }, $class
95 my ($self, $path) = @_;
96 $self->{-git_path}->{$path} //= do {
98 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
100 # git prior to 2.5.0 did not understand --git-path
101 if ($str eq "--git-path\n$path") {
102 $str = "$self->{git_dir}/$path";
108 sub alternates_changed {
110 my $alt = git_path($self, 'objects/info/alternates');
111 my @st = stat($alt) or return 0;
113 # can't rely on 'q' on some 32-bit builds, but `d' works
114 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
115 return 0 if ($self->{alt_st} // '') eq $st;
116 $self->{alt_st} = $st; # always a true value
120 $_[0]->{object_format} //= do {
121 my $fmt = $_[0]->qx(qw(config extensions.objectformat));
122 $fmt eq "sha256\n" ? \'sha256' : \undef;
128 my $fh = $self->{err_c} or return;
129 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
130 defined(sysread($fh, my $buf, -s $fh)) or
131 $self->fail("sysread failed: $!");
136 my ($self, $batch, $in, $out, $pid, $err) = @_;
138 if (defined $err) { # "err_c"
139 my $fh = $self->{$err};
140 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
141 truncate($fh, 0) or $self->fail("truncate failed: $!");
146 pipe(my ($out_r, $out_w)) or $self->fail("pipe failed: $!");
147 my $rdr = { 0 => $out_r, pgid => 0 };
148 my $gd = $self->{git_dir};
149 if ($gd =~ s!/([^/]+/[^/]+)\z!/!) {
154 # git 2.31.0+ supports -c core.abbrev=no, don't bother with
155 # core.abbrev=64 since not many releases had SHA-256 prior to 2.31
156 my $abbr = $GIT_VER < (2 << 24 | 31 << 16) ? 40 : 'no';
157 my @cmd = ($GIT_EXE, "--git-dir=$gd", '-c', "core.abbrev=$abbr",
158 'cat-file', "--$batch");
160 my $id = "git.$self->{git_dir}.$batch.err";
161 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
165 # see lib/PublicInbox/ProcessPipe.pm for why we don't use that here
166 my ($in_r, $p) = popen_rd(\@cmd, undef, $rdr);
167 awaitpid($self->{$pid} = $p, undef);
168 $self->{"$pid.owner"} = $$;
169 $out_w->autoflush(1);
170 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
171 fcntl($out_w, 1031, 4096);
172 fcntl($in_r, 1031, 4096) if $batch eq 'batch-check';
175 $self->{$out} = $out_w;
176 $self->{$in} = $in_r;
179 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
182 my ($fh, $rbuf, $len) = @_;
183 my $left = $len - length($$rbuf);
186 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
189 } elsif (defined($r)) { # EOF
192 next if ($! == EAGAIN and poll_in($fh));
193 next if $! == EINTR; # may be set by sysread or poll_in
194 return; # unrecoverable error
197 my $no_pad = substr($$rbuf, 0, $len, '');
201 sub my_readline ($$) {
202 my ($fh, $rbuf) = @_;
204 if ((my $n = index($$rbuf, "\n")) >= 0) {
205 return substr($$rbuf, 0, $n + 1, '');
207 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
210 # return whatever's left on EOF
211 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
213 next if ($! == EAGAIN and poll_in($fh));
214 next if $! == EINTR; # may be set by sysread or poll_in
215 return; # unrecoverable error
219 sub cat_async_retry ($$) {
220 my ($self, $inflight) = @_;
222 # {inflight} may be non-existent, but if it isn't we delete it
223 # here to prevent cleanup() from waiting:
224 delete $self->{inflight};
227 $self->{inflight} = $inflight;
228 batch_prepare($self);
230 for (my $i = 0; $i < @$inflight; $i += 3) {
231 $buf .= "$inflight->[$i]\n";
233 $self->{out}->blocking(1); # brand new pipe, should never block
234 print { $self->{out} } $buf or $self->fail("write error: $!");
235 $self->{out}->blocking(0);
236 my $req = shift @$inflight;
237 unshift(@$inflight, \$req); # \$ref to indicate retried
239 cat_async_step($self, $inflight); # take one step
242 # returns true if prefetch is successful
244 my ($self, $oid, $cb, $arg) = @_;
245 my $inflight = $self->{inflight} or return;
246 return if @$inflight;
247 substr($oid, 0, 0) = 'contents ' if $self->{-bc};
248 write_all($self, $self->{out}, "$oid\n", \&cat_async_step, $inflight);
249 push(@$inflight, $oid, $cb, $arg);
252 sub cat_async_step ($$) {
253 my ($self, $inflight) = @_;
254 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
255 my ($req, $cb, $arg) = @$inflight[0, 1, 2];
256 my $rbuf = delete($self->{rbuf}) // \(my $new = '');
257 my ($bref, $oid, $type, $size);
258 my $head = my_readline($self->{in}, $rbuf);
259 my $cmd = ref($req) ? $$req : $req;
260 # ->fail may be called via Gcf2Client.pm
261 my $bc = $self->{-bc};
262 if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
263 ($oid, $type, $size) = ($1, $2, $3 + 0);
264 unless ($bc && $cmd =~ /\Ainfo /) { # --batch-command
265 $bref = my_read($self->{in}, $rbuf, $size + 1) or
266 $self->fail(defined($bref) ?
267 'read EOF' : "read: $!");
268 chop($$bref) eq "\n" or
269 $self->fail('LF missing after blob');
271 } elsif ($bc && $cmd =~ /\Ainfo / &&
272 $head =~ / (missing|ambiguous)\n/) {
274 $oid = substr($cmd, 5);
275 } elsif ($head =~ s/ missing\n//s) {
277 # ref($req) indicates it's already been retried
278 # -gcf2 retries internally, so it never hits this path:
279 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
280 return cat_async_retry($self, $inflight);
285 $oid =~ s/\A(?:contents|info) // if $bc;
288 my $err = $! ? " ($!)" : '';
289 $self->fail("bad result from async cat-file: $head$err");
291 $self->{rbuf} = $rbuf if $$rbuf ne '';
292 splice(@$inflight, 0, 3); # don't retry $cb on ->fail
293 if ($bc && $cmd =~ /\Ainfo /) {
294 eval { $cb->($oid, $type, $size, $arg, $self) };
295 async_err($self, $req, $oid, $@, 'check') if $@;
297 eval { $cb->($bref, $oid, $type, $size, $arg) };
298 async_err($self, $req, $oid, $@, 'cat') if $@;
302 sub cat_async_wait ($) {
304 my $inflight = $self->{inflight} or return;
305 while (scalar(@$inflight)) {
306 cat_async_step($self, $inflight);
310 sub batch_prepare ($) {
313 if ($GIT_VER >= BATCH_CMD_VER) {
314 _bidi_pipe($self, qw(batch-command in out pid err_c));
317 _bidi_pipe($self, qw(batch in out pid));
319 $self->{inflight} = [];
323 my ($bref, $oid, $type, $size, $result) = @_;
324 @$result = ($bref, $oid, $type, $size);
328 my ($self, $oid) = @_;
330 cat_async($self, $oid, \&_cat_file_cb, $result);
331 cat_async_wait($self);
332 wantarray ? @$result : $result->[0];
335 sub check_async_step ($$) {
336 my ($self, $inflight_c) = @_;
337 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
338 my ($req, $cb, $arg) = @$inflight_c[0, 1, 2];
339 my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
340 chomp(my $line = my_readline($self->{in_c}, $rbuf));
341 my ($hex, $type, $size) = split(/ /, $line);
343 # git <2.21 would show `dangling' (2.21+ shows `ambiguous')
344 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
345 if ($hex eq 'dangling') {
346 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
347 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
349 $self->{rbuf_c} = $rbuf if $$rbuf ne '';
350 splice(@$inflight_c, 0, 3); # don't retry $cb on ->fail
351 eval { $cb->($hex, $type, $size, $arg, $self) };
352 async_err($self, $req, $hex, $@, 'check') if $@;
355 sub check_async_wait ($) {
357 return cat_async_wait($self) if $self->{-bc};
358 my $inflight_c = $self->{inflight_c} or return;
359 check_async_step($self, $inflight_c) while (scalar(@$inflight_c));
362 sub check_async_begin ($) {
364 die 'BUG: already in async check' if $self->{inflight_c};
365 cleanup($self) if alternates_changed($self);
367 if ($GIT_VER >= BATCH_CMD_VER) {
368 _bidi_pipe($self, qw(batch-command in out pid err_c));
370 $self->{inflight} = [];
372 _bidi_pipe($self, qw(batch-check in_c out_c pid_c err_c));
373 $self->{inflight_c} = [];
378 my ($self, $out, $buf, $read_step, $inflight) = @_;
379 $read_step->($self, $inflight) while @$inflight >= MAX_INFLIGHT;
381 my $w = syswrite($out, $buf);
383 return if $w == length($buf);
384 substr($buf, 0, $w, ''); # sv_chop
385 } elsif ($! != EAGAIN) {
386 $self->fail("write: $!");
388 $read_step->($self, $inflight);
392 sub check_async ($$$$) {
393 my ($self, $oid, $cb, $arg) = @_;
394 my $inflight = $self->{-bc} ?
395 ($self->{inflight} // cat_async_begin($self)) :
396 ($self->{inflight_c} // check_async_begin($self));
398 substr($oid, 0, 0) = 'info ';
399 write_all($self, $self->{out}, "$oid\n",
400 \&cat_async_step, $inflight);
402 write_all($self, $self->{out_c}, "$oid\n",
403 \&check_async_step, $inflight);
405 push(@$inflight, $oid, $cb, $arg);
408 sub _check_cb { # check_async callback
409 my ($hex, $type, $size, $result) = @_;
410 @$result = ($hex, $type, $size);
414 my ($self, $oid) = @_;
416 check_async($self, $oid, \&_check_cb, $result);
417 check_async_wait($self);
418 my ($hex, $type, $size) = @$result;
420 # git <2.21 would show `dangling' (2.21+ shows `ambiguous')
421 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
422 return if $type =~ /\A(?:missing|ambiguous)\z/ || $hex eq 'dangling';
423 ($hex, $type, $size);
427 my ($self, $pid, @rest) = @_; # rest = rbuf, in, out, err
428 my ($p) = delete @$self{($pid, @rest)};
430 # GitAsyncCat::event_step may delete {$pid}
431 awaitpid($p) if defined($p) && $$ == $self->{"$pid.owner"};
434 sub async_abort ($) {
436 while (scalar(@{$self->{inflight_c} // []}) ||
437 scalar(@{$self->{inflight} // []})) {
438 for my $c ('', '_c') {
439 my $q = $self->{"inflight$c"} or next;
441 my ($req, $cb, $arg) = splice(@$q, 0, 3);
442 $req = $$req if ref($req);
444 $req =~ s/\A(?:contents|info) //;
445 $req =~ s/ .*//; # drop git_dir for Gcf2Client
446 eval { $cb->(undef, $req, undef, undef, $arg) };
447 warn "E: (in abort) $req: $@" if $@;
449 delete $self->{"inflight$c"};
450 delete $self->{"rbuf$c"};
456 sub fail { # may be augmented in subclasses
457 my ($self, $msg) = @_;
459 croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
462 sub async_err ($$$$$) {
463 my ($self, $req, $oid, $err, $action) = @_;
464 $req = $$req if ref($req); # retried
465 my $msg = "E: $action $req ($oid): $err";
466 $async_warn ? carp($msg) : $self->fail($msg);
469 # $git->popen(qw(show f00)); # or
470 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
472 my ($self, $cmd) = splice(@_, 0, 2);
473 $cmd = [ 'git', "--git-dir=$self->{git_dir}",
474 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
475 popen_rd($cmd, grep { !defined || ref } @_); # env and opt
478 # same args as popen above
483 close $fh; # caller should check $?
488 close $fh; # caller should check $?
496 substr($_, length('--max-age='), -1)
497 } $self->qx('rev-parse', map { "--since=$_" } @_);
500 # check_async and cat_async may trigger the other, so ensure they're
501 # both completely done by using this:
502 sub async_wait_all ($) {
504 while (scalar(@{$self->{inflight_c} // []}) ||
505 scalar(@{$self->{inflight} // []})) {
506 check_async_wait($self);
507 cat_async_wait($self);
511 # returns true if there are pending "git cat-file" processes
513 my ($self, $lazy) = @_;
514 return 1 if $lazy && (scalar(@{$self->{inflight_c} // []}) ||
515 scalar(@{$self->{inflight} // []}));
516 local $in_cleanup = 1;
517 delete @$self{qw(async_cat async_chk)};
518 async_wait_all($self);
519 delete @$self{qw(inflight inflight_c -bc)};
520 _destroy($self, qw(pid rbuf in out err_c));
521 _destroy($self, qw(pid_c rbuf_c in_c out_c err_c));
525 # assuming a well-maintained repo, this should be a somewhat
526 # accurate estimation of its size
527 # TODO: show this in the WWW UI as a hint to potential cloners
531 my $pack_dir = git_path($self, 'objects/pack');
532 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
538 sub DESTROY { cleanup(@_) }
541 # don't show full FS path, basename should be OK:
542 $_[0]->{nick} // ($_[0]->{git_dir} =~ m!/([^/]+?)(?:/*\.git/*)?\z! ?
546 sub host_prefix_url ($$) {
547 my ($env, $url) = @_;
548 return $url if index($url, '//') >= 0;
549 my $host_port = $env->{HTTP_HOST} //
550 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
551 my $sn = $env->{SCRIPT_NAME} // '';
552 "$env->{'psgi.url_scheme'}://$host_port$sn/$url";
555 sub base_url { # for coderepos, PSGI-only
556 my ($self, $env) = @_; # env - PSGI env
557 my $nick = $self->{nick} // return undef;
558 my $url = host_prefix_url($env, '');
559 # for mount in Plack::Builder
560 $url .= '/' if substr($url, -1, 1) ne '/';
567 my ($self, $env) = @_;
568 if (my $urls = $self->{cgit_url}) {
569 map { host_prefix_url($env, $_) } @$urls;
571 (base_url($self, $env) // '???');
575 sub cat_async_begin {
577 cleanup($self) if $self->alternates_changed;
578 die 'BUG: already in async' if $self->{inflight};
579 batch_prepare($self);
582 sub cat_async ($$$;$) {
583 my ($self, $oid, $cb, $arg) = @_;
584 my $inflight = $self->{inflight} // cat_async_begin($self);
585 substr($oid, 0, 0) = 'contents ' if $self->{-bc};
586 write_all($self, $self->{out}, $oid."\n", \&cat_async_step, $inflight);
587 push(@$inflight, $oid, $cb, $arg);
590 # returns the modified time of a git repo, same as the "modified" field
591 # of a grokmirror manifest
593 # committerdate:unix is git 2.9.4+ (2017-05-05), so using raw instead
594 my $fh = popen($_[0], qw[for-each-ref --sort=-committerdate
595 --format=%(committerdate:raw) --count=1]);
596 (split(/ /, <$fh> // time))[0] + 0; # integerize for JSON
601 open(my $fh, '<', $path) or return '';
607 my $desc = try_cat($_[0]);
610 $desc =~ s/\s+/ /smg;
611 $desc eq '' ? undef : $desc;
615 cat_desc("$_[0]->{git_dir}/description") // 'Unnamed repository';
619 my ($self, $env) = @_;
620 $self->{cloneurl} // do {
621 my @urls = split(/\s+/s, try_cat("$self->{git_dir}/cloneurl"));
622 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
623 } // [ substr(base_url($self, $env), 0, -1) ];
626 # for grokmirror, which doesn't read gitweb.description
627 # templates/hooks--update.sample and git-multimail in git.git
628 # only match "Unnamed repository", not the full contents of
629 # templates/this--description in git.git
631 my ($self, $epoch, $default_desc) = @_;
632 my $fh = $self->popen('show-ref');
633 my $dig = PublicInbox::SHA->new(1);
634 while (read($fh, my $buf, 65536)) {
637 close $fh or return; # empty, uninitialized git repo
638 undef $fh; # for open, below
639 my $git_dir = $self->{git_dir};
641 fingerprint => $dig->hexdigest,
643 modified => modified($self),
645 chomp(my $owner = $self->qx('config', 'gitweb.owner'));
646 utf8::decode($owner);
647 $ent->{owner} = $owner eq '' ? undef : $owner;
648 my $desc = description($self);
649 if (defined $epoch && index($desc, 'Unnamed repository') == 0) {
650 $desc = "$default_desc [epoch $epoch]";
652 $ent->{description} = $desc;
653 if (open($fh, '<', "$git_dir/objects/info/alternates")) {
654 # n.b.: GitPython doesn't seem to handle comments or C-quoted
655 # strings like native git does; and we don't for now, either.
657 chomp(my @alt = <$fh>);
659 # grokmirror only supports 1 alternate for "reference",
660 if (scalar(@alt) == 1) {
661 my $objdir = "$git_dir/objects";
662 my $ref = File::Spec->rel2abs($alt[0], $objdir);
663 $ref =~ s!/[^/]+/?\z!!; # basename
664 $ent->{reference} = $ref;
670 # returns true if there are pending cat-file processes
671 sub cleanup_if_unlinked {
673 return cleanup($self, 1) if $^O ne 'linux';
674 # Linux-specific /proc/$PID/maps access
675 # TODO: support this inside git.git
677 for my $fld (qw(pid pid_c)) {
678 my $pid = $self->{$fld} // next;
679 open my $fh, '<', "/proc/$pid/maps" or return cleanup($self, 1);
681 # n.b. we do not restart for unlinked multi-pack-index
682 # since it's not too huge, and the startup cost may
684 /\.(?:idx|pack) \(deleted\)$/ and
685 return cleanup($self, 1);
698 PublicInbox::Git - git wrapper
706 use PublicInbox::Git;
707 chomp(my $git_dir = `git rev-parse --git-dir`);
708 $git_dir or die "GIT_DIR= must be specified\n";
709 my $git = PublicInbox::Git->new($git_dir);
713 Unstable API outside of the L</new> method.
714 It requires L<git(1)> to be installed.
722 my $git = PublicInbox::Git->new($git_dir);
724 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
725 This is the only public API method we support. Everything else
726 in this module is subject to change.
730 L<Git>, L<PublicInbox::Import>
734 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
736 The mail archives are hosted at L<https://public-inbox.org/meta/>
740 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
742 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>