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