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);
11 foreach my $mod (qw(Plack::Util Plack::Builder
12 HTTP::Date HTTP::Status IPC::Run)) {
14 plan skip_all => "$mod missing for httpd-corner.t" if $@;
17 use Digest::SHA qw(sha1_hex);
18 use File::Temp qw/tempdir/;
22 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
24 require './t/common.perl';
25 my $tmpdir = tempdir('httpd-corner-XXXXXX', TMPDIR => 1, CLEANUP => 1);
26 my $fifo = "$tmpdir/fifo";
27 ok(defined mkfifo($fifo, 0777), 'created FIFO');
28 my $err = "$tmpdir/stderr.log";
29 my $out = "$tmpdir/stdout.log";
30 my $httpd = 'blib/script/public-inbox-httpd';
31 my $psgi = "./t/httpd-corner.psgi";
32 my $sock = tcp_server();
34 # make sure stdin is not a pipe for lsof test to check for leaking pipes
35 open(my $null, '<', '/dev/null') or die 'no /dev/null: $!';
36 my $rdr = { 0 => fileno($null) };
38 # Make sure we don't clobber socket options set by systemd or similar
39 # using socket activation:
40 my ($defer_accept_val, $accf_arg);
42 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
43 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
44 defined $x or die "getsockopt: $!";
45 $defer_accept_val = unpack('i', $x);
46 if ($defer_accept_val <= 0) {
47 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
49 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
50 require PublicInbox::Daemon;
51 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
52 $accf_arg = pack('a16a240', 'dataready', '');
53 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
56 my $upath = "$tmpdir/s";
57 my $unix = unix_server($upath);
58 ok($unix, 'UNIX socket created');
60 END { kill 'TERM', $pid if defined $pid };
61 my $spawn_httpd = sub {
63 my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
64 $pid = spawn_listener(undef, $cmd, [ $sock, $unix ], $rdr);
65 ok(defined $pid, 'forked httpd process successfully');
69 ok($sock, 'sock created');
70 $spawn_httpd->('-W0');
74 my $conn = conn_for($sock, 'streaming callback');
75 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
76 ok($conn->read(my $buf, 8192), 'read response');
77 my ($head, $body) = split(/\r\n\r\n/, $buf);
78 is($body, "hello world\n", 'callback body matches expected');
82 my $conn = conn_for($sock, 'getline-die');
83 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
84 ok($conn->read(my $buf, 8192), 'read some response');
85 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
86 is($conn->read(my $nil, 8192), 0, 'read EOF');
88 my $after = capture($err);
89 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
90 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
94 my $conn = conn_for($sock, 'close-die');
95 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
96 ok($conn->read(my $buf, 8192), 'read some response');
97 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
98 is($conn->read(my $nil, 8192), 0, 'read EOF');
100 my $after = capture($err);
101 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
102 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
106 my $conn = conn_for($sock, 'excessive header');
107 $SIG{PIPE} = 'IGNORE';
108 $conn->write("GET /callback HTTP/1.0\r\n");
109 foreach my $i (1..500000) {
110 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
112 ok(!$conn->write("\r\n"), 'broken request');
113 ok($conn->read(my $buf, 8192), 'read response');
114 my ($head, $body) = split(/\r\n\r\n/, $buf);
115 like($head, qr/\b400\b/, 'got 400 response');
119 my $conn = conn_for($sock, 'excessive body Content-Length');
120 $SIG{PIPE} = 'IGNORE';
121 my $n = (10 * 1024 * 1024) + 1;
122 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
123 ok($conn->read(my $buf, 8192), 'read response');
124 my ($head, $body) = split(/\r\n\r\n/, $buf);
125 like($head, qr/\b413\b/, 'got 413 response');
129 my $conn = conn_for($sock, 'excessive body chunked');
130 $SIG{PIPE} = 'IGNORE';
131 my $n = (10 * 1024 * 1024) + 1;
132 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
133 $conn->write("\r\n".sprintf("%x\r\n", $n));
134 ok($conn->read(my $buf, 8192), 'read response');
135 my ($head, $body) = split(/\r\n\r\n/, $buf);
136 like($head, qr/\b413\b/, 'got 413 response');
140 my $conn = conn_for($sock, 'chunk with pipeline');
142 my $payload = 'b'x$n;
143 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
144 $conn->write("\r\n".sprintf("%x\r\n", $n));
145 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
146 $conn->read(my $buf, 4096);
148 $lim++ while ($conn->read($buf, 4096, bytes::length($buf)) && $lim < 9);
149 my $exp = sha1_hex($payload);
150 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
151 'chunk parser can handled pipelined requests');
154 # Unix domain sockets
156 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
157 ok($u, 'unix socket connected');
158 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
159 $u->read(my $buf, 4096);
160 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
161 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
165 my ($dest, $msg) = @_;
166 my $conn = tcp_connect($dest);
167 ok($conn, "connected for $msg");
168 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
173 my $conn = conn_for($sock, 'host-port');
174 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
175 $conn->read(my $buf, 4096);
176 my ($head, $body) = split(/\r\n\r\n/, $buf);
177 my ($addr, $port) = split(/:/, $body);
178 is($addr, $conn->sockhost, 'host matches addr');
179 is($port, $conn->sockport, 'port matches');
182 # graceful termination
184 my $conn = conn_for($sock, 'graceful termination via slow header');
185 $conn->write("GET /slow-header HTTP/1.0\r\n" .
186 "X-Check-Fifo: $fifo\r\n\r\n");
187 open my $f, '>', $fifo or die "open $fifo: $!\n";
189 ok(print($f "hello\n"), 'wrote something to fifo');
192 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
193 ok(print($f "world\n"), 'wrote else to fifo');
194 close $f or die "close fifo: $!\n";
195 $conn->read(my $buf, 8192);
196 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
197 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
198 is($body, "hello\nworld\n", 'read expected body');
199 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
200 is($?, 0, 'no error');
201 $spawn_httpd->('-W0');
205 my $conn = conn_for($sock, 'graceful termination via slow-body');
206 $conn->write("GET /slow-body HTTP/1.0\r\n" .
207 "X-Check-Fifo: $fifo\r\n\r\n");
208 open my $f, '>', $fifo or die "open $fifo: $!\n";
211 $conn->sysread($buf, 8192);
212 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
213 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
215 foreach my $c ('a'..'c') {
217 ok(print($f $c), 'wrote line to fifo');
218 $conn->sysread($buf, 8192);
219 is($buf, $c, 'got trickle for reading');
223 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
224 ok(print($f "world\n"), 'wrote else to fifo');
225 close $f or die "close fifo: $!\n";
226 $conn->sysread($buf, 8192);
227 is($buf, "world\n", 'read expected body');
228 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
229 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
230 is($?, 0, 'no error');
231 $spawn_httpd->('-W0');
234 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
236 my $str = 'abcdefghijklmnopqrstuvwxyz';
237 my $len = length $str;
238 is($len, 26, 'got the alphabet');
239 my $check_self = sub {
241 $conn->read(my $buf, 4096);
242 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
243 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
244 is($body, sha1_hex($str), 'read expected body');
248 which('curl') or skip('curl(1) missing', 4);
249 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
250 my $url = "$base/sha1";
252 pipe($r, $w) or die "pipe: $!";
253 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
254 my ($out, $err) = ('', '');
255 my $h = IPC::Run::start($cmd, $r, \$out, \$err);
257 foreach my $c ('a'..'z') {
258 print $w $c or die "failed to write to curl: $!";
261 close $w or die "close write pipe: $!";
262 close $r or die "close read pipe: $!";
263 IPC::Run::finish($h);
264 is($?, 0, 'curl exited successfully');
265 is($err, '', 'no errors from curl');
266 is($out, sha1_hex($str), 'read expected body');
268 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
272 my $r = sysread($fh, my $buf, 4096) or last;
274 $buf =~ /\A\0+\z/ or $non_zero++;
276 is($n, 30 * 1024 * 1024, 'got expected output from curl');
277 is($non_zero, 0, 'read all zeros');
281 my $conn = conn_for($sock, '1.1 pipeline together');
282 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
283 "PUT /sha1 HTTP/1.1\r\n\r\n");
286 until (scalar(@r) >= 2) {
287 my $r = $conn->sysread(my $tmp, 4096);
288 die $! unless defined $r;
289 die "EOF <$buf>" unless $r;
291 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
293 is(2, scalar @r, 'got 2 responses');
295 foreach my $hex (@r) {
296 is($hex, sha1_hex(''), "read expected body $i");
302 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
303 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
305 my $t0 = [ gettimeofday ];
306 until ($buf =~ /\r\n\r\n/s) {
307 $conn->sysread($buf, 4096, length($buf));
309 my $elapsed = tv_interval($t0, [ gettimeofday ]);
310 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
314 my $conn = conn_for($sock, 'graceful termination during slow request');
315 $conn->write("PUT /sha1 HTTP/1.0\r\n");
317 $conn->write("Content-Length: $len\r\n");
319 $conn->write("\r\n");
322 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
325 foreach my $c ('a'..'z') {
326 $n += $conn->write($c);
328 is($n, $len, 'wrote alphabet');
329 $check_self->($conn);
330 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
331 is($?, 0, 'no error');
332 $spawn_httpd->('-W0');
335 # various DoS attacks against the chunk parser:
337 local $SIG{PIPE} = 'IGNORE';
338 my $conn = conn_for($sock, '1.1 chunk header excessive');
339 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
342 while ($w = $conn->write('ffffffff')) {
345 ok($!, 'got error set in $!');
346 is($w, undef, 'write error happened');
347 ok($n > 0, 'was able to write');
348 my $r = $conn->read(my $buf, 66666);
349 ok($r > 0, 'got non-empty response');
350 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
352 $conn = conn_for($sock, '1.1 chunk trailer excessive');
353 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
354 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
357 while ($w = $conn->write("\r")) {
360 ok($!, 'got error set in $!');
361 ok($n > 0, 'wrote part of chunk end (\r)');
362 $r = $conn->read($buf, 66666);
363 ok($r > 0, 'got non-empty response');
364 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
368 my $conn = conn_for($sock, '1.1 chunked close trickle');
369 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
370 $conn->write("Transfer-encoding: chunked\r\n\r\n");
371 foreach my $x ('a'..'z') {
395 $check_self->($conn);
399 my $conn = conn_for($sock, '1.1 chunked close');
400 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
401 my $xlen = sprintf('%x', $len);
402 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
403 "$str\r\n0\r\n\r\n");
404 $check_self->($conn);
408 my $conn = conn_for($sock, 'chunked body + pipeline');
409 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
410 "Transfer-Encoding: chunked\r\n");
412 $conn->write("\r\n1\r\n");
416 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
420 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
421 $conn->sysread(my $tmp, 4096);
424 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
425 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
426 is($body, sha1_hex('a'), 'read expected body');
428 $conn->write("Connection: close\r\n");
429 $conn->write("Content-Length: $len\r\n\r\n$str");
430 $check_self->($conn);
434 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
435 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
436 "Connection: keep-alive\r\n");
438 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
440 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
441 $conn->sysread(my $tmp, 4096);
444 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
445 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
446 is($body, sha1_hex($str), 'read expected body');
448 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
449 $check_self->($conn);
453 my $conn = conn_for($sock, 'trickle body');
454 $conn->write("PUT /sha1 HTTP/1.0\r\n");
455 $conn->write("Content-Length: $len\r\n\r\n");
456 my $beg = substr($str, 0, 10);
457 my $end = substr($str, 10);
458 is($beg . $end, $str, 'substr setup correct');
463 $check_self->($conn);
467 my $conn = conn_for($sock, 'one-shot write');
468 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
469 "Content-Length: $len\r\n\r\n$str");
470 $check_self->($conn);
474 my $conn = conn_for($sock, 'trickle header, one-shot body');
475 $conn->write("PUT /sha1 HTTP/1.0\r\n");
477 $conn->write("Content-Length: $len\r\n\r\n$str");
478 $check_self->($conn);
482 my $conn = conn_for($sock, '1.1 Connnection: close');
483 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
485 $conn->write("Content-Length: $len\r\n\r\n$str");
486 $check_self->($conn);
490 my $conn = conn_for($sock, '1.1 pipeline start');
491 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
493 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
494 $conn->sysread(my $tmp, 4096);
497 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
498 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
499 is($body, sha1_hex(''), 'read expected body');
502 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
504 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
505 $conn->sysread(my $tmp, 4096);
508 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
509 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
510 is($body, sha1_hex(''), 'read expected body #2');
514 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
515 my $var = Socket::TCP_DEFER_ACCEPT();
516 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
517 is(unpack('i', $x), $defer_accept_val,
518 'TCP_DEFER_ACCEPT unchanged if previously set');
521 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
522 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
523 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
524 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
525 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
528 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
529 skip 'no lsof in PATH', 1 unless which('lsof');
530 my @lsof = `lsof -p $pid`;
531 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
532 is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
539 open my $fh, '+<', $f or die "failed to open $f: $!\n";
542 truncate($fh, 0) or die "truncate failed on $f: $!\n";