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