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