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' };
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);
21 my $u1 = "$tmpdir/u1";
22 my $conf_fh = write_file '>', $u_conf, <<EOM;
26 $conf_fh->autoflush(1);
27 my $ar = unicorn(qw(-E none t/integration.ru -c), $u_conf, { 3 => $srv });
28 my $curl = which('curl');
29 local $ENV{NO_PROXY} = '*'; # for curl
30 my $fifo = "$tmpdir/fifo";
31 POSIX::mkfifo($fifo, 0600) or die "mkfifo: $!";
34 my ($in, $out, $path, %opt) = @_;
35 my $dig = Digest::MD5->new;
38 Transfer-Encoding: chunked\r
39 Trailer: Content-MD5\r
44 $r = read($in, $buf, 999 + int(rand(0xffff)));
46 printf $out "%x\r\n", length($buf);
47 print $out $buf, "\r\n";
50 print $out "0\r\nContent-MD5: ", $dig->b64digest, "\r\n\r\n";
53 my ($in, $out, $path, %opt) = @_;
54 my $clen = $opt{-s} // -s $in;
57 Content-Length: $clen\r
60 my ($buf, $r, $len, $bs);
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;
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]);
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));
105 eval { require JSON::PP } or skip "JSON::PP missing: $@", 1;
108 my @r = do_req $srv, @req;
109 my $env = eval { JSON::PP->new->decode($r[2]) };
110 diag "$@ (r[2]=$r[2])" if $@;
111 is ref($env), 'HASH', "@req response body is JSON";
114 ($status, $hdr, my $json, my $env) = $get_json->('GET /env_dump');
115 is($status, undef, 'no status for HTTP/0.9');
116 is($hdr, undef, 'no header for HTTP/0.9');
117 unlike($json, qr/^Connection: /smi, 'no connection header for 0.9');
118 unlike($json, qr!\AHTTP/!s, 'no HTTP/1.x prefix for 0.9');
119 is($env->{SERVER_PROTOCOL}, 'HTTP/0.9', 'SERVER_PROTOCOL is 0.9');
120 is $env->{'rack.url_scheme'}, 'http', 'rack.url_scheme default';
121 is $env->{'rack.input'}, 'StringIO', 'StringIO for no content';
123 my $req = 'OPTIONS *';
124 ($status, $hdr, $json, $env) = $get_json->("$req HTTP/1.0");
125 is $env->{REQUEST_PATH}, '', "$req => REQUEST_PATH";
126 is $env->{PATH_INFO}, '', "$req => PATH_INFO";
127 is $env->{REQUEST_URI}, '*', "$req => REQUEST_URI";
129 $req = 'GET http://e:3/env_dump?y=z';
130 ($status, $hdr, $json, $env) = $get_json->("$req HTTP/1.0");
131 is $env->{REQUEST_PATH}, '/env_dump', "$req => REQUEST_PATH";
132 is $env->{PATH_INFO}, '/env_dump', "$req => PATH_INFO";
133 is $env->{QUERY_STRING}, 'y=z', "$req => QUERY_STRING";
135 $req = 'GET http://e:3/env_dump#frag';
136 ($status, $hdr, $json, $env) = $get_json->("$req HTTP/1.0");
137 is $env->{REQUEST_PATH}, '/env_dump', "$req => REQUEST_PATH";
138 is $env->{PATH_INFO}, '/env_dump', "$req => PATH_INFO";
139 is $env->{QUERY_STRING}, '', "$req => QUERY_STRING";
140 is $env->{FRAGMENT}, 'frag', "$req => FRAGMENT";
142 $req = 'GET http://e:3/env_dump?a=b#frag';
143 ($status, $hdr, $json, $env) = $get_json->("$req HTTP/1.0");
144 is $env->{REQUEST_PATH}, '/env_dump', "$req => REQUEST_PATH";
145 is $env->{PATH_INFO}, '/env_dump', "$req => PATH_INFO";
146 is $env->{QUERY_STRING}, 'a=b', "$req => QUERY_STRING";
147 is $env->{FRAGMENT}, 'frag', "$req => FRAGMENT";
149 for my $proto (qw(https http)) {
150 $req = "X-Forwarded-Proto: $proto";
151 ($status, $hdr, $json, $env) = $get_json->(
152 "GET /env_dump HTTP/1.0\r\n".
153 "X-Forwarded-Proto: $proto");
154 is $env->{REQUEST_PATH}, '/env_dump', "$req => REQUEST_PATH";
155 is $env->{PATH_INFO}, '/env_dump', "$req => PATH_INFO";
156 is $env->{'rack.url_scheme'}, $proto, "$req => rack.url_scheme";
159 $req = 'X-Forwarded-Proto: ftp'; # invalid proto
160 ($status, $hdr, $json, $env) = $get_json->(
161 "GET /env_dump HTTP/1.0\r\n".
162 "X-Forwarded-Proto: ftp");
163 is $env->{REQUEST_PATH}, '/env_dump', "$req => REQUEST_PATH";
164 is $env->{PATH_INFO}, '/env_dump', "$req => PATH_INFO";
165 is $env->{'rack.url_scheme'}, 'http', "$req => rack.url_scheme";
167 ($status, $hdr, $json, $env) = $get_json->("PUT /env_dump HTTP/1.0\r\n".
168 'Content-Length: 0');
169 is $env->{'rack.input'}, 'StringIO', 'content-length: 0 uses StringIO';
171 ($status, $hdr, $json, $env) = $get_json->("PUT /env_dump HTTP/1.0\r\n".
172 'Content-Length: 1');
173 is $env->{'rack.input'}, 'Unicorn::TeeInput',
174 'content-length: 1 uses TeeInput';
177 # cf. <CAO47=rJa=zRcLn_Xm4v2cHPr6c0UswaFC_omYFEH+baSxHOWKQ@mail.gmail.com>
178 ($status, $hdr) = do_req($srv, 'GET /nil-header-value HTTP/1.0');
179 is_deeply([grep(/^X-Nil:/, @$hdr)], ['X-Nil: '],
180 'nil header value accepted for broken apps') or diag(explain($hdr));
183 ($status, $hdr, $bdy) = do_req($srv, 'GET /broken_app HTTP/1.0');
184 like($status, qr!\AHTTP/1\.[0-1] 500\b!, 'got 500 error on broken endpoint');
185 is($bdy, undef, 'no response body after exception');
186 seek $errfh, 0, SEEK_SET;
189 while (!defined($nxt) && defined($_ = <$errfh>)) {
190 $nxt = <$errfh> if /app error/;
192 ok $nxt, 'got app error' and
193 like $nxt, qr/\bintegration\.ru/, 'got backtrace';
195 seek $errfh, 0, SEEK_SET;
198 ($status, $hdr, $bdy) = do_req($srv, 'GET /nil HTTP/1.0');
199 like($status, qr!\AHTTP/1\.[0-1] 500\b!, 'got 500 error on nil endpoint');
200 like slurp($err_log), qr/app error/, 'exception logged for nil';
201 seek $errfh, 0, SEEK_SET;
204 my $ck_early_hints = sub {
206 $c = unix_start($u1, 'GET /early_hints_rack2 HTTP/1.0');
207 ($status, $hdr) = slurp_hdr($c);
208 like($status, qr!\AHTTP/1\.[01] 103\b!, 'got 103 for rack 2 value');
209 is_deeply(['link: r', 'link: 2'], $hdr, 'rack 2 hints match '.$note);
210 ($status, $hdr) = slurp_hdr($c);
211 like($status, qr!\AHTTP/1\.[01] 200\b!, 'got 200 afterwards');
212 is(readline($c), 'String', 'early hints used a String for rack 2');
214 $c = unix_start($u1, 'GET /early_hints_rack3 HTTP/1.0');
215 ($status, $hdr) = slurp_hdr($c);
216 like($status, qr!\AHTTP/1\.[01] 103\b!, 'got 103 for rack 3');
217 is_deeply(['link: r', 'link: 3'], $hdr, 'rack 3 hints match '.$note);
218 ($status, $hdr) = slurp_hdr($c);
219 like($status, qr!\AHTTP/1\.[01] 200\b!, 'got 200 afterwards');
220 is(readline($c), 'Array', 'early hints used a String for rack 3');
222 $ck_early_hints->('ccc off'); # we'll retest later
224 if ('TODO: ensure Rack::Utils::HTTP_STATUS_CODES is available') {
225 ($status, $hdr) = do_req $srv, 'POST /tweak-status-code HTTP/1.0';
226 like($status, qr!\AHTTP/1\.[01] 200 HI\b!, 'status tweaked');
228 ($status, $hdr) = do_req $srv, 'POST /restore-status-code HTTP/1.0';
229 is($status, $orig_200_status, 'original status restored');
233 eval { require HTTP::Tiny } or skip "HTTP::Tiny missing: $@", 1;
234 my $ht = HTTP::Tiny->new;
235 my $res = $ht->get("http://$host_port/write_on_close");
236 is($res->{content}, 'Goodbye', 'write-on-close body read');
239 if ('bad requests') {
240 ($status, $hdr) = do_req $srv, 'GET /env_dump HTTP/1/1';
241 like($status, qr!\AHTTP/1\.[01] 400 \b!, 'got 400 on bad request');
243 for my $abs_uri (qw(ssh+http://e/ ftp://e/x http+ssh://e/x)) {
244 ($status, $hdr) = do_req $srv, "GET $abs_uri HTTP/1.0";
245 like $status, qr!\AHTTP/1\.[01] 400 \b!, "400 on $abs_uri";
248 $c = tcp_start($srv);
250 my $buf = join('', (0..9), 'ab');
251 for (0..1023) { print $c $buf }
252 print $c " HTTP/1.0\r\n\r\n";
253 ($status, $hdr) = slurp_hdr($c);
254 like($status, qr!\AHTTP/1\.[01] 414 \b!,
255 '414 on REQUEST_PATH > (12 * 1024)');
257 $c = tcp_start($srv);
258 print $c 'GET /hello-world?a';
259 $buf = join('', (0..9));
260 for (0..1023) { print $c $buf }
261 print $c " HTTP/1.0\r\n\r\n";
262 ($status, $hdr) = slurp_hdr($c);
263 like($status, qr!\AHTTP/1\.[01] 414 \b!,
264 '414 on QUERY_STRING > (10 * 1024)');
266 $c = tcp_start($srv);
267 print $c 'GET /hello-world#a';
268 $buf = join('', (0..9), 'a'..'f');
269 for (0..63) { print $c $buf }
270 print $c " HTTP/1.0\r\n\r\n";
271 ($status, $hdr) = slurp_hdr($c);
272 like($status, qr!\AHTTP/1\.[01] 414 \b!, '414 on FRAGMENT > (1024)');
276 my ($blob_size, $blob_hash);
278 skip 'SKIP_EXPENSIVE on', 1 if $ENV{SKIP_EXPENSIVE};
279 CORE::open(my $rh, '<', 't/random_blob') or
280 skip "t/random_blob not generated $!", 1;
283 $blob_hash = Digest::MD5->new->addfile($rh)->hexdigest;
286 my ($sub, $path, %opt) = @_;
287 seek($rh, 0, SEEK_SET);
288 $c = tcp_start($srv);
289 $c->autoflush($opt{sync} // 0);
290 $PUT{$sub}->($rh, $c, $path, %opt);
291 defined($opt{overwrite}) and
292 print { $c } ('x' x $opt{overwrite});
294 shutdown($c, SHUT_WR);
295 ($status, $hdr) = slurp_hdr($c);
296 is(readline($c), $blob_hash, "$sub $path");
298 $ck_hash->('identity', '/rack_input', -s => $blob_size);
299 $ck_hash->('chunked_md5', '/rack_input');
300 $ck_hash->('identity', '/rack_input/size_first', -s => $blob_size);
301 $ck_hash->('identity', '/rack_input/rewind_first', -s => $blob_size);
302 $ck_hash->('chunked_md5', '/rack_input/size_first');
303 $ck_hash->('chunked_md5', '/rack_input/rewind_first');
305 $ck_hash->('identity', '/rack_input', -s => $blob_size, sync => 1);
306 $ck_hash->('chunked_md5', '/rack_input', sync => 1);
308 # ensure small overwrites don't get checksummed
309 $ck_hash->('identity', '/rack_input', -s => $blob_size,
310 overwrite => 1); # one extra byte
311 unlike(slurp($err_log), qr/ClientShutdown/,
312 'no overreads after client SHUT_WR');
314 # excessive overwrite truncated
315 $c = tcp_start($srv);
317 print $c "PUT /rack_input HTTP/1.0\r\nContent-Length: 1\r\n\r\n";
319 local $SIG{PIPE} = 'IGNORE';
320 my $buf = "\0" x 8192;
324 while (print $c $buf and time < $end) { ++$n }
325 ok($!, 'overwrite truncated') or diag "n=$n err=$! ".time;
329 # client shutdown early
330 $c = tcp_start($srv);
332 print $c "PUT /rack_input HTTP/1.0\r\nContent-Length: 16384\r\n\r\n";
334 local $SIG{PIPE} = 'IGNORE';
335 print $c 'too short body';
336 shutdown($c, SHUT_WR);
337 vec(my $rvec = '', fileno($c), 1) = 1;
338 select($rvec, undef, undef, 10) or BAIL_OUT "timed out";
340 is($buf, undef, 'server aborted after client SHUT_WR');
344 $curl // skip 'no curl found in PATH', 1;
347 my $url = "http://$host_port/rack_input";
350 pipe(my $cout, $copt->{1});
351 open $copt->{2}, '>', "$tmpdir/curl.err";
352 my $cpid = spawn($curl, '-sSf', @arg, $url, $copt);
353 close(delete $copt->{1});
354 is(readline($cout), $blob_hash, "curl @arg response");
355 is(waitpid($cpid, 0), $cpid, "curl @arg exited");
356 is($?, 0, "no error from curl @arg");
357 is(slurp("$tmpdir/curl.err"), '', "no stderr from curl @arg");
360 $do_curl->(qw(-T t/random_blob));
362 seek($rh, 0, SEEK_SET);
366 diag 'testing Unicorn::PrereadInput...';
367 local $srv = tcp_server();
368 local $host_port = tcp_host_port($srv);
372 my $pri = unicorn(qw(-E none t/preread_input.ru), { 3 => $srv });
373 $url = "http://$host_port/";
375 $do_curl->(qw(-T t/random_blob));
376 seek($rh, 0, SEEK_SET);
380 my @pr_err = slurp("$tmpdir/err.log");
381 is(scalar(grep(/app dispatch:/, @pr_err)), 2, 'app dispatched twice');
383 # abort a chunked request by blocking curl on a FIFO:
384 $c = tcp_start($srv, "PUT / HTTP/1.1\r\nTransfer-Encoding: chunked");
386 @pr_err = slurp("$tmpdir/err.log");
387 is(scalar(grep(/app dispatch:/, @pr_err)), 2,
388 'app did not dispatch on aborted request');
391 diag 'Unicorn::PrereadInput middleware tests done';
394 # ... more stuff here
396 # SIGHUP-able stuff goes here
398 if ('check_client_connection') {
399 print $conf_fh <<EOM; # appending to existing
400 check_client_connection true
401 after_fork { |_,_| File.open('$fifo', 'w') { |fp| fp.write "pid=#\$\$" } }
404 open my $fifo_fh, '<', $fifo;
405 my $wpid = readline($fifo_fh);
406 like($wpid, qr/\Apid=\d+\z/a , 'new worker ready');
407 $ck_early_hints->('ccc on');
409 $c = tcp_start $srv, 'GET /env_dump HTTP/1.0';
410 vec(my $rvec = '', fileno($c), 1) = 1;
411 select($rvec, undef, undef, 10) or BAIL_OUT 'timed out env_dump';
412 ($status, $hdr) = slurp_hdr($c);
413 like $status, qr!\AHTTP/1\.[01] 200!, 'got part of first response';
414 ok $hdr, 'got all headers';
416 # start a slow TCP request
417 my $rfifo = "$tmpdir/rfifo";
419 $c = tcp_start $srv, "GET /read_fifo HTTP/1.0\r\nRead-FIFO: $rfifo";
420 tcp_start $srv, 'GET /aborted HTTP/1.0' for (1..100);
421 write_file '>', $rfifo, 'TFIN';
422 ($status, $hdr) = slurp_hdr($c);
423 like $status, qr!\AHTTP/1\.[01] 200!, 'got part of first response';
425 is $bdy, 'TFIN', 'got slow response from TCP socket';
427 # slow Unix socket request
428 $c = unix_start $u1, "GET /read_fifo HTTP/1.0\r\nRead-FIFO: $rfifo";
429 vec($rvec = '', fileno($c), 1) = 1;
430 select($rvec, undef, undef, 10) or BAIL_OUT 'timed out Unix CCC';
431 unix_start $u1, 'GET /aborted HTTP/1.0' for (1..100);
432 write_file '>', $rfifo, 'UFIN';
433 ($status, $hdr) = slurp_hdr($c);
434 like $status, qr!\AHTTP/1\.[01] 200!, 'got part of first response';
436 is $bdy, 'UFIN', 'got slow response from Unix socket';
438 ($status, $hdr, $bdy) = do_req $srv, 'GET /nr_aborts HTTP/1.0';
439 like "@$hdr", qr/nr-aborts: 0\b/,
440 'aborted connections unseen by Rack app';
443 if ('max_header_len internal API') {
445 my $req = 'GET / HTTP/1.0';
446 my $len = length($req."\r\n\r\n");
447 print $conf_fh <<EOM; # appending to existing
448 Unicorn::HttpParser.max_header_len = $len
451 open my $fifo_fh, '<', $fifo;
452 my $wpid = readline($fifo_fh);
453 like($wpid, qr/\Apid=\d+\z/a , 'new worker ready');
455 $wpid =~ s/\Apid=// or die;
456 ok(CORE::kill(0, $wpid), 'worker PID retrieved');
458 ($status, $hdr) = do_req($srv, $req);
459 like($status, qr!\AHTTP/1\.[01] 200\b!, 'minimal request succeeds');
461 ($status, $hdr) = do_req($srv, 'GET /xxxxxx HTTP/1.0');
462 like($status, qr!\AHTTP/1\.[01] 413\b!, 'big request fails');