]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/HTTP.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / HTTP.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
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
9 #
10 # fields:
11 # httpd: PublicInbox::HTTPD ref
12 # env: PSGI env hashref
13 # input_left: bytes left to read in request body (e.g. POST/PUT)
14 # remote_addr: remote IP address as a string (e.g. "127.0.0.1")
15 # remote_port: peer port
16 # forward: response body object, response to ->getline + ->close
17 # alive: HTTP keepalive state:
18 #       0: drop connection when done
19 #       1: keep connection when done
20 #       2: keep connection, chunk responses
21 package PublicInbox::HTTP;
22 use strict;
23 use parent qw(PublicInbox::DS);
24 use Fcntl qw(:seek);
25 use Plack::HTTPParser qw(parse_http_request); # XS or pure Perl
26 use Plack::Util;
27 use HTTP::Status qw(status_message);
28 use HTTP::Date qw(time2str);
29 use PublicInbox::DS qw(msg_more);
30 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
31 use PublicInbox::Tmpfile;
32 use constant {
33         CHUNK_START => -1,   # [a-f0-9]+\r\n
34         CHUNK_END => -2,     # \r\n
35         CHUNK_ZEND => -3,    # \r\n
36         CHUNK_MAX_HDR => 256,
37 };
38 use Errno qw(EAGAIN);
39
40 # Use the same configuration parameter as git since this is primarily
41 # a slow-client sponge for git-http-backend
42 # TODO: support per-respository http.maxRequestBuffer somehow...
43 our $MAX_REQUEST_BUFFER = $ENV{GIT_HTTP_MAX_REQUEST_BUFFER} ||
44                         (10 * 1024 * 1024);
45
46 open(my $null_io, '<', '/dev/null') or die "open /dev/null: $!";
47 {
48         my @n = stat($null_io) or die "stat(/dev/null): $!";
49         my @i = stat(STDIN) or die "stat(STDIN): $!";
50         $null_io = *STDIN{IO} if "@n[0, 1]" eq "@i[0, 1]";
51 }
52
53 my $http_date;
54 my $prev = 0;
55 sub http_date () {
56         my $now = time;
57         $now == $prev ? $http_date : ($http_date = time2str($prev = $now));
58 }
59
60 sub new ($$$) {
61         my ($class, $sock, $addr, $srv_env) = @_;
62         my $self = bless { srv_env => $srv_env }, $class;
63         my $ev = EPOLLIN;
64         my $wbuf;
65         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
66                 return CORE::close($sock) if $! != EAGAIN;
67                 $ev = PublicInbox::TLS::epollbit() or return CORE::close($sock);
68                 $wbuf = [ \&PublicInbox::DS::accept_tls_step ];
69         }
70         $self->{wbuf} = $wbuf if $wbuf;
71         ($self->{remote_addr}, $self->{remote_port}) =
72                 PublicInbox::Daemon::host_with_port($addr);
73         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
74 }
75
76 sub event_step { # called by PublicInbox::DS
77         my ($self) = @_;
78         local $SIG{__WARN__} = $self->{srv_env}->{'pi-httpd.warn_cb'};
79         return unless $self->flush_write && $self->{sock};
80
81         # only read more requests if we've drained the write buffer,
82         # otherwise we can be buffering infinitely w/o backpressure
83
84         return read_input($self) if ref($self->{env});
85
86         my $rbuf = $self->{rbuf} // (\(my $x = ''));
87         my %env = %{$self->{srv_env}}; # full hash copy
88         my $r;
89         while (($r = parse_http_request($$rbuf, \%env)) < 0) {
90                 # We do not support Trailers in chunked requests, for
91                 # now (they are rarely-used and git (as of 2.7.2) does
92                 # not use them).
93                 # this length-check is necessary for PURE_PERL=1:
94                 if ($r == -1 || $env{HTTP_TRAILER} ||
95                                 ($r == -2 && length($$rbuf) > 0x4000)) {
96                         return quit($self, 400);
97                 }
98                 $self->do_read($rbuf, 8192, length($$rbuf)) or return;
99         }
100         return quit($self, 400) if grep(/\s/, keys %env); # stop smugglers
101         $$rbuf = substr($$rbuf, $r);
102         my $len = input_prepare($self, \%env) //
103                 return write_err($self, undef); # EMFILE/ENFILE
104
105         $len ? read_input($self, $rbuf) : app_dispatch($self, undef, $rbuf);
106 }
107
108 sub read_input ($;$) {
109         my ($self, $rbuf) = @_;
110         $rbuf //= $self->{rbuf} // (\(my $x = ''));
111         my $env = $self->{env};
112         return read_input_chunked($self, $rbuf) if env_chunked($env);
113
114         # env->{CONTENT_LENGTH} (identity)
115         my $len = delete $self->{input_left};
116         my $input = $env->{'psgi.input'};
117
118         while ($len > 0) {
119                 if ($$rbuf ne '') {
120                         my $w = syswrite($input, $$rbuf, $len);
121                         return write_err($self, $len) unless $w;
122                         $len -= $w;
123                         die "BUG: $len < 0 (w=$w)" if $len < 0;
124                         if ($len == 0) { # next request may be pipelined
125                                 $$rbuf = substr($$rbuf, $w);
126                                 last;
127                         }
128                         $$rbuf = '';
129                 }
130                 $self->do_read($rbuf, 8192) or return recv_err($self, $len);
131                 # continue looping if $r > 0;
132         }
133         app_dispatch($self, $input, $rbuf);
134 }
135
136 sub app_dispatch {
137         my ($self, $input, $rbuf) = @_;
138         $self->rbuf_idle($rbuf);
139         my $env = $self->{env};
140         $self->{env} = undef; # for exists() check in ->busy
141         $env->{REMOTE_ADDR} = $self->{remote_addr};
142         $env->{REMOTE_PORT} = $self->{remote_port};
143         if (defined(my $host = $env->{HTTP_HOST})) {
144                 $host =~ s/:([0-9]+)\z// and $env->{SERVER_PORT} = $1 + 0;
145                 $env->{SERVER_NAME} = $host;
146         }
147         if (defined $input) {
148                 sysseek($input, 0, SEEK_SET) or
149                         die "BUG: psgi.input seek failed: $!";
150         }
151         # note: NOT $self->{sock}, we want our close (+ PublicInbox::DS::close),
152         # to do proper cleanup:
153         $env->{'psgix.io'} = $self; # for ->close or async_pass
154         my $res = Plack::Util::run_app($env->{'pi-httpd.app'}, $env);
155         eval {
156                 if (ref($res) eq 'CODE') {
157                         $res->(sub { response_write($self, $env, $_[0]) });
158                 } else {
159                         response_write($self, $env, $res);
160                 }
161         };
162         if ($@) {
163                 warn "response_write error: $@";
164                 $self->close;
165         }
166 }
167
168 sub response_header_write {
169         my ($self, $env, $res) = @_;
170         my $proto = $env->{SERVER_PROTOCOL} or return; # HTTP/0.9 :P
171         my $status = $res->[0];
172         my $h = "$proto $status " . status_message($status) . "\r\n";
173         my ($len, $chunked);
174         my $headers = $res->[1];
175
176         for (my $i = 0; $i < @$headers; $i += 2) {
177                 my $k = $headers->[$i];
178                 my $v = $headers->[$i + 1];
179                 next if $k =~ /\A(?:Connection|Date)\z/i;
180
181                 $len = $v if $k =~ /\AContent-Length\z/i;
182                 if ($k =~ /\ATransfer-Encoding\z/i && $v =~ /\bchunked\b/i) {
183                         $chunked = 1;
184                 }
185                 $h .= "$k: $v\r\n";
186         }
187
188         my $conn = $env->{HTTP_CONNECTION} || '';
189         my $term = defined($len) || $chunked;
190         my $prot_persist = ($proto eq 'HTTP/1.1') && ($conn !~ /\bclose\b/i);
191         my $alive;
192         if (!$term && $prot_persist) { # auto-chunk
193                 $chunked = $alive = 2;
194                 $alive = 3 if $env->{REQUEST_METHOD} eq 'HEAD';
195                 $h .= "Transfer-Encoding: chunked\r\n";
196                 # no need for "Connection: keep-alive" with HTTP/1.1
197         } elsif ($term && ($prot_persist || ($conn =~ /\bkeep-alive\b/i))) {
198                 $alive = 1;
199                 $h .= "Connection: keep-alive\r\n";
200         } else {
201                 $alive = 0;
202                 $h .= "Connection: close\r\n";
203         }
204         $h .= 'Date: ' . http_date() . "\r\n\r\n";
205
206         if (($len || $chunked) && $env->{REQUEST_METHOD} ne 'HEAD') {
207                 msg_more($self, $h);
208         } else {
209                 $self->write(\$h);
210         }
211         $alive;
212 }
213
214 # middlewares such as Deflater may write empty strings
215 sub chunked_write ($$) {
216         my $self = $_[0];
217         return if $_[1] eq '';
218         msg_more($self, sprintf("%x\r\n", length($_[1])));
219         msg_more($self, $_[1]);
220
221         # use $self->write(\"\n\n") if you care about real-time
222         # streaming responses, public-inbox WWW does not.
223         msg_more($self, "\r\n");
224 }
225
226 sub identity_write ($$) {
227         my $self = $_[0];
228         $self->write(\($_[1])) if $_[1] ne '';
229 }
230
231 sub response_done {
232         my ($self, $alive) = @_;
233         delete $self->{env}; # we're no longer busy
234         # HEAD requests set $alive = 3 so we don't send "0\r\n\r\n";
235         $self->write(\"0\r\n\r\n") if $alive == 2;
236         $self->write($alive ? $self->can('requeue') : \&close);
237 }
238
239 sub getline_pull {
240         my ($self) = @_;
241         my $forward = $self->{forward};
242
243         # limit our own running time for fairness with other
244         # clients and to avoid buffering too much:
245         my $buf = eval {
246                 local $/ = \65536;
247                 $forward->getline;
248         } if $forward;
249
250         if (defined $buf) {
251                 # may close in PublicInbox::DS::write
252                 if ($self->{alive} == 2) {
253                         chunked_write($self, $buf);
254                 } else {
255                         identity_write($self, $buf);
256                 }
257
258                 if ($self->{sock}) {
259                         # autovivify wbuf
260                         my $new_size = push(@{$self->{wbuf}}, \&getline_pull);
261
262                         # wbuf may be populated by {chunked,identity}_write()
263                         # above, no need to rearm if so:
264                         $self->requeue if $new_size == 1;
265                         return; # likely
266                 }
267         } elsif ($@) {
268                 warn "response ->getline error: $@";
269                 $self->close;
270         }
271         # avoid recursion
272         if (delete $self->{forward}) {
273                 eval { $forward->close };
274                 if ($@) {
275                         warn "response ->close error: $@";
276                         $self->close; # idempotent
277                 }
278         }
279         response_done($self, delete $self->{alive});
280 }
281
282 sub response_write {
283         my ($self, $env, $res) = @_;
284         my $alive = response_header_write($self, $env, $res);
285         if (defined(my $body = $res->[2])) {
286                 if (ref $body eq 'ARRAY') {
287                         if ($alive == 2) {
288                                 chunked_write($self, $_) for @$body;
289                         } else {
290                                 identity_write($self, $_) for @$body;
291                         }
292                         response_done($self, $alive);
293                 } else {
294                         $self->{forward} = $body;
295                         $self->{alive} = $alive;
296                         getline_pull($self); # kick-off!
297                 }
298         # these are returned to the calling application:
299         } elsif ($alive >= 2) {
300                 bless [ $self, $alive ], 'PublicInbox::HTTP::Chunked';
301         } else {
302                 bless [ $self, $alive ], 'PublicInbox::HTTP::Identity';
303         }
304 }
305
306 sub input_prepare {
307         my ($self, $env) = @_;
308         my ($input, $len);
309
310         # rfc 7230 3.3.2, 3.3.3,: favor Transfer-Encoding over Content-Length
311         my $hte = $env->{HTTP_TRANSFER_ENCODING};
312         if (defined $hte) {
313                 # rfc7230 3.3.3, point 3 says only chunked is accepted
314                 # as the final encoding.  Since neither public-inbox-httpd,
315                 # git-http-backend, or our WWW-related code uses "gzip",
316                 # "deflate" or "compress" as the Transfer-Encoding, we'll
317                 # reject them:
318                 return quit($self, 400) if $hte !~ /\Achunked\z/i;
319
320                 $len = CHUNK_START;
321                 $input = tmpfile('http.input', $self->{sock});
322         } else {
323                 $len = $env->{CONTENT_LENGTH};
324                 if (defined $len) {
325                         # rfc7230 3.3.3.4
326                         return quit($self, 400) if $len !~ /\A[0-9]+\z/;
327                         return quit($self, 413) if $len > $MAX_REQUEST_BUFFER;
328                         $input = $len ? tmpfile('http.input', $self->{sock})
329                                 : $null_io;
330                 } else {
331                         $input = $null_io;
332                 }
333         }
334
335         # TODO: expire idle clients on ENFILE / EMFILE
336         $env->{'psgi.input'} = $input // return;
337         $self->{env} = $env;
338         $self->{input_left} = $len || 0;
339 }
340
341 sub env_chunked { ($_[0]->{HTTP_TRANSFER_ENCODING} // '') =~ /\Achunked\z/i }
342
343 sub write_err {
344         my ($self, $len) = @_;
345         my $msg = $! || '(zero write)';
346         $msg .= " ($len bytes remaining)" if defined $len;
347         warn "error buffering to input: $msg";
348         quit($self, 500);
349 }
350
351 sub recv_err {
352         my ($self, $len) = @_;
353         if ($! == EAGAIN) { # epoll/kevent watch already set by do_read
354                 $self->{input_left} = $len;
355         } else {
356                 warn "error reading input: $! ($len bytes remaining)";
357         }
358 }
359
360 sub read_input_chunked { # unlikely...
361         my ($self, $rbuf) = @_;
362         $rbuf //= $self->{rbuf} // (\(my $x = ''));
363         my $input = $self->{env}->{'psgi.input'};
364         my $len = delete $self->{input_left};
365
366         while (1) { # chunk start
367                 if ($len == CHUNK_ZEND) {
368                         $$rbuf =~ s/\A\r\n//s and
369                                 return app_dispatch($self, $input, $rbuf);
370
371                         return quit($self, 400) if length($$rbuf) > 2;
372                 }
373                 if ($len == CHUNK_END) {
374                         if ($$rbuf =~ s/\A\r\n//s) {
375                                 $len = CHUNK_START;
376                         } elsif (length($$rbuf) > 2) {
377                                 return quit($self, 400);
378                         }
379                 }
380                 if ($len == CHUNK_START) {
381                         if ($$rbuf =~ s/\A([a-f0-9]+).*?\r\n//i) {
382                                 $len = hex $1;
383                                 if (($len + -s $input) > $MAX_REQUEST_BUFFER) {
384                                         return quit($self, 413);
385                                 }
386                         } elsif (length($$rbuf) > CHUNK_MAX_HDR) {
387                                 return quit($self, 400);
388                         }
389                         # will break from loop since $len >= 0
390                 }
391
392                 if ($len < 0) { # chunk header is trickled, read more
393                         $self->do_read($rbuf, 8192, length($$rbuf)) or
394                                 return recv_err($self, $len);
395                         # (implicit) goto chunk_start if $r > 0;
396                 }
397                 $len = CHUNK_ZEND if $len == 0;
398
399                 # drain the current chunk
400                 until ($len <= 0) {
401                         if ($$rbuf ne '') {
402                                 my $w = syswrite($input, $$rbuf, $len);
403                                 return write_err($self, "$len chunk") if !$w;
404                                 $len -= $w;
405                                 if ($len == 0) {
406                                         # we may have leftover data to parse
407                                         # in chunk
408                                         $$rbuf = substr($$rbuf, $w);
409                                         $len = CHUNK_END;
410                                 } elsif ($len < 0) {
411                                         die "BUG: len < 0: $len";
412                                 } else {
413                                         $$rbuf = '';
414                                 }
415                         }
416                         if ($$rbuf eq '') {
417                                 # read more of current chunk
418                                 $self->do_read($rbuf, 8192) or
419                                         return recv_err($self, $len);
420                         }
421                 }
422         }
423 }
424
425 sub quit {
426         my ($self, $status) = @_;
427         my $h = "HTTP/1.1 $status " . status_message($status) . "\r\n\r\n";
428         $self->write(\$h);
429         $self->close;
430         undef; # input_prepare expects this
431 }
432
433 sub close {
434         my $self = $_[0];
435         if (my $forward = delete $self->{forward}) {
436                 eval { $forward->close };
437                 warn "forward ->close error: $@" if $@;
438         }
439         $self->SUPER::close; # PublicInbox::DS::close
440 }
441
442 sub busy { # for graceful shutdown in PublicInbox::Daemon:
443         my ($self) = @_;
444         defined($self->{rbuf}) || exists($self->{env}) || defined($self->{wbuf})
445 }
446
447 # runs $cb on the next iteration of the event loop at earliest
448 sub next_step {
449         my ($self, $cb) = @_;
450         return unless exists $self->{sock};
451         $self->requeue if 1 == push(@{$self->{wbuf}}, $cb);
452 }
453
454 # Chunked and Identity packages are used for writing responses.
455 # They may be exposed to the PSGI application when the PSGI app
456 # returns a CODE ref for "push"-based responses
457 package PublicInbox::HTTP::Chunked;
458 use strict;
459
460 sub write {
461         # ([$http], $buf) = @_;
462         PublicInbox::HTTP::chunked_write($_[0]->[0], $_[1])
463 }
464
465 sub close {
466         # $_[0] = [$http, $alive]
467         PublicInbox::HTTP::response_done(@{$_[0]});
468 }
469
470 package PublicInbox::HTTP::Identity;
471 use strict;
472 our @ISA = qw(PublicInbox::HTTP::Chunked);
473
474 sub write {
475         # ([$http], $buf) = @_;
476         PublicInbox::HTTP::identity_write($_[0]->[0], $_[1]);
477 }
478
479 1;