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();
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: $!";
54 my $upath = "$tmpdir/s";
55 my $unix = unix_server($upath);
56 ok($unix, 'UNIX socket created');
58 END { kill 'TERM', $pid if defined $pid };
59 my $spawn_httpd = sub {
61 my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
62 $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
63 ok(defined $pid, 'forked httpd process successfully');
67 ok($sock, 'sock created');
68 $spawn_httpd->('-W0');
72 my $conn = conn_for($sock, 'streaming callback');
73 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
74 ok($conn->read(my $buf, 8192), 'read response');
75 my ($head, $body) = split(/\r\n\r\n/, $buf);
76 is($body, "hello world\n", 'callback body matches expected');
80 my $conn = conn_for($sock, 'getline-die');
81 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
82 ok($conn->read(my $buf, 8192), 'read some response');
83 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
84 is($conn->read(my $nil, 8192), 0, 'read EOF');
86 my $after = capture($err);
87 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
88 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
92 my $conn = conn_for($sock, 'close-die');
93 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
94 ok($conn->read(my $buf, 8192), 'read some response');
95 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
96 is($conn->read(my $nil, 8192), 0, 'read EOF');
98 my $after = capture($err);
99 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
100 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
104 my $conn = conn_for($sock, 'excessive header');
105 $SIG{PIPE} = 'IGNORE';
106 $conn->write("GET /callback HTTP/1.0\r\n");
107 foreach my $i (1..500000) {
108 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
110 ok(!$conn->write("\r\n"), 'broken request');
111 ok($conn->read(my $buf, 8192), 'read response');
112 my ($head, $body) = split(/\r\n\r\n/, $buf);
113 like($head, qr/\b400\b/, 'got 400 response');
117 my $conn = conn_for($sock, 'excessive body Content-Length');
118 $SIG{PIPE} = 'IGNORE';
119 my $n = (10 * 1024 * 1024) + 1;
120 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
121 ok($conn->read(my $buf, 8192), 'read response');
122 my ($head, $body) = split(/\r\n\r\n/, $buf);
123 like($head, qr/\b413\b/, 'got 413 response');
127 my $conn = conn_for($sock, 'excessive body chunked');
128 $SIG{PIPE} = 'IGNORE';
129 my $n = (10 * 1024 * 1024) + 1;
130 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
131 $conn->write("\r\n".sprintf("%x\r\n", $n));
132 ok($conn->read(my $buf, 8192), 'read response');
133 my ($head, $body) = split(/\r\n\r\n/, $buf);
134 like($head, qr/\b413\b/, 'got 413 response');
138 my $conn = conn_for($sock, 'chunk with pipeline');
140 my $payload = 'b'x$n;
141 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
142 $conn->write("\r\n".sprintf("%x\r\n", $n));
143 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
144 $conn->read(my $buf, 4096);
146 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
147 my $exp = sha1_hex($payload);
148 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
149 'chunk parser can handled pipelined requests');
152 # Unix domain sockets
154 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
155 ok($u, 'unix socket connected');
156 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
157 $u->read(my $buf, 4096);
158 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
159 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
163 my ($dest, $msg) = @_;
164 my $conn = tcp_connect($dest);
165 ok($conn, "connected for $msg");
166 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
171 my $conn = conn_for($sock, 'host-port');
172 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
173 $conn->read(my $buf, 4096);
174 my ($head, $body) = split(/\r\n\r\n/, $buf);
175 my ($addr, $port) = split(/:/, $body);
176 is($addr, $conn->sockhost, 'host matches addr');
177 is($port, $conn->sockport, 'port matches');
180 # graceful termination
182 my $conn = conn_for($sock, 'graceful termination via slow header');
183 $conn->write("GET /slow-header HTTP/1.0\r\n" .
184 "X-Check-Fifo: $fifo\r\n\r\n");
185 open my $f, '>', $fifo or die "open $fifo: $!\n";
187 ok(print($f "hello\n"), 'wrote something to fifo');
190 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
191 ok(print($f "world\n"), 'wrote else to fifo');
192 close $f or die "close fifo: $!\n";
193 $conn->read(my $buf, 8192);
194 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
195 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
196 is($body, "hello\nworld\n", 'read expected body');
197 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
198 is($?, 0, 'no error');
199 $spawn_httpd->('-W0');
203 my $conn = conn_for($sock, 'graceful termination via slow-body');
204 $conn->write("GET /slow-body HTTP/1.0\r\n" .
205 "X-Check-Fifo: $fifo\r\n\r\n");
206 open my $f, '>', $fifo or die "open $fifo: $!\n";
209 $conn->sysread($buf, 8192);
210 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
211 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
213 foreach my $c ('a'..'c') {
215 ok(print($f $c), 'wrote line to fifo');
216 $conn->sysread($buf, 8192);
217 is($buf, $c, 'got trickle for reading');
221 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
222 ok(print($f "world\n"), 'wrote else to fifo');
223 close $f or die "close fifo: $!\n";
224 $conn->sysread($buf, 8192);
225 is($buf, "world\n", 'read expected body');
226 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
227 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
228 is($?, 0, 'no error');
229 $spawn_httpd->('-W0');
232 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
234 my $str = 'abcdefghijklmnopqrstuvwxyz';
235 my $len = length $str;
236 is($len, 26, 'got the alphabet');
237 my $check_self = sub {
239 $conn->read(my $buf, 4096);
240 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
241 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
242 is($body, sha1_hex($str), 'read expected body');
246 which('curl') or skip('curl(1) missing', 4);
247 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
248 my $url = "$base/sha1";
250 pipe($r, $w) or die "pipe: $!";
251 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
252 open my $cout, '+>', undef or die;
253 open my $cerr, '>', undef or die;
254 my $rdr = { 0 => fileno($r), 1 => fileno($cout), 2 => fileno($cerr) };
255 my $pid = spawn($cmd, undef, $rdr);
256 close $r or die "close read pipe: $!";
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: $!";
263 is($?, 0, 'curl exited successfully');
264 is(-s $cerr, 0, 'no errors from curl');
265 $cout->seek(0, SEEK_SET);
266 is(<$cout>, 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 close $fh or die "curl errored out \$?=$?";
277 is($n, 30 * 1024 * 1024, 'got expected output from curl');
278 is($non_zero, 0, 'read all zeros');
282 my $conn = conn_for($sock, '1.1 pipeline together');
283 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
284 "PUT /sha1 HTTP/1.1\r\n\r\n");
287 until (scalar(@r) >= 2) {
288 my $r = $conn->sysread(my $tmp, 4096);
289 die $! unless defined $r;
290 die "EOF <$buf>" unless $r;
292 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
294 is(2, scalar @r, 'got 2 responses');
296 foreach my $hex (@r) {
297 is($hex, sha1_hex(''), "read expected body $i");
303 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
304 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
306 my $t0 = [ gettimeofday ];
307 until ($buf =~ /\r\n\r\n/s) {
308 $conn->sysread($buf, 4096, length($buf));
310 my $elapsed = tv_interval($t0, [ gettimeofday ]);
311 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
315 my $conn = conn_for($sock, 'graceful termination during slow request');
316 $conn->write("PUT /sha1 HTTP/1.0\r\n");
318 $conn->write("Content-Length: $len\r\n");
320 $conn->write("\r\n");
323 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
326 foreach my $c ('a'..'z') {
327 $n += $conn->write($c);
329 is($n, $len, 'wrote alphabet');
330 $check_self->($conn);
331 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
332 is($?, 0, 'no error');
333 $spawn_httpd->('-W0');
336 # various DoS attacks against the chunk parser:
338 local $SIG{PIPE} = 'IGNORE';
339 my $conn = conn_for($sock, '1.1 chunk header excessive');
340 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
343 while ($w = $conn->write('ffffffff')) {
346 ok($!, 'got error set in $!');
347 is($w, undef, 'write error happened');
348 ok($n > 0, 'was able to write');
349 my $r = $conn->read(my $buf, 66666);
350 ok($r > 0, 'got non-empty response');
351 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
353 $conn = conn_for($sock, '1.1 chunk trailer excessive');
354 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
355 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
358 while ($w = $conn->write("\r")) {
361 ok($!, 'got error set in $!');
362 ok($n > 0, 'wrote part of chunk end (\r)');
363 $r = $conn->read($buf, 66666);
364 ok($r > 0, 'got non-empty response');
365 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
369 my $conn = conn_for($sock, '1.1 chunked close trickle');
370 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
371 $conn->write("Transfer-encoding: chunked\r\n\r\n");
372 foreach my $x ('a'..'z') {
396 $check_self->($conn);
400 my $conn = conn_for($sock, '1.1 chunked close');
401 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
402 my $xlen = sprintf('%x', $len);
403 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
404 "$str\r\n0\r\n\r\n");
405 $check_self->($conn);
409 my $conn = conn_for($sock, 'chunked body + pipeline');
410 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
411 "Transfer-Encoding: chunked\r\n");
413 $conn->write("\r\n1\r\n");
417 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
421 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
422 $conn->sysread(my $tmp, 4096);
425 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
426 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
427 is($body, sha1_hex('a'), 'read expected body');
429 $conn->write("Connection: close\r\n");
430 $conn->write("Content-Length: $len\r\n\r\n$str");
431 $check_self->($conn);
435 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
436 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
437 "Connection: keep-alive\r\n");
439 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
441 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
442 $conn->sysread(my $tmp, 4096);
445 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
446 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
447 is($body, sha1_hex($str), 'read expected body');
449 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
450 $check_self->($conn);
454 my $conn = conn_for($sock, 'trickle body');
455 $conn->write("PUT /sha1 HTTP/1.0\r\n");
456 $conn->write("Content-Length: $len\r\n\r\n");
457 my $beg = substr($str, 0, 10);
458 my $end = substr($str, 10);
459 is($beg . $end, $str, 'substr setup correct');
464 $check_self->($conn);
468 my $conn = conn_for($sock, 'one-shot write');
469 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
470 "Content-Length: $len\r\n\r\n$str");
471 $check_self->($conn);
475 my $conn = conn_for($sock, 'trickle header, one-shot body');
476 $conn->write("PUT /sha1 HTTP/1.0\r\n");
478 $conn->write("Content-Length: $len\r\n\r\n$str");
479 $check_self->($conn);
483 my $conn = conn_for($sock, '1.1 Connnection: close');
484 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
486 $conn->write("Content-Length: $len\r\n\r\n$str");
487 $check_self->($conn);
491 my $conn = conn_for($sock, '1.1 pipeline start');
492 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
494 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
495 $conn->sysread(my $tmp, 4096);
498 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
499 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
500 is($body, sha1_hex(''), 'read expected body');
503 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
505 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
506 $conn->sysread(my $tmp, 4096);
509 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
510 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
511 is($body, sha1_hex(''), 'read expected body #2');
515 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
516 my $var = Socket::TCP_DEFER_ACCEPT();
517 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
518 is(unpack('i', $x), $defer_accept_val,
519 'TCP_DEFER_ACCEPT unchanged if previously set');
522 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
523 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
524 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
525 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
526 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
529 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
530 skip 'no lsof in PATH', 1 unless which('lsof');
531 my @lsof = `lsof -p $pid`;
532 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
533 is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
540 open my $fh, '+<', $f or die "failed to open $f: $!\n";
543 truncate($fh, 0) or die "truncate failed on $f: $!\n";