]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
get rid of unnecessary bytes::length usage
[public-inbox.git] / lib / PublicInbox / Git.pm
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>
3 #
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;
10 use strict;
11 use v5.10.1;
12 use parent qw(Exporter);
13 use POSIX ();
14 use IO::Handle; # ->autoflush
15 use Errno qw(EINTR EAGAIN);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
17 use File::Spec ();
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
22 use Carp qw(croak);
23 use Digest::SHA ();
24 use PublicInbox::DS qw(dwaitpid);
25 our @EXPORT_OK = qw(git_unquote git_quote);
26 our $PIPE_BUFSIZ = 65536; # Linux default
27 our $in_cleanup;
28 our $RDTIMEO = 60_000; # milliseconds
29
30 use constant MAX_INFLIGHT =>
31         (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
32         /
33         65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
34
35 my %GIT_ESC = (
36         a => "\a",
37         b => "\b",
38         f => "\f",
39         n => "\n",
40         r => "\r",
41         t => "\t",
42         v => "\013",
43         '"' => '"',
44         '\\' => '\\',
45 );
46 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
47
48
49 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
50 sub git_unquote ($) {
51         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
52         $_[0] = $1;
53         $_[0] =~ s!\\([\\"abfnrtv]|[0-3][0-7]{2})!$GIT_ESC{$1}//chr(oct($1))!ge;
54         $_[0];
55 }
56
57 sub git_quote ($) {
58         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
59                       '\\'.($ESC_GIT{$1}||sprintf("%03o",ord($1)))/egs) {
60                 return qq{"$_[0]"};
61         }
62         $_[0];
63 }
64
65 sub new {
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
69 }
70
71 sub git_path ($$) {
72         my ($self, $path) = @_;
73         $self->{-git_path}->{$path} ||= do {
74                 local $/ = "\n";
75                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
76
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";
80                 }
81                 $str;
82         };
83 }
84
85 sub alternates_changed {
86         my ($self) = @_;
87         my $alt = git_path($self, 'objects/info/alternates');
88         my @st = stat($alt) or return 0;
89
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
94 }
95
96 sub last_check_err {
97         my ($self) = @_;
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: $!");
102         $buf;
103 }
104
105 sub _bidi_pipe {
106         my ($self, $batch, $in, $out, $pid, $err) = @_;
107         if ($self->{$pid}) {
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: $!");
112                 }
113                 return;
114         }
115         my ($out_r, $out_w);
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 };
120         if ($err) {
121                 my $id = "git.$self->{git_dir}$batch.err";
122                 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
123                 $self->{$err} = $fh;
124                 $redir->{2} = $fh;
125         }
126         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
127         $self->{$pid} = $p;
128         $self->{"$pid.owner"} = $$;
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';
133         }
134         $self->{$out} = $out_w;
135         $self->{$in} = $in_r;
136 }
137
138 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
139
140 sub my_read ($$$) {
141         my ($fh, $rbuf, $len) = @_;
142         my $left = $len - length($$rbuf);
143         my $r;
144         while ($left > 0) {
145                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
146                 if ($r) {
147                         $left -= $r;
148                 } elsif (defined($r)) { # EOF
149                         return 0;
150                 } else {
151                         next if ($! == EAGAIN and poll_in($fh));
152                         next if $! == EINTR; # may be set by sysread or poll_in
153                         return; # unrecoverable error
154                 }
155         }
156         \substr($$rbuf, 0, $len, '');
157 }
158
159 sub my_readline ($$) {
160         my ($fh, $rbuf) = @_;
161         while (1) {
162                 if ((my $n = index($$rbuf, "\n")) >= 0) {
163                         return substr($$rbuf, 0, $n + 1, '');
164                 }
165                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
166                                                                 and next;
167
168                 # return whatever's left on EOF
169                 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
170
171                 next if ($! == EAGAIN and poll_in($fh));
172                 next if $! == EINTR; # may be set by sysread or poll_in
173                 return; # unrecoverable error
174         }
175 }
176
177 sub cat_async_retry ($$$$$) {
178         my ($self, $inflight, $req, $cb, $arg) = @_;
179
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};
183         cleanup($self);
184
185         $self->{inflight} = $inflight;
186         batch_prepare($self);
187         my $buf = "$req\n";
188         for (my $i = 0; $i < @$inflight; $i += 3) {
189                 $buf .= "$inflight->[$i]\n";
190         }
191         print { $self->{out} } $buf or $self->fail("write error: $!");
192         unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
193
194         cat_async_step($self, $inflight); # take one step
195 }
196
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) {
211                 $oid = $head;
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,
216                                                 $req, $cb, $arg);
217                 }
218                 $type = 'missing';
219                 $oid = ref($req) ? $$req : $req if $oid eq '';
220         } else {
221                 my $err = $! ? " ($!)" : '';
222                 $self->fail("bad result from async cat-file: $head$err");
223         }
224         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
225         eval { $cb->($bref, $oid, $type, $size, $arg) };
226         warn "E: $oid: $@\n" if $@;
227 }
228
229 sub cat_async_wait ($) {
230         my ($self) = @_;
231         my $inflight = $self->{inflight} or return;
232         while (scalar(@$inflight)) {
233                 cat_async_step($self, $inflight);
234         }
235 }
236
237 sub batch_prepare ($) {
238         _bidi_pipe($_[0], qw(--batch in out pid));
239 }
240
241 sub _cat_file_cb {
242         my ($bref, $oid, $type, $size, $result) = @_;
243         @$result = ($bref, $oid, $type, $size);
244 }
245
246 sub cat_file {
247         my ($self, $oid) = @_;
248         my $result = [];
249         cat_async($self, $oid, \&_cat_file_cb, $result);
250         cat_async_wait($self);
251         wantarray ? @$result : $result->[0];
252 }
253
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);
261
262         # Future versions of git.git may have type=ambiguous, but for now,
263         # we must handle 'dangling' below (and maybe some other oddball
264         # stuff):
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;
269         }
270         $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
271         eval { $cb->($hex, $type, $size, $arg, $self) };
272         warn "E: check($req) $@\n" if $@;
273 }
274
275 sub check_async_wait ($) {
276         my ($self) = @_;
277         my $inflight_c = $self->{inflight_c} or return;
278         while (scalar(@$inflight_c)) {
279                 check_async_step($self, $inflight_c);
280         }
281 }
282
283 sub check_async_begin ($) {
284         my ($self) = @_;
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} = [];
289 }
290
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);
296         }
297         print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
298         push(@$inflight_c, $oid, $cb, $arg);
299 }
300
301 sub _check_cb { # check_async callback
302         my ($hex, $type, $size, $result) = @_;
303         @$result = ($hex, $type, $size);
304 }
305
306 sub check {
307         my ($self, $oid) = @_;
308         my $result = [];
309         check_async($self, $oid, \&_check_cb, $result);
310         check_async_wait($self);
311         my ($hex, $type, $size) = @$result;
312
313         # Future versions of git.git may show 'ambiguous', but for now,
314         # we must handle 'dangling' below (and maybe some other oddball
315         # stuff):
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);
320 }
321
322 sub _destroy {
323         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
324         delete @$self{($rbuf, $in, $out)};
325         delete $self->{$err} if $err; # `err_c'
326
327         # GitAsyncCat::event_step may delete {pid}
328         my $p = delete $self->{$pid} or return;
329         dwaitpid($p) if $$ == $self->{"$pid.owner"};
330 }
331
332 sub cat_async_abort ($) {
333         my ($self) = @_;
334         if (my $inflight = $self->{inflight}) {
335                 while (@$inflight) {
336                         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
337                         $req =~ s/ .*//; # drop git_dir for Gcf2Client
338                         eval { $cb->(undef, $req, undef, undef, $arg) };
339                         warn "E: $req: $@ (in abort)\n" if $@;
340                 }
341                 delete $self->{cat_rbuf};
342                 delete $self->{inflight};
343         }
344         cleanup($self);
345 }
346
347 sub fail { # may be augmented in subclasses
348         my ($self, $msg) = @_;
349         cat_async_abort($self);
350         croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
351 }
352
353 # $git->popen(qw(show f00)); # or
354 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
355 sub popen {
356         my ($self, $cmd) = splice(@_, 0, 2);
357         $cmd = [ 'git', "--git-dir=$self->{git_dir}",
358                 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
359         popen_rd($cmd, grep { !defined || ref } @_); # env and opt
360 }
361
362 # same args as popen above
363 sub qx {
364         my $fh = popen(@_);
365         if (wantarray) {
366                 my @ret = <$fh>;
367                 close $fh; # caller should check $?
368                 @ret;
369         } else {
370                 local $/;
371                 my $ret = <$fh>;
372                 close $fh; # caller should check $?
373                 $ret;
374         }
375 }
376
377 sub date_parse {
378         my $self = shift;
379         map {
380                 substr($_, length('--max-age='), -1)
381         } $self->qx('rev-parse', map { "--since=$_" } @_);
382 }
383
384 # check_async and cat_async may trigger the other, so ensure they're
385 # both completely done by using this:
386 sub async_wait_all ($) {
387         my ($self) = @_;
388         while (scalar(@{$self->{inflight_c} // []}) ||
389                         scalar(@{$self->{inflight} // []})) {
390                 $self->check_async_wait;
391                 $self->cat_async_wait;
392         }
393 }
394
395 # returns true if there are pending "git cat-file" processes
396 sub cleanup {
397         my ($self) = @_;
398         local $in_cleanup = 1;
399         delete $self->{async_cat};
400         async_wait_all($self);
401         delete $self->{inflight};
402         delete $self->{inflight_c};
403         _destroy($self, qw(cat_rbuf in out pid));
404         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
405         !!($self->{pid} || $self->{pid_c});
406 }
407
408
409 # assuming a well-maintained repo, this should be a somewhat
410 # accurate estimation of its size
411 # TODO: show this in the WWW UI as a hint to potential cloners
412 sub packed_bytes {
413         my ($self) = @_;
414         my $n = 0;
415         my $pack_dir = git_path($self, 'objects/pack');
416         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
417                 $n += -s $p;
418         }
419         $n
420 }
421
422 sub DESTROY { cleanup(@_) }
423
424 sub local_nick ($) {
425         my ($self) = @_;
426         my $ret = '???';
427         # don't show full FS path, basename should be OK:
428         if ($self->{git_dir} =~ m!/([^/]+)(?:/*\.git/*)?\z!) {
429                 $ret = "$1.git";
430         }
431         wantarray ? ($ret) : $ret;
432 }
433
434 sub host_prefix_url ($$) {
435         my ($env, $url) = @_;
436         return $url if index($url, '//') >= 0;
437         my $scheme = $env->{'psgi.url_scheme'};
438         my $host_port = $env->{HTTP_HOST} //
439                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
440         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
441 }
442
443 sub pub_urls {
444         my ($self, $env) = @_;
445         if (my $urls = $self->{cgit_url}) {
446                 return map { host_prefix_url($env, $_) } @$urls;
447         }
448         local_nick($self);
449 }
450
451 sub cat_async_begin {
452         my ($self) = @_;
453         cleanup($self) if $self->alternates_changed;
454         $self->batch_prepare;
455         die 'BUG: already in async' if $self->{inflight};
456         $self->{inflight} = [];
457 }
458
459 sub cat_async ($$$;$) {
460         my ($self, $oid, $cb, $arg) = @_;
461         my $inflight = $self->{inflight} // cat_async_begin($self);
462         while (scalar(@$inflight) >= MAX_INFLIGHT) {
463                 cat_async_step($self, $inflight);
464         }
465         print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
466         push(@$inflight, $oid, $cb, $arg);
467 }
468
469 sub extract_cmt_time {
470         my ($bref, undef, undef, undef, $modified) = @_;
471
472         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
473                 my $cmt_time = $1 + 0;
474                 $$modified = $cmt_time if $cmt_time > $$modified;
475         }
476 }
477
478 # returns the modified time of a git repo, same as the "modified" field
479 # of a grokmirror manifest
480 sub modified ($) {
481         my ($self) = @_;
482         my $modified = 0;
483         my $fh = popen($self, qw(rev-parse --branches));
484         local $/ = "\n";
485         while (my $oid = <$fh>) {
486                 chomp $oid;
487                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
488         }
489         cat_async_wait($self);
490         $modified || time;
491 }
492
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
497 sub manifest_entry {
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)) {
502                 $dig->add($buf);
503         }
504         close $fh or return; # empty, uninitialized git repo
505         undef $fh; # for open, below
506         my $git_dir = $self->{git_dir};
507         my $ent = {
508                 fingerprint => $dig->hexdigest,
509                 reference => undef,
510                 modified => modified($self),
511         };
512         chomp(my $owner = $self->qx('config', 'gitweb.owner'));
513         utf8::decode($owner);
514         $ent->{owner} = $owner eq '' ? undef : $owner;
515         my $desc = '';
516         if (open($fh, '<', "$git_dir/description")) {
517                 local $/ = "\n";
518                 chomp($desc = <$fh>);
519                 utf8::decode($desc);
520         }
521         $desc = 'Unnamed repository' if $desc eq '';
522         if (defined $epoch && $desc =~ /\AUnnamed repository/) {
523                 $desc = "$default_desc [epoch $epoch]";
524         }
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.
529                 local $/ = "\n";
530                 chomp(my @alt = <$fh>);
531
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;
538                 }
539         }
540         $ent;
541 }
542
543 1;
544 __END__
545 =pod
546
547 =head1 NAME
548
549 PublicInbox::Git - git wrapper
550
551 =head1 VERSION
552
553 version 1.0
554
555 =head1 SYNOPSIS
556
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);
561
562 =head1 DESCRIPTION
563
564 Unstable API outside of the L</new> method.
565 It requires L<git(1)> to be installed.
566
567 =head1 METHODS
568
569 =cut
570
571 =head2 new
572
573         my $git = PublicInbox::Git->new($git_dir);
574
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.
578
579 =head1 SEE ALSO
580
581 L<Git>, L<PublicInbox::Import>
582
583 =head1 CONTACT
584
585 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
586
587 The mail archives are hosted at L<https://public-inbox.org/meta/>
588
589 =head1 COPYRIGHT
590
591 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
592
593 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
594
595 =cut