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