1 # Copyright (C) 2016-2018 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 rbuf input_left remote_addr remote_port forward pull);
15 use bytes (); # only for bytes::length
17 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
18 use HTTP::Status qw(status_message);
19 use HTTP::Date qw(time2str);
21 require PublicInbox::EvCleanup;
23 CHUNK_START => -1, # [a-f0-9]+\r\n
24 CHUNK_END => -2, # \r\n
25 CHUNK_ZEND => -3, # \r\n
31 sub process_pipelineq () {
41 # Use the same configuration parameter as git since this is primarily
42 # a slow-client sponge for git-http-backend
43 # TODO: support per-respository http.maxRequestBuffer somehow...
44 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
47 open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!";
52 $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
56 my ($class, $sock, $addr, $httpd) = @_;
57 my $self = fields::new($class);
58 $self->SUPER::new($sock);
59 $self->{httpd} = $httpd;
61 ($self->{remote_addr}, $self->{remote_port}) =
62 PublicInbox::Daemon::host_with_port($addr);
67 sub event_step { # called by PublicInbox::DS
70 my $wbuf = $self->{wbuf};
73 return if $self->{closed} || scalar(@$wbuf);
75 # only read more requests if we've drained the write buffer,
76 # otherwise we can be buffering infinitely w/o backpressure
78 return read_input($self) if defined $self->{env};
80 my $off = length($self->{rbuf});
81 my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
83 return $self->close if $r == 0;
84 return rbuf_process($self);
86 return if $!{EAGAIN}; # no need to call watch_read(1) again
88 # common for clients to break connections without warning,
89 # would be too noisy to log here:
96 my %env = %{$self->{httpd}->{env}}; # full hash copy
97 my $r = parse_http_request($self->{rbuf}, \%env);
99 # We do not support Trailers in chunked requests, for now
100 # (they are rarely-used and git (as of 2.7.2) does not use them)
101 if ($r == -1 || $env{HTTP_TRAILER} ||
102 # this length-check is necessary for PURE_PERL=1:
103 ($r == -2 && length($self->{rbuf}) > 0x4000)) {
104 return quit($self, 400);
106 return $self->watch_read(1) if $r < 0; # incomplete
107 $self->{rbuf} = substr($self->{rbuf}, $r);
109 my $len = input_prepare($self, \%env);
110 defined $len or return write_err($self, undef); # EMFILE/ENFILE
112 $len ? read_input($self) : app_dispatch($self);
117 my $env = $self->{env};
118 return if $env->{REMOTE_ADDR}; # in app dispatch
119 return read_input_chunked($self) if env_chunked($env);
121 # env->{CONTENT_LENGTH} (identity)
122 my $sock = $self->{sock};
123 my $len = $self->{input_left};
124 $self->{input_left} = undef;
125 my $rbuf = \($self->{rbuf});
126 my $input = $env->{'psgi.input'};
130 my $w = write_in_full($input, $rbuf, $len);
131 return write_err($self, $len) unless $w;
133 die "BUG: $len < 0 (w=$w)" if $len < 0;
134 if ($len == 0) { # next request may be pipelined
135 $$rbuf = substr($$rbuf, $w);
140 my $r = sysread($sock, $$rbuf, 8192);
141 return recv_err($self, $r, $len) unless $r;
142 # continue looping if $r > 0;
144 app_dispatch($self, $input);
148 my ($self, $input) = @_;
149 $self->watch_read(0);
150 my $env = $self->{env};
151 $env->{REMOTE_ADDR} = $self->{remote_addr};
152 $env->{REMOTE_PORT} = $self->{remote_port};
153 if (my $host = $env->{HTTP_HOST}) {
154 $host =~ s/:([0-9]+)\z// and $env->{SERVER_PORT} = $1;
155 $env->{SERVER_NAME} = $host;
157 if (defined $input) {
158 sysseek($input, 0, SEEK_SET) or
159 die "BUG: psgi.input seek failed: $!";
161 # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
162 # to do proper cleanup:
163 $env->{'psgix.io'} = $self; # only for ->close
164 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
166 if (ref($res) eq 'CODE') {
167 $res->(sub { response_write($self, $env, $_[0]) });
169 response_write($self, $env, $res);
175 sub response_header_write {
176 my ($self, $env, $res) = @_;
177 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
178 my $status = $res->[0];
179 my $h = "$proto $status " . status_message($status) . "\r\n";
181 my $headers = $res->[1];
183 for (my $i = 0; $i < @$headers; $i += 2) {
184 my $k = $headers->[$i];
185 my $v = $headers->[$i + 1];
186 next if $k =~ /\A(?:Connection|Date)\z/i;
188 $len = $v if $k =~ /\AContent-Length\z/i;
189 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
195 my $conn = $env->{HTTP_CONNECTION} || '';
196 my $term = defined($len) || $chunked;
197 my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
199 if (!$term && $prot_persist) { # auto-chunk
200 $chunked = $alive = 2;
201 $h .= "Transfer-Encoding: chunked\r\n";
202 # no need for "Connection: keep-alive" with HTTP/1.1
203 } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
205 $h .= "Connection: keep-alive\r\n";
208 $h .= "Connection: close\r\n";
210 $h .= 'Date: ' . http_date() . "\r\n\r\n";
212 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
220 # middlewares such as Deflater may write empty strings
221 sub chunked_wcb ($) {
224 return if $_[0] eq '';
225 more($self, sprintf("%x\r\n", bytes::length($_[0])));
228 # use $self->write("\n\n") if you care about real-time
229 # streaming responses, public-inbox WWW does not.
234 sub identity_wcb ($) {
236 sub { $self->write(\($_[0])) if $_[0] ne '' }
239 sub next_request ($) {
241 if ($self->{rbuf} eq '') { # wait for next request
242 $self->watch_read(1);
243 } else { # avoid recursion for pipelined requests
244 push @$pipelineq, $self;
245 $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
249 sub response_done_cb ($$) {
250 my ($self, $alive) = @_;
252 my $env = $self->{env};
253 $self->{env} = undef;
254 $self->write("0\r\n\r\n") if $alive == 2;
255 $self->write(sub{$alive ? next_request($self) : $self->close});
259 sub getline_cb ($$$) {
260 my ($self, $write, $close) = @_;
262 my $forward = $self->{forward};
263 # limit our own running time for fairness with other
264 # clients and to avoid buffering too much:
266 my $buf = eval { $forward->getline };
268 $write->($buf); # may close in PublicInbox::DS::write
269 unless ($self->{closed}) {
270 my $next = $self->{pull};
271 if (scalar @{$self->{wbuf}}) {
274 PublicInbox::EvCleanup::asap($next);
279 err($self, "response ->getline error: $@");
285 $self->{forward} = $self->{pull} = undef;
288 eval { $forward->close };
290 err($self, "response ->close error: $@");
291 $self->close; # idempotent
297 sub getline_response ($$$) {
298 my ($self, $write, $close) = @_;
299 my $pull = $self->{pull} = sub { getline_cb($self, $write, $close) };
304 my ($self, $env, $res) = @_;
305 my $alive = response_header_write($self, $env, $res);
306 my $close = response_done_cb($self, $alive);
307 my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
308 if (defined(my $body = $res->[2])) {
309 if (ref $body eq 'ARRAY') {
310 $write->($_) foreach @$body;
313 $self->{forward} = $body;
314 getline_response($self, $write, $close);
317 # this is returned to the calling application:
318 Plack::Util::inline_object(write => $write, close => $close);
322 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
325 return if $self->{closed};
326 if (MSG_MORE && !scalar(@{$self->{wbuf}})) {
327 my $n = send($self->{sock}, $_[1], MSG_MORE);
329 my $nlen = length($_[1]) - $n;
330 return 1 if $nlen == 0; # all done!
332 # PublicInbox::DS::write queues the unwritten substring:
333 return $self->write(substr($_[1], $n, $nlen));
340 my ($self, $env) = @_;
342 my $len = $env->{CONTENT_LENGTH};
344 if ($len > $MAX_REQUEST_BUFFER) {
348 open($input, '+>', undef);
349 } elsif (env_chunked($env)) {
351 open($input, '+>', undef);
356 # TODO: expire idle clients on ENFILE / EMFILE
357 return unless $input;
359 $env->{'psgi.input'} = $input;
361 $self->{input_left} = $len || 0;
364 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
367 eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
371 my ($self, $len) = @_;
372 my $msg = $! || '(zero write)';
373 $msg .= " ($len bytes remaining)" if defined $len;
374 err($self, "error buffering to input: $msg");
379 my ($self, $r, $len) = @_;
380 return $self->close if (defined $r && $r == 0);
382 $self->{input_left} = $len;
385 err($self, "error reading for input: $! ($len bytes remaining)");
390 my ($fh, $rbuf, $len) = @_;
394 my $w = syswrite($fh, $$rbuf, $len, $off);
395 return ($rv ? $rv : $w) unless $w; # undef or 0
403 sub read_input_chunked { # unlikely...
405 my $input = $self->{env}->{'psgi.input'};
406 my $sock = $self->{sock};
407 my $len = $self->{input_left};
408 $self->{input_left} = undef;
409 my $rbuf = \($self->{rbuf});
411 while (1) { # chunk start
412 if ($len == CHUNK_ZEND) {
413 $$rbuf =~ s/\A\r\n//s and
414 return app_dispatch($self, $input);
415 return quit($self, 400) if length($$rbuf) > 2;
417 if ($len == CHUNK_END) {
418 if ($$rbuf =~ s/\A\r\n//s) {
420 } elsif (length($$rbuf) > 2) {
421 return quit($self, 400);
424 if ($len == CHUNK_START) {
425 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
427 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
428 return quit($self, 413);
430 } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
431 return quit($self, 400);
433 # will break from loop since $len >= 0
436 if ($len < 0) { # chunk header is trickled, read more
437 my $off = length($$rbuf);
438 my $r = sysread($sock, $$rbuf, 8192, $off);
439 return recv_err($self, $r, $len) unless $r;
440 # (implicit) goto chunk_start if $r > 0;
442 $len = CHUNK_ZEND if $len == 0;
444 # drain the current chunk
447 my $w = write_in_full($input, $rbuf, $len);
448 return write_err($self, "$len chunk") if !$w;
451 # we may have leftover data to parse
453 $$rbuf = substr($$rbuf, $w);
456 die "BUG: len < 0: $len";
462 # read more of current chunk
463 my $r = sysread($sock, $$rbuf, 8192);
464 return recv_err($self, $r, $len) unless $r;
471 my ($self, $status) = @_;
472 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
479 my $forward = $self->{forward};
480 my $env = $self->{env};
481 delete $env->{'psgix.io'} if $env; # prevent circular references
482 $self->{pull} = $self->{forward} = $self->{env} = undef;
484 eval { $forward->close };
485 err($self, "forward ->close error: $@") if $@;
487 $self->SUPER::close(@_);
490 # for graceful shutdown in PublicInbox::Daemon:
493 ($self->{rbuf} ne '' || $self->{env} || scalar(@{$self->{wbuf}}));