1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # note: our HTTP server should be standalone and capable of running
4 # generic PSGI/Plack apps.
8 use Time::HiRes qw(gettimeofday tv_interval);
9 use PublicInbox::Spawn qw(which spawn);
10 use PublicInbox::TestCommon;
11 require_mods(qw(Plack::Util Plack::Builder HTTP::Date HTTP::Status));
12 use Digest::SHA qw(sha1_hex);
16 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
18 my ($tmpdir, $for_destroy) = tmpdir();
19 my $fifo = "$tmpdir/fifo";
20 ok(defined mkfifo($fifo, 0777), 'created FIFO');
21 my $err = "$tmpdir/stderr.log";
22 my $out = "$tmpdir/stdout.log";
23 my $psgi = "./t/httpd-corner.psgi";
24 my $sock = tcp_server() or die;
25 my @zmods = qw(PublicInbox::GzipFilter IO::Uncompress::Gunzip);
27 # make sure stdin is not a pipe for lsof test to check for leaking pipes
28 open(STDIN, '<', '/dev/null') or die 'no /dev/null: $!';
30 # Make sure we don't clobber socket options set by systemd or similar
31 # using socket activation:
32 my ($defer_accept_val, $accf_arg, $TCP_DEFER_ACCEPT);
34 $TCP_DEFER_ACCEPT = eval { Socket::TCP_DEFER_ACCEPT() } // 9;
35 setsockopt($sock, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 5) or die;
36 my $x = getsockopt($sock, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
37 defined $x or die "getsockopt: $!";
38 $defer_accept_val = unpack('i', $x);
39 if ($defer_accept_val <= 0) {
40 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
42 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
43 require PublicInbox::Daemon;
44 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
45 $accf_arg = pack('a16a240', 'dataready', '');
46 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
50 my $s = IO::Socket::UNIX->new(
52 Type => Socket::SOCK_STREAM(),
59 my $upath = "$tmpdir/s";
60 my $unix = unix_server($upath);
61 ok($unix, 'UNIX socket created');
63 my $spawn_httpd = sub {
65 my $cmd = [ '-httpd', @args, "--stdout=$out", "--stderr=$err", $psgi ];
66 $td = start_script($cmd, undef, { 3 => $sock, 4 => $unix });
70 if ('test worker death') {
71 my $conn = conn_for($sock, 'killed worker');
72 $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
74 while (defined(my $line = $conn->getline)) {
75 next unless $line eq "\r\n";
76 chomp($pid = $conn->getline);
79 like($pid, qr/\A[0-9]+\z/, '/pid response');
80 is(kill('KILL', $pid), 1, 'killed worker');
81 is($conn->getline, undef, 'worker died and EOF-ed client');
83 $conn = conn_for($sock, 'respawned worker');
84 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
85 ok($conn->read(my $buf, 8192), 'read response');
86 my ($head, $body) = split(/\r\n\r\n/, $buf);
88 like($body, qr/\A[0-9]+\z/, '/pid response');
89 isnt($body, $pid, 'respawned worker');
93 my $conn = conn_for($sock, 'streaming callback');
94 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
95 ok($conn->read(my $buf, 8192), 'read response');
96 my ($head, $body) = split(/\r\n\r\n/, $buf);
97 is($body, "hello world\n", 'callback body matches expected');
101 my $conn = conn_for($sock, 'getline-die');
102 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
103 ok($conn->read(my $buf, 8192), 'read some response');
104 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
105 is($conn->read(my $nil, 8192), 0, 'read EOF');
107 my $after = capture($err);
108 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
109 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
113 my $conn = conn_for($sock, 'close-die');
114 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
115 ok($conn->read(my $buf, 8192), 'read some response');
116 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
117 is($conn->read(my $nil, 8192), 0, 'read EOF');
119 my $after = capture($err);
120 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
121 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
125 my $conn = conn_for($sock, 'excessive header');
126 $SIG{PIPE} = 'IGNORE';
127 $conn->write("GET /callback HTTP/1.0\r\n");
128 foreach my $i (1..500000) {
129 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
131 ok(!$conn->write("\r\n"), 'broken request');
132 ok($conn->read(my $buf, 8192), 'read response');
133 my ($head, $body) = split(/\r\n\r\n/, $buf);
134 like($head, qr/\b400\b/, 'got 400 response');
138 my $conn = conn_for($sock, 'excessive body Content-Length');
139 $SIG{PIPE} = 'IGNORE';
140 my $n = (10 * 1024 * 1024) + 1;
141 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
142 ok($conn->read(my $buf, 8192), 'read response');
143 my ($head, $body) = split(/\r\n\r\n/, $buf);
144 like($head, qr/\b413\b/, 'got 413 response');
148 my $conn = conn_for($sock, 'excessive body chunked');
149 $SIG{PIPE} = 'IGNORE';
150 my $n = (10 * 1024 * 1024) + 1;
151 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
152 $conn->write("\r\n".sprintf("%x\r\n", $n));
153 ok($conn->read(my $buf, 8192), 'read response');
154 my ($head, $body) = split(/\r\n\r\n/, $buf);
155 like($head, qr/\b413\b/, 'got 413 response');
159 my $conn = conn_for($sock, '1.1 Transfer-Encoding bogus');
160 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: bogus\r\n\r\n");
161 $conn->read(my $buf, 4096);
162 like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on bogus TE');
165 my $conn = conn_for($sock, '1.1 Content-Length bogus');
166 $conn->write("PUT /sha1 HTTP/1.1\r\nContent-Length: 3.3\r\n\r\n");
167 $conn->read(my $buf, 4096);
168 like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on bad length');
172 my $req = "PUT /sha1 HTTP/1.1\r\nContent-Length: 3\r\n" .
173 "Content-Length: 3\r\n\r\n";
174 # this is stricter than it needs to be. Due to the way
175 # Plack::HTTPParser, PSGI specs, and how hash tables work in common
176 # languages; it's not possible to tell the difference between folded
177 # and intentionally bad commas (e.g. "Content-Length: 3, 3")
179 require Plack::HTTPParser; # XS or pure Perl
180 require Data::Dumper;
181 Plack::HTTPParser::parse_http_request($req, my $env = {});
182 diag Data::Dumper::Dumper($env); # "Content-Length: 3, 3"
184 my $conn = conn_for($sock, '1.1 Content-Length dupe');
186 $conn->read(my $buf, 4096);
187 like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on dupe length');
191 my $conn = conn_for($sock, 'chunk with pipeline');
193 my $payload = 'b'x$n;
194 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
195 $conn->write("\r\n".sprintf("%x\r\n", $n));
196 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
197 $conn->read(my $buf, 4096);
199 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
200 my $exp = sha1_hex($payload);
201 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
202 'chunk parser can handled pipelined requests');
205 # Unix domain sockets
207 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
208 ok($u, 'unix socket connected');
209 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
210 $u->read(my $buf, 4096);
211 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
212 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
216 my ($dest, $msg) = @_;
217 my $conn = tcp_connect($dest);
218 ok($conn, "connected for $msg");
219 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
224 my $conn = conn_for($sock, 'host-port');
225 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
226 $conn->read(my $buf, 4096);
227 my ($head, $body) = split(/\r\n\r\n/, $buf);
228 my ($addr, $port) = split(/:/, $body);
229 is($addr, $conn->sockhost, 'host matches addr');
230 is($port, $conn->sockport, 'port matches');
233 # graceful termination
235 my $conn = conn_for($sock, 'graceful termination via slow header');
236 $conn->write("GET /slow-header HTTP/1.0\r\n" .
237 "X-Check-Fifo: $fifo\r\n\r\n");
238 open my $f, '>', $fifo or die "open $fifo: $!\n";
240 ok(print($f "hello\n"), 'wrote something to fifo');
241 is($td->kill, 1, 'started graceful shutdown');
242 ok(print($f "world\n"), 'wrote else to fifo');
243 close $f or die "close fifo: $!\n";
244 $conn->read(my $buf, 8192);
245 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
246 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
247 is($body, "hello\nworld\n", 'read expected body');
249 is($?, 0, 'no error');
250 $spawn_httpd->('-W0');
254 my $conn = conn_for($sock, 'graceful termination via slow-body');
255 $conn->write("GET /slow-body HTTP/1.0\r\n" .
256 "X-Check-Fifo: $fifo\r\n\r\n");
257 open my $f, '>', $fifo or die "open $fifo: $!\n";
260 $conn->sysread($buf, 8192);
261 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
262 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
264 foreach my $c ('a'..'c') {
266 ok(print($f $c), 'wrote line to fifo');
267 $conn->sysread($buf, 8192);
268 is($buf, $c, 'got trickle for reading');
270 is($td->kill, 1, 'started graceful shutdown');
271 ok(print($f "world\n"), 'wrote else to fifo');
272 close $f or die "close fifo: $!\n";
273 $conn->sysread($buf, 8192);
274 is($buf, "world\n", 'read expected body');
275 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
277 is($?, 0, 'no error');
278 $spawn_httpd->('-W0');
281 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
283 my $str = 'abcdefghijklmnopqrstuvwxyz';
284 my $len = length $str;
285 is($len, 26, 'got the alphabet');
286 my $check_self = sub {
288 $conn->read(my $buf, 4096);
289 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
290 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
291 is($body, sha1_hex($str), 'read expected body');
295 which('curl') or skip('curl(1) missing', 4);
296 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
297 my $url = "$base/sha1";
299 pipe($r, $w) or die "pipe: $!";
300 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
301 open my $cout, '+>', undef or die;
302 open my $cerr, '>', undef or die;
303 my $rdr = { 0 => $r, 1 => $cout, 2 => $cerr };
304 my $pid = spawn($cmd, undef, $rdr);
305 close $r or die "close read pipe: $!";
306 foreach my $c ('a'..'z') {
307 print $w $c or die "failed to write to curl: $!";
310 close $w or die "close write pipe: $!";
312 is($?, 0, 'curl exited successfully');
313 is(-s $cerr, 0, 'no errors from curl');
314 seek($cout, 0, SEEK_SET);
315 is(<$cout>, sha1_hex($str), 'read expected body');
317 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
321 my $r = sysread($fh, my $buf, 4096) or last;
323 $buf =~ /\A\0+\z/ or $non_zero++;
325 close $fh or die "curl errored out \$?=$?";
326 is($n, 30 * 1024 * 1024, 'got expected output from curl');
327 is($non_zero, 0, 'read all zeros');
329 require_mods(@zmods, 1);
330 open $fh, '-|', qw(curl -sS), "$base/psgi-return-gzip" or die;
332 my $buf = do { local $/; <$fh> };
333 close $fh or die "curl errored out \$?=$?";
334 IO::Uncompress::Gunzip::gunzip(\$buf => \(my $out));
335 is($out, "hello world\n");
339 my $conn = conn_for($sock, '1.1 pipeline together');
340 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
341 "PUT /sha1 HTTP/1.1\r\n\r\n");
344 until (scalar(@r) >= 2) {
345 my $r = $conn->sysread(my $tmp, 4096);
346 die $! unless defined $r;
347 die "EOF <$buf>" unless $r;
349 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
351 is(2, scalar @r, 'got 2 responses');
353 foreach my $hex (@r) {
354 is($hex, sha1_hex(''), "read expected body $i");
360 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
361 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
363 my $t0 = [ gettimeofday ];
364 until ($buf =~ /\r\n\r\n/s) {
365 $conn->sysread($buf, 4096, length($buf));
367 my $elapsed = tv_interval($t0, [ gettimeofday ]);
368 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
372 my $conn = conn_for($sock, 'graceful termination during slow request');
373 $conn->write("PUT /sha1 HTTP/1.0\r\n");
375 $conn->write("Content-Length: $len\r\n");
377 $conn->write("\r\n");
378 is($td->kill, 1, 'started graceful shutdown');
381 foreach my $c ('a'..'z') {
382 $n += $conn->write($c);
384 is($n, $len, 'wrote alphabet');
385 $check_self->($conn);
387 is($?, 0, 'no error');
388 $spawn_httpd->('-W0');
391 # various DoS attacks against the chunk parser:
393 local $SIG{PIPE} = 'IGNORE';
394 my $conn = conn_for($sock, '1.1 chunk header excessive');
395 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
398 while ($w = $conn->write('ffffffff')) {
401 ok($!, 'got error set in $!');
402 is($w, undef, 'write error happened');
403 ok($n > 0, 'was able to write');
404 my $r = $conn->read(my $buf, 66666);
405 ok($r > 0, 'got non-empty response');
406 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
408 $conn = conn_for($sock, '1.1 chunk trailer excessive');
409 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
410 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
413 while ($w = $conn->write("\r")) {
416 ok($!, 'got error set in $!');
417 ok($n > 0, 'wrote part of chunk end (\r)');
418 $r = $conn->read($buf, 66666);
419 ok($r > 0, 'got non-empty response');
420 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
424 my $conn = conn_for($sock, '1.1 chunked close trickle');
425 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
426 $conn->write("Transfer-encoding: chunked\r\n\r\n");
427 foreach my $x ('a'..'z') {
451 $check_self->($conn);
455 my $conn = conn_for($sock, '1.1 chunked close');
456 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
457 my $xlen = sprintf('%x', $len);
458 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
459 "$str\r\n0\r\n\r\n");
460 $check_self->($conn);
464 my $conn = conn_for($sock, 'chunked body + pipeline');
465 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
466 "Transfer-Encoding: chunked\r\n");
468 $conn->write("\r\n1\r\n");
472 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
476 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
477 $conn->sysread(my $tmp, 4096);
480 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
481 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
482 is($body, sha1_hex('a'), 'read expected body');
484 $conn->write("Connection: close\r\n");
485 $conn->write("Content-Length: $len\r\n\r\n$str");
486 $check_self->($conn);
490 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
491 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
492 "Connection: keep-alive\r\n");
494 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
496 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
497 $conn->sysread(my $tmp, 4096);
500 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
501 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
502 is($body, sha1_hex($str), 'read expected body');
504 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
505 $check_self->($conn);
509 my $conn = conn_for($sock, 'trickle body');
510 $conn->write("PUT /sha1 HTTP/1.0\r\n");
511 $conn->write("Content-Length: $len\r\n\r\n");
512 my $beg = substr($str, 0, 10);
513 my $end = substr($str, 10);
514 is($beg . $end, $str, 'substr setup correct');
519 $check_self->($conn);
523 my $conn = conn_for($sock, 'one-shot write');
524 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
525 "Content-Length: $len\r\n\r\n$str");
526 $check_self->($conn);
530 my $conn = conn_for($sock, 'trickle header, one-shot body');
531 $conn->write("PUT /sha1 HTTP/1.0\r\n");
533 $conn->write("Content-Length: $len\r\n\r\n$str");
534 $check_self->($conn);
538 my $conn = conn_for($sock, '1.1 Connnection: close');
539 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
541 $conn->write("Content-Length: $len\r\n\r\n$str");
542 $check_self->($conn);
546 my $conn = conn_for($sock, '1.1 pipeline start');
547 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
549 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
550 $conn->sysread(my $tmp, 4096);
553 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
554 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
555 is($body, sha1_hex(''), 'read expected body');
558 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
560 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
561 $conn->sysread(my $tmp, 4096);
564 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
565 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
566 is($body, sha1_hex(''), 'read expected body #2');
570 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
571 my $var = $TCP_DEFER_ACCEPT;
572 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
573 is(unpack('i', $x), $defer_accept_val,
574 'TCP_DEFER_ACCEPT unchanged if previously set');
577 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
578 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
579 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
580 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
581 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
585 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
586 skip 'no lsof in PATH', 1 unless which('lsof');
587 my @lsof = `lsof -p $td->{pid}`;
588 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
590 # filter out pipes inherited from the parent
591 my @this = `lsof -p $$`;
593 my $extract_inodes = sub {
595 my @f = split(' ', $_);
597 $bad = $_ if $inode !~ /\A[0-9]+\z/;
599 } grep (/\bpipe\b/, @_);
601 my %child = $extract_inodes->(@lsof);
602 my %parent = $extract_inodes->(@this);
603 skip("inode not in expected format: $bad", 1) if defined($bad);
604 delete @child{(keys %parent)};
605 is_deeply([], [keys %child], 'no extra pipes with -W0');
608 # ensure compatibility with other PSGI servers
610 require_mods(@zmods, qw(Plack::Test HTTP::Request::Common), 3);
611 use_ok 'HTTP::Request::Common';
612 use_ok 'Plack::Test';
613 my $app = require $psgi;
614 test_psgi($app, sub {
616 my $req = GET('http://example.com/psgi-return-gzip');
617 my $res = $cb->($req);
618 my $buf = $res->content;
619 IO::Uncompress::Gunzip::gunzip(\$buf => \(my $out));
620 is($out, "hello world\n");
628 open my $fh, '+<', $f or die "failed to open $f: $!\n";
631 truncate($fh, 0) or die "truncate failed on $f: $!\n";