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 # TODO: make configurable, but keep in mind it's better to have
15 # multiple -httpd worker processes which are already scaled to
16 # the proper number of CPUs and memory. git-pack-objects(1) may
17 # also use threads and bust memory limits, too, so I recommend
18 # limiting threads to 1 (via `pack.threads` knob in git) for serving.
22 # n.b. serving "description" and "cloneurl" should be innocuous enough to
23 # not cause problems. serving "config" might...
24 my @text = qw[HEAD info/refs
25 objects/info/(?:http-alternates|alternates|packs)
26 cloneurl description];
29 objects/[a-f0-9]{2}/[a-f0-9]{38}
30 objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
33 our $ANY = join('|', @binary, @text);
34 my $BIN = join('|', @binary);
35 my $TEXT = join('|', @text);
37 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
39 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
45 while (my $cb = shift @$q) {
46 $cb->(); # this may redefine nextq
52 [ $s, [qw(Content-Type text/plain Content-Length 0), @no_cache ], [] ]
56 my ($cgi, $git, $path) = @_;
57 return serve_dumb($cgi, $git, $path) if $nr_running >= $LIMIT;
59 my $service = $cgi->param('service') || '';
60 if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
61 my $ok = serve_smart($cgi, $git, $path);
65 serve_dumb($cgi, $git, $path);
70 $env->{'psgi.errors'}->print(@msg, "\n");
74 if (my $io = $_[0]->{'psgix.io'}) {
75 $io->close; # this is Danga::Socket::close
80 my ($cgi, $git, $path) = @_;
84 if ($path =~ /\A(?:$BIN)\z/o) {
85 $type = 'application/octet-stream';
86 push @h, 'Expires', time2str(time + 31536000);
87 push @h, 'Cache-Control', 'public, max-age=31536000';
88 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
95 my $f = "$git->{git_dir}/$path";
96 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
99 my $env = $cgi->{env};
101 # TODO: If-Modified-Since and Last-Modified?
102 open my $in, '<', $f or return r(404);
104 my $n = 65536; # try to negotiate a big TCP window, first
107 $n = $len if $len < $n;
108 my $r = sysread($in, my $buf, $n);
110 err($env, "$f read error: $!");
113 err($env, "$f EOF with $len bytes left");
121 # avoid recursion in Danga::Socket::write
124 Danga::Socket->AddTimer(0, *do_next);
126 # avoid buffering too much in case we have
133 # all done, cleanup references:
138 push @h, 'Content-Type', $type;
139 my $range = $env->{HTTP_RANGE};
140 if (defined $range && $range =~ /\bbytes=(\d*)-(\d*)\z/) {
141 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
143 push @h, 'Content-Range', "bytes */$size";
144 return [ 416, \@h, [] ];
147 push @h, 'Content-Length', $len;
150 my ($res) = @_; # Plack callback
151 $fh = $res->([ $code, \@h ]);
152 if (defined $env->{'pi-httpd.async'}) {
153 my $pi_http = $env->{'psgix.io'};
154 $next = sub { $pi_http->write($cb) };
155 $cb->(); # start it off!
163 my ($cgi, $in, $h, $beg, $end, $size) = @_;
167 if ($end ne '') { # "bytes=-$end" => last N bytes
169 $beg = 0 if $beg < 0;
178 } elsif ($end eq '' || $end >= $size) {
181 } elsif ($end < $size) {
188 $len = $end - $beg + 1;
192 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
193 push @$h, qw(Accept-Ranges bytes Content-Range);
194 push @$h, "bytes $beg-$end/$size";
196 # FIXME: Plack::Middleware::Deflater bug?
197 $cgi->{env}->{'psgix.no-compress'} = 1;
203 # returns undef if 403 so it falls back to dumb HTTP
205 my ($cgi, $git, $path) = @_;
206 my $env = $cgi->{env};
208 my $input = $env->{'psgi.input'};
211 my $fd = eval { fileno($input) };
212 if (defined $fd && $fd >= 0) {
215 $in = input_to_file($env) or return r(500);
218 unless (pipe($rpipe, $wpipe)) {
219 err($env, "error creating pipe: $! - going static");
223 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
224 # may be set in the server-process and are passed as-is
225 foreach my $name (qw(QUERY_STRING
226 REMOTE_USER REMOTE_ADDR
227 HTTP_CONTENT_ENCODING
231 my $val = $env->{$name};
232 $env{$name} = $val if defined $val;
234 my $git_dir = $git->{git_dir};
235 $env{GIT_HTTP_EXPORT_ALL} = '1';
236 $env{PATH_TRANSLATED} = "$git_dir/$path";
237 my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
238 my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
239 unless (defined $pid) {
240 err($env, "error spawning: $! - going static");
243 $wpipe = $in = undef;
245 my ($vin, $fh, $res);
248 # Danga::Socket users, we queue up the read_enable callback to
249 # fire after pending writes are complete:
250 my $pi_http = $env->{'psgix.io'};
251 my $read_enable = sub { $rpipe->watch_read(1) };
252 my $read_disable = sub {
253 $rpipe->watch_read(0);
254 $pi_http->write($read_enable);
263 # _may_ be Danga::Socket::close via
264 # PublicInbox::HTTPD::Async::close:
270 my $e = $pid == waitpid($pid, 0) ?
271 $? : "PID:$pid still running?";
272 err($env, "git http-backend ($git_dir): $e") if $e;
275 my $dumb = serve_dumb($cgi, $git, $path);
276 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
279 if ($!{EAGAIN} || $!{EINTR}) {
280 select($vin, undef, undef, undef) if defined $vin;
281 # $vin is undef on async, so this is a noop on EAGAIN
286 err($env, "git http-backend ($git_dir): $e\n");
288 my $cb = sub { # read git-http-backend output and stream to client
289 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
290 return $fail->() unless defined $r;
291 return $end->() if $r == 0; # EOF
292 if ($fh) { # stream body from git-http-backend to HTTP client
295 $read_disable->() if $read_disable;
296 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
300 foreach my $l (split(/\r\n/, $h)) {
301 my ($k, $v) = split(/:\s*/, $l, 2);
302 if ($k =~ /\AStatus\z/i) {
303 ($code) = ($v =~ /\b(\d+)\b/);
309 # smart cloning disabled, serve dumbly
310 # in $end since we never undef $res in here
311 } else { # write response header:
312 $fh = $res->([ $code, \@h ]);
317 } # else { keep reading ... }
319 if (my $async = $env->{'pi-httpd.async'}) {
320 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
321 $rpipe = $async->($rpipe, $cb);
322 sub { ($res) = @_ } # let Danga::Socket handle the rest.
323 } else { # synchronous loop for other PSGI servers
324 $read_enable = $read_disable = undef;
326 vec($vin, fileno($rpipe), 1) = 1;
329 while ($rpipe) { $cb->() }
336 my $in = IO::File->new_tmpfile;
337 my $input = $env->{'psgi.input'};
340 my $r = $input->read($buf, 8192);
341 unless (defined $r) {
342 err($env, "error reading input: $!");
349 $in->sysseek(0, SEEK_SET);