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>
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
10 package PublicInbox::HTTP;
13 use base qw(PublicInbox::DS);
14 use fields qw(httpd env input_left remote_addr remote_port forward alive);
15 use bytes (); # only for bytes::length
17 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
19 use HTTP::Status qw(status_message);
20 use HTTP::Date qw(time2str);
21 use IO::Handle; # ->write
22 use PublicInbox::DS qw(msg_more);
23 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
24 use PublicInbox::Tmpfile;
26 CHUNK_START => -1, # [a-f0-9]+\r\n
27 CHUNK_END => -2, # \r\n
28 CHUNK_ZEND => -3, # \r\n
34 sub process_pipelineq () {
38 next unless $_->{sock};
43 # Use the same configuration parameter as git since this is primarily
44 # a slow-client sponge for git-http-backend
45 # TODO: support per-respository http.maxRequestBuffer somehow...
46 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
49 open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!";
54 $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
58 my ($class, $sock, $addr, $httpd) = @_;
59 my $self = fields::new($class);
62 if (ref($sock) eq 'IO::Socket::SSL' && !$sock->accept_SSL) {
63 return CORE::close($sock) if $! != EAGAIN;
64 $ev = PublicInbox::TLS::epollbit();
65 $wbuf = [ \&PublicInbox::DS::accept_tls_step ];
67 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
68 $self->{httpd} = $httpd;
69 $self->{wbuf} = $wbuf if $wbuf;
70 ($self->{remote_addr}, $self->{remote_port}) =
71 PublicInbox::Daemon::host_with_port($addr);
75 sub event_step { # called by PublicInbox::DS
78 return unless $self->flush_write && $self->{sock};
80 # only read more requests if we've drained the write buffer,
81 # otherwise we can be buffering infinitely w/o backpressure
83 return read_input($self) if ref($self->{env});
84 my $rbuf = $self->{rbuf} // (\(my $x = ''));
85 $self->do_read($rbuf, 8192, bytes::length($$rbuf)) or return;
86 rbuf_process($self, $rbuf);
90 my ($self, $rbuf) = @_;
91 $rbuf //= $self->{rbuf} // (\(my $x = ''));
93 my %env = %{$self->{httpd}->{env}}; # full hash copy
94 my $r = parse_http_request($$rbuf, \%env);
96 # We do not support Trailers in chunked requests, for now
97 # (they are rarely-used and git (as of 2.7.2) does not use them)
98 if ($r == -1 || $env{HTTP_TRAILER} ||
99 # this length-check is necessary for PURE_PERL=1:
100 ($r == -2 && bytes::length($$rbuf) > 0x4000)) {
101 return quit($self, 400);
103 if ($r < 0) { # incomplete
104 $self->rbuf_idle($rbuf);
105 return $self->requeue;
107 $$rbuf = substr($$rbuf, $r);
108 my $len = input_prepare($self, \%env);
109 defined $len or return write_err($self, undef); # EMFILE/ENFILE
111 $len ? read_input($self, $rbuf) : app_dispatch($self, undef, $rbuf);
114 # IO::Handle::write returns boolean, this returns bytes written:
116 my ($fh, $rbuf, $max) = @_;
117 my $w = bytes::length($$rbuf);
118 $w = $max if $w > $max;
119 $fh->write($$rbuf, $w) or return;
123 sub read_input ($;$) {
124 my ($self, $rbuf) = @_;
125 $rbuf //= $self->{rbuf} // (\(my $x = ''));
126 my $env = $self->{env};
127 return read_input_chunked($self, $rbuf) if env_chunked($env);
129 # env->{CONTENT_LENGTH} (identity)
130 my $len = delete $self->{input_left};
131 my $input = $env->{'psgi.input'};
135 my $w = xwrite($input, $rbuf, $len);
136 return write_err($self, $len) unless $w;
138 die "BUG: $len < 0 (w=$w)" if $len < 0;
139 if ($len == 0) { # next request may be pipelined
140 $$rbuf = substr($$rbuf, $w);
145 $self->do_read($rbuf, 8192) or return recv_err($self, $len);
146 # continue looping if $r > 0;
148 app_dispatch($self, $input, $rbuf);
152 my ($self, $input, $rbuf) = @_;
153 $self->rbuf_idle($rbuf);
154 my $env = $self->{env};
155 $self->{env} = undef; # for exists() check in ->busy
156 $env->{REMOTE_ADDR} = $self->{remote_addr};
157 $env->{REMOTE_PORT} = $self->{remote_port};
158 if (defined(my $host = $env->{HTTP_HOST})) {
159 $host =~ s/:([0-9]+)\z// and $env->{SERVER_PORT} = $1;
160 $env->{SERVER_NAME} = $host;
162 if (defined $input) {
163 sysseek($input, 0, SEEK_SET) or
164 die "BUG: psgi.input seek failed: $!";
166 # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
167 # to do proper cleanup:
168 $env->{'psgix.io'} = $self; # for ->close or async_pass
169 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
171 if (ref($res) eq 'CODE') {
172 $res->(sub { response_write($self, $env, $_[0]) });
174 response_write($self, $env, $res);
178 err($self, "response_write error: $@");
183 sub response_header_write {
184 my ($self, $env, $res) = @_;
185 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
186 my $status = $res->[0];
187 my $h = "$proto $status " . status_message($status) . "\r\n";
189 my $headers = $res->[1];
191 for (my $i = 0; $i < @$headers; $i += 2) {
192 my $k = $headers->[$i];
193 my $v = $headers->[$i + 1];
194 next if $k =~ /\A(?:Connection|Date)\z/i;
196 $len = $v if $k =~ /\AContent-Length\z/i;
197 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
203 my $conn = $env->{HTTP_CONNECTION} || '';
204 my $term = defined($len) || $chunked;
205 my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
207 if (!$term && $prot_persist) { # auto-chunk
208 $chunked = $alive = 2;
209 $h .= "Transfer-Encoding: chunked\r\n";
210 # no need for "Connection: keep-alive" with HTTP/1.1
211 } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
213 $h .= "Connection: keep-alive\r\n";
216 $h .= "Connection: close\r\n";
218 $h .= 'Date: ' . http_date() . "\r\n\r\n";
220 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
228 # middlewares such as Deflater may write empty strings
229 sub chunked_write ($$) {
231 return if $_[1] eq '';
232 msg_more($self, sprintf("%x\r\n", bytes::length($_[1])));
233 msg_more($self, $_[1]);
235 # use $self->write(\"\n\n") if you care about real-time
236 # streaming responses, public-inbox WWW does not.
237 msg_more($self, "\r\n");
240 sub identity_write ($$) {
242 $self->write(\($_[1])) if $_[1] ne '';
245 sub next_request ($) {
248 # avoid recursion for pipelined requests
249 PublicInbox::DS::requeue(\&process_pipelineq) if !@$pipelineq;
250 push @$pipelineq, $self;
251 } else { # wait for next request
257 my ($self, $alive) = @_;
258 delete $self->{env}; # we're no longer busy
259 $self->write(\"0\r\n\r\n") if $alive == 2;
260 $self->write($alive ? \&next_request : \&close);
265 my $forward = $self->{forward};
267 # limit our own running time for fairness with other
268 # clients and to avoid buffering too much:
275 # may close in PublicInbox::DS::write
276 if ($self->{alive} == 2) {
277 chunked_write($self, $buf);
279 identity_write($self, $buf);
284 my $new_size = push(@{$self->{wbuf}}, \&getline_pull);
286 # wbuf may be populated by {chunked,identity}_write()
287 # above, no need to rearm if so:
288 $self->requeue if $new_size == 1;
292 err($self, "response ->getline error: $@");
296 if (delete $self->{forward}) {
297 eval { $forward->close };
299 err($self, "response ->close error: $@");
300 $self->close; # idempotent
303 response_done($self, delete $self->{alive});
307 my ($self, $env, $res) = @_;
308 my $alive = response_header_write($self, $env, $res);
309 if (defined(my $body = $res->[2])) {
310 if (ref $body eq 'ARRAY') {
312 chunked_write($self, $_) for @$body;
314 identity_write($self, $_) for @$body;
316 response_done($self, $alive);
318 $self->{forward} = $body;
319 $self->{alive} = $alive;
320 getline_pull($self); # kick-off!
322 # these are returned to the calling application:
323 } elsif ($alive == 2) {
324 bless [ $self, $alive ], 'PublicInbox::HTTP::Chunked';
326 bless [ $self, $alive ], 'PublicInbox::HTTP::Identity';
330 sub input_tmpfile ($) {
331 my $input = tmpfile('http.input', $_[0]->{sock}) or return;
332 $input->autoflush(1);
337 my ($self, $env) = @_;
340 # rfc 7230 3.3.2, 3.3.3,: favor Transfer-Encoding over Content-Length
341 my $hte = $env->{HTTP_TRANSFER_ENCODING};
343 # rfc7230 3.3.3, point 3 says only chunked is accepted
344 # as the final encoding. Since neither public-inbox-httpd,
345 # git-http-backend, or our WWW-related code uses "gzip",
346 # "deflate" or "compress" as the Transfer-Encoding, we'll
348 return quit($self, 400) if $hte !~ /\Achunked\z/i;
351 $input = input_tmpfile($self);
353 $len = $env->{CONTENT_LENGTH};
356 return quit($self, 400) if $len !~ /\A[0-9]+\z/;
358 return quit($self, 413) if $len > $MAX_REQUEST_BUFFER;
359 $input = $len ? input_tmpfile($self) : $null_io;
365 # TODO: expire idle clients on ENFILE / EMFILE
366 return unless $input;
368 $env->{'psgi.input'} = $input;
370 $self->{input_left} = $len || 0;
373 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} // '') =~ /\Achunked\z/i }
376 eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
380 my ($self, $len) = @_;
381 my $msg = $! || '(zero write)';
382 $msg .= " ($len bytes remaining)" if defined $len;
383 err($self, "error buffering to input: $msg");
388 my ($self, $len) = @_;
389 if ($! == EAGAIN) { # epoll/kevent watch already set by do_read
390 $self->{input_left} = $len;
392 err($self, "error reading input: $! ($len bytes remaining)");
396 sub read_input_chunked { # unlikely...
397 my ($self, $rbuf) = @_;
398 $rbuf //= $self->{rbuf} // (\(my $x = ''));
399 my $input = $self->{env}->{'psgi.input'};
400 my $len = delete $self->{input_left};
402 while (1) { # chunk start
403 if ($len == CHUNK_ZEND) {
404 $$rbuf =~ s/\A\r\n//s and
405 return app_dispatch($self, $input, $rbuf);
407 return quit($self, 400) if bytes::length($$rbuf) > 2;
409 if ($len == CHUNK_END) {
410 if ($$rbuf =~ s/\A\r\n//s) {
412 } elsif (bytes::length($$rbuf) > 2) {
413 return quit($self, 400);
416 if ($len == CHUNK_START) {
417 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
419 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
420 return quit($self, 413);
422 } elsif (bytes::length($$rbuf) > CHUNK_MAX_HDR) {
423 return quit($self, 400);
425 # will break from loop since $len >= 0
428 if ($len < 0) { # chunk header is trickled, read more
429 $self->do_read($rbuf, 8192, bytes::length($$rbuf)) or
430 return recv_err($self, $len);
431 # (implicit) goto chunk_start if $r > 0;
433 $len = CHUNK_ZEND if $len == 0;
435 # drain the current chunk
438 my $w = xwrite($input, $rbuf, $len);
439 return write_err($self, "$len chunk") if !$w;
442 # we may have leftover data to parse
444 $$rbuf = substr($$rbuf, $w);
447 die "BUG: len < 0: $len";
453 # read more of current chunk
454 $self->do_read($rbuf, 8192) or
455 return recv_err($self, $len);
462 my ($self, $status) = @_;
463 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
466 undef; # input_prepare expects this
471 if (my $forward = delete $self->{forward}) {
472 eval { $forward->close };
473 err($self, "forward ->close error: $@") if $@;
475 $self->SUPER::close; # PublicInbox::DS::close
478 # for graceful shutdown in PublicInbox::Daemon:
481 ($self->{rbuf} || exists($self->{env}) || $self->{wbuf});
484 # Chunked and Identity packages are used for writing responses.
485 # They may be exposed to the PSGI application when the PSGI app
486 # returns a CODE ref for "push"-based responses
487 package PublicInbox::HTTP::Chunked;
491 # ([$http], $buf) = @_;
492 PublicInbox::HTTP::chunked_write($_[0]->[0], $_[1])
496 # $_[0] = [$http, $alive]
497 PublicInbox::HTTP::response_done(@{$_[0]});
500 package PublicInbox::HTTP::Identity;
502 our @ISA = qw(PublicInbox::HTTP::Chunked);
505 # ([$http], $buf) = @_;
506 PublicInbox::HTTP::identity_write($_[0]->[0], $_[1]);