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