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>
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);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
24 our @EXPORT_OK = qw(git_unquote git_quote);
25 our $PIPE_BUFSIZ = 65536; # Linux default
27 our $RDTIMEO = 60_000; # milliseconds
29 use constant MAX_INFLIGHT =>
30 (($^O eq 'linux' ? 4096 : POSIX::_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])/$GIT_ESC{$1}/g;
53 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
58 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
59 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
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
72 my ($self, $path) = @_;
73 $self->{-git_path}->{$path} ||= do {
75 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
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";
85 sub alternates_changed {
87 my $alt = git_path($self, 'objects/info/alternates');
88 my @st = stat($alt) or return 0;
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
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: $!");
106 my ($self, $batch, $in, $out, $pid, $err) = @_;
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: $!");
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 };
121 my $id = "git.$self->{git_dir}$batch.err";
122 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
126 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
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';
133 $self->{$out} = $out_w;
134 $self->{$in} = $in_r;
137 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
140 my ($fh, $rbuf, $len) = @_;
141 my $left = $len - length($$rbuf);
144 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
147 } elsif (defined($r)) { # EOF
150 next if ($! == EAGAIN and poll_in($fh));
151 next if $! == EINTR; # may be set by sysread or poll_in
152 return; # unrecoverable error
155 \substr($$rbuf, 0, $len, '');
158 sub my_readline ($$) {
159 my ($fh, $rbuf) = @_;
161 if ((my $n = index($$rbuf, "\n")) >= 0) {
162 return substr($$rbuf, 0, $n + 1, '');
164 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
167 # return whatever's left on EOF
168 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
170 next if ($! == EAGAIN and poll_in($fh));
171 next if $! == EINTR; # may be set by sysread or poll_in
172 return; # unrecoverable error
176 sub cat_async_retry ($$$$$) {
177 my ($self, $inflight, $req, $cb, $arg) = @_;
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};
184 $self->{inflight} = $inflight;
185 batch_prepare($self);
187 for (my $i = 0; $i < @$inflight; $i += 3) {
188 $buf .= "$inflight->[$i]\n";
190 print { $self->{out} } $buf or $self->fail("write error: $!");
191 unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
193 cat_async_step($self, $inflight); # take one step
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) {
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,
218 $oid = ref($req) ? $$req : $req if $oid eq '';
220 my $err = $! ? " ($!)" : '';
221 $self->fail("bad result from async cat-file: $head$err");
223 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
224 eval { $cb->($bref, $oid, $type, $size, $arg) };
225 warn "E: $oid: $@\n" if $@;
228 sub cat_async_wait ($) {
230 my $inflight = $self->{inflight} or return;
231 while (scalar(@$inflight)) {
232 cat_async_step($self, $inflight);
236 sub batch_prepare ($) {
237 _bidi_pipe($_[0], qw(--batch in out pid));
241 my ($bref, undef, undef, $size, $result) = @_;
242 @$result = ($bref, $size);
246 my ($self, $oid, $sizeref) = @_;
248 cat_async($self, $oid, \&_cat_file_cb, $result);
249 cat_async_wait($self);
250 $$sizeref = $result->[1] if $sizeref;
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);
262 # Future versions of git.git may have type=ambiguous, but for now,
263 # we must handle 'dangling' below (and maybe some other oddball
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;
270 $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
271 eval { $cb->($hex, $type, $size, $arg, $self) };
272 warn "E: check($req) $@\n" if $@;
275 sub check_async_wait ($) {
277 my $inflight_c = $self->{inflight_c} or return;
278 while (scalar(@$inflight_c)) {
279 check_async_step($self, $inflight_c);
283 sub check_async_begin ($) {
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} = [];
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);
297 print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
298 push(@$inflight_c, $oid, $cb, $arg);
301 sub _check_cb { # check_async callback
302 my ($hex, $type, $size, $result) = @_;
303 @$result = ($hex, $type, $size);
307 my ($self, $oid) = @_;
309 check_async($self, $oid, \&_check_cb, $result);
310 check_async_wait($self);
311 my ($hex, $type, $size) = @$result;
313 # Future versions of git.git may show 'ambiguous', but for now,
314 # we must handle 'dangling' below (and maybe some other oddball
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);
323 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
324 delete @$self{($rbuf, $in, $out)};
325 delete $self->{$err} if $err; # `err_c'
327 # GitAsyncCat::event_step may delete {pid}
328 my $p = delete $self->{$pid} or return;
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
335 sub cat_async_abort ($) {
337 if (my $inflight = $self->{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 $@;
344 delete $self->{cat_rbuf};
345 delete $self->{inflight};
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");
357 my ($self, @cmd) = @_;
358 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
363 my ($self, @cmd) = @_;
364 my $fh = $self->popen(@cmd);
365 local $/ = wantarray ? "\n" : undef;
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 ($) {
373 while (scalar(@{$self->{inflight_c} // []}) ||
374 scalar(@{$self->{inflight} // []})) {
375 $self->check_async_wait;
376 $self->cat_async_wait;
380 # returns true if there are pending "git cat-file" processes
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});
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
400 my $pack_dir = git_path($self, 'objects/pack');
401 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
407 sub DESTROY { cleanup(@_) }
412 # don't show full FS path, basename should be OK:
413 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
414 $ret = "/path/to/$1";
416 wantarray ? ($ret) : $ret;
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;
429 my ($self, $env) = @_;
430 if (my $urls = $self->{cgit_url}) {
431 return map { host_prefix_url($env, $_) } @$urls;
436 sub cat_async_begin {
438 cleanup($self) if $self->alternates_changed;
439 $self->batch_prepare;
440 die 'BUG: already in async' if $self->{inflight};
441 $self->{inflight} = [];
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);
450 print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
451 push(@$inflight, $oid, $cb, $arg);
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);
468 sub extract_cmt_time {
469 my ($bref, undef, undef, undef, $modified) = @_;
471 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
472 my $cmt_time = $1 + 0;
473 $$modified = $cmt_time if $cmt_time > $$modified;
477 # returns the modified time of a git repo, same as the "modified" field
478 # of a grokmirror manifest
482 my $fh = popen($self, qw(rev-parse --branches));
484 while (my $oid = <$fh>) {
486 cat_async($self, $oid, \&extract_cmt_time, \$modified);
488 cat_async_wait($self);
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
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)) {
505 return if $?; # empty, uninitialized git repo
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;
549 PublicInbox::Git - git wrapper
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);
564 Unstable API outside of the L</new> method.
565 It requires L<git(1)> to be installed.
573 my $git = PublicInbox::Git->new($git_dir);
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.
581 L<Git>, L<PublicInbox::Import>
585 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
587 The mail archives are hosted at L<https://public-inbox.org/meta/>
591 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
593 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>