http_SUITE.erl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. %% Copyright (c) 2018, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(http_SUITE).
  15. -compile(export_all).
  16. -compile(nowarn_export_all).
  17. -import(ct_helper, [config/2]).
  18. -import(ct_helper, [doc/1]).
  19. -import(ct_helper, [get_remote_pid_tcp/1]).
  20. -import(cowboy_test, [gun_open/1]).
  21. -import(cowboy_test, [gun_down/1]).
  22. -import(cowboy_test, [raw_open/1]).
  23. -import(cowboy_test, [raw_send/2]).
  24. -import(cowboy_test, [raw_recv_head/1]).
  25. -import(cowboy_test, [raw_recv_rest/3]).
  26. -import(cowboy_test, [raw_recv/3]).
  27. -import(cowboy_test, [raw_expect_recv/2]).
  28. all() -> [{group, clear}].
  29. groups() -> [{clear, [parallel], ct_helper:all(?MODULE)}].
  30. init_per_group(Name, Config) ->
  31. cowboy_test:init_http(Name, #{
  32. env => #{dispatch => init_dispatch(Config)}
  33. }, Config).
  34. end_per_group(Name, _) ->
  35. cowboy:stop_listener(Name).
  36. init_dispatch(_) ->
  37. cowboy_router:compile([{"localhost", [
  38. {"/", hello_h, []},
  39. {"/echo/:key", echo_h, []},
  40. {"/resp/:key[/:arg]", resp_h, []},
  41. {"/set_options/:key", set_options_h, []}
  42. ]}]).
  43. chunked_false(Config) ->
  44. doc("Confirm the option chunked => false disables chunked "
  45. "transfer-encoding for HTTP/1.1 connections."),
  46. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  47. env => #{dispatch => init_dispatch(Config)},
  48. chunked => false
  49. }),
  50. Port = ranch:get_port(?FUNCTION_NAME),
  51. try
  52. Request = "GET /resp/stream_reply2/200 HTTP/1.1\r\nhost: localhost\r\n\r\n",
  53. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  54. ok = raw_send(Client, Request),
  55. Rest = case catch raw_recv_head(Client) of
  56. {'EXIT', _} -> error(closed);
  57. Data ->
  58. %% Cowboy always advertises itself as HTTP/1.1.
  59. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  60. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  61. false = lists:keyfind(<<"content-length">>, 1, Headers),
  62. false = lists:keyfind(<<"transfer-encoding">>, 1, Headers),
  63. Rest1
  64. end,
  65. Bits = 8000000 - bit_size(Rest),
  66. raw_expect_recv(Client, <<0:Bits>>),
  67. {error, closed} = raw_recv(Client, 1, 1000)
  68. after
  69. cowboy:stop_listener(?FUNCTION_NAME)
  70. end.
  71. chunked_one_byte_at_a_time(Config) ->
  72. doc("Confirm that chunked transfer-encoding works when "
  73. "the body is received one byte at a time."),
  74. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  75. ChunkedBody = iolist_to_binary(do_chunked_body(50, Body, [])),
  76. Client = raw_open(Config),
  77. ok = raw_send(Client,
  78. "POST /echo/read_body HTTP/1.1\r\n"
  79. "Host: localhost\r\n"
  80. "Transfer-encoding: chunked\r\n\r\n"),
  81. _ = [begin
  82. raw_send(Client, <<C>>),
  83. timer:sleep(10)
  84. end || <<C>> <= ChunkedBody],
  85. Rest = case catch raw_recv_head(Client) of
  86. {'EXIT', _} -> error(closed);
  87. Data ->
  88. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  89. {_, Rest1} = cow_http:parse_headers(Rest0),
  90. Rest1
  91. end,
  92. RestSize = byte_size(Rest),
  93. <<Rest:RestSize/binary, Expect/bits>> = Body,
  94. raw_expect_recv(Client, Expect).
  95. chunked_one_chunk_at_a_time(Config) ->
  96. doc("Confirm that chunked transfer-encoding works when "
  97. "the body is received one chunk at a time."),
  98. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  99. Chunks = do_chunked_body(50, Body, []),
  100. Client = raw_open(Config),
  101. ok = raw_send(Client,
  102. "POST /echo/read_body HTTP/1.1\r\n"
  103. "Host: localhost\r\n"
  104. "Transfer-encoding: chunked\r\n\r\n"),
  105. _ = [begin
  106. raw_send(Client, Chunk),
  107. timer:sleep(10)
  108. end || Chunk <- Chunks],
  109. Rest = case catch raw_recv_head(Client) of
  110. {'EXIT', _} -> error(closed);
  111. Data ->
  112. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  113. {_, Rest1} = cow_http:parse_headers(Rest0),
  114. Rest1
  115. end,
  116. RestSize = byte_size(Rest),
  117. <<Rest:RestSize/binary, Expect/bits>> = Body,
  118. raw_expect_recv(Client, Expect).
  119. chunked_split_delay_in_chunk_body(Config) ->
  120. doc("Confirm that chunked transfer-encoding works when "
  121. "the body is received with a delay inside the chunks."),
  122. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  123. Chunks = do_chunked_body(50, Body, []),
  124. Client = raw_open(Config),
  125. ok = raw_send(Client,
  126. "POST /echo/read_body HTTP/1.1\r\n"
  127. "Host: localhost\r\n"
  128. "Transfer-encoding: chunked\r\n\r\n"),
  129. _ = [begin
  130. case Chunk of
  131. <<"0\r\n\r\n">> ->
  132. raw_send(Client, Chunk);
  133. _ ->
  134. [Size, ChunkBody, <<>>] = binary:split(Chunk, <<"\r\n">>, [global]),
  135. PartASize = rand:uniform(byte_size(ChunkBody)),
  136. <<PartA:PartASize/binary, PartB/binary>> = ChunkBody,
  137. raw_send(Client, [Size, <<"\r\n">>, PartA]),
  138. timer:sleep(10),
  139. raw_send(Client, [PartB, <<"\r\n">>])
  140. end
  141. end || Chunk <- Chunks],
  142. Rest = case catch raw_recv_head(Client) of
  143. {'EXIT', _} -> error(closed);
  144. Data ->
  145. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  146. {_, Rest1} = cow_http:parse_headers(Rest0),
  147. Rest1
  148. end,
  149. RestSize = byte_size(Rest),
  150. <<Rest:RestSize/binary, Expect/bits>> = Body,
  151. raw_expect_recv(Client, Expect).
  152. chunked_split_delay_in_chunk_crlf(Config) ->
  153. doc("Confirm that chunked transfer-encoding works when "
  154. "the body is received with a delay inside the chunks end CRLF."),
  155. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  156. Chunks = do_chunked_body(50, Body, []),
  157. Client = raw_open(Config),
  158. ok = raw_send(Client,
  159. "POST /echo/read_body HTTP/1.1\r\n"
  160. "Host: localhost\r\n"
  161. "Transfer-encoding: chunked\r\n\r\n"),
  162. _ = [begin
  163. Len = byte_size(Chunk) - (rand:uniform(2) - 1),
  164. <<Begin:Len/binary, End/binary>> = Chunk,
  165. raw_send(Client, Begin),
  166. timer:sleep(10),
  167. raw_send(Client, End)
  168. end || Chunk <- Chunks],
  169. Rest = case catch raw_recv_head(Client) of
  170. {'EXIT', _} -> error(closed);
  171. Data ->
  172. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  173. {_, Rest1} = cow_http:parse_headers(Rest0),
  174. Rest1
  175. end,
  176. RestSize = byte_size(Rest),
  177. <<Rest:RestSize/binary, Expect/bits>> = Body,
  178. raw_expect_recv(Client, Expect).
  179. do_chunked_body(_, <<>>, Acc) ->
  180. lists:reverse([cow_http_te:last_chunk()|Acc]);
  181. do_chunked_body(ChunkSize0, Data, Acc) ->
  182. ChunkSize = min(byte_size(Data), ChunkSize0),
  183. <<Chunk:ChunkSize/binary, Rest/binary>> = Data,
  184. do_chunked_body(ChunkSize, Rest,
  185. [iolist_to_binary(cow_http_te:chunk(Chunk))|Acc]).
  186. http10_keepalive_false(Config) ->
  187. doc("Confirm the option http10_keepalive => false disables keep-alive "
  188. "completely for HTTP/1.0 connections."),
  189. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  190. env => #{dispatch => init_dispatch(Config)},
  191. http10_keepalive => false
  192. }),
  193. Port = ranch:get_port(?FUNCTION_NAME),
  194. try
  195. Keepalive = "GET / HTTP/1.0\r\nhost: localhost\r\nConnection: keep-alive\r\n\r\n",
  196. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  197. ok = raw_send(Client, Keepalive),
  198. _ = case catch raw_recv_head(Client) of
  199. {'EXIT', _} -> error(closed);
  200. Data ->
  201. %% Cowboy always advertises itself as HTTP/1.1.
  202. {'HTTP/1.1', 200, _, Rest} = cow_http:parse_status_line(Data),
  203. {Headers, _} = cow_http:parse_headers(Rest),
  204. {_, <<"close">>} = lists:keyfind(<<"connection">>, 1, Headers)
  205. end,
  206. ok = raw_send(Client, Keepalive),
  207. case catch raw_recv_head(Client) of
  208. {'EXIT', _} -> closed;
  209. _ -> error(not_closed)
  210. end
  211. after
  212. cowboy:stop_listener(?FUNCTION_NAME)
  213. end.
  214. idle_timeout_infinity(Config) ->
  215. doc("Ensure the idle_timeout option accepts the infinity value."),
  216. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  217. env => #{dispatch => init_dispatch(Config)},
  218. idle_timeout => infinity
  219. }),
  220. Port = ranch:get_port(?FUNCTION_NAME),
  221. try
  222. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  223. {ok, http} = gun:await_up(ConnPid),
  224. timer:sleep(500),
  225. #{socket := Socket} = gun:info(ConnPid),
  226. Pid = get_remote_pid_tcp(Socket),
  227. _ = gun:post(ConnPid, "/echo/read_body",
  228. [{<<"content-type">>, <<"text/plain">>}]),
  229. Ref = erlang:monitor(process, Pid),
  230. receive
  231. {'DOWN', Ref, process, Pid, Reason} ->
  232. error(Reason)
  233. after 1000 ->
  234. gun:close(ConnPid)
  235. end
  236. after
  237. cowboy:stop_listener(?FUNCTION_NAME)
  238. end.
  239. persistent_term_router(Config) ->
  240. doc("The router can retrieve the routes from persistent_term storage."),
  241. case erlang:function_exported(persistent_term, get, 1) of
  242. true -> do_persistent_term_router(Config);
  243. false -> {skip, "This test uses the persistent_term functionality added in Erlang/OTP 21.2."}
  244. end.
  245. do_persistent_term_router(Config) ->
  246. persistent_term:put(?FUNCTION_NAME, init_dispatch(Config)),
  247. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  248. env => #{dispatch => {persistent_term, ?FUNCTION_NAME}}
  249. }),
  250. Port = ranch:get_port(?FUNCTION_NAME),
  251. try
  252. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  253. {ok, http} = gun:await_up(ConnPid),
  254. StreamRef = gun:get(ConnPid, "/"),
  255. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef),
  256. gun:close(ConnPid)
  257. after
  258. cowboy:stop_listener(?FUNCTION_NAME)
  259. end.
  260. request_timeout_infinity(Config) ->
  261. doc("Ensure the request_timeout option accepts the infinity value."),
  262. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  263. env => #{dispatch => init_dispatch(Config)},
  264. request_timeout => infinity
  265. }),
  266. Port = ranch:get_port(?FUNCTION_NAME),
  267. try
  268. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  269. {ok, http} = gun:await_up(ConnPid),
  270. timer:sleep(500),
  271. #{socket := Socket} = gun:info(ConnPid),
  272. Pid = get_remote_pid_tcp(Socket),
  273. Ref = erlang:monitor(process, Pid),
  274. receive
  275. {'DOWN', Ref, process, Pid, Reason} ->
  276. error(Reason)
  277. after 1000 ->
  278. gun:close(ConnPid)
  279. end
  280. after
  281. cowboy:stop_listener(?FUNCTION_NAME)
  282. end.
  283. set_options_chunked_false(Config) ->
  284. doc("Confirm the option chunked can be dynamically set to disable "
  285. "chunked transfer-encoding. This results in the closing of the "
  286. "connection after the current request."),
  287. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  288. env => #{dispatch => init_dispatch(Config)},
  289. chunked => true
  290. }),
  291. Port = ranch:get_port(?FUNCTION_NAME),
  292. try
  293. Request = "GET /set_options/chunked_false HTTP/1.1\r\nhost: localhost\r\n\r\n",
  294. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  295. ok = raw_send(Client, Request),
  296. Rest = case catch raw_recv_head(Client) of
  297. {'EXIT', _} -> error(closed);
  298. Data ->
  299. %% Cowboy always advertises itself as HTTP/1.1.
  300. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  301. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  302. false = lists:keyfind(<<"content-length">>, 1, Headers),
  303. false = lists:keyfind(<<"transfer-encoding">>, 1, Headers),
  304. Rest1
  305. end,
  306. Bits = 8000000 - bit_size(Rest),
  307. raw_expect_recv(Client, <<0:Bits>>),
  308. {error, closed} = raw_recv(Client, 1, 1000)
  309. after
  310. cowboy:stop_listener(?FUNCTION_NAME)
  311. end.
  312. set_options_chunked_false_ignored(Config) ->
  313. doc("Confirm the option chunked can be dynamically set to disable "
  314. "chunked transfer-encoding, and that it is ignored if the "
  315. "response is not streamed."),
  316. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  317. env => #{dispatch => init_dispatch(Config)},
  318. chunked => true
  319. }),
  320. Port = ranch:get_port(?FUNCTION_NAME),
  321. try
  322. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  323. %% We do a first request setting the option but not
  324. %% using chunked transfer-encoding in the response.
  325. StreamRef1 = gun:get(ConnPid, "/set_options/chunked_false_ignored"),
  326. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef1),
  327. {ok, <<"Hello world!">>} = gun:await_body(ConnPid, StreamRef1),
  328. %% We then do a second request to confirm that chunked
  329. %% is not disabled for that second request.
  330. StreamRef2 = gun:get(ConnPid, "/resp/stream_reply2/200"),
  331. {response, nofin, 200, Headers} = gun:await(ConnPid, StreamRef2),
  332. {_, <<"chunked">>} = lists:keyfind(<<"transfer-encoding">>, 1, Headers),
  333. gun:close(ConnPid)
  334. after
  335. cowboy:stop_listener(?FUNCTION_NAME)
  336. end.
  337. set_options_idle_timeout(Config) ->
  338. doc("Confirm that the idle_timeout option can be dynamically "
  339. "set to change how long Cowboy will wait before it closes the connection."),
  340. %% We start with a long timeout and then cut it short.
  341. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  342. env => #{dispatch => init_dispatch(Config)},
  343. idle_timeout => 60000
  344. }),
  345. Port = ranch:get_port(?FUNCTION_NAME),
  346. try
  347. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  348. {ok, http} = gun:await_up(ConnPid),
  349. timer:sleep(500),
  350. #{socket := Socket} = gun:info(ConnPid),
  351. Pid = get_remote_pid_tcp(Socket),
  352. _ = gun:post(ConnPid, "/set_options/idle_timeout_short",
  353. [{<<"content-type">>, <<"text/plain">>}]),
  354. Ref = erlang:monitor(process, Pid),
  355. receive
  356. {'DOWN', Ref, process, Pid, _} ->
  357. ok
  358. after 2000 ->
  359. error(timeout)
  360. end
  361. after
  362. cowboy:stop_listener(?FUNCTION_NAME)
  363. end.
  364. set_options_idle_timeout_only_applies_to_current_request(Config) ->
  365. doc("Confirm that changes to the idle_timeout option only apply to the current stream."),
  366. %% We start with a long timeout and then cut it short.
  367. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  368. env => #{dispatch => init_dispatch(Config)},
  369. idle_timeout => 500
  370. }),
  371. Port = ranch:get_port(?FUNCTION_NAME),
  372. try
  373. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  374. {ok, http} = gun:await_up(ConnPid),
  375. timer:sleep(500),
  376. #{socket := Socket} = gun:info(ConnPid),
  377. Pid = get_remote_pid_tcp(Socket),
  378. StreamRef = gun:post(ConnPid, "/set_options/idle_timeout_long",
  379. [{<<"content-type">>, <<"text/plain">>}]),
  380. Ref = erlang:monitor(process, Pid),
  381. receive
  382. {'DOWN', Ref, process, Pid, Reason} ->
  383. error(Reason)
  384. after 2000 ->
  385. ok
  386. end,
  387. %% Finish the first request and start a second one to confirm
  388. %% the idle_timeout option is back to normal.
  389. gun:data(ConnPid, StreamRef, fin, <<"Hello!">>),
  390. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef),
  391. {ok, <<"Hello!">>} = gun:await_body(ConnPid, StreamRef),
  392. _ = gun:post(ConnPid, "/echo/read_body",
  393. [{<<"content-type">>, <<"text/plain">>}]),
  394. receive
  395. {'DOWN', Ref, process, Pid, _} ->
  396. ok
  397. after 2000 ->
  398. error(timeout)
  399. end
  400. after
  401. cowboy:stop_listener(?FUNCTION_NAME)
  402. end.
  403. switch_protocol_flush(Config) ->
  404. doc("Confirm that switch_protocol does not flush unrelated messages."),
  405. ProtoOpts = #{
  406. env => #{dispatch => init_dispatch(Config)},
  407. stream_handlers => [switch_protocol_flush_h]
  408. },
  409. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  410. Port = ranch:get_port(?FUNCTION_NAME),
  411. try
  412. Self = self(),
  413. ConnPid = gun_open([{port, Port}, {type, tcp}, {protocol, http}|Config]),
  414. _ = gun:get(ConnPid, "/", [
  415. {<<"x-test-pid">>, pid_to_list(Self)}
  416. ]),
  417. receive
  418. {Self, Events} ->
  419. switch_protocol_flush_h:validate(Events)
  420. after 5000 ->
  421. error(timeout)
  422. end
  423. after
  424. cowboy:stop_listener(?FUNCTION_NAME)
  425. end.
  426. graceful_shutdown_connection(Config) ->
  427. doc("Check that the current request is handled before gracefully "
  428. "shutting down a connection."),
  429. Dispatch = cowboy_router:compile([{"localhost", [
  430. {"/hello", delay_hello_h,
  431. #{delay => 0, notify_received => self()}},
  432. {"/delay_hello", delay_hello_h,
  433. #{delay => 1000, notify_received => self()}}
  434. ]}]),
  435. ProtoOpts = #{
  436. env => #{dispatch => Dispatch}
  437. },
  438. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  439. Port = ranch:get_port(?FUNCTION_NAME),
  440. try
  441. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  442. ok = raw_send(Client,
  443. "GET /delay_hello HTTP/1.1\r\n"
  444. "Host: localhost\r\n\r\n"
  445. "GET /hello HTTP/1.1\r\n"
  446. "Host: localhost\r\n\r\n"),
  447. receive {request_received, <<"/delay_hello">>} -> ok end,
  448. receive {request_received, <<"/hello">>} -> ok end,
  449. CowboyConnPid = get_remote_pid_tcp(element(2, Client)),
  450. CowboyConnRef = erlang:monitor(process, CowboyConnPid),
  451. ok = sys:terminate(CowboyConnPid, system_is_going_down),
  452. Rest = case catch raw_recv_head(Client) of
  453. {'EXIT', _} -> error(closed);
  454. Data ->
  455. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  456. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  457. <<"close">> = proplists:get_value(<<"connection">>, Headers),
  458. Rest1
  459. end,
  460. <<"Hello world!">> = raw_recv_rest(Client, byte_size(<<"Hello world!">>), Rest),
  461. {error, closed} = raw_recv(Client, 0, 1000),
  462. receive
  463. {'DOWN', CowboyConnRef, process, CowboyConnPid, _Reason} ->
  464. ok
  465. end
  466. after
  467. cowboy:stop_listener(?FUNCTION_NAME)
  468. end.
  469. graceful_shutdown_listener(Config) ->
  470. doc("Check that connections are shut down gracefully when stopping a listener."),
  471. TransOpts = #{
  472. socket_opts => [{port, 0}],
  473. shutdown => 1000 %% Shorter timeout to make the test case faster.
  474. },
  475. Dispatch = cowboy_router:compile([{"localhost", [
  476. {"/delay_hello", delay_hello_h,
  477. #{delay => 500, notify_received => self()}},
  478. {"/long_delay_hello", delay_hello_h,
  479. #{delay => 10000, notify_received => self()}}
  480. ]}]),
  481. ProtoOpts = #{
  482. env => #{dispatch => Dispatch}
  483. },
  484. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, TransOpts, ProtoOpts),
  485. Port = ranch:get_port(?FUNCTION_NAME),
  486. ConnPid1 = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  487. Ref1 = gun:get(ConnPid1, "/delay_hello"),
  488. ConnPid2 = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  489. Ref2 = gun:get(ConnPid2, "/long_delay_hello"),
  490. %% Shutdown listener while the handlers are working.
  491. receive {request_received, <<"/delay_hello">>} -> ok end,
  492. receive {request_received, <<"/long_delay_hello">>} -> ok end,
  493. %% Note: This call does not complete quickly and will
  494. %% prevent other cowboy:stop_listener/1 calls to complete.
  495. ok = cowboy:stop_listener(?FUNCTION_NAME),
  496. %% Check that the 1st request is handled before shutting down.
  497. {response, nofin, 200, RespHeaders} = gun:await(ConnPid1, Ref1),
  498. <<"close">> = proplists:get_value(<<"connection">>, RespHeaders),
  499. {ok, RespBody} = gun:await_body(ConnPid1, Ref1),
  500. <<"Hello world!">> = iolist_to_binary(RespBody),
  501. gun:close(ConnPid1),
  502. %% Check that the 2nd (very slow) request is not handled.
  503. {error, {stream_error, closed}} = gun:await(ConnPid2, Ref2),
  504. gun:close(ConnPid2).
  505. send_timeout_close(_Config) ->
  506. doc("Check that connections are closed on send timeout."),
  507. TransOpts = #{
  508. port => 0,
  509. socket_opts => [
  510. {send_timeout, 100},
  511. {send_timeout_close, true},
  512. {sndbuf, 10}
  513. ]
  514. },
  515. Dispatch = cowboy_router:compile([{"localhost", [
  516. {"/endless", loop_handler_endless_h, #{delay => 100}}
  517. ]}]),
  518. ProtoOpts = #{
  519. env => #{dispatch => Dispatch},
  520. idle_timeout => infinity
  521. },
  522. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, TransOpts, ProtoOpts),
  523. Port = ranch:get_port(?FUNCTION_NAME),
  524. try
  525. %% Connect a client that sends a request and waits indefinitely.
  526. {ok, ClientSocket} = gen_tcp:connect("localhost", Port,
  527. [{recbuf, 10}, {buffer, 10}, {active, false}, {packet, 0}]),
  528. ok = gen_tcp:send(ClientSocket, [
  529. "GET /endless HTTP/1.1\r\n",
  530. "Host: localhost:", integer_to_list(Port), "\r\n",
  531. "x-test-pid: ", pid_to_list(self()), "\r\n\r\n"
  532. ]),
  533. %% Wait for the handler to start then get its pid,
  534. %% the remote connection's pid and socket.
  535. StreamPid = receive
  536. {Self, StreamPid0, init} when Self =:= self() ->
  537. StreamPid0
  538. after 1000 ->
  539. error(timeout)
  540. end,
  541. ServerPid = ct_helper:get_remote_pid_tcp(ClientSocket),
  542. {links, ServerLinks} = process_info(ServerPid, links),
  543. [ServerSocket] = [PidOrPort || PidOrPort <- ServerLinks, is_port(PidOrPort)],
  544. %% Poll the socket repeatedly until it is closed by the server.
  545. WaitClosedFun =
  546. fun F(T) when T =< 0 ->
  547. error({status, prim_inet:getstatus(ServerSocket)});
  548. F(T) ->
  549. Snooze = 100,
  550. case inet:sockname(ServerSocket) of
  551. {error, _} ->
  552. timer:sleep(Snooze);
  553. {ok, _} ->
  554. timer:sleep(Snooze),
  555. F(T - Snooze)
  556. end
  557. end,
  558. ok = WaitClosedFun(2000),
  559. false = erlang:is_process_alive(StreamPid),
  560. false = erlang:is_process_alive(ServerPid)
  561. after
  562. cowboy:stop_listener(?FUNCTION_NAME)
  563. end.