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 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
30 use constant MAX_INFLIGHT =>
31 (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
33 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
46 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
49 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
51 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
53 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
54 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
59 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
60 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
67 my ($class, $git_dir) = @_;
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: $!");
117 pipe($out_r, $out_w) or $self->fail("pipe failed: $!");
118 my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
119 qw(-c core.abbrev=40 cat-file), $batch);
120 my $redir = { 0 => $out_r };
122 my $id = "git.$self->{git_dir}$batch.err";
123 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
127 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
129 $out_w->autoflush(1);
130 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
131 fcntl($out_w, 1031, 4096);
132 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
134 $self->{$out} = $out_w;
135 $self->{$in} = $in_r;
138 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
141 my ($fh, $rbuf, $len) = @_;
142 my $left = $len - length($$rbuf);
145 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
148 } elsif (defined($r)) { # EOF
151 next if ($! == EAGAIN and poll_in($fh));
152 next if $! == EINTR; # may be set by sysread or poll_in
153 return; # unrecoverable error
156 \substr($$rbuf, 0, $len, '');
159 sub my_readline ($$) {
160 my ($fh, $rbuf) = @_;
162 if ((my $n = index($$rbuf, "\n")) >= 0) {
163 return substr($$rbuf, 0, $n + 1, '');
165 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
168 # return whatever's left on EOF
169 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
171 next if ($! == EAGAIN and poll_in($fh));
172 next if $! == EINTR; # may be set by sysread or poll_in
173 return; # unrecoverable error
177 sub cat_async_retry ($$$$$) {
178 my ($self, $inflight, $req, $cb, $arg) = @_;
180 # {inflight} may be non-existent, but if it isn't we delete it
181 # here to prevent cleanup() from waiting:
182 delete $self->{inflight};
185 $self->{inflight} = $inflight;
186 batch_prepare($self);
188 for (my $i = 0; $i < @$inflight; $i += 3) {
189 $buf .= "$inflight->[$i]\n";
191 print { $self->{out} } $buf or $self->fail("write error: $!");
192 unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
194 cat_async_step($self, $inflight); # take one step
197 sub cat_async_step ($$) {
198 my ($self, $inflight) = @_;
199 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
200 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
201 my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
202 my ($bref, $oid, $type, $size);
203 my $head = my_readline($self->{in}, $rbuf);
204 # ->fail may be called via Gcf2Client.pm
205 if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
206 ($oid, $type, $size) = ($1, $2, $3 + 0);
207 $bref = my_read($self->{in}, $rbuf, $size + 1) or
208 $self->fail(defined($bref) ? 'read EOF' : "read: $!");
209 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
210 } elsif ($head =~ s/ missing\n//s) {
212 # ref($req) indicates it's already been retried
213 # -gcf2 retries internally, so it never hits this path:
214 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
215 return cat_async_retry($self, $inflight,
219 $oid = ref($req) ? $$req : $req if $oid eq '';
221 my $err = $! ? " ($!)" : '';
222 $self->fail("bad result from async cat-file: $head$err");
224 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
225 eval { $cb->($bref, $oid, $type, $size, $arg) };
226 warn "E: $oid: $@\n" if $@;
229 sub cat_async_wait ($) {
231 my $inflight = $self->{inflight} or return;
232 while (scalar(@$inflight)) {
233 cat_async_step($self, $inflight);
237 sub batch_prepare ($) {
238 _bidi_pipe($_[0], qw(--batch in out pid));
242 my ($bref, undef, undef, $size, $result) = @_;
243 @$result = ($bref, $size);
247 my ($self, $oid, $sizeref) = @_;
249 cat_async($self, $oid, \&_cat_file_cb, $result);
250 cat_async_wait($self);
251 $$sizeref = $result->[1] if $sizeref;
255 sub check_async_step ($$) {
256 my ($self, $inflight_c) = @_;
257 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
258 my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
259 my $rbuf = delete($self->{chk_rbuf}) // \(my $new = '');
260 chomp(my $line = my_readline($self->{in_c}, $rbuf));
261 my ($hex, $type, $size) = split(/ /, $line);
263 # Future versions of git.git may have type=ambiguous, but for now,
264 # we must handle 'dangling' below (and maybe some other oddball
266 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
267 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
268 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
269 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
271 $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
272 eval { $cb->($hex, $type, $size, $arg, $self) };
273 warn "E: check($req) $@\n" if $@;
276 sub check_async_wait ($) {
278 my $inflight_c = $self->{inflight_c} or return;
279 while (scalar(@$inflight_c)) {
280 check_async_step($self, $inflight_c);
284 sub check_async_begin ($) {
286 cleanup($self) if alternates_changed($self);
287 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
288 die 'BUG: already in async check' if $self->{inflight_c};
289 $self->{inflight_c} = [];
292 sub check_async ($$$$) {
293 my ($self, $oid, $cb, $arg) = @_;
294 my $inflight_c = $self->{inflight_c} // check_async_begin($self);
295 while (scalar(@$inflight_c) >= MAX_INFLIGHT) {
296 check_async_step($self, $inflight_c);
298 print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
299 push(@$inflight_c, $oid, $cb, $arg);
302 sub _check_cb { # check_async callback
303 my ($hex, $type, $size, $result) = @_;
304 @$result = ($hex, $type, $size);
308 my ($self, $oid) = @_;
310 check_async($self, $oid, \&_check_cb, $result);
311 check_async_wait($self);
312 my ($hex, $type, $size) = @$result;
314 # Future versions of git.git may show 'ambiguous', but for now,
315 # we must handle 'dangling' below (and maybe some other oddball
317 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
318 return if $type eq 'missing' || $type eq 'ambiguous';
319 return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
320 ($hex, $type, $size);
324 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
325 delete @$self{($rbuf, $in, $out)};
326 delete $self->{$err} if $err; # `err_c'
328 # GitAsyncCat::event_step may delete {pid}
329 my $p = delete $self->{$pid} or return;
333 sub cat_async_abort ($) {
335 if (my $inflight = $self->{inflight}) {
337 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
338 $req =~ s/ .*//; # drop git_dir for Gcf2Client
339 eval { $cb->(undef, $req, undef, undef, $arg) };
340 warn "E: $req: $@ (in abort)\n" if $@;
342 delete $self->{cat_rbuf};
343 delete $self->{inflight};
348 sub fail { # may be augmented in subclasses
349 my ($self, $msg) = @_;
350 cat_async_abort($self);
351 croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
355 my ($self, @cmd) = @_;
356 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
361 my ($self, @cmd) = @_;
362 my $fh = $self->popen(@cmd);
363 local $/ = wantarray ? "\n" : undef;
367 # check_async and cat_async may trigger the other, so ensure they're
368 # both completely done by using this:
369 sub async_wait_all ($) {
371 while (scalar(@{$self->{inflight_c} // []}) ||
372 scalar(@{$self->{inflight} // []})) {
373 $self->check_async_wait;
374 $self->cat_async_wait;
378 # returns true if there are pending "git cat-file" processes
381 local $in_cleanup = 1;
382 delete $self->{async_cat};
383 async_wait_all($self);
384 delete $self->{inflight};
385 delete $self->{inflight_c};
386 _destroy($self, qw(cat_rbuf in out pid));
387 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
388 !!($self->{pid} || $self->{pid_c});
392 # assuming a well-maintained repo, this should be a somewhat
393 # accurate estimation of its size
394 # TODO: show this in the WWW UI as a hint to potential cloners
398 my $pack_dir = git_path($self, 'objects/pack');
399 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
405 sub DESTROY { cleanup(@_) }
410 # don't show full FS path, basename should be OK:
411 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
412 $ret = "/path/to/$1";
414 wantarray ? ($ret) : $ret;
417 sub host_prefix_url ($$) {
418 my ($env, $url) = @_;
419 return $url if index($url, '//') >= 0;
420 my $scheme = $env->{'psgi.url_scheme'};
421 my $host_port = $env->{HTTP_HOST} //
422 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
423 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
427 my ($self, $env) = @_;
428 if (my $urls = $self->{cgit_url}) {
429 return map { host_prefix_url($env, $_) } @$urls;
434 sub cat_async_begin {
436 cleanup($self) if $self->alternates_changed;
437 $self->batch_prepare;
438 die 'BUG: already in async' if $self->{inflight};
439 $self->{inflight} = [];
442 sub cat_async ($$$;$) {
443 my ($self, $oid, $cb, $arg) = @_;
444 my $inflight = $self->{inflight} // cat_async_begin($self);
445 while (scalar(@$inflight) >= MAX_INFLIGHT) {
446 cat_async_step($self, $inflight);
448 print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
449 push(@$inflight, $oid, $cb, $arg);
453 my ($self, $oid, $cb, $arg) = @_;
454 if (my $inflight = $self->{inflight}) {
455 # we could use MAX_INFLIGHT here w/o the halving,
456 # but lets not allow one client to monopolize a git process
457 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
458 print { $self->{out} } $oid, "\n" or
459 $self->fail("write error: $!");
460 return push(@$inflight, $oid, $cb, $arg);
466 sub extract_cmt_time {
467 my ($bref, undef, undef, undef, $modified) = @_;
469 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
470 my $cmt_time = $1 + 0;
471 $$modified = $cmt_time if $cmt_time > $$modified;
475 # returns the modified time of a git repo, same as the "modified" field
476 # of a grokmirror manifest
480 my $fh = popen($self, qw(rev-parse --branches));
482 while (my $oid = <$fh>) {
484 cat_async($self, $oid, \&extract_cmt_time, \$modified);
486 cat_async_wait($self);
490 # for grokmirror, which doesn't read gitweb.description
491 # templates/hooks--update.sample and git-multimail in git.git
492 # only match "Unnamed repository", not the full contents of
493 # templates/this--description in git.git
495 my ($self, $epoch, $default_desc) = @_;
496 my ($fh, $pid) = $self->popen('show-ref');
497 my $dig = Digest::SHA->new(1);
498 while (read($fh, my $buf, 65536)) {
503 return if $?; # empty, uninitialized git repo
504 my $git_dir = $self->{git_dir};
506 fingerprint => $dig->hexdigest,
508 modified => modified($self),
510 chomp(my $owner = $self->qx('config', 'gitweb.owner'));
511 utf8::decode($owner);
512 $ent->{owner} = $owner eq '' ? undef : $owner;
514 if (open($fh, '<', "$git_dir/description")) {
516 chomp($desc = <$fh>);
519 $desc = 'Unnamed repository' if $desc eq '';
520 if (defined $epoch && $desc =~ /\AUnnamed repository/) {
521 $desc = "$default_desc [epoch $epoch]";
523 $ent->{description} = $desc;
524 if (open($fh, '<', "$git_dir/objects/info/alternates")) {
525 # n.b.: GitPython doesn't seem to handle comments or C-quoted
526 # strings like native git does; and we don't for now, either.
528 chomp(my @alt = <$fh>);
530 # grokmirror only supports 1 alternate for "reference",
531 if (scalar(@alt) == 1) {
532 my $objdir = "$git_dir/objects";
533 my $ref = File::Spec->rel2abs($alt[0], $objdir);
534 $ref =~ s!/[^/]+/?\z!!; # basename
535 $ent->{reference} = $ref;
547 PublicInbox::Git - git wrapper
555 use PublicInbox::Git;
556 chomp(my $git_dir = `git rev-parse --git-dir`);
557 $git_dir or die "GIT_DIR= must be specified\n";
558 my $git = PublicInbox::Git->new($git_dir);
562 Unstable API outside of the L</new> method.
563 It requires L<git(1)> to be installed.
571 my $git = PublicInbox::Git->new($git_dir);
573 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
574 This is the only public API method we support. Everything else
575 in this module is subject to change.
579 L<Git>, L<PublicInbox::Import>
583 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
585 The mail archives are hosted at L<https://public-inbox.org/meta/>
589 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
591 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>