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