1 # Copyright (C) 2014-2021 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 ENOENT);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd spawn);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
22 use Carp qw(croak carp);
24 use PublicInbox::DS qw(dwaitpid);
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 use constant MAX_INFLIGHT => (POSIX::PIPE_BUF * 3) /
32 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
45 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
48 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
50 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
52 $_[0] =~ s!\\([\\"abfnrtv]|[0-3][0-7]{2})!$GIT_ESC{$1}//chr(oct($1))!ge;
57 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
58 '\\'.($ESC_GIT{$1}||sprintf("%03o",ord($1)))/egs) {
65 my ($class, $git_dir) = @_;
67 $git_dir =~ s!/*\z!!s;
68 # may contain {-tmp} field for File::Temp::Dir
69 bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
73 my ($self, $path) = @_;
74 $self->{-git_path}->{$path} ||= do {
76 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
78 # git prior to 2.5.0 did not understand --git-path
79 if ($str eq "--git-path\n$path") {
80 $str = "$self->{git_dir}/$path";
86 sub alternates_changed {
88 my $alt = git_path($self, 'objects/info/alternates');
89 my @st = stat($alt) or return 0;
91 # can't rely on 'q' on some 32-bit builds, but `d' works
92 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
93 return 0 if $self->{alt_st} eq $st;
94 $self->{alt_st} = $st; # always a true value
99 my $fh = $self->{err_c} or return;
100 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
101 defined(sysread($fh, my $buf, -s $fh)) or
102 $self->fail("sysread failed: $!");
107 my ($self, $batch, $in, $out, $pid, $err) = @_;
109 if (defined $err) { # "err_c"
110 my $fh = $self->{$err};
111 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
112 truncate($fh, 0) or $self->fail("truncate failed: $!");
116 pipe(my ($out_r, $out_w)) or $self->fail("pipe failed: $!");
117 my $rdr = { 0 => $out_r, pgid => 0 };
118 my $gd = $self->{git_dir};
119 if ($gd =~ s!/([^/]+/[^/]+)\z!/!) {
123 my @cmd = (qw(git), "--git-dir=$gd",
124 qw(-c core.abbrev=40 cat-file), $batch);
126 my $id = "git.$self->{git_dir}$batch.err";
127 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
131 my ($in_r, $p) = popen_rd(\@cmd, undef, $rdr);
133 $self->{"$pid.owner"} = $$;
134 $out_w->autoflush(1);
135 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
136 fcntl($out_w, 1031, 4096);
137 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
139 $self->{$out} = $out_w;
140 $self->{$in} = $in_r;
143 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
146 my ($fh, $rbuf, $len) = @_;
147 my $left = $len - length($$rbuf);
150 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
153 } elsif (defined($r)) { # EOF
156 next if ($! == EAGAIN and poll_in($fh));
157 next if $! == EINTR; # may be set by sysread or poll_in
158 return; # unrecoverable error
161 \substr($$rbuf, 0, $len, '');
164 sub my_readline ($$) {
165 my ($fh, $rbuf) = @_;
167 if ((my $n = index($$rbuf, "\n")) >= 0) {
168 return substr($$rbuf, 0, $n + 1, '');
170 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
173 # return whatever's left on EOF
174 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
176 next if ($! == EAGAIN and poll_in($fh));
177 next if $! == EINTR; # may be set by sysread or poll_in
178 return; # unrecoverable error
182 sub cat_async_retry ($$) {
183 my ($self, $inflight) = @_;
185 # {inflight} may be non-existent, but if it isn't we delete it
186 # here to prevent cleanup() from waiting:
187 delete $self->{inflight};
190 $self->{inflight} = $inflight;
191 batch_prepare($self);
193 for (my $i = 0; $i < @$inflight; $i += 3) {
194 $buf .= "$inflight->[$i]\n";
196 print { $self->{out} } $buf or $self->fail("write error: $!");
197 my $req = shift @$inflight;
198 unshift(@$inflight, \$req); # \$ref to indicate retried
200 cat_async_step($self, $inflight); # take one step
203 sub cat_async_step ($$) {
204 my ($self, $inflight) = @_;
205 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
206 my ($req, $cb, $arg) = @$inflight[0, 1, 2];
207 my $rbuf = delete($self->{rbuf}) // \(my $new = '');
208 my ($bref, $oid, $type, $size);
209 my $head = my_readline($self->{in}, $rbuf);
210 # ->fail may be called via Gcf2Client.pm
211 if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
212 ($oid, $type, $size) = ($1, $2, $3 + 0);
213 $bref = my_read($self->{in}, $rbuf, $size + 1) or
214 $self->fail(defined($bref) ? 'read EOF' : "read: $!");
215 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
216 } elsif ($head =~ s/ missing\n//s) {
218 # ref($req) indicates it's already been retried
219 # -gcf2 retries internally, so it never hits this path:
220 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
221 return cat_async_retry($self, $inflight);
224 $oid = ref($req) ? $$req : $req if $oid eq '';
226 my $err = $! ? " ($!)" : '';
227 $self->fail("bad result from async cat-file: $head$err");
229 $self->{rbuf} = $rbuf if $$rbuf ne '';
230 splice(@$inflight, 0, 3); # don't retry $cb on ->fail
231 eval { $cb->($bref, $oid, $type, $size, $arg) };
232 async_err($self, $req, $oid, $@, 'cat') if $@;
235 sub cat_async_wait ($) {
237 my $inflight = $self->{inflight} or return;
238 while (scalar(@$inflight)) {
239 cat_async_step($self, $inflight);
243 sub batch_prepare ($) {
244 _bidi_pipe($_[0], qw(--batch in out pid));
248 my ($bref, $oid, $type, $size, $result) = @_;
249 @$result = ($bref, $oid, $type, $size);
253 my ($self, $oid) = @_;
255 cat_async($self, $oid, \&_cat_file_cb, $result);
256 cat_async_wait($self);
257 wantarray ? @$result : $result->[0];
260 sub check_async_step ($$) {
261 my ($self, $inflight_c) = @_;
262 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
263 my ($req, $cb, $arg) = @$inflight_c[0, 1, 2];
264 my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
265 chomp(my $line = my_readline($self->{in_c}, $rbuf));
266 my ($hex, $type, $size) = split(/ /, $line);
268 # Future versions of git.git may have type=ambiguous, but for now,
269 # we must handle 'dangling' below (and maybe some other oddball
271 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
272 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
273 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
274 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
276 $self->{rbuf_c} = $rbuf if $$rbuf ne '';
277 splice(@$inflight_c, 0, 3); # don't retry $cb on ->fail
278 eval { $cb->($hex, $type, $size, $arg, $self) };
279 async_err($self, $req, $hex, $@, 'check') if $@;
282 sub check_async_wait ($) {
284 my $inflight_c = $self->{inflight_c} or return;
285 while (scalar(@$inflight_c)) {
286 check_async_step($self, $inflight_c);
290 sub check_async_begin ($) {
292 cleanup($self) if alternates_changed($self);
293 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
294 die 'BUG: already in async check' if $self->{inflight_c};
295 $self->{inflight_c} = [];
298 sub check_async ($$$$) {
299 my ($self, $oid, $cb, $arg) = @_;
300 my $inflight_c = $self->{inflight_c} // check_async_begin($self);
301 while (scalar(@$inflight_c) >= MAX_INFLIGHT) {
302 check_async_step($self, $inflight_c);
304 print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
305 push(@$inflight_c, $oid, $cb, $arg);
308 sub _check_cb { # check_async callback
309 my ($hex, $type, $size, $result) = @_;
310 @$result = ($hex, $type, $size);
314 my ($self, $oid) = @_;
316 check_async($self, $oid, \&_check_cb, $result);
317 check_async_wait($self);
318 my ($hex, $type, $size) = @$result;
320 # Future versions of git.git may show 'ambiguous', but for now,
321 # we must handle 'dangling' below (and maybe some other oddball
323 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
324 return if $type eq 'missing' || $type eq 'ambiguous';
325 return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
326 ($hex, $type, $size);
330 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
331 delete @$self{($rbuf, $in, $out)};
332 delete $self->{$err} if $err; # `err_c'
334 # GitAsyncCat::event_step may delete {pid}
335 my $p = delete $self->{$pid} or return;
336 dwaitpid($p) if $$ == $self->{"$pid.owner"};
339 sub async_abort ($) {
341 while (scalar(@{$self->{inflight_c} // []}) ||
342 scalar(@{$self->{inflight} // []})) {
343 for my $c ('', '_c') {
344 my $q = $self->{"inflight$c"};
346 my ($req, $cb, $arg) = splice(@$q, 0, 3);
347 $req = $$req if ref($req);
348 $req =~ s/ .*//; # drop git_dir for Gcf2Client
349 eval { $cb->(undef, $req, undef, undef, $arg) };
350 warn "E: (in abort) $req: $@" if $@;
352 delete $self->{"inflight$c"};
353 delete $self->{"rbuf$c"};
359 sub fail { # may be augmented in subclasses
360 my ($self, $msg) = @_;
362 croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
365 sub async_err ($$$$$) {
366 my ($self, $req, $oid, $err, $action) = @_;
367 $req = $$req if ref($req); # retried
368 my $msg = "E: $action $req ($oid): $err";
369 $async_warn ? carp($msg) : $self->fail($msg);
372 # $git->popen(qw(show f00)); # or
373 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
375 my ($self, $cmd) = splice(@_, 0, 2);
376 $cmd = [ 'git', "--git-dir=$self->{git_dir}",
377 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
378 popen_rd($cmd, grep { !defined || ref } @_); # env and opt
381 # same args as popen above
386 close $fh; # caller should check $?
391 close $fh; # caller should check $?
399 substr($_, length('--max-age='), -1)
400 } $self->qx('rev-parse', map { "--since=$_" } @_);
403 # check_async and cat_async may trigger the other, so ensure they're
404 # both completely done by using this:
405 sub async_wait_all ($) {
407 while (scalar(@{$self->{inflight_c} // []}) ||
408 scalar(@{$self->{inflight} // []})) {
409 check_async_wait($self);
410 cat_async_wait($self);
414 # returns true if there are pending "git cat-file" processes
416 my ($self, $lazy) = @_;
417 return 1 if $lazy && (scalar(@{$self->{inflight_c} // []}) ||
418 scalar(@{$self->{inflight} // []}));
419 local $in_cleanup = 1;
420 delete $self->{async_cat};
421 async_wait_all($self);
422 delete $self->{inflight};
423 delete $self->{inflight_c};
424 _destroy($self, qw(rbuf in out pid));
425 _destroy($self, qw(rbuf_c in_c out_c pid_c err_c));
429 # assuming a well-maintained repo, this should be a somewhat
430 # accurate estimation of its size
431 # TODO: show this in the WWW UI as a hint to potential cloners
435 my $pack_dir = git_path($self, 'objects/pack');
436 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
442 sub DESTROY { cleanup(@_) }
445 # don't show full FS path, basename should be OK:
446 $_[0]->{git_dir} =~ m!/([^/]+?)(?:/*\.git/*)?\z! ? "$1.git" : '???';
449 sub host_prefix_url ($$) {
450 my ($env, $url) = @_;
451 return $url if index($url, '//') >= 0;
452 my $scheme = $env->{'psgi.url_scheme'};
453 my $host_port = $env->{HTTP_HOST} //
454 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
455 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
459 my ($self, $env) = @_;
460 if (my $urls = $self->{cgit_url}) {
461 return map { host_prefix_url($env, $_) } @$urls;
466 sub cat_async_begin {
468 cleanup($self) if $self->alternates_changed;
469 $self->batch_prepare;
470 die 'BUG: already in async' if $self->{inflight};
471 $self->{inflight} = [];
474 sub cat_async ($$$;$) {
475 my ($self, $oid, $cb, $arg) = @_;
476 my $inflight = $self->{inflight} // cat_async_begin($self);
477 while (scalar(@$inflight) >= MAX_INFLIGHT) {
478 cat_async_step($self, $inflight);
480 print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
481 push(@$inflight, $oid, $cb, $arg);
484 # returns the modified time of a git repo, same as the "modified" field
485 # of a grokmirror manifest
487 # committerdate:unix is git 2.9.4+ (2017-05-05), so using raw instead
488 my $fh = popen($_[0], qw[for-each-ref --sort=-committerdate
489 --format=%(committerdate:raw) --count=1]);
490 (split(/ /, <$fh> // time))[0] + 0; # integerize for JSON
493 # for grokmirror, which doesn't read gitweb.description
494 # templates/hooks--update.sample and git-multimail in git.git
495 # only match "Unnamed repository", not the full contents of
496 # templates/this--description in git.git
498 my ($self, $epoch, $default_desc) = @_;
499 my $fh = $self->popen('show-ref');
500 my $dig = Digest::SHA->new(1);
501 while (read($fh, my $buf, 65536)) {
504 close $fh or return; # empty, uninitialized git repo
505 undef $fh; # for open, below
506 my $git_dir = $self->{git_dir};
508 fingerprint => $dig->hexdigest,
510 modified => modified($self),
512 chomp(my $owner = $self->qx('config', 'gitweb.owner'));
513 utf8::decode($owner);
514 $ent->{owner} = $owner eq '' ? undef : $owner;
516 if (open($fh, '<', "$git_dir/description")) {
518 chomp($desc = <$fh>);
521 $desc = 'Unnamed repository' if $desc eq '';
522 if (defined $epoch && $desc =~ /\AUnnamed repository/) {
523 $desc = "$default_desc [epoch $epoch]";
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.
530 chomp(my @alt = <$fh>);
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;
543 # returns true if there are pending cat-file processes
544 sub cleanup_if_unlinked {
546 return cleanup($self, 1) if $^O ne 'linux';
547 # Linux-specific /proc/$PID/maps access
548 # TODO: support this inside git.git
550 for my $fld (qw(pid pid_c)) {
551 my $pid = $self->{$fld} // next;
552 open my $fh, '<', "/proc/$pid/maps" or return cleanup($self, 1);
554 # n.b. we do not restart for unlinked multi-pack-index
555 # since it's not too huge, and the startup cost may
557 /\.(?:idx|pack) \(deleted\)$/ and
558 return cleanup($self, 1);
571 PublicInbox::Git - git wrapper
579 use PublicInbox::Git;
580 chomp(my $git_dir = `git rev-parse --git-dir`);
581 $git_dir or die "GIT_DIR= must be specified\n";
582 my $git = PublicInbox::Git->new($git_dir);
586 Unstable API outside of the L</new> method.
587 It requires L<git(1)> to be installed.
595 my $git = PublicInbox::Git->new($git_dir);
597 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
598 This is the only public API method we support. Everything else
599 in this module is subject to change.
603 L<Git>, L<PublicInbox::Import>
607 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
609 The mail archives are hosted at L<https://public-inbox.org/meta/>
613 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
615 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>