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