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 = delete $self->{input_left};
122 my $rbuf = \($self->{rbuf});
123 my $input = $env->{'psgi.input'};
127 my $w = write_in_full($input, $rbuf, $len, 0);
128 return write_err($self, $len) unless $w;
130 die "BUG: $len < 0 (w=$w)" if $len < 0;
131 if ($len == 0) { # next request may be pipelined
132 $$rbuf = substr($$rbuf, $w);
137 my $r = sysread($sock, $$rbuf, 8192);
138 return recv_err($self, $r, $len) unless $r;
139 # continue looping if $r > 0;
141 app_dispatch($self, $input);
145 my ($self, $input) = @_;
146 my $env = $self->{env};
147 $env->{REMOTE_ADDR} = $self->{remote_addr};
148 $env->{REMOTE_PORT} = $self->{remote_port};
149 if (my $host = $env->{HTTP_HOST}) {
150 $host =~ s/:([0-9]+)\z// and $env->{SERVER_PORT} = $1;
151 $env->{SERVER_NAME} = $host;
153 if (defined $input) {
154 sysseek($input, 0, SEEK_SET) or
155 die "BUG: psgi.input seek failed: $!";
157 # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
158 # to do proper cleanup:
159 $env->{'psgix.io'} = $self; # only for ->close
160 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
162 if (ref($res) eq 'CODE') {
163 $res->(sub { response_write($self, $env, $_[0]) });
165 response_write($self, $env, $res);
171 sub response_header_write {
172 my ($self, $env, $res) = @_;
173 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
174 my $status = $res->[0];
175 my $h = "$proto $status " . status_message($status) . "\r\n";
177 my $headers = $res->[1];
179 for (my $i = 0; $i < @$headers; $i += 2) {
180 my $k = $headers->[$i];
181 my $v = $headers->[$i + 1];
182 next if $k =~ /\A(?:Connection|Date)\z/i;
184 $len = $v if $k =~ /\AContent-Length\z/i;
185 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
191 my $conn = $env->{HTTP_CONNECTION} || '';
192 my $term = defined($len) || $chunked;
193 my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
195 if (!$term && $prot_persist) { # auto-chunk
196 $chunked = $alive = 2;
197 $h .= "Transfer-Encoding: chunked\r\n";
198 # no need for "Connection: keep-alive" with HTTP/1.1
199 } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
201 $h .= "Connection: keep-alive\r\n";
204 $h .= "Connection: close\r\n";
206 $h .= 'Date: ' . http_date() . "\r\n\r\n";
208 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
216 # middlewares such as Deflater may write empty strings
217 sub chunked_wcb ($) {
220 return if $_[0] eq '';
221 msg_more($self, sprintf("%x\r\n", bytes::length($_[0])));
222 msg_more($self, $_[0]);
224 # use $self->write(\"\n\n") if you care about real-time
225 # streaming responses, public-inbox WWW does not.
226 msg_more($self, "\r\n");
230 sub identity_wcb ($) {
232 sub { $self->write(\($_[0])) if $_[0] ne '' }
235 sub next_request ($) {
237 if ($self->{rbuf} eq '') { # wait for next request
239 } else { # avoid recursion for pipelined requests
240 push @$pipelineq, $self;
241 $pipet ||= PublicInbox::EvCleanup::asap(*process_pipelineq);
245 sub response_done_cb ($$) {
246 my ($self, $alive) = @_;
248 my $env = delete $self->{env};
249 $self->write(\"0\r\n\r\n") if $alive == 2;
250 $self->write(sub{$alive ? next_request($self) : $self->close});
254 sub getline_cb ($$$) {
255 my ($self, $write, $close) = @_;
257 my $forward = $self->{forward};
258 # limit our own running time for fairness with other
259 # clients and to avoid buffering too much:
261 my $buf = eval { $forward->getline };
263 $write->($buf); # may close in PublicInbox::DS::write
265 my $next = $self->{pull};
269 PublicInbox::EvCleanup::asap($next);
274 err($self, "response ->getline error: $@");
280 delete @$self{qw(forward pull)};
283 eval { $forward->close };
285 err($self, "response ->close error: $@");
286 $self->close; # idempotent
292 sub getline_response ($$$) {
293 my ($self, $write, $close) = @_;
294 my $pull = $self->{pull} = sub { getline_cb($self, $write, $close) };
299 my ($self, $env, $res) = @_;
300 my $alive = response_header_write($self, $env, $res);
301 my $close = response_done_cb($self, $alive);
302 my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
303 if (defined(my $body = $res->[2])) {
304 if (ref $body eq 'ARRAY') {
305 $write->($_) foreach @$body;
308 $self->{forward} = $body;
309 getline_response($self, $write, $close);
312 # this is returned to the calling application:
313 Plack::Util::inline_object(write => $write, close => $close);
318 my ($self, $env) = @_;
320 my $len = $env->{CONTENT_LENGTH};
322 if ($len > $MAX_REQUEST_BUFFER) {
326 open($input, '+>', undef);
327 } elsif (env_chunked($env)) {
329 open($input, '+>', undef);
334 # TODO: expire idle clients on ENFILE / EMFILE
335 return unless $input;
337 $env->{'psgi.input'} = $input;
339 $self->{input_left} = $len || 0;
342 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
345 eval { $_[0]->{httpd}->{env}->{'psgi.errors'}->print($_[1]."\n") };
349 my ($self, $len) = @_;
350 my $msg = $! || '(zero write)';
351 $msg .= " ($len bytes remaining)" if defined $len;
352 err($self, "error buffering to input: $msg");
357 my ($self, $r, $len) = @_;
358 return $self->close if (defined $r && $r == 0);
360 $self->{input_left} = $len;
361 return $self->watch_in1;
363 err($self, "error reading for input: $! ($len bytes remaining)");
367 sub read_input_chunked { # unlikely...
369 my $input = $self->{env}->{'psgi.input'};
370 my $sock = $self->{sock};
371 my $len = delete $self->{input_left};
372 my $rbuf = \($self->{rbuf});
374 while (1) { # chunk start
375 if ($len == CHUNK_ZEND) {
376 $$rbuf =~ s/\A\r\n//s and
377 return app_dispatch($self, $input);
378 return quit($self, 400) if length($$rbuf) > 2;
380 if ($len == CHUNK_END) {
381 if ($$rbuf =~ s/\A\r\n//s) {
383 } elsif (length($$rbuf) > 2) {
384 return quit($self, 400);
387 if ($len == CHUNK_START) {
388 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
390 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
391 return quit($self, 413);
393 } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
394 return quit($self, 400);
396 # will break from loop since $len >= 0
399 if ($len < 0) { # chunk header is trickled, read more
400 my $off = length($$rbuf);
401 my $r = sysread($sock, $$rbuf, 8192, $off);
402 return recv_err($self, $r, $len) unless $r;
403 # (implicit) goto chunk_start if $r > 0;
405 $len = CHUNK_ZEND if $len == 0;
407 # drain the current chunk
410 my $w = write_in_full($input, $rbuf, $len, 0);
411 return write_err($self, "$len chunk") if !$w;
414 # we may have leftover data to parse
416 $$rbuf = substr($$rbuf, $w);
419 die "BUG: len < 0: $len";
425 # read more of current chunk
426 my $r = sysread($sock, $$rbuf, 8192);
427 return recv_err($self, $r, $len) unless $r;
434 my ($self, $status) = @_;
435 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
442 if (my $env = delete $self->{env}) {
443 delete $env->{'psgix.io'}; # prevent circular references
445 delete $self->{pull};
446 if (my $forward = delete $self->{forward}) {
447 eval { $forward->close };
448 err($self, "forward ->close error: $@") if $@;
450 $self->SUPER::close(@_);
453 # for graceful shutdown in PublicInbox::Daemon:
456 ($self->{rbuf} ne '' || $self->{env} || $self->{wbuf});