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