1 # Copyright (C) 2016-2019 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);
33 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
34 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
35 defined $x or die "getsockopt: $!";
36 $defer_accept_val = unpack('i', $x);
37 if ($defer_accept_val <= 0) {
38 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
40 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
41 require PublicInbox::Daemon;
42 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
43 $accf_arg = pack('a16a240', 'dataready', '');
44 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
48 my $s = IO::Socket::UNIX->new(
50 Type => Socket::SOCK_STREAM(),
57 my $upath = "$tmpdir/s";
58 my $unix = unix_server($upath);
59 ok($unix, 'UNIX socket created');
61 my $spawn_httpd = sub {
63 my $cmd = [ '-httpd', @args, "--stdout=$out", "--stderr=$err", $psgi ];
64 $td = start_script($cmd, undef, { 3 => $sock, 4 => $unix });
68 if ('test worker death') {
69 my $conn = conn_for($sock, 'killed worker');
70 $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
72 while (defined(my $line = $conn->getline)) {
73 next unless $line eq "\r\n";
74 chomp($pid = $conn->getline);
77 like($pid, qr/\A[0-9]+\z/, '/pid response');
78 is(kill('KILL', $pid), 1, 'killed worker');
79 is($conn->getline, undef, 'worker died and EOF-ed client');
81 $conn = conn_for($sock, 'respawned worker');
82 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
83 ok($conn->read(my $buf, 8192), 'read response');
84 my ($head, $body) = split(/\r\n\r\n/, $buf);
86 like($body, qr/\A[0-9]+\z/, '/pid response');
87 isnt($body, $pid, 'respawned worker');
91 my $conn = conn_for($sock, 'streaming callback');
92 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
93 ok($conn->read(my $buf, 8192), 'read response');
94 my ($head, $body) = split(/\r\n\r\n/, $buf);
95 is($body, "hello world\n", 'callback body matches expected');
99 my $conn = conn_for($sock, 'getline-die');
100 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
101 ok($conn->read(my $buf, 8192), 'read some response');
102 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
103 is($conn->read(my $nil, 8192), 0, 'read EOF');
105 my $after = capture($err);
106 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
107 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
111 my $conn = conn_for($sock, 'close-die');
112 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
113 ok($conn->read(my $buf, 8192), 'read some response');
114 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
115 is($conn->read(my $nil, 8192), 0, 'read EOF');
117 my $after = capture($err);
118 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
119 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
123 my $conn = conn_for($sock, 'excessive header');
124 $SIG{PIPE} = 'IGNORE';
125 $conn->write("GET /callback HTTP/1.0\r\n");
126 foreach my $i (1..500000) {
127 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
129 ok(!$conn->write("\r\n"), 'broken request');
130 ok($conn->read(my $buf, 8192), 'read response');
131 my ($head, $body) = split(/\r\n\r\n/, $buf);
132 like($head, qr/\b400\b/, 'got 400 response');
136 my $conn = conn_for($sock, 'excessive body Content-Length');
137 $SIG{PIPE} = 'IGNORE';
138 my $n = (10 * 1024 * 1024) + 1;
139 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
140 ok($conn->read(my $buf, 8192), 'read response');
141 my ($head, $body) = split(/\r\n\r\n/, $buf);
142 like($head, qr/\b413\b/, 'got 413 response');
146 my $conn = conn_for($sock, 'excessive body chunked');
147 $SIG{PIPE} = 'IGNORE';
148 my $n = (10 * 1024 * 1024) + 1;
149 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
150 $conn->write("\r\n".sprintf("%x\r\n", $n));
151 ok($conn->read(my $buf, 8192), 'read response');
152 my ($head, $body) = split(/\r\n\r\n/, $buf);
153 like($head, qr/\b413\b/, 'got 413 response');
157 my $conn = conn_for($sock, 'chunk with pipeline');
159 my $payload = 'b'x$n;
160 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
161 $conn->write("\r\n".sprintf("%x\r\n", $n));
162 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
163 $conn->read(my $buf, 4096);
165 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
166 my $exp = sha1_hex($payload);
167 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
168 'chunk parser can handled pipelined requests');
171 # Unix domain sockets
173 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
174 ok($u, 'unix socket connected');
175 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
176 $u->read(my $buf, 4096);
177 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
178 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
182 my ($dest, $msg) = @_;
183 my $conn = tcp_connect($dest);
184 ok($conn, "connected for $msg");
185 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
190 my $conn = conn_for($sock, 'host-port');
191 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
192 $conn->read(my $buf, 4096);
193 my ($head, $body) = split(/\r\n\r\n/, $buf);
194 my ($addr, $port) = split(/:/, $body);
195 is($addr, $conn->sockhost, 'host matches addr');
196 is($port, $conn->sockport, 'port matches');
199 # graceful termination
201 my $conn = conn_for($sock, 'graceful termination via slow header');
202 $conn->write("GET /slow-header HTTP/1.0\r\n" .
203 "X-Check-Fifo: $fifo\r\n\r\n");
204 open my $f, '>', $fifo or die "open $fifo: $!\n";
206 ok(print($f "hello\n"), 'wrote something to fifo');
207 is($td->kill, 1, 'started graceful shutdown');
208 ok(print($f "world\n"), 'wrote else to fifo');
209 close $f or die "close fifo: $!\n";
210 $conn->read(my $buf, 8192);
211 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
212 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
213 is($body, "hello\nworld\n", 'read expected body');
215 is($?, 0, 'no error');
216 $spawn_httpd->('-W0');
220 my $conn = conn_for($sock, 'graceful termination via slow-body');
221 $conn->write("GET /slow-body HTTP/1.0\r\n" .
222 "X-Check-Fifo: $fifo\r\n\r\n");
223 open my $f, '>', $fifo or die "open $fifo: $!\n";
226 $conn->sysread($buf, 8192);
227 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
228 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
230 foreach my $c ('a'..'c') {
232 ok(print($f $c), 'wrote line to fifo');
233 $conn->sysread($buf, 8192);
234 is($buf, $c, 'got trickle for reading');
236 is($td->kill, 1, 'started graceful shutdown');
237 ok(print($f "world\n"), 'wrote else to fifo');
238 close $f or die "close fifo: $!\n";
239 $conn->sysread($buf, 8192);
240 is($buf, "world\n", 'read expected body');
241 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
243 is($?, 0, 'no error');
244 $spawn_httpd->('-W0');
247 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
249 my $str = 'abcdefghijklmnopqrstuvwxyz';
250 my $len = length $str;
251 is($len, 26, 'got the alphabet');
252 my $check_self = sub {
254 $conn->read(my $buf, 4096);
255 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
256 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
257 is($body, sha1_hex($str), 'read expected body');
261 which('curl') or skip('curl(1) missing', 4);
262 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
263 my $url = "$base/sha1";
265 pipe($r, $w) or die "pipe: $!";
266 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
267 open my $cout, '+>', undef or die;
268 open my $cerr, '>', undef or die;
269 my $rdr = { 0 => $r, 1 => $cout, 2 => $cerr };
270 my $pid = spawn($cmd, undef, $rdr);
271 close $r or die "close read pipe: $!";
272 foreach my $c ('a'..'z') {
273 print $w $c or die "failed to write to curl: $!";
276 close $w or die "close write pipe: $!";
278 is($?, 0, 'curl exited successfully');
279 is(-s $cerr, 0, 'no errors from curl');
280 $cout->seek(0, SEEK_SET);
281 is(<$cout>, sha1_hex($str), 'read expected body');
283 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
287 my $r = sysread($fh, my $buf, 4096) or last;
289 $buf =~ /\A\0+\z/ or $non_zero++;
291 close $fh or die "curl errored out \$?=$?";
292 is($n, 30 * 1024 * 1024, 'got expected output from curl');
293 is($non_zero, 0, 'read all zeros');
297 my $conn = conn_for($sock, '1.1 pipeline together');
298 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
299 "PUT /sha1 HTTP/1.1\r\n\r\n");
302 until (scalar(@r) >= 2) {
303 my $r = $conn->sysread(my $tmp, 4096);
304 die $! unless defined $r;
305 die "EOF <$buf>" unless $r;
307 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
309 is(2, scalar @r, 'got 2 responses');
311 foreach my $hex (@r) {
312 is($hex, sha1_hex(''), "read expected body $i");
318 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
319 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
321 my $t0 = [ gettimeofday ];
322 until ($buf =~ /\r\n\r\n/s) {
323 $conn->sysread($buf, 4096, length($buf));
325 my $elapsed = tv_interval($t0, [ gettimeofday ]);
326 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
330 my $conn = conn_for($sock, 'graceful termination during slow request');
331 $conn->write("PUT /sha1 HTTP/1.0\r\n");
333 $conn->write("Content-Length: $len\r\n");
335 $conn->write("\r\n");
336 is($td->kill, 1, 'started graceful shutdown');
339 foreach my $c ('a'..'z') {
340 $n += $conn->write($c);
342 is($n, $len, 'wrote alphabet');
343 $check_self->($conn);
345 is($?, 0, 'no error');
346 $spawn_httpd->('-W0');
349 # various DoS attacks against the chunk parser:
351 local $SIG{PIPE} = 'IGNORE';
352 my $conn = conn_for($sock, '1.1 chunk header excessive');
353 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
356 while ($w = $conn->write('ffffffff')) {
359 ok($!, 'got error set in $!');
360 is($w, undef, 'write error happened');
361 ok($n > 0, 'was able to write');
362 my $r = $conn->read(my $buf, 66666);
363 ok($r > 0, 'got non-empty response');
364 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
366 $conn = conn_for($sock, '1.1 chunk trailer excessive');
367 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
368 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
371 while ($w = $conn->write("\r")) {
374 ok($!, 'got error set in $!');
375 ok($n > 0, 'wrote part of chunk end (\r)');
376 $r = $conn->read($buf, 66666);
377 ok($r > 0, 'got non-empty response');
378 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
382 my $conn = conn_for($sock, '1.1 chunked close trickle');
383 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
384 $conn->write("Transfer-encoding: chunked\r\n\r\n");
385 foreach my $x ('a'..'z') {
409 $check_self->($conn);
413 my $conn = conn_for($sock, '1.1 chunked close');
414 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
415 my $xlen = sprintf('%x', $len);
416 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
417 "$str\r\n0\r\n\r\n");
418 $check_self->($conn);
422 my $conn = conn_for($sock, 'chunked body + pipeline');
423 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
424 "Transfer-Encoding: chunked\r\n");
426 $conn->write("\r\n1\r\n");
430 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
434 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
435 $conn->sysread(my $tmp, 4096);
438 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
439 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
440 is($body, sha1_hex('a'), 'read expected body');
442 $conn->write("Connection: close\r\n");
443 $conn->write("Content-Length: $len\r\n\r\n$str");
444 $check_self->($conn);
448 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
449 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
450 "Connection: keep-alive\r\n");
452 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
454 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
455 $conn->sysread(my $tmp, 4096);
458 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
459 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
460 is($body, sha1_hex($str), 'read expected body');
462 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
463 $check_self->($conn);
467 my $conn = conn_for($sock, 'trickle body');
468 $conn->write("PUT /sha1 HTTP/1.0\r\n");
469 $conn->write("Content-Length: $len\r\n\r\n");
470 my $beg = substr($str, 0, 10);
471 my $end = substr($str, 10);
472 is($beg . $end, $str, 'substr setup correct');
477 $check_self->($conn);
481 my $conn = conn_for($sock, 'one-shot write');
482 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
483 "Content-Length: $len\r\n\r\n$str");
484 $check_self->($conn);
488 my $conn = conn_for($sock, 'trickle header, one-shot body');
489 $conn->write("PUT /sha1 HTTP/1.0\r\n");
491 $conn->write("Content-Length: $len\r\n\r\n$str");
492 $check_self->($conn);
496 my $conn = conn_for($sock, '1.1 Connnection: close');
497 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
499 $conn->write("Content-Length: $len\r\n\r\n$str");
500 $check_self->($conn);
504 my $conn = conn_for($sock, '1.1 pipeline start');
505 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
507 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
508 $conn->sysread(my $tmp, 4096);
511 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
512 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
513 is($body, sha1_hex(''), 'read expected body');
516 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
518 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
519 $conn->sysread(my $tmp, 4096);
522 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
523 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
524 is($body, sha1_hex(''), 'read expected body #2');
528 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
529 my $var = Socket::TCP_DEFER_ACCEPT();
530 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
531 is(unpack('i', $x), $defer_accept_val,
532 'TCP_DEFER_ACCEPT unchanged if previously set');
535 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
536 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
537 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
538 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
539 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
543 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
544 skip 'no lsof in PATH', 1 unless which('lsof');
545 my @lsof = `lsof -p $td->{pid}`;
546 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
548 # filter out pipes inherited from the parent
549 my @this = `lsof -p $$`;
551 my $extract_inodes = sub {
553 my @f = split(' ', $_);
555 $bad = $_ if $inode !~ /\A[0-9]+\z/;
557 } grep (/\bpipe\b/, @_);
559 my %child = $extract_inodes->(@lsof);
560 my %parent = $extract_inodes->(@this);
561 skip("inode not in expected format: $bad", 1) if defined($bad);
562 delete @child{(keys %parent)};
563 is_deeply([], [keys %child], 'no extra pipes with -W0');
570 open my $fh, '+<', $f or die "failed to open $f: $!\n";
573 truncate($fh, 0) or die "truncate failed on $f: $!\n";