]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTP.pm
5844ef440f1e8dd324ce6b67401de7c99e696c8e
[public-inbox.git] / lib / PublicInbox / HTTP.pm
1 # Copyright (C) 2016-2020 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 which depends on public-inbox, here.
8 # Each instance of this class represents a HTTP client socket
9 #
10 # fields:
11 # httpd: PublicInbox::HTTPD ref
12 # env: PSGI env hashref
13 # input_left: bytes left to read in request body (e.g. POST/PUT)
14 # remote_addr: remote IP address as a string (e.g. "127.0.0.1")
15 # remote_port: peer port
16 # forward: response body object, response to ->getline + ->close
17 # alive: HTTP keepalive state:
18 #       0: drop connection when done
19 #       1: keep connection when done
20 #       2: keep connection, chunk responses
21 package PublicInbox::HTTP;
22 use strict;
23 use parent qw(PublicInbox::DS);
24 use bytes (); # only for bytes::length
25 use Fcntl qw(:seek);
26 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
27 use Plack::Util;
28 use HTTP::Status qw(status_message);
29 use HTTP::Date qw(time2str);
30 use IO::Handle; # ->write
31 use PublicInbox::DS qw(msg_more);
32 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
33 use PublicInbox::Tmpfile;
34 use constant {
35         CHUNK_START => -1,   # [a-f0-9]+\r\n
36         CHUNK_END => -2,     # \r\n
37         CHUNK_ZEND => -3,    # \r\n
38         CHUNK_MAX_HDR => 256,
39 };
40 use Errno qw(EAGAIN);
41
42 my $pipelineq = [];
43 sub process_pipelineq () {
44         my $q = $pipelineq;
45         $pipelineq = [];
46         foreach (@$q) {
47                 next unless $_->{sock};
48                 rbuf_process($_);
49         }
50 }
51
52 # Use the same configuration parameter as git since this is primarily
53 # a slow-client sponge for git-http-backend
54 # TODO: support per-respository http.maxRequestBuffer somehow...
55 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
56                         (10 * 1024 * 1024);
57
58 open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!";
59 my $http_date;
60 my $prev = 0;
61 sub http_date () {
62         my $now = time;
63         $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
64 }
65
66 sub new ($$$) {
67         my ($class, $sock, $addr, $httpd) = @_;
68         my $self = bless { httpd => $httpd }, $class;
69         my $ev = EPOLLIN;
70         my $wbuf;
71         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
72                 return CORE::close($sock) if $! != EAGAIN;
73                 $ev = PublicInbox::TLS::epollbit();
74                 $wbuf = [ \&PublicInbox::DS::accept_tls_step ];
75         }
76         $self->{wbuf} = $wbuf if $wbuf;
77         ($self->{remote_addr}, $self->{remote_port}) =
78                 PublicInbox::Daemon::host_with_port($addr);
79         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
80 }
81
82 sub event_step { # called by PublicInbox::DS
83         my ($self) = @_;
84
85         return unless $self->flush_write && $self->{sock};
86
87         # only read more requests if we've drained the write buffer,
88         # otherwise we can be buffering infinitely w/o backpressure
89
90         return read_input($self) if ref($self->{env});
91         my $rbuf = $self->{rbuf} // (\(my $x = ''));
92         $self->do_read($rbuf, 8192, bytes::length($$rbuf)) or return;
93         rbuf_process($self, $rbuf);
94 }
95
96 sub rbuf_process {
97         my ($self, $rbuf) = @_;
98         $rbuf //= $self->{rbuf} // (\(my $x = ''));
99
100         my %env = %{$self->{httpd}->{env}}; # full hash copy
101         my $r = parse_http_request($$rbuf, \%env);
102
103         # We do not support Trailers in chunked requests, for now
104         # (they are rarely-used and git (as of 2.7.2) does not use them)
105         if ($r == -1 || $env{HTTP_TRAILER} ||
106                         # this length-check is necessary for PURE_PERL=1:
107                         ($r == -2 && bytes::length($$rbuf) > 0x4000)) {
108                 return quit($self, 400);
109         }
110         if ($r < 0) { # incomplete
111                 $self->rbuf_idle($rbuf);
112                 return $self->requeue;
113         }
114         $$rbuf = substr($$rbuf, $r);
115         my $len = input_prepare($self, \%env);
116         defined $len or return write_err($self, undef); # EMFILE/ENFILE
117
118         $len ? read_input($self, $rbuf) : app_dispatch($self, undef, $rbuf);
119 }
120
121 # IO::Handle::write returns boolean, this returns bytes written:
122 sub xwrite ($$$) {
123         my ($fh, $rbuf, $max) = @_;
124         my $w = bytes::length($$rbuf);
125         $w = $max if $w > $max;
126         $fh->write($$rbuf, $w) or return;
127         $w;
128 }
129
130 sub read_input ($;$) {
131         my ($self, $rbuf) = @_;
132         $rbuf //= $self->{rbuf} // (\(my $x = ''));
133         my $env = $self->{env};
134         return read_input_chunked($self, $rbuf) if env_chunked($env);
135
136         # env->{CONTENT_LENGTH} (identity)
137         my $len = delete $self->{input_left};
138         my $input = $env->{'psgi.input'};
139
140         while ($len > 0) {
141                 if ($$rbuf ne '') {
142                         my $w = xwrite($input, $rbuf, $len);
143                         return write_err($self, $len) unless $w;
144                         $len -= $w;
145                         die "BUG: $len < 0 (w=$w)" if $len < 0;
146                         if ($len == 0) { # next request may be pipelined
147                                 $$rbuf = substr($$rbuf, $w);
148                                 last;
149                         }
150                         $$rbuf = '';
151                 }
152                 $self->do_read($rbuf, 8192) or return recv_err($self, $len);
153                 # continue looping if $r > 0;
154         }
155         app_dispatch($self, $input, $rbuf);
156 }
157
158 sub app_dispatch {
159         my ($self, $input, $rbuf) = @_;
160         $self->rbuf_idle($rbuf);
161         my $env = $self->{env};
162         $self->{env} = undef; # for exists() check in ->busy
163         $env->{REMOTE_ADDR} = $self->{remote_addr};
164         $env->{REMOTE_PORT} = $self->{remote_port};
165         if (defined(my $host = $env->{HTTP_HOST})) {
166                 $host =~ s/:([0-9]+)\z// and $env->{SERVER_PORT} = $1;
167                 $env->{SERVER_NAME} = $host;
168         }
169         if (defined $input) {
170                 sysseek($input, 0, SEEK_SET) or
171                         die "BUG: psgi.input seek failed: $!";
172         }
173         # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
174         # to do proper cleanup:
175         $env->{'psgix.io'} = $self; # for ->close or async_pass
176         my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
177         eval {
178                 if (ref($res) eq 'CODE') {
179                         $res->(sub { response_write($self, $env, $_[0]) });
180                 } else {
181                         response_write($self, $env, $res);
182                 }
183         };
184         if ($@) {
185                 err($self, "response_write error: $@");
186                 $self->close;
187         }
188 }
189
190 sub response_header_write {
191         my ($self, $env, $res) = @_;
192         my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
193         my $status = $res->[0];
194         my $h = "$proto $status " . status_message($status) . "\r\n";
195         my ($len, $chunked);
196         my $headers = $res->[1];
197
198         for (my $i = 0; $i < @$headers; $i += 2) {
199                 my $k = $headers->[$i];
200                 my $v = $headers->[$i + 1];
201                 next if $k =~ /\A(?:Connection|Date)\z/i;
202
203                 $len = $v if $k =~ /\AContent-Length\z/i;
204                 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
205                         $chunked = 1;
206                 }
207                 $h .= "$k: $v\r\n";
208         }
209
210         my $conn = $env->{HTTP_CONNECTION} || '';
211         my $term = defined($len) || $chunked;
212         my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
213         my $alive;
214         if (!$term && $prot_persist) { # auto-chunk
215                 $chunked = $alive = 2;
216                 $h .= "Transfer-Encoding: chunked\r\n";
217                 # no need for "Connection: keep-alive" with HTTP/1.1
218         } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
219                 $alive = 1;
220                 $h .= "Connection: keep-alive\r\n";
221         } else {
222                 $alive = 0;
223                 $h .= "Connection: close\r\n";
224         }
225         $h .= 'Date: ' . http_date() . "\r\n\r\n";
226
227         if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
228                 msg_more($self, $h);
229         } else {
230                 $self->write(\$h);
231         }
232         $alive;
233 }
234
235 # middlewares such as Deflater may write empty strings
236 sub chunked_write ($$) {
237         my $self = $_[0];
238         return if $_[1] eq '';
239         msg_more($self, sprintf("%x\r\n", bytes::length($_[1])));
240         msg_more($self, $_[1]);
241
242         # use $self->write(\"\n\n") if you care about real-time
243         # streaming responses, public-inbox WWW does not.
244         msg_more($self, "\r\n");
245 }
246
247 sub identity_write ($$) {
248         my $self = $_[0];
249         $self->write(\($_[1])) if $_[1] ne '';
250 }
251
252 sub next_request ($) {
253         my ($self) = @_;
254         if ($self->{rbuf}) {
255                 # avoid recursion for pipelined requests
256                 PublicInbox::DS::requeue(\&process_pipelineq) if !@$pipelineq;
257                 push @$pipelineq, $self;
258         } else { # wait for next request
259                 $self->requeue;
260         }
261 }
262
263 sub response_done {
264         my ($self, $alive) = @_;
265         delete $self->{env}; # we're no longer busy
266         $self->write(\"0\r\n\r\n") if $alive == 2;
267         $self->write($alive ? \&next_request : \&close);
268 }
269
270 sub getline_pull {
271         my ($self) = @_;
272         my $forward = $self->{forward};
273
274         # limit our own running time for fairness with other
275         # clients and to avoid buffering too much:
276         my $buf = eval {
277                 local $/ = \8192;
278                 $forward->getline;
279         } if $forward;
280
281         if (defined $buf) {
282                 # may close in PublicInbox::DS::write
283                 if ($self->{alive} == 2) {
284                         chunked_write($self, $buf);
285                 } else {
286                         identity_write($self, $buf);
287                 }
288
289                 if ($self->{sock}) {
290                         # autovivify wbuf
291                         my $new_size = push(@{$self->{wbuf}}, \&getline_pull);
292
293                         # wbuf may be populated by {chunked,identity}_write()
294                         # above, no need to rearm if so:
295                         $self->requeue if $new_size == 1;
296                         return; # likely
297                 }
298         } elsif ($@) {
299                 err($self, "response ->getline error: $@");
300                 $self->close;
301         }
302         # avoid recursion
303         if (delete $self->{forward}) {
304                 eval { $forward->close };
305                 if ($@) {
306                         err($self, "response ->close error: $@");
307                         $self->close; # idempotent
308                 }
309         }
310         response_done($self, delete $self->{alive});
311 }
312
313 sub response_write {
314         my ($self, $env, $res) = @_;
315         my $alive = response_header_write($self, $env, $res);
316         if (defined(my $body = $res->[2])) {
317                 if (ref $body eq 'ARRAY') {
318                         if ($alive == 2) {
319                                 chunked_write($self, $_) for @$body;
320                         } else {
321                                 identity_write($self, $_) for @$body;
322                         }
323                         response_done($self, $alive);
324                 } else {
325                         $self->{forward} = $body;
326                         $self->{alive} = $alive;
327                         getline_pull($self); # kick-off!
328                 }
329         # these are returned to the calling application:
330         } elsif ($alive == 2) {
331                 bless [ $self, $alive ], 'PublicInbox::HTTP::Chunked';
332         } else {
333                 bless [ $self, $alive ], 'PublicInbox::HTTP::Identity';
334         }
335 }
336
337 sub input_tmpfile ($) {
338         my $input = tmpfile('http.input', $_[0]->{sock}) or return;
339         $input->autoflush(1);
340         $input;
341 }
342
343 sub input_prepare {
344         my ($self, $env) = @_;
345         my ($input, $len);
346
347         # rfc 7230 3.3.2, 3.3.3,: favor Transfer-Encoding over Content-Length
348         my $hte = $env->{HTTP_TRANSFER_ENCODING};
349         if (defined $hte) {
350                 # rfc7230 3.3.3, point 3 says only chunked is accepted
351                 # as the final encoding.  Since neither public-inbox-httpd,
352                 # git-http-backend, or our WWW-related code uses "gzip",
353                 # "deflate" or "compress" as the Transfer-Encoding, we'll
354                 # reject them:
355                 return quit($self, 400) if $hte !~ /\Achunked\z/i;
356
357                 $len = CHUNK_START;
358                 $input = input_tmpfile($self);
359         } else {
360                 $len = $env->{CONTENT_LENGTH};
361                 if (defined $len) {
362                         # rfc7230 3.3.3.4
363                         return quit($self, 400) if $len !~ /\A[0-9]+\z/;
364
365                         return quit($self, 413) if $len > $MAX_REQUEST_BUFFER;
366                         $input = $len ? input_tmpfile($self) : $null_io;
367                 } else {
368                         $input = $null_io;
369                 }
370         }
371
372         # TODO: expire idle clients on ENFILE / EMFILE
373         return unless $input;
374
375         $env->{'psgi.input'} = $input;
376         $self->{env} = $env;
377         $self->{input_left} = $len || 0;
378 }
379
380 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} // '') =~ /\Achunked\z/i }
381
382 sub err ($$) {
383         eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
384 }
385
386 sub write_err {
387         my ($self, $len) = @_;
388         my $msg = $! || '(zero write)';
389         $msg .= " ($len bytes remaining)" if defined $len;
390         err($self, "error buffering to input: $msg");
391         quit($self, 500);
392 }
393
394 sub recv_err {
395         my ($self, $len) = @_;
396         if ($! == EAGAIN) { # epoll/kevent watch already set by do_read
397                 $self->{input_left} = $len;
398         } else {
399                 err($self, "error reading input: $! ($len bytes remaining)");
400         }
401 }
402
403 sub read_input_chunked { # unlikely...
404         my ($self, $rbuf) = @_;
405         $rbuf //= $self->{rbuf} // (\(my $x = ''));
406         my $input = $self->{env}->{'psgi.input'};
407         my $len = delete $self->{input_left};
408
409         while (1) { # chunk start
410                 if ($len == CHUNK_ZEND) {
411                         $$rbuf =~ s/\A\r\n//s and
412                                 return app_dispatch($self, $input, $rbuf);
413
414                         return quit($self, 400) if bytes::length($$rbuf) > 2;
415                 }
416                 if ($len == CHUNK_END) {
417                         if ($$rbuf =~ s/\A\r\n//s) {
418                                 $len = CHUNK_START;
419                         } elsif (bytes::length($$rbuf) > 2) {
420                                 return quit($self, 400);
421                         }
422                 }
423                 if ($len == CHUNK_START) {
424                         if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
425                                 $len = hex $1;
426                                 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
427                                         return quit($self, 413);
428                                 }
429                         } elsif (bytes::length($$rbuf) > CHUNK_MAX_HDR) {
430                                 return quit($self, 400);
431                         }
432                         # will break from loop since $len >= 0
433                 }
434
435                 if ($len < 0) { # chunk header is trickled, read more
436                         $self->do_read($rbuf, 8192, bytes::length($$rbuf)) or
437                                 return recv_err($self, $len);
438                         # (implicit) goto chunk_start if $r > 0;
439                 }
440                 $len = CHUNK_ZEND if $len == 0;
441
442                 # drain the current chunk
443                 until ($len <= 0) {
444                         if ($$rbuf ne '') {
445                                 my $w = xwrite($input, $rbuf, $len);
446                                 return write_err($self, "$len chunk") if !$w;
447                                 $len -= $w;
448                                 if ($len == 0) {
449                                         # we may have leftover data to parse
450                                         # in chunk
451                                         $$rbuf = substr($$rbuf, $w);
452                                         $len = CHUNK_END;
453                                 } elsif ($len < 0) {
454                                         die "BUG: len < 0: $len";
455                                 } else {
456                                         $$rbuf = '';
457                                 }
458                         }
459                         if ($$rbuf eq '') {
460                                 # read more of current chunk
461                                 $self->do_read($rbuf, 8192) or
462                                         return recv_err($self, $len);
463                         }
464                 }
465         }
466 }
467
468 sub quit {
469         my ($self, $status) = @_;
470         my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
471         $self->write(\$h);
472         $self->close;
473         undef; # input_prepare expects this
474 }
475
476 sub close {
477         my $self = $_[0];
478         if (my $forward = delete $self->{forward}) {
479                 eval { $forward->close };
480                 err($self, "forward ->close error: $@") if $@;
481         }
482         $self->SUPER::close; # PublicInbox::DS::close
483 }
484
485 # for graceful shutdown in PublicInbox::Daemon:
486 sub busy () {
487         my ($self) = @_;
488         ($self->{rbuf} || exists($self->{env}) || $self->{wbuf});
489 }
490
491 # runs $cb on the next iteration of the event loop at earliest
492 sub next_step {
493         my ($self, $cb) = @_;
494         return unless exists $self->{sock};
495         $self->requeue if 1 == push(@{$self->{wbuf}}, $cb);
496 }
497
498 # Chunked and Identity packages are used for writing responses.
499 # They may be exposed to the PSGI application when the PSGI app
500 # returns a CODE ref for "push"-based responses
501 package PublicInbox::HTTP::Chunked;
502 use strict;
503
504 sub write {
505         # ([$http], $buf) = @_;
506         PublicInbox::HTTP::chunked_write($_[0]->[0], $_[1])
507 }
508
509 sub close {
510         # $_[0] = [$http, $alive]
511         PublicInbox::HTTP::response_done(@{$_[0]});
512 }
513
514 package PublicInbox::HTTP::Identity;
515 use strict;
516 our @ISA = qw(PublicInbox::HTTP::Chunked);
517
518 sub write {
519         # ([$http], $buf) = @_;
520         PublicInbox::HTTP::identity_write($_[0]->[0], $_[1]);
521 }
522
523 1;