]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
7b2ada243969fd660faca083070d78bb475ea45f
[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);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
17 use Time::HiRes qw(stat);
18 use PublicInbox::Spawn qw(popen_rd);
19 use PublicInbox::Tmpfile;
20 our @EXPORT_OK = qw(git_unquote git_quote);
21 our $PIPE_BUFSIZ = 65536; # Linux default
22 our $in_cleanup;
23
24 use constant MAX_INFLIGHT =>
25         (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
26         /
27         65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
28
29 my %GIT_ESC = (
30         a => "\a",
31         b => "\b",
32         f => "\f",
33         n => "\n",
34         r => "\r",
35         t => "\t",
36         v => "\013",
37         '"' => '"',
38         '\\' => '\\',
39 );
40 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
41
42
43 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
44 sub git_unquote ($) {
45         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
46         $_[0] = $1;
47         $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
48         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
49         $_[0];
50 }
51
52 sub git_quote ($) {
53         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
54                       '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
55                 return qq{"$_[0]"};
56         }
57         $_[0];
58 }
59
60 sub new {
61         my ($class, $git_dir) = @_;
62         # may contain {-tmp} field for File::Temp::Dir
63         bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
64 }
65
66 sub git_path ($$) {
67         my ($self, $path) = @_;
68         $self->{-git_path}->{$path} ||= do {
69                 local $/ = "\n";
70                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
71
72                 # git prior to 2.5.0 did not understand --git-path
73                 if ($str eq "--git-path\n$path") {
74                         $str = "$self->{git_dir}/$path";
75                 }
76                 $str;
77         };
78 }
79
80 sub alternates_changed {
81         my ($self) = @_;
82         my $alt = git_path($self, 'objects/info/alternates');
83         my @st = stat($alt) or return 0;
84
85         # can't rely on 'q' on some 32-bit builds, but `d' works
86         my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
87         return 0 if $self->{alt_st} eq $st;
88         $self->{alt_st} = $st; # always a true value
89 }
90
91 sub last_check_err {
92         my ($self) = @_;
93         my $fh = $self->{err_c} or return;
94         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
95         defined(sysread($fh, my $buf, -s $fh)) or
96                         fail($self, "sysread failed: $!");
97         $buf;
98 }
99
100 sub _bidi_pipe {
101         my ($self, $batch, $in, $out, $pid, $err) = @_;
102         if ($self->{$pid}) {
103                 if (defined $err) { # "err_c"
104                         my $fh = $self->{$err};
105                         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
106                         truncate($fh, 0) or fail($self, "truncate failed: $!");
107                 }
108                 return;
109         }
110         my ($out_r, $out_w);
111         pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
112         my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
113                         qw(-c core.abbrev=40 cat-file), $batch);
114         my $redir = { 0 => $out_r };
115         if ($err) {
116                 my $id = "git.$self->{git_dir}$batch.err";
117                 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
118                 $self->{$err} = $fh;
119                 $redir->{2} = $fh;
120         }
121         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
122         $self->{$pid} = $p;
123         $out_w->autoflush(1);
124         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
125                 fcntl($out_w, 1031, 4096);
126                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
127         }
128         $self->{$out} = $out_w;
129         $self->{$in} = $in_r;
130 }
131
132 sub my_read ($$$) {
133         my ($fh, $rbuf, $len) = @_;
134         my $left = $len - length($$rbuf);
135         my $r;
136         while ($left > 0) {
137                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
138                 if ($r) {
139                         $left -= $r;
140                 } else {
141                         next if (!defined($r) && $! == EINTR);
142                         return $r;
143                 }
144         }
145         \substr($$rbuf, 0, $len, '');
146 }
147
148 sub my_readline ($$) {
149         my ($fh, $rbuf) = @_;
150         while (1) {
151                 if ((my $n = index($$rbuf, "\n")) >= 0) {
152                         return substr($$rbuf, 0, $n + 1, '');
153                 }
154                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
155                 next if $r || (!defined($r) && $! == EINTR);
156                 return defined($r) ? '' : undef; # EOF or error
157         }
158 }
159
160 sub cat_async_retry ($$$$$) {
161         my ($self, $inflight, $req, $cb, $arg) = @_;
162
163         # {inflight} may be non-existent, but if it isn't we delete it
164         # here to prevent cleanup() from waiting:
165         delete $self->{inflight};
166         cleanup($self);
167
168         $self->{inflight} = $inflight;
169         batch_prepare($self);
170         my $buf = "$req\n";
171         for (my $i = 0; $i < @$inflight; $i += 3) {
172                 $buf .= "$inflight->[$i]\n";
173         }
174         print { $self->{out} } $buf or fail($self, "write error: $!");
175         unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
176
177         cat_async_step($self, $inflight); # take one step
178 }
179
180 sub cat_async_step ($$) {
181         my ($self, $inflight) = @_;
182         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
183         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
184         my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
185         my ($bref, $oid, $type, $size);
186         my $head = my_readline($self->{in}, $rbuf);
187         if ($head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/) {
188                 ($oid, $type, $size) = ($1, $2, $3 + 0);
189                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
190                         fail($self, defined($bref) ? 'read EOF' : "read: $!");
191                 chop($$bref) eq "\n" or fail($self, 'LF missing after blob');
192         } elsif ($head =~ / missing$/) {
193                 # ref($req) indicates it's already been retried
194                 if (!ref($req) && !$in_cleanup && alternates_changed($self)) {
195                         return cat_async_retry($self, $inflight,
196                                                 $req, $cb, $arg);
197                 }
198                 $type = 'missing';
199                 $oid = ref($req) ? $$req : $req;
200         } else {
201                 fail($self, "Unexpected result from async git cat-file: $head");
202         }
203         eval { $cb->($bref, $oid, $type, $size, $arg) };
204         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
205         warn "E: $oid: $@\n" if $@;
206 }
207
208 sub cat_async_wait ($) {
209         my ($self) = @_;
210         my $inflight = delete $self->{inflight} or return;
211         while (scalar(@$inflight)) {
212                 cat_async_step($self, $inflight);
213         }
214 }
215
216 sub batch_prepare ($) {
217         _bidi_pipe($_[0], qw(--batch in out pid));
218 }
219
220 sub _cat_file_cb {
221         my ($bref, undef, undef, $size, $result) = @_;
222         @$result = ($bref, $size);
223 }
224
225 sub cat_file {
226         my ($self, $oid, $sizeref) = @_;
227         my $result = [];
228         cat_async($self, $oid, \&_cat_file_cb, $result);
229         cat_async_wait($self);
230         $$sizeref = $result->[1] if $sizeref;
231         $result->[0];
232 }
233
234 sub check_async_step ($$) {
235         my ($self, $inflight_c) = @_;
236         die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
237         my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
238         my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
239         chomp(my $line = my_readline($self->{in_c}, $rbuf));
240         my ($hex, $type, $size) = split(/ /, $line);
241
242         # Future versions of git.git may have type=ambiguous, but for now,
243         # we must handle 'dangling' below (and maybe some other oddball
244         # stuff):
245         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
246         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
247                 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
248                 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
249         }
250         eval { $cb->($hex, $type, $size, $arg, $self) };
251         warn "E: check($req) $@\n" if $@;
252         $self->{rbuf_c} = $rbuf if $$rbuf ne '';
253 }
254
255 sub check_async_wait ($) {
256         my ($self) = @_;
257         my $inflight_c = delete $self->{inflight_c} or return;
258         while (scalar(@$inflight_c)) {
259                 check_async_step($self, $inflight_c);
260         }
261 }
262
263 sub check_async_begin ($) {
264         my ($self) = @_;
265         cleanup($self) if alternates_changed($self);
266         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
267         die 'BUG: already in async check' if $self->{inflight_c};
268         $self->{inflight_c} = [];
269 }
270
271 sub check_async ($$$$) {
272         my ($self, $oid, $cb, $arg) = @_;
273         my $inflight_c = $self->{inflight_c} // check_async_begin($self);
274         if (scalar(@$inflight_c) >= MAX_INFLIGHT) {
275                 check_async_step($self, $inflight_c);
276         }
277         print { $self->{out_c} } $oid, "\n" or fail($self, "write error: $!");
278         push(@$inflight_c, $oid, $cb, $arg);
279 }
280
281 sub _check_cb { # check_async callback
282         my ($hex, $type, $size, $result) = @_;
283         @$result = ($hex, $type, $size);
284 }
285
286 sub check {
287         my ($self, $oid) = @_;
288         my $result = [];
289         check_async($self, $oid, \&_check_cb, $result);
290         check_async_wait($self);
291         my ($hex, $type, $size) = @$result;
292
293         # Future versions of git.git may show 'ambiguous', but for now,
294         # we must handle 'dangling' below (and maybe some other oddball
295         # stuff):
296         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
297         return if $type eq 'missing' || $type eq 'ambiguous';
298         return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
299         ($hex, $type, $size);
300 }
301
302 sub _destroy {
303         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
304         my $p = delete $self->{$pid} or return;
305         delete @$self{($rbuf, $in, $out)};
306         delete $self->{$err} if $err; # `err_c'
307
308         # PublicInbox::DS may not be loaded
309         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
310         waitpid($p, 0) if $@; # wait synchronously if not in event loop
311 }
312
313 sub cat_async_abort ($) {
314         my ($self) = @_;
315         my $inflight = delete $self->{inflight} or die 'BUG: not in async';
316         cleanup($self);
317 }
318
319 sub fail {
320         my ($self, $msg) = @_;
321         $self->{inflight} ? cat_async_abort($self) : cleanup($self);
322         die $msg;
323 }
324
325 sub popen {
326         my ($self, @cmd) = @_;
327         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
328         popen_rd(\@cmd);
329 }
330
331 sub qx {
332         my ($self, @cmd) = @_;
333         my $fh = $self->popen(@cmd);
334         local $/ = "\n";
335         return <$fh> if wantarray;
336         local $/;
337         <$fh>
338 }
339
340 # returns true if there are pending "git cat-file" processes
341 sub cleanup {
342         my ($self) = @_;
343         local $in_cleanup = 1;
344         delete $self->{async_cat};
345         check_async_wait($self);
346         cat_async_wait($self);
347         _destroy($self, qw(cat_rbuf in out pid));
348         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
349         !!($self->{pid} || $self->{pid_c});
350 }
351
352 # assuming a well-maintained repo, this should be a somewhat
353 # accurate estimation of its size
354 # TODO: show this in the WWW UI as a hint to potential cloners
355 sub packed_bytes {
356         my ($self) = @_;
357         my $n = 0;
358         my $pack_dir = git_path($self, 'objects/pack');
359         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
360                 $n += -s $p;
361         }
362         $n
363 }
364
365 sub DESTROY { cleanup(@_) }
366
367 sub local_nick ($) {
368         my ($self) = @_;
369         my $ret = '???';
370         # don't show full FS path, basename should be OK:
371         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
372                 $ret = "/path/to/$1";
373         }
374         wantarray ? ($ret) : $ret;
375 }
376
377 sub host_prefix_url ($$) {
378         my ($env, $url) = @_;
379         return $url if index($url, '//') >= 0;
380         my $scheme = $env->{'psgi.url_scheme'};
381         my $host_port = $env->{HTTP_HOST} //
382                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
383         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
384 }
385
386 sub pub_urls {
387         my ($self, $env) = @_;
388         if (my $urls = $self->{cgit_url}) {
389                 return map { host_prefix_url($env, $_) } @$urls;
390         }
391         local_nick($self);
392 }
393
394 sub cat_async_begin {
395         my ($self) = @_;
396         cleanup($self) if alternates_changed($self);
397         batch_prepare($self);
398         die 'BUG: already in async' if $self->{inflight};
399         $self->{inflight} = [];
400 }
401
402 sub cat_async ($$$;$) {
403         my ($self, $oid, $cb, $arg) = @_;
404         my $inflight = $self->{inflight} // cat_async_begin($self);
405         if (scalar(@$inflight) >= MAX_INFLIGHT) {
406                 cat_async_step($self, $inflight);
407         }
408
409         print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
410         push(@$inflight, $oid, $cb, $arg);
411 }
412
413 # this is safe to call inside $cb, but not guaranteed to enqueue
414 # returns true if successful, undef if not.
415 sub async_prefetch {
416         my ($self, $oid, $cb, $arg) = @_;
417         if (defined($self->{async_cat}) && (my $inflight = $self->{inflight})) {
418                 # we could use MAX_INFLIGHT here w/o the halving,
419                 # but lets not allow one client to monopolize a git process
420                 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
421                         print { $self->{out} } $oid, "\n" or
422                                                 fail($self, "write error: $!");
423                         return push(@$inflight, $oid, $cb, $arg);
424                 }
425         }
426         undef;
427 }
428
429 sub extract_cmt_time {
430         my ($bref, undef, undef, undef, $modified) = @_;
431
432         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
433                 my $cmt_time = $1 + 0;
434                 $$modified = $cmt_time if $cmt_time > $$modified;
435         }
436 }
437
438 # returns the modified time of a git repo, same as the "modified" field
439 # of a grokmirror manifest
440 sub modified ($) {
441         my ($self) = @_;
442         my $modified = 0;
443         my $fh = popen($self, qw(rev-parse --branches));
444         local $/ = "\n";
445         while (my $oid = <$fh>) {
446                 chomp $oid;
447                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
448         }
449         cat_async_wait($self);
450         $modified || time;
451 }
452
453 1;
454 __END__
455 =pod
456
457 =head1 NAME
458
459 PublicInbox::Git - git wrapper
460
461 =head1 VERSION
462
463 version 1.0
464
465 =head1 SYNOPSIS
466
467         use PublicInbox::Git;
468         chomp(my $git_dir = `git rev-parse --git-dir`);
469         $git_dir or die "GIT_DIR= must be specified\n";
470         my $git = PublicInbox::Git->new($git_dir);
471
472 =head1 DESCRIPTION
473
474 Unstable API outside of the L</new> method.
475 It requires L<git(1)> to be installed.
476
477 =head1 METHODS
478
479 =cut
480
481 =head2 new
482
483         my $git = PublicInbox::Git->new($git_dir);
484
485 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
486 This is the only public API method we support.  Everything else
487 in this module is subject to change.
488
489 =head1 SEE ALSO
490
491 L<Git>, L<PublicInbox::Import>
492
493 =head1 CONTACT
494
495 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
496
497 The mail archives are hosted at L<https://public-inbox.org/meta/>
498
499 =head1 COPYRIGHT
500
501 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
502
503 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
504
505 =cut