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 # Use the same configuration parameter as git since this is primarily
28 # a slow-client sponge for git-http-backend
29 # TODO: support per-respository http.maxRequestBuffer somehow...
30 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
33 my $null_io = IO::File->new('/dev/null', '<');
38 $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
42 my ($class, $sock, $addr, $httpd) = @_;
43 my $self = fields::new($class);
44 $self->SUPER::new($sock);
45 $self->{httpd} = $httpd;
47 ($self->{remote_addr}, $self->{remote_port}) =
48 PublicInbox::Daemon::host_with_port($addr);
53 sub event_read { # called by Danga::Socket
56 return event_read_input($self) if defined $self->{env};
58 my $off = length($self->{rbuf});
59 my $r = sysread($self->{sock}, $self->{rbuf}, 8192, $off);
61 return $self->close if $r == 0;
62 return rbuf_process($self);
64 return if $!{EAGAIN}; # no need to call watch_read(1) again
66 # common for clients to break connections without warning,
67 # would be too noisy to log here:
74 my %env = %{$self->{httpd}->{env}}; # full hash copy
75 my $r = parse_http_request($self->{rbuf}, \%env);
77 # We do not support Trailers in chunked requests, for now
78 # (they are rarely-used and git (as of 2.7.2) does not use them)
79 if ($r == -1 || $env{HTTP_TRAILER} ||
80 # this length-check is necessary for PURE_PERL=1:
81 ($r == -2 && length($self->{rbuf}) > 0x4000)) {
82 return quit($self, 400);
84 return $self->watch_read(1) if $r < 0; # incomplete
85 $self->{rbuf} = substr($self->{rbuf}, $r);
87 my $len = input_prepare($self, \%env);
88 defined $len or return write_err($self); # EMFILE/ENFILE
90 $len ? event_read_input($self) : app_dispatch($self);
93 sub event_read_input ($) {
95 my $env = $self->{env};
96 return event_read_input_chunked($self) if env_chunked($env);
98 # env->{CONTENT_LENGTH} (identity)
99 my $sock = $self->{sock};
100 my $len = $self->{input_left};
101 $self->{input_left} = undef;
102 my $rbuf = \($self->{rbuf});
103 my $input = $env->{'psgi.input'};
107 my $w = write_in_full($input, $rbuf, $len);
108 return write_err($self) unless $w;
110 die "BUG: $len < 0 (w=$w)" if $len < 0;
111 if ($len == 0) { # next request may be pipelined
112 $$rbuf = substr($$rbuf, $w);
117 my $r = sysread($sock, $$rbuf, 8192);
118 return recv_err($self, $r, $len) unless $r;
119 # continue looping if $r > 0;
124 sub app_dispatch ($) {
126 $self->watch_read(0);
127 my $env = $self->{env};
128 $env->{REMOTE_ADDR} = $self->{remote_addr};
129 $env->{REMOTE_PORT} = $self->{remote_port};
130 if (my $host = $env->{HTTP_HOST}) {
131 $host =~ s/:(\d+)\z// and $env->{SERVER_PORT} = $1;
132 $env->{SERVER_NAME} = $host;
135 sysseek($env->{'psgi.input'}, 0, SEEK_SET) or
136 die "BUG: psgi.input seek failed: $!";
138 my $res = Plack::Util::run_app($self->{httpd}->{app}, $env);
140 if (ref($res) eq 'CODE') {
141 $res->(sub { response_write($self, $env, $_[0]) });
143 response_write($self, $env, $res);
149 sub response_header_write {
150 my ($self, $env, $res) = @_;
151 my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
152 my $status = $res->[0];
153 my $h = "$proto $status " . status_message($status) . "\r\n";
155 my $headers = $res->[1];
157 for (my $i = 0; $i < @$headers; $i += 2) {
158 my $k = $headers->[$i];
159 my $v = $headers->[$i + 1];
160 next if $k =~ /\A(?:Connection|Date)\z/i;
162 $len = $v if $k =~ /\AContent-Length\z/i;
163 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
170 my $conn = $env->{HTTP_CONNECTION} || '';
171 my $alive = (defined($len) || $chunked) &&
172 ($proto eq 'HTTP/1.1' && $conn !~ /\bclose\b/i) ||
173 ($conn =~ /\bkeep-alive\b/i);
175 $h .= 'Connection: ' . ($alive ? 'keep-alive' : 'close');
176 $h .= "\r\nDate: " . http_date() . "\r\n\r\n";
178 if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
187 my ($self, $env, $res) = @_;
188 my ($alive, $chunked) = response_header_write($self, $env, $res);
189 my $write = sub { $self->write($_[0]) };
192 $self->event_write; # watch for readability if done
194 $self->write(sub { $self->close });
196 $self->{env} = undef;
199 if (defined $res->[2]) {
200 Plack::Util::foreach($res->[2], $write);
203 # this is returned to the calling application:
204 Plack::Util::inline_object(write => $write, close => $close);
208 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
211 if (MSG_MORE && !$self->{write_buf_size}) {
212 my $n = send($self->{sock}, $_[1], MSG_MORE);
214 my $dlen = length($_[1]);
215 return 1 if $n == $dlen; # all done!
216 $_[1] = substr($_[1], $n, $dlen - $n);
217 # fall through to normal write:
223 # overrides existing Danga::Socket method
226 # only continue watching for readability when we are done writing:
227 return if $self->write(undef) != 1;
229 if ($self->{rbuf} eq '') { # wait for next request
230 $self->watch_read(1);
231 } else { # avoid recursion for pipelined requests
232 Danga::Socket->AddTimer(0, sub { rbuf_process($self) });
237 my ($self, $env) = @_;
238 my $input = $null_io;
239 my $len = $env->{CONTENT_LENGTH};
241 if ($len > $MAX_REQUEST_BUFFER) {
245 $input = IO::File->new_tmpfile;
246 } elsif (env_chunked($env)) {
248 $input = IO::File->new_tmpfile;
251 # TODO: expire idle clients on ENFILE / EMFILE
252 return unless $input;
255 $env->{'psgi.input'} = $input;
257 $self->{input_left} = $len || 0;
260 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} || '') =~ /\bchunked\b/i }
264 my $err = $self->{httpd}->{env}->{'psgi.errors'};
265 my $msg = $! || '(zero write)';
266 $err->print("error buffering to input: $msg\n");
271 my ($self, $r, $len) = @_;
272 return $self->close if (defined $r && $r == 0);
274 $self->{input_left} = $len;
277 my $err = $self->{httpd}->{env}->{'psgi.errors'};
278 $err->print("error reading for input: $! ($len bytes remaining)\n");
283 my ($fh, $rbuf, $len) = @_;
287 my $w = syswrite($fh, $$rbuf, $len, $off);
288 return ($rv ? $rv : $w) unless $w; # undef or 0
296 sub event_read_input_chunked { # unlikely...
298 my $input = $self->{env}->{'psgi.input'};
299 my $sock = $self->{sock};
300 my $len = $self->{input_left};
301 $self->{input_left} = undef;
302 my $rbuf = \($self->{rbuf});
304 while (1) { # chunk start
305 if ($len == CHUNK_ZEND) {
306 return app_dispatch($self) if $$rbuf =~ s/\A\r\n//s;
307 return quit($self, 400) if length($$rbuf) > 2;
309 if ($len == CHUNK_END) {
310 if ($$rbuf =~ s/\A\r\n//s) {
312 } elsif (length($$rbuf) > 2) {
313 return quit($self, 400);
316 if ($len == CHUNK_START) {
317 if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
319 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
320 return quit($self, 413);
322 } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
323 return quit($self, 400);
325 # will break from loop since $len >= 0
328 if ($len < 0) { # chunk header is trickled, read more
329 my $off = length($$rbuf);
330 my $r = sysread($sock, $$rbuf, 8192, $off);
331 return recv_err($self, $r, $len) unless $r;
332 # (implicit) goto chunk_start if $r > 0;
334 $len = CHUNK_ZEND if $len == 0;
336 # drain the current chunk
339 my $w = write_in_full($input, $rbuf, $len);
340 return write_err($self) unless $w;
343 # we may have leftover data to parse
345 $$rbuf = substr($$rbuf, $w);
348 die "BUG: len < 0: $len";
354 # read more of current chunk
355 my $r = sysread($sock, $$rbuf, 8192);
356 return recv_err($self, $r, $len) unless $r;
363 my ($self, $status) = @_;
364 my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
369 # callbacks for Danga::Socket
371 sub event_hup { $_[0]->close }
372 sub event_err { $_[0]->close }
374 sub write ($$) : method {
375 my PublicInbox::HTTP $self = $_[0];
376 return 1 if (defined($_[1]) && ref($_[1]) eq '' && $_[1] eq '');
378 $self->SUPER::write($_[1]);
381 # for graceful shutdown in PublicInbox::Daemon:
384 ($self->{rbuf} ne '' || $self->{env} || $self->{write_buf_size});