1 # Copyright (C) 2016 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 # Documentation/technical/http-protocol.txt in git.git
50 # requires one and exactly one query parameter:
51 if ($env->{QUERY_STRING} =~ /\Aservice=git-\w+-pack\z/ ||
52 $path =~ /\Agit-\w+-pack\z/) {
53 my $ok = serve_smart($env, $git, $path);
57 serve_dumb($env, $git, $path);
62 $env->{'psgi.errors'}->print(@msg, "\n");
66 if (my $io = $_[0]->{'psgix.io'}) {
67 $io->close; # this is Danga::Socket::close
75 my $t = time + 31536000;
76 push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
77 'Cache-Control', 'public, max-age=31536000';
81 my ($env, $git, $path) = @_;
85 if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38}\z!) {
86 $type = 'application/x-git-loose-object';
88 } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.pack\z!) {
89 $type = 'application/x-git-packed-objects';
91 } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.idx\z!) {
92 $type = 'application/x-git-packed-objects-toc';
94 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
101 my $f = (ref $git ? $git->{git_dir} : $git) . '/' . $path;
102 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
105 # TODO: If-Modified-Since and Last-Modified?
106 open my $in, '<', $f or return r(404);
109 push @h, 'Content-Type', $type;
110 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
111 ($code, $len) = prepare_range($env, $in, \@h, $1, $2, $size);
113 push @h, 'Content-Range', "bytes */$size";
114 return [ 416, \@h, [] ];
117 push @h, 'Content-Length', $len;
119 [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
122 $n = $len if $len < $n;
123 my $r = sysread($in, my $buf, $n);
125 err($env, "$f read error: $!");
127 err($env, "$f EOF with $len bytes left");
139 my ($env, $in, $h, $beg, $end, $size) = @_;
143 if ($end ne '') { # "bytes=-$end" => last N bytes
145 $beg = 0 if $beg < 0;
154 } elsif ($end eq '' || $end >= $size) {
157 } elsif ($end < $size) {
164 $len = $end - $beg + 1;
168 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
169 push @$h, qw(Accept-Ranges bytes Content-Range);
170 push @$h, "bytes $beg-$end/$size";
172 # FIXME: Plack::Middleware::Deflater bug?
173 $env->{'psgix.no-compress'} = 1;
179 # returns undef if 403 so it falls back to dumb HTTP
181 my ($env, $git, $path) = @_;
182 my $in = $env->{'psgi.input'};
183 my $fd = eval { fileno($in) };
184 unless (defined $fd && $fd >= 0) {
185 $in = input_to_file($env) or return r(500);
188 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
189 # may be set in the server-process and are passed as-is
190 foreach my $name (qw(QUERY_STRING
191 REMOTE_USER REMOTE_ADDR
192 HTTP_CONTENT_ENCODING
196 my $val = $env->{$name};
197 $env{$name} = $val if defined $val;
199 my ($git_dir, $limiter);
201 $limiter = $git->{-httpbackend_limiter} || $default_limiter;
202 $git_dir = $git->{git_dir};
204 $limiter = $default_limiter;
207 $env{GIT_HTTP_EXPORT_ALL} = '1';
208 $env{PATH_TRANSLATED} = "$git_dir/$path";
209 my %rdr = ( 0 => fileno($in) );
210 my $x = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, \%rdr);
213 if (my $err = $x->finish) {
214 err($env, "git http-backend ($git_dir): $err");
216 $fh->close if $fh; # async-only
219 # Danga::Socket users, we queue up the read_enable callback to
220 # fire after pending writes are complete:
223 my $r = sysread($rpipe, $buf, 1024, length($buf));
224 return if !defined($r) && ($!{EINTR} || $!{EAGAIN});
225 return r(500, 'http-backend error') unless $r;
226 $r = parse_cgi_headers(\$buf) or return; # incomplete headers
227 $r->[0] == 403 ? serve_dumb($env, $git, $path) : $r;
230 my $async = $env->{'pi-httpd.async'};
231 my $io = $env->{'psgix.io'};
233 my $r = $rd_hdr->() or return;
235 if (scalar(@$r) == 3) { # error:
237 $async->close; # calls rpipe->close
246 return $async->async_pass($io, $fh, \$buf);
249 # for synchronous PSGI servers
250 require PublicInbox::GetlineBody;
251 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end, $buf);
257 # hopefully this doesn't break any middlewares,
258 # holding the input here is a waste of FDs and memory
259 $env->{'psgi.input'} = undef;
261 $x->start($limiter, sub { # may run later, much later...
265 $async = $async->($rpipe, $cb, $end);
266 } else { # generic PSGI
267 $cb->() while $rd_hdr;
275 my $in = IO::File->new_tmpfile;
276 my $input = $env->{'psgi.input'};
279 my $r = $input->read($buf, 8192);
280 unless (defined $r) {
281 err($env, "error reading input: $!");
288 $in->sysseek(0, SEEK_SET);
292 sub parse_cgi_headers {
294 $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
298 foreach my $l (split(/\r\n/, $h)) {
299 my ($k, $v) = split(/:\s*/, $l, 2);
300 if ($k =~ /\AStatus\z/i) {
301 ($code) = ($v =~ /\b(\d+)\b/);