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