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 $psgi = "./t/httpd-corner.psgi";
30 my $sock = tcp_server() or die;
32 # make sure stdin is not a pipe for lsof test to check for leaking pipes
33 open(STDIN, '<', '/dev/null') or die 'no /dev/null: $!';
35 # Make sure we don't clobber socket options set by systemd or similar
36 # using socket activation:
37 my ($defer_accept_val, $accf_arg);
39 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
40 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
41 defined $x or die "getsockopt: $!";
42 $defer_accept_val = unpack('i', $x);
43 if ($defer_accept_val <= 0) {
44 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
46 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
47 require PublicInbox::Daemon;
48 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
49 $accf_arg = pack('a16a240', 'dataready', '');
50 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
54 my $s = IO::Socket::UNIX->new(
56 Type => Socket::SOCK_STREAM(),
63 my $upath = "$tmpdir/s";
64 my $unix = unix_server($upath);
65 ok($unix, 'UNIX socket created');
67 my $spawn_httpd = sub {
69 my $cmd = [ '-httpd', @args, "--stdout=$out", "--stderr=$err", $psgi ];
70 $td = start_script($cmd, undef, { 3 => $sock, 4 => $unix });
74 if ('test worker death') {
75 my $conn = conn_for($sock, 'killed worker');
76 $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
78 while (defined(my $line = $conn->getline)) {
79 next unless $line eq "\r\n";
80 chomp($pid = $conn->getline);
83 like($pid, qr/\A[0-9]+\z/, '/pid response');
84 is(kill('KILL', $pid), 1, 'killed worker');
85 is($conn->getline, undef, 'worker died and EOF-ed client');
87 $conn = conn_for($sock, 'respawned worker');
88 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
89 ok($conn->read(my $buf, 8192), 'read response');
90 my ($head, $body) = split(/\r\n\r\n/, $buf);
92 like($body, qr/\A[0-9]+\z/, '/pid response');
93 isnt($body, $pid, 'respawned worker');
97 my $conn = conn_for($sock, 'streaming callback');
98 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
99 ok($conn->read(my $buf, 8192), 'read response');
100 my ($head, $body) = split(/\r\n\r\n/, $buf);
101 is($body, "hello world\n", 'callback body matches expected');
105 my $conn = conn_for($sock, 'getline-die');
106 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
107 ok($conn->read(my $buf, 8192), 'read some response');
108 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
109 is($conn->read(my $nil, 8192), 0, 'read EOF');
111 my $after = capture($err);
112 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
113 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
117 my $conn = conn_for($sock, 'close-die');
118 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
119 ok($conn->read(my $buf, 8192), 'read some response');
120 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
121 is($conn->read(my $nil, 8192), 0, 'read EOF');
123 my $after = capture($err);
124 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
125 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
129 my $conn = conn_for($sock, 'excessive header');
130 $SIG{PIPE} = 'IGNORE';
131 $conn->write("GET /callback HTTP/1.0\r\n");
132 foreach my $i (1..500000) {
133 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
135 ok(!$conn->write("\r\n"), 'broken request');
136 ok($conn->read(my $buf, 8192), 'read response');
137 my ($head, $body) = split(/\r\n\r\n/, $buf);
138 like($head, qr/\b400\b/, 'got 400 response');
142 my $conn = conn_for($sock, 'excessive body Content-Length');
143 $SIG{PIPE} = 'IGNORE';
144 my $n = (10 * 1024 * 1024) + 1;
145 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
146 ok($conn->read(my $buf, 8192), 'read response');
147 my ($head, $body) = split(/\r\n\r\n/, $buf);
148 like($head, qr/\b413\b/, 'got 413 response');
152 my $conn = conn_for($sock, 'excessive body chunked');
153 $SIG{PIPE} = 'IGNORE';
154 my $n = (10 * 1024 * 1024) + 1;
155 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
156 $conn->write("\r\n".sprintf("%x\r\n", $n));
157 ok($conn->read(my $buf, 8192), 'read response');
158 my ($head, $body) = split(/\r\n\r\n/, $buf);
159 like($head, qr/\b413\b/, 'got 413 response');
163 my $conn = conn_for($sock, 'chunk with pipeline');
165 my $payload = 'b'x$n;
166 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
167 $conn->write("\r\n".sprintf("%x\r\n", $n));
168 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
169 $conn->read(my $buf, 4096);
171 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
172 my $exp = sha1_hex($payload);
173 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
174 'chunk parser can handled pipelined requests');
177 # Unix domain sockets
179 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
180 ok($u, 'unix socket connected');
181 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
182 $u->read(my $buf, 4096);
183 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
184 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
188 my ($dest, $msg) = @_;
189 my $conn = tcp_connect($dest);
190 ok($conn, "connected for $msg");
191 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
196 my $conn = conn_for($sock, 'host-port');
197 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
198 $conn->read(my $buf, 4096);
199 my ($head, $body) = split(/\r\n\r\n/, $buf);
200 my ($addr, $port) = split(/:/, $body);
201 is($addr, $conn->sockhost, 'host matches addr');
202 is($port, $conn->sockport, 'port matches');
205 # graceful termination
207 my $conn = conn_for($sock, 'graceful termination via slow header');
208 $conn->write("GET /slow-header HTTP/1.0\r\n" .
209 "X-Check-Fifo: $fifo\r\n\r\n");
210 open my $f, '>', $fifo or die "open $fifo: $!\n";
212 ok(print($f "hello\n"), 'wrote something to fifo');
213 is($td->kill, 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');
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');
242 is($td->kill, 1, 'started graceful shutdown');
243 ok(print($f "world\n"), 'wrote else to fifo');
244 close $f or die "close fifo: $!\n";
245 $conn->sysread($buf, 8192);
246 is($buf, "world\n", 'read expected body');
247 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
249 is($?, 0, 'no error');
250 $spawn_httpd->('-W0');
253 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
255 my $str = 'abcdefghijklmnopqrstuvwxyz';
256 my $len = length $str;
257 is($len, 26, 'got the alphabet');
258 my $check_self = sub {
260 $conn->read(my $buf, 4096);
261 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
262 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
263 is($body, sha1_hex($str), 'read expected body');
267 which('curl') or skip('curl(1) missing', 4);
268 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
269 my $url = "$base/sha1";
271 pipe($r, $w) or die "pipe: $!";
272 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
273 open my $cout, '+>', undef or die;
274 open my $cerr, '>', undef or die;
275 my $rdr = { 0 => fileno($r), 1 => fileno($cout), 2 => fileno($cerr) };
276 my $pid = spawn($cmd, undef, $rdr);
277 close $r or die "close read pipe: $!";
278 foreach my $c ('a'..'z') {
279 print $w $c or die "failed to write to curl: $!";
282 close $w or die "close write pipe: $!";
284 is($?, 0, 'curl exited successfully');
285 is(-s $cerr, 0, 'no errors from curl');
286 $cout->seek(0, SEEK_SET);
287 is(<$cout>, sha1_hex($str), 'read expected body');
289 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
293 my $r = sysread($fh, my $buf, 4096) or last;
295 $buf =~ /\A\0+\z/ or $non_zero++;
297 close $fh or die "curl errored out \$?=$?";
298 is($n, 30 * 1024 * 1024, 'got expected output from curl');
299 is($non_zero, 0, 'read all zeros');
303 my $conn = conn_for($sock, '1.1 pipeline together');
304 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
305 "PUT /sha1 HTTP/1.1\r\n\r\n");
308 until (scalar(@r) >= 2) {
309 my $r = $conn->sysread(my $tmp, 4096);
310 die $! unless defined $r;
311 die "EOF <$buf>" unless $r;
313 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
315 is(2, scalar @r, 'got 2 responses');
317 foreach my $hex (@r) {
318 is($hex, sha1_hex(''), "read expected body $i");
324 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
325 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
327 my $t0 = [ gettimeofday ];
328 until ($buf =~ /\r\n\r\n/s) {
329 $conn->sysread($buf, 4096, length($buf));
331 my $elapsed = tv_interval($t0, [ gettimeofday ]);
332 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
336 my $conn = conn_for($sock, 'graceful termination during slow request');
337 $conn->write("PUT /sha1 HTTP/1.0\r\n");
339 $conn->write("Content-Length: $len\r\n");
341 $conn->write("\r\n");
342 is($td->kill, 1, 'started graceful shutdown');
345 foreach my $c ('a'..'z') {
346 $n += $conn->write($c);
348 is($n, $len, 'wrote alphabet');
349 $check_self->($conn);
351 is($?, 0, 'no error');
352 $spawn_httpd->('-W0');
355 # various DoS attacks against the chunk parser:
357 local $SIG{PIPE} = 'IGNORE';
358 my $conn = conn_for($sock, '1.1 chunk header excessive');
359 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
362 while ($w = $conn->write('ffffffff')) {
365 ok($!, 'got error set in $!');
366 is($w, undef, 'write error happened');
367 ok($n > 0, 'was able to write');
368 my $r = $conn->read(my $buf, 66666);
369 ok($r > 0, 'got non-empty response');
370 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
372 $conn = conn_for($sock, '1.1 chunk trailer excessive');
373 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
374 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
377 while ($w = $conn->write("\r")) {
380 ok($!, 'got error set in $!');
381 ok($n > 0, 'wrote part of chunk end (\r)');
382 $r = $conn->read($buf, 66666);
383 ok($r > 0, 'got non-empty response');
384 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
388 my $conn = conn_for($sock, '1.1 chunked close trickle');
389 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
390 $conn->write("Transfer-encoding: chunked\r\n\r\n");
391 foreach my $x ('a'..'z') {
415 $check_self->($conn);
419 my $conn = conn_for($sock, '1.1 chunked close');
420 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
421 my $xlen = sprintf('%x', $len);
422 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
423 "$str\r\n0\r\n\r\n");
424 $check_self->($conn);
428 my $conn = conn_for($sock, 'chunked body + pipeline');
429 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
430 "Transfer-Encoding: chunked\r\n");
432 $conn->write("\r\n1\r\n");
436 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
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('a'), 'read expected body');
448 $conn->write("Connection: close\r\n");
449 $conn->write("Content-Length: $len\r\n\r\n$str");
450 $check_self->($conn);
454 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
455 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
456 "Connection: keep-alive\r\n");
458 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
460 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
461 $conn->sysread(my $tmp, 4096);
464 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
465 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
466 is($body, sha1_hex($str), 'read expected body');
468 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
469 $check_self->($conn);
473 my $conn = conn_for($sock, 'trickle body');
474 $conn->write("PUT /sha1 HTTP/1.0\r\n");
475 $conn->write("Content-Length: $len\r\n\r\n");
476 my $beg = substr($str, 0, 10);
477 my $end = substr($str, 10);
478 is($beg . $end, $str, 'substr setup correct');
483 $check_self->($conn);
487 my $conn = conn_for($sock, 'one-shot write');
488 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
489 "Content-Length: $len\r\n\r\n$str");
490 $check_self->($conn);
494 my $conn = conn_for($sock, 'trickle header, one-shot body');
495 $conn->write("PUT /sha1 HTTP/1.0\r\n");
497 $conn->write("Content-Length: $len\r\n\r\n$str");
498 $check_self->($conn);
502 my $conn = conn_for($sock, '1.1 Connnection: close');
503 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
505 $conn->write("Content-Length: $len\r\n\r\n$str");
506 $check_self->($conn);
510 my $conn = conn_for($sock, '1.1 pipeline start');
511 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
513 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
514 $conn->sysread(my $tmp, 4096);
517 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
518 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
519 is($body, sha1_hex(''), 'read expected body');
522 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
524 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
525 $conn->sysread(my $tmp, 4096);
528 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
529 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
530 is($body, sha1_hex(''), 'read expected body #2');
534 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
535 my $var = Socket::TCP_DEFER_ACCEPT();
536 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
537 is(unpack('i', $x), $defer_accept_val,
538 'TCP_DEFER_ACCEPT unchanged if previously set');
541 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
542 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
543 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
544 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
545 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
549 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
550 skip 'no lsof in PATH', 1 unless which('lsof');
551 my @lsof = `lsof -p $td->{pid}`;
552 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
554 # filter out pipes inherited from the parent
555 my @this = `lsof -p $$`;
559 my @f = split(' ', $_);
561 $bad = $_ if $inode !~ /\A[0-9]+\z/;
563 } grep (/\bpipe\b/, @_);
565 my %child = extract_inodes(@lsof);
566 my %parent = extract_inodes(@this);
567 skip("inode not in expected format: $bad", 1) if defined($bad);
568 delete @child{(keys %parent)};
569 is_deeply([], [keys %child], 'no extra pipes with -W0');
576 open my $fh, '+<', $f or die "failed to open $f: $!\n";
579 truncate($fh, 0) or die "truncate failed on $f: $!\n";