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