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);
11 foreach my $mod (qw(Plack::Util Plack::Builder HTTP::Date HTTP::Status)) {
13 plan skip_all => "$mod missing for httpd-corner.t" if $@;
16 use Digest::SHA qw(sha1_hex);
17 use File::Temp qw/tempdir/;
21 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
23 require './t/common.perl';
24 my $tmpdir = tempdir('httpd-corner-XXXXXX', TMPDIR => 1, CLEANUP => 1);
25 my $fifo = "$tmpdir/fifo";
26 ok(defined mkfifo($fifo, 0777), 'created FIFO');
27 my $err = "$tmpdir/stderr.log";
28 my $out = "$tmpdir/stdout.log";
29 my $httpd = 'blib/script/public-inbox-httpd';
30 my $psgi = "./t/httpd-corner.psgi";
31 my $sock = tcp_server() or die;
33 # make sure stdin is not a pipe for lsof test to check for leaking pipes
34 open(STDIN, '<', '/dev/null') or die 'no /dev/null: $!';
36 # Make sure we don't clobber socket options set by systemd or similar
37 # using socket activation:
38 my ($defer_accept_val, $accf_arg);
40 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
41 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
42 defined $x or die "getsockopt: $!";
43 $defer_accept_val = unpack('i', $x);
44 if ($defer_accept_val <= 0) {
45 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
47 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
48 require PublicInbox::Daemon;
49 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
50 $accf_arg = pack('a16a240', 'dataready', '');
51 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
55 my $s = IO::Socket::UNIX->new(
57 Type => Socket::SOCK_STREAM(),
64 my $upath = "$tmpdir/s";
65 my $unix = unix_server($upath);
66 ok($unix, 'UNIX socket created');
68 END { kill 'TERM', $pid if defined $pid };
69 my $spawn_httpd = sub {
71 my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
72 $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
73 ok(defined $pid, 'forked httpd process successfully');
77 if ('test worker death') {
78 my $conn = conn_for($sock, 'killed worker');
79 $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
81 while (defined(my $line = $conn->getline)) {
82 next unless $line eq "\r\n";
83 chomp($pid = $conn->getline);
86 like($pid, qr/\A[0-9]+\z/, '/pid response');
87 is(kill('KILL', $pid), 1, 'killed worker');
88 is($conn->getline, undef, 'worker died and EOF-ed client');
90 $conn = conn_for($sock, 'respawned worker');
91 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
92 ok($conn->read(my $buf, 8192), 'read response');
93 my ($head, $body) = split(/\r\n\r\n/, $buf);
95 like($body, qr/\A[0-9]+\z/, '/pid response');
96 isnt($body, $pid, 'respawned worker');
100 my $conn = conn_for($sock, 'streaming callback');
101 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
102 ok($conn->read(my $buf, 8192), 'read response');
103 my ($head, $body) = split(/\r\n\r\n/, $buf);
104 is($body, "hello world\n", 'callback body matches expected');
108 my $conn = conn_for($sock, 'getline-die');
109 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
110 ok($conn->read(my $buf, 8192), 'read some response');
111 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
112 is($conn->read(my $nil, 8192), 0, 'read EOF');
114 my $after = capture($err);
115 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
116 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
120 my $conn = conn_for($sock, 'close-die');
121 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
122 ok($conn->read(my $buf, 8192), 'read some response');
123 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
124 is($conn->read(my $nil, 8192), 0, 'read EOF');
126 my $after = capture($err);
127 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
128 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
132 my $conn = conn_for($sock, 'excessive header');
133 $SIG{PIPE} = 'IGNORE';
134 $conn->write("GET /callback HTTP/1.0\r\n");
135 foreach my $i (1..500000) {
136 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
138 ok(!$conn->write("\r\n"), 'broken request');
139 ok($conn->read(my $buf, 8192), 'read response');
140 my ($head, $body) = split(/\r\n\r\n/, $buf);
141 like($head, qr/\b400\b/, 'got 400 response');
145 my $conn = conn_for($sock, 'excessive body Content-Length');
146 $SIG{PIPE} = 'IGNORE';
147 my $n = (10 * 1024 * 1024) + 1;
148 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
149 ok($conn->read(my $buf, 8192), 'read response');
150 my ($head, $body) = split(/\r\n\r\n/, $buf);
151 like($head, qr/\b413\b/, 'got 413 response');
155 my $conn = conn_for($sock, 'excessive body chunked');
156 $SIG{PIPE} = 'IGNORE';
157 my $n = (10 * 1024 * 1024) + 1;
158 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
159 $conn->write("\r\n".sprintf("%x\r\n", $n));
160 ok($conn->read(my $buf, 8192), 'read response');
161 my ($head, $body) = split(/\r\n\r\n/, $buf);
162 like($head, qr/\b413\b/, 'got 413 response');
166 my $conn = conn_for($sock, 'chunk with pipeline');
168 my $payload = 'b'x$n;
169 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
170 $conn->write("\r\n".sprintf("%x\r\n", $n));
171 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
172 $conn->read(my $buf, 4096);
174 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
175 my $exp = sha1_hex($payload);
176 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
177 'chunk parser can handled pipelined requests');
180 # Unix domain sockets
182 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
183 ok($u, 'unix socket connected');
184 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
185 $u->read(my $buf, 4096);
186 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
187 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
191 my ($dest, $msg) = @_;
192 my $conn = tcp_connect($dest);
193 ok($conn, "connected for $msg");
194 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
199 my $conn = conn_for($sock, 'host-port');
200 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
201 $conn->read(my $buf, 4096);
202 my ($head, $body) = split(/\r\n\r\n/, $buf);
203 my ($addr, $port) = split(/:/, $body);
204 is($addr, $conn->sockhost, 'host matches addr');
205 is($port, $conn->sockport, 'port matches');
208 # graceful termination
210 my $conn = conn_for($sock, 'graceful termination via slow header');
211 $conn->write("GET /slow-header HTTP/1.0\r\n" .
212 "X-Check-Fifo: $fifo\r\n\r\n");
213 open my $f, '>', $fifo or die "open $fifo: $!\n";
215 ok(print($f "hello\n"), 'wrote something to fifo');
218 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
219 ok(print($f "world\n"), 'wrote else to fifo');
220 close $f or die "close fifo: $!\n";
221 $conn->read(my $buf, 8192);
222 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
223 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
224 is($body, "hello\nworld\n", 'read expected body');
225 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
226 is($?, 0, 'no error');
227 $spawn_httpd->('-W0');
231 my $conn = conn_for($sock, 'graceful termination via slow-body');
232 $conn->write("GET /slow-body HTTP/1.0\r\n" .
233 "X-Check-Fifo: $fifo\r\n\r\n");
234 open my $f, '>', $fifo or die "open $fifo: $!\n";
237 $conn->sysread($buf, 8192);
238 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
239 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
241 foreach my $c ('a'..'c') {
243 ok(print($f $c), 'wrote line to fifo');
244 $conn->sysread($buf, 8192);
245 is($buf, $c, 'got trickle for reading');
249 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
250 ok(print($f "world\n"), 'wrote else to fifo');
251 close $f or die "close fifo: $!\n";
252 $conn->sysread($buf, 8192);
253 is($buf, "world\n", 'read expected body');
254 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
255 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
256 is($?, 0, 'no error');
257 $spawn_httpd->('-W0');
260 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
262 my $str = 'abcdefghijklmnopqrstuvwxyz';
263 my $len = length $str;
264 is($len, 26, 'got the alphabet');
265 my $check_self = sub {
267 $conn->read(my $buf, 4096);
268 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
269 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
270 is($body, sha1_hex($str), 'read expected body');
274 which('curl') or skip('curl(1) missing', 4);
275 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
276 my $url = "$base/sha1";
278 pipe($r, $w) or die "pipe: $!";
279 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
280 open my $cout, '+>', undef or die;
281 open my $cerr, '>', undef or die;
282 my $rdr = { 0 => fileno($r), 1 => fileno($cout), 2 => fileno($cerr) };
283 my $pid = spawn($cmd, undef, $rdr);
284 close $r or die "close read pipe: $!";
285 foreach my $c ('a'..'z') {
286 print $w $c or die "failed to write to curl: $!";
289 close $w or die "close write pipe: $!";
291 is($?, 0, 'curl exited successfully');
292 is(-s $cerr, 0, 'no errors from curl');
293 $cout->seek(0, SEEK_SET);
294 is(<$cout>, sha1_hex($str), 'read expected body');
296 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
300 my $r = sysread($fh, my $buf, 4096) or last;
302 $buf =~ /\A\0+\z/ or $non_zero++;
304 close $fh or die "curl errored out \$?=$?";
305 is($n, 30 * 1024 * 1024, 'got expected output from curl');
306 is($non_zero, 0, 'read all zeros');
310 my $conn = conn_for($sock, '1.1 pipeline together');
311 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
312 "PUT /sha1 HTTP/1.1\r\n\r\n");
315 until (scalar(@r) >= 2) {
316 my $r = $conn->sysread(my $tmp, 4096);
317 die $! unless defined $r;
318 die "EOF <$buf>" unless $r;
320 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
322 is(2, scalar @r, 'got 2 responses');
324 foreach my $hex (@r) {
325 is($hex, sha1_hex(''), "read expected body $i");
331 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
332 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
334 my $t0 = [ gettimeofday ];
335 until ($buf =~ /\r\n\r\n/s) {
336 $conn->sysread($buf, 4096, length($buf));
338 my $elapsed = tv_interval($t0, [ gettimeofday ]);
339 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
343 my $conn = conn_for($sock, 'graceful termination during slow request');
344 $conn->write("PUT /sha1 HTTP/1.0\r\n");
346 $conn->write("Content-Length: $len\r\n");
348 $conn->write("\r\n");
351 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
354 foreach my $c ('a'..'z') {
355 $n += $conn->write($c);
357 is($n, $len, 'wrote alphabet');
358 $check_self->($conn);
359 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
360 is($?, 0, 'no error');
361 $spawn_httpd->('-W0');
364 # various DoS attacks against the chunk parser:
366 local $SIG{PIPE} = 'IGNORE';
367 my $conn = conn_for($sock, '1.1 chunk header excessive');
368 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
371 while ($w = $conn->write('ffffffff')) {
374 ok($!, 'got error set in $!');
375 is($w, undef, 'write error happened');
376 ok($n > 0, 'was able to write');
377 my $r = $conn->read(my $buf, 66666);
378 ok($r > 0, 'got non-empty response');
379 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
381 $conn = conn_for($sock, '1.1 chunk trailer excessive');
382 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
383 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
386 while ($w = $conn->write("\r")) {
389 ok($!, 'got error set in $!');
390 ok($n > 0, 'wrote part of chunk end (\r)');
391 $r = $conn->read($buf, 66666);
392 ok($r > 0, 'got non-empty response');
393 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
397 my $conn = conn_for($sock, '1.1 chunked close trickle');
398 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
399 $conn->write("Transfer-encoding: chunked\r\n\r\n");
400 foreach my $x ('a'..'z') {
424 $check_self->($conn);
428 my $conn = conn_for($sock, '1.1 chunked close');
429 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
430 my $xlen = sprintf('%x', $len);
431 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
432 "$str\r\n0\r\n\r\n");
433 $check_self->($conn);
437 my $conn = conn_for($sock, 'chunked body + pipeline');
438 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
439 "Transfer-Encoding: chunked\r\n");
441 $conn->write("\r\n1\r\n");
445 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
449 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
450 $conn->sysread(my $tmp, 4096);
453 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
454 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
455 is($body, sha1_hex('a'), 'read expected body');
457 $conn->write("Connection: close\r\n");
458 $conn->write("Content-Length: $len\r\n\r\n$str");
459 $check_self->($conn);
463 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
464 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
465 "Connection: keep-alive\r\n");
467 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
469 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
470 $conn->sysread(my $tmp, 4096);
473 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
474 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
475 is($body, sha1_hex($str), 'read expected body');
477 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
478 $check_self->($conn);
482 my $conn = conn_for($sock, 'trickle body');
483 $conn->write("PUT /sha1 HTTP/1.0\r\n");
484 $conn->write("Content-Length: $len\r\n\r\n");
485 my $beg = substr($str, 0, 10);
486 my $end = substr($str, 10);
487 is($beg . $end, $str, 'substr setup correct');
492 $check_self->($conn);
496 my $conn = conn_for($sock, 'one-shot write');
497 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
498 "Content-Length: $len\r\n\r\n$str");
499 $check_self->($conn);
503 my $conn = conn_for($sock, 'trickle header, one-shot body');
504 $conn->write("PUT /sha1 HTTP/1.0\r\n");
506 $conn->write("Content-Length: $len\r\n\r\n$str");
507 $check_self->($conn);
511 my $conn = conn_for($sock, '1.1 Connnection: close');
512 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
514 $conn->write("Content-Length: $len\r\n\r\n$str");
515 $check_self->($conn);
519 my $conn = conn_for($sock, '1.1 pipeline start');
520 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
522 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
523 $conn->sysread(my $tmp, 4096);
526 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
527 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
528 is($body, sha1_hex(''), 'read expected body');
531 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
533 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
534 $conn->sysread(my $tmp, 4096);
537 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
538 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
539 is($body, sha1_hex(''), 'read expected body #2');
543 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
544 my $var = Socket::TCP_DEFER_ACCEPT();
545 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
546 is(unpack('i', $x), $defer_accept_val,
547 'TCP_DEFER_ACCEPT unchanged if previously set');
550 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
551 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
552 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
553 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
554 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
557 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
558 skip 'no lsof in PATH', 1 unless which('lsof');
559 my @lsof = `lsof -p $pid`;
560 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
561 is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
568 open my $fh, '+<', $f or die "failed to open $f: $!\n";
571 truncate($fh, 0) or die "truncate failed on $f: $!\n";