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 PublicInbox::Spawn qw(spawn);
12 use HTTP::Date qw(time2str);
13 use HTTP::Status qw(status_message);
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);
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');
38 while (my $cb = shift @$q) {
39 $cb->(); # this may redefine nextq
44 my ($code, $msg) = @_;
45 $msg ||= status_message($code);
46 my $len = length($msg);
47 [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
52 my ($cgi, $git, $path) = @_;
54 my $service = $cgi->param('service') || '';
55 if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
56 my $ok = serve_smart($cgi, $git, $path);
60 serve_dumb($cgi, $git, $path);
65 $env->{'psgi.errors'}->print(@msg, "\n");
69 if (my $io = $_[0]->{'psgix.io'}) {
70 $io->close; # this is Danga::Socket::close
75 my ($cgi, $git, $path) = @_;
79 if ($path =~ /\A(?:$BIN)\z/o) {
80 $type = 'application/octet-stream';
81 push @h, 'Expires', time2str(time + 31536000);
82 push @h, 'Cache-Control', 'public, max-age=31536000';
83 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
90 my $f = "$git->{git_dir}/$path";
91 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
94 my $env = $cgi->{env};
96 # TODO: If-Modified-Since and Last-Modified?
97 open my $in, '<', $f or return r(404);
100 push @h, 'Content-Type', $type;
101 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
102 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
104 push @h, 'Content-Range', "bytes */$size";
105 return [ 416, \@h, [] ];
108 push @h, 'Content-Length', $len;
110 [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
113 $n = $len if $len < $n;
114 my $r = sysread($in, my $buf, $n);
116 err($env, "$f read error: $!");
118 err($env, "$f EOF with $len bytes left");
130 my ($cgi, $in, $h, $beg, $end, $size) = @_;
134 if ($end ne '') { # "bytes=-$end" => last N bytes
136 $beg = 0 if $beg < 0;
145 } elsif ($end eq '' || $end >= $size) {
148 } elsif ($end < $size) {
155 $len = $end - $beg + 1;
159 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
160 push @$h, qw(Accept-Ranges bytes Content-Range);
161 push @$h, "bytes $beg-$end/$size";
163 # FIXME: Plack::Middleware::Deflater bug?
164 $cgi->{env}->{'psgix.no-compress'} = 1;
170 # returns undef if 403 so it falls back to dumb HTTP
172 my ($cgi, $git, $path) = @_;
173 my $env = $cgi->{env};
174 my $in = $env->{'psgi.input'};
175 my $fd = eval { fileno($in) };
176 unless (defined $fd && $fd >= 0) {
177 $in = input_to_file($env) or return r(500);
180 unless (pipe($rpipe, $wpipe)) {
181 err($env, "error creating pipe: $! - going static");
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 = $git->{git_dir};
197 $env{GIT_HTTP_EXPORT_ALL} = '1';
198 $env{PATH_TRANSLATED} = "$git_dir/$path";
199 my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
200 my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
201 unless (defined $pid) {
202 err($env, "error spawning: $! - going static");
205 $wpipe = $in = undef;
208 my $e = $pid == waitpid($pid, 0) ?
209 $? : "PID:$pid still running?";
211 err($env, "git http-backend ($git_dir): $e");
216 # Danga::Socket users, we queue up the read_enable callback to
217 # fire after pending writes are complete:
219 if (my $async = $env->{'pi-httpd.async'}) {
226 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
227 $async = $async->($rpipe, sub {
228 my $r = sysread($rpipe, $buf, 1024, length($buf));
229 if (!defined $r || $r == 0) {
230 return $q->(r(500, 'http-backend error'));
232 $r = parse_cgi_headers(\$buf) or return;
233 if ($r->[0] == 403) {
234 return $q->(serve_dumb($cgi, $git, $path));
239 my $dst = Plack::Util::inline_object(
240 write => sub { $fh->write(@_) },
245 $async->async_pass($env->{'psgix.io'}, $dst);
247 sub { ($res) = @_ }; # let Danga::Socket handle the rest.
248 } else { # getline + close for other PSGI servers
251 $r = read($rpipe, $buf, 1024, length($buf));
252 if (!defined $r || $r == 0) {
253 return r(500, 'http-backend error');
255 $r = parse_cgi_headers(\$buf);
257 return serve_dumb($cgi, $git, $path) if $r->[0] == 403;
258 $r->[2] = Plack::Util::inline_object(
259 close => sub { $end->() },
263 defined $ret ? $ret : $rpipe->getline;
272 my $in = IO::File->new_tmpfile;
273 my $input = $env->{'psgi.input'};
276 my $r = $input->read($buf, 8192);
277 unless (defined $r) {
278 err($env, "error reading input: $!");
285 $in->sysseek(0, SEEK_SET);
289 sub parse_cgi_headers {
291 $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
295 foreach my $l (split(/\r\n/, $h)) {
296 my ($k, $v) = split(/:\s*/, $l, 2);
297 if ($k =~ /\AStatus\z/i) {
298 ($code) = ($v =~ /\b(\d+)\b/);