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