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');
247 foreach my $p (split(':', $ENV{PATH})) {
248 -x "$p/curl" or next;
253 $have_curl or skip('curl(1) missing', $ntest);
254 my $url = 'http://' . $sock->sockhost . ':' . $sock->sockport . '/sha1';
256 pipe($r, $w) or die "pipe: $!";
257 open(my $tout, '+>', undef) or die "open temporary file: $!";
259 defined $pid or die "fork: $!";
260 my @cmd = (qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url);
262 dup2(fileno($r), 0) or die "redirect stdin failed: $!\n";
263 dup2(fileno($tout), 1) or die "redirect stdout failed: $!\n";
264 exec(@cmd) or die 'exec `' . join(' '). "' failed: $!\n";
267 foreach my $c ('a'..'z') {
268 print $w $c or die "failed to write to curl: $!";
271 close $w or die "close write pipe: $!";
272 close $r or die "close read pipe: $!";
273 my $kid = waitpid $pid, 0;
274 is($?, 0, 'curl exited successfully');
275 $tout->sysseek(0, SEEK_SET);
276 $tout->sysread(my $buf, 100);
277 is($buf, sha1_hex($str), 'read expected body');
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');
517 open my $fh, '+<', $f or die "failed to open $f: $!\n";
520 truncate($fh, 0) or die "truncate failed on $f: $!\n";