update dependency to Ruby 2.5+
[unicorn.git] / t / integration.t
blob7310ff29f402b6e29104be1c7560053cfa5389bb
1 #!perl -w
2 # Copyright (C) unicorn hackers <unicorn-public@yhbt.net>
3 # License: GPL-3.0+ <https://www.gnu.org/licenses/gpl-3.0.txt>
5 # This is the main integration test for fast-ish things to minimize
6 # Ruby startup time penalties.
8 use v5.14; BEGIN { require './t/lib.perl' };
9 use autodie;
10 use Socket qw(SOL_SOCKET SO_KEEPALIVE SHUT_WR);
11 our $srv = tcp_server();
12 our $host_port = tcp_host_port($srv);
14 if ('ensure Perl does not set SO_KEEPALIVE by default') {
15         my $val = getsockopt($srv, SOL_SOCKET, SO_KEEPALIVE);
16         unpack('i', $val) == 0 or
17                 setsockopt($srv, SOL_SOCKET, SO_KEEPALIVE, pack('i', 0));
18         $val = getsockopt($srv, SOL_SOCKET, SO_KEEPALIVE);
20 my $t0 = time;
21 open my $conf_fh, '>', $u_conf;
22 $conf_fh->autoflush(1);
23 my $u1 = "$tmpdir/u1";
24 print $conf_fh <<EOM;
25 early_hints true
26 listen "$u1"
27 EOM
28 my $ar = unicorn(qw(-E none t/integration.ru -c), $u_conf, { 3 => $srv });
29 my $curl = which('curl');
30 my $fifo = "$tmpdir/fifo";
31 POSIX::mkfifo($fifo, 0600) or die "mkfifo: $!";
32 my %PUT = (
33         chunked_md5 => sub {
34                 my ($in, $out, $path, %opt) = @_;
35                 my $dig = Digest::MD5->new;
36                 print $out <<EOM;
37 PUT $path HTTP/1.1\r
38 Transfer-Encoding: chunked\r
39 Trailer: Content-MD5\r
41 EOM
42                 my ($buf, $r);
43                 while (1) {
44                         $r = read($in, $buf, 999 + int(rand(0xffff)));
45                         last if $r == 0;
46                         printf $out "%x\r\n", length($buf);
47                         print $out $buf, "\r\n";
48                         $dig->add($buf);
49                 }
50                 print $out "0\r\nContent-MD5: ", $dig->b64digest, "\r\n\r\n";
51         },
52         identity => sub {
53                 my ($in, $out, $path, %opt) = @_;
54                 my $clen = $opt{-s} // -s $in;
55                 print $out <<EOM;
56 PUT $path HTTP/1.0\r
57 Content-Length: $clen\r
59 EOM
60                 my ($buf, $r, $len, $bs);
61                 while ($clen) {
62                         $bs = 999 + int(rand(0xffff));
63                         $len = $clen > $bs ? $bs : $clen;
64                         $r = read($in, $buf, $len);
65                         die 'premature EOF' if $r == 0;
66                         print $out $buf;
67                         $clen -= $r;
68                 }
69         },
72 my ($c, $status, $hdr, $bdy);
74 # response header tests
75 ($status, $hdr) = do_req($srv, 'GET /rack-2-newline-headers HTTP/1.0');
76 like($status, qr!\AHTTP/1\.[01] 200\b!, 'status line valid');
77 my $orig_200_status = $status;
78 is_deeply([ grep(/^X-R2: /, @$hdr) ],
79         [ 'X-R2: a', 'X-R2: b', 'X-R2: c' ],
80         'rack 2 LF-delimited headers supported') or diag(explain($hdr));
83         my $val = getsockopt($srv, SOL_SOCKET, SO_KEEPALIVE);
84         is(unpack('i', $val), 1, 'SO_KEEPALIVE set on inherited socket');
87 SKIP: { # Date header check
88         my @d = grep(/^Date: /i, @$hdr);
89         is(scalar(@d), 1, 'got one date header') or diag(explain(\@d));
90         eval { require HTTP::Date } or skip "HTTP::Date missing: $@", 1;
91         $d[0] =~ s/^Date: //i or die 'BUG: did not strip date: prefix';
92         my $t = HTTP::Date::str2time($d[0]);
93         my $now = time;
94         ok($t >= ($t0 - 1) && $t > 0 && $t <= ($now + 1), 'valid date') or
95                 diag(explain(["t=$t t0=$t0 now=$now", $!, \@d]));
99 ($status, $hdr) = do_req($srv, 'GET /rack-3-array-headers HTTP/1.0');
100 is_deeply([ grep(/^x-r3: /, @$hdr) ],
101         [ 'x-r3: a', 'x-r3: b', 'x-r3: c' ],
102         'rack 3 array headers supported') or diag(explain($hdr));
104 SKIP: {
105         eval { require JSON::PP } or skip "JSON::PP missing: $@", 1;
106         ($status, $hdr, my $json) = do_req $srv, 'GET /env_dump';
107         is($status, undef, 'no status for HTTP/0.9');
108         is($hdr, undef, 'no header for HTTP/0.9');
109         unlike($json, qr/^Connection: /smi, 'no connection header for 0.9');
110         unlike($json, qr!\AHTTP/!s, 'no HTTP/1.x prefix for 0.9');
111         my $env = JSON::PP->new->decode($json);
112         is(ref($env), 'HASH', 'JSON decoded body to hashref');
113         is($env->{SERVER_PROTOCOL}, 'HTTP/0.9', 'SERVER_PROTOCOL is 0.9');
116 # cf. <CAO47=rJa=zRcLn_Xm4v2cHPr6c0UswaFC_omYFEH+baSxHOWKQ@mail.gmail.com>
117 ($status, $hdr) = do_req($srv, 'GET /nil-header-value HTTP/1.0');
118 is_deeply([grep(/^X-Nil:/, @$hdr)], ['X-Nil: '],
119         'nil header value accepted for broken apps') or diag(explain($hdr));
121 check_stderr;
122 ($status, $hdr, $bdy) = do_req($srv, 'GET /broken_app HTTP/1.0');
123 like($status, qr!\AHTTP/1\.[0-1] 500\b!, 'got 500 error on broken endpoint');
124 is($bdy, undef, 'no response body after exception');
125 truncate($errfh, 0);
127 my $ck_early_hints = sub {
128         my ($note) = @_;
129         $c = unix_start($u1, 'GET /early_hints_rack2 HTTP/1.0');
130         ($status, $hdr) = slurp_hdr($c);
131         like($status, qr!\AHTTP/1\.[01] 103\b!, 'got 103 for rack 2 value');
132         is_deeply(['link: r', 'link: 2'], $hdr, 'rack 2 hints match '.$note);
133         ($status, $hdr) = slurp_hdr($c);
134         like($status, qr!\AHTTP/1\.[01] 200\b!, 'got 200 afterwards');
135         is(readline($c), 'String', 'early hints used a String for rack 2');
137         $c = unix_start($u1, 'GET /early_hints_rack3 HTTP/1.0');
138         ($status, $hdr) = slurp_hdr($c);
139         like($status, qr!\AHTTP/1\.[01] 103\b!, 'got 103 for rack 3');
140         is_deeply(['link: r', 'link: 3'], $hdr, 'rack 3 hints match '.$note);
141         ($status, $hdr) = slurp_hdr($c);
142         like($status, qr!\AHTTP/1\.[01] 200\b!, 'got 200 afterwards');
143         is(readline($c), 'Array', 'early hints used a String for rack 3');
145 $ck_early_hints->('ccc off'); # we'll retest later
147 if ('TODO: ensure Rack::Utils::HTTP_STATUS_CODES is available') {
148         ($status, $hdr) = do_req $srv, 'POST /tweak-status-code HTTP/1.0';
149         like($status, qr!\AHTTP/1\.[01] 200 HI\b!, 'status tweaked');
151         ($status, $hdr) = do_req $srv, 'POST /restore-status-code HTTP/1.0';
152         is($status, $orig_200_status, 'original status restored');
155 SKIP: {
156         eval { require HTTP::Tiny } or skip "HTTP::Tiny missing: $@", 1;
157         my $ht = HTTP::Tiny->new;
158         my $res = $ht->get("http://$host_port/write_on_close");
159         is($res->{content}, 'Goodbye', 'write-on-close body read');
162 if ('bad requests') {
163         ($status, $hdr) = do_req $srv, 'GET /env_dump HTTP/1/1';
164         like($status, qr!\AHTTP/1\.[01] 400 \b!, 'got 400 on bad request');
166         $c = tcp_start($srv);
167         print $c 'GET /';
168         my $buf = join('', (0..9), 'ab');
169         for (0..1023) { print $c $buf }
170         print $c " HTTP/1.0\r\n\r\n";
171         ($status, $hdr) = slurp_hdr($c);
172         like($status, qr!\AHTTP/1\.[01] 414 \b!,
173                 '414 on REQUEST_PATH > (12 * 1024)');
175         $c = tcp_start($srv);
176         print $c 'GET /hello-world?a';
177         $buf = join('', (0..9));
178         for (0..1023) { print $c $buf }
179         print $c " HTTP/1.0\r\n\r\n";
180         ($status, $hdr) = slurp_hdr($c);
181         like($status, qr!\AHTTP/1\.[01] 414 \b!,
182                 '414 on QUERY_STRING > (10 * 1024)');
184         $c = tcp_start($srv);
185         print $c 'GET /hello-world#a';
186         $buf = join('', (0..9), 'a'..'f');
187         for (0..63) { print $c $buf }
188         print $c " HTTP/1.0\r\n\r\n";
189         ($status, $hdr) = slurp_hdr($c);
190         like($status, qr!\AHTTP/1\.[01] 414 \b!, '414 on FRAGMENT > (1024)');
193 # input tests
194 my ($blob_size, $blob_hash);
195 SKIP: {
196         skip 'SKIP_EXPENSIVE on', 1 if $ENV{SKIP_EXPENSIVE};
197         CORE::open(my $rh, '<', 't/random_blob') or
198                 skip "t/random_blob not generated $!", 1;
199         $blob_size = -s $rh;
200         require Digest::MD5;
201         $blob_hash = Digest::MD5->new->addfile($rh)->hexdigest;
203         my $ck_hash = sub {
204                 my ($sub, $path, %opt) = @_;
205                 seek($rh, 0, SEEK_SET);
206                 $c = tcp_start($srv);
207                 $c->autoflush($opt{sync} // 0);
208                 $PUT{$sub}->($rh, $c, $path, %opt);
209                 defined($opt{overwrite}) and
210                         print { $c } ('x' x $opt{overwrite});
211                 $c->flush or die $!;
212                 shutdown($c, SHUT_WR);
213                 ($status, $hdr) = slurp_hdr($c);
214                 is(readline($c), $blob_hash, "$sub $path");
215         };
216         $ck_hash->('identity', '/rack_input', -s => $blob_size);
217         $ck_hash->('chunked_md5', '/rack_input');
218         $ck_hash->('identity', '/rack_input/size_first', -s => $blob_size);
219         $ck_hash->('identity', '/rack_input/rewind_first', -s => $blob_size);
220         $ck_hash->('chunked_md5', '/rack_input/size_first');
221         $ck_hash->('chunked_md5', '/rack_input/rewind_first');
223         $ck_hash->('identity', '/rack_input', -s => $blob_size, sync => 1);
224         $ck_hash->('chunked_md5', '/rack_input', sync => 1);
226         # ensure small overwrites don't get checksummed
227         $ck_hash->('identity', '/rack_input', -s => $blob_size,
228                         overwrite => 1); # one extra byte
229         unlike(slurp($err_log), qr/ClientShutdown/,
230                 'no overreads after client SHUT_WR');
232         # excessive overwrite truncated
233         $c = tcp_start($srv);
234         $c->autoflush(0);
235         print $c "PUT /rack_input HTTP/1.0\r\nContent-Length: 1\r\n\r\n";
236         if (1) {
237                 local $SIG{PIPE} = 'IGNORE';
238                 my $buf = "\0" x 8192;
239                 my $n = 0;
240                 my $end = time + 5;
241                 $! = 0;
242                 while (print $c $buf and time < $end) { ++$n }
243                 ok($!, 'overwrite truncated') or diag "n=$n err=$! ".time;
244                 undef $c;
245         }
247         # client shutdown early
248         $c = tcp_start($srv);
249         $c->autoflush(0);
250         print $c "PUT /rack_input HTTP/1.0\r\nContent-Length: 16384\r\n\r\n";
251         if (1) {
252                 local $SIG{PIPE} = 'IGNORE';
253                 print $c 'too short body';
254                 shutdown($c, SHUT_WR);
255                 vec(my $rvec = '', fileno($c), 1) = 1;
256                 select($rvec, undef, undef, 10) or BAIL_OUT "timed out";
257                 my $buf = <$c>;
258                 is($buf, undef, 'server aborted after client SHUT_WR');
259                 undef $c;
260         }
262         $curl // skip 'no curl found in PATH', 1;
264         my ($copt, $cout);
265         my $url = "http://$host_port/rack_input";
266         my $do_curl = sub {
267                 my (@arg) = @_;
268                 pipe(my $cout, $copt->{1});
269                 open $copt->{2}, '>', "$tmpdir/curl.err";
270                 my $cpid = spawn($curl, '-sSf', @arg, $url, $copt);
271                 close(delete $copt->{1});
272                 is(readline($cout), $blob_hash, "curl @arg response");
273                 is(waitpid($cpid, 0), $cpid, "curl @arg exited");
274                 is($?, 0, "no error from curl @arg");
275                 is(slurp("$tmpdir/curl.err"), '', "no stderr from curl @arg");
276         };
278         $do_curl->(qw(-T t/random_blob));
280         seek($rh, 0, SEEK_SET);
281         $copt->{0} = $rh;
282         $do_curl->('-T-');
284         diag 'testing Unicorn::PrereadInput...';
285         local $srv = tcp_server();
286         local $host_port = tcp_host_port($srv);
287         check_stderr;
288         truncate($errfh, 0);
290         my $pri = unicorn(qw(-E none t/preread_input.ru), { 3 => $srv });
291         $url = "http://$host_port/";
293         $do_curl->(qw(-T t/random_blob));
294         seek($rh, 0, SEEK_SET);
295         $copt->{0} = $rh;
296         $do_curl->('-T-');
298         my @pr_err = slurp("$tmpdir/err.log");
299         is(scalar(grep(/app dispatch:/, @pr_err)), 2, 'app dispatched twice');
301         # abort a chunked request by blocking curl on a FIFO:
302         $c = tcp_start($srv, "PUT / HTTP/1.1\r\nTransfer-Encoding: chunked");
303         close $c;
304         @pr_err = slurp("$tmpdir/err.log");
305         is(scalar(grep(/app dispatch:/, @pr_err)), 2,
306                         'app did not dispatch on aborted request');
307         undef $pri;
308         check_stderr;
309         diag 'Unicorn::PrereadInput middleware tests done';
312 # ... more stuff here
314 # SIGHUP-able stuff goes here
316 if ('check_client_connection') {
317         print $conf_fh <<EOM; # appending to existing
318 check_client_connection true
319 after_fork { |_,_| File.open('$fifo', 'w') { |fp| fp.write "pid=#\$\$" } }
321         $ar->do_kill('HUP');
322         open my $fifo_fh, '<', $fifo;
323         my $wpid = readline($fifo_fh);
324         like($wpid, qr/\Apid=\d+\z/a , 'new worker ready');
325         $ck_early_hints->('ccc on');
328 if ('max_header_len internal API') {
329         undef $c;
330         my $req = 'GET / HTTP/1.0';
331         my $len = length($req."\r\n\r\n");
332         print $conf_fh <<EOM; # appending to existing
333 Unicorn::HttpParser.max_header_len = $len
335         $ar->do_kill('HUP');
336         open my $fifo_fh, '<', $fifo;
337         my $wpid = readline($fifo_fh);
338         like($wpid, qr/\Apid=\d+\z/a , 'new worker ready');
339         close $fifo_fh;
340         $wpid =~ s/\Apid=// or die;
341         ok(CORE::kill(0, $wpid), 'worker PID retrieved');
343         ($status, $hdr) = do_req($srv, $req);
344         like($status, qr!\AHTTP/1\.[01] 200\b!, 'minimal request succeeds');
346         ($status, $hdr) = do_req($srv, 'GET /xxxxxx HTTP/1.0');
347         like($status, qr!\AHTTP/1\.[01] 413\b!, 'big request fails');
351 undef $ar;
353 check_stderr;
355 undef $tmpdir;
356 done_testing;