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(Danga::Socket);
14 use fields qw(httpd env rbuf input_left remote_addr remote_port forward pull);
16 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
17 use HTTP::Status qw(status_message);
18 use HTTP::Date qw(time2str);
21 CHUNK_START => -1, # [a-f0-9]+\r\n
22 CHUNK_END => -2, # \r\n
23 CHUNK_ZEND => -3, # \r\n
29 sub process_pipelineq () {
39 # Use the same configuration parameter as git since this is primarily
40 # a slow-client sponge for git-http-backend
41 # TODO: support per-respository http.maxRequestBuffer somehow...
42 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
45 open(my $null_io, '<', '/dev/null') or die "failed to open /dev/null: $!";
50 $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
54 my ($class, $sock, $addr, $httpd) = @_;
55 my $self = fields::new($class);
56 $self->SUPER::new($sock);
57 $self->{httpd} = $httpd;
59 ($self->{remote_addr}, $self->{remote_port}) =
60 PublicInbox::Daemon::host_with_port($addr);
65 sub event_read { # called by Danga::Socket
68 return event_read_input($self) if defined $self->{env};
70 my $off = length($self->{rbuf});
71 my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
73 return $self->close if $r == 0;
74 return rbuf_process($self);
76 return if $!{EAGAIN}; # no need to call watch_read(1) again
78 # common for clients to break connections without warning,
79 # would be too noisy to log here:
86 my %env = %{$self->{httpd}->{env}}; # full hash copy
87 my $r = parse_http_request($self->{rbuf}, \%env);
89 # We do not support Trailers in chunked requests, for now
90 # (they are rarely-used and git (as of 2.7.2) does not use them)
91 if ($r == -1 || $env{HTTP_TRAILER} ||
92 # this length-check is necessary for PURE_PERL=1:
93 ($r == -2 && length($self->{rbuf}) > 0x4000)) {
94 return quit($self, 400);
96 return $self->watch_read(1) if $r < 0; # incomplete
97 $self->{rbuf} = substr($self->{rbuf}, $r);
99 my $len = input_prepare($self, \%env);
100 defined $len or return write_err($self, undef); # EMFILE/ENFILE
102 $len ? event_read_input($self) : app_dispatch($self);
105 sub event_read_input ($) {
107 my $env = $self->{env};
108 return event_read_input_chunked($self) if env_chunked($env);
110 # env->{CONTENT_LENGTH} (identity)
111 my $sock = $self->{sock};
112 my $len = $self->{input_left};
113 $self->{input_left} = undef;
114 my $rbuf = \($self->{rbuf});
115 my $input = $env->{'psgi.input'};
119 my $w = write_in_full($input, $rbuf, $len);
120 return write_err($self, $len) unless $w;
122 die "BUG: $len < 0 (w=$w)" if $len < 0;
123 if ($len == 0) { # next request may be pipelined
124 $$rbuf = substr($$rbuf, $w);
129 my $r = sysread($sock, $$rbuf, 8192);
130 return recv_err($self, $r, $len) unless $r;
131 # continue looping if $r > 0;
133 app_dispatch($self, $input);
137 my ($self, $input) = @_;
138 $self->watch_read(0);
139 my $env = $self->{env};
140 $env->{REMOTE_ADDR} = $self->{remote_addr};
141 $env->{REMOTE_PORT} = $self->{remote_port};
142 if (my $host = $env->{HTTP_HOST}) {
143 $host =~ s/:(\d+)\z// and $env->{SERVER_PORT} = $1;
144 $env->{SERVER_NAME} = $host;
146 if (defined $input) {
147 sysseek($input, 0, SEEK_SET) or
148 die "BUG: psgi.input seek failed: $!";
150 # note: NOT $self->{sock}, we want our close (+ Danga::Socket::close),
151 # to do proper cleanup:
152 $env->{'psgix.io'} = $self; # only for ->close
153 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
155 if (ref($res) eq 'CODE') {
156 $res->(sub { response_write($self, $env, $_[0]) });
158 response_write($self, $env, $res);
164 sub response_header_write {
165 my ($self, $env, $res) = @_;
166 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
167 my $status = $res->[0];
168 my $h = "$proto $status " . status_message($status) . "\r\n";
170 my $headers = $res->[1];
172 for (my $i = 0; $i < @$headers; $i += 2) {
173 my $k = $headers->[$i];
174 my $v = $headers->[$i + 1];
175 next if $k =~ /\A(?:Connection|Date)\z/i;
177 $len = $v if $k =~ /\AContent-Length\z/i;
178 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
184 my $conn = $env->{HTTP_CONNECTION} || '';
185 my $term = defined($len) || $chunked;
186 my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
188 if (!$term && $prot_persist) { # auto-chunk
189 $chunked = $alive = 2;
190 $h .= "Transfer-Encoding: chunked\r\n";
191 # no need for "Connection: keep-alive" with HTTP/1.1
192 } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
194 $h .= "Connection: keep-alive\r\n";
197 $h .= "Connection: close\r\n";
199 $h .= 'Date: ' . http_date() . "\r\n\r\n";
201 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
209 # middlewares such as Deflater may write empty strings
210 sub chunked_wcb ($) {
213 return if $_[0] eq '';
214 more($self, sprintf("%x\r\n", bytes::length($_[0])));
217 # use $self->write("\n\n") if you care about real-time
218 # streaming responses, public-inbox WWW does not.
223 sub identity_wcb ($) {
225 sub { $self->write(\($_[0])) if $_[0] ne '' }
228 sub next_request ($) {
230 $self->watch_write(0);
231 if ($self->{rbuf} eq '') { # wait for next request
232 $self->watch_read(1);
233 } else { # avoid recursion for pipelined requests
234 push @$pipelineq, $self;
235 $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
239 sub response_done_cb ($$) {
240 my ($self, $alive) = @_;
242 my $env = $self->{env};
243 $self->{env} = undef;
244 $self->write("0\r\n\r\n") if $alive == 2;
245 $self->write(sub{$alive ? next_request($self) : $self->close});
249 sub getline_cb ($$$) {
250 my ($self, $write, $close) = @_;
252 my $forward = $self->{forward};
253 # limit our own running time for fairness with other
254 # clients and to avoid buffering too much:
256 my $buf = eval { $forward->getline };
258 $write->($buf); # may close in Danga::Socket::write
259 unless ($self->{closed}) {
260 my $next = $self->{pull};
261 if ($self->{write_buf_size}) {
264 PublicInbox::EvCleanup::asap($next);
269 err($self, "response ->getline error: $@");
275 $self->{forward} = $self->{pull} = undef;
278 eval { $forward->close };
280 err($self, "response ->close error: $@");
281 $self->close; # idempotent
287 sub getline_response ($$$) {
288 my ($self, $write, $close) = @_;
289 my $pull = $self->{pull} = sub { getline_cb($self, $write, $close) };
294 my ($self, $env, $res) = @_;
295 my $alive = response_header_write($self, $env, $res);
296 my $close = response_done_cb($self, $alive);
297 my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
298 if (defined(my $body = $res->[2])) {
299 if (ref $body eq 'ARRAY') {
300 $write->($_) foreach @$body;
303 $self->{forward} = $body;
304 getline_response($self, $write, $close);
307 # this is returned to the calling application:
308 Plack::Util::inline_object(write => $write, close => $close);
312 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
315 return if $self->{closed};
316 if (MSG_MORE && !$self->{write_buf_size}) {
317 my $n = send($self->{sock}, $_[1], MSG_MORE);
319 my $nlen = length($_[1]) - $n;
320 return 1 if $nlen == 0; # all done!
321 eval { $_[1] = substr($_[1], $n, $nlen) };
322 if ($@) { # modification of read-only value:
323 return $self->write(substr($_[1], $n, $nlen));
325 # fall through to normal write:
332 my ($self, $env) = @_;
334 my $len = $env->{CONTENT_LENGTH};
336 if ($len > $MAX_REQUEST_BUFFER) {
340 open($input, '+>', undef);
341 } elsif (env_chunked($env)) {
343 open($input, '+>', undef);
348 # TODO: expire idle clients on ENFILE / EMFILE
349 return unless $input;
351 $env->{'psgi.input'} = $input;
353 $self->{input_left} = $len || 0;
356 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
359 eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
363 my ($self, $len) = @_;
364 my $msg = $! || '(zero write)';
365 $msg .= " ($len bytes remaining)" if defined $len;
366 err($self, "error buffering to input: $msg");
371 my ($self, $r, $len) = @_;
372 return $self->close if (defined $r && $r == 0);
374 $self->{input_left} = $len;
377 err($self, "error reading for input: $! ($len bytes remaining)");
382 my ($fh, $rbuf, $len) = @_;
386 my $w = syswrite($fh, $$rbuf, $len, $off);
387 return ($rv ? $rv : $w) unless $w; # undef or 0
395 sub event_read_input_chunked { # unlikely...
397 my $input = $self->{env}->{'psgi.input'};
398 my $sock = $self->{sock};
399 my $len = $self->{input_left};
400 $self->{input_left} = undef;
401 my $rbuf = \($self->{rbuf});
403 while (1) { # chunk start
404 if ($len == CHUNK_ZEND) {
405 $$rbuf =~ s/\A\r\n//s and
406 return app_dispatch($self, $input);
407 return quit($self, 400) if length($$rbuf) > 2;
409 if ($len == CHUNK_END) {
410 if ($$rbuf =~ s/\A\r\n//s) {
412 } elsif (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 (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 my $off = length($$rbuf);
430 my $r = sysread($sock, $$rbuf, 8192, $off);
431 return recv_err($self, $r, $len) unless $r;
432 # (implicit) goto chunk_start if $r > 0;
434 $len = CHUNK_ZEND if $len == 0;
436 # drain the current chunk
439 my $w = write_in_full($input, $rbuf, $len);
440 return write_err($self, "$len chunk") if !$w;
443 # we may have leftover data to parse
445 $$rbuf = substr($$rbuf, $w);
448 die "BUG: len < 0: $len";
454 # read more of current chunk
455 my $r = sysread($sock, $$rbuf, 8192);
456 return recv_err($self, $r, $len) unless $r;
463 my ($self, $status) = @_;
464 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
469 # callbacks for Danga::Socket
471 sub event_hup { $_[0]->close }
472 sub event_err { $_[0]->close }
476 my $forward = $self->{forward};
477 my $env = $self->{env};
478 delete $env->{'psgix.io'} if $env; # prevent circular references
479 $self->{pull} = $self->{forward} = $self->{env} = undef;
481 eval { $forward->close };
482 err($self, "forward ->close error: $@") if $@;
484 $self->SUPER::close(@_);
487 # for graceful shutdown in PublicInbox::Daemon:
490 ($self->{rbuf} ne '' || $self->{env} || $self->{write_buf_size});