1 # Copyright (C) 2016 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 public-inbox-specific, 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);
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
27 # FIXME: duplicated code with NNTP.pm
28 my $WEAKEN = {}; # string(inbox) -> inbox
32 $_->weaken_all for values %$WEAKEN;
36 # Use the same configuration parameter as git since this is primarily
37 # a slow-client sponge for git-http-backend
38 # TODO: support per-respository http.maxRequestBuffer somehow...
39 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
42 my $null_io = IO::File->new('/dev/null', '<');
47 $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
51 my ($class, $sock, $addr, $httpd) = @_;
52 my $self = fields::new($class);
53 $self->SUPER::new($sock);
54 $self->{httpd} = $httpd;
56 ($self->{remote_addr}, $self->{remote_port}) =
57 PublicInbox::Daemon::host_with_port($addr);
62 sub event_read { # called by Danga::Socket
65 return event_read_input($self) if defined $self->{env};
67 my $off = length($self->{rbuf});
68 my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
70 return $self->close if $r == 0;
71 return rbuf_process($self);
73 return if $!{EAGAIN}; # no need to call watch_read(1) again
75 # common for clients to break connections without warning,
76 # would be too noisy to log here:
83 my %env = %{$self->{httpd}->{env}}; # full hash copy
84 my $r = parse_http_request($self->{rbuf}, \%env);
86 # We do not support Trailers in chunked requests, for now
87 # (they are rarely-used and git (as of 2.7.2) does not use them)
88 if ($r == -1 || $env{HTTP_TRAILER} ||
89 # this length-check is necessary for PURE_PERL=1:
90 ($r == -2 && length($self->{rbuf}) > 0x4000)) {
91 return quit($self, 400);
93 return $self->watch_read(1) if $r < 0; # incomplete
94 $self->{rbuf} = substr($self->{rbuf}, $r);
96 my $len = input_prepare($self, \%env);
97 defined $len or return write_err($self); # EMFILE/ENFILE
99 $len ? event_read_input($self) : app_dispatch($self);
102 sub event_read_input ($) {
104 my $env = $self->{env};
105 return event_read_input_chunked($self) if env_chunked($env);
107 # env->{CONTENT_LENGTH} (identity)
108 my $sock = $self->{sock};
109 my $len = $self->{input_left};
110 $self->{input_left} = undef;
111 my $rbuf = \($self->{rbuf});
112 my $input = $env->{'psgi.input'};
116 my $w = write_in_full($input, $rbuf, $len);
117 return write_err($self) unless $w;
119 die "BUG: $len < 0 (w=$w)" if $len < 0;
120 if ($len == 0) { # next request may be pipelined
121 $$rbuf = substr($$rbuf, $w);
126 my $r = sysread($sock, $$rbuf, 8192);
127 return recv_err($self, $r, $len) unless $r;
128 # continue looping if $r > 0;
130 app_dispatch($self, $input);
134 my ($self, $input) = @_;
135 $self->watch_read(0);
136 my $env = $self->{env};
137 $env->{REMOTE_ADDR} = $self->{remote_addr};
138 $env->{REMOTE_PORT} = $self->{remote_port};
139 if (my $host = $env->{HTTP_HOST}) {
140 $host =~ s/:(\d+)\z// and $env->{SERVER_PORT} = $1;
141 $env->{SERVER_NAME} = $host;
143 if (defined $input) {
144 sysseek($input, 0, SEEK_SET) or
145 die "BUG: psgi.input seek failed: $!";
147 # note: NOT $self->{sock}, we want our close (+ Danga::Socket::close),
148 # to do proper cleanup:
149 $env->{'psgix.io'} = $self; # only for ->close
150 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
152 if (ref($res) eq 'CODE') {
153 $res->(sub { response_write($self, $env, $_[0]) });
155 response_write($self, $env, $res);
161 sub response_header_write {
162 my ($self, $env, $res) = @_;
163 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
164 my $status = $res->[0];
165 my $h = "$proto $status " . status_message($status) . "\r\n";
167 my $headers = $res->[1];
169 for (my $i = 0; $i < @$headers; $i += 2) {
170 my $k = $headers->[$i];
171 my $v = $headers->[$i + 1];
172 next if $k =~ /\A(?:Connection|Date)\z/i;
174 $len = $v if $k =~ /\AContent-Length\z/i;
175 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
181 my $conn = $env->{HTTP_CONNECTION} || '';
182 my $term = defined($len) || $chunked;
183 my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
185 if (!$term && $prot_persist) { # auto-chunk
186 $chunked = $alive = 2;
187 $h .= "Transfer-Encoding: chunked\r\n";
188 # no need for "Connection: keep-alive" with HTTP/1.1
189 } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
191 $h .= "Connection: keep-alive\r\n";
193 $h .= "Connection: close\r\n";
195 $h .= 'Date: ' . http_date() . "\r\n\r\n";
197 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
205 # middlewares such as Deflater may write empty strings
206 sub chunked_wcb ($) {
209 return if $_[0] eq '';
210 more($self, sprintf("%x\r\n", bytes::length($_[0])));
212 $self->write("\r\n");
216 sub identity_wcb ($) {
218 sub { $self->write(\($_[0])) if $_[0] ne '' }
222 my ($self, $env, $res) = @_;
223 my $alive = response_header_write($self, $env, $res);
225 my $write = $alive == 2 ? chunked_wcb($self) : identity_wcb($self);
227 $self->write("0\r\n\r\n") if $alive == 2;
229 $self->event_write; # watch for readability if done
231 Danga::Socket::write($self, sub { $self->close });
233 if (my $obj = $env->{'pi-httpd.inbox'}) {
234 # grace period for reaping resources
235 $WEAKEN->{"$obj"} = $obj;
236 $WEAKTIMER ||= Danga::Socket->AddTimer(60, *weaken_task);
238 $self->{env} = undef;
241 if (defined(my $body = $res->[2])) {
242 if (ref $body eq 'ARRAY') {
243 $write->($_) foreach @$body;
249 while (defined(my $buf = $body->getline)) {
251 if ($self->{write_buf_size}) {
263 # this is returned to the calling application:
264 Plack::Util::inline_object(write => $write, close => $close);
268 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
271 if (MSG_MORE && !$self->{write_buf_size}) {
272 my $n = send($self->{sock}, $_[1], MSG_MORE);
274 my $dlen = length($_[1]);
275 return 1 if $n == $dlen; # all done!
276 $_[1] = substr($_[1], $n, $dlen - $n);
277 # fall through to normal write:
285 sub process_pipelineq () {
289 rbuf_process($_) foreach @$q;
292 # overrides existing Danga::Socket method
295 # only continue watching for readability when we are done writing:
296 return if $self->write(undef) != 1;
298 if ($self->{rbuf} eq '') { # wait for next request
299 $self->watch_read(1);
300 } else { # avoid recursion for pipelined requests
301 push @$pipelineq, $self;
302 $next_tick ||= Danga::Socket->AddTimer(0, *process_pipelineq);
307 my ($self, $env) = @_;
308 my $input = $null_io;
309 my $len = $env->{CONTENT_LENGTH};
311 if ($len > $MAX_REQUEST_BUFFER) {
315 $input = IO::File->new_tmpfile;
316 } elsif (env_chunked($env)) {
318 $input = IO::File->new_tmpfile;
321 # TODO: expire idle clients on ENFILE / EMFILE
322 return unless $input;
324 $env->{'psgi.input'} = $input;
326 $self->{input_left} = $len || 0;
329 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
333 my $err = $self->{httpd}->{env}->{'psgi.errors'};
334 my $msg = $! || '(zero write)';
335 $err->print("error buffering to input: $msg\n");
340 my ($self, $r, $len) = @_;
341 return $self->close if (defined $r && $r == 0);
343 $self->{input_left} = $len;
346 my $err = $self->{httpd}->{env}->{'psgi.errors'};
347 $err->print("error reading for input: $! ($len bytes remaining)\n");
352 my ($fh, $rbuf, $len) = @_;
356 my $w = syswrite($fh, $$rbuf, $len, $off);
357 return ($rv ? $rv : $w) unless $w; # undef or 0
365 sub event_read_input_chunked { # unlikely...
367 my $input = $self->{env}->{'psgi.input'};
368 my $sock = $self->{sock};
369 my $len = $self->{input_left};
370 $self->{input_left} = undef;
371 my $rbuf = \($self->{rbuf});
373 while (1) { # chunk start
374 if ($len == CHUNK_ZEND) {
375 $$rbuf =~ s/\A\r\n//s and
376 return app_dispatch($self, $input);
377 return quit($self, 400) if length($$rbuf) > 2;
379 if ($len == CHUNK_END) {
380 if ($$rbuf =~ s/\A\r\n//s) {
382 } elsif (length($$rbuf) > 2) {
383 return quit($self, 400);
386 if ($len == CHUNK_START) {
387 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
389 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
390 return quit($self, 413);
392 } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
393 return quit($self, 400);
395 # will break from loop since $len >= 0
398 if ($len < 0) { # chunk header is trickled, read more
399 my $off = length($$rbuf);
400 my $r = sysread($sock, $$rbuf, 8192, $off);
401 return recv_err($self, $r, $len) unless $r;
402 # (implicit) goto chunk_start if $r > 0;
404 $len = CHUNK_ZEND if $len == 0;
406 # drain the current chunk
409 my $w = write_in_full($input, $rbuf, $len);
410 return write_err($self) unless $w;
413 # we may have leftover data to parse
415 $$rbuf = substr($$rbuf, $w);
418 die "BUG: len < 0: $len";
424 # read more of current chunk
425 my $r = sysread($sock, $$rbuf, 8192);
426 return recv_err($self, $r, $len) unless $r;
433 my ($self, $status) = @_;
434 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
439 # callbacks for Danga::Socket
441 sub event_hup { $_[0]->close }
442 sub event_err { $_[0]->close }
446 my $forward = $self->{forward};
447 $forward->close if $forward;
448 $self->{forward} = $self->{env} = undef;
449 $self->SUPER::close(@_);
452 # for graceful shutdown in PublicInbox::Daemon:
455 ($self->{rbuf} ne '' || $self->{env} || $self->{write_buf_size});