]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
rename {pi_config} fields to {pi_cfg}
[public-inbox.git] / lib / PublicInbox / Git.pm
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>
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 our @EXPORT_OK = qw(git_unquote git_quote);
25 our $PIPE_BUFSIZ = 65536; # Linux default
26 our $in_cleanup;
27 our $RDTIMEO = 60_000; # milliseconds
28
29 use constant MAX_INFLIGHT =>
30         (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
31         /
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])/$GIT_ESC{$1}/g;
53         $_[0] =~ s/\\([0-7]{1,3})/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("%0o",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         $out_w->autoflush(1);
129         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
130                 fcntl($out_w, 1031, 4096);
131                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
132         }
133         $self->{$out} = $out_w;
134         $self->{$in} = $in_r;
135 }
136
137 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
138
139 sub my_read ($$$) {
140         my ($fh, $rbuf, $len) = @_;
141         my $left = $len - length($$rbuf);
142         my $r;
143         while ($left > 0) {
144                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
145                 if ($r) {
146                         $left -= $r;
147                 } elsif (defined($r)) { # EOF
148                         return 0;
149                 } else {
150                         next if ($! == EAGAIN and poll_in($fh));
151                         next if $! == EINTR; # may be set by sysread or poll_in
152                         return; # unrecoverable error
153                 }
154         }
155         \substr($$rbuf, 0, $len, '');
156 }
157
158 sub my_readline ($$) {
159         my ($fh, $rbuf) = @_;
160         while (1) {
161                 if ((my $n = index($$rbuf, "\n")) >= 0) {
162                         return substr($$rbuf, 0, $n + 1, '');
163                 }
164                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
165                                                                 and next;
166
167                 # return whatever's left on EOF
168                 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
169
170                 next if ($! == EAGAIN and poll_in($fh));
171                 next if $! == EINTR; # may be set by sysread or poll_in
172                 return; # unrecoverable error
173         }
174 }
175
176 sub cat_async_retry ($$$$$) {
177         my ($self, $inflight, $req, $cb, $arg) = @_;
178
179         # {inflight} may be non-existent, but if it isn't we delete it
180         # here to prevent cleanup() from waiting:
181         delete $self->{inflight};
182         cleanup($self);
183
184         $self->{inflight} = $inflight;
185         batch_prepare($self);
186         my $buf = "$req\n";
187         for (my $i = 0; $i < @$inflight; $i += 3) {
188                 $buf .= "$inflight->[$i]\n";
189         }
190         print { $self->{out} } $buf or $self->fail("write error: $!");
191         unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
192
193         cat_async_step($self, $inflight); # take one step
194 }
195
196 sub cat_async_step ($$) {
197         my ($self, $inflight) = @_;
198         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
199         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
200         my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
201         my ($bref, $oid, $type, $size);
202         my $head = my_readline($self->{in}, $rbuf);
203         # ->fail may be called via Gcf2Client.pm
204         if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
205                 ($oid, $type, $size) = ($1, $2, $3 + 0);
206                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
207                         $self->fail(defined($bref) ? 'read EOF' : "read: $!");
208                 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
209         } elsif ($head =~ s/ missing\n//s) {
210                 $oid = $head;
211                 # ref($req) indicates it's already been retried
212                 # -gcf2 retries internally, so it never hits this path:
213                 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
214                         return cat_async_retry($self, $inflight,
215                                                 $req, $cb, $arg);
216                 }
217                 $type = 'missing';
218                 $oid = ref($req) ? $$req : $req if $oid eq '';
219         } else {
220                 my $err = $! ? " ($!)" : '';
221                 $self->fail("bad result from async cat-file: $head$err");
222         }
223         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
224         eval { $cb->($bref, $oid, $type, $size, $arg) };
225         warn "E: $oid: $@\n" if $@;
226 }
227
228 sub cat_async_wait ($) {
229         my ($self) = @_;
230         my $inflight = $self->{inflight} or return;
231         while (scalar(@$inflight)) {
232                 cat_async_step($self, $inflight);
233         }
234 }
235
236 sub batch_prepare ($) {
237         _bidi_pipe($_[0], qw(--batch in out pid));
238 }
239
240 sub _cat_file_cb {
241         my ($bref, undef, undef, $size, $result) = @_;
242         @$result = ($bref, $size);
243 }
244
245 sub cat_file {
246         my ($self, $oid, $sizeref) = @_;
247         my $result = [];
248         cat_async($self, $oid, \&_cat_file_cb, $result);
249         cat_async_wait($self);
250         $$sizeref = $result->[1] if $sizeref;
251         $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
330         # PublicInbox::DS may not be loaded
331         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
332         waitpid($p, 0) if $@; # wait synchronously if not in event loop
333 }
334
335 sub cat_async_abort ($) {
336         my ($self) = @_;
337         if (my $inflight = $self->{inflight}) {
338                 while (@$inflight) {
339                         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
340                         $req =~ s/ .*//; # drop git_dir for Gcf2Client
341                         eval { $cb->(undef, $req, undef, undef, $arg) };
342                         warn "E: $req: $@ (in abort)\n" if $@;
343                 }
344                 delete $self->{cat_rbuf};
345                 delete $self->{inflight};
346         }
347         cleanup($self);
348 }
349
350 sub fail { # may be augmented in subclasses
351         my ($self, $msg) = @_;
352         cat_async_abort($self);
353         croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
354 }
355
356 sub popen {
357         my ($self, @cmd) = @_;
358         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
359         popen_rd(\@cmd);
360 }
361
362 sub qx {
363         my ($self, @cmd) = @_;
364         my $fh = $self->popen(@cmd);
365         local $/ = "\n";
366         return <$fh> if wantarray;
367         local $/;
368         <$fh>
369 }
370
371 # check_async and cat_async may trigger the other, so ensure they're
372 # both completely done by using this:
373 sub async_wait_all ($) {
374         my ($self) = @_;
375         while (scalar(@{$self->{inflight_c} // []}) ||
376                         scalar(@{$self->{inflight} // []})) {
377                 $self->check_async_wait;
378                 $self->cat_async_wait;
379         }
380 }
381
382 # returns true if there are pending "git cat-file" processes
383 sub cleanup {
384         my ($self) = @_;
385         local $in_cleanup = 1;
386         delete $self->{async_cat};
387         async_wait_all($self);
388         delete $self->{inflight};
389         delete $self->{inflight_c};
390         _destroy($self, qw(cat_rbuf in out pid));
391         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
392         !!($self->{pid} || $self->{pid_c});
393 }
394
395
396 # assuming a well-maintained repo, this should be a somewhat
397 # accurate estimation of its size
398 # TODO: show this in the WWW UI as a hint to potential cloners
399 sub packed_bytes {
400         my ($self) = @_;
401         my $n = 0;
402         my $pack_dir = git_path($self, 'objects/pack');
403         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
404                 $n += -s $p;
405         }
406         $n
407 }
408
409 sub DESTROY { cleanup(@_) }
410
411 sub local_nick ($) {
412         my ($self) = @_;
413         my $ret = '???';
414         # don't show full FS path, basename should be OK:
415         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
416                 $ret = "/path/to/$1";
417         }
418         wantarray ? ($ret) : $ret;
419 }
420
421 sub host_prefix_url ($$) {
422         my ($env, $url) = @_;
423         return $url if index($url, '//') >= 0;
424         my $scheme = $env->{'psgi.url_scheme'};
425         my $host_port = $env->{HTTP_HOST} //
426                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
427         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
428 }
429
430 sub pub_urls {
431         my ($self, $env) = @_;
432         if (my $urls = $self->{cgit_url}) {
433                 return map { host_prefix_url($env, $_) } @$urls;
434         }
435         local_nick($self);
436 }
437
438 sub cat_async_begin {
439         my ($self) = @_;
440         cleanup($self) if $self->alternates_changed;
441         $self->batch_prepare;
442         die 'BUG: already in async' if $self->{inflight};
443         $self->{inflight} = [];
444 }
445
446 sub cat_async ($$$;$) {
447         my ($self, $oid, $cb, $arg) = @_;
448         my $inflight = $self->{inflight} // cat_async_begin($self);
449         while (scalar(@$inflight) >= MAX_INFLIGHT) {
450                 cat_async_step($self, $inflight);
451         }
452         print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
453         push(@$inflight, $oid, $cb, $arg);
454 }
455
456 sub async_prefetch {
457         my ($self, $oid, $cb, $arg) = @_;
458         if (my $inflight = $self->{inflight}) {
459                 # we could use MAX_INFLIGHT here w/o the halving,
460                 # but lets not allow one client to monopolize a git process
461                 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
462                         print { $self->{out} } $oid, "\n" or
463                                                 $self->fail("write error: $!");
464                         return push(@$inflight, $oid, $cb, $arg);
465                 }
466         }
467         undef;
468 }
469
470 sub extract_cmt_time {
471         my ($bref, undef, undef, undef, $modified) = @_;
472
473         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
474                 my $cmt_time = $1 + 0;
475                 $$modified = $cmt_time if $cmt_time > $$modified;
476         }
477 }
478
479 # returns the modified time of a git repo, same as the "modified" field
480 # of a grokmirror manifest
481 sub modified ($) {
482         my ($self) = @_;
483         my $modified = 0;
484         my $fh = popen($self, qw(rev-parse --branches));
485         local $/ = "\n";
486         while (my $oid = <$fh>) {
487                 chomp $oid;
488                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
489         }
490         cat_async_wait($self);
491         $modified || time;
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, $pid) = $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;
506         waitpid($pid, 0);
507         return if $?; # empty, uninitialized git repo
508         my $git_dir = $self->{git_dir};
509         my $ent = {
510                 fingerprint => $dig->hexdigest,
511                 reference => undef,
512                 modified => modified($self),
513         };
514         chomp(my $owner = $self->qx('config', 'gitweb.owner'));
515         utf8::decode($owner);
516         $ent->{owner} = $owner eq '' ? undef : $owner;
517         my $desc = '';
518         if (open($fh, '<', "$git_dir/description")) {
519                 local $/ = "\n";
520                 chomp($desc = <$fh>);
521                 utf8::decode($desc);
522         }
523         $desc = 'Unnamed repository' if $desc eq '';
524         if (defined $epoch && $desc =~ /\AUnnamed repository/) {
525                 $desc = "$default_desc [epoch $epoch]";
526         }
527         $ent->{description} = $desc;
528         if (open($fh, '<', "$git_dir/objects/info/alternates")) {
529                 # n.b.: GitPython doesn't seem to handle comments or C-quoted
530                 # strings like native git does; and we don't for now, either.
531                 local $/ = "\n";
532                 chomp(my @alt = <$fh>);
533
534                 # grokmirror only supports 1 alternate for "reference",
535                 if (scalar(@alt) == 1) {
536                         my $objdir = "$git_dir/objects";
537                         my $ref = File::Spec->rel2abs($alt[0], $objdir);
538                         $ref =~ s!/[^/]+/?\z!!; # basename
539                         $ent->{reference} = $ref;
540                 }
541         }
542         $ent;
543 }
544
545 1;
546 __END__
547 =pod
548
549 =head1 NAME
550
551 PublicInbox::Git - git wrapper
552
553 =head1 VERSION
554
555 version 1.0
556
557 =head1 SYNOPSIS
558
559         use PublicInbox::Git;
560         chomp(my $git_dir = `git rev-parse --git-dir`);
561         $git_dir or die "GIT_DIR= must be specified\n";
562         my $git = PublicInbox::Git->new($git_dir);
563
564 =head1 DESCRIPTION
565
566 Unstable API outside of the L</new> method.
567 It requires L<git(1)> to be installed.
568
569 =head1 METHODS
570
571 =cut
572
573 =head2 new
574
575         my $git = PublicInbox::Git->new($git_dir);
576
577 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
578 This is the only public API method we support.  Everything else
579 in this module is subject to change.
580
581 =head1 SEE ALSO
582
583 L<Git>, L<PublicInbox::Import>
584
585 =head1 CONTACT
586
587 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
588
589 The mail archives are hosted at L<https://public-inbox.org/meta/>
590
591 =head1 COPYRIGHT
592
593 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
594
595 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
596
597 =cut