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);
20 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
22 require './t/common.perl';
23 my ($tmpdir, $for_destroy) = tmpdir();
24 my $fifo = "$tmpdir/fifo";
25 ok(defined mkfifo($fifo, 0777), 'created FIFO');
26 my $err = "$tmpdir/stderr.log";
27 my $out = "$tmpdir/stdout.log";
28 my $psgi = "./t/httpd-corner.psgi";
29 my $sock = tcp_server() or die;
31 # make sure stdin is not a pipe for lsof test to check for leaking pipes
32 open(STDIN, '<', '/dev/null') or die 'no /dev/null: $!';
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: $!";
53 my $s = IO::Socket::UNIX->new(
55 Type => Socket::SOCK_STREAM(),
62 my $upath = "$tmpdir/s";
63 my $unix = unix_server($upath);
64 ok($unix, 'UNIX socket created');
66 my $spawn_httpd = sub {
68 my $cmd = [ '-httpd', @args, "--stdout=$out", "--stderr=$err", $psgi ];
69 $td = start_script($cmd, undef, { 3 => $sock, 4 => $unix });
73 if ('test worker death') {
74 my $conn = conn_for($sock, 'killed worker');
75 $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
77 while (defined(my $line = $conn->getline)) {
78 next unless $line eq "\r\n";
79 chomp($pid = $conn->getline);
82 like($pid, qr/\A[0-9]+\z/, '/pid response');
83 is(kill('KILL', $pid), 1, 'killed worker');
84 is($conn->getline, undef, 'worker died and EOF-ed client');
86 $conn = conn_for($sock, 'respawned worker');
87 $conn->write("GET /pid HTTP/1.0\r\n\r\n");
88 ok($conn->read(my $buf, 8192), 'read response');
89 my ($head, $body) = split(/\r\n\r\n/, $buf);
91 like($body, qr/\A[0-9]+\z/, '/pid response');
92 isnt($body, $pid, 'respawned worker');
96 my $conn = conn_for($sock, 'streaming callback');
97 $conn->write("GET /callback HTTP/1.0\r\n\r\n");
98 ok($conn->read(my $buf, 8192), 'read response');
99 my ($head, $body) = split(/\r\n\r\n/, $buf);
100 is($body, "hello world\n", 'callback body matches expected');
104 my $conn = conn_for($sock, 'getline-die');
105 $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
106 ok($conn->read(my $buf, 8192), 'read some response');
107 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
108 is($conn->read(my $nil, 8192), 0, 'read EOF');
110 my $after = capture($err);
111 is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
112 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
116 my $conn = conn_for($sock, 'close-die');
117 $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
118 ok($conn->read(my $buf, 8192), 'read some response');
119 like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
120 is($conn->read(my $nil, 8192), 0, 'read EOF');
122 my $after = capture($err);
123 is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
124 is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
128 my $conn = conn_for($sock, 'excessive header');
129 $SIG{PIPE} = 'IGNORE';
130 $conn->write("GET /callback HTTP/1.0\r\n");
131 foreach my $i (1..500000) {
132 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
134 ok(!$conn->write("\r\n"), 'broken request');
135 ok($conn->read(my $buf, 8192), 'read response');
136 my ($head, $body) = split(/\r\n\r\n/, $buf);
137 like($head, qr/\b400\b/, 'got 400 response');
141 my $conn = conn_for($sock, 'excessive body Content-Length');
142 $SIG{PIPE} = 'IGNORE';
143 my $n = (10 * 1024 * 1024) + 1;
144 $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\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, 'excessive body chunked');
152 $SIG{PIPE} = 'IGNORE';
153 my $n = (10 * 1024 * 1024) + 1;
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 ok($conn->read(my $buf, 8192), 'read response');
157 my ($head, $body) = split(/\r\n\r\n/, $buf);
158 like($head, qr/\b413\b/, 'got 413 response');
162 my $conn = conn_for($sock, 'chunk with pipeline');
164 my $payload = 'b'x$n;
165 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
166 $conn->write("\r\n".sprintf("%x\r\n", $n));
167 $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
168 $conn->read(my $buf, 4096);
170 $lim++ while ($conn->read($buf, 4096, length($buf)) && $lim < 9);
171 my $exp = sha1_hex($payload);
172 like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
173 'chunk parser can handled pipelined requests');
176 # Unix domain sockets
178 my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
179 ok($u, 'unix socket connected');
180 $u->write("GET /host-port HTTP/1.0\r\n\r\n");
181 $u->read(my $buf, 4096);
182 like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
183 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
187 my ($dest, $msg) = @_;
188 my $conn = tcp_connect($dest);
189 ok($conn, "connected for $msg");
190 setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
195 my $conn = conn_for($sock, 'host-port');
196 $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
197 $conn->read(my $buf, 4096);
198 my ($head, $body) = split(/\r\n\r\n/, $buf);
199 my ($addr, $port) = split(/:/, $body);
200 is($addr, $conn->sockhost, 'host matches addr');
201 is($port, $conn->sockport, 'port matches');
204 # graceful termination
206 my $conn = conn_for($sock, 'graceful termination via slow header');
207 $conn->write("GET /slow-header HTTP/1.0\r\n" .
208 "X-Check-Fifo: $fifo\r\n\r\n");
209 open my $f, '>', $fifo or die "open $fifo: $!\n";
211 ok(print($f "hello\n"), 'wrote something to fifo');
212 is($td->kill, 1, 'started graceful shutdown');
213 ok(print($f "world\n"), 'wrote else to fifo');
214 close $f or die "close fifo: $!\n";
215 $conn->read(my $buf, 8192);
216 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
217 like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
218 is($body, "hello\nworld\n", 'read expected body');
220 is($?, 0, 'no error');
221 $spawn_httpd->('-W0');
225 my $conn = conn_for($sock, 'graceful termination via slow-body');
226 $conn->write("GET /slow-body HTTP/1.0\r\n" .
227 "X-Check-Fifo: $fifo\r\n\r\n");
228 open my $f, '>', $fifo or die "open $fifo: $!\n";
231 $conn->sysread($buf, 8192);
232 like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
233 like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
235 foreach my $c ('a'..'c') {
237 ok(print($f $c), 'wrote line to fifo');
238 $conn->sysread($buf, 8192);
239 is($buf, $c, 'got trickle for reading');
241 is($td->kill, 1, 'started graceful shutdown');
242 ok(print($f "world\n"), 'wrote else to fifo');
243 close $f or die "close fifo: $!\n";
244 $conn->sysread($buf, 8192);
245 is($buf, "world\n", 'read expected body');
246 is($conn->sysread($buf, 8192), 0, 'got EOF from server');
248 is($?, 0, 'no error');
249 $spawn_httpd->('-W0');
252 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
254 my $str = 'abcdefghijklmnopqrstuvwxyz';
255 my $len = length $str;
256 is($len, 26, 'got the alphabet');
257 my $check_self = sub {
259 $conn->read(my $buf, 4096);
260 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
261 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
262 is($body, sha1_hex($str), 'read expected body');
266 which('curl') or skip('curl(1) missing', 4);
267 my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
268 my $url = "$base/sha1";
270 pipe($r, $w) or die "pipe: $!";
271 my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
272 open my $cout, '+>', undef or die;
273 open my $cerr, '>', undef or die;
274 my $rdr = { 0 => fileno($r), 1 => fileno($cout), 2 => fileno($cerr) };
275 my $pid = spawn($cmd, undef, $rdr);
276 close $r or die "close read pipe: $!";
277 foreach my $c ('a'..'z') {
278 print $w $c or die "failed to write to curl: $!";
281 close $w or die "close write pipe: $!";
283 is($?, 0, 'curl exited successfully');
284 is(-s $cerr, 0, 'no errors from curl');
285 $cout->seek(0, SEEK_SET);
286 is(<$cout>, sha1_hex($str), 'read expected body');
288 open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
292 my $r = sysread($fh, my $buf, 4096) or last;
294 $buf =~ /\A\0+\z/ or $non_zero++;
296 close $fh or die "curl errored out \$?=$?";
297 is($n, 30 * 1024 * 1024, 'got expected output from curl');
298 is($non_zero, 0, 'read all zeros');
302 my $conn = conn_for($sock, '1.1 pipeline together');
303 $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
304 "PUT /sha1 HTTP/1.1\r\n\r\n");
307 until (scalar(@r) >= 2) {
308 my $r = $conn->sysread(my $tmp, 4096);
309 die $! unless defined $r;
310 die "EOF <$buf>" unless $r;
312 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
314 is(2, scalar @r, 'got 2 responses');
316 foreach my $hex (@r) {
317 is($hex, sha1_hex(''), "read expected body $i");
323 my $conn = conn_for($sock, 'no TCP_CORK on empty body');
324 $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
326 my $t0 = [ gettimeofday ];
327 until ($buf =~ /\r\n\r\n/s) {
328 $conn->sysread($buf, 4096, length($buf));
330 my $elapsed = tv_interval($t0, [ gettimeofday ]);
331 ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
335 my $conn = conn_for($sock, 'graceful termination during slow request');
336 $conn->write("PUT /sha1 HTTP/1.0\r\n");
338 $conn->write("Content-Length: $len\r\n");
340 $conn->write("\r\n");
341 is($td->kill, 1, 'started graceful shutdown');
344 foreach my $c ('a'..'z') {
345 $n += $conn->write($c);
347 is($n, $len, 'wrote alphabet');
348 $check_self->($conn);
350 is($?, 0, 'no error');
351 $spawn_httpd->('-W0');
354 # various DoS attacks against the chunk parser:
356 local $SIG{PIPE} = 'IGNORE';
357 my $conn = conn_for($sock, '1.1 chunk header excessive');
358 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
361 while ($w = $conn->write('ffffffff')) {
364 ok($!, 'got error set in $!');
365 is($w, undef, 'write error happened');
366 ok($n > 0, 'was able to write');
367 my $r = $conn->read(my $buf, 66666);
368 ok($r > 0, 'got non-empty response');
369 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
371 $conn = conn_for($sock, '1.1 chunk trailer excessive');
372 $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
373 is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
376 while ($w = $conn->write("\r")) {
379 ok($!, 'got error set in $!');
380 ok($n > 0, 'wrote part of chunk end (\r)');
381 $r = $conn->read($buf, 66666);
382 ok($r > 0, 'got non-empty response');
383 like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
387 my $conn = conn_for($sock, '1.1 chunked close trickle');
388 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
389 $conn->write("Transfer-encoding: chunked\r\n\r\n");
390 foreach my $x ('a'..'z') {
414 $check_self->($conn);
418 my $conn = conn_for($sock, '1.1 chunked close');
419 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
420 my $xlen = sprintf('%x', $len);
421 $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
422 "$str\r\n0\r\n\r\n");
423 $check_self->($conn);
427 my $conn = conn_for($sock, 'chunked body + pipeline');
428 $conn->write("PUT /sha1 HTTP/1.1\r\n" .
429 "Transfer-Encoding: chunked\r\n");
431 $conn->write("\r\n1\r\n");
435 $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
439 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
440 $conn->sysread(my $tmp, 4096);
443 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
444 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
445 is($body, sha1_hex('a'), 'read expected body');
447 $conn->write("Connection: close\r\n");
448 $conn->write("Content-Length: $len\r\n\r\n$str");
449 $check_self->($conn);
453 my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
454 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
455 "Connection: keep-alive\r\n");
457 $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
459 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
460 $conn->sysread(my $tmp, 4096);
463 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
464 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
465 is($body, sha1_hex($str), 'read expected body');
467 $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
468 $check_self->($conn);
472 my $conn = conn_for($sock, 'trickle body');
473 $conn->write("PUT /sha1 HTTP/1.0\r\n");
474 $conn->write("Content-Length: $len\r\n\r\n");
475 my $beg = substr($str, 0, 10);
476 my $end = substr($str, 10);
477 is($beg . $end, $str, 'substr setup correct');
482 $check_self->($conn);
486 my $conn = conn_for($sock, 'one-shot write');
487 $conn->write("PUT /sha1 HTTP/1.0\r\n" .
488 "Content-Length: $len\r\n\r\n$str");
489 $check_self->($conn);
493 my $conn = conn_for($sock, 'trickle header, one-shot body');
494 $conn->write("PUT /sha1 HTTP/1.0\r\n");
496 $conn->write("Content-Length: $len\r\n\r\n$str");
497 $check_self->($conn);
501 my $conn = conn_for($sock, '1.1 Connnection: close');
502 $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
504 $conn->write("Content-Length: $len\r\n\r\n$str");
505 $check_self->($conn);
509 my $conn = conn_for($sock, '1.1 pipeline start');
510 $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
512 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
513 $conn->sysread(my $tmp, 4096);
516 my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
517 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
518 is($body, sha1_hex(''), 'read expected body');
521 $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
523 until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
524 $conn->sysread(my $tmp, 4096);
527 ($head, $body) = split(/\r\n\r\n/, $buf, 2);
528 like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
529 is($body, sha1_hex(''), 'read expected body #2');
533 skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
534 my $var = Socket::TCP_DEFER_ACCEPT();
535 defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
536 is(unpack('i', $x), $defer_accept_val,
537 'TCP_DEFER_ACCEPT unchanged if previously set');
540 skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
541 skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
542 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
543 defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
544 is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
548 skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
549 skip 'no lsof in PATH', 1 unless which('lsof');
550 my @lsof = `lsof -p $td->{pid}`;
551 is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
553 # filter out pipes inherited from the parent
554 my @this = `lsof -p $$`;
558 my @f = split(' ', $_);
560 $bad = $_ if $inode !~ /\A[0-9]+\z/;
562 } grep (/\bpipe\b/, @_);
564 my %child = extract_inodes(@lsof);
565 my %parent = extract_inodes(@this);
566 skip("inode not in expected format: $bad", 1) if defined($bad);
567 delete @child{(keys %parent)};
568 is_deeply([], [keys %child], 'no extra pipes with -W0');
575 open my $fh, '+<', $f or die "failed to open $f: $!\n";
578 truncate($fh, 0) or die "truncate failed on $f: $!\n";