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