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