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');
35 my ($code, $msg) = @_;
36 $msg ||= status_message($code);
37 my $len = length($msg);
38 [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
43 my ($cgi, $git, $path) = @_;
45 my $service = $cgi->query_parameters->get('service') || '';
46 if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
47 my $ok = serve_smart($cgi, $git, $path);
51 serve_dumb($cgi, $git, $path);
56 $env->{'psgi.errors'}->print(@msg, "\n");
60 if (my $io = $_[0]->{'psgix.io'}) {
61 $io->close; # this is Danga::Socket::close
66 my ($cgi, $git, $path) = @_;
70 if ($path =~ /\A(?:$BIN)\z/o) {
71 $type = 'application/octet-stream';
72 push @h, 'Expires', time2str(time + 31536000);
73 push @h, 'Cache-Control', 'public, max-age=31536000';
74 } elsif ($path =~ /\A(?:$TEXT)\z/o) {
81 my $f = "$git->{git_dir}/$path";
82 return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
85 my $env = $cgi->{env};
87 # TODO: If-Modified-Since and Last-Modified?
88 open my $in, '<', $f or return r(404);
91 push @h, 'Content-Type', $type;
92 if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
93 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
95 push @h, 'Content-Range', "bytes */$size";
96 return [ 416, \@h, [] ];
99 push @h, 'Content-Length', $len;
101 [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
104 $n = $len if $len < $n;
105 my $r = sysread($in, my $buf, $n);
107 err($env, "$f read error: $!");
109 err($env, "$f EOF with $len bytes left");
121 my ($cgi, $in, $h, $beg, $end, $size) = @_;
125 if ($end ne '') { # "bytes=-$end" => last N bytes
127 $beg = 0 if $beg < 0;
136 } elsif ($end eq '' || $end >= $size) {
139 } elsif ($end < $size) {
146 $len = $end - $beg + 1;
150 sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
151 push @$h, qw(Accept-Ranges bytes Content-Range);
152 push @$h, "bytes $beg-$end/$size";
154 # FIXME: Plack::Middleware::Deflater bug?
155 $cgi->{env}->{'psgix.no-compress'} = 1;
161 # returns undef if 403 so it falls back to dumb HTTP
163 my ($cgi, $git, $path) = @_;
164 my $env = $cgi->{env};
165 my $in = $env->{'psgi.input'};
166 my $fd = eval { fileno($in) };
167 unless (defined $fd && $fd >= 0) {
168 $in = input_to_file($env) or return r(500);
171 unless (pipe($rpipe, $wpipe)) {
172 err($env, "error creating pipe: $! - going static");
176 # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
177 # may be set in the server-process and are passed as-is
178 foreach my $name (qw(QUERY_STRING
179 REMOTE_USER REMOTE_ADDR
180 HTTP_CONTENT_ENCODING
184 my $val = $env->{$name};
185 $env{$name} = $val if defined $val;
187 my $git_dir = $git->{git_dir};
188 $env{GIT_HTTP_EXPORT_ALL} = '1';
189 $env{PATH_TRANSLATED} = "$git_dir/$path";
190 my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
191 my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
192 unless (defined $pid) {
193 err($env, "error spawning: $! - going static");
196 $wpipe = $in = undef;
199 my $e = $pid == waitpid($pid, 0) ?
200 $? : "PID:$pid still running?";
202 err($env, "git http-backend ($git_dir): $e");
207 # Danga::Socket users, we queue up the read_enable callback to
208 # fire after pending writes are complete:
210 if (my $async = $env->{'pi-httpd.async'}) {
217 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
218 $async = $async->($rpipe, sub {
219 my $r = sysread($rpipe, $buf, 1024, length($buf));
220 if (!defined $r || $r == 0) {
221 return $q->(r(500, 'http-backend error'));
223 $r = parse_cgi_headers(\$buf) or return;
224 if ($r->[0] == 403) {
225 return $q->(serve_dumb($cgi, $git, $path));
230 my $dst = Plack::Util::inline_object(
231 write => sub { $fh->write(@_) },
236 $async->async_pass($env->{'psgix.io'}, $dst);
238 sub { ($res) = @_ }; # let Danga::Socket handle the rest.
239 } else { # getline + close for other PSGI servers
242 $r = read($rpipe, $buf, 1024, length($buf));
243 if (!defined $r || $r == 0) {
244 return r(500, 'http-backend error');
246 $r = parse_cgi_headers(\$buf);
248 return serve_dumb($cgi, $git, $path) if $r->[0] == 403;
249 $r->[2] = Plack::Util::inline_object(
250 close => sub { $end->() },
254 defined $ret ? $ret : $rpipe->getline;
263 my $in = IO::File->new_tmpfile;
264 my $input = $env->{'psgi.input'};
267 my $r = $input->read($buf, 8192);
268 unless (defined $r) {
269 err($env, "error reading input: $!");
276 $in->sysseek(0, SEEK_SET);
280 sub parse_cgi_headers {
282 $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
286 foreach my $l (split(/\r\n/, $h)) {
287 my ($k, $v) = split(/:\s*/, $l, 2);
288 if ($k =~ /\AStatus\z/i) {
289 ($code) = ($v =~ /\b(\d+)\b/);