]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: use qspawn to limit running processes
[public-inbox.git] / lib / PublicInbox / GitHTTPBackend.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # when no endpoints match, fallback to this and serve a static file
5 # or smart HTTP
6 package PublicInbox::GitHTTPBackend;
7 use strict;
8 use warnings;
9 use Fcntl qw(:seek);
10 use IO::File;
11 use HTTP::Date qw(time2str);
12 use HTTP::Status qw(status_message);
13 use PublicInbox::Qspawn;
14
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];
20
21 my @binary = qw!
22         objects/[a-f0-9]{2}/[a-f0-9]{38}
23         objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
24         !;
25
26 our $ANY = join('|', @binary, @text);
27 my $BIN = join('|', @binary);
28 my $TEXT = join('|', @text);
29
30 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
31                 'Pragma', 'no-cache',
32                 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
33
34 sub r ($;$) {
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],
39                 [$msg] ]
40 }
41
42 sub serve {
43         my ($cgi, $git, $path) = @_;
44
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);
48                 return $ok if $ok;
49         }
50
51         serve_dumb($cgi, $git, $path);
52 }
53
54 sub err ($@) {
55         my ($env, @msg) = @_;
56         $env->{'psgi.errors'}->print(@msg, "\n");
57 }
58
59 sub drop_client ($) {
60         if (my $io = $_[0]->{'psgix.io'}) {
61                 $io->close; # this is Danga::Socket::close
62         }
63 }
64
65 sub serve_dumb {
66         my ($cgi, $git, $path) = @_;
67
68         my @h;
69         my $type;
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) {
75                 $type = 'text/plain';
76                 push @h, @no_cache;
77         } else {
78                 return r(404);
79         }
80
81         my $f = "$git->{git_dir}/$path";
82         return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
83         my @st = stat(_);
84         my $size = $st[7];
85         my $env = $cgi->{env};
86
87         # TODO: If-Modified-Since and Last-Modified?
88         open my $in, '<', $f or return r(404);
89         my $len = $size;
90         my $code = 200;
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);
94                 if ($code == 416) {
95                         push @h, 'Content-Range', "bytes */$size";
96                         return [ 416, \@h, [] ];
97                 }
98         }
99         push @h, 'Content-Length', $len;
100         my $n = 65536;
101         [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
102                 getline => sub {
103                         return if $len == 0;
104                         $n = $len if $len < $n;
105                         my $r = sysread($in, my $buf, $n);
106                         if (!defined $r) {
107                                 err($env, "$f read error: $!");
108                         } elsif ($r <= 0) {
109                                 err($env, "$f EOF with $len bytes left");
110                         } else {
111                                 $len -= $r;
112                                 $n = 8192;
113                                 return $buf;
114                         }
115                         drop_client($env);
116                         return;
117                 })]
118 }
119
120 sub prepare_range {
121         my ($cgi, $in, $h, $beg, $end, $size) = @_;
122         my $code = 200;
123         my $len = $size;
124         if ($beg eq '') {
125                 if ($end ne '') { # "bytes=-$end" => last N bytes
126                         $beg = $size - $end;
127                         $beg = 0 if $beg < 0;
128                         $end = $size - 1;
129                         $code = 206;
130                 } else {
131                         $code = 416;
132                 }
133         } else {
134                 if ($beg > $size) {
135                         $code = 416;
136                 } elsif ($end eq '' || $end >= $size) {
137                         $end = $size - 1;
138                         $code = 206;
139                 } elsif ($end < $size) {
140                         $code = 206;
141                 } else {
142                         $code = 416;
143                 }
144         }
145         if ($code == 206) {
146                 $len = $end - $beg + 1;
147                 if ($len <= 0) {
148                         $code = 416;
149                 } else {
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";
153
154                         # FIXME: Plack::Middleware::Deflater bug?
155                         $cgi->{env}->{'psgix.no-compress'} = 1;
156                 }
157         }
158         ($code, $len);
159 }
160
161 # returns undef if 403 so it falls back to dumb HTTP
162 sub serve_smart {
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);
169         }
170         my %env = %ENV;
171         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
172         # may be set in the server-process and are passed as-is
173         foreach my $name (qw(QUERY_STRING
174                                 REMOTE_USER REMOTE_ADDR
175                                 HTTP_CONTENT_ENCODING
176                                 CONTENT_TYPE
177                                 SERVER_PROTOCOL
178                                 REQUEST_METHOD)) {
179                 my $val = $env->{$name};
180                 $env{$name} = $val if defined $val;
181         }
182         my $git_dir = $git->{git_dir};
183         $env{GIT_HTTP_EXPORT_ALL} = '1';
184         $env{PATH_TRANSLATED} = "$git_dir/$path";
185         my %rdr = ( 0 => fileno($in) );
186         my $x = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, \%rdr);
187         my ($fh, $rpipe);
188         my $end = sub {
189                 $rpipe = undef;
190                 if (my $err = $x->finish) {
191                         err($env, "git http-backend ($git_dir): $err");
192                         drop_client($env);
193                 }
194                 $fh->close if $fh; # async-only
195         };
196
197         # Danga::Socket users, we queue up the read_enable callback to
198         # fire after pending writes are complete:
199         my $buf = '';
200         my $rd_hdr = sub {
201                 my $r = sysread($rpipe, $buf, 1024, length($buf));
202                 return if !defined($r) && ($!{EINTR} || $!{EAGAIN});
203                 return r(500, 'http-backend error') unless $r;
204                 $r = parse_cgi_headers(\$buf) or return;
205                 $r->[0] == 403 ? serve_dumb($cgi, $git, $path) : $r;
206         };
207         my $res;
208         my $async = $env->{'pi-httpd.async'};
209         my $io = $env->{'psgix.io'};
210         my $cb = sub {
211                 my $r = $rd_hdr->() or return;
212                 $rd_hdr = undef;
213                 if (scalar(@$r) == 3) { # error:
214                         $async->close if $async;
215                         return $res->($r);
216                 }
217                 if ($async) {
218                         $fh = $res->($r);
219                         return $async->async_pass($io, $fh, \$buf);
220                 }
221
222                 # for synchronous PSGI servers
223                 $r->[2] = Plack::Util::inline_object(
224                         close => $end,
225                         getline => sub {
226                                 my $ret = $buf;
227                                 $buf = undef;
228                                 defined $ret ? $ret : $rpipe->getline;
229                         });
230                 $res->($r);
231         };
232         sub {
233                 ($res) = @_;
234
235                 # hopefully this doesn't break any middlewares,
236                 # holding the input here is a waste of FDs and memory
237                 $env->{'psgi.input'} = undef;
238
239                 $x->start(sub { # may run later, much later...
240                         ($rpipe) = @_;
241                         $in = undef;
242                         if ($async) {
243                                 $async = $async->($rpipe, $cb, $end);
244                         } else { # generic PSGI
245                                 $cb->() while $rd_hdr;
246                         }
247                 });
248         };
249 }
250
251 sub input_to_file {
252         my ($env) = @_;
253         my $in = IO::File->new_tmpfile;
254         my $input = $env->{'psgi.input'};
255         my $buf;
256         while (1) {
257                 my $r = $input->read($buf, 8192);
258                 unless (defined $r) {
259                         err($env, "error reading input: $!");
260                         return;
261                 }
262                 last if ($r == 0);
263                 $in->write($buf);
264         }
265         $in->flush;
266         $in->sysseek(0, SEEK_SET);
267         return $in;
268 }
269
270 sub parse_cgi_headers {
271         my ($bref) = @_;
272         $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
273         my $h = $1;
274         my $code = 200;
275         my @h;
276         foreach my $l (split(/\r\n/, $h)) {
277                 my ($k, $v) = split(/:\s*/, $l, 2);
278                 if ($k =~ /\AStatus\z/i) {
279                         ($code) = ($v =~ /\b(\d+)\b/);
280                 } else {
281                         push @h, $k, $v;
282                 }
283         }
284         [ $code, \@h ]
285 }
286
287 1;