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, 'chunk with pipeline');
160 my $payload = 'b'x$n;
161 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
162 $conn->write("\r\n".sprintf("%x\r\n", $n));
163 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
164 $conn->read(my $buf, 4096);
166 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
167 my $exp = sha1_hex($payload);
168 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
169 'chunk parser can handled pipelined requests');
172 # Unix domain sockets
174 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
175 ok($u, 'unix socket connected');
176 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
177 $u->read(my $buf, 4096);
178 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
179 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
183 my ($dest, $msg) = @_;
184 my $conn = tcp_connect($dest);
185 ok($conn, "connected for $msg");
186 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
191 my $conn = conn_for($sock, 'host-port');
192 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
193 $conn->read(my $buf, 4096);
194 my ($head, $body) = split(/\r\n\r\n/, $buf);
195 my ($addr, $port) = split(/:/, $body);
196 is($addr, $conn->sockhost, 'host matches addr');
197 is($port, $conn->sockport, 'port matches');
200 # graceful termination
202 my $conn = conn_for($sock, 'graceful termination via slow header');
203 $conn->write("GET /slow-header HTTP/1.0\r\n" .
204 "X-Check-Fifo: $fifo\r\n\r\n");
205 open my $f, '>', $fifo or die "open $fifo: $!\n";
207 ok(print($f "hello\n"), 'wrote something to fifo');
208 is($td->kill, 1, 'started graceful shutdown');
209 ok(print($f "world\n"), 'wrote else to fifo');
210 close $f or die "close fifo: $!\n";
211 $conn->read(my $buf, 8192);
212 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
213 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
214 is($body, "hello\nworld\n", 'read expected body');
216 is($?, 0, 'no error');
217 $spawn_httpd->('-W0');
221 my $conn = conn_for($sock, 'graceful termination via slow-body');
222 $conn->write("GET /slow-body HTTP/1.0\r\n" .
223 "X-Check-Fifo: $fifo\r\n\r\n");
224 open my $f, '>', $fifo or die "open $fifo: $!\n";
227 $conn->sysread($buf, 8192);
228 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
229 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
231 foreach my $c ('a'..'c') {
233 ok(print($f $c), 'wrote line to fifo');
234 $conn->sysread($buf, 8192);
235 is($buf, $c, 'got trickle for reading');
237 is($td->kill, 1, 'started graceful shutdown');
238 ok(print($f "world\n"), 'wrote else to fifo');
239 close $f or die "close fifo: $!\n";
240 $conn->sysread($buf, 8192);
241 is($buf, "world\n", 'read expected body');
242 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
244 is($?, 0, 'no error');
245 $spawn_httpd->('-W0');
248 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
250 my $str = 'abcdefghijklmnopqrstuvwxyz';
251 my $len = length $str;
252 is($len, 26, 'got the alphabet');
253 my $check_self = sub {
255 $conn->read(my $buf, 4096);
256 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
257 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
258 is($body, sha1_hex($str), 'read expected body');
262 which('curl') or skip('curl(1) missing', 4);
263 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
264 my $url = "$base/sha1";
266 pipe($r, $w) or die "pipe: $!";
267 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
268 open my $cout, '+>', undef or die;
269 open my $cerr, '>', undef or die;
270 my $rdr = { 0 => $r, 1 => $cout, 2 => $cerr };
271 my $pid = spawn($cmd, undef, $rdr);
272 close $r or die "close read pipe: $!";
273 foreach my $c ('a'..'z') {
274 print $w $c or die "failed to write to curl: $!";
277 close $w or die "close write pipe: $!";
279 is($?, 0, 'curl exited successfully');
280 is(-s $cerr, 0, 'no errors from curl');
281 seek($cout, 0, SEEK_SET);
282 is(<$cout>, sha1_hex($str), 'read expected body');
284 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
288 my $r = sysread($fh, my $buf, 4096) or last;
290 $buf =~ /\A\0+\z/ or $non_zero++;
292 close $fh or die "curl errored out \$?=$?";
293 is($n, 30 * 1024 * 1024, 'got expected output from curl');
294 is($non_zero, 0, 'read all zeros');
298 my $conn = conn_for($sock, '1.1 pipeline together');
299 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
300 "PUT /sha1 HTTP/1.1\r\n\r\n");
303 until (scalar(@r) >= 2) {
304 my $r = $conn->sysread(my $tmp, 4096);
305 die $! unless defined $r;
306 die "EOF <$buf>" unless $r;
308 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
310 is(2, scalar @r, 'got 2 responses');
312 foreach my $hex (@r) {
313 is($hex, sha1_hex(''), "read expected body $i");
319 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
320 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
322 my $t0 = [ gettimeofday ];
323 until ($buf =~ /\r\n\r\n/s) {
324 $conn->sysread($buf, 4096, length($buf));
326 my $elapsed = tv_interval($t0, [ gettimeofday ]);
327 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
331 my $conn = conn_for($sock, 'graceful termination during slow request');
332 $conn->write("PUT /sha1 HTTP/1.0\r\n");
334 $conn->write("Content-Length: $len\r\n");
336 $conn->write("\r\n");
337 is($td->kill, 1, 'started graceful shutdown');
340 foreach my $c ('a'..'z') {
341 $n += $conn->write($c);
343 is($n, $len, 'wrote alphabet');
344 $check_self->($conn);
346 is($?, 0, 'no error');
347 $spawn_httpd->('-W0');
350 # various DoS attacks against the chunk parser:
352 local $SIG{PIPE} = 'IGNORE';
353 my $conn = conn_for($sock, '1.1 chunk header excessive');
354 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
357 while ($w = $conn->write('ffffffff')) {
360 ok($!, 'got error set in $!');
361 is($w, undef, 'write error happened');
362 ok($n > 0, 'was able to write');
363 my $r = $conn->read(my $buf, 66666);
364 ok($r > 0, 'got non-empty response');
365 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
367 $conn = conn_for($sock, '1.1 chunk trailer excessive');
368 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
369 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
372 while ($w = $conn->write("\r")) {
375 ok($!, 'got error set in $!');
376 ok($n > 0, 'wrote part of chunk end (\r)');
377 $r = $conn->read($buf, 66666);
378 ok($r > 0, 'got non-empty response');
379 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
383 my $conn = conn_for($sock, '1.1 chunked close trickle');
384 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
385 $conn->write("Transfer-encoding: chunked\r\n\r\n");
386 foreach my $x ('a'..'z') {
410 $check_self->($conn);
414 my $conn = conn_for($sock, '1.1 chunked close');
415 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
416 my $xlen = sprintf('%x', $len);
417 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
418 "$str\r\n0\r\n\r\n");
419 $check_self->($conn);
423 my $conn = conn_for($sock, 'chunked body + pipeline');
424 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
425 "Transfer-Encoding: chunked\r\n");
427 $conn->write("\r\n1\r\n");
431 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
435 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
436 $conn->sysread(my $tmp, 4096);
439 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
440 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
441 is($body, sha1_hex('a'), 'read expected body');
443 $conn->write("Connection: close\r\n");
444 $conn->write("Content-Length: $len\r\n\r\n$str");
445 $check_self->($conn);
449 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
450 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
451 "Connection: keep-alive\r\n");
453 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
455 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
456 $conn->sysread(my $tmp, 4096);
459 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
460 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
461 is($body, sha1_hex($str), 'read expected body');
463 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
464 $check_self->($conn);
468 my $conn = conn_for($sock, 'trickle body');
469 $conn->write("PUT /sha1 HTTP/1.0\r\n");
470 $conn->write("Content-Length: $len\r\n\r\n");
471 my $beg = substr($str, 0, 10);
472 my $end = substr($str, 10);
473 is($beg . $end, $str, 'substr setup correct');
478 $check_self->($conn);
482 my $conn = conn_for($sock, 'one-shot write');
483 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
484 "Content-Length: $len\r\n\r\n$str");
485 $check_self->($conn);
489 my $conn = conn_for($sock, 'trickle header, one-shot body');
490 $conn->write("PUT /sha1 HTTP/1.0\r\n");
492 $conn->write("Content-Length: $len\r\n\r\n$str");
493 $check_self->($conn);
497 my $conn = conn_for($sock, '1.1 Connnection: close');
498 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
500 $conn->write("Content-Length: $len\r\n\r\n$str");
501 $check_self->($conn);
505 my $conn = conn_for($sock, '1.1 pipeline start');
506 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
508 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
509 $conn->sysread(my $tmp, 4096);
512 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
513 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
514 is($body, sha1_hex(''), 'read expected body');
517 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
519 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
520 $conn->sysread(my $tmp, 4096);
523 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
524 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
525 is($body, sha1_hex(''), 'read expected body #2');
529 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
530 my $var = $TCP_DEFER_ACCEPT;
531 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
532 is(unpack('i', $x), $defer_accept_val,
533 'TCP_DEFER_ACCEPT unchanged if previously set');
536 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
537 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
538 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
539 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
540 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
544 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
545 skip 'no lsof in PATH', 1 unless which('lsof');
546 my @lsof = `lsof -p $td->{pid}`;
547 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
549 # filter out pipes inherited from the parent
550 my @this = `lsof -p $$`;
552 my $extract_inodes = sub {
554 my @f = split(' ', $_);
556 $bad = $_ if $inode !~ /\A[0-9]+\z/;
558 } grep (/\bpipe\b/, @_);
560 my %child = $extract_inodes->(@lsof);
561 my %parent = $extract_inodes->(@this);
562 skip("inode not in expected format: $bad", 1) if defined($bad);
563 delete @child{(keys %parent)};
564 is_deeply([], [keys %child], 'no extra pipes with -W0');
571 open my $fh, '+<', $f or die "failed to open $f: $!\n";
574 truncate($fh, 0) or die "truncate failed on $f: $!\n";