]> Sergey Matveev's repositories - public-inbox.git/blob - t/httpd-corner.t
No ext_urls
[public-inbox.git] / t / httpd-corner.t
1 # Copyright (C) 2016-2021 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; use v5.10.1; use PublicInbox::TestCommon;
6 use Time::HiRes qw(gettimeofday tv_interval);
7 use PublicInbox::Spawn qw(spawn popen_rd);
8 require_mods(qw(Plack::Util Plack::Builder HTTP::Date HTTP::Status));
9 use Digest::SHA qw(sha1_hex);
10 use IO::Handle ();
11 use IO::Socket::UNIX;
12 use Fcntl qw(:seek);
13 use Socket qw(IPPROTO_TCP TCP_NODELAY SOL_SOCKET);
14 use POSIX qw(mkfifo);
15 use Carp ();
16 my ($tmpdir, $for_destroy) = tmpdir();
17 my $fifo = "$tmpdir/fifo";
18 ok(defined mkfifo($fifo, 0777), 'created FIFO');
19 my $err = "$tmpdir/stderr.log";
20 my $out = "$tmpdir/stdout.log";
21 my $psgi = "./t/httpd-corner.psgi";
22 my $sock = tcp_server() or die;
23 my @zmods = qw(PublicInbox::GzipFilter IO::Uncompress::Gunzip);
24
25 # Make sure we don't clobber socket options set by systemd or similar
26 # using socket activation:
27 my ($defer_accept_val, $accf_arg, $TCP_DEFER_ACCEPT);
28 if ($^O eq 'linux') {
29         $TCP_DEFER_ACCEPT = eval { Socket::TCP_DEFER_ACCEPT() } // 9;
30         setsockopt($sock, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 5) or die;
31         my $x = getsockopt($sock, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
32         defined $x or die "getsockopt: $!";
33         $defer_accept_val = unpack('i', $x);
34         if ($defer_accept_val <= 0) {
35                 die "unexpected TCP_DEFER_ACCEPT value: $defer_accept_val";
36         }
37 } elsif ($^O eq 'freebsd' && system('kldstat -m accf_data >/dev/null') == 0) {
38         require PublicInbox::Daemon;
39         my $var = $PublicInbox::Daemon::SO_ACCEPTFILTER;
40         $accf_arg = pack('a16a240', 'dataready', '');
41         setsockopt($sock, SOL_SOCKET, $var, $accf_arg) or die "setsockopt: $!";
42 }
43
44 sub unix_server ($) {
45         my $s = IO::Socket::UNIX->new(
46                 Listen => 1024,
47                 Type => Socket::SOCK_STREAM(),
48                 Local => $_[0],
49         ) or BAIL_OUT "bind + listen $_[0]: $!";
50         $s->blocking(0);
51         $s;
52 }
53
54 my $upath = "$tmpdir/s";
55 my $unix = unix_server($upath);
56 my $td;
57 my $spawn_httpd = sub {
58         my (@args) = @_;
59         my $cmd = [ '-httpd', @args, "--stdout=$out", "--stderr=$err", $psgi ];
60         $td = start_script($cmd, undef, { 3 => $sock, 4 => $unix });
61 };
62
63 $spawn_httpd->();
64 if ('test worker death') {
65         my $conn = conn_for($sock, 'killed worker');
66         $conn->write("GET /pid HTTP/1.1\r\nHost:example.com\r\n\r\n");
67         my $pid;
68         while (defined(my $line = $conn->getline)) {
69                 next unless $line eq "\r\n";
70                 chomp($pid = $conn->getline);
71                 last;
72         }
73         like($pid, qr/\A[0-9]+\z/, '/pid response');
74         is(kill('KILL', $pid), 1, 'killed worker');
75         is($conn->getline, undef, 'worker died and EOF-ed client');
76
77         $conn = conn_for($sock, 'respawned worker');
78         $conn->write("GET /pid HTTP/1.0\r\n\r\n");
79         ok($conn->read(my $buf, 8192), 'read response');
80         my ($head, $body) = split(/\r\n\r\n/, $buf);
81         chomp($body);
82         like($body, qr/\A[0-9]+\z/, '/pid response');
83         isnt($body, $pid, 'respawned worker');
84 }
85 {
86         my $conn = conn_for($sock, 'Header spaces bogus');
87         $conn->write("GET /empty HTTP/1.1\r\nSpaced-Out : 3\r\n\r\n");
88         $conn->read(my $buf, 4096);
89         like($buf, qr!\AHTTP/1\.[0-9] 400 !, 'got 400 response on bad request');
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, (tcp_host_port($conn))[0], '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 = require_cmd('curl', 1) or skip('curl(1) missing', 4);
309         my $base = 'http://'.tcp_host_port($sock);
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, 4);
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         my $curl_rdr = { 2 => \(my $curl_err = '') };
349         $buf = xqx([$curl, qw(-sSv --compressed),
350                         "$base/psgi-return-compressible"], undef, $curl_rdr);
351         is($?, 0, 'curl --compressed successful');
352         is($buf, "goodbye world\n", 'gzipped response as expected');
353         like($curl_err, qr/\bContent-Encoding: gzip\b/,
354                 'curl got gzipped response');
355 }
356
357 {
358         my $conn = conn_for($sock, 'psgi_return ENOENT');
359         print $conn "GET /psgi-return-enoent HTTP/1.1\r\n\r\n" or die;
360         my $buf = '';
361         sysread($conn, $buf, 16384, length($buf)) until $buf =~ /\r\n\r\n/;
362         like($buf, qr!HTTP/1\.[01] 500\b!, 'got 500 error on ENOENT');
363 }
364
365 {
366         my $conn = conn_for($sock, '1.1 pipeline together');
367         $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
368                         "PUT /sha1 HTTP/1.1\r\n\r\n");
369         my $buf = '';
370         my @r;
371         until (scalar(@r) >= 2) {
372                 my $r = $conn->sysread(my $tmp, 4096);
373                 die $! unless defined $r;
374                 die "EOF <$buf>" unless $r;
375                 $buf .= $tmp;
376                 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
377         }
378         is(2, scalar @r, 'got 2 responses');
379         my $i = 3;
380         foreach my $hex (@r) {
381                 is($hex, sha1_hex(''), "read expected body $i");
382                 $i++;
383         }
384 }
385
386 {
387         my $conn = conn_for($sock, 'no TCP_CORK on empty body');
388         $conn->write("GET /empty HTTP/1.1\r\nHost:example.com\r\n\r\n");
389         my $buf = '';
390         my $t0 = [ gettimeofday ];
391         until ($buf =~ /\r\n\r\n/s) {
392                 $conn->sysread($buf, 4096, length($buf));
393         }
394         my $elapsed = tv_interval($t0, [ gettimeofday ]);
395         ok($elapsed < 0.190, 'no 200ms TCP cork delay on empty body');
396 }
397
398 {
399         my $conn = conn_for($sock, 'graceful termination during slow request');
400         $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n");
401
402         # XXX ugh, want a reliable and non-intrusive way to detect
403         # that the server has started buffering our partial request so we
404         # can reliably test graceful termination.  Maybe making this and
405         # similar tests dependent on Linux strace is a possibility?
406         delay(0.1);
407
408         is($td->kill, 1, 'start graceful shutdown');
409         my $n = 0;
410         foreach my $c ('a'..'z') {
411                 $n += $conn->write($c);
412         }
413         ok(kill(0, $td->{pid}), 'graceful shutdown did not kill httpd');
414         is($n, $len, 'wrote alphabet');
415         $check_self->($conn);
416         $td->join;
417         is($?, 0, 'no error');
418         $spawn_httpd->('-W0');
419 }
420
421 # various DoS attacks against the chunk parser:
422 {
423         local $SIG{PIPE} = 'IGNORE';
424         my $conn = conn_for($sock, '1.1 chunk header excessive');
425         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
426         my $n = 0;
427         my $w;
428         while ($w = $conn->write('ffffffff')) {
429                 $n += $w;
430         }
431         ok($!, 'got error set in $!');
432         is($w, undef, 'write error happened');
433         ok($n > 0, 'was able to write');
434         check_400($conn);
435         $conn = conn_for($sock, '1.1 chunk trailer excessive');
436         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
437         is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
438         delay();
439         $n = 0;
440         while ($w = $conn->write("\r")) {
441                 $n += $w;
442         }
443         ok($!, 'got error set in $!');
444         ok($n > 0, 'wrote part of chunk end (\r)');
445         check_400($conn);
446 }
447
448 {
449         my $conn = conn_for($sock, '1.1 chunked close trickle');
450         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
451         $conn->write("Transfer-encoding: chunked\r\n\r\n");
452         foreach my $x ('a'..'z') {
453                 delay();
454                 $conn->write('1');
455                 delay();
456                 $conn->write("\r");
457                 delay();
458                 $conn->write("\n");
459                 delay();
460                 $conn->write($x);
461                 delay();
462                 $conn->write("\r");
463                 delay();
464                 $conn->write("\n");
465         }
466         $conn->write('0');
467         delay();
468         $conn->write("\r");
469         delay();
470         $conn->write("\n");
471         delay();
472         $conn->write("\r");
473         delay();
474         $conn->write("\n");
475         delay();
476         $check_self->($conn);
477 }
478
479 {
480         my $conn = conn_for($sock, '1.1 chunked close');
481         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
482         my $xlen = sprintf('%x', $len);
483         $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
484                 "$str\r\n0\r\n\r\n");
485         $check_self->($conn);
486 }
487
488 {
489         my $conn = conn_for($sock, 'chunked body + pipeline');
490         $conn->write("PUT /sha1 HTTP/1.1\r\n" .
491                         "Transfer-Encoding: chunked\r\n");
492         delay();
493         $conn->write("\r\n1\r\n");
494         delay();
495         $conn->write('a');
496         delay();
497         $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
498         delay();
499
500         my $buf = '';
501         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
502                 $conn->sysread(my $tmp, 4096);
503                 $buf .= $tmp;
504         }
505         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
506         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
507         is($body, sha1_hex('a'), 'read expected body');
508
509         $conn->write("Connection: close\r\n");
510         $conn->write("Content-Length: $len\r\n\r\n$str");
511         $check_self->($conn);
512 }
513
514 {
515         my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
516         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
517                         "Connection: keep-alive\r\n");
518         delay();
519         $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
520         my $buf = '';
521         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
522                 $conn->sysread(my $tmp, 4096);
523                 $buf .= $tmp;
524         }
525         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
526         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
527         is($body, sha1_hex($str), 'read expected body');
528
529         $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
530         $check_self->($conn);
531 }
532
533 {
534         my $conn = conn_for($sock, 'trickle body');
535         $conn->write("PUT /sha1 HTTP/1.0\r\n");
536         $conn->write("Content-Length: $len\r\n\r\n");
537         my $beg = substr($str, 0, 10);
538         my $end = substr($str, 10);
539         is($beg . $end, $str, 'substr setup correct');
540         delay();
541         $conn->write($beg);
542         delay();
543         $conn->write($end);
544         $check_self->($conn);
545 }
546
547 {
548         my $conn = conn_for($sock, 'one-shot write');
549         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
550                         "Content-Length: $len\r\n\r\n$str");
551         $check_self->($conn);
552 }
553
554 {
555         my $conn = conn_for($sock, 'trickle header, one-shot body');
556         $conn->write("PUT /sha1 HTTP/1.0\r\n");
557         delay();
558         $conn->write("Content-Length: $len\r\n\r\n$str");
559         $check_self->($conn);
560 }
561
562 {
563         my $conn = conn_for($sock, '1.1 Connection: close');
564         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
565         delay();
566         $conn->write("Content-Length: $len\r\n\r\n$str");
567         $check_self->($conn);
568 }
569
570 {
571         my $conn = conn_for($sock, '1.1 pipeline start');
572         $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
573         my $buf = '';
574         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
575                 $conn->sysread(my $tmp, 4096);
576                 $buf .= $tmp;
577         }
578         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
579         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
580         is($body, sha1_hex(''), 'read expected body');
581
582         # 2nd request
583         $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
584         $buf = '';
585         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
586                 $conn->sysread(my $tmp, 4096);
587                 $buf .= $tmp;
588         }
589         ($head, $body) = split(/\r\n\r\n/, $buf, 2);
590         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
591         is($body, sha1_hex(''), 'read expected body #2');
592 }
593
594 SKIP: {
595         skip 'TCP_DEFER_ACCEPT is Linux-only', 1 if $^O ne 'linux';
596         my $var = $TCP_DEFER_ACCEPT;
597         defined(my $x = getsockopt($sock, IPPROTO_TCP, $var)) or die;
598         is(unpack('i', $x), $defer_accept_val,
599                 'TCP_DEFER_ACCEPT unchanged if previously set');
600 };
601 SKIP: {
602         skip 'SO_ACCEPTFILTER is FreeBSD-only', 1 if $^O ne 'freebsd';
603         skip 'accf_data not loaded: kldload accf_data' if !defined $accf_arg;
604         my $var = $PublicInbox::Daemon::SO_ACCEPTFILTER;
605         defined(my $x = getsockopt($sock, SOL_SOCKET, $var)) or die;
606         is($x, $accf_arg, 'SO_ACCEPTFILTER unchanged if previously set');
607 };
608
609 SKIP: {
610         skip 'only testing lsof(8) output on Linux', 1 if $^O ne 'linux';
611         my $lsof = require_cmd('lsof', 1) or skip 'no lsof in PATH', 1;
612         my $null_in = '';
613         my $rdr = { 2 => \(my $null_err), 0 => \$null_in };
614         my @lsof = xqx([$lsof, '-p', $td->{pid}], undef, $rdr);
615         my $d = [ grep(/\(deleted\)/, @lsof) ];
616         is_deeply($d, [], 'no lingering deleted inputs') or diag explain($d);
617
618         # filter out pipes inherited from the parent
619         my @this = xqx([$lsof, '-p', $$], undef, $rdr);
620         my $bad;
621         my $extract_inodes = sub {
622                 map {;
623                         my @f = split(' ', $_);
624                         my $inode = $f[-2];
625                         $bad = $_ if $inode !~ /\A[0-9]+\z/;
626                         $inode => 1;
627                 } grep (/\bpipe\b/, @_);
628         };
629         my %child = $extract_inodes->(@lsof);
630         my %parent = $extract_inodes->(@this);
631         skip("inode not in expected format: $bad", 1) if defined($bad);
632         delete @child{(keys %parent)};
633         is_deeply([], [keys %child], 'no extra pipes with -W0');
634 };
635
636 # ensure compatibility with other PSGI servers
637 SKIP: {
638         require_mods(@zmods, qw(Plack::Test HTTP::Request::Common), 3);
639         use_ok 'HTTP::Request::Common';
640         use_ok 'Plack::Test';
641         STDERR->flush;
642         open my $olderr, '>&', \*STDERR or die "dup stderr: $!";
643         open my $tmperr, '+>', undef or die;
644         open STDERR, '>&', $tmperr or die;
645         STDERR->autoflush(1);
646         my $app = require $psgi;
647         test_psgi($app, sub {
648                 my ($cb) = @_;
649                 my $req = GET('http://example.com/psgi-return-gzip');
650                 my $res = $cb->($req);
651                 my $buf = $res->content;
652                 IO::Uncompress::Gunzip::gunzip(\$buf => \(my $out));
653                 is($out, "hello world\n", 'got expected output');
654
655                 $req = GET('http://example.com/psgi-return-enoent');
656                 $res = $cb->($req);
657                 is($res->code, 500, 'got error on ENOENT');
658                 seek($tmperr, 0, SEEK_SET) or die;
659                 my $errbuf = do { local $/; <$tmperr> };
660                 like($errbuf, qr/this-better-not-exist/,
661                         'error logged about missing command');
662         });
663         open STDERR, '>&', $olderr or die "restore stderr: $!";
664 }
665
666 done_testing();
667
668 sub capture {
669         my ($f) = @_;
670         open my $fh, '+<', $f or die "failed to open $f: $!\n";
671         local $/ = "\n";
672         my @r = <$fh>;
673         truncate($fh, 0) or die "truncate failed on $f: $!\n";
674         \@r
675 }
676
677 1;