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