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.0\r\n\r\n");
80 ok($conn->read(my $buf, 8192), 'read response');
81 my ($head, $body) = split(/\r\n\r\n/, $buf);
82 like($body, qr/\A[0-9]+\z/, '/pid response');
84 is(kill('KILL', $pid), 1, 'killed worker');
86 $conn = conn_for($sock, 'respawned worker');
87 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
88 ok($conn->read($buf, 8192), 'read response');
89 ($head, $body) = split(/\r\n\r\n/, $buf);
90 like($body, qr/\A[0-9]+\z/, '/pid response');
91 isnt($body, $pid, 'respawned worker');
95 my $conn = conn_for($sock, 'streaming callback');
96 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
97 ok($conn->read(my $buf, 8192), 'read response');
98 my ($head, $body) = split(/\r\n\r\n/, $buf);
99 is($body, "hello world\n", 'callback body matches expected');
103 my $conn = conn_for($sock, 'getline-die');
104 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
105 ok($conn->read(my $buf, 8192), 'read some response');
106 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
107 is($conn->read(my $nil, 8192), 0, 'read EOF');
109 my $after = capture($err);
110 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
111 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
115 my $conn = conn_for($sock, 'close-die');
116 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
117 ok($conn->read(my $buf, 8192), 'read some response');
118 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
119 is($conn->read(my $nil, 8192), 0, 'read EOF');
121 my $after = capture($err);
122 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
123 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
127 my $conn = conn_for($sock, 'excessive header');
128 $SIG{PIPE} = 'IGNORE';
129 $conn->write("GET /callback HTTP/1.0\r\n");
130 foreach my $i (1..500000) {
131 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
133 ok(!$conn->write("\r\n"), 'broken request');
134 ok($conn->read(my $buf, 8192), 'read response');
135 my ($head, $body) = split(/\r\n\r\n/, $buf);
136 like($head, qr/\b400\b/, 'got 400 response');
140 my $conn = conn_for($sock, 'excessive body Content-Length');
141 $SIG{PIPE} = 'IGNORE';
142 my $n = (10 * 1024 * 1024) + 1;
143 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
144 ok($conn->read(my $buf, 8192), 'read response');
145 my ($head, $body) = split(/\r\n\r\n/, $buf);
146 like($head, qr/\b413\b/, 'got 413 response');
150 my $conn = conn_for($sock, 'excessive body chunked');
151 $SIG{PIPE} = 'IGNORE';
152 my $n = (10 * 1024 * 1024) + 1;
153 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
154 $conn->write("\r\n".sprintf("%x\r\n", $n));
155 ok($conn->read(my $buf, 8192), 'read response');
156 my ($head, $body) = split(/\r\n\r\n/, $buf);
157 like($head, qr/\b413\b/, 'got 413 response');
161 my $conn = conn_for($sock, 'chunk with pipeline');
163 my $payload = 'b'x$n;
164 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
165 $conn->write("\r\n".sprintf("%x\r\n", $n));
166 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
167 $conn->read(my $buf, 4096);
169 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
170 my $exp = sha1_hex($payload);
171 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
172 'chunk parser can handled pipelined requests');
175 # Unix domain sockets
177 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
178 ok($u, 'unix socket connected');
179 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
180 $u->read(my $buf, 4096);
181 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
182 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
186 my ($dest, $msg) = @_;
187 my $conn = tcp_connect($dest);
188 ok($conn, "connected for $msg");
189 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
194 my $conn = conn_for($sock, 'host-port');
195 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
196 $conn->read(my $buf, 4096);
197 my ($head, $body) = split(/\r\n\r\n/, $buf);
198 my ($addr, $port) = split(/:/, $body);
199 is($addr, $conn->sockhost, 'host matches addr');
200 is($port, $conn->sockport, 'port matches');
203 # graceful termination
205 my $conn = conn_for($sock, 'graceful termination via slow header');
206 $conn->write("GET /slow-header HTTP/1.0\r\n" .
207 "X-Check-Fifo: $fifo\r\n\r\n");
208 open my $f, '>', $fifo or die "open $fifo: $!\n";
210 ok(print($f "hello\n"), 'wrote something to fifo');
213 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
214 ok(print($f "world\n"), 'wrote else to fifo');
215 close $f or die "close fifo: $!\n";
216 $conn->read(my $buf, 8192);
217 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
218 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
219 is($body, "hello\nworld\n", 'read expected body');
220 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
221 is($?, 0, 'no error');
222 $spawn_httpd->('-W0');
226 my $conn = conn_for($sock, 'graceful termination via slow-body');
227 $conn->write("GET /slow-body HTTP/1.0\r\n" .
228 "X-Check-Fifo: $fifo\r\n\r\n");
229 open my $f, '>', $fifo or die "open $fifo: $!\n";
232 $conn->sysread($buf, 8192);
233 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
234 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
236 foreach my $c ('a'..'c') {
238 ok(print($f $c), 'wrote line to fifo');
239 $conn->sysread($buf, 8192);
240 is($buf, $c, 'got trickle for reading');
244 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
245 ok(print($f "world\n"), 'wrote else to fifo');
246 close $f or die "close fifo: $!\n";
247 $conn->sysread($buf, 8192);
248 is($buf, "world\n", 'read expected body');
249 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
250 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
251 is($?, 0, 'no error');
252 $spawn_httpd->('-W0');
255 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
257 my $str = 'abcdefghijklmnopqrstuvwxyz';
258 my $len = length $str;
259 is($len, 26, 'got the alphabet');
260 my $check_self = sub {
262 $conn->read(my $buf, 4096);
263 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
264 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
265 is($body, sha1_hex($str), 'read expected body');
269 which('curl') or skip('curl(1) missing', 4);
270 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
271 my $url = "$base/sha1";
273 pipe($r, $w) or die "pipe: $!";
274 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
275 open my $cout, '+>', undef or die;
276 open my $cerr, '>', undef or die;
277 my $rdr = { 0 => fileno($r), 1 => fileno($cout), 2 => fileno($cerr) };
278 my $pid = spawn($cmd, undef, $rdr);
279 close $r or die "close read pipe: $!";
280 foreach my $c ('a'..'z') {
281 print $w $c or die "failed to write to curl: $!";
284 close $w or die "close write pipe: $!";
286 is($?, 0, 'curl exited successfully');
287 is(-s $cerr, 0, 'no errors from curl');
288 $cout->seek(0, SEEK_SET);
289 is(<$cout>, sha1_hex($str), 'read expected body');
291 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
295 my $r = sysread($fh, my $buf, 4096) or last;
297 $buf =~ /\A\0+\z/ or $non_zero++;
299 close $fh or die "curl errored out \$?=$?";
300 is($n, 30 * 1024 * 1024, 'got expected output from curl');
301 is($non_zero, 0, 'read all zeros');
305 my $conn = conn_for($sock, '1.1 pipeline together');
306 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
307 "PUT /sha1 HTTP/1.1\r\n\r\n");
310 until (scalar(@r) >= 2) {
311 my $r = $conn->sysread(my $tmp, 4096);
312 die $! unless defined $r;
313 die "EOF <$buf>" unless $r;
315 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
317 is(2, scalar @r, 'got 2 responses');
319 foreach my $hex (@r) {
320 is($hex, sha1_hex(''), "read expected body $i");
326 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
327 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
329 my $t0 = [ gettimeofday ];
330 until ($buf =~ /\r\n\r\n/s) {
331 $conn->sysread($buf, 4096, length($buf));
333 my $elapsed = tv_interval($t0, [ gettimeofday ]);
334 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
338 my $conn = conn_for($sock, 'graceful termination during slow request');
339 $conn->write("PUT /sha1 HTTP/1.0\r\n");
341 $conn->write("Content-Length: $len\r\n");
343 $conn->write("\r\n");
346 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
349 foreach my $c ('a'..'z') {
350 $n += $conn->write($c);
352 is($n, $len, 'wrote alphabet');
353 $check_self->($conn);
354 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
355 is($?, 0, 'no error');
356 $spawn_httpd->('-W0');
359 # various DoS attacks against the chunk parser:
361 local $SIG{PIPE} = 'IGNORE';
362 my $conn = conn_for($sock, '1.1 chunk header excessive');
363 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
366 while ($w = $conn->write('ffffffff')) {
369 ok($!, 'got error set in $!');
370 is($w, undef, 'write error happened');
371 ok($n > 0, 'was able to write');
372 my $r = $conn->read(my $buf, 66666);
373 ok($r > 0, 'got non-empty response');
374 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
376 $conn = conn_for($sock, '1.1 chunk trailer excessive');
377 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
378 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
381 while ($w = $conn->write("\r")) {
384 ok($!, 'got error set in $!');
385 ok($n > 0, 'wrote part of chunk end (\r)');
386 $r = $conn->read($buf, 66666);
387 ok($r > 0, 'got non-empty response');
388 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
392 my $conn = conn_for($sock, '1.1 chunked close trickle');
393 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
394 $conn->write("Transfer-encoding: chunked\r\n\r\n");
395 foreach my $x ('a'..'z') {
419 $check_self->($conn);
423 my $conn = conn_for($sock, '1.1 chunked close');
424 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
425 my $xlen = sprintf('%x', $len);
426 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
427 "$str\r\n0\r\n\r\n");
428 $check_self->($conn);
432 my $conn = conn_for($sock, 'chunked body + pipeline');
433 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
434 "Transfer-Encoding: chunked\r\n");
436 $conn->write("\r\n1\r\n");
440 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
444 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
445 $conn->sysread(my $tmp, 4096);
448 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
449 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
450 is($body, sha1_hex('a'), 'read expected body');
452 $conn->write("Connection: close\r\n");
453 $conn->write("Content-Length: $len\r\n\r\n$str");
454 $check_self->($conn);
458 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
459 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
460 "Connection: keep-alive\r\n");
462 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
464 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
465 $conn->sysread(my $tmp, 4096);
468 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
469 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
470 is($body, sha1_hex($str), 'read expected body');
472 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
473 $check_self->($conn);
477 my $conn = conn_for($sock, 'trickle body');
478 $conn->write("PUT /sha1 HTTP/1.0\r\n");
479 $conn->write("Content-Length: $len\r\n\r\n");
480 my $beg = substr($str, 0, 10);
481 my $end = substr($str, 10);
482 is($beg . $end, $str, 'substr setup correct');
487 $check_self->($conn);
491 my $conn = conn_for($sock, 'one-shot write');
492 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
493 "Content-Length: $len\r\n\r\n$str");
494 $check_self->($conn);
498 my $conn = conn_for($sock, 'trickle header, one-shot body');
499 $conn->write("PUT /sha1 HTTP/1.0\r\n");
501 $conn->write("Content-Length: $len\r\n\r\n$str");
502 $check_self->($conn);
506 my $conn = conn_for($sock, '1.1 Connnection: close');
507 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
509 $conn->write("Content-Length: $len\r\n\r\n$str");
510 $check_self->($conn);
514 my $conn = conn_for($sock, '1.1 pipeline start');
515 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
517 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
518 $conn->sysread(my $tmp, 4096);
521 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
522 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
523 is($body, sha1_hex(''), 'read expected body');
526 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
528 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
529 $conn->sysread(my $tmp, 4096);
532 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
533 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
534 is($body, sha1_hex(''), 'read expected body #2');
538 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
539 my $var = Socket::TCP_DEFER_ACCEPT();
540 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
541 is(unpack('i', $x), $defer_accept_val,
542 'TCP_DEFER_ACCEPT unchanged if previously set');
545 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
546 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
547 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
548 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
549 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
552 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
553 skip 'no lsof in PATH', 1 unless which('lsof');
554 my @lsof = `lsof -p $pid`;
555 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
556 is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
563 open my $fh, '+<', $f or die "failed to open $f: $!\n";
566 truncate($fh, 0) or die "truncate failed on $f: $!\n";