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;
26 # make sure stdin is not a pipe for lsof test to check for leaking pipes
27 open(STDIN, '<', '/dev/null') or die 'no /dev/null: $!';
29 # Make sure we don't clobber socket options set by systemd or similar
30 # using socket activation:
31 my ($defer_accept_val, $accf_arg, $TCP_DEFER_ACCEPT);
33 $TCP_DEFER_ACCEPT = eval { Socket::TCP_DEFER_ACCEPT() } // 9;
34 setsockopt($sock, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 5) or die;
35 my $x = getsockopt($sock, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
36 defined $x or die "getsockopt: $!";
37 $defer_accept_val = unpack('i', $x);
38 if ($defer_accept_val <= 0) {
39 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
41 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
42 require PublicInbox::Daemon;
43 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
44 $accf_arg = pack('a16a240', 'dataready', '');
45 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
49 my $s = IO::Socket::UNIX->new(
51 Type => Socket::SOCK_STREAM(),
58 my $upath = "$tmpdir/s";
59 my $unix = unix_server($upath);
60 ok($unix, 'UNIX socket created');
62 my $spawn_httpd = sub {
64 my $cmd = [ '-httpd', @args, "--stdout=$out", "--stderr=$err", $psgi ];
65 $td = start_script($cmd, undef, { 3 => $sock, 4 => $unix });
69 if ('test worker death') {
70 my $conn = conn_for($sock, 'killed worker');
71 $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
73 while (defined(my $line = $conn->getline)) {
74 next unless $line eq "\r\n";
75 chomp($pid = $conn->getline);
78 like($pid, qr/\A[0-9]+\z/, '/pid response');
79 is(kill('KILL', $pid), 1, 'killed worker');
80 is($conn->getline, undef, 'worker died and EOF-ed client');
82 $conn = conn_for($sock, 'respawned worker');
83 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
84 ok($conn->read(my $buf, 8192), 'read response');
85 my ($head, $body) = split(/\r\n\r\n/, $buf);
87 like($body, qr/\A[0-9]+\z/, '/pid response');
88 isnt($body, $pid, 'respawned worker');
92 my $conn = conn_for($sock, 'streaming callback');
93 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
94 ok($conn->read(my $buf, 8192), 'read response');
95 my ($head, $body) = split(/\r\n\r\n/, $buf);
96 is($body, "hello world\n", 'callback body matches expected');
100 my $conn = conn_for($sock, 'getline-die');
101 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
102 ok($conn->read(my $buf, 8192), 'read some response');
103 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
104 is($conn->read(my $nil, 8192), 0, 'read EOF');
106 my $after = capture($err);
107 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
108 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
112 my $conn = conn_for($sock, 'close-die');
113 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
114 ok($conn->read(my $buf, 8192), 'read some response');
115 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
116 is($conn->read(my $nil, 8192), 0, 'read EOF');
118 my $after = capture($err);
119 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
120 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
124 my $conn = conn_for($sock, 'excessive header');
125 $SIG{PIPE} = 'IGNORE';
126 $conn->write("GET /callback HTTP/1.0\r\n");
127 foreach my $i (1..500000) {
128 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
130 ok(!$conn->write("\r\n"), 'broken request');
131 ok($conn->read(my $buf, 8192), 'read response');
132 my ($head, $body) = split(/\r\n\r\n/, $buf);
133 like($head, qr/\b400\b/, 'got 400 response');
137 my $conn = conn_for($sock, 'excessive body Content-Length');
138 $SIG{PIPE} = 'IGNORE';
139 my $n = (10 * 1024 * 1024) + 1;
140 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
141 ok($conn->read(my $buf, 8192), 'read response');
142 my ($head, $body) = split(/\r\n\r\n/, $buf);
143 like($head, qr/\b413\b/, 'got 413 response');
147 my $conn = conn_for($sock, 'excessive body chunked');
148 $SIG{PIPE} = 'IGNORE';
149 my $n = (10 * 1024 * 1024) + 1;
150 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
151 $conn->write("\r\n".sprintf("%x\r\n", $n));
152 ok($conn->read(my $buf, 8192), 'read response');
153 my ($head, $body) = split(/\r\n\r\n/, $buf);
154 like($head, qr/\b413\b/, 'got 413 response');
158 my $conn = conn_for($sock, '1.1 Transfer-Encoding bogus');
159 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: bogus\r\n\r\n");
160 $conn->read(my $buf, 4096);
161 like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on bogus TE');
164 my $conn = conn_for($sock, '1.1 Content-Length bogus');
165 $conn->write("PUT /sha1 HTTP/1.1\r\nContent-Length: 3.3\r\n\r\n");
166 $conn->read(my $buf, 4096);
167 like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on bad length');
171 my $req = "PUT /sha1 HTTP/1.1\r\nContent-Length: 3\r\n" .
172 "Content-Length: 3\r\n\r\n";
173 # this is stricter than it needs to be. Due to the way
174 # Plack::HTTPParser, PSGI specs, and how hash tables work in common
175 # languages; it's not possible to tell the difference between folded
176 # and intentionally bad commas (e.g. "Content-Length: 3, 3")
178 require Plack::HTTPParser; # XS or pure Perl
179 require Data::Dumper;
180 Plack::HTTPParser::parse_http_request($req, my $env = {});
181 diag Data::Dumper::Dumper($env); # "Content-Length: 3, 3"
183 my $conn = conn_for($sock, '1.1 Content-Length dupe');
185 $conn->read(my $buf, 4096);
186 like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on dupe length');
190 my $conn = conn_for($sock, 'chunk with pipeline');
192 my $payload = 'b'x$n;
193 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
194 $conn->write("\r\n".sprintf("%x\r\n", $n));
195 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
196 $conn->read(my $buf, 4096);
198 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
199 my $exp = sha1_hex($payload);
200 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
201 'chunk parser can handled pipelined requests');
204 # Unix domain sockets
206 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
207 ok($u, 'unix socket connected');
208 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
209 $u->read(my $buf, 4096);
210 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
211 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
215 my ($dest, $msg) = @_;
216 my $conn = tcp_connect($dest);
217 ok($conn, "connected for $msg");
218 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
223 my $conn = conn_for($sock, 'host-port');
224 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
225 $conn->read(my $buf, 4096);
226 my ($head, $body) = split(/\r\n\r\n/, $buf);
227 my ($addr, $port) = split(/:/, $body);
228 is($addr, $conn->sockhost, 'host matches addr');
229 is($port, $conn->sockport, 'port matches');
232 # graceful termination
234 my $conn = conn_for($sock, 'graceful termination via slow header');
235 $conn->write("GET /slow-header HTTP/1.0\r\n" .
236 "X-Check-Fifo: $fifo\r\n\r\n");
237 open my $f, '>', $fifo or die "open $fifo: $!\n";
239 ok(print($f "hello\n"), 'wrote something to fifo');
240 is($td->kill, 1, 'started graceful shutdown');
241 ok(print($f "world\n"), 'wrote else to fifo');
242 close $f or die "close fifo: $!\n";
243 $conn->read(my $buf, 8192);
244 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
245 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
246 is($body, "hello\nworld\n", 'read expected body');
248 is($?, 0, 'no error');
249 $spawn_httpd->('-W0');
253 my $conn = conn_for($sock, 'graceful termination via slow-body');
254 $conn->write("GET /slow-body HTTP/1.0\r\n" .
255 "X-Check-Fifo: $fifo\r\n\r\n");
256 open my $f, '>', $fifo or die "open $fifo: $!\n";
259 $conn->sysread($buf, 8192);
260 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
261 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
263 foreach my $c ('a'..'c') {
265 ok(print($f $c), 'wrote line to fifo');
266 $conn->sysread($buf, 8192);
267 is($buf, $c, 'got trickle for reading');
269 is($td->kill, 1, 'started graceful shutdown');
270 ok(print($f "world\n"), 'wrote else to fifo');
271 close $f or die "close fifo: $!\n";
272 $conn->sysread($buf, 8192);
273 is($buf, "world\n", 'read expected body');
274 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
276 is($?, 0, 'no error');
277 $spawn_httpd->('-W0');
280 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
282 my $str = 'abcdefghijklmnopqrstuvwxyz';
283 my $len = length $str;
284 is($len, 26, 'got the alphabet');
285 my $check_self = sub {
287 $conn->read(my $buf, 4096);
288 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
289 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
290 is($body, sha1_hex($str), 'read expected body');
294 which('curl') or skip('curl(1) missing', 4);
295 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
296 my $url = "$base/sha1";
298 pipe($r, $w) or die "pipe: $!";
299 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
300 open my $cout, '+>', undef or die;
301 open my $cerr, '>', undef or die;
302 my $rdr = { 0 => $r, 1 => $cout, 2 => $cerr };
303 my $pid = spawn($cmd, undef, $rdr);
304 close $r or die "close read pipe: $!";
305 foreach my $c ('a'..'z') {
306 print $w $c or die "failed to write to curl: $!";
309 close $w or die "close write pipe: $!";
311 is($?, 0, 'curl exited successfully');
312 is(-s $cerr, 0, 'no errors from curl');
313 seek($cout, 0, SEEK_SET);
314 is(<$cout>, sha1_hex($str), 'read expected body');
316 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
320 my $r = sysread($fh, my $buf, 4096) or last;
322 $buf =~ /\A\0+\z/ or $non_zero++;
324 close $fh or die "curl errored out \$?=$?";
325 is($n, 30 * 1024 * 1024, 'got expected output from curl');
326 is($non_zero, 0, 'read all zeros');
330 my $conn = conn_for($sock, '1.1 pipeline together');
331 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
332 "PUT /sha1 HTTP/1.1\r\n\r\n");
335 until (scalar(@r) >= 2) {
336 my $r = $conn->sysread(my $tmp, 4096);
337 die $! unless defined $r;
338 die "EOF <$buf>" unless $r;
340 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
342 is(2, scalar @r, 'got 2 responses');
344 foreach my $hex (@r) {
345 is($hex, sha1_hex(''), "read expected body $i");
351 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
352 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
354 my $t0 = [ gettimeofday ];
355 until ($buf =~ /\r\n\r\n/s) {
356 $conn->sysread($buf, 4096, length($buf));
358 my $elapsed = tv_interval($t0, [ gettimeofday ]);
359 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
363 my $conn = conn_for($sock, 'graceful termination during slow request');
364 $conn->write("PUT /sha1 HTTP/1.0\r\n");
366 $conn->write("Content-Length: $len\r\n");
368 $conn->write("\r\n");
369 is($td->kill, 1, 'started graceful shutdown');
372 foreach my $c ('a'..'z') {
373 $n += $conn->write($c);
375 is($n, $len, 'wrote alphabet');
376 $check_self->($conn);
378 is($?, 0, 'no error');
379 $spawn_httpd->('-W0');
382 # various DoS attacks against the chunk parser:
384 local $SIG{PIPE} = 'IGNORE';
385 my $conn = conn_for($sock, '1.1 chunk header excessive');
386 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
389 while ($w = $conn->write('ffffffff')) {
392 ok($!, 'got error set in $!');
393 is($w, undef, 'write error happened');
394 ok($n > 0, 'was able to write');
395 my $r = $conn->read(my $buf, 66666);
396 ok($r > 0, 'got non-empty response');
397 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
399 $conn = conn_for($sock, '1.1 chunk trailer excessive');
400 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
401 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
404 while ($w = $conn->write("\r")) {
407 ok($!, 'got error set in $!');
408 ok($n > 0, 'wrote part of chunk end (\r)');
409 $r = $conn->read($buf, 66666);
410 ok($r > 0, 'got non-empty response');
411 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
415 my $conn = conn_for($sock, '1.1 chunked close trickle');
416 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
417 $conn->write("Transfer-encoding: chunked\r\n\r\n");
418 foreach my $x ('a'..'z') {
442 $check_self->($conn);
446 my $conn = conn_for($sock, '1.1 chunked close');
447 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
448 my $xlen = sprintf('%x', $len);
449 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
450 "$str\r\n0\r\n\r\n");
451 $check_self->($conn);
455 my $conn = conn_for($sock, 'chunked body + pipeline');
456 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
457 "Transfer-Encoding: chunked\r\n");
459 $conn->write("\r\n1\r\n");
463 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
467 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
468 $conn->sysread(my $tmp, 4096);
471 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
472 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
473 is($body, sha1_hex('a'), 'read expected body');
475 $conn->write("Connection: close\r\n");
476 $conn->write("Content-Length: $len\r\n\r\n$str");
477 $check_self->($conn);
481 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
482 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
483 "Connection: keep-alive\r\n");
485 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
487 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
488 $conn->sysread(my $tmp, 4096);
491 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
492 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
493 is($body, sha1_hex($str), 'read expected body');
495 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
496 $check_self->($conn);
500 my $conn = conn_for($sock, 'trickle body');
501 $conn->write("PUT /sha1 HTTP/1.0\r\n");
502 $conn->write("Content-Length: $len\r\n\r\n");
503 my $beg = substr($str, 0, 10);
504 my $end = substr($str, 10);
505 is($beg . $end, $str, 'substr setup correct');
510 $check_self->($conn);
514 my $conn = conn_for($sock, 'one-shot write');
515 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
516 "Content-Length: $len\r\n\r\n$str");
517 $check_self->($conn);
521 my $conn = conn_for($sock, 'trickle header, one-shot body');
522 $conn->write("PUT /sha1 HTTP/1.0\r\n");
524 $conn->write("Content-Length: $len\r\n\r\n$str");
525 $check_self->($conn);
529 my $conn = conn_for($sock, '1.1 Connnection: close');
530 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
532 $conn->write("Content-Length: $len\r\n\r\n$str");
533 $check_self->($conn);
537 my $conn = conn_for($sock, '1.1 pipeline start');
538 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
540 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
541 $conn->sysread(my $tmp, 4096);
544 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
545 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
546 is($body, sha1_hex(''), 'read expected body');
549 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
551 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
552 $conn->sysread(my $tmp, 4096);
555 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
556 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
557 is($body, sha1_hex(''), 'read expected body #2');
561 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
562 my $var = $TCP_DEFER_ACCEPT;
563 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
564 is(unpack('i', $x), $defer_accept_val,
565 'TCP_DEFER_ACCEPT unchanged if previously set');
568 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
569 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
570 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
571 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
572 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
576 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
577 skip 'no lsof in PATH', 1 unless which('lsof');
578 my @lsof = `lsof -p $td->{pid}`;
579 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
581 # filter out pipes inherited from the parent
582 my @this = `lsof -p $$`;
584 my $extract_inodes = sub {
586 my @f = split(' ', $_);
588 $bad = $_ if $inode !~ /\A[0-9]+\z/;
590 } grep (/\bpipe\b/, @_);
592 my %child = $extract_inodes->(@lsof);
593 my %parent = $extract_inodes->(@this);
594 skip("inode not in expected format: $bad", 1) if defined($bad);
595 delete @child{(keys %parent)};
596 is_deeply([], [keys %child], 'no extra pipes with -W0');
603 open my $fh, '+<', $f or die "failed to open $f: $!\n";
606 truncate($fh, 0) or die "truncate failed on $f: $!\n";