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);
13 use PublicInbox::Qspawn;
15 # n.b. serving "description" and "cloneurl" should be innocuous enough to
16 # not cause problems. serving "config" might...
17 my @text = qw[HEAD info/refs
18 objects/info/(?:http-alternates|alternates|packs)
19 cloneurl description];
22 objects/[a-f0-9]{2}/[a-f0-9]{38}
23 objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
26 our $ANY = join('|', @binary, @text, 'git-upload-pack');
27 my $BIN = join('|', @binary);
28 my $TEXT = join('|', @text);
30 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
32 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
35 my ($code, $msg) = @_;
36 $msg ||= status_message($code);
37 my $len = length($msg);
38 [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
43 my ($env, $git, $path) = @_;
45 # Documentation/technical/http-protocol.txt in git.git
46 # requires one and exactly one query parameter:
47 if ($env->{QUERY_STRING} =~ /\Aservice=git-\w+-pack\z/ ||
48 $path =~ /\Agit-\w+-pack\z/) {
49 my $ok = serve_smart($env, $git, $path);
53 serve_dumb($env, $git, $path);
58 $env->{'psgi.errors'}->print(@msg, "\n");
62 if (my $io = $_[0]->{'psgix.io'}) {
63 $io->close; # this is Danga::Socket::close
71 my $t = time + 31536000;
72 push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
73 'Cache-Control', 'public, max-age=31536000';
77 my ($env, $git, $path) = @_;
81 if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38}\z!) {
82 $type = 'application/x-git-loose-object';
84 } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.pack\z!) {
85 $type = 'application/x-git-packed-objects';
87 } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.idx\z!) {
88 $type = 'application/x-git-packed-objects-toc';
90 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
97 my $f = (ref $git ? $git->{git_dir} : $git) . '/' . $path;
98 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
102 # TODO: If-Modified-Since and Last-Modified?
103 open my $in, '<', $f or return r(404);
106 push @h, 'Content-Type', $type;
107 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
108 ($code, $len) = prepare_range($env, $in, \@h, $1, $2, $size);
110 push @h, 'Content-Range', "bytes */$size";
111 return [ 416, \@h, [] ];
114 push @h, 'Content-Length', $len;
116 [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
119 $n = $len if $len < $n;
120 my $r = sysread($in, my $buf, $n);
122 err($env, "$f read error: $!");
124 err($env, "$f EOF with $len bytes left");
136 my ($env, $in, $h, $beg, $end, $size) = @_;
140 if ($end ne '') { # "bytes=-$end" => last N bytes
142 $beg = 0 if $beg < 0;
151 } elsif ($end eq '' || $end >= $size) {
154 } elsif ($end < $size) {
161 $len = $end - $beg + 1;
165 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
166 push @$h, qw(Accept-Ranges bytes Content-Range);
167 push @$h, "bytes $beg-$end/$size";
169 # FIXME: Plack::Middleware::Deflater bug?
170 $env->{'psgix.no-compress'} = 1;
176 # returns undef if 403 so it falls back to dumb HTTP
178 my ($env, $git, $path) = @_;
179 my $in = $env->{'psgi.input'};
180 my $fd = eval { fileno($in) };
181 unless (defined $fd && $fd >= 0) {
182 $in = input_to_file($env) or return r(500);
185 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
186 # may be set in the server-process and are passed as-is
187 foreach my $name (qw(QUERY_STRING
188 REMOTE_USER REMOTE_ADDR
189 HTTP_CONTENT_ENCODING
193 my $val = $env->{$name};
194 $env{$name} = $val if defined $val;
196 my $git_dir = ref $git ? $git->{git_dir} : $git;
197 $env{GIT_HTTP_EXPORT_ALL} = '1';
198 $env{PATH_TRANSLATED} = "$git_dir/$path";
199 my %rdr = ( 0 => fileno($in) );
200 my $x = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, \%rdr);
203 if (my $err = $x->finish) {
204 err($env, "git http-backend ($git_dir): $err");
206 $fh->close if $fh; # async-only
209 # Danga::Socket users, we queue up the read_enable callback to
210 # fire after pending writes are complete:
213 my $r = sysread($rpipe, $buf, 1024, length($buf));
214 return if !defined($r) && ($!{EINTR} || $!{EAGAIN});
215 return r(500, 'http-backend error') unless $r;
216 $r = parse_cgi_headers(\$buf) or return; # incomplete headers
217 $r->[0] == 403 ? serve_dumb($env, $git, $path) : $r;
220 my $async = $env->{'pi-httpd.async'};
221 my $io = $env->{'psgix.io'};
223 my $r = $rd_hdr->() or return;
225 if (scalar(@$r) == 3) { # error:
227 $async->close; # calls rpipe->close
236 return $async->async_pass($io, $fh, \$buf);
239 # for synchronous PSGI servers
240 require PublicInbox::GetlineBody;
241 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end, $buf);
247 # hopefully this doesn't break any middlewares,
248 # holding the input here is a waste of FDs and memory
249 $env->{'psgi.input'} = undef;
251 $x->start(sub { # may run later, much later...
255 $async = $async->($rpipe, $cb, $end);
256 } else { # generic PSGI
257 $cb->() while $rd_hdr;
265 my $in = IO::File->new_tmpfile;
266 my $input = $env->{'psgi.input'};
269 my $r = $input->read($buf, 8192);
270 unless (defined $r) {
271 err($env, "error reading input: $!");
278 $in->sysseek(0, SEEK_SET);
282 sub parse_cgi_headers {
284 $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
288 foreach my $l (split(/\r\n/, $h)) {
289 my ($k, $v) = split(/:\s*/, $l, 2);
290 if ($k =~ /\AStatus\z/i) {
291 ($code) = ($v =~ /\b(\d+)\b/);