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