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 $httpd = 'blib/script/public-inbox-httpd';
30 my $psgi = "./t/httpd-corner.psgi";
31 my $sock = tcp_server() or die;
33 # make sure stdin is not a pipe for lsof test to check for leaking pipes
34 open(STDIN, '<', '/dev/null') or die 'no /dev/null: $!';
36 # Make sure we don't clobber socket options set by systemd or similar
37 # using socket activation:
38 my ($defer_accept_val, $accf_arg);
40 setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
41 my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
42 defined $x or die "getsockopt: $!";
43 $defer_accept_val = unpack('i', $x);
44 if ($defer_accept_val <= 0) {
45 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
47 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
48 require PublicInbox::Daemon;
49 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
50 $accf_arg = pack('a16a240', 'dataready', '');
51 setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
54 my $upath = "$tmpdir/s";
55 my $unix = unix_server($upath);
56 ok($unix, 'UNIX socket created');
58 END { kill 'TERM', $pid if defined $pid };
59 my $spawn_httpd = sub {
61 my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
62 $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
63 ok(defined $pid, 'forked httpd process successfully');
67 if ('test worker death') {
68 my $conn = conn_for($sock, 'killed worker');
69 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
70 ok($conn->read(my $buf, 8192), 'read response');
71 my ($head, $body) = split(/\r\n\r\n/, $buf);
72 like($body, qr/\A[0-9]+\z/, '/pid response');
74 is(kill('KILL', $pid), 1, 'killed worker');
76 $conn = conn_for($sock, 'respawned worker');
77 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
78 ok($conn->read($buf, 8192), 'read response');
79 ($head, $body) = split(/\r\n\r\n/, $buf);
80 like($body, qr/\A[0-9]+\z/, '/pid response');
81 isnt($body, $pid, 'respawned worker');
85 my $conn = conn_for($sock, 'streaming callback');
86 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
87 ok($conn->read(my $buf, 8192), 'read response');
88 my ($head, $body) = split(/\r\n\r\n/, $buf);
89 is($body, "hello world\n", 'callback body matches expected');
93 my $conn = conn_for($sock, 'getline-die');
94 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
95 ok($conn->read(my $buf, 8192), 'read some response');
96 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
97 is($conn->read(my $nil, 8192), 0, 'read EOF');
99 my $after = capture($err);
100 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
101 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
105 my $conn = conn_for($sock, 'close-die');
106 $conn->write("GET /close-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)), 0, 'getline not failed');
113 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
117 my $conn = conn_for($sock, 'excessive header');
118 $SIG{PIPE} = 'IGNORE';
119 $conn->write("GET /callback HTTP/1.0\r\n");
120 foreach my $i (1..500000) {
121 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
123 ok(!$conn->write("\r\n"), 'broken request');
124 ok($conn->read(my $buf, 8192), 'read response');
125 my ($head, $body) = split(/\r\n\r\n/, $buf);
126 like($head, qr/\b400\b/, 'got 400 response');
130 my $conn = conn_for($sock, 'excessive body Content-Length');
131 $SIG{PIPE} = 'IGNORE';
132 my $n = (10 * 1024 * 1024) + 1;
133 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
134 ok($conn->read(my $buf, 8192), 'read response');
135 my ($head, $body) = split(/\r\n\r\n/, $buf);
136 like($head, qr/\b413\b/, 'got 413 response');
140 my $conn = conn_for($sock, 'excessive body chunked');
141 $SIG{PIPE} = 'IGNORE';
142 my $n = (10 * 1024 * 1024) + 1;
143 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
144 $conn->write("\r\n".sprintf("%x\r\n", $n));
145 ok($conn->read(my $buf, 8192), 'read response');
146 my ($head, $body) = split(/\r\n\r\n/, $buf);
147 like($head, qr/\b413\b/, 'got 413 response');
151 my $conn = conn_for($sock, 'chunk with pipeline');
153 my $payload = 'b'x$n;
154 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
155 $conn->write("\r\n".sprintf("%x\r\n", $n));
156 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
157 $conn->read(my $buf, 4096);
159 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
160 my $exp = sha1_hex($payload);
161 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
162 'chunk parser can handled pipelined requests');
165 # Unix domain sockets
167 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
168 ok($u, 'unix socket connected');
169 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
170 $u->read(my $buf, 4096);
171 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
172 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
176 my ($dest, $msg) = @_;
177 my $conn = tcp_connect($dest);
178 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');
259 which('curl') or skip('curl(1) missing', 4);
260 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
261 my $url = "$base/sha1";
263 pipe($r, $w) or die "pipe: $!";
264 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
265 open my $cout, '+>', undef or die;
266 open my $cerr, '>', undef or die;
267 my $rdr = { 0 => fileno($r), 1 => fileno($cout), 2 => fileno($cerr) };
268 my $pid = spawn($cmd, undef, $rdr);
269 close $r or die "close read pipe: $!";
270 foreach my $c ('a'..'z') {
271 print $w $c or die "failed to write to curl: $!";
274 close $w or die "close write pipe: $!";
276 is($?, 0, 'curl exited successfully');
277 is(-s $cerr, 0, 'no errors from curl');
278 $cout->seek(0, SEEK_SET);
279 is(<$cout>, sha1_hex($str), 'read expected body');
281 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
285 my $r = sysread($fh, my $buf, 4096) or last;
287 $buf =~ /\A\0+\z/ or $non_zero++;
289 close $fh or die "curl errored out \$?=$?";
290 is($n, 30 * 1024 * 1024, 'got expected output from curl');
291 is($non_zero, 0, 'read all zeros');
295 my $conn = conn_for($sock, '1.1 pipeline together');
296 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
297 "PUT /sha1 HTTP/1.1\r\n\r\n");
300 until (scalar(@r) >= 2) {
301 my $r = $conn->sysread(my $tmp, 4096);
302 die $! unless defined $r;
303 die "EOF <$buf>" unless $r;
305 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
307 is(2, scalar @r, 'got 2 responses');
309 foreach my $hex (@r) {
310 is($hex, sha1_hex(''), "read expected body $i");
316 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
317 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
319 my $t0 = [ gettimeofday ];
320 until ($buf =~ /\r\n\r\n/s) {
321 $conn->sysread($buf, 4096, length($buf));
323 my $elapsed = tv_interval($t0, [ gettimeofday ]);
324 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
328 my $conn = conn_for($sock, 'graceful termination during slow request');
329 $conn->write("PUT /sha1 HTTP/1.0\r\n");
331 $conn->write("Content-Length: $len\r\n");
333 $conn->write("\r\n");
336 is(kill('TERM', $kpid), 1, 'started graceful shutdown');
339 foreach my $c ('a'..'z') {
340 $n += $conn->write($c);
342 is($n, $len, 'wrote alphabet');
343 $check_self->($conn);
344 is(waitpid($kpid, 0), $kpid, 'reaped httpd');
345 is($?, 0, 'no error');
346 $spawn_httpd->('-W0');
349 # various DoS attacks against the chunk parser:
351 local $SIG{PIPE} = 'IGNORE';
352 my $conn = conn_for($sock, '1.1 chunk header excessive');
353 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
356 while ($w = $conn->write('ffffffff')) {
359 ok($!, 'got error set in $!');
360 is($w, undef, 'write error happened');
361 ok($n > 0, 'was able to write');
362 my $r = $conn->read(my $buf, 66666);
363 ok($r > 0, 'got non-empty response');
364 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
366 $conn = conn_for($sock, '1.1 chunk trailer excessive');
367 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
368 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
371 while ($w = $conn->write("\r")) {
374 ok($!, 'got error set in $!');
375 ok($n > 0, 'wrote part of chunk end (\r)');
376 $r = $conn->read($buf, 66666);
377 ok($r > 0, 'got non-empty response');
378 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
382 my $conn = conn_for($sock, '1.1 chunked close trickle');
383 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
384 $conn->write("Transfer-encoding: chunked\r\n\r\n");
385 foreach my $x ('a'..'z') {
409 $check_self->($conn);
413 my $conn = conn_for($sock, '1.1 chunked close');
414 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
415 my $xlen = sprintf('%x', $len);
416 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
417 "$str\r\n0\r\n\r\n");
418 $check_self->($conn);
422 my $conn = conn_for($sock, 'chunked body + pipeline');
423 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
424 "Transfer-Encoding: chunked\r\n");
426 $conn->write("\r\n1\r\n");
430 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
434 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
435 $conn->sysread(my $tmp, 4096);
438 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
439 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
440 is($body, sha1_hex('a'), 'read expected body');
442 $conn->write("Connection: close\r\n");
443 $conn->write("Content-Length: $len\r\n\r\n$str");
444 $check_self->($conn);
448 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
449 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
450 "Connection: keep-alive\r\n");
452 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
454 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
455 $conn->sysread(my $tmp, 4096);
458 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
459 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
460 is($body, sha1_hex($str), 'read expected body');
462 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
463 $check_self->($conn);
467 my $conn = conn_for($sock, 'trickle body');
468 $conn->write("PUT /sha1 HTTP/1.0\r\n");
469 $conn->write("Content-Length: $len\r\n\r\n");
470 my $beg = substr($str, 0, 10);
471 my $end = substr($str, 10);
472 is($beg . $end, $str, 'substr setup correct');
477 $check_self->($conn);
481 my $conn = conn_for($sock, 'one-shot write');
482 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
483 "Content-Length: $len\r\n\r\n$str");
484 $check_self->($conn);
488 my $conn = conn_for($sock, 'trickle header, one-shot body');
489 $conn->write("PUT /sha1 HTTP/1.0\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 Connnection: close');
497 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
499 $conn->write("Content-Length: $len\r\n\r\n$str");
500 $check_self->($conn);
504 my $conn = conn_for($sock, '1.1 pipeline start');
505 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
507 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
508 $conn->sysread(my $tmp, 4096);
511 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
512 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
513 is($body, sha1_hex(''), 'read expected body');
516 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
518 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
519 $conn->sysread(my $tmp, 4096);
522 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
523 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
524 is($body, sha1_hex(''), 'read expected body #2');
528 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
529 my $var = Socket::TCP_DEFER_ACCEPT();
530 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
531 is(unpack('i', $x), $defer_accept_val,
532 'TCP_DEFER_ACCEPT unchanged if previously set');
535 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
536 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
537 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
538 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
539 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
542 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
543 skip 'no lsof in PATH', 1 unless which('lsof');
544 my @lsof = `lsof -p $pid`;
545 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
546 is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
553 open my $fh, '+<', $f or die "failed to open $f: $!\n";
556 truncate($fh, 0) or die "truncate failed on $f: $!\n";