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