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