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);
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;
184 (($proto eq 'HTTP/1.1' && $conn !~ /\bclose\b/i) ||
185 ($conn =~ /\bkeep-alive\b/i));
187 $h .= 'Connection: ' . ($alive ? 'keep-alive' : 'close');
188 $h .= "\r\nDate: " . http_date() . "\r\n\r\n";
190 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
199 my ($self, $env, $res) = @_;
200 my $alive = response_header_write($self, $env, $res);
202 # middlewares such as Deflater may write empty strings
203 my $write = sub { $self->write(\($_[0])) if $_[0] ne '' };
206 $self->event_write; # watch for readability if done
208 Danga::Socket::write($self, sub { $self->close });
210 if (my $obj = $env->{'pi-httpd.inbox'}) {
211 # grace period for reaping resources
212 $WEAKEN->{"$obj"} = $obj;
213 $WEAKTIMER ||= Danga::Socket->AddTimer(60, *weaken_task);
215 $self->{env} = undef;
218 if (defined(my $body = $res->[2])) {
219 if (ref $body eq 'ARRAY') {
220 $write->($_) foreach @$body;
222 } elsif ($body->can('async_pass')) { # HTTPD::Async
223 # prevent us from reading the body faster than we
224 # can write to the client
225 my $restart_read = sub { $body->watch_read(1) };
226 $body->async_pass(sub {
228 my $buf = $body->getline;
231 if ($self->{write_buf_size}) {
232 $body->watch_read(0);
233 $self->write($restart_read);
235 return; # continue waiting
244 while (defined(my $buf = $body->getline)) {
246 if ($self->{write_buf_size}) {
258 # this is returned to the calling application:
259 Plack::Util::inline_object(write => $write, close => $close);
263 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
266 if (MSG_MORE && !$self->{write_buf_size}) {
267 my $n = send($self->{sock}, $_[1], MSG_MORE);
269 my $dlen = length($_[1]);
270 return 1 if $n == $dlen; # all done!
271 $_[1] = substr($_[1], $n, $dlen - $n);
272 # fall through to normal write:
280 sub process_pipelineq () {
284 rbuf_process($_) foreach @$q;
287 # overrides existing Danga::Socket method
290 # only continue watching for readability when we are done writing:
291 return if $self->write(undef) != 1;
293 if ($self->{rbuf} eq '') { # wait for next request
294 $self->watch_read(1);
295 } else { # avoid recursion for pipelined requests
296 push @$pipelineq, $self;
297 $next_tick ||= Danga::Socket->AddTimer(0, *process_pipelineq);
302 my ($self, $env) = @_;
303 my $input = $null_io;
304 my $len = $env->{CONTENT_LENGTH};
306 if ($len > $MAX_REQUEST_BUFFER) {
310 $input = IO::File->new_tmpfile;
311 } elsif (env_chunked($env)) {
313 $input = IO::File->new_tmpfile;
316 # TODO: expire idle clients on ENFILE / EMFILE
317 return unless $input;
319 $env->{'psgi.input'} = $input;
321 $self->{input_left} = $len || 0;
324 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
328 my $err = $self->{httpd}->{env}->{'psgi.errors'};
329 my $msg = $! || '(zero write)';
330 $err->print("error buffering to input: $msg\n");
335 my ($self, $r, $len) = @_;
336 return $self->close if (defined $r && $r == 0);
338 $self->{input_left} = $len;
341 my $err = $self->{httpd}->{env}->{'psgi.errors'};
342 $err->print("error reading for input: $! ($len bytes remaining)\n");
347 my ($fh, $rbuf, $len) = @_;
351 my $w = syswrite($fh, $$rbuf, $len, $off);
352 return ($rv ? $rv : $w) unless $w; # undef or 0
360 sub event_read_input_chunked { # unlikely...
362 my $input = $self->{env}->{'psgi.input'};
363 my $sock = $self->{sock};
364 my $len = $self->{input_left};
365 $self->{input_left} = undef;
366 my $rbuf = \($self->{rbuf});
368 while (1) { # chunk start
369 if ($len == CHUNK_ZEND) {
370 $$rbuf =~ s/\A\r\n//s and
371 return app_dispatch($self, $input);
372 return quit($self, 400) if length($$rbuf) > 2;
374 if ($len == CHUNK_END) {
375 if ($$rbuf =~ s/\A\r\n//s) {
377 } elsif (length($$rbuf) > 2) {
378 return quit($self, 400);
381 if ($len == CHUNK_START) {
382 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
384 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
385 return quit($self, 413);
387 } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
388 return quit($self, 400);
390 # will break from loop since $len >= 0
393 if ($len < 0) { # chunk header is trickled, read more
394 my $off = length($$rbuf);
395 my $r = sysread($sock, $$rbuf, 8192, $off);
396 return recv_err($self, $r, $len) unless $r;
397 # (implicit) goto chunk_start if $r > 0;
399 $len = CHUNK_ZEND if $len == 0;
401 # drain the current chunk
404 my $w = write_in_full($input, $rbuf, $len);
405 return write_err($self) unless $w;
408 # we may have leftover data to parse
410 $$rbuf = substr($$rbuf, $w);
413 die "BUG: len < 0: $len";
419 # read more of current chunk
420 my $r = sysread($sock, $$rbuf, 8192);
421 return recv_err($self, $r, $len) unless $r;
428 my ($self, $status) = @_;
429 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
434 # callbacks for Danga::Socket
436 sub event_hup { $_[0]->close }
437 sub event_err { $_[0]->close }
441 $self->{env} = undef;
442 $self->SUPER::close(@_);
445 # for graceful shutdown in PublicInbox::Daemon:
448 ($self->{rbuf} ne '' || $self->{env} || $self->{write_buf_size});