1 # Copyright (C) 2016 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
8 use Time::HiRes qw(gettimeofday tv_interval);
10 foreach my $mod (qw(Plack::Util Plack::Builder Danga::Socket
11 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 Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
22 use Socket qw(SO_KEEPALIVE IPPROTO_TCP TCP_NODELAY);
23 use POSIX qw(dup2 mkfifo :sys_wait_h);
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 = getcwd()."/t/httpd-corner.psgi";
32 LocalAddr => '127.0.0.1',
38 my $sock = IO::Socket::INET->new(%opts);
39 my $upath = "$tmpdir/s";
40 my $unix = IO::Socket::UNIX->new(
45 ok($unix, 'UNIX socket created');
47 END { kill 'TERM', $pid if defined $pid };
48 my $spawn_httpd = sub {
51 my $fl = fcntl($sock, F_GETFD, 0);
52 ok(! $!, 'no error from fcntl(F_GETFD)');
53 is($fl, FD_CLOEXEC, 'cloexec set by default (Perl behavior)');
56 # pretend to be systemd
57 dup2(fileno($sock), 3) or die "dup2 failed: $!\n";
58 dup2(fileno($unix), 4) or die "dup2 failed: $!\n";
59 my $t = IO::Handle->new_from_fd(3, 'r');
60 $t->fcntl(F_SETFD, 0);
61 my $u = IO::Handle->new_from_fd(4, 'r');
62 $u->fcntl(F_SETFD, 0);
63 $ENV{LISTEN_PID} = $$;
65 exec $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi;
68 ok(defined $pid, 'forked httpd process successfully');
72 ok($sock, 'sock created');
74 my $fl = fcntl($sock, F_GETFD, 0);
75 ok(! $!, 'no error from fcntl(F_GETFD)');
76 is($fl, FD_CLOEXEC, 'cloexec set by default (Perl behavior)');
77 $spawn_httpd->('-W0');
81 my $conn = conn_for($sock, 'streaming callback');
82 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
83 ok($conn->read(my $buf, 8192), 'read response');
84 my ($head, $body) = split(/\r\n\r\n/, $buf);
85 is($body, "hello world\n", 'callback body matches expected');
89 my $conn = conn_for($sock, 'getline-die');
90 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
91 ok($conn->read(my $buf, 8192), 'read some response');
92 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
93 is($conn->read(my $nil, 8192), 0, 'read EOF');
95 my $after = capture($err);
96 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
97 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
101 my $conn = conn_for($sock, 'close-die');
102 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
103 ok($conn->read(my $buf, 8192), 'read some response');
104 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
105 is($conn->read(my $nil, 8192), 0, 'read EOF');
107 my $after = capture($err);
108 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
109 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
113 my $conn = conn_for($sock, 'excessive header');
114 $SIG{PIPE} = 'IGNORE';
115 $conn->write("GET /callback HTTP/1.0\r\n");
116 foreach my $i (1..500000) {
117 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
119 ok(!$conn->write("\r\n"), 'broken request');
120 ok($conn->read(my $buf, 8192), 'read response');
121 my ($head, $body) = split(/\r\n\r\n/, $buf);
122 like($head, qr/\b400\b/, 'got 400 response');
126 my $conn = conn_for($sock, 'excessive body Content-Length');
127 $SIG{PIPE} = 'IGNORE';
128 my $n = (10 * 1024 * 1024) + 1;
129 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
130 ok($conn->read(my $buf, 8192), 'read response');
131 my ($head, $body) = split(/\r\n\r\n/, $buf);
132 like($head, qr/\b413\b/, 'got 413 response');
136 my $conn = conn_for($sock, 'excessive body chunked');
137 $SIG{PIPE} = 'IGNORE';
138 my $n = (10 * 1024 * 1024) + 1;
139 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
140 $conn->write("\r\n".sprintf("%x\r\n", $n));
141 ok($conn->read(my $buf, 8192), 'read response');
142 my ($head, $body) = split(/\r\n\r\n/, $buf);
143 like($head, qr/\b413\b/, 'got 413 response');
146 # Unix domain sockets
148 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
149 ok($u, 'unix socket connected');
150 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
151 $u->read(my $buf, 4096);
152 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
153 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
157 my ($sock, $msg) = @_;
158 my $conn = IO::Socket::INET->new(
159 PeerAddr => $sock->sockhost,
160 PeerPort => $sock->sockport,
162 Type => SOCK_STREAM);
163 ok($conn, "connected for $msg");
165 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
170 my $conn = conn_for($sock, 'host-port');
171 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
172 $conn->read(my $buf, 4096);
173 my ($head, $body) = split(/\r\n\r\n/, $buf);
174 my ($addr, $port) = split(/:/, $body);
175 is($addr, $conn->sockhost, 'host matches addr');
176 is($port, $conn->sockport, 'port matches');
179 # graceful termination
181 my $conn = conn_for($sock, 'graceful termination via slow header');
182 $conn->write("GET /slow-header HTTP/1.0\r\n" .
183 "X-Check-Fifo: $fifo\r\n\r\n");
184 open my $f, '>', $fifo or die "open $fifo: $!\n";
186 ok(print($f "hello\n"), 'wrote something to fifo');
189 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
190 ok(print($f "world\n"), 'wrote else to fifo');
191 close $f or die "close fifo: $!\n";
192 $conn->read(my $buf, 8192);
193 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
194 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
195 is($body, "hello\nworld\n", 'read expected body');
196 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
197 is($?, 0, 'no error');
198 $spawn_httpd->('-W0');
202 my $conn = conn_for($sock, 'graceful termination via slow-body');
203 $conn->write("GET /slow-body HTTP/1.0\r\n" .
204 "X-Check-Fifo: $fifo\r\n\r\n");
205 open my $f, '>', $fifo or die "open $fifo: $!\n";
208 $conn->sysread($buf, 8192);
209 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
210 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
212 foreach my $c ('a'..'c') {
214 ok(print($f $c), 'wrote line to fifo');
215 $conn->sysread($buf, 8192);
216 is($buf, $c, 'got trickle for reading');
220 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
221 ok(print($f "world\n"), 'wrote else to fifo');
222 close $f or die "close fifo: $!\n";
223 $conn->sysread($buf, 8192);
224 is($buf, "world\n", 'read expected body');
225 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
226 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
227 is($?, 0, 'no error');
228 $spawn_httpd->('-W0');
231 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
233 my $str = 'abcdefghijklmnopqrstuvwxyz';
234 my $len = length $str;
235 is($len, 26, 'got the alphabet');
236 my $check_self = sub {
238 $conn->read(my $buf, 4096);
239 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
240 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
241 is($body, sha1_hex($str), 'read expected body');
248 foreach my $p (split(':', $ENV{PATH})) {
249 -x "$p/curl" or next;
254 $have_curl or skip('curl(1) missing', $ntest);
255 my $url = 'http://' . $sock->sockhost . ':' . $sock->sockport . '/sha1';
257 pipe($r, $w) or die "pipe: $!";
258 my $tout = IO::File->new_tmpfile or die "new_tmpfile: $!";
260 defined $pid or die "fork: $!";
261 my @cmd = (qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url);
263 dup2(fileno($r), 0) or die "redirect stdin failed: $!\n";
264 dup2(fileno($tout), 1) or die "redirect stdout failed: $!\n";
265 exec(@cmd) or die 'exec `' . join(' '). "' failed: $!\n";
268 foreach my $c ('a'..'z') {
269 print $w $c or die "failed to write to curl: $!";
272 close $w or die "close write pipe: $!";
273 close $r or die "close read pipe: $!";
274 my $kid = waitpid $pid, 0;
275 is($?, 0, 'curl exited successfully');
276 $tout->sysseek(0, SEEK_SET);
277 $tout->sysread(my $buf, 100);
278 is($buf, sha1_hex($str), 'read expected body');
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');
518 open my $fh, '+<', $f or die "failed to open $f: $!\n";
521 truncate($fh, 0) or die "truncate failed on $f: $!\n";