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