]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTP.pm
480800bd90b00c51a747bf4cd3a0ff1957ab4f7e
[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 $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                 } else {
223                         my $pull;
224                         $pull = sub {
225                                 local $/ = \8192;
226                                 while (defined(my $buf = $body->getline)) {
227                                         $write->($buf);
228                                         if ($self->{write_buf_size}) {
229                                                 $self->write($pull);
230                                                 return;
231                                         }
232                                 }
233                                 $pull = undef;
234                                 $body->close();
235                                 $close->();
236                         };
237                         $pull->();
238                 }
239         } else {
240                 # this is returned to the calling application:
241                 Plack::Util::inline_object(write => $write, close => $close);
242         }
243 }
244
245 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
246 sub more ($$) {
247         my $self = $_[0];
248         if (MSG_MORE && !$self->{write_buf_size}) {
249                 my $n = send($self->{sock}, $_[1], MSG_MORE);
250                 if (defined $n) {
251                         my $dlen = length($_[1]);
252                         return 1 if $n == $dlen; # all done!
253                         $_[1] = substr($_[1], $n, $dlen - $n);
254                         # fall through to normal write:
255                 }
256         }
257         $self->write($_[1]);
258 }
259
260 my $pipelineq = [];
261 my $next_tick;
262 sub process_pipelineq () {
263         $next_tick = undef;
264         my $q = $pipelineq;
265         $pipelineq = [];
266         rbuf_process($_) foreach @$q;
267 }
268
269 # overrides existing Danga::Socket method
270 sub event_write {
271         my ($self) = @_;
272         # only continue watching for readability when we are done writing:
273         return if $self->write(undef) != 1;
274
275         if ($self->{rbuf} eq '') { # wait for next request
276                 $self->watch_read(1);
277         } else { # avoid recursion for pipelined requests
278                 push @$pipelineq, $self;
279                 $next_tick ||= Danga::Socket->AddTimer(0, *process_pipelineq);
280         }
281 }
282
283 sub input_prepare {
284         my ($self, $env) = @_;
285         my $input = $null_io;
286         my $len = $env->{CONTENT_LENGTH};
287         if ($len) {
288                 if ($len > $MAX_REQUEST_BUFFER) {
289                         quit($self, 413);
290                         return;
291                 }
292                 $input = IO::File->new_tmpfile;
293         } elsif (env_chunked($env)) {
294                 $len = CHUNK_START;
295                 $input = IO::File->new_tmpfile;
296         }
297
298         # TODO: expire idle clients on ENFILE / EMFILE
299         return unless $input;
300
301         $env->{'psgi.input'} = $input;
302         $self->{env} = $env;
303         $self->{input_left} = $len || 0;
304 }
305
306 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
307
308 sub write_err {
309         my ($self) = @_;
310         my $err = $self->{httpd}->{env}->{'psgi.errors'};
311         my $msg = $! || '(zero write)';
312         $err->print("error buffering to input: $msg\n");
313         quit($self, 500);
314 }
315
316 sub recv_err {
317         my ($self, $r, $len) = @_;
318         return $self->close if (defined $r && $r == 0);
319         if ($!{EAGAIN}) {
320                 $self->{input_left} = $len;
321                 return;
322         }
323         my $err = $self->{httpd}->{env}->{'psgi.errors'};
324         $err->print("error reading for input: $! ($len bytes remaining)\n");
325         quit($self, 500);
326 }
327
328 sub write_in_full {
329         my ($fh, $rbuf, $len) = @_;
330         my $rv = 0;
331         my $off = 0;
332         while ($len > 0) {
333                 my $w = syswrite($fh, $$rbuf, $len, $off);
334                 return ($rv ? $rv : $w) unless $w; # undef or 0
335                 $rv += $w;
336                 $off += $w;
337                 $len -= $w;
338         }
339         $rv
340 }
341
342 sub event_read_input_chunked { # unlikely...
343         my ($self) = @_;
344         my $input = $self->{env}->{'psgi.input'};
345         my $sock = $self->{sock};
346         my $len = $self->{input_left};
347         $self->{input_left} = undef;
348         my $rbuf = \($self->{rbuf});
349
350         while (1) { # chunk start
351                 if ($len == CHUNK_ZEND) {
352                         $$rbuf =~ s/\A\r\n//s and
353                                 return app_dispatch($self, $input);
354                         return quit($self, 400) if length($$rbuf) > 2;
355                 }
356                 if ($len == CHUNK_END) {
357                         if ($$rbuf =~ s/\A\r\n//s) {
358                                 $len = CHUNK_START;
359                         } elsif (length($$rbuf) > 2) {
360                                 return quit($self, 400);
361                         }
362                 }
363                 if ($len == CHUNK_START) {
364                         if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
365                                 $len = hex $1;
366                                 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
367                                         return quit($self, 413);
368                                 }
369                         } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
370                                 return quit($self, 400);
371                         }
372                         # will break from loop since $len >= 0
373                 }
374
375                 if ($len < 0) { # chunk header is trickled, read more
376                         my $off = length($$rbuf);
377                         my $r = sysread($sock, $$rbuf, 8192, $off);
378                         return recv_err($self, $r, $len) unless $r;
379                         # (implicit) goto chunk_start if $r > 0;
380                 }
381                 $len = CHUNK_ZEND if $len == 0;
382
383                 # drain the current chunk
384                 until ($len <= 0) {
385                         if ($$rbuf ne '') {
386                                 my $w = write_in_full($input, $rbuf, $len);
387                                 return write_err($self) unless $w;
388                                 $len -= $w;
389                                 if ($len == 0) {
390                                         # we may have leftover data to parse
391                                         # in chunk
392                                         $$rbuf = substr($$rbuf, $w);
393                                         $len = CHUNK_END;
394                                 } elsif ($len < 0) {
395                                         die "BUG: len < 0: $len";
396                                 } else {
397                                         $$rbuf = '';
398                                 }
399                         }
400                         if ($$rbuf eq '') {
401                                 # read more of current chunk
402                                 my $r = sysread($sock, $$rbuf, 8192);
403                                 return recv_err($self, $r, $len) unless $r;
404                         }
405                 }
406         }
407 }
408
409 sub quit {
410         my ($self, $status) = @_;
411         my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
412         $self->write($h);
413         $self->close;
414 }
415
416 # callbacks for Danga::Socket
417
418 sub event_hup { $_[0]->close }
419 sub event_err { $_[0]->close }
420
421 sub close {
422         my $self = shift;
423         my $forward = $self->{forward};
424         $forward->close if $forward;
425         $self->{forward} = $self->{env} = undef;
426         $self->SUPER::close(@_);
427 }
428
429 # for graceful shutdown in PublicInbox::Daemon:
430 sub busy () {
431         my ($self) = @_;
432         ($self->{rbuf} ne '' || $self->{env} || $self->{write_buf_size});
433 }
434
435 1;