X-Git-Url: http://www.git.stargrave.org/?p=public-inbox.git;a=blobdiff_plain;f=lib%2FPublicInbox%2FHTTP.pm;h=10e6d6a43b518115c7eece8a5f11e67ebe613fb2;hp=a5c56e2573946a1ba179c8d3eb73076585053f43;hb=b6f480ed58abc5ae2a426ef4f792621b9d3cf283;hpb=7dd78012da81d48e5e73e56c3255895dfa9de1f5 diff --git a/lib/PublicInbox/HTTP.pm b/lib/PublicInbox/HTTP.pm index a5c56e25..10e6d6a4 100644 --- a/lib/PublicInbox/HTTP.pm +++ b/lib/PublicInbox/HTTP.pm @@ -1,22 +1,24 @@ -# Copyright (C) 2016 all contributors +# Copyright (C) 2016-2018 all contributors # License: AGPL-3.0+ # # Generic PSGI server for convenience. It aims to provide # a consistent experience for public-inbox admins so they don't have # to learn different ways to admin both NNTP and HTTP components. -# There's nothing public-inbox-specific, here. +# There's nothing which depends on public-inbox, here. # Each instance of this class represents a HTTP client socket package PublicInbox::HTTP; use strict; use warnings; -use base qw(Danga::Socket); -use fields qw(httpd env rbuf input_left remote_addr remote_port); +use base qw(PublicInbox::DS); +use fields qw(httpd env rbuf input_left remote_addr remote_port forward pull); +use bytes (); # only for bytes::length use Fcntl qw(:seek); use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl use HTTP::Status qw(status_message); use HTTP::Date qw(time2str); -use IO::File; +use IO::Handle; +require PublicInbox::EvCleanup; use constant { CHUNK_START => -1, # [a-f0-9]+\r\n CHUNK_END => -2, # \r\n @@ -24,13 +26,25 @@ use constant { CHUNK_MAX_HDR => 256, }; +my $pipelineq = []; +my $pipet; +sub process_pipelineq () { + my $q = $pipelineq; + $pipet = undef; + $pipelineq = []; + foreach (@$q) { + next if $_->{closed}; + rbuf_process($_); + } +} + # Use the same configuration parameter as git since this is primarily # a slow-client sponge for git-http-backend # TODO: support per-respository http.maxRequestBuffer somehow... our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} || (10 * 1024 * 1024); -my $null_io = IO::File->new('/dev/null', '<'); +open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!"; my $http_date; my $prev = 0; sub http_date () { @@ -50,7 +64,7 @@ sub new ($$$) { $self; } -sub event_read { # called by Danga::Socket +sub event_read { # called by PublicInbox::DS my ($self) = @_; return event_read_input($self) if defined $self->{env}; @@ -85,7 +99,7 @@ sub rbuf_process { $self->{rbuf} = substr($self->{rbuf}, $r); my $len = input_prepare($self, \%env); - defined $len or return write_err($self); # EMFILE/ENFILE + defined $len or return write_err($self, undef); # EMFILE/ENFILE $len ? event_read_input($self) : app_dispatch($self); } @@ -105,7 +119,7 @@ sub event_read_input ($) { while ($len > 0) { if ($$rbuf ne '') { my $w = write_in_full($input, $rbuf, $len); - return write_err($self) unless $w; + return write_err($self, $len) unless $w; $len -= $w; die "BUG: $len < 0 (w=$w)" if $len < 0; if ($len == 0) { # next request may be pipelined @@ -118,11 +132,11 @@ sub event_read_input ($) { return recv_err($self, $r, $len) unless $r; # continue looping if $r > 0; } - app_dispatch($self); + app_dispatch($self, $input); } -sub app_dispatch ($) { - my ($self) = @_; +sub app_dispatch { + my ($self, $input) = @_; $self->watch_read(0); my $env = $self->{env}; $env->{REMOTE_ADDR} = $self->{remote_addr}; @@ -131,10 +145,13 @@ sub app_dispatch ($) { $host =~ s/:(\d+)\z// and $env->{SERVER_PORT} = $1; $env->{SERVER_NAME} = $host; } - - sysseek($env->{'psgi.input'}, 0, SEEK_SET) or + if (defined $input) { + sysseek($input, 0, SEEK_SET) or die "BUG: psgi.input seek failed: $!"; - + } + # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close), + # to do proper cleanup: + $env->{'psgix.io'} = $self; # only for ->close my $res = Plack::Util::run_app($self->{httpd}->{app}, $env); eval { if (ref($res) eq 'CODE') { @@ -163,42 +180,131 @@ sub response_header_write { if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) { $chunked = 1; } - $h .= "$k: $v\r\n"; } my $conn = $env->{HTTP_CONNECTION} || ''; - my $alive = (defined($len) || $chunked) && - ($proto eq 'HTTP/1.1' && $conn !~ /\bclose\b/i) || - ($conn =~ /\bkeep-alive\b/i); - - $h .= 'Connection: ' . ($alive ? 'keep-alive' : 'close'); - $h .= "\r\nDate: " . http_date() . "\r\n\r\n"; + my $term = defined($len) || $chunked; + my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i); + my $alive; + if (!$term && $prot_persist) { # auto-chunk + $chunked = $alive = 2; + $h .= "Transfer-Encoding: chunked\r\n"; + # no need for "Connection: keep-alive" with HTTP/1.1 + } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) { + $alive = 1; + $h .= "Connection: keep-alive\r\n"; + } else { + $alive = 0; + $h .= "Connection: close\r\n"; + } + $h .= 'Date: ' . http_date() . "\r\n\r\n"; if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') { more($self, $h); } else { $self->write($h); } - ($alive, $chunked); + $alive; +} + +# middlewares such as Deflater may write empty strings +sub chunked_wcb ($) { + my ($self) = @_; + sub { + return if $_[0] eq ''; + more($self, sprintf("%x\r\n", bytes::length($_[0]))); + more($self, $_[0]); + + # use $self->write("\n\n") if you care about real-time + # streaming responses, public-inbox WWW does not. + more($self, "\r\n"); + } +} + +sub identity_wcb ($) { + my ($self) = @_; + sub { $self->write(\($_[0])) if $_[0] ne '' } +} + +sub next_request ($) { + my ($self) = @_; + $self->watch_write(0); + if ($self->{rbuf} eq '') { # wait for next request + $self->watch_read(1); + } else { # avoid recursion for pipelined requests + push @$pipelineq, $self; + $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq); + } +} + +sub response_done_cb ($$) { + my ($self, $alive) = @_; + sub { + my $env = $self->{env}; + $self->{env} = undef; + $self->write("0\r\n\r\n") if $alive == 2; + $self->write(sub{$alive ? next_request($self) : $self->close}); + } +} + +sub getline_cb ($$$) { + my ($self, $write, $close) = @_; + local $/ = \8192; + my $forward = $self->{forward}; + # limit our own running time for fairness with other + # clients and to avoid buffering too much: + if ($forward) { + my $buf = eval { $forward->getline }; + if (defined $buf) { + $write->($buf); # may close in PublicInbox::DS::write + unless ($self->{closed}) { + my $next = $self->{pull}; + if ($self->{write_buf_size}) { + $self->write($next); + } else { + PublicInbox::EvCleanup::asap($next); + } + return; + } + } elsif ($@) { + err($self, "response ->getline error: $@"); + $forward = undef; + $self->close; + } + } + + $self->{forward} = $self->{pull} = undef; + # avoid recursion + if ($forward) { + eval { $forward->close }; + if ($@) { + err($self, "response ->close error: $@"); + $self->close; # idempotent + } + } + $close->(); +} + +sub getline_response ($$$) { + my ($self, $write, $close) = @_; + my $pull = $self->{pull} = sub { getline_cb($self, $write, $close) }; + $pull->(); } sub response_write { my ($self, $env, $res) = @_; - my ($alive, $chunked) = response_header_write($self, $env, $res); - my $write = sub { $self->write($_[0]) }; - my $close = sub { - if ($alive) { - $self->event_write; # watch for readability if done + my $alive = response_header_write($self, $env, $res); + my $close = response_done_cb($self, $alive); + my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self); + if (defined(my $body = $res->[2])) { + if (ref $body eq 'ARRAY') { + $write->($_) foreach @$body; + $close->(); } else { - $self->write(sub { $self->close }); + $self->{forward} = $body; + getline_response($self, $write, $close); } - $self->{env} = undef; - }; - - if (defined $res->[2]) { - Plack::Util::foreach($res->[2], $write); - $close->(); } else { # this is returned to the calling application: Plack::Util::inline_object(write => $write, close => $close); @@ -208,50 +314,40 @@ sub response_write { use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0; sub more ($$) { my $self = $_[0]; + return if $self->{closed}; if (MSG_MORE && !$self->{write_buf_size}) { my $n = send($self->{sock}, $_[1], MSG_MORE); if (defined $n) { - my $dlen = length($_[1]); - return 1 if $n == $dlen; # all done! - $_[1] = substr($_[1], $n, $dlen - $n); - # fall through to normal write: + my $nlen = length($_[1]) - $n; + return 1 if $nlen == 0; # all done! + + # PublicInbox::DS::write queues the unwritten substring: + return $self->write(substr($_[1], $n, $nlen)); } } $self->write($_[1]); } -# overrides existing Danga::Socket method -sub event_write { - my ($self) = @_; - # only continue watching for readability when we are done writing: - return if $self->write(undef) != 1; - - if ($self->{rbuf} eq '') { # wait for next request - $self->watch_read(1); - } else { # avoid recursion for pipelined requests - Danga::Socket->AddTimer(0, sub { rbuf_process($self) }); - } -} - sub input_prepare { my ($self, $env) = @_; - my $input = $null_io; + my $input; my $len = $env->{CONTENT_LENGTH}; if ($len) { if ($len > $MAX_REQUEST_BUFFER) { quit($self, 413); return; } - $input = IO::File->new_tmpfile; + open($input, '+>', undef); } elsif (env_chunked($env)) { $len = CHUNK_START; - $input = IO::File->new_tmpfile; + open($input, '+>', undef); + } else { + $input = $null_io; } # TODO: expire idle clients on ENFILE / EMFILE return unless $input; - binmode $input; $env->{'psgi.input'} = $input; $self->{env} = $env; $self->{input_left} = $len || 0; @@ -259,11 +355,15 @@ sub input_prepare { sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i } +sub err ($$) { + eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") }; +} + sub write_err { - my ($self) = @_; - my $err = $self->{httpd}->{env}->{'psgi.errors'}; + my ($self, $len) = @_; my $msg = $! || '(zero write)'; - $err->print("error buffering to input: $msg\n"); + $msg .= " ($len bytes remaining)" if defined $len; + err($self, "error buffering to input: $msg"); quit($self, 500); } @@ -274,8 +374,7 @@ sub recv_err { $self->{input_left} = $len; return; } - my $err = $self->{httpd}->{env}->{'psgi.errors'}; - $err->print("error reading for input: $! ($len bytes remaining)\n"); + err($self, "error reading for input: $! ($len bytes remaining)"); quit($self, 500); } @@ -303,7 +402,8 @@ sub event_read_input_chunked { # unlikely... while (1) { # chunk start if ($len == CHUNK_ZEND) { - return app_dispatch($self) if $$rbuf =~ s/\A\r\n//s; + $$rbuf =~ s/\A\r\n//s and + return app_dispatch($self, $input); return quit($self, 400) if length($$rbuf) > 2; } if ($len == CHUNK_END) { @@ -337,7 +437,7 @@ sub event_read_input_chunked { # unlikely... until ($len <= 0) { if ($$rbuf ne '') { my $w = write_in_full($input, $rbuf, $len); - return write_err($self) unless $w; + return write_err($self, "$len chunk") if !$w; $len -= $w; if ($len == 0) { # we may have leftover data to parse @@ -366,16 +466,22 @@ sub quit { $self->close; } -# callbacks for Danga::Socket +# callbacks for PublicInbox::DS sub event_hup { $_[0]->close } sub event_err { $_[0]->close } -sub write ($$) : method { - my PublicInbox::HTTP $self = $_[0]; - return 1 if (defined($_[1]) && ref($_[1]) eq '' && $_[1] eq ''); - - $self->SUPER::write($_[1]); +sub close { + my $self = shift; + my $forward = $self->{forward}; + my $env = $self->{env}; + delete $env->{'psgix.io'} if $env; # prevent circular references + $self->{pull} = $self->{forward} = $self->{env} = undef; + if ($forward) { + eval { $forward->close }; + err($self, "forward ->close error: $@") if $@; + } + $self->SUPER::close(@_); } # for graceful shutdown in PublicInbox::Daemon: