]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTP.pm
http: fix various race conditions
[public-inbox.git] / lib / PublicInbox / HTTP.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 # Generic PSGI server for convenience.  It aims to provide
5 # a consistent experience for public-inbox admins so they don't have
6 # to learn different ways to admin both NNTP and HTTP components.
7 # There's nothing public-inbox-specific, here.
8 # Each instance of this class represents a HTTP client socket
9
10 package PublicInbox::HTTP;
11 use strict;
12 use warnings;
13 use base qw(Danga::Socket);
14 use fields qw(httpd env rbuf input_left remote_addr remote_port forward);
15 use Fcntl qw(:seek);
16 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
17 use HTTP::Status qw(status_message);
18 use HTTP::Date qw(time2str);
19 use IO::File;
20 use constant {
21         CHUNK_START => -1,   # [a-f0-9]+\r\n
22         CHUNK_END => -2,     # \r\n
23         CHUNK_ZEND => -3,    # \r\n
24         CHUNK_MAX_HDR => 256,
25 };
26
27 # FIXME: duplicated code with NNTP.pm
28 my $WEAKEN = {}; # string(inbox) -> inbox
29 my $weakt;
30 sub weaken_task () {
31         $weakt = undef;
32         $_->weaken_all for values %$WEAKEN;
33         $WEAKEN = {};
34 }
35
36 my $pipelineq = [];
37 my $pipet;
38 sub process_pipelineq () {
39         my $q = $pipelineq;
40         $pipet = undef;
41         $pipelineq = [];
42         foreach (@$q) {
43                 next if $_->{closed};
44                 rbuf_process($_);
45         }
46 }
47
48 # Use the same configuration parameter as git since this is primarily
49 # a slow-client sponge for git-http-backend
50 # TODO: support per-respository http.maxRequestBuffer somehow...
51 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
52                         (10 * 1024 * 1024);
53
54 my $null_io = IO::File->new('/dev/null', '<');
55 my $http_date;
56 my $prev = 0;
57 sub http_date () {
58         my $now = time;
59         $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
60 }
61
62 sub new ($$$) {
63         my ($class, $sock, $addr, $httpd) = @_;
64         my $self = fields::new($class);
65         $self->SUPER::new($sock);
66         $self->{httpd} = $httpd;
67         $self->{rbuf} = '';
68         ($self->{remote_addr}, $self->{remote_port}) =
69                 PublicInbox::Daemon::host_with_port($addr);
70         $self->watch_read(1);
71         $self;
72 }
73
74 sub event_read { # called by Danga::Socket
75         my ($self) = @_;
76
77         return event_read_input($self) if defined $self->{env};
78
79         my $off = length($self->{rbuf});
80         my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
81         if (defined $r) {
82                 return $self->close if $r == 0;
83                 return rbuf_process($self);
84         }
85         return if $!{EAGAIN}; # no need to call watch_read(1) again
86
87         # common for clients to break connections without warning,
88         # would be too noisy to log here:
89         return $self->close;
90 }
91
92 sub rbuf_process {
93         my ($self) = @_;
94
95         my %env = %{$self->{httpd}->{env}}; # full hash copy
96         my $r = parse_http_request($self->{rbuf}, \%env);
97
98         # We do not support Trailers in chunked requests, for now
99         # (they are rarely-used and git (as of 2.7.2) does not use them)
100         if ($r == -1 || $env{HTTP_TRAILER} ||
101                         # this length-check is necessary for PURE_PERL=1:
102                         ($r == -2 && length($self->{rbuf}) > 0x4000)) {
103                 return quit($self, 400);
104         }
105         return $self->watch_read(1) if $r < 0; # incomplete
106         $self->{rbuf} = substr($self->{rbuf}, $r);
107
108         my $len = input_prepare($self, \%env);
109         defined $len or return write_err($self); # EMFILE/ENFILE
110
111         $len ? event_read_input($self) : app_dispatch($self);
112 }
113
114 sub event_read_input ($) {
115         my ($self) = @_;
116         my $env = $self->{env};
117         return event_read_input_chunked($self) if env_chunked($env);
118
119         # env->{CONTENT_LENGTH} (identity)
120         my $sock = $self->{sock};
121         my $len = $self->{input_left};
122         $self->{input_left} = undef;
123         my $rbuf = \($self->{rbuf});
124         my $input = $env->{'psgi.input'};
125
126         while ($len > 0) {
127                 if ($$rbuf ne '') {
128                         my $w = write_in_full($input, $rbuf, $len);
129                         return write_err($self) unless $w;
130                         $len -= $w;
131                         die "BUG: $len < 0 (w=$w)" if $len < 0;
132                         if ($len == 0) { # next request may be pipelined
133                                 $$rbuf = substr($$rbuf, $w);
134                                 last;
135                         }
136                         $$rbuf = '';
137                 }
138                 my $r = sysread($sock, $$rbuf, 8192);
139                 return recv_err($self, $r, $len) unless $r;
140                 # continue looping if $r > 0;
141         }
142         app_dispatch($self, $input);
143 }
144
145 sub app_dispatch {
146         my ($self, $input) = @_;
147         $self->watch_read(0);
148         my $env = $self->{env};
149         $env->{REMOTE_ADDR} = $self->{remote_addr};
150         $env->{REMOTE_PORT} = $self->{remote_port};
151         if (my $host = $env->{HTTP_HOST}) {
152                 $host =~ s/:(\d+)\z// and $env->{SERVER_PORT} = $1;
153                 $env->{SERVER_NAME} = $host;
154         }
155         if (defined $input) {
156                 sysseek($input, 0, SEEK_SET) or
157                         die "BUG: psgi.input seek failed: $!";
158         }
159         # note: NOT $self->{sock}, we want our close (+ Danga::Socket::close),
160         # to do proper cleanup:
161         $env->{'psgix.io'} = $self; # only for ->close
162         my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
163         eval {
164                 if (ref($res) eq 'CODE') {
165                         $res->(sub { response_write($self, $env, $_[0]) });
166                 } else {
167                         response_write($self, $env, $res);
168                 }
169         };
170         $self->close if $@;
171 }
172
173 sub response_header_write {
174         my ($self, $env, $res) = @_;
175         my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
176         my $status = $res->[0];
177         my $h = "$proto $status " . status_message($status) . "\r\n";
178         my ($len, $chunked);
179         my $headers = $res->[1];
180
181         for (my $i = 0; $i < @$headers; $i += 2) {
182                 my $k = $headers->[$i];
183                 my $v = $headers->[$i + 1];
184                 next if $k =~ /\A(?:Connection|Date)\z/i;
185
186                 $len = $v if $k =~ /\AContent-Length\z/i;
187                 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
188                         $chunked = 1;
189                 }
190                 $h .= "$k: $v\r\n";
191         }
192
193         my $conn = $env->{HTTP_CONNECTION} || '';
194         my $term = defined($len) || $chunked;
195         my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
196         my $alive;
197         if (!$term && $prot_persist) { # auto-chunk
198                 $chunked = $alive = 2;
199                 $h .= "Transfer-Encoding: chunked\r\n";
200                 # no need for "Connection: keep-alive" with HTTP/1.1
201         } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
202                 $alive = 1;
203                 $h .= "Connection: keep-alive\r\n";
204         } else {
205                 $alive = 0;
206                 $h .= "Connection: close\r\n";
207         }
208         $h .= 'Date: ' . http_date() . "\r\n\r\n";
209
210         if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
211                 more($self, $h);
212         } else {
213                 $self->write($h);
214         }
215         $alive;
216 }
217
218 # middlewares such as Deflater may write empty strings
219 sub chunked_wcb ($) {
220         my ($self) = @_;
221         sub {
222                 return if $_[0] eq '';
223                 more($self, sprintf("%x\r\n", bytes::length($_[0])));
224                 more($self, $_[0]);
225                 $self->write("\r\n");
226         }
227 }
228
229 sub identity_wcb ($) {
230         my ($self) = @_;
231         sub { $self->write(\($_[0])) if $_[0] ne '' }
232 }
233
234 sub next_request ($) {
235         my ($self) = @_;
236         $self->watch_write(0);
237         if ($self->{rbuf} eq '') { # wait for next request
238                 $self->watch_read(1);
239         } else { # avoid recursion for pipelined requests
240                 push @$pipelineq, $self;
241                 $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
242         }
243 }
244
245 sub response_done ($$) {
246         my ($self, $alive) = @_;
247         my $env = $self->{env};
248         $self->{env} = undef;
249         $self->write("0\r\n\r\n") if $alive == 2;
250         $self->write(sub { $alive ? next_request($self) : $self->close });
251         if (my $obj = $env->{'pi-httpd.inbox'}) {
252                 # grace period for reaping resources
253                 $WEAKEN->{"$obj"} = $obj;
254                 PublicInbox::EvCleanup::later(*weaken_task);
255         }
256 }
257
258 sub response_write {
259         my ($self, $env, $res) = @_;
260         my $alive = response_header_write($self, $env, $res);
261
262         my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
263         my $close = sub { response_done($self, $alive) };
264         if (defined(my $body = $res->[2])) {
265                 if (ref $body eq 'ARRAY') {
266                         $write->($_) foreach @$body;
267                         $close->();
268                 } else {
269                         my $pull;
270                         $pull = sub {
271                                 local $/ = \8192;
272                                 while (defined(my $buf = $body->getline)) {
273                                         $write->($buf);
274                                         if ($self->{write_buf_size}) {
275                                                 $self->write($pull);
276                                                 return;
277                                         }
278                                 }
279                                 $pull = undef;
280                                 $body->close();
281                                 $close->();
282                         };
283                         $pull->();
284                 }
285         } else {
286                 # this is returned to the calling application:
287                 Plack::Util::inline_object(write => $write, close => $close);
288         }
289 }
290
291 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
292 sub more ($$) {
293         my $self = $_[0];
294         return if $self->{closed};
295         if (MSG_MORE && !$self->{write_buf_size}) {
296                 my $n = send($self->{sock}, $_[1], MSG_MORE);
297                 if (defined $n) {
298                         my $dlen = length($_[1]);
299                         return 1 if $n == $dlen; # all done!
300                         $_[1] = substr($_[1], $n, $dlen - $n);
301                         # fall through to normal write:
302                 }
303         }
304         $self->write($_[1]);
305 }
306
307 sub input_prepare {
308         my ($self, $env) = @_;
309         my $input = $null_io;
310         my $len = $env->{CONTENT_LENGTH};
311         if ($len) {
312                 if ($len > $MAX_REQUEST_BUFFER) {
313                         quit($self, 413);
314                         return;
315                 }
316                 $input = IO::File->new_tmpfile;
317         } elsif (env_chunked($env)) {
318                 $len = CHUNK_START;
319                 $input = IO::File->new_tmpfile;
320         }
321
322         # TODO: expire idle clients on ENFILE / EMFILE
323         return unless $input;
324
325         $env->{'psgi.input'} = $input;
326         $self->{env} = $env;
327         $self->{input_left} = $len || 0;
328 }
329
330 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
331
332 sub write_err {
333         my ($self) = @_;
334         my $err = $self->{httpd}->{env}->{'psgi.errors'};
335         my $msg = $! || '(zero write)';
336         $err->print("error buffering to input: $msg\n");
337         quit($self, 500);
338 }
339
340 sub recv_err {
341         my ($self, $r, $len) = @_;
342         return $self->close if (defined $r && $r == 0);
343         if ($!{EAGAIN}) {
344                 $self->{input_left} = $len;
345                 return;
346         }
347         my $err = $self->{httpd}->{env}->{'psgi.errors'};
348         $err->print("error reading for input: $! ($len bytes remaining)\n");
349         quit($self, 500);
350 }
351
352 sub write_in_full {
353         my ($fh, $rbuf, $len) = @_;
354         my $rv = 0;
355         my $off = 0;
356         while ($len > 0) {
357                 my $w = syswrite($fh, $$rbuf, $len, $off);
358                 return ($rv ? $rv : $w) unless $w; # undef or 0
359                 $rv += $w;
360                 $off += $w;
361                 $len -= $w;
362         }
363         $rv
364 }
365
366 sub event_read_input_chunked { # unlikely...
367         my ($self) = @_;
368         my $input = $self->{env}->{'psgi.input'};
369         my $sock = $self->{sock};
370         my $len = $self->{input_left};
371         $self->{input_left} = undef;
372         my $rbuf = \($self->{rbuf});
373
374         while (1) { # chunk start
375                 if ($len == CHUNK_ZEND) {
376                         $$rbuf =~ s/\A\r\n//s and
377                                 return app_dispatch($self, $input);
378                         return quit($self, 400) if length($$rbuf) > 2;
379                 }
380                 if ($len == CHUNK_END) {
381                         if ($$rbuf =~ s/\A\r\n//s) {
382                                 $len = CHUNK_START;
383                         } elsif (length($$rbuf) > 2) {
384                                 return quit($self, 400);
385                         }
386                 }
387                 if ($len == CHUNK_START) {
388                         if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
389                                 $len = hex $1;
390                                 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
391                                         return quit($self, 413);
392                                 }
393                         } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
394                                 return quit($self, 400);
395                         }
396                         # will break from loop since $len >= 0
397                 }
398
399                 if ($len < 0) { # chunk header is trickled, read more
400                         my $off = length($$rbuf);
401                         my $r = sysread($sock, $$rbuf, 8192, $off);
402                         return recv_err($self, $r, $len) unless $r;
403                         # (implicit) goto chunk_start if $r > 0;
404                 }
405                 $len = CHUNK_ZEND if $len == 0;
406
407                 # drain the current chunk
408                 until ($len <= 0) {
409                         if ($$rbuf ne '') {
410                                 my $w = write_in_full($input, $rbuf, $len);
411                                 return write_err($self) unless $w;
412                                 $len -= $w;
413                                 if ($len == 0) {
414                                         # we may have leftover data to parse
415                                         # in chunk
416                                         $$rbuf = substr($$rbuf, $w);
417                                         $len = CHUNK_END;
418                                 } elsif ($len < 0) {
419                                         die "BUG: len < 0: $len";
420                                 } else {
421                                         $$rbuf = '';
422                                 }
423                         }
424                         if ($$rbuf eq '') {
425                                 # read more of current chunk
426                                 my $r = sysread($sock, $$rbuf, 8192);
427                                 return recv_err($self, $r, $len) unless $r;
428                         }
429                 }
430         }
431 }
432
433 sub quit {
434         my ($self, $status) = @_;
435         my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
436         $self->write($h);
437         $self->close;
438 }
439
440 # callbacks for Danga::Socket
441
442 sub event_hup { $_[0]->close }
443 sub event_err { $_[0]->close }
444
445 sub close {
446         my $self = shift;
447         my $forward = $self->{forward};
448         $forward->close if $forward;
449         $self->{forward} = $self->{env} = undef;
450         $self->SUPER::close(@_);
451 }
452
453 # for graceful shutdown in PublicInbox::Daemon:
454 sub busy () {
455         my ($self) = @_;
456         ($self->{rbuf} ne '' || $self->{env} || $self->{write_buf_size});
457 }
458
459 1;