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