]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
lei_store: quiet down "git var" failures
[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])/$GIT_ESC{$1}/g;
54         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
55         $_[0];
56 }
57
58 sub git_quote ($) {
59         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
60                       '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
61                 return qq{"$_[0]"};
62         }
63         $_[0];
64 }
65
66 sub new {
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
70 }
71
72 sub git_path ($$) {
73         my ($self, $path) = @_;
74         $self->{-git_path}->{$path} ||= do {
75                 local $/ = "\n";
76                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
77
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";
81                 }
82                 $str;
83         };
84 }
85
86 sub alternates_changed {
87         my ($self) = @_;
88         my $alt = git_path($self, 'objects/info/alternates');
89         my @st = stat($alt) or return 0;
90
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
95 }
96
97 sub last_check_err {
98         my ($self) = @_;
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: $!");
103         $buf;
104 }
105
106 sub _bidi_pipe {
107         my ($self, $batch, $in, $out, $pid, $err) = @_;
108         if ($self->{$pid}) {
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: $!");
113                 }
114                 return;
115         }
116         my ($out_r, $out_w);
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 };
121         if ($err) {
122                 my $id = "git.$self->{git_dir}$batch.err";
123                 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
124                 $self->{$err} = $fh;
125                 $redir->{2} = $fh;
126         }
127         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
128         $self->{$pid} = $p;
129         $self->{"$pid.owner"} = $$;
130         $out_w->autoflush(1);
131         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
132                 fcntl($out_w, 1031, 4096);
133                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
134         }
135         $self->{$out} = $out_w;
136         $self->{$in} = $in_r;
137 }
138
139 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
140
141 sub my_read ($$$) {
142         my ($fh, $rbuf, $len) = @_;
143         my $left = $len - length($$rbuf);
144         my $r;
145         while ($left > 0) {
146                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
147                 if ($r) {
148                         $left -= $r;
149                 } elsif (defined($r)) { # EOF
150                         return 0;
151                 } else {
152                         next if ($! == EAGAIN and poll_in($fh));
153                         next if $! == EINTR; # may be set by sysread or poll_in
154                         return; # unrecoverable error
155                 }
156         }
157         \substr($$rbuf, 0, $len, '');
158 }
159
160 sub my_readline ($$) {
161         my ($fh, $rbuf) = @_;
162         while (1) {
163                 if ((my $n = index($$rbuf, "\n")) >= 0) {
164                         return substr($$rbuf, 0, $n + 1, '');
165                 }
166                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
167                                                                 and next;
168
169                 # return whatever's left on EOF
170                 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
171
172                 next if ($! == EAGAIN and poll_in($fh));
173                 next if $! == EINTR; # may be set by sysread or poll_in
174                 return; # unrecoverable error
175         }
176 }
177
178 sub cat_async_retry ($$$$$) {
179         my ($self, $inflight, $req, $cb, $arg) = @_;
180
181         # {inflight} may be non-existent, but if it isn't we delete it
182         # here to prevent cleanup() from waiting:
183         delete $self->{inflight};
184         cleanup($self);
185
186         $self->{inflight} = $inflight;
187         batch_prepare($self);
188         my $buf = "$req\n";
189         for (my $i = 0; $i < @$inflight; $i += 3) {
190                 $buf .= "$inflight->[$i]\n";
191         }
192         print { $self->{out} } $buf or $self->fail("write error: $!");
193         unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
194
195         cat_async_step($self, $inflight); # take one step
196 }
197
198 sub cat_async_step ($$) {
199         my ($self, $inflight) = @_;
200         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
201         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
202         my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
203         my ($bref, $oid, $type, $size);
204         my $head = my_readline($self->{in}, $rbuf);
205         # ->fail may be called via Gcf2Client.pm
206         if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
207                 ($oid, $type, $size) = ($1, $2, $3 + 0);
208                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
209                         $self->fail(defined($bref) ? 'read EOF' : "read: $!");
210                 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
211         } elsif ($head =~ s/ missing\n//s) {
212                 $oid = $head;
213                 # ref($req) indicates it's already been retried
214                 # -gcf2 retries internally, so it never hits this path:
215                 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
216                         return cat_async_retry($self, $inflight,
217                                                 $req, $cb, $arg);
218                 }
219                 $type = 'missing';
220                 $oid = ref($req) ? $$req : $req if $oid eq '';
221         } else {
222                 my $err = $! ? " ($!)" : '';
223                 $self->fail("bad result from async cat-file: $head$err");
224         }
225         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
226         eval { $cb->($bref, $oid, $type, $size, $arg) };
227         warn "E: $oid: $@\n" if $@;
228 }
229
230 sub cat_async_wait ($) {
231         my ($self) = @_;
232         my $inflight = $self->{inflight} or return;
233         while (scalar(@$inflight)) {
234                 cat_async_step($self, $inflight);
235         }
236 }
237
238 sub batch_prepare ($) {
239         _bidi_pipe($_[0], qw(--batch in out pid));
240 }
241
242 sub _cat_file_cb {
243         my ($bref, undef, undef, $size, $result) = @_;
244         @$result = ($bref, $size);
245 }
246
247 sub cat_file {
248         my ($self, $oid, $sizeref) = @_;
249         my $result = [];
250         cat_async($self, $oid, \&_cat_file_cb, $result);
251         cat_async_wait($self);
252         $$sizeref = $result->[1] if $sizeref;
253         $result->[0];
254 }
255
256 sub check_async_step ($$) {
257         my ($self, $inflight_c) = @_;
258         die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
259         my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
260         my $rbuf = delete($self->{chk_rbuf}) // \(my $new = '');
261         chomp(my $line = my_readline($self->{in_c}, $rbuf));
262         my ($hex, $type, $size) = split(/ /, $line);
263
264         # Future versions of git.git may have type=ambiguous, but for now,
265         # we must handle 'dangling' below (and maybe some other oddball
266         # stuff):
267         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
268         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
269                 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
270                 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
271         }
272         $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
273         eval { $cb->($hex, $type, $size, $arg, $self) };
274         warn "E: check($req) $@\n" if $@;
275 }
276
277 sub check_async_wait ($) {
278         my ($self) = @_;
279         my $inflight_c = $self->{inflight_c} or return;
280         while (scalar(@$inflight_c)) {
281                 check_async_step($self, $inflight_c);
282         }
283 }
284
285 sub check_async_begin ($) {
286         my ($self) = @_;
287         cleanup($self) if alternates_changed($self);
288         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
289         die 'BUG: already in async check' if $self->{inflight_c};
290         $self->{inflight_c} = [];
291 }
292
293 sub check_async ($$$$) {
294         my ($self, $oid, $cb, $arg) = @_;
295         my $inflight_c = $self->{inflight_c} // check_async_begin($self);
296         while (scalar(@$inflight_c) >= MAX_INFLIGHT) {
297                 check_async_step($self, $inflight_c);
298         }
299         print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
300         push(@$inflight_c, $oid, $cb, $arg);
301 }
302
303 sub _check_cb { # check_async callback
304         my ($hex, $type, $size, $result) = @_;
305         @$result = ($hex, $type, $size);
306 }
307
308 sub check {
309         my ($self, $oid) = @_;
310         my $result = [];
311         check_async($self, $oid, \&_check_cb, $result);
312         check_async_wait($self);
313         my ($hex, $type, $size) = @$result;
314
315         # Future versions of git.git may show 'ambiguous', but for now,
316         # we must handle 'dangling' below (and maybe some other oddball
317         # stuff):
318         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
319         return if $type eq 'missing' || $type eq 'ambiguous';
320         return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
321         ($hex, $type, $size);
322 }
323
324 sub _destroy {
325         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
326         delete @$self{($rbuf, $in, $out)};
327         delete $self->{$err} if $err; # `err_c'
328
329         # GitAsyncCat::event_step may delete {pid}
330         my $p = delete $self->{$pid} or return;
331         dwaitpid($p) if $$ == $self->{"$pid.owner"};
332 }
333
334 sub cat_async_abort ($) {
335         my ($self) = @_;
336         if (my $inflight = $self->{inflight}) {
337                 while (@$inflight) {
338                         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
339                         $req =~ s/ .*//; # drop git_dir for Gcf2Client
340                         eval { $cb->(undef, $req, undef, undef, $arg) };
341                         warn "E: $req: $@ (in abort)\n" if $@;
342                 }
343                 delete $self->{cat_rbuf};
344                 delete $self->{inflight};
345         }
346         cleanup($self);
347 }
348
349 sub fail { # may be augmented in subclasses
350         my ($self, $msg) = @_;
351         cat_async_abort($self);
352         croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
353 }
354
355 # $git->popen(qw(show f00)); # or
356 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
357 sub popen {
358         my ($self, $cmd) = splice(@_, 0, 2);
359         $cmd = [ 'git', "--git-dir=$self->{git_dir}",
360                 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
361         popen_rd($cmd, grep { !defined || ref } @_); # env and opt
362 }
363
364 # same args as popen above
365 sub qx {
366         my $self = shift;
367         my $fh = $self->popen(@_);
368         local $/ = wantarray ? "\n" : undef;
369         <$fh>;
370 }
371
372 # check_async and cat_async may trigger the other, so ensure they're
373 # both completely done by using this:
374 sub async_wait_all ($) {
375         my ($self) = @_;
376         while (scalar(@{$self->{inflight_c} // []}) ||
377                         scalar(@{$self->{inflight} // []})) {
378                 $self->check_async_wait;
379                 $self->cat_async_wait;
380         }
381 }
382
383 # returns true if there are pending "git cat-file" processes
384 sub cleanup {
385         my ($self) = @_;
386         local $in_cleanup = 1;
387         delete $self->{async_cat};
388         async_wait_all($self);
389         delete $self->{inflight};
390         delete $self->{inflight_c};
391         _destroy($self, qw(cat_rbuf in out pid));
392         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
393         !!($self->{pid} || $self->{pid_c});
394 }
395
396
397 # assuming a well-maintained repo, this should be a somewhat
398 # accurate estimation of its size
399 # TODO: show this in the WWW UI as a hint to potential cloners
400 sub packed_bytes {
401         my ($self) = @_;
402         my $n = 0;
403         my $pack_dir = git_path($self, 'objects/pack');
404         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
405                 $n += -s $p;
406         }
407         $n
408 }
409
410 sub DESTROY { cleanup(@_) }
411
412 sub local_nick ($) {
413         my ($self) = @_;
414         my $ret = '???';
415         # don't show full FS path, basename should be OK:
416         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
417                 $ret = "/path/to/$1";
418         }
419         wantarray ? ($ret) : $ret;
420 }
421
422 sub host_prefix_url ($$) {
423         my ($env, $url) = @_;
424         return $url if index($url, '//') >= 0;
425         my $scheme = $env->{'psgi.url_scheme'};
426         my $host_port = $env->{HTTP_HOST} //
427                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
428         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
429 }
430
431 sub pub_urls {
432         my ($self, $env) = @_;
433         if (my $urls = $self->{cgit_url}) {
434                 return map { host_prefix_url($env, $_) } @$urls;
435         }
436         local_nick($self);
437 }
438
439 sub cat_async_begin {
440         my ($self) = @_;
441         cleanup($self) if $self->alternates_changed;
442         $self->batch_prepare;
443         die 'BUG: already in async' if $self->{inflight};
444         $self->{inflight} = [];
445 }
446
447 sub cat_async ($$$;$) {
448         my ($self, $oid, $cb, $arg) = @_;
449         my $inflight = $self->{inflight} // cat_async_begin($self);
450         while (scalar(@$inflight) >= MAX_INFLIGHT) {
451                 cat_async_step($self, $inflight);
452         }
453         print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
454         push(@$inflight, $oid, $cb, $arg);
455 }
456
457 sub async_prefetch {
458         my ($self, $oid, $cb, $arg) = @_;
459         if (my $inflight = $self->{inflight}) {
460                 # we could use MAX_INFLIGHT here w/o the halving,
461                 # but lets not allow one client to monopolize a git process
462                 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
463                         print { $self->{out} } $oid, "\n" or
464                                                 $self->fail("write error: $!");
465                         return push(@$inflight, $oid, $cb, $arg);
466                 }
467         }
468         undef;
469 }
470
471 sub extract_cmt_time {
472         my ($bref, undef, undef, undef, $modified) = @_;
473
474         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
475                 my $cmt_time = $1 + 0;
476                 $$modified = $cmt_time if $cmt_time > $$modified;
477         }
478 }
479
480 # returns the modified time of a git repo, same as the "modified" field
481 # of a grokmirror manifest
482 sub modified ($) {
483         my ($self) = @_;
484         my $modified = 0;
485         my $fh = popen($self, qw(rev-parse --branches));
486         local $/ = "\n";
487         while (my $oid = <$fh>) {
488                 chomp $oid;
489                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
490         }
491         cat_async_wait($self);
492         $modified || time;
493 }
494
495 # for grokmirror, which doesn't read gitweb.description
496 # templates/hooks--update.sample and git-multimail in git.git
497 # only match "Unnamed repository", not the full contents of
498 # templates/this--description in git.git
499 sub manifest_entry {
500         my ($self, $epoch, $default_desc) = @_;
501         my ($fh, $pid) = $self->popen('show-ref');
502         my $dig = Digest::SHA->new(1);
503         while (read($fh, my $buf, 65536)) {
504                 $dig->add($buf);
505         }
506         close $fh;
507         waitpid($pid, 0);
508         return if $?; # empty, uninitialized git repo
509         my $git_dir = $self->{git_dir};
510         my $ent = {
511                 fingerprint => $dig->hexdigest,
512                 reference => undef,
513                 modified => modified($self),
514         };
515         chomp(my $owner = $self->qx('config', 'gitweb.owner'));
516         utf8::decode($owner);
517         $ent->{owner} = $owner eq '' ? undef : $owner;
518         my $desc = '';
519         if (open($fh, '<', "$git_dir/description")) {
520                 local $/ = "\n";
521                 chomp($desc = <$fh>);
522                 utf8::decode($desc);
523         }
524         $desc = 'Unnamed repository' if $desc eq '';
525         if (defined $epoch && $desc =~ /\AUnnamed repository/) {
526                 $desc = "$default_desc [epoch $epoch]";
527         }
528         $ent->{description} = $desc;
529         if (open($fh, '<', "$git_dir/objects/info/alternates")) {
530                 # n.b.: GitPython doesn't seem to handle comments or C-quoted
531                 # strings like native git does; and we don't for now, either.
532                 local $/ = "\n";
533                 chomp(my @alt = <$fh>);
534
535                 # grokmirror only supports 1 alternate for "reference",
536                 if (scalar(@alt) == 1) {
537                         my $objdir = "$git_dir/objects";
538                         my $ref = File::Spec->rel2abs($alt[0], $objdir);
539                         $ref =~ s!/[^/]+/?\z!!; # basename
540                         $ent->{reference} = $ref;
541                 }
542         }
543         $ent;
544 }
545
546 1;
547 __END__
548 =pod
549
550 =head1 NAME
551
552 PublicInbox::Git - git wrapper
553
554 =head1 VERSION
555
556 version 1.0
557
558 =head1 SYNOPSIS
559
560         use PublicInbox::Git;
561         chomp(my $git_dir = `git rev-parse --git-dir`);
562         $git_dir or die "GIT_DIR= must be specified\n";
563         my $git = PublicInbox::Git->new($git_dir);
564
565 =head1 DESCRIPTION
566
567 Unstable API outside of the L</new> method.
568 It requires L<git(1)> to be installed.
569
570 =head1 METHODS
571
572 =cut
573
574 =head2 new
575
576         my $git = PublicInbox::Git->new($git_dir);
577
578 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
579 This is the only public API method we support.  Everything else
580 in this module is subject to change.
581
582 =head1 SEE ALSO
583
584 L<Git>, L<PublicInbox::Import>
585
586 =head1 CONTACT
587
588 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
589
590 The mail archives are hosted at L<https://public-inbox.org/meta/>
591
592 =head1 COPYRIGHT
593
594 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
595
596 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
597
598 =cut