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);
11 foreach my $mod (qw(Plack::Util Plack::Builder
12 HTTP::Date HTTP::Status IPC::Run)) {
14 plan skip_all => "$mod missing for httpd-corner.t" if $@;
17 use Digest::SHA qw(sha1_hex);
18 use File::Temp qw/tempdir/;
22 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
24 require './t/common.perl';
25 my $tmpdir = tempdir('httpd-corner-XXXXXX', TMPDIR => 1, CLEANUP => 1);
26 my $fifo = "$tmpdir/fifo";
27 ok(defined mkfifo($fifo, 0777), 'created FIFO');
28 my $err = "$tmpdir/stderr.log";
29 my $out = "$tmpdir/stdout.log";
30 my $httpd = 'blib/script/public-inbox-httpd';
31 my $psgi = "./t/httpd-corner.psgi";
32 my $sock = tcp_server();
34 # Make sure we don't clobber socket options set by systemd or similar
35 # using socket activation:
36 my ($defer_accept_val, $accf_arg);
38 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
39 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
40 defined $x or die "getsockopt: $!";
41 $defer_accept_val = unpack('i', $x);
42 if ($defer_accept_val <= 0) {
43 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
45 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
46 require PublicInbox::Daemon;
47 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
48 $accf_arg = pack('a16a240', 'dataready', '');
49 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
52 my $upath = "$tmpdir/s";
53 my $unix = unix_server($upath);
54 ok($unix, 'UNIX socket created');
56 END { kill 'TERM', $pid if defined $pid };
57 my $spawn_httpd = sub {
59 my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
60 $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
61 ok(defined $pid, 'forked httpd process successfully');
65 ok($sock, 'sock created');
66 $spawn_httpd->('-W0');
70 my $conn = conn_for($sock, 'streaming callback');
71 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
72 ok($conn->read(my $buf, 8192), 'read response');
73 my ($head, $body) = split(/\r\n\r\n/, $buf);
74 is($body, "hello world\n", 'callback body matches expected');
78 my $conn = conn_for($sock, 'getline-die');
79 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
80 ok($conn->read(my $buf, 8192), 'read some response');
81 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
82 is($conn->read(my $nil, 8192), 0, 'read EOF');
84 my $after = capture($err);
85 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
86 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
90 my $conn = conn_for($sock, 'close-die');
91 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
92 ok($conn->read(my $buf, 8192), 'read some response');
93 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
94 is($conn->read(my $nil, 8192), 0, 'read EOF');
96 my $after = capture($err);
97 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
98 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
102 my $conn = conn_for($sock, 'excessive header');
103 $SIG{PIPE} = 'IGNORE';
104 $conn->write("GET /callback HTTP/1.0\r\n");
105 foreach my $i (1..500000) {
106 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
108 ok(!$conn->write("\r\n"), 'broken request');
109 ok($conn->read(my $buf, 8192), 'read response');
110 my ($head, $body) = split(/\r\n\r\n/, $buf);
111 like($head, qr/\b400\b/, 'got 400 response');
115 my $conn = conn_for($sock, 'excessive body Content-Length');
116 $SIG{PIPE} = 'IGNORE';
117 my $n = (10 * 1024 * 1024) + 1;
118 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
119 ok($conn->read(my $buf, 8192), 'read response');
120 my ($head, $body) = split(/\r\n\r\n/, $buf);
121 like($head, qr/\b413\b/, 'got 413 response');
125 my $conn = conn_for($sock, 'excessive body chunked');
126 $SIG{PIPE} = 'IGNORE';
127 my $n = (10 * 1024 * 1024) + 1;
128 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
129 $conn->write("\r\n".sprintf("%x\r\n", $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, 'chunk with pipeline');
138 my $payload = 'b'x$n;
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 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
142 $conn->read(my $buf, 4096);
144 $lim++ while ($conn->read($buf, 4096, bytes::length($buf)) && $lim < 9);
145 my $exp = sha1_hex($payload);
146 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
147 'chunk parser can handled pipelined requests');
150 # Unix domain sockets
152 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
153 ok($u, 'unix socket connected');
154 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
155 $u->read(my $buf, 4096);
156 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
157 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
161 my ($dest, $msg) = @_;
162 my $conn = tcp_connect($dest);
163 ok($conn, "connected for $msg");
164 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
169 my $conn = conn_for($sock, 'host-port');
170 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
171 $conn->read(my $buf, 4096);
172 my ($head, $body) = split(/\r\n\r\n/, $buf);
173 my ($addr, $port) = split(/:/, $body);
174 is($addr, $conn->sockhost, 'host matches addr');
175 is($port, $conn->sockport, 'port matches');
178 # graceful termination
180 my $conn = conn_for($sock, 'graceful termination via slow header');
181 $conn->write("GET /slow-header HTTP/1.0\r\n" .
182 "X-Check-Fifo: $fifo\r\n\r\n");
183 open my $f, '>', $fifo or die "open $fifo: $!\n";
185 ok(print($f "hello\n"), 'wrote something to fifo');
188 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
189 ok(print($f "world\n"), 'wrote else to fifo');
190 close $f or die "close fifo: $!\n";
191 $conn->read(my $buf, 8192);
192 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
193 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
194 is($body, "hello\nworld\n", 'read expected body');
195 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
196 is($?, 0, 'no error');
197 $spawn_httpd->('-W0');
201 my $conn = conn_for($sock, 'graceful termination via slow-body');
202 $conn->write("GET /slow-body HTTP/1.0\r\n" .
203 "X-Check-Fifo: $fifo\r\n\r\n");
204 open my $f, '>', $fifo or die "open $fifo: $!\n";
207 $conn->sysread($buf, 8192);
208 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
209 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
211 foreach my $c ('a'..'c') {
213 ok(print($f $c), 'wrote line to fifo');
214 $conn->sysread($buf, 8192);
215 is($buf, $c, 'got trickle for reading');
219 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
220 ok(print($f "world\n"), 'wrote else to fifo');
221 close $f or die "close fifo: $!\n";
222 $conn->sysread($buf, 8192);
223 is($buf, "world\n", 'read expected body');
224 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
225 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
226 is($?, 0, 'no error');
227 $spawn_httpd->('-W0');
230 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
232 my $str = 'abcdefghijklmnopqrstuvwxyz';
233 my $len = length $str;
234 is($len, 26, 'got the alphabet');
235 my $check_self = sub {
237 $conn->read(my $buf, 4096);
238 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
239 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
240 is($body, sha1_hex($str), 'read expected body');
244 which('curl') or skip('curl(1) missing', 4);
245 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
246 my $url = "$base/sha1";
248 pipe($r, $w) or die "pipe: $!";
249 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
250 my ($out, $err) = ('', '');
251 my $h = IPC::Run::start($cmd, $r, \$out, \$err);
253 foreach my $c ('a'..'z') {
254 print $w $c or die "failed to write to curl: $!";
257 close $w or die "close write pipe: $!";
258 close $r or die "close read pipe: $!";
259 IPC::Run::finish($h);
260 is($?, 0, 'curl exited successfully');
261 is($err, '', 'no errors from curl');
262 is($out, sha1_hex($str), 'read expected body');
264 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
268 my $r = sysread($fh, my $buf, 4096) or last;
270 $buf =~ /\A\0+\z/ or $non_zero++;
272 is($n, 30 * 1024 * 1024, 'got expected output from curl');
273 is($non_zero, 0, 'read all zeros');
277 my $conn = conn_for($sock, '1.1 pipeline together');
278 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
279 "PUT /sha1 HTTP/1.1\r\n\r\n");
282 until (scalar(@r) >= 2) {
283 my $r = $conn->sysread(my $tmp, 4096);
284 die $! unless defined $r;
285 die "EOF <$buf>" unless $r;
287 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
289 is(2, scalar @r, 'got 2 responses');
291 foreach my $hex (@r) {
292 is($hex, sha1_hex(''), "read expected body $i");
298 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
299 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
301 my $t0 = [ gettimeofday ];
302 until ($buf =~ /\r\n\r\n/s) {
303 $conn->sysread($buf, 4096, length($buf));
305 my $elapsed = tv_interval($t0, [ gettimeofday ]);
306 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
310 my $conn = conn_for($sock, 'graceful termination during slow request');
311 $conn->write("PUT /sha1 HTTP/1.0\r\n");
313 $conn->write("Content-Length: $len\r\n");
315 $conn->write("\r\n");
318 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
321 foreach my $c ('a'..'z') {
322 $n += $conn->write($c);
324 is($n, $len, 'wrote alphabet');
325 $check_self->($conn);
326 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
327 is($?, 0, 'no error');
328 $spawn_httpd->('-W0');
331 # various DoS attacks against the chunk parser:
333 local $SIG{PIPE} = 'IGNORE';
334 my $conn = conn_for($sock, '1.1 chunk header excessive');
335 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
338 while ($w = $conn->write('ffffffff')) {
341 ok($!, 'got error set in $!');
342 is($w, undef, 'write error happened');
343 ok($n > 0, 'was able to write');
344 my $r = $conn->read(my $buf, 66666);
345 ok($r > 0, 'got non-empty response');
346 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
348 $conn = conn_for($sock, '1.1 chunk trailer excessive');
349 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
350 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
353 while ($w = $conn->write("\r")) {
356 ok($!, 'got error set in $!');
357 ok($n > 0, 'wrote part of chunk end (\r)');
358 $r = $conn->read($buf, 66666);
359 ok($r > 0, 'got non-empty response');
360 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
364 my $conn = conn_for($sock, '1.1 chunked close trickle');
365 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
366 $conn->write("Transfer-encoding: chunked\r\n\r\n");
367 foreach my $x ('a'..'z') {
391 $check_self->($conn);
395 my $conn = conn_for($sock, '1.1 chunked close');
396 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
397 my $xlen = sprintf('%x', $len);
398 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
399 "$str\r\n0\r\n\r\n");
400 $check_self->($conn);
404 my $conn = conn_for($sock, 'chunked body + pipeline');
405 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
406 "Transfer-Encoding: chunked\r\n");
408 $conn->write("\r\n1\r\n");
412 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
416 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
417 $conn->sysread(my $tmp, 4096);
420 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
421 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
422 is($body, sha1_hex('a'), 'read expected body');
424 $conn->write("Connection: close\r\n");
425 $conn->write("Content-Length: $len\r\n\r\n$str");
426 $check_self->($conn);
430 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
431 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
432 "Connection: keep-alive\r\n");
434 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
436 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
437 $conn->sysread(my $tmp, 4096);
440 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
441 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
442 is($body, sha1_hex($str), 'read expected body');
444 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
445 $check_self->($conn);
449 my $conn = conn_for($sock, 'trickle body');
450 $conn->write("PUT /sha1 HTTP/1.0\r\n");
451 $conn->write("Content-Length: $len\r\n\r\n");
452 my $beg = substr($str, 0, 10);
453 my $end = substr($str, 10);
454 is($beg . $end, $str, 'substr setup correct');
459 $check_self->($conn);
463 my $conn = conn_for($sock, 'one-shot write');
464 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
465 "Content-Length: $len\r\n\r\n$str");
466 $check_self->($conn);
470 my $conn = conn_for($sock, 'trickle header, one-shot body');
471 $conn->write("PUT /sha1 HTTP/1.0\r\n");
473 $conn->write("Content-Length: $len\r\n\r\n$str");
474 $check_self->($conn);
478 my $conn = conn_for($sock, '1.1 Connnection: close');
479 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
481 $conn->write("Content-Length: $len\r\n\r\n$str");
482 $check_self->($conn);
486 my $conn = conn_for($sock, '1.1 pipeline start');
487 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
489 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
490 $conn->sysread(my $tmp, 4096);
493 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
494 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
495 is($body, sha1_hex(''), 'read expected body');
498 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
500 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
501 $conn->sysread(my $tmp, 4096);
504 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
505 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
506 is($body, sha1_hex(''), 'read expected body #2');
510 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
511 my $var = Socket::TCP_DEFER_ACCEPT();
512 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
513 is(unpack('i', $x), $defer_accept_val,
514 'TCP_DEFER_ACCEPT unchanged if previously set');
517 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
518 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
519 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
520 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
521 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
524 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
525 skip 'no lsof in PATH', 1 unless which('lsof');
526 my @lsof = `lsof -p $pid`;
527 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
528 is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
535 open my $fh, '+<', $f or die "failed to open $f: $!\n";
538 truncate($fh, 0) or die "truncate failed on $f: $!\n";