1 # Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # when no endpoints match, fallback to this and serve a static file
6 package PublicInbox::GitHTTPBackend;
11 use HTTP::Date qw(time2str);
12 use HTTP::Status qw(status_message);
14 use PublicInbox::Qspawn;
16 # 32 is same as the git-daemon connection limit
17 my $default_limiter = PublicInbox::Qspawn::Limiter->new(32);
19 # n.b. serving "description" and "cloneurl" should be innocuous enough to
20 # not cause problems. serving "config" might...
21 my @text = qw[HEAD info/refs
22 objects/info/(?:http-alternates|alternates|packs)
23 cloneurl description];
26 objects/[a-f0-9]{2}/[a-f0-9]{38}
27 objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
30 our $ANY = join('|', @binary, @text, 'git-upload-pack');
31 my $BIN = join('|', @binary);
32 my $TEXT = join('|', @text);
34 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
36 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
39 my ($code, $msg) = @_;
40 $msg ||= status_message($code);
41 my $len = length($msg);
42 [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
47 my ($env, $git, $path) = @_;
49 # XXX compatibility... ugh, can we stop supporting this?
50 $git = PublicInbox::Git->new($git) unless ref($git);
52 # Documentation/technical/http-protocol.txt in git.git
53 # requires one and exactly one query parameter:
54 if ($env->{QUERY_STRING} =~ /\Aservice=git-\w+-pack\z/ ||
55 $path =~ /\Agit-\w+-pack\z/) {
56 my $ok = serve_smart($env, $git, $path);
60 serve_dumb($env, $git, $path);
65 $env->{'psgi.errors'}->print(@msg, "\n");
69 if (my $io = $_[0]->{'psgix.io'}) {
70 $io->close; # this is Danga::Socket::close
78 my $t = time + 31536000;
79 push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
80 'Cache-Control', 'public, max-age=31536000';
84 my ($env, $git, $path) = @_;
88 if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38}\z!) {
89 $type = 'application/x-git-loose-object';
91 } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.pack\z!) {
92 $type = 'application/x-git-packed-objects';
94 } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.idx\z!) {
95 $type = 'application/x-git-packed-objects-toc';
97 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
104 my $f = $git->{git_dir} . '/' . $path;
105 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
108 # TODO: If-Modified-Since and Last-Modified?
109 open my $in, '<', $f or return r(404);
112 push @h, 'Content-Type', $type;
113 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
114 ($code, $len) = prepare_range($env, $in, \@h, $1, $2, $size);
116 push @h, 'Content-Range', "bytes */$size";
117 return [ 416, \@h, [] ];
120 push @h, 'Content-Length', $len;
122 [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
125 $n = $len if $len < $n;
126 my $r = sysread($in, my $buf, $n);
128 err($env, "$f read error: $!");
130 err($env, "$f EOF with $len bytes left");
142 my ($env, $in, $h, $beg, $end, $size) = @_;
146 if ($end ne '') { # "bytes=-$end" => last N bytes
148 $beg = 0 if $beg < 0;
157 } elsif ($end eq '' || $end >= $size) {
160 } elsif ($end < $size) {
167 $len = $end - $beg + 1;
171 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
172 push @$h, qw(Accept-Ranges bytes Content-Range);
173 push @$h, "bytes $beg-$end/$size";
175 # FIXME: Plack::Middleware::Deflater bug?
176 $env->{'psgix.no-compress'} = 1;
182 # returns undef if 403 so it falls back to dumb HTTP
184 my ($env, $git, $path) = @_;
185 my $in = $env->{'psgi.input'};
186 my $fd = eval { fileno($in) };
187 unless (defined $fd && $fd >= 0) {
188 $in = input_to_file($env) or return r(500);
191 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
192 # may be set in the server-process and are passed as-is
193 foreach my $name (qw(QUERY_STRING
194 REMOTE_USER REMOTE_ADDR
195 HTTP_CONTENT_ENCODING
199 my $val = $env->{$name};
200 $env{$name} = $val if defined $val;
202 my $limiter = $git->{-httpbackend_limiter} || $default_limiter;
203 my $git_dir = $git->{git_dir};
204 $env{GIT_HTTP_EXPORT_ALL} = '1';
205 $env{PATH_TRANSLATED} = "$git_dir/$path";
206 my $rdr = { 0 => fileno($in) };
207 my $qsp = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, $rdr);
210 if (my $err = $qsp->finish) {
211 err($env, "git http-backend ($git_dir): $err");
213 $fh->close if $fh; # async-only
216 # Danga::Socket users, we queue up the read_enable callback to
217 # fire after pending writes are complete:
220 my $r = sysread($rpipe, $buf, 1024, length($buf));
221 return if !defined($r) && ($!{EINTR} || $!{EAGAIN});
222 return r(500, 'http-backend error') unless $r;
223 $r = parse_cgi_headers(\$buf) or return; # incomplete headers
224 $r->[0] == 403 ? serve_dumb($env, $git, $path) : $r;
227 my $async = $env->{'pi-httpd.async'}; # XXX unstable API
229 my $r = $rd_hdr->() or return;
231 if (scalar(@$r) == 3) { # error:
233 $async->close; # calls rpipe->close
241 $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
242 } else { # for synchronous PSGI servers
243 require PublicInbox::GetlineBody;
244 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
252 # hopefully this doesn't break any middlewares,
253 # holding the input here is a waste of FDs and memory
254 $env->{'psgi.input'} = undef;
256 $qsp->start($limiter, sub { # may run later, much later...
260 $async = $async->($rpipe, $cb, $end);
261 } else { # generic PSGI
262 $cb->() while $rd_hdr;
270 open(my $in, '+>', undef);
271 unless (defined $in) {
272 err($env, "could not open temporary file: $!");
275 my $input = $env->{'psgi.input'};
278 my $r = $input->read($buf, 8192);
279 unless (defined $r) {
280 err($env, "error reading input: $!");
286 my $w = syswrite($in, $buf, $r, $off);
291 err($env, "error writing temporary file: $!");
296 unless (defined(sysseek($in, 0, SEEK_SET))) {
297 err($env, "error seeking temporary file: $!");
303 sub parse_cgi_headers {
305 $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
309 foreach my $l (split(/\r\n/, $h)) {
310 my ($k, $v) = split(/:\s*/, $l, 2);
311 if ($k =~ /\AStatus\z/i) {
312 ($code) = ($v =~ /\b(\d+)\b/);