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