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);
10 foreach my $mod (qw(Plack::Util Plack::Builder
11 HTTP::Date HTTP::Status IPC::Run)) {
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";
32 LocalAddr => '127.0.0.1',
38 my $sock = IO::Socket::INET->new(%opts);
40 # Make sure we don't clobber socket options set by systemd or similar
41 # using socket activation:
42 my ($defer_accept_val, $accf_arg);
44 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
45 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
46 defined $x or die "getsockopt: $!";
47 $defer_accept_val = unpack('i', $x);
48 if ($defer_accept_val <= 0) {
49 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
51 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
52 require PublicInbox::Daemon;
53 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
54 $accf_arg = pack('a16a240', 'dataready', '');
55 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
58 my $upath = "$tmpdir/s";
59 my $unix = IO::Socket::UNIX->new(
64 ok($unix, 'UNIX socket created');
66 END { kill 'TERM', $pid if defined $pid };
67 my $spawn_httpd = sub {
69 my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
70 $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
71 ok(defined $pid, 'forked httpd process successfully');
75 ok($sock, 'sock created');
76 $spawn_httpd->('-W0');
80 my $conn = conn_for($sock, 'streaming callback');
81 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
82 ok($conn->read(my $buf, 8192), 'read response');
83 my ($head, $body) = split(/\r\n\r\n/, $buf);
84 is($body, "hello world\n", 'callback body matches expected');
88 my $conn = conn_for($sock, 'getline-die');
89 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
90 ok($conn->read(my $buf, 8192), 'read some response');
91 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
92 is($conn->read(my $nil, 8192), 0, 'read EOF');
94 my $after = capture($err);
95 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
96 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
100 my $conn = conn_for($sock, 'close-die');
101 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
102 ok($conn->read(my $buf, 8192), 'read some response');
103 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
104 is($conn->read(my $nil, 8192), 0, 'read EOF');
106 my $after = capture($err);
107 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
108 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
112 my $conn = conn_for($sock, 'excessive header');
113 $SIG{PIPE} = 'IGNORE';
114 $conn->write("GET /callback HTTP/1.0\r\n");
115 foreach my $i (1..500000) {
116 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
118 ok(!$conn->write("\r\n"), 'broken request');
119 ok($conn->read(my $buf, 8192), 'read response');
120 my ($head, $body) = split(/\r\n\r\n/, $buf);
121 like($head, qr/\b400\b/, 'got 400 response');
125 my $conn = conn_for($sock, 'excessive body Content-Length');
126 $SIG{PIPE} = 'IGNORE';
127 my $n = (10 * 1024 * 1024) + 1;
128 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
129 ok($conn->read(my $buf, 8192), 'read response');
130 my ($head, $body) = split(/\r\n\r\n/, $buf);
131 like($head, qr/\b413\b/, 'got 413 response');
135 my $conn = conn_for($sock, 'excessive body chunked');
136 $SIG{PIPE} = 'IGNORE';
137 my $n = (10 * 1024 * 1024) + 1;
138 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
139 $conn->write("\r\n".sprintf("%x\r\n", $n));
140 ok($conn->read(my $buf, 8192), 'read response');
141 my ($head, $body) = split(/\r\n\r\n/, $buf);
142 like($head, qr/\b413\b/, 'got 413 response');
146 my $conn = conn_for($sock, 'chunk with pipeline');
148 my $payload = 'b'x$n;
149 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
150 $conn->write("\r\n".sprintf("%x\r\n", $n));
151 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
152 $conn->read(my $buf, 4096);
154 $lim++ while ($conn->read($buf, 4096, bytes::length($buf)) && $lim < 9);
155 my $exp = sha1_hex($payload);
156 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
157 'chunk parser can handled pipelined requests');
160 # Unix domain sockets
162 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
163 ok($u, 'unix socket connected');
164 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
165 $u->read(my $buf, 4096);
166 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
167 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
171 my ($sock, $msg) = @_;
172 my $conn = IO::Socket::INET->new(
173 PeerAddr => $sock->sockhost,
174 PeerPort => $sock->sockport,
176 Type => SOCK_STREAM);
177 ok($conn, "connected for $msg");
179 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
184 my $conn = conn_for($sock, 'host-port');
185 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
186 $conn->read(my $buf, 4096);
187 my ($head, $body) = split(/\r\n\r\n/, $buf);
188 my ($addr, $port) = split(/:/, $body);
189 is($addr, $conn->sockhost, 'host matches addr');
190 is($port, $conn->sockport, 'port matches');
193 # graceful termination
195 my $conn = conn_for($sock, 'graceful termination via slow header');
196 $conn->write("GET /slow-header HTTP/1.0\r\n" .
197 "X-Check-Fifo: $fifo\r\n\r\n");
198 open my $f, '>', $fifo or die "open $fifo: $!\n";
200 ok(print($f "hello\n"), 'wrote something to fifo');
203 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
204 ok(print($f "world\n"), 'wrote else to fifo');
205 close $f or die "close fifo: $!\n";
206 $conn->read(my $buf, 8192);
207 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
208 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
209 is($body, "hello\nworld\n", 'read expected body');
210 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
211 is($?, 0, 'no error');
212 $spawn_httpd->('-W0');
216 my $conn = conn_for($sock, 'graceful termination via slow-body');
217 $conn->write("GET /slow-body HTTP/1.0\r\n" .
218 "X-Check-Fifo: $fifo\r\n\r\n");
219 open my $f, '>', $fifo or die "open $fifo: $!\n";
222 $conn->sysread($buf, 8192);
223 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
224 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
226 foreach my $c ('a'..'c') {
228 ok(print($f $c), 'wrote line to fifo');
229 $conn->sysread($buf, 8192);
230 is($buf, $c, 'got trickle for reading');
234 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
235 ok(print($f "world\n"), 'wrote else to fifo');
236 close $f or die "close fifo: $!\n";
237 $conn->sysread($buf, 8192);
238 is($buf, "world\n", 'read expected body');
239 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
240 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
241 is($?, 0, 'no error');
242 $spawn_httpd->('-W0');
245 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
247 my $str = 'abcdefghijklmnopqrstuvwxyz';
248 my $len = length $str;
249 is($len, 26, 'got the alphabet');
250 my $check_self = sub {
252 $conn->read(my $buf, 4096);
253 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
254 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
255 is($body, sha1_hex($str), 'read expected body');
260 foreach my $p (split(':', $ENV{PATH})) {
261 -x "$p/curl" or next;
266 $have_curl or skip('curl(1) missing', $ntest);
267 my $url = 'http://' . $sock->sockhost . ':' . $sock->sockport . '/sha1';
269 pipe($r, $w) or die "pipe: $!";
270 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
271 my ($out, $err) = ('', '');
272 my $h = IPC::Run::start($cmd, $r, \$out, \$err);
274 foreach my $c ('a'..'z') {
275 print $w $c or die "failed to write to curl: $!";
278 close $w or die "close write pipe: $!";
279 close $r or die "close read pipe: $!";
280 IPC::Run::finish($h);
281 is($?, 0, 'curl exited successfully');
282 is($err, '', 'no errors from curl');
283 is($out, sha1_hex($str), 'read expected body');
287 my $conn = conn_for($sock, '1.1 pipeline together');
288 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
289 "PUT /sha1 HTTP/1.1\r\n\r\n");
292 until (scalar(@r) >= 2) {
293 my $r = $conn->sysread(my $tmp, 4096);
294 die $! unless defined $r;
295 die "EOF <$buf>" unless $r;
297 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
299 is(2, scalar @r, 'got 2 responses');
301 foreach my $hex (@r) {
302 is($hex, sha1_hex(''), "read expected body $i");
308 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
309 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
311 my $t0 = [ gettimeofday ];
312 until ($buf =~ /\r\n\r\n/s) {
313 $conn->sysread($buf, 4096, length($buf));
315 my $elapsed = tv_interval($t0, [ gettimeofday ]);
316 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
320 my $conn = conn_for($sock, 'graceful termination during slow request');
321 $conn->write("PUT /sha1 HTTP/1.0\r\n");
323 $conn->write("Content-Length: $len\r\n");
325 $conn->write("\r\n");
328 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
331 foreach my $c ('a'..'z') {
332 $n += $conn->write($c);
334 is($n, $len, 'wrote alphabet');
335 $check_self->($conn);
336 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
337 is($?, 0, 'no error');
338 $spawn_httpd->('-W0');
341 # various DoS attacks against the chunk parser:
343 local $SIG{PIPE} = 'IGNORE';
344 my $conn = conn_for($sock, '1.1 chunk header excessive');
345 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
348 while ($w = $conn->write('ffffffff')) {
351 ok($!, 'got error set in $!');
352 is($w, undef, 'write error happened');
353 ok($n > 0, 'was able to write');
354 my $r = $conn->read(my $buf, 66666);
355 ok($r > 0, 'got non-empty response');
356 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
358 $conn = conn_for($sock, '1.1 chunk trailer excessive');
359 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
360 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
363 while ($w = $conn->write("\r")) {
366 ok($!, 'got error set in $!');
367 ok($n > 0, 'wrote part of chunk end (\r)');
368 $r = $conn->read($buf, 66666);
369 ok($r > 0, 'got non-empty response');
370 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
374 my $conn = conn_for($sock, '1.1 chunked close trickle');
375 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
376 $conn->write("Transfer-encoding: chunked\r\n\r\n");
377 foreach my $x ('a'..'z') {
401 $check_self->($conn);
405 my $conn = conn_for($sock, '1.1 chunked close');
406 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
407 my $xlen = sprintf('%x', $len);
408 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
409 "$str\r\n0\r\n\r\n");
410 $check_self->($conn);
414 my $conn = conn_for($sock, 'chunked body + pipeline');
415 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
416 "Transfer-Encoding: chunked\r\n");
418 $conn->write("\r\n1\r\n");
422 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
426 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
427 $conn->sysread(my $tmp, 4096);
430 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
431 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
432 is($body, sha1_hex('a'), 'read expected body');
434 $conn->write("Connection: close\r\n");
435 $conn->write("Content-Length: $len\r\n\r\n$str");
436 $check_self->($conn);
440 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
441 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
442 "Connection: keep-alive\r\n");
444 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
446 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
447 $conn->sysread(my $tmp, 4096);
450 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
451 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
452 is($body, sha1_hex($str), 'read expected body');
454 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
455 $check_self->($conn);
459 my $conn = conn_for($sock, 'trickle body');
460 $conn->write("PUT /sha1 HTTP/1.0\r\n");
461 $conn->write("Content-Length: $len\r\n\r\n");
462 my $beg = substr($str, 0, 10);
463 my $end = substr($str, 10);
464 is($beg . $end, $str, 'substr setup correct');
469 $check_self->($conn);
473 my $conn = conn_for($sock, 'one-shot write');
474 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
475 "Content-Length: $len\r\n\r\n$str");
476 $check_self->($conn);
480 my $conn = conn_for($sock, 'trickle header, one-shot body');
481 $conn->write("PUT /sha1 HTTP/1.0\r\n");
483 $conn->write("Content-Length: $len\r\n\r\n$str");
484 $check_self->($conn);
488 my $conn = conn_for($sock, '1.1 Connnection: close');
489 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
491 $conn->write("Content-Length: $len\r\n\r\n$str");
492 $check_self->($conn);
496 my $conn = conn_for($sock, '1.1 pipeline start');
497 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
499 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
500 $conn->sysread(my $tmp, 4096);
503 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
504 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
505 is($body, sha1_hex(''), 'read expected body');
508 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
510 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
511 $conn->sysread(my $tmp, 4096);
514 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
515 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
516 is($body, sha1_hex(''), 'read expected body #2');
520 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
521 my $var = Socket::TCP_DEFER_ACCEPT();
522 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
523 is(unpack('i', $x), $defer_accept_val,
524 'TCP_DEFER_ACCEPT unchanged if previously set');
527 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
528 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
529 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
530 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
531 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
538 open my $fh, '+<', $f or die "failed to open $f: $!\n";
541 truncate($fh, 0) or die "truncate failed on $f: $!\n";