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);
60 sub check_git_exe () {
61 $GIT_EXE = which('git') // die "git not found in $ENV{PATH}";
62 my @st = stat($GIT_EXE) or die "stat: $!";
63 my $st = pack('dd', $st[10], $st[7]);
65 my $rd = popen_rd([ $GIT_EXE, '--version' ]);
66 my $v = readline($rd);
67 $v =~ /\b([0-9]+(?:\.[0-9]+){2})/ or die
68 "$GIT_EXE --version output: $v # unparseable";
69 my @v = split(/\./, $1, 3);
70 $GIT_VER = ($v[0] << 24) | ($v[1] << 16) | $v[2];
75 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
77 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
79 $_[0] =~ s!\\([\\"abfnrtv]|[0-3][0-7]{2})!$GIT_ESC{$1}//chr(oct($1))!ge;
84 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
85 '\\'.($ESC_GIT{$1}||sprintf("%03o",ord($1)))/egs) {
92 my ($class, $git_dir) = @_;
94 $git_dir =~ s!/*\z!!s;
95 # may contain {-tmp} field for File::Temp::Dir
96 bless { git_dir => $git_dir }, $class
100 my ($self, $path) = @_;
101 $self->{-git_path}->{$path} //= do {
103 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
105 # git prior to 2.5.0 did not understand --git-path
106 if ($str eq "--git-path\n$path") {
107 $str = "$self->{git_dir}/$path";
113 sub alternates_changed {
115 my $alt = git_path($self, 'objects/info/alternates');
116 my @st = stat($alt) or return 0;
118 # can't rely on 'q' on some 32-bit builds, but `d' works
119 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
120 return 0 if ($self->{alt_st} // '') eq $st;
121 $self->{alt_st} = $st; # always a true value
125 $_[0]->{object_format} //= do {
126 my $fmt = $_[0]->qx(qw(config extensions.objectformat));
127 $fmt eq "sha256\n" ? \'sha256' : \undef;
133 my $fh = $self->{err_c} or return;
134 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
135 defined(sysread($fh, my $buf, -s $fh)) or
136 $self->fail("sysread failed: $!");
141 my ($self, $batch, $in, $out, $pid, $err) = @_;
143 if (defined $err) { # "err_c"
144 my $fh = $self->{$err};
145 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
146 truncate($fh, 0) or $self->fail("truncate failed: $!");
151 pipe(my ($out_r, $out_w)) or $self->fail("pipe failed: $!");
152 my $rdr = { 0 => $out_r, pgid => 0 };
153 my $gd = $self->{git_dir};
154 if ($gd =~ s!/([^/]+/[^/]+)\z!/!) {
159 # git 2.31.0+ supports -c core.abbrev=no, don't bother with
160 # core.abbrev=64 since not many releases had SHA-256 prior to 2.31
161 my $abbr = $GIT_VER < (2 << 24 | 31 << 16) ? 40 : 'no';
162 my @cmd = ($GIT_EXE, "--git-dir=$gd", '-c', "core.abbrev=$abbr",
163 'cat-file', "--$batch");
165 my $id = "git.$self->{git_dir}.$batch.err";
166 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
170 # see lib/PublicInbox/ProcessPipe.pm for why we don't use that here
171 my ($in_r, $p) = popen_rd(\@cmd, undef, $rdr);
172 awaitpid($self->{$pid} = $p, undef);
173 $self->{"$pid.owner"} = $$;
174 $out_w->autoflush(1);
175 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
176 fcntl($out_w, 1031, 4096);
177 fcntl($in_r, 1031, 4096) if $batch eq 'batch-check';
180 $self->{$out} = $out_w;
181 $self->{$in} = $in_r;
184 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
187 my ($fh, $rbuf, $len) = @_;
188 my $left = $len - length($$rbuf);
191 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
194 } elsif (defined($r)) { # EOF
197 next if ($! == EAGAIN and poll_in($fh));
198 next if $! == EINTR; # may be set by sysread or poll_in
199 return; # unrecoverable error
202 my $no_pad = substr($$rbuf, 0, $len, '');
206 sub my_readline ($$) {
207 my ($fh, $rbuf) = @_;
209 if ((my $n = index($$rbuf, "\n")) >= 0) {
210 return substr($$rbuf, 0, $n + 1, '');
212 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
215 # return whatever's left on EOF
216 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
218 next if ($! == EAGAIN and poll_in($fh));
219 next if $! == EINTR; # may be set by sysread or poll_in
220 return; # unrecoverable error
224 sub cat_async_retry ($$) {
225 my ($self, $inflight) = @_;
227 # {inflight} may be non-existent, but if it isn't we delete it
228 # here to prevent cleanup() from waiting:
229 delete $self->{inflight};
232 $self->{inflight} = $inflight;
233 batch_prepare($self);
235 for (my $i = 0; $i < @$inflight; $i += 3) {
236 $buf .= "$inflight->[$i]\n";
238 $self->{out}->blocking(1); # brand new pipe, should never block
239 print { $self->{out} } $buf or $self->fail("write error: $!");
240 $self->{out}->blocking(0);
241 my $req = shift @$inflight;
242 unshift(@$inflight, \$req); # \$ref to indicate retried
244 cat_async_step($self, $inflight); # take one step
247 # returns true if prefetch is successful
249 my ($self, $oid, $cb, $arg) = @_;
250 my $inflight = $self->{inflight} or return;
251 return if @$inflight;
252 substr($oid, 0, 0) = 'contents ' if $self->{-bc};
253 write_all($self, $self->{out}, "$oid\n", \&cat_async_step, $inflight);
254 push(@$inflight, $oid, $cb, $arg);
257 sub cat_async_step ($$) {
258 my ($self, $inflight) = @_;
259 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
260 my ($req, $cb, $arg) = @$inflight[0, 1, 2];
261 my $rbuf = delete($self->{rbuf}) // \(my $new = '');
262 my ($bref, $oid, $type, $size);
263 my $head = my_readline($self->{in}, $rbuf);
264 my $cmd = ref($req) ? $$req : $req;
265 # ->fail may be called via Gcf2Client.pm
266 my $bc = $self->{-bc};
267 if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
268 ($oid, $type, $size) = ($1, $2, $3 + 0);
269 unless ($bc && $cmd =~ /\Ainfo /) { # --batch-command
270 $bref = my_read($self->{in}, $rbuf, $size + 1) or
271 $self->fail(defined($bref) ?
272 'read EOF' : "read: $!");
273 chop($$bref) eq "\n" or
274 $self->fail('LF missing after blob');
276 } elsif ($bc && $cmd =~ /\Ainfo / &&
277 $head =~ / (missing|ambiguous)\n/) {
279 $oid = substr($cmd, 5);
280 } elsif ($head =~ s/ missing\n//s) {
282 # ref($req) indicates it's already been retried
283 # -gcf2 retries internally, so it never hits this path:
284 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
285 return cat_async_retry($self, $inflight);
290 $oid =~ s/\A(?:contents|info) // if $bc;
293 my $err = $! ? " ($!)" : '';
294 $self->fail("bad result from async cat-file: $head$err");
296 $self->{rbuf} = $rbuf if $$rbuf ne '';
297 splice(@$inflight, 0, 3); # don't retry $cb on ->fail
298 if ($bc && $cmd =~ /\Ainfo /) {
299 eval { $cb->($oid, $type, $size, $arg, $self) };
300 async_err($self, $req, $oid, $@, 'check') if $@;
302 eval { $cb->($bref, $oid, $type, $size, $arg) };
303 async_err($self, $req, $oid, $@, 'cat') if $@;
307 sub cat_async_wait ($) {
309 my $inflight = $self->{inflight} or return;
310 while (scalar(@$inflight)) {
311 cat_async_step($self, $inflight);
315 sub batch_prepare ($) {
318 if ($GIT_VER >= BATCH_CMD_VER) {
319 _bidi_pipe($self, qw(batch-command in out pid err_c));
322 _bidi_pipe($self, qw(batch in out pid));
324 $self->{inflight} = [];
328 my ($bref, $oid, $type, $size, $result) = @_;
329 @$result = ($bref, $oid, $type, $size);
333 my ($self, $oid) = @_;
335 cat_async($self, $oid, \&_cat_file_cb, $result);
336 cat_async_wait($self);
337 wantarray ? @$result : $result->[0];
340 sub check_async_step ($$) {
341 my ($self, $inflight_c) = @_;
342 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
343 my ($req, $cb, $arg) = @$inflight_c[0, 1, 2];
344 my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
345 chomp(my $line = my_readline($self->{in_c}, $rbuf));
346 my ($hex, $type, $size) = split(/ /, $line);
348 # git <2.21 would show `dangling' (2.21+ shows `ambiguous')
349 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
350 if ($hex eq 'dangling') {
351 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
352 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
354 $self->{rbuf_c} = $rbuf if $$rbuf ne '';
355 splice(@$inflight_c, 0, 3); # don't retry $cb on ->fail
356 eval { $cb->($hex, $type, $size, $arg, $self) };
357 async_err($self, $req, $hex, $@, 'check') if $@;
360 sub check_async_wait ($) {
362 return cat_async_wait($self) if $self->{-bc};
363 my $inflight_c = $self->{inflight_c} or return;
364 check_async_step($self, $inflight_c) while (scalar(@$inflight_c));
367 sub check_async_begin ($) {
369 die 'BUG: already in async check' if $self->{inflight_c};
370 cleanup($self) if alternates_changed($self);
372 if ($GIT_VER >= BATCH_CMD_VER) {
373 _bidi_pipe($self, qw(batch-command in out pid err_c));
375 $self->{inflight} = [];
377 _bidi_pipe($self, qw(batch-check in_c out_c pid_c err_c));
378 $self->{inflight_c} = [];
383 my ($self, $out, $buf, $read_step, $inflight) = @_;
384 $read_step->($self, $inflight) while @$inflight >= MAX_INFLIGHT;
386 my $w = syswrite($out, $buf);
388 return if $w == length($buf);
389 substr($buf, 0, $w, ''); # sv_chop
390 } elsif ($! != EAGAIN) {
391 $self->fail("write: $!");
393 $read_step->($self, $inflight);
397 sub check_async ($$$$) {
398 my ($self, $oid, $cb, $arg) = @_;
399 my $inflight = $self->{-bc} ?
400 ($self->{inflight} // cat_async_begin($self)) :
401 ($self->{inflight_c} // check_async_begin($self));
403 substr($oid, 0, 0) = 'info ';
404 write_all($self, $self->{out}, "$oid\n",
405 \&cat_async_step, $inflight);
407 write_all($self, $self->{out_c}, "$oid\n",
408 \&check_async_step, $inflight);
410 push(@$inflight, $oid, $cb, $arg);
413 sub _check_cb { # check_async callback
414 my ($hex, $type, $size, $result) = @_;
415 @$result = ($hex, $type, $size);
419 my ($self, $oid) = @_;
421 check_async($self, $oid, \&_check_cb, $result);
422 check_async_wait($self);
423 my ($hex, $type, $size) = @$result;
425 # git <2.21 would show `dangling' (2.21+ shows `ambiguous')
426 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
427 return if $type =~ /\A(?:missing|ambiguous)\z/ || $hex eq 'dangling';
428 ($hex, $type, $size);
432 my ($self, $pid, @rest) = @_; # rest = rbuf, in, out, err
433 my ($p) = delete @$self{($pid, @rest)};
435 # GitAsyncCat::event_step may delete {$pid}
436 awaitpid($p) if defined($p) && $$ == $self->{"$pid.owner"};
439 sub async_abort ($) {
441 while (scalar(@{$self->{inflight_c} // []}) ||
442 scalar(@{$self->{inflight} // []})) {
443 for my $c ('', '_c') {
444 my $q = $self->{"inflight$c"} or next;
446 my ($req, $cb, $arg) = splice(@$q, 0, 3);
447 $req = $$req if ref($req);
449 $req =~ s/\A(?:contents|info) //;
450 $req =~ s/ .*//; # drop git_dir for Gcf2Client
451 eval { $cb->(undef, $req, undef, undef, $arg) };
452 warn "E: (in abort) $req: $@" if $@;
454 delete $self->{"inflight$c"};
455 delete $self->{"rbuf$c"};
461 sub fail { # may be augmented in subclasses
462 my ($self, $msg) = @_;
464 croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
467 sub async_err ($$$$$) {
468 my ($self, $req, $oid, $err, $action) = @_;
469 $req = $$req if ref($req); # retried
470 my $msg = "E: $action $req ($oid): $err";
471 $async_warn ? carp($msg) : $self->fail($msg);
474 # $git->popen(qw(show f00)); # or
475 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
477 my ($self, $cmd) = splice(@_, 0, 2);
478 $cmd = [ 'git', "--git-dir=$self->{git_dir}",
479 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
480 popen_rd($cmd, grep { !defined || ref } @_); # env and opt
483 # same args as popen above
488 close $fh; # caller should check $?
493 close $fh; # caller should check $?
501 substr($_, length('--max-age='), -1)
502 } $self->qx('rev-parse', map { "--since=$_" } @_);
505 # check_async and cat_async may trigger the other, so ensure they're
506 # both completely done by using this:
507 sub async_wait_all ($) {
509 while (scalar(@{$self->{inflight_c} // []}) ||
510 scalar(@{$self->{inflight} // []})) {
511 check_async_wait($self);
512 cat_async_wait($self);
516 # returns true if there are pending "git cat-file" processes
518 my ($self, $lazy) = @_;
519 return 1 if $lazy && (scalar(@{$self->{inflight_c} // []}) ||
520 scalar(@{$self->{inflight} // []}));
521 local $in_cleanup = 1;
522 delete @$self{qw(async_cat async_chk)};
523 async_wait_all($self);
524 delete @$self{qw(inflight inflight_c -bc)};
525 _destroy($self, qw(pid rbuf in out err_c));
526 _destroy($self, qw(pid_c rbuf_c in_c out_c err_c));
530 # assuming a well-maintained repo, this should be a somewhat
531 # accurate estimation of its size
532 # TODO: show this in the WWW UI as a hint to potential cloners
536 my $pack_dir = git_path($self, 'objects/pack');
537 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
543 sub DESTROY { cleanup(@_) }
546 # don't show full FS path, basename should be OK:
547 $_[0]->{nick} // ($_[0]->{git_dir} =~ m!/([^/]+?)(?:/*\.git/*)?\z! ?
551 sub host_prefix_url ($$) {
552 my ($env, $url) = @_;
553 return $url if index($url, '//') >= 0;
554 my $host_port = $env->{HTTP_HOST} //
555 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
556 my $sn = $env->{SCRIPT_NAME} // '';
557 "$env->{'psgi.url_scheme'}://$host_port$sn/$url";
560 sub base_url { # for coderepos, PSGI-only
561 my ($self, $env) = @_; # env - PSGI env
562 my $nick = $self->{nick} // return undef;
563 my $url = host_prefix_url($env, '');
564 # for mount in Plack::Builder
565 $url .= '/' if substr($url, -1, 1) ne '/';
572 my ($self, $env) = @_;
573 if (my $urls = $self->{cgit_url}) {
574 map { host_prefix_url($env, $_) } @$urls;
576 (base_url($self, $env) // '???');
580 sub cat_async_begin {
582 cleanup($self) if $self->alternates_changed;
583 die 'BUG: already in async' if $self->{inflight};
584 batch_prepare($self);
587 sub cat_async ($$$;$) {
588 my ($self, $oid, $cb, $arg) = @_;
589 my $inflight = $self->{inflight} // cat_async_begin($self);
590 substr($oid, 0, 0) = 'contents ' if $self->{-bc};
591 write_all($self, $self->{out}, $oid."\n", \&cat_async_step, $inflight);
592 push(@$inflight, $oid, $cb, $arg);
595 # returns the modified time of a git repo, same as the "modified" field
596 # of a grokmirror manifest
598 # committerdate:unix is git 2.9.4+ (2017-05-05), so using raw instead
599 my $fh = popen($_[0], qw[for-each-ref --sort=-committerdate
600 --format=%(committerdate:raw) --count=1]);
601 (split(/ /, <$fh> // time))[0] + 0; # integerize for JSON
606 open(my $fh, '<', $path) or return '';
612 my $desc = try_cat($_[0]);
615 $desc =~ s/\s+/ /smg;
616 $desc eq '' ? undef : $desc;
620 cat_desc("$_[0]->{git_dir}/description") // 'Unnamed repository';
624 my ($self, $env) = @_;
625 $self->{cloneurl} // do {
626 my @urls = split(/\s+/s, try_cat("$self->{git_dir}/cloneurl"));
627 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
628 } // [ substr(base_url($self, $env), 0, -1) ];
631 # for grokmirror, which doesn't read gitweb.description
632 # templates/hooks--update.sample and git-multimail in git.git
633 # only match "Unnamed repository", not the full contents of
634 # templates/this--description in git.git
636 my ($self, $epoch, $default_desc) = @_;
637 my $fh = $self->popen('show-ref');
638 my $dig = PublicInbox::SHA->new(1);
639 while (read($fh, my $buf, 65536)) {
642 close $fh or return; # empty, uninitialized git repo
643 undef $fh; # for open, below
644 my $git_dir = $self->{git_dir};
646 fingerprint => $dig->hexdigest,
648 modified => modified($self),
650 chomp(my $owner = $self->qx('config', 'gitweb.owner'));
651 utf8::decode($owner);
652 $ent->{owner} = $owner eq '' ? undef : $owner;
653 my $desc = description($self);
654 if (defined $epoch && index($desc, 'Unnamed repository') == 0) {
655 $desc = "$default_desc [epoch $epoch]";
657 $ent->{description} = $desc;
658 if (open($fh, '<', "$git_dir/objects/info/alternates")) {
659 # n.b.: GitPython doesn't seem to handle comments or C-quoted
660 # strings like native git does; and we don't for now, either.
662 chomp(my @alt = <$fh>);
664 # grokmirror only supports 1 alternate for "reference",
665 if (scalar(@alt) == 1) {
666 my $objdir = "$git_dir/objects";
667 my $ref = File::Spec->rel2abs($alt[0], $objdir);
668 $ref =~ s!/[^/]+/?\z!!; # basename
669 $ent->{reference} = $ref;
675 # returns true if there are pending cat-file processes
676 sub cleanup_if_unlinked {
678 return cleanup($self, 1) if $^O ne 'linux';
679 # Linux-specific /proc/$PID/maps access
680 # TODO: support this inside git.git
682 for my $fld (qw(pid pid_c)) {
683 my $pid = $self->{$fld} // next;
684 open my $fh, '<', "/proc/$pid/maps" or return cleanup($self, 1);
686 # n.b. we do not restart for unlinked multi-pack-index
687 # since it's not too huge, and the startup cost may
689 /\.(?:idx|pack) \(deleted\)$/ and
690 return cleanup($self, 1);
703 PublicInbox::Git - git wrapper
711 use PublicInbox::Git;
712 chomp(my $git_dir = `git rev-parse --git-dir`);
713 $git_dir or die "GIT_DIR= must be specified\n";
714 my $git = PublicInbox::Git->new($git_dir);
718 Unstable API outside of the L</new> method.
719 It requires L<git(1)> to be installed.
727 my $git = PublicInbox::Git->new($git_dir);
729 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
730 This is the only public API method we support. Everything else
731 in this module is subject to change.
735 L<Git>, L<PublicInbox::Import>
739 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
741 The mail archives are hosted at L<https://public-inbox.org/meta/>
745 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
747 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>