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);
13 # TODO: make configurable, but keep in mind it's better to have
14 # multiple -httpd worker processes which are already scaled to
15 # the proper number of CPUs and memory. git-pack-objects(1) may
16 # also use threads and bust memory limits, too, so I recommend
17 # limiting threads to 1 (via `pack.threads` knob in git) for serving.
21 # n.b. serving "description" and "cloneurl" should be innocuous enough to
22 # not cause problems. serving "config" might...
23 my @text = qw[HEAD info/refs
24 objects/info/(?:http-alternates|alternates|packs)
25 cloneurl description];
28 objects/[a-f0-9]{2}/[a-f0-9]{38}
29 objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
32 our $ANY = join('|', @binary, @text);
33 my $BIN = join('|', @binary);
34 my $TEXT = join('|', @text);
40 while (my $cb = shift @$q) {
41 $cb->(); # this may redefine nextq
46 [ $_[0] , [qw(Content-Type text/plain Content-Length 0) ], [] ]
50 my ($cgi, $git, $path) = @_;
51 return serve_dumb($cgi, $git, $path) if $nr_running >= $LIMIT;
53 my $service = $cgi->param('service') || '';
54 if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
55 my $ok = serve_smart($cgi, $git, $path);
59 serve_dumb($cgi, $git, $path);
64 $env->{'psgi.errors'}->print(@msg, "\n");
68 if (my $io = $_[0]->{'psgix.io'}) {
69 $io->close; # this is Danga::Socket::close
74 my ($cgi, $git, $path) = @_;
77 if ($path =~ /\A(?:$BIN)\z/o) {
78 $type = 'application/octet-stream';
79 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
85 my $f = "$git->{git_dir}/$path";
86 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
89 my $env = $cgi->{env};
91 # TODO: If-Modified-Since and Last-Modified?
92 open my $in, '<', $f or return r(404);
94 my $n = 65536; # try to negotiate a big TCP window, first
97 $n = $len if $len < $n;
98 my $r = sysread($in, my $buf, $n);
100 err($env, "$f read error: $!");
103 err($env, "$f EOF with $len bytes left");
111 # avoid recursion in Danga::Socket::write
114 Danga::Socket->AddTimer(0, *do_next);
116 # avoid buffering too much in case we have
123 # all done, cleanup references:
128 my @h = ('Content-Type', $type);
129 my $range = $env->{HTTP_RANGE};
130 if (defined $range && $range =~ /\bbytes=(\d*)-(\d*)\z/) {
131 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
133 push @h, 'Content-Range', "bytes */$size";
134 return [ 416, \@h, [] ];
137 push @h, 'Content-Length', $len;
140 my ($res) = @_; # Plack callback
141 $fh = $res->([ $code, \@h ]);
142 if (defined $env->{'pi-httpd.async'}) {
143 my $pi_http = $env->{'psgix.io'};
144 $next = sub { $pi_http->write($cb) };
145 $cb->(); # start it off!
153 my ($cgi, $in, $h, $beg, $end, $size) = @_;
157 if ($end ne '') { # "bytes=-$end" => last N bytes
159 $beg = 0 if $beg < 0;
168 } elsif ($end eq '' || $end >= $size) {
171 } elsif ($end < $size) {
178 $len = $end - $beg + 1;
182 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
183 push @$h, qw(Accept-Ranges bytes Content-Range);
184 push @$h, "bytes $beg-$end/$size";
186 # FIXME: Plack::Middleware::Deflater bug?
187 $cgi->{env}->{'psgix.no-compress'} = 1;
193 # returns undef if 403 so it falls back to dumb HTTP
195 my ($cgi, $git, $path) = @_;
196 my $env = $cgi->{env};
198 my $input = $env->{'psgi.input'};
201 my $fd = eval { fileno($input) };
202 if (defined $fd && $fd >= 0) {
205 $in = input_to_file($env) or return r(500);
208 unless (pipe($rpipe, $wpipe)) {
209 err($env, "error creating pipe: $! - going static");
213 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
214 # may be set in the server-process and are passed as-is
215 foreach my $name (qw(QUERY_STRING
216 REMOTE_USER REMOTE_ADDR
217 HTTP_CONTENT_ENCODING
221 my $val = $env->{$name};
222 $env{$name} = $val if defined $val;
224 my $git_dir = $git->{git_dir};
225 $env{GIT_HTTP_EXPORT_ALL} = '1';
226 $env{PATH_TRANSLATED} = "$git_dir/$path";
227 my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
228 my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
229 unless (defined $pid) {
230 err($env, "error spawning: $! - going static");
233 $wpipe = $in = undef;
235 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:
260 my $e = $pid == waitpid($pid, 0) ?
261 $? : "PID:$pid still running?";
263 err($env, "git http-backend ($git_dir): $e");
268 my $dumb = serve_dumb($cgi, $git, $path);
269 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
272 if ($!{EAGAIN} || $!{EINTR}) {
273 select($vin, undef, undef, undef) if defined $vin;
274 # $vin is undef on async, so this is a noop on EAGAIN
279 err($env, "git http-backend ($git_dir): $e\n");
281 my $cb = sub { # read git-http-backend output and stream to client
282 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
283 return $fail->() unless defined $r;
284 return $end->() if $r == 0; # EOF
285 if ($fh) { # stream body from git-http-backend to HTTP client
288 $read_disable->() if $read_disable;
289 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
293 foreach my $l (split(/\r\n/, $h)) {
294 my ($k, $v) = split(/:\s*/, $l, 2);
295 if ($k =~ /\AStatus\z/i) {
296 ($code) = ($v =~ /\b(\d+)\b/);
302 # smart cloning disabled, serve dumbly
303 # in $end since we never undef $res in here
304 } else { # write response header:
305 $fh = $res->([ $code, \@h ]);
310 } # else { keep reading ... }
312 if (my $async = $env->{'pi-httpd.async'}) {
313 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
314 $rpipe = $async->($rpipe, $cb);
315 sub { ($res) = @_ } # let Danga::Socket handle the rest.
316 } else { # synchronous loop for other PSGI servers
317 $read_enable = $read_disable = undef;
319 vec($vin, fileno($rpipe), 1) = 1;
322 while ($rpipe) { $cb->() }
329 my $in = IO::File->new_tmpfile;
330 my $input = $env->{'psgi.input'};
333 my $r = $input->read($buf, 8192);
334 unless (defined $r) {
335 err($env, "error reading input: $!");
342 $in->sysseek(0, SEEK_SET);