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