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