]> Sergey Matveev's repositories - public-inbox.git/blob - t/httpd-corner.t
t/httpd-corner: check for leaking FDs and pipes
[public-inbox.git] / t / httpd-corner.t
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.
5 use strict;
6 use warnings;
7 use Test::More;
8 use Time::HiRes qw(gettimeofday tv_interval);
9
10 foreach my $mod (qw(Plack::Util Plack::Builder
11                         HTTP::Date HTTP::Status IPC::Run)) {
12         eval "require $mod";
13         plan skip_all => "$mod missing for httpd-corner.t" if $@;
14 }
15
16 use Digest::SHA qw(sha1_hex);
17 use File::Temp qw/tempdir/;
18 use IO::Socket;
19 use IO::Socket::UNIX;
20 use Fcntl qw(:seek);
21 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
22 use POSIX qw(mkfifo);
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();
32
33 # Make sure we don't clobber socket options set by systemd or similar
34 # using socket activation:
35 my ($defer_accept_val, $accf_arg);
36 if ($^O eq 'linux') {
37         setsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 5) or die;
38         my $x = getsockopt($sock, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
39         defined $x or die "getsockopt: $!";
40         $defer_accept_val = unpack('i', $x);
41         if ($defer_accept_val <= 0) {
42                 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
43         }
44 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
45         require PublicInbox::Daemon;
46         my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
47         $accf_arg = pack('a16a240', 'dataready', '');
48         setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
49 }
50
51 my $upath = "$tmpdir/s";
52 my $unix = unix_server($upath);
53 ok($unix, 'UNIX socket created');
54 my $pid;
55 END { kill 'TERM', $pid if defined $pid };
56 my $spawn_httpd = sub {
57         my (@args) = @_;
58         my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
59         $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
60         ok(defined $pid, 'forked httpd process successfully');
61 };
62
63 {
64         ok($sock, 'sock created');
65         $spawn_httpd->('-W0');
66 }
67
68 {
69         my $conn = conn_for($sock, 'streaming callback');
70         $conn->write("GET /callback HTTP/1.0\r\n\r\n");
71         ok($conn->read(my $buf, 8192), 'read response');
72         my ($head, $body) = split(/\r\n\r\n/, $buf);
73         is($body, "hello world\n", 'callback body matches expected');
74 }
75
76 {
77         my $conn = conn_for($sock, 'getline-die');
78         $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
79         ok($conn->read(my $buf, 8192), 'read some response');
80         like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
81         is($conn->read(my $nil, 8192), 0, 'read EOF');
82         $conn = undef;
83         my $after = capture($err);
84         is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
85         is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
86 }
87
88 {
89         my $conn = conn_for($sock, 'close-die');
90         $conn->write("GET /close-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');
94         $conn = undef;
95         my $after = capture($err);
96         is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
97         is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
98 }
99
100 SKIP: {
101         my $conn = conn_for($sock, 'excessive header');
102         $SIG{PIPE} = 'IGNORE';
103         $conn->write("GET /callback HTTP/1.0\r\n");
104         foreach my $i (1..500000) {
105                 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
106         }
107         ok(!$conn->write("\r\n"), 'broken request');
108         ok($conn->read(my $buf, 8192), 'read response');
109         my ($head, $body) = split(/\r\n\r\n/, $buf);
110         like($head, qr/\b400\b/, 'got 400 response');
111 }
112
113 {
114         my $conn = conn_for($sock, 'excessive body Content-Length');
115         $SIG{PIPE} = 'IGNORE';
116         my $n = (10 * 1024 * 1024) + 1;
117         $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
118         ok($conn->read(my $buf, 8192), 'read response');
119         my ($head, $body) = split(/\r\n\r\n/, $buf);
120         like($head, qr/\b413\b/, 'got 413 response');
121 }
122
123 {
124         my $conn = conn_for($sock, 'excessive body chunked');
125         $SIG{PIPE} = 'IGNORE';
126         my $n = (10 * 1024 * 1024) + 1;
127         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
128         $conn->write("\r\n".sprintf("%x\r\n", $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');
132 }
133
134 {
135         my $conn = conn_for($sock, 'chunk with pipeline');
136         my $n = 10;
137         my $payload = 'b'x$n;
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         $conn->write($payload . "\r\n0\r\n\r\nGET /empty HTTP/1.0\r\n\r\n");
141         $conn->read(my $buf, 4096);
142         my $lim = 0;
143         $lim++ while ($conn->read($buf, 4096, bytes::length($buf)) && $lim < 9);
144         my $exp = sha1_hex($payload);
145         like($buf, qr!\r\n\r\n${exp}HTTP/1\.0 200 OK\r\n!s,
146                 'chunk parser can handled pipelined requests');
147 }
148
149 # Unix domain sockets
150 {
151         my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
152         ok($u, 'unix socket connected');
153         $u->write("GET /host-port HTTP/1.0\r\n\r\n");
154         $u->read(my $buf, 4096);
155         like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
156                 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
157 }
158
159 sub conn_for {
160         my ($dest, $msg) = @_;
161         my $conn = tcp_connect($dest);
162         ok($conn, "connected for $msg");
163         setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
164         return $conn;
165 }
166
167 {
168         my $conn = conn_for($sock, 'host-port');
169         $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
170         $conn->read(my $buf, 4096);
171         my ($head, $body) = split(/\r\n\r\n/, $buf);
172         my ($addr, $port) = split(/:/, $body);
173         is($addr, $conn->sockhost, 'host matches addr');
174         is($port, $conn->sockport, 'port matches');
175 }
176
177 # graceful termination
178 {
179         my $conn = conn_for($sock, 'graceful termination via slow header');
180         $conn->write("GET /slow-header HTTP/1.0\r\n" .
181                         "X-Check-Fifo: $fifo\r\n\r\n");
182         open my $f, '>', $fifo or die "open $fifo: $!\n";
183         $f->autoflush(1);
184         ok(print($f "hello\n"), 'wrote something to fifo');
185         my $kpid = $pid;
186         $pid = undef;
187         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
188         ok(print($f "world\n"), 'wrote else to fifo');
189         close $f or die "close fifo: $!\n";
190         $conn->read(my $buf, 8192);
191         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
192         like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
193         is($body, "hello\nworld\n", 'read expected body');
194         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
195         is($?, 0, 'no error');
196         $spawn_httpd->('-W0');
197 }
198
199 {
200         my $conn = conn_for($sock, 'graceful termination via slow-body');
201         $conn->write("GET /slow-body HTTP/1.0\r\n" .
202                         "X-Check-Fifo: $fifo\r\n\r\n");
203         open my $f, '>', $fifo or die "open $fifo: $!\n";
204         $f->autoflush(1);
205         my $buf;
206         $conn->sysread($buf, 8192);
207         like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
208         like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
209
210         foreach my $c ('a'..'c') {
211                 $c .= "\n";
212                 ok(print($f $c), 'wrote line to fifo');
213                 $conn->sysread($buf, 8192);
214                 is($buf, $c, 'got trickle for reading');
215         }
216         my $kpid = $pid;
217         $pid = undef;
218         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
219         ok(print($f "world\n"), 'wrote else to fifo');
220         close $f or die "close fifo: $!\n";
221         $conn->sysread($buf, 8192);
222         is($buf, "world\n", 'read expected body');
223         is($conn->sysread($buf, 8192), 0, 'got EOF from server');
224         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
225         is($?, 0, 'no error');
226         $spawn_httpd->('-W0');
227 }
228
229 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
230
231 my $str = 'abcdefghijklmnopqrstuvwxyz';
232 my $len = length $str;
233 is($len, 26, 'got the alphabet');
234 my $check_self = sub {
235         my ($conn) = @_;
236         $conn->read(my $buf, 4096);
237         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
238         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
239         is($body, sha1_hex($str), 'read expected body');
240 };
241
242 SKIP: {
243         my $have_curl = 0;
244         foreach my $p (split(':', $ENV{PATH})) {
245                 -x "$p/curl" or next;
246                 $have_curl = 1;
247                 last;
248         }
249         my $ntest = 4;
250         $have_curl or skip('curl(1) missing', $ntest);
251         my $base = 'http://' . $sock->sockhost . ':' . $sock->sockport;
252         my $url = "$base/sha1";
253         my ($r, $w);
254         pipe($r, $w) or die "pipe: $!";
255         my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
256         my ($out, $err) = ('', '');
257         my $h = IPC::Run::start($cmd, $r, \$out, \$err);
258         $w->autoflush(1);
259         foreach my $c ('a'..'z') {
260                 print $w $c or die "failed to write to curl: $!";
261                 delay();
262         }
263         close $w or die "close write pipe: $!";
264         close $r or die "close read pipe: $!";
265         IPC::Run::finish($h);
266         is($?, 0, 'curl exited successfully');
267         is($err, '', 'no errors from curl');
268         is($out, sha1_hex($str), 'read expected body');
269
270         open my $fh, '-|', qw(curl -sS), "$base/async-big" or die $!;
271         my $n = 0;
272         my $non_zero = 0;
273         while (1) {
274                 my $r = sysread($fh, my $buf, 4096) or last;
275                 $n += $r;
276                 $buf =~ /\A\0+\z/ or $non_zero++;
277         }
278         is($n, 30 * 1024 * 1024, 'got expected output from curl');
279         is($non_zero, 0, 'read all zeros');
280 }
281
282 {
283         my $conn = conn_for($sock, '1.1 pipeline together');
284         $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
285                         "PUT /sha1 HTTP/1.1\r\n\r\n");
286         my $buf = '';
287         my @r;
288         until (scalar(@r) >= 2) {
289                 my $r = $conn->sysread(my $tmp, 4096);
290                 die $! unless defined $r;
291                 die "EOF <$buf>" unless $r;
292                 $buf .= $tmp;
293                 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
294         }
295         is(2, scalar @r, 'got 2 responses');
296         my $i = 3;
297         foreach my $hex (@r) {
298                 is($hex, sha1_hex(''), "read expected body $i");
299                 $i++;
300         }
301 }
302
303 {
304         my $conn = conn_for($sock, 'no TCP_CORK on empty body');
305         $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
306         my $buf = '';
307         my $t0 = [ gettimeofday ];
308         until ($buf =~ /\r\n\r\n/s) {
309                 $conn->sysread($buf, 4096, length($buf));
310         }
311         my $elapsed = tv_interval($t0, [ gettimeofday ]);
312         ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
313 }
314
315 {
316         my $conn = conn_for($sock, 'graceful termination during slow request');
317         $conn->write("PUT /sha1 HTTP/1.0\r\n");
318         delay();
319         $conn->write("Content-Length: $len\r\n");
320         delay();
321         $conn->write("\r\n");
322         my $kpid = $pid;
323         $pid = undef;
324         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
325         delay();
326         my $n = 0;
327         foreach my $c ('a'..'z') {
328                 $n += $conn->write($c);
329         }
330         is($n, $len, 'wrote alphabet');
331         $check_self->($conn);
332         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
333         is($?, 0, 'no error');
334         $spawn_httpd->('-W0');
335 }
336
337 # various DoS attacks against the chunk parser:
338 {
339         local $SIG{PIPE} = 'IGNORE';
340         my $conn = conn_for($sock, '1.1 chunk header excessive');
341         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
342         my $n = 0;
343         my $w;
344         while ($w = $conn->write('ffffffff')) {
345                 $n += $w;
346         }
347         ok($!, 'got error set in $!');
348         is($w, undef, 'write error happened');
349         ok($n > 0, 'was able to write');
350         my $r = $conn->read(my $buf, 66666);
351         ok($r > 0, 'got non-empty response');
352         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
353
354         $conn = conn_for($sock, '1.1 chunk trailer excessive');
355         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
356         is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
357         delay();
358         $n = 0;
359         while ($w = $conn->write("\r")) {
360                 $n += $w;
361         }
362         ok($!, 'got error set in $!');
363         ok($n > 0, 'wrote part of chunk end (\r)');
364         $r = $conn->read($buf, 66666);
365         ok($r > 0, 'got non-empty response');
366         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
367 }
368
369 {
370         my $conn = conn_for($sock, '1.1 chunked close trickle');
371         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
372         $conn->write("Transfer-encoding: chunked\r\n\r\n");
373         foreach my $x ('a'..'z') {
374                 delay();
375                 $conn->write('1');
376                 delay();
377                 $conn->write("\r");
378                 delay();
379                 $conn->write("\n");
380                 delay();
381                 $conn->write($x);
382                 delay();
383                 $conn->write("\r");
384                 delay();
385                 $conn->write("\n");
386         }
387         $conn->write('0');
388         delay();
389         $conn->write("\r");
390         delay();
391         $conn->write("\n");
392         delay();
393         $conn->write("\r");
394         delay();
395         $conn->write("\n");
396         delay();
397         $check_self->($conn);
398 }
399
400 {
401         my $conn = conn_for($sock, '1.1 chunked close');
402         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
403         my $xlen = sprintf('%x', $len);
404         $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
405                 "$str\r\n0\r\n\r\n");
406         $check_self->($conn);
407 }
408
409 {
410         my $conn = conn_for($sock, 'chunked body + pipeline');
411         $conn->write("PUT /sha1 HTTP/1.1\r\n" .
412                         "Transfer-Encoding: chunked\r\n");
413         delay();
414         $conn->write("\r\n1\r\n");
415         delay();
416         $conn->write('a');
417         delay();
418         $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
419         delay();
420
421         my $buf = '';
422         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
423                 $conn->sysread(my $tmp, 4096);
424                 $buf .= $tmp;
425         }
426         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
427         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
428         is($body, sha1_hex('a'), 'read expected body');
429
430         $conn->write("Connection: close\r\n");
431         $conn->write("Content-Length: $len\r\n\r\n$str");
432         $check_self->($conn);
433 }
434
435 {
436         my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
437         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
438                         "Connection: keep-alive\r\n");
439         delay();
440         $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
441         my $buf = '';
442         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
443                 $conn->sysread(my $tmp, 4096);
444                 $buf .= $tmp;
445         }
446         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
447         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
448         is($body, sha1_hex($str), 'read expected body');
449
450         $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
451         $check_self->($conn);
452 }
453
454 {
455         my $conn = conn_for($sock, 'trickle body');
456         $conn->write("PUT /sha1 HTTP/1.0\r\n");
457         $conn->write("Content-Length: $len\r\n\r\n");
458         my $beg = substr($str, 0, 10);
459         my $end = substr($str, 10);
460         is($beg . $end, $str, 'substr setup correct');
461         delay();
462         $conn->write($beg);
463         delay();
464         $conn->write($end);
465         $check_self->($conn);
466 }
467
468 {
469         my $conn = conn_for($sock, 'one-shot write');
470         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
471                         "Content-Length: $len\r\n\r\n$str");
472         $check_self->($conn);
473 }
474
475 {
476         my $conn = conn_for($sock, 'trickle header, one-shot body');
477         $conn->write("PUT /sha1 HTTP/1.0\r\n");
478         delay();
479         $conn->write("Content-Length: $len\r\n\r\n$str");
480         $check_self->($conn);
481 }
482
483 {
484         my $conn = conn_for($sock, '1.1 Connnection: close');
485         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
486         delay();
487         $conn->write("Content-Length: $len\r\n\r\n$str");
488         $check_self->($conn);
489 }
490
491 {
492         my $conn = conn_for($sock, '1.1 pipeline start');
493         $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
494         my $buf = '';
495         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
496                 $conn->sysread(my $tmp, 4096);
497                 $buf .= $tmp;
498         }
499         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
500         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
501         is($body, sha1_hex(''), 'read expected body');
502
503         # 2nd request
504         $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
505         $buf = '';
506         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
507                 $conn->sysread(my $tmp, 4096);
508                 $buf .= $tmp;
509         }
510         ($head, $body) = split(/\r\n\r\n/, $buf, 2);
511         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
512         is($body, sha1_hex(''), 'read expected body #2');
513 }
514
515 SKIP: {
516         skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
517         my $var = Socket::TCP_DEFER_ACCEPT();
518         defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
519         is(unpack('i', $x), $defer_accept_val,
520                 'TCP_DEFER_ACCEPT unchanged if previously set');
521 };
522 SKIP: {
523         skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
524         skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
525         my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
526         defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
527         is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
528 };
529 SKIP: {
530         use PublicInbox::Spawn qw(which);
531         skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
532         skip 'no lsof in PATH', 1 unless which('lsof');
533         my @lsof = `lsof -p $pid`;
534         is_deeply([grep(/\bdeleted\b/, @lsof)], [], 'no lingering deleted inputs');
535         is_deeply([grep(/\bpipe\b/, @lsof)], [], 'no extra pipes with -W0');
536 };
537
538 done_testing();
539
540 sub capture {
541         my ($f) = @_;
542         open my $fh, '+<', $f or die "failed to open $f: $!\n";
543         local $/ = "\n";
544         my @r = <$fh>;
545         truncate($fh, 0) or die "truncate failed on $f: $!\n";
546         \@r
547 }
548
549 1;