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