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;
22 PublicInbox::DS->import(qw(msg_more write_in_full));
23 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
25 CHUNK_START => -1, # [a-f0-9]+\r\n
26 CHUNK_END => -2, # \r\n
27 CHUNK_ZEND => -3, # \r\n
34 sub process_pipelineq () {
39 next unless $_->{sock};
44 # Use the same configuration parameter as git since this is primarily
45 # a slow-client sponge for git-http-backend
46 # TODO: support per-respository http.maxRequestBuffer somehow...
47 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
50 open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!";
55 $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
59 my ($class, $sock, $addr, $httpd) = @_;
60 my $self = fields::new($class);
61 $self->SUPER::new($sock, EPOLLIN | EPOLLONESHOT);
62 $self->{httpd} = $httpd;
64 ($self->{remote_addr}, $self->{remote_port}) =
65 PublicInbox::Daemon::host_with_port($addr);
69 sub event_step { # called by PublicInbox::DS
72 return unless $self->flush_write && $self->{sock};
74 # only read more requests if we've drained the write buffer,
75 # otherwise we can be buffering infinitely w/o backpressure
77 return read_input($self) if defined $self->{env};
79 my $off = length($self->{rbuf});
80 my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
82 return $self->close if $r == 0;
83 return rbuf_process($self);
86 # common for clients to break connections without warning,
87 # would be too noisy to log here:
88 $! == EAGAIN ? $self->watch_in1 : $self->close;
94 my %env = %{$self->{httpd}->{env}}; # full hash copy
95 my $r = parse_http_request($self->{rbuf}, \%env);
97 # We do not support Trailers in chunked requests, for now
98 # (they are rarely-used and git (as of 2.7.2) does not use them)
99 if ($r == -1 || $env{HTTP_TRAILER} ||
100 # this length-check is necessary for PURE_PERL=1:
101 ($r == -2 && length($self->{rbuf}) > 0x4000)) {
102 return quit($self, 400);
104 return $self->watch_in1 if $r < 0; # incomplete
105 $self->{rbuf} = substr($self->{rbuf}, $r);
107 my $len = input_prepare($self, \%env);
108 defined $len or return write_err($self, undef); # EMFILE/ENFILE
110 $len ? read_input($self) : app_dispatch($self);
115 my $env = $self->{env};
116 return if $env->{REMOTE_ADDR}; # in app dispatch
117 return read_input_chunked($self) if env_chunked($env);
119 # env->{CONTENT_LENGTH} (identity)
120 my $sock = $self->{sock};
121 my $len = $self->{input_left};
122 $self->{input_left} = undef;
123 my $rbuf = \($self->{rbuf});
124 my $input = $env->{'psgi.input'};
128 my $w = write_in_full($input, $rbuf, $len, 0);
129 return write_err($self, $len) unless $w;
131 die "BUG: $len < 0 (w=$w)" if $len < 0;
132 if ($len == 0) { # next request may be pipelined
133 $$rbuf = substr($$rbuf, $w);
138 my $r = sysread($sock, $$rbuf, 8192);
139 return recv_err($self, $r, $len) unless $r;
140 # continue looping if $r > 0;
142 app_dispatch($self, $input);
146 my ($self, $input) = @_;
147 my $env = $self->{env};
148 $env->{REMOTE_ADDR} = $self->{remote_addr};
149 $env->{REMOTE_PORT} = $self->{remote_port};
150 if (my $host = $env->{HTTP_HOST}) {
151 $host =~ s/:([0-9]+)\z// and $env->{SERVER_PORT} = $1;
152 $env->{SERVER_NAME} = $host;
154 if (defined $input) {
155 sysseek($input, 0, SEEK_SET) or
156 die "BUG: psgi.input seek failed: $!";
158 # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
159 # to do proper cleanup:
160 $env->{'psgix.io'} = $self; # only for ->close
161 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
163 if (ref($res) eq 'CODE') {
164 $res->(sub { response_write($self, $env, $_[0]) });
166 response_write($self, $env, $res);
172 sub response_header_write {
173 my ($self, $env, $res) = @_;
174 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
175 my $status = $res->[0];
176 my $h = "$proto $status " . status_message($status) . "\r\n";
178 my $headers = $res->[1];
180 for (my $i = 0; $i < @$headers; $i += 2) {
181 my $k = $headers->[$i];
182 my $v = $headers->[$i + 1];
183 next if $k =~ /\A(?:Connection|Date)\z/i;
185 $len = $v if $k =~ /\AContent-Length\z/i;
186 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
192 my $conn = $env->{HTTP_CONNECTION} || '';
193 my $term = defined($len) || $chunked;
194 my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
196 if (!$term && $prot_persist) { # auto-chunk
197 $chunked = $alive = 2;
198 $h .= "Transfer-Encoding: chunked\r\n";
199 # no need for "Connection: keep-alive" with HTTP/1.1
200 } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
202 $h .= "Connection: keep-alive\r\n";
205 $h .= "Connection: close\r\n";
207 $h .= 'Date: ' . http_date() . "\r\n\r\n";
209 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
217 # middlewares such as Deflater may write empty strings
218 sub chunked_wcb ($) {
221 return if $_[0] eq '';
222 msg_more($self, sprintf("%x\r\n", bytes::length($_[0])));
223 msg_more($self, $_[0]);
225 # use $self->write(\"\n\n") if you care about real-time
226 # streaming responses, public-inbox WWW does not.
227 msg_more($self, "\r\n");
231 sub identity_wcb ($) {
233 sub { $self->write(\($_[0])) if $_[0] ne '' }
236 sub next_request ($) {
238 if ($self->{rbuf} eq '') { # wait for next request
240 } else { # avoid recursion for pipelined requests
241 push @$pipelineq, $self;
242 $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
246 sub response_done_cb ($$) {
247 my ($self, $alive) = @_;
249 my $env = $self->{env};
250 $self->{env} = undef;
251 $self->write(\"0\r\n\r\n") if $alive == 2;
252 $self->write(sub{$alive ? next_request($self) : $self->close});
256 sub getline_cb ($$$) {
257 my ($self, $write, $close) = @_;
259 my $forward = $self->{forward};
260 # limit our own running time for fairness with other
261 # clients and to avoid buffering too much:
263 my $buf = eval { $forward->getline };
265 $write->($buf); # may close in PublicInbox::DS::write
267 my $next = $self->{pull};
271 PublicInbox::EvCleanup::asap($next);
276 err($self, "response ->getline error: $@");
282 $self->{forward} = $self->{pull} = undef;
285 eval { $forward->close };
287 err($self, "response ->close error: $@");
288 $self->close; # idempotent
294 sub getline_response ($$$) {
295 my ($self, $write, $close) = @_;
296 my $pull = $self->{pull} = sub { getline_cb($self, $write, $close) };
301 my ($self, $env, $res) = @_;
302 my $alive = response_header_write($self, $env, $res);
303 my $close = response_done_cb($self, $alive);
304 my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
305 if (defined(my $body = $res->[2])) {
306 if (ref $body eq 'ARRAY') {
307 $write->($_) foreach @$body;
310 $self->{forward} = $body;
311 getline_response($self, $write, $close);
314 # this is returned to the calling application:
315 Plack::Util::inline_object(write => $write, close => $close);
320 my ($self, $env) = @_;
322 my $len = $env->{CONTENT_LENGTH};
324 if ($len > $MAX_REQUEST_BUFFER) {
328 open($input, '+>', undef);
329 } elsif (env_chunked($env)) {
331 open($input, '+>', undef);
336 # TODO: expire idle clients on ENFILE / EMFILE
337 return unless $input;
339 $env->{'psgi.input'} = $input;
341 $self->{input_left} = $len || 0;
344 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
347 eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
351 my ($self, $len) = @_;
352 my $msg = $! || '(zero write)';
353 $msg .= " ($len bytes remaining)" if defined $len;
354 err($self, "error buffering to input: $msg");
359 my ($self, $r, $len) = @_;
360 return $self->close if (defined $r && $r == 0);
362 $self->{input_left} = $len;
363 return $self->watch_in1;
365 err($self, "error reading for input: $! ($len bytes remaining)");
369 sub read_input_chunked { # unlikely...
371 my $input = $self->{env}->{'psgi.input'};
372 my $sock = $self->{sock};
373 my $len = $self->{input_left};
374 $self->{input_left} = undef;
375 my $rbuf = \($self->{rbuf});
377 while (1) { # chunk start
378 if ($len == CHUNK_ZEND) {
379 $$rbuf =~ s/\A\r\n//s and
380 return app_dispatch($self, $input);
381 return quit($self, 400) if length($$rbuf) > 2;
383 if ($len == CHUNK_END) {
384 if ($$rbuf =~ s/\A\r\n//s) {
386 } elsif (length($$rbuf) > 2) {
387 return quit($self, 400);
390 if ($len == CHUNK_START) {
391 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
393 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
394 return quit($self, 413);
396 } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
397 return quit($self, 400);
399 # will break from loop since $len >= 0
402 if ($len < 0) { # chunk header is trickled, read more
403 my $off = length($$rbuf);
404 my $r = sysread($sock, $$rbuf, 8192, $off);
405 return recv_err($self, $r, $len) unless $r;
406 # (implicit) goto chunk_start if $r > 0;
408 $len = CHUNK_ZEND if $len == 0;
410 # drain the current chunk
413 my $w = write_in_full($input, $rbuf, $len, 0);
414 return write_err($self, "$len chunk") if !$w;
417 # we may have leftover data to parse
419 $$rbuf = substr($$rbuf, $w);
422 die "BUG: len < 0: $len";
428 # read more of current chunk
429 my $r = sysread($sock, $$rbuf, 8192);
430 return recv_err($self, $r, $len) unless $r;
437 my ($self, $status) = @_;
438 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
445 my $forward = $self->{forward};
446 my $env = $self->{env};
447 delete $env->{'psgix.io'} if $env; # prevent circular references
448 $self->{pull} = $self->{forward} = $self->{env} = undef;
450 eval { $forward->close };
451 err($self, "forward ->close error: $@") if $@;
453 $self->SUPER::close(@_);
456 # for graceful shutdown in PublicInbox::Daemon:
459 ($self->{rbuf} ne '' || $self->{env} || $self->{wbuf});