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