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);
95 my $n = 65536; # try to negotiate a big TCP window, first
98 $n = $len if $len < $n;
99 my $r = sysread($in, my $buf, $n);
101 err($env, "$f read error: $!");
104 err($env, "$f EOF with $len bytes left");
112 # avoid recursion in Danga::Socket::write
115 Danga::Socket->AddTimer(0, *do_next);
117 # avoid buffering too much in case we have
124 # all done, cleanup references:
129 push @h, 'Content-Type', $type;
130 my $range = $env->{HTTP_RANGE};
131 if (defined $range && $range =~ /\bbytes=(\d*)-(\d*)\z/) {
132 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
134 push @h, 'Content-Range', "bytes */$size";
135 return [ 416, \@h, [] ];
138 push @h, 'Content-Length', $len;
141 my ($res) = @_; # Plack callback
142 $fh = $res->([ $code, \@h ]);
143 if (defined $env->{'pi-httpd.async'}) {
144 my $pi_http = $env->{'psgix.io'};
145 $next = sub { $pi_http->write($cb) };
146 $cb->(); # start it off!
154 my ($cgi, $in, $h, $beg, $end, $size) = @_;
158 if ($end ne '') { # "bytes=-$end" => last N bytes
160 $beg = 0 if $beg < 0;
169 } elsif ($end eq '' || $end >= $size) {
172 } elsif ($end < $size) {
179 $len = $end - $beg + 1;
183 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
184 push @$h, qw(Accept-Ranges bytes Content-Range);
185 push @$h, "bytes $beg-$end/$size";
187 # FIXME: Plack::Middleware::Deflater bug?
188 $cgi->{env}->{'psgix.no-compress'} = 1;
194 # returns undef if 403 so it falls back to dumb HTTP
196 my ($cgi, $git, $path) = @_;
197 my $env = $cgi->{env};
199 my $input = $env->{'psgi.input'};
202 my $fd = eval { fileno($input) };
203 if (defined $fd && $fd >= 0) {
206 $in = input_to_file($env) or return r(500);
209 unless (pipe($rpipe, $wpipe)) {
210 err($env, "error creating pipe: $! - going static");
214 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
215 # may be set in the server-process and are passed as-is
216 foreach my $name (qw(QUERY_STRING
217 REMOTE_USER REMOTE_ADDR
218 HTTP_CONTENT_ENCODING
222 my $val = $env->{$name};
223 $env{$name} = $val if defined $val;
225 my $git_dir = $git->{git_dir};
226 $env{GIT_HTTP_EXPORT_ALL} = '1';
227 $env{PATH_TRANSLATED} = "$git_dir/$path";
228 my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
229 my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
230 unless (defined $pid) {
231 err($env, "error spawning: $! - going static");
234 $wpipe = $in = undef;
236 my ($vin, $fh, $res);
238 # Danga::Socket users, we queue up the read_enable callback to
239 # fire after pending writes are complete:
240 my $pi_http = $env->{'psgix.io'};
241 my $read_enable = sub { $rpipe->watch_read(1) };
242 my $read_disable = sub {
243 $rpipe->watch_read(0);
244 $pi_http->write($read_enable);
253 # _may_ be Danga::Socket::close via
254 # PublicInbox::HTTPD::Async::close:
259 my $e = $pid == waitpid($pid, 0) ?
260 $? : "PID:$pid still running?";
261 err($env, "git http-backend ($git_dir): $e") if $e;
264 my $dumb = serve_dumb($cgi, $git, $path);
265 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
268 if ($!{EAGAIN} || $!{EINTR}) {
269 select($vin, undef, undef, undef) if defined $vin;
270 # $vin is undef on async, so this is a noop on EAGAIN
275 err($env, "git http-backend ($git_dir): $e\n");
277 my $cb = sub { # read git-http-backend output and stream to client
278 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
279 return $fail->() unless defined $r;
280 return $end->() if $r == 0; # EOF
281 if ($fh) { # stream body from git-http-backend to HTTP client
284 $read_disable->() if $read_disable;
285 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
289 foreach my $l (split(/\r\n/, $h)) {
290 my ($k, $v) = split(/:\s*/, $l, 2);
291 if ($k =~ /\AStatus\z/i) {
292 ($code) = ($v =~ /\b(\d+)\b/);
298 # smart cloning disabled, serve dumbly
299 # in $end since we never undef $res in here
300 } else { # write response header:
301 $fh = $res->([ $code, \@h ]);
306 } # else { keep reading ... }
308 if (my $async = $env->{'pi-httpd.async'}) {
309 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
310 $rpipe = $async->($rpipe, $cb);
311 sub { ($res) = @_ } # let Danga::Socket handle the rest.
312 } else { # synchronous loop for other PSGI servers
313 $read_enable = $read_disable = undef;
315 vec($vin, fileno($rpipe), 1) = 1;
318 while ($rpipe) { $cb->() }
325 my $in = IO::File->new_tmpfile;
326 my $input = $env->{'psgi.input'};
329 my $r = $input->read($buf, 8192);
330 unless (defined $r) {
331 err($env, "error reading input: $!");
338 $in->sysseek(0, SEEK_SET);