]> Sergey Matveev's repositories - public-inbox.git/blob - t/httpd-corner.t
tests: get rid of unnecessary Cwd module use
[public-inbox.git] / t / httpd-corner.t
1 # Copyright (C) 2016-2018 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 Rack 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);
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 %opts = (
32         LocalAddr => '127.0.0.1',
33         ReuseAddr => 1,
34         Proto => 'tcp',
35         Type => SOCK_STREAM,
36         Listen => 1024,
37 );
38 my $sock = IO::Socket::INET->new(%opts);
39 my $upath = "$tmpdir/s";
40 my $unix = IO::Socket::UNIX->new(
41         Listen => 1024,
42         Type => SOCK_STREAM,
43         Local => $upath
44 );
45 ok($unix, 'UNIX socket created');
46 my $pid;
47 END { kill 'TERM', $pid if defined $pid };
48 my $spawn_httpd = sub {
49         my (@args) = @_;
50         my $cmd = [ $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi ];
51         $pid = spawn_listener(undef, $cmd, [ $sock, $unix ]);
52         ok(defined $pid, 'forked httpd process successfully');
53 };
54
55 {
56         ok($sock, 'sock created');
57         $spawn_httpd->('-W0');
58 }
59
60 {
61         my $conn = conn_for($sock, 'streaming callback');
62         $conn->write("GET /callback HTTP/1.0\r\n\r\n");
63         ok($conn->read(my $buf, 8192), 'read response');
64         my ($head, $body) = split(/\r\n\r\n/, $buf);
65         is($body, "hello world\n", 'callback body matches expected');
66 }
67
68 {
69         my $conn = conn_for($sock, 'getline-die');
70         $conn->write("GET /getline-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
71         ok($conn->read(my $buf, 8192), 'read some response');
72         like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
73         is($conn->read(my $nil, 8192), 0, 'read EOF');
74         $conn = undef;
75         my $after = capture($err);
76         is(scalar(grep(/GETLINE FAIL/, @$after)), 1, 'failure logged');
77         is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
78 }
79
80 {
81         my $conn = conn_for($sock, 'close-die');
82         $conn->write("GET /close-die HTTP/1.1\r\nHost: example.com\r\n\r\n");
83         ok($conn->read(my $buf, 8192), 'read some response');
84         like($buf, qr!HTTP/1\.1 200\b[^\r]*\r\n!, 'got some sort of header');
85         is($conn->read(my $nil, 8192), 0, 'read EOF');
86         $conn = undef;
87         my $after = capture($err);
88         is(scalar(grep(/GETLINE FAIL/, @$after)), 0, 'getline not failed');
89         is(scalar(grep(/CLOSE FAIL/, @$after)), 1, 'body->close not called');
90 }
91
92 {
93         my $conn = conn_for($sock, 'excessive header');
94         $SIG{PIPE} = 'IGNORE';
95         $conn->write("GET /callback HTTP/1.0\r\n");
96         foreach my $i (1..500000) {
97                 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
98         }
99         ok(!$conn->write("\r\n"), 'broken request');
100         ok($conn->read(my $buf, 8192), 'read response');
101         my ($head, $body) = split(/\r\n\r\n/, $buf);
102         like($head, qr/\b400\b/, 'got 400 response');
103 }
104
105 {
106         my $conn = conn_for($sock, 'excessive body Content-Length');
107         $SIG{PIPE} = 'IGNORE';
108         my $n = (10 * 1024 * 1024) + 1;
109         $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
110         ok($conn->read(my $buf, 8192), 'read response');
111         my ($head, $body) = split(/\r\n\r\n/, $buf);
112         like($head, qr/\b413\b/, 'got 413 response');
113 }
114
115 {
116         my $conn = conn_for($sock, 'excessive body chunked');
117         $SIG{PIPE} = 'IGNORE';
118         my $n = (10 * 1024 * 1024) + 1;
119         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
120         $conn->write("\r\n".sprintf("%x\r\n", $n));
121         ok($conn->read(my $buf, 8192), 'read response');
122         my ($head, $body) = split(/\r\n\r\n/, $buf);
123         like($head, qr/\b413\b/, 'got 413 response');
124 }
125
126 # Unix domain sockets
127 {
128         my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
129         ok($u, 'unix socket connected');
130         $u->write("GET /host-port HTTP/1.0\r\n\r\n");
131         $u->read(my $buf, 4096);
132         like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
133                 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
134 }
135
136 sub conn_for {
137         my ($sock, $msg) = @_;
138         my $conn = IO::Socket::INET->new(
139                                 PeerAddr => $sock->sockhost,
140                                 PeerPort => $sock->sockport,
141                                 Proto => 'tcp',
142                                 Type => SOCK_STREAM);
143         ok($conn, "connected for $msg");
144         $conn->autoflush(1);
145         setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
146         return $conn;
147 }
148
149 {
150         my $conn = conn_for($sock, 'host-port');
151         $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
152         $conn->read(my $buf, 4096);
153         my ($head, $body) = split(/\r\n\r\n/, $buf);
154         my ($addr, $port) = split(/:/, $body);
155         is($addr, $conn->sockhost, 'host matches addr');
156         is($port, $conn->sockport, 'port matches');
157 }
158
159 # graceful termination
160 {
161         my $conn = conn_for($sock, 'graceful termination via slow header');
162         $conn->write("GET /slow-header HTTP/1.0\r\n" .
163                         "X-Check-Fifo: $fifo\r\n\r\n");
164         open my $f, '>', $fifo or die "open $fifo: $!\n";
165         $f->autoflush(1);
166         ok(print($f "hello\n"), 'wrote something to fifo');
167         my $kpid = $pid;
168         $pid = undef;
169         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
170         ok(print($f "world\n"), 'wrote else to fifo');
171         close $f or die "close fifo: $!\n";
172         $conn->read(my $buf, 8192);
173         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
174         like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
175         is($body, "hello\nworld\n", 'read expected body');
176         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
177         is($?, 0, 'no error');
178         $spawn_httpd->('-W0');
179 }
180
181 {
182         my $conn = conn_for($sock, 'graceful termination via slow-body');
183         $conn->write("GET /slow-body HTTP/1.0\r\n" .
184                         "X-Check-Fifo: $fifo\r\n\r\n");
185         open my $f, '>', $fifo or die "open $fifo: $!\n";
186         $f->autoflush(1);
187         my $buf;
188         $conn->sysread($buf, 8192);
189         like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
190         like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
191
192         foreach my $c ('a'..'c') {
193                 $c .= "\n";
194                 ok(print($f $c), 'wrote line to fifo');
195                 $conn->sysread($buf, 8192);
196                 is($buf, $c, 'got trickle for reading');
197         }
198         my $kpid = $pid;
199         $pid = undef;
200         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
201         ok(print($f "world\n"), 'wrote else to fifo');
202         close $f or die "close fifo: $!\n";
203         $conn->sysread($buf, 8192);
204         is($buf, "world\n", 'read expected body');
205         is($conn->sysread($buf, 8192), 0, 'got EOF from server');
206         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
207         is($?, 0, 'no error');
208         $spawn_httpd->('-W0');
209 }
210
211 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
212
213 my $str = 'abcdefghijklmnopqrstuvwxyz';
214 my $len = length $str;
215 is($len, 26, 'got the alphabet');
216 my $check_self = sub {
217         my ($conn) = @_;
218         $conn->read(my $buf, 4096);
219         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
220         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
221         is($body, sha1_hex($str), 'read expected body');
222 };
223
224 SKIP: {
225         my $have_curl = 0;
226         foreach my $p (split(':', $ENV{PATH})) {
227                 -x "$p/curl" or next;
228                 $have_curl = 1;
229                 last;
230         }
231         my $ntest = 2;
232         $have_curl or skip('curl(1) missing', $ntest);
233         my $url = 'http://' . $sock->sockhost . ':' . $sock->sockport . '/sha1';
234         my ($r, $w);
235         pipe($r, $w) or die "pipe: $!";
236         my $cmd = [qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url];
237         my ($out, $err) = ('', '');
238         my $h = IPC::Run::start($cmd, $r, \$out, \$err);
239         $w->autoflush(1);
240         foreach my $c ('a'..'z') {
241                 print $w $c or die "failed to write to curl: $!";
242                 delay();
243         }
244         close $w or die "close write pipe: $!";
245         close $r or die "close read pipe: $!";
246         IPC::Run::finish($h);
247         is($?, 0, 'curl exited successfully');
248         is($err, '', 'no errors from curl');
249         is($out, sha1_hex($str), 'read expected body');
250 }
251
252 {
253         my $conn = conn_for($sock, '1.1 pipeline together');
254         $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
255                         "PUT /sha1 HTTP/1.1\r\n\r\n");
256         my $buf = '';
257         my @r;
258         until (scalar(@r) >= 2) {
259                 my $r = $conn->sysread(my $tmp, 4096);
260                 die $! unless defined $r;
261                 die "EOF <$buf>" unless $r;
262                 $buf .= $tmp;
263                 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
264         }
265         is(2, scalar @r, 'got 2 responses');
266         my $i = 3;
267         foreach my $hex (@r) {
268                 is($hex, sha1_hex(''), "read expected body $i");
269                 $i++;
270         }
271 }
272
273 {
274         my $conn = conn_for($sock, 'no TCP_CORK on empty body');
275         $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
276         my $buf = '';
277         my $t0 = [ gettimeofday ];
278         until ($buf =~ /\r\n\r\n/s) {
279                 $conn->sysread($buf, 4096, length($buf));
280         }
281         my $elapsed = tv_interval($t0, [ gettimeofday ]);
282         ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
283 }
284
285 {
286         my $conn = conn_for($sock, 'graceful termination during slow request');
287         $conn->write("PUT /sha1 HTTP/1.0\r\n");
288         delay();
289         $conn->write("Content-Length: $len\r\n");
290         delay();
291         $conn->write("\r\n");
292         my $kpid = $pid;
293         $pid = undef;
294         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
295         delay();
296         my $n = 0;
297         foreach my $c ('a'..'z') {
298                 $n += $conn->write($c);
299         }
300         is($n, $len, 'wrote alphabet');
301         $check_self->($conn);
302         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
303         is($?, 0, 'no error');
304         $spawn_httpd->('-W0');
305 }
306
307 # various DoS attacks against the chunk parser:
308 {
309         local $SIG{PIPE} = 'IGNORE';
310         my $conn = conn_for($sock, '1.1 chunk header excessive');
311         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
312         my $n = 0;
313         my $w;
314         while ($w = $conn->write('ffffffff')) {
315                 $n += $w;
316         }
317         ok($!, 'got error set in $!');
318         is($w, undef, 'write error happened');
319         ok($n > 0, 'was able to write');
320         my $r = $conn->read(my $buf, 66666);
321         ok($r > 0, 'got non-empty response');
322         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
323
324         $conn = conn_for($sock, '1.1 chunk trailer excessive');
325         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
326         is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
327         delay();
328         $n = 0;
329         while ($w = $conn->write("\r")) {
330                 $n += $w;
331         }
332         ok($!, 'got error set in $!');
333         ok($n > 0, 'wrote part of chunk end (\r)');
334         $r = $conn->read($buf, 66666);
335         ok($r > 0, 'got non-empty response');
336         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
337 }
338
339 {
340         my $conn = conn_for($sock, '1.1 chunked close trickle');
341         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
342         $conn->write("Transfer-encoding: chunked\r\n\r\n");
343         foreach my $x ('a'..'z') {
344                 delay();
345                 $conn->write('1');
346                 delay();
347                 $conn->write("\r");
348                 delay();
349                 $conn->write("\n");
350                 delay();
351                 $conn->write($x);
352                 delay();
353                 $conn->write("\r");
354                 delay();
355                 $conn->write("\n");
356         }
357         $conn->write('0');
358         delay();
359         $conn->write("\r");
360         delay();
361         $conn->write("\n");
362         delay();
363         $conn->write("\r");
364         delay();
365         $conn->write("\n");
366         delay();
367         $check_self->($conn);
368 }
369
370 {
371         my $conn = conn_for($sock, '1.1 chunked close');
372         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
373         my $xlen = sprintf('%x', $len);
374         $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
375                 "$str\r\n0\r\n\r\n");
376         $check_self->($conn);
377 }
378
379 {
380         my $conn = conn_for($sock, 'chunked body + pipeline');
381         $conn->write("PUT /sha1 HTTP/1.1\r\n" .
382                         "Transfer-Encoding: chunked\r\n");
383         delay();
384         $conn->write("\r\n1\r\n");
385         delay();
386         $conn->write('a');
387         delay();
388         $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
389         delay();
390
391         my $buf = '';
392         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
393                 $conn->sysread(my $tmp, 4096);
394                 $buf .= $tmp;
395         }
396         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
397         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
398         is($body, sha1_hex('a'), 'read expected body');
399
400         $conn->write("Connection: close\r\n");
401         $conn->write("Content-Length: $len\r\n\r\n$str");
402         $check_self->($conn);
403 }
404
405 {
406         my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
407         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
408                         "Connection: keep-alive\r\n");
409         delay();
410         $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
411         my $buf = '';
412         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
413                 $conn->sysread(my $tmp, 4096);
414                 $buf .= $tmp;
415         }
416         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
417         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
418         is($body, sha1_hex($str), 'read expected body');
419
420         $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
421         $check_self->($conn);
422 }
423
424 {
425         my $conn = conn_for($sock, 'trickle body');
426         $conn->write("PUT /sha1 HTTP/1.0\r\n");
427         $conn->write("Content-Length: $len\r\n\r\n");
428         my $beg = substr($str, 0, 10);
429         my $end = substr($str, 10);
430         is($beg . $end, $str, 'substr setup correct');
431         delay();
432         $conn->write($beg);
433         delay();
434         $conn->write($end);
435         $check_self->($conn);
436 }
437
438 {
439         my $conn = conn_for($sock, 'one-shot write');
440         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
441                         "Content-Length: $len\r\n\r\n$str");
442         $check_self->($conn);
443 }
444
445 {
446         my $conn = conn_for($sock, 'trickle header, one-shot body');
447         $conn->write("PUT /sha1 HTTP/1.0\r\n");
448         delay();
449         $conn->write("Content-Length: $len\r\n\r\n$str");
450         $check_self->($conn);
451 }
452
453 {
454         my $conn = conn_for($sock, '1.1 Connnection: close');
455         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
456         delay();
457         $conn->write("Content-Length: $len\r\n\r\n$str");
458         $check_self->($conn);
459 }
460
461 {
462         my $conn = conn_for($sock, '1.1 pipeline start');
463         $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
464         my $buf = '';
465         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
466                 $conn->sysread(my $tmp, 4096);
467                 $buf .= $tmp;
468         }
469         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
470         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
471         is($body, sha1_hex(''), 'read expected body');
472
473         # 2nd request
474         $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
475         $buf = '';
476         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
477                 $conn->sysread(my $tmp, 4096);
478                 $buf .= $tmp;
479         }
480         ($head, $body) = split(/\r\n\r\n/, $buf, 2);
481         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
482         is($body, sha1_hex(''), 'read expected body #2');
483 }
484
485 done_testing();
486
487 sub capture {
488         my ($f) = @_;
489         open my $fh, '+<', $f or die "failed to open $f: $!\n";
490         local $/ = "\n";
491         my @r = <$fh>;
492         truncate($fh, 0) or die "truncate failed on $f: $!\n";
493         \@r
494 }
495
496 1;