]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTP.pm
standardize timer-related event-loop code
[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         rbuf_process($_) foreach @$q;
43 }
44
45 # Use the same configuration parameter as git since this is primarily
46 # a slow-client sponge for git-http-backend
47 # TODO: support per-respository http.maxRequestBuffer somehow...
48 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
49                         (10 * 1024 * 1024);
50
51 my $null_io = IO::File->new('/dev/null', '<');
52 my $http_date;
53 my $prev = 0;
54 sub http_date () {
55         my $now = time;
56         $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
57 }
58
59 sub new ($$$) {
60         my ($class, $sock, $addr, $httpd) = @_;
61         my $self = fields::new($class);
62         $self->SUPER::new($sock);
63         $self->{httpd} = $httpd;
64         $self->{rbuf} = '';
65         ($self->{remote_addr}, $self->{remote_port}) =
66                 PublicInbox::Daemon::host_with_port($addr);
67         $self->watch_read(1);
68         $self;
69 }
70
71 sub event_read { # called by Danga::Socket
72         my ($self) = @_;
73
74         return event_read_input($self) if defined $self->{env};
75
76         my $off = length($self->{rbuf});
77         my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
78         if (defined $r) {
79                 return $self->close if $r == 0;
80                 return rbuf_process($self);
81         }
82         return if $!{EAGAIN}; # no need to call watch_read(1) again
83
84         # common for clients to break connections without warning,
85         # would be too noisy to log here:
86         return $self->close;
87 }
88
89 sub rbuf_process {
90         my ($self) = @_;
91
92         my %env = %{$self->{httpd}->{env}}; # full hash copy
93         my $r = parse_http_request($self->{rbuf}, \%env);
94
95         # We do not support Trailers in chunked requests, for now
96         # (they are rarely-used and git (as of 2.7.2) does not use them)
97         if ($r == -1 || $env{HTTP_TRAILER} ||
98                         # this length-check is necessary for PURE_PERL=1:
99                         ($r == -2 && length($self->{rbuf}) > 0x4000)) {
100                 return quit($self, 400);
101         }
102         return $self->watch_read(1) if $r < 0; # incomplete
103         $self->{rbuf} = substr($self->{rbuf}, $r);
104
105         my $len = input_prepare($self, \%env);
106         defined $len or return write_err($self); # EMFILE/ENFILE
107
108         $len ? event_read_input($self) : app_dispatch($self);
109 }
110
111 sub event_read_input ($) {
112         my ($self) = @_;
113         my $env = $self->{env};
114         return event_read_input_chunked($self) if env_chunked($env);
115
116         # env->{CONTENT_LENGTH} (identity)
117         my $sock = $self->{sock};
118         my $len = $self->{input_left};
119         $self->{input_left} = undef;
120         my $rbuf = \($self->{rbuf});
121         my $input = $env->{'psgi.input'};
122
123         while ($len > 0) {
124                 if ($$rbuf ne '') {
125                         my $w = write_in_full($input, $rbuf, $len);
126                         return write_err($self) unless $w;
127                         $len -= $w;
128                         die "BUG: $len < 0 (w=$w)" if $len < 0;
129                         if ($len == 0) { # next request may be pipelined
130                                 $$rbuf = substr($$rbuf, $w);
131                                 last;
132                         }
133                         $$rbuf = '';
134                 }
135                 my $r = sysread($sock, $$rbuf, 8192);
136                 return recv_err($self, $r, $len) unless $r;
137                 # continue looping if $r > 0;
138         }
139         app_dispatch($self, $input);
140 }
141
142 sub app_dispatch {
143         my ($self, $input) = @_;
144         $self->watch_read(0);
145         my $env = $self->{env};
146         $env->{REMOTE_ADDR} = $self->{remote_addr};
147         $env->{REMOTE_PORT} = $self->{remote_port};
148         if (my $host = $env->{HTTP_HOST}) {
149                 $host =~ s/:(\d+)\z// and $env->{SERVER_PORT} = $1;
150                 $env->{SERVER_NAME} = $host;
151         }
152         if (defined $input) {
153                 sysseek($input, 0, SEEK_SET) or
154                         die "BUG: psgi.input seek failed: $!";
155         }
156         # note: NOT $self->{sock}, we want our close (+ Danga::Socket::close),
157         # to do proper cleanup:
158         $env->{'psgix.io'} = $self; # only for ->close
159         my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
160         eval {
161                 if (ref($res) eq 'CODE') {
162                         $res->(sub { response_write($self, $env, $_[0]) });
163                 } else {
164                         response_write($self, $env, $res);
165                 }
166         };
167         $self->close if $@;
168 }
169
170 sub response_header_write {
171         my ($self, $env, $res) = @_;
172         my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
173         my $status = $res->[0];
174         my $h = "$proto $status " . status_message($status) . "\r\n";
175         my ($len, $chunked);
176         my $headers = $res->[1];
177
178         for (my $i = 0; $i < @$headers; $i += 2) {
179                 my $k = $headers->[$i];
180                 my $v = $headers->[$i + 1];
181                 next if $k =~ /\A(?:Connection|Date)\z/i;
182
183                 $len = $v if $k =~ /\AContent-Length\z/i;
184                 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
185                         $chunked = 1;
186                 }
187                 $h .= "$k: $v\r\n";
188         }
189
190         my $conn = $env->{HTTP_CONNECTION} || '';
191         my $term = defined($len) || $chunked;
192         my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
193         my $alive;
194         if (!$term && $prot_persist) { # auto-chunk
195                 $chunked = $alive = 2;
196                 $h .= "Transfer-Encoding: chunked\r\n";
197                 # no need for "Connection: keep-alive" with HTTP/1.1
198         } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
199                 $alive = 1;
200                 $h .= "Connection: keep-alive\r\n";
201         } else {
202                 $alive = 0;
203                 $h .= "Connection: close\r\n";
204         }
205         $h .= 'Date: ' . http_date() . "\r\n\r\n";
206
207         if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
208                 more($self, $h);
209         } else {
210                 $self->write($h);
211         }
212         $alive;
213 }
214
215 # middlewares such as Deflater may write empty strings
216 sub chunked_wcb ($) {
217         my ($self) = @_;
218         sub {
219                 return if $_[0] eq '';
220                 more($self, sprintf("%x\r\n", bytes::length($_[0])));
221                 more($self, $_[0]);
222                 $self->write("\r\n");
223         }
224 }
225
226 sub identity_wcb ($) {
227         my ($self) = @_;
228         sub { $self->write(\($_[0])) if $_[0] ne '' }
229 }
230
231 sub response_write {
232         my ($self, $env, $res) = @_;
233         my $alive = response_header_write($self, $env, $res);
234
235         my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
236         my $close = sub {
237                 $self->write("0\r\n\r\n") if $alive == 2;
238                 if ($alive) {
239                         $self->event_write; # watch for readability if done
240                 } else {
241                         Danga::Socket::write($self, sub { $self->close });
242                 }
243                 if (my $obj = $env->{'pi-httpd.inbox'}) {
244                         # grace period for reaping resources
245                         $WEAKEN->{"$obj"} = $obj;
246                         $weakt ||= PublicInbox::EvCleanup::later(*weaken_task);
247                 }
248                 $self->{env} = undef;
249         };
250
251         if (defined(my $body = $res->[2])) {
252                 if (ref $body eq 'ARRAY') {
253                         $write->($_) foreach @$body;
254                         $close->();
255                 } else {
256                         my $pull;
257                         $pull = sub {
258                                 local $/ = \8192;
259                                 while (defined(my $buf = $body->getline)) {
260                                         $write->($buf);
261                                         if ($self->{write_buf_size}) {
262                                                 $self->write($pull);
263                                                 return;
264                                         }
265                                 }
266                                 $pull = undef;
267                                 $body->close();
268                                 $close->();
269                         };
270                         $pull->();
271                 }
272         } else {
273                 # this is returned to the calling application:
274                 Plack::Util::inline_object(write => $write, close => $close);
275         }
276 }
277
278 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
279 sub more ($$) {
280         my $self = $_[0];
281         if (MSG_MORE && !$self->{write_buf_size}) {
282                 my $n = send($self->{sock}, $_[1], MSG_MORE);
283                 if (defined $n) {
284                         my $dlen = length($_[1]);
285                         return 1 if $n == $dlen; # all done!
286                         $_[1] = substr($_[1], $n, $dlen - $n);
287                         # fall through to normal write:
288                 }
289         }
290         $self->write($_[1]);
291 }
292
293 # overrides existing Danga::Socket method
294 sub event_write {
295         my ($self) = @_;
296         # only continue watching for readability when we are done writing:
297         return if $self->write(undef) != 1;
298
299         if ($self->{rbuf} eq '') { # wait for next request
300                 $self->watch_read(1);
301         } else { # avoid recursion for pipelined requests
302                 push @$pipelineq, $self;
303                 $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
304         }
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;