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