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);
14 # n.b. serving "description" and "cloneurl" should be innocuous enough to
15 # not cause problems. serving "config" might...
16 my @text = qw[HEAD info/refs
17 objects/info/(?:http-alternates|alternates|packs)
18 cloneurl description];
21 objects/[a-f0-9]{2}/[a-f0-9]{38}
22 objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
25 our $ANY = join('|', @binary, @text);
26 my $BIN = join('|', @binary);
27 my $TEXT = join('|', @text);
29 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
31 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
37 while (my $cb = shift @$q) {
38 $cb->(); # this may redefine nextq
44 [ $s, [qw(Content-Type text/plain Content-Length 0), @no_cache ], [] ]
48 my ($cgi, $git, $path) = @_;
50 my $service = $cgi->param('service') || '';
51 if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
52 my $ok = serve_smart($cgi, $git, $path);
56 serve_dumb($cgi, $git, $path);
61 $env->{'psgi.errors'}->print(@msg, "\n");
65 if (my $io = $_[0]->{'psgix.io'}) {
66 $io->close; # this is Danga::Socket::close
71 my ($cgi, $git, $path) = @_;
75 if ($path =~ /\A(?:$BIN)\z/o) {
76 $type = 'application/octet-stream';
77 push @h, 'Expires', time2str(time + 31536000);
78 push @h, 'Cache-Control', 'public, max-age=31536000';
79 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
86 my $f = "$git->{git_dir}/$path";
87 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
90 my $env = $cgi->{env};
92 # TODO: If-Modified-Since and Last-Modified?
93 open my $in, '<', $f or return r(404);
96 push @h, 'Content-Type', $type;
97 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
98 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
100 push @h, 'Content-Range', "bytes */$size";
101 return [ 416, \@h, [] ];
104 push @h, 'Content-Length', $len;
106 [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
109 $n = $len if $len < $n;
110 my $r = sysread($in, my $buf, $n);
112 err($env, "$f read error: $!");
114 err($env, "$f EOF with $len bytes left");
126 my ($cgi, $in, $h, $beg, $end, $size) = @_;
130 if ($end ne '') { # "bytes=-$end" => last N bytes
132 $beg = 0 if $beg < 0;
141 } elsif ($end eq '' || $end >= $size) {
144 } elsif ($end < $size) {
151 $len = $end - $beg + 1;
155 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
156 push @$h, qw(Accept-Ranges bytes Content-Range);
157 push @$h, "bytes $beg-$end/$size";
159 # FIXME: Plack::Middleware::Deflater bug?
160 $cgi->{env}->{'psgix.no-compress'} = 1;
166 # returns undef if 403 so it falls back to dumb HTTP
168 my ($cgi, $git, $path) = @_;
169 my $env = $cgi->{env};
171 my $input = $env->{'psgi.input'};
174 my $fd = eval { fileno($input) };
175 if (defined $fd && $fd >= 0) {
178 $in = input_to_file($env) or return r(500);
181 unless (pipe($rpipe, $wpipe)) {
182 err($env, "error creating pipe: $! - going static");
186 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
187 # may be set in the server-process and are passed as-is
188 foreach my $name (qw(QUERY_STRING
189 REMOTE_USER REMOTE_ADDR
190 HTTP_CONTENT_ENCODING
194 my $val = $env->{$name};
195 $env{$name} = $val if defined $val;
197 my $git_dir = $git->{git_dir};
198 $env{GIT_HTTP_EXPORT_ALL} = '1';
199 $env{PATH_TRANSLATED} = "$git_dir/$path";
200 my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
201 my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
202 unless (defined $pid) {
203 err($env, "error spawning: $! - going static");
206 $wpipe = $in = undef;
208 my ($vin, $fh, $res);
210 # Danga::Socket users, we queue up the read_enable callback to
211 # fire after pending writes are complete:
212 my $pi_http = $env->{'psgix.io'};
213 my $read_enable = sub { $rpipe->watch_read(1) };
214 my $read_disable = sub {
215 $rpipe->watch_read(0);
216 $pi_http->write($read_enable);
225 # _may_ be Danga::Socket::close via
226 # PublicInbox::HTTPD::Async::close:
231 my $e = $pid == waitpid($pid, 0) ?
232 $? : "PID:$pid still running?";
233 err($env, "git http-backend ($git_dir): $e") if $e;
236 my $dumb = serve_dumb($cgi, $git, $path);
237 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
240 if ($!{EAGAIN} || $!{EINTR}) {
241 select($vin, undef, undef, undef) if defined $vin;
242 # $vin is undef on async, so this is a noop on EAGAIN
247 err($env, "git http-backend ($git_dir): $e\n");
249 my $cb = sub { # read git-http-backend output and stream to client
250 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
251 return $fail->() unless defined $r;
252 return $end->() if $r == 0; # EOF
253 if ($fh) { # stream body from git-http-backend to HTTP client
256 $read_disable->() if $read_disable;
257 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
261 foreach my $l (split(/\r\n/, $h)) {
262 my ($k, $v) = split(/:\s*/, $l, 2);
263 if ($k =~ /\AStatus\z/i) {
264 ($code) = ($v =~ /\b(\d+)\b/);
270 # smart cloning disabled, serve dumbly
271 # in $end since we never undef $res in here
272 } else { # write response header:
273 $fh = $res->([ $code, \@h ]);
278 } # else { keep reading ... }
280 if (my $async = $env->{'pi-httpd.async'}) {
281 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
282 $rpipe = $async->($rpipe, $cb);
283 sub { ($res) = @_ } # let Danga::Socket handle the rest.
284 } else { # synchronous loop for other PSGI servers
285 $read_enable = $read_disable = undef;
287 vec($vin, fileno($rpipe), 1) = 1;
290 while ($rpipe) { $cb->() }
297 my $in = IO::File->new_tmpfile;
298 my $input = $env->{'psgi.input'};
301 my $r = $input->read($buf, 8192);
302 unless (defined $r) {
303 err($env, "error reading input: $!");
310 $in->sysseek(0, SEEK_SET);