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