]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: switch to async_pass
[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 PublicInbox::Spawn qw(spawn);
12 use HTTP::Date qw(time2str);
13 use HTTP::Status qw(status_message);
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 my $nextq;
35 sub do_next () {
36         my $q = $nextq;
37         $nextq = undef;
38         while (my $cb = shift @$q) {
39                 $cb->(); # this may redefine nextq
40         }
41 }
42
43 sub r ($;$) {
44         my ($code, $msg) = @_;
45         $msg ||= status_message($code);
46         my $len = length($msg);
47         [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
48                 [$msg] ]
49 }
50
51 sub serve {
52         my ($cgi, $git, $path) = @_;
53
54         my $service = $cgi->param('service') || '';
55         if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
56                 my $ok = serve_smart($cgi, $git, $path);
57                 return $ok if $ok;
58         }
59
60         serve_dumb($cgi, $git, $path);
61 }
62
63 sub err ($@) {
64         my ($env, @msg) = @_;
65         $env->{'psgi.errors'}->print(@msg, "\n");
66 }
67
68 sub drop_client ($) {
69         if (my $io = $_[0]->{'psgix.io'}) {
70                 $io->close; # this is Danga::Socket::close
71         }
72 }
73
74 sub serve_dumb {
75         my ($cgi, $git, $path) = @_;
76
77         my @h;
78         my $type;
79         if ($path =~ /\A(?:$BIN)\z/o) {
80                 $type = 'application/octet-stream';
81                 push @h, 'Expires', time2str(time + 31536000);
82                 push @h, 'Cache-Control', 'public, max-age=31536000';
83         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
84                 $type = 'text/plain';
85                 push @h, @no_cache;
86         } else {
87                 return r(404);
88         }
89
90         my $f = "$git->{git_dir}/$path";
91         return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
92         my @st = stat(_);
93         my $size = $st[7];
94         my $env = $cgi->{env};
95
96         # TODO: If-Modified-Since and Last-Modified?
97         open my $in, '<', $f or return r(404);
98         my $len = $size;
99         my $code = 200;
100         push @h, 'Content-Type', $type;
101         if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
102                 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
103                 if ($code == 416) {
104                         push @h, 'Content-Range', "bytes */$size";
105                         return [ 416, \@h, [] ];
106                 }
107         }
108         push @h, 'Content-Length', $len;
109         my $n = 65536;
110         [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
111                 getline => sub {
112                         return if $len == 0;
113                         $n = $len if $len < $n;
114                         my $r = sysread($in, my $buf, $n);
115                         if (!defined $r) {
116                                 err($env, "$f read error: $!");
117                         } elsif ($r <= 0) {
118                                 err($env, "$f EOF with $len bytes left");
119                         } else {
120                                 $len -= $r;
121                                 $n = 8192;
122                                 return $buf;
123                         }
124                         drop_client($env);
125                         return;
126                 })]
127 }
128
129 sub prepare_range {
130         my ($cgi, $in, $h, $beg, $end, $size) = @_;
131         my $code = 200;
132         my $len = $size;
133         if ($beg eq '') {
134                 if ($end ne '') { # "bytes=-$end" => last N bytes
135                         $beg = $size - $end;
136                         $beg = 0 if $beg < 0;
137                         $end = $size - 1;
138                         $code = 206;
139                 } else {
140                         $code = 416;
141                 }
142         } else {
143                 if ($beg > $size) {
144                         $code = 416;
145                 } elsif ($end eq '' || $end >= $size) {
146                         $end = $size - 1;
147                         $code = 206;
148                 } elsif ($end < $size) {
149                         $code = 206;
150                 } else {
151                         $code = 416;
152                 }
153         }
154         if ($code == 206) {
155                 $len = $end - $beg + 1;
156                 if ($len <= 0) {
157                         $code = 416;
158                 } else {
159                         sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
160                         push @$h, qw(Accept-Ranges bytes Content-Range);
161                         push @$h, "bytes $beg-$end/$size";
162
163                         # FIXME: Plack::Middleware::Deflater bug?
164                         $cgi->{env}->{'psgix.no-compress'} = 1;
165                 }
166         }
167         ($code, $len);
168 }
169
170 # returns undef if 403 so it falls back to dumb HTTP
171 sub serve_smart {
172         my ($cgi, $git, $path) = @_;
173         my $env = $cgi->{env};
174         my $in = $env->{'psgi.input'};
175         my $fd = eval { fileno($in) };
176         unless (defined $fd && $fd >= 0) {
177                 $in = input_to_file($env) or return r(500);
178         }
179         my ($rpipe, $wpipe);
180         unless (pipe($rpipe, $wpipe)) {
181                 err($env, "error creating pipe: $! - going static");
182                 return;
183         }
184         my %env = %ENV;
185         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
186         # may be set in the server-process and are passed as-is
187         foreach my $name (qw(QUERY_STRING
188                                 REMOTE_USER REMOTE_ADDR
189                                 HTTP_CONTENT_ENCODING
190                                 CONTENT_TYPE
191                                 SERVER_PROTOCOL
192                                 REQUEST_METHOD)) {
193                 my $val = $env->{$name};
194                 $env{$name} = $val if defined $val;
195         }
196         my $git_dir = $git->{git_dir};
197         $env{GIT_HTTP_EXPORT_ALL} = '1';
198         $env{PATH_TRANSLATED} = "$git_dir/$path";
199         my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
200         my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
201         unless (defined $pid) {
202                 err($env, "error spawning: $! - going static");
203                 return;
204         }
205         $wpipe = $in = undef;
206         my $end = sub {
207                 $rpipe = undef;
208                 my $e = $pid == waitpid($pid, 0) ?
209                         $? : "PID:$pid still running?";
210                 if ($e) {
211                         err($env, "git http-backend ($git_dir): $e");
212                         drop_client($env);
213                 }
214         };
215
216         # Danga::Socket users, we queue up the read_enable callback to
217         # fire after pending writes are complete:
218         my $buf = '';
219         if (my $async = $env->{'pi-httpd.async'}) {
220                 my $res;
221                 my $q = sub {
222                         $async->close;
223                         $end->();
224                         $res->(@_);
225                 };
226                 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
227                 $async = $async->($rpipe, sub {
228                         my $r = sysread($rpipe, $buf, 1024, length($buf));
229                         if (!defined $r || $r == 0) {
230                                 return $q->(r(500, 'http-backend error'));
231                         }
232                         $r = parse_cgi_headers(\$buf) or return;
233                         if ($r->[0] == 403) {
234                                 return $q->(serve_dumb($cgi, $git, $path));
235                         }
236                         my $fh = $res->($r);
237                         $fh->write($buf);
238                         $buf = undef;
239                         my $dst = Plack::Util::inline_object(
240                                 write => sub { $fh->write(@_) },
241                                 close => sub {
242                                         $end->();
243                                         $fh->close;
244                                 });
245                         $async->async_pass($env->{'psgix.io'}, $dst);
246                 });
247                 sub { ($res) = @_ }; # let Danga::Socket handle the rest.
248         } else { # getline + close for other PSGI servers
249                 my $r;
250                 do {
251                         $r = read($rpipe, $buf, 1024, length($buf));
252                         if (!defined $r || $r == 0) {
253                                 return r(500, 'http-backend error');
254                         }
255                         $r = parse_cgi_headers(\$buf);
256                 } until ($r);
257                 return serve_dumb($cgi, $git, $path) if $r->[0] == 403;
258                 $r->[2] = Plack::Util::inline_object(
259                         close => sub { $end->() },
260                         getline => sub {
261                                 my $ret = $buf;
262                                 $buf = undef;
263                                 defined $ret ? $ret : $rpipe->getline;
264                         });
265                 $r;
266
267         }
268 }
269
270 sub input_to_file {
271         my ($env) = @_;
272         my $in = IO::File->new_tmpfile;
273         my $input = $env->{'psgi.input'};
274         my $buf;
275         while (1) {
276                 my $r = $input->read($buf, 8192);
277                 unless (defined $r) {
278                         err($env, "error reading input: $!");
279                         return;
280                 }
281                 last if ($r == 0);
282                 $in->write($buf);
283         }
284         $in->flush;
285         $in->sysseek(0, SEEK_SET);
286         return $in;
287 }
288
289 sub parse_cgi_headers {
290         my ($bref) = @_;
291         $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
292         my $h = $1;
293         my $code = 200;
294         my @h;
295         foreach my $l (split(/\r\n/, $h)) {
296                 my ($k, $v) = split(/:\s*/, $l, 2);
297                 if ($k =~ /\AStatus\z/i) {
298                         ($code) = ($v =~ /\b(\d+)\b/);
299                 } else {
300                         push @h, $k, $v;
301                 }
302         }
303         [ $code, \@h ]
304 }
305
306 1;