http_SUITE.erl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. ok
  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. ok
  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. after
  334. cowboy:stop_listener(?FUNCTION_NAME)
  335. end.
  336. set_options_idle_timeout(Config) ->
  337. doc("Confirm that the idle_timeout option can be dynamically "
  338. "set to change how long Cowboy will wait before it closes the connection."),
  339. %% We start with a long timeout and then cut it short.
  340. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  341. env => #{dispatch => init_dispatch(Config)},
  342. idle_timeout => 60000
  343. }),
  344. Port = ranch:get_port(?FUNCTION_NAME),
  345. try
  346. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  347. {ok, http} = gun:await_up(ConnPid),
  348. timer:sleep(500),
  349. #{socket := Socket} = gun:info(ConnPid),
  350. Pid = get_remote_pid_tcp(Socket),
  351. _ = gun:post(ConnPid, "/set_options/idle_timeout_short",
  352. [{<<"content-type">>, <<"text/plain">>}]),
  353. Ref = erlang:monitor(process, Pid),
  354. receive
  355. {'DOWN', Ref, process, Pid, _} ->
  356. ok
  357. after 2000 ->
  358. error(timeout)
  359. end
  360. after
  361. cowboy:stop_listener(?FUNCTION_NAME)
  362. end.
  363. set_options_idle_timeout_only_applies_to_current_request(Config) ->
  364. doc("Confirm that changes to the idle_timeout option only apply to the current stream."),
  365. %% We start with a long timeout and then cut it short.
  366. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  367. env => #{dispatch => init_dispatch(Config)},
  368. idle_timeout => 500
  369. }),
  370. Port = ranch:get_port(?FUNCTION_NAME),
  371. try
  372. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  373. {ok, http} = gun:await_up(ConnPid),
  374. timer:sleep(500),
  375. #{socket := Socket} = gun:info(ConnPid),
  376. Pid = get_remote_pid_tcp(Socket),
  377. StreamRef = gun:post(ConnPid, "/set_options/idle_timeout_long",
  378. [{<<"content-type">>, <<"text/plain">>}]),
  379. Ref = erlang:monitor(process, Pid),
  380. receive
  381. {'DOWN', Ref, process, Pid, Reason} ->
  382. error(Reason)
  383. after 2000 ->
  384. ok
  385. end,
  386. %% Finish the first request and start a second one to confirm
  387. %% the idle_timeout option is back to normal.
  388. gun:data(ConnPid, StreamRef, fin, <<"Hello!">>),
  389. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef),
  390. {ok, <<"Hello!">>} = gun:await_body(ConnPid, StreamRef),
  391. _ = gun:post(ConnPid, "/echo/read_body",
  392. [{<<"content-type">>, <<"text/plain">>}]),
  393. receive
  394. {'DOWN', Ref, process, Pid, _} ->
  395. ok
  396. after 2000 ->
  397. error(timeout)
  398. end
  399. after
  400. cowboy:stop_listener(?FUNCTION_NAME)
  401. end.
  402. switch_protocol_flush(Config) ->
  403. doc("Confirm that switch_protocol does not flush unrelated messages."),
  404. ProtoOpts = #{
  405. env => #{dispatch => init_dispatch(Config)},
  406. stream_handlers => [switch_protocol_flush_h]
  407. },
  408. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  409. Port = ranch:get_port(?FUNCTION_NAME),
  410. try
  411. Self = self(),
  412. ConnPid = gun_open([{port, Port}, {type, tcp}, {protocol, http}|Config]),
  413. _ = gun:get(ConnPid, "/", [
  414. {<<"x-test-pid">>, pid_to_list(Self)}
  415. ]),
  416. receive
  417. {Self, Events} ->
  418. switch_protocol_flush_h:validate(Events)
  419. after 5000 ->
  420. error(timeout)
  421. end
  422. after
  423. cowboy:stop_listener(?FUNCTION_NAME)
  424. end.
  425. graceful_shutdown_connection(Config) ->
  426. doc("Check that the current request is handled before gracefully "
  427. "shutting down a connection."),
  428. Dispatch = cowboy_router:compile([{"localhost", [
  429. {"/hello", delay_hello_h,
  430. #{delay => 0, notify_received => self()}},
  431. {"/delay_hello", delay_hello_h,
  432. #{delay => 1000, notify_received => self()}}
  433. ]}]),
  434. ProtoOpts = #{
  435. env => #{dispatch => Dispatch}
  436. },
  437. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  438. Port = ranch:get_port(?FUNCTION_NAME),
  439. try
  440. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  441. ok = raw_send(Client,
  442. "GET /delay_hello HTTP/1.1\r\n"
  443. "Host: localhost\r\n\r\n"
  444. "GET /hello HTTP/1.1\r\n"
  445. "Host: localhost\r\n\r\n"),
  446. receive {request_received, <<"/delay_hello">>} -> ok end,
  447. receive {request_received, <<"/hello">>} -> ok end,
  448. CowboyConnPid = get_remote_pid_tcp(element(2, Client)),
  449. CowboyConnRef = erlang:monitor(process, CowboyConnPid),
  450. ok = sys:terminate(CowboyConnPid, system_is_going_down),
  451. Rest = case catch raw_recv_head(Client) of
  452. {'EXIT', _} -> error(closed);
  453. Data ->
  454. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  455. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  456. <<"close">> = proplists:get_value(<<"connection">>, Headers),
  457. Rest1
  458. end,
  459. <<"Hello world!">> = raw_recv_rest(Client, byte_size(<<"Hello world!">>), Rest),
  460. {error, closed} = raw_recv(Client, 0, 1000),
  461. receive
  462. {'DOWN', CowboyConnRef, process, CowboyConnPid, _Reason} ->
  463. ok
  464. end
  465. after
  466. cowboy:stop_listener(?FUNCTION_NAME)
  467. end.
  468. graceful_shutdown_listener(Config) ->
  469. doc("Check that connections are shut down gracefully when stopping a listener."),
  470. Dispatch = cowboy_router:compile([{"localhost", [
  471. {"/delay_hello", delay_hello_h,
  472. #{delay => 500, notify_received => self()}},
  473. {"/long_delay_hello", delay_hello_h,
  474. #{delay => 10000, notify_received => self()}}
  475. ]}]),
  476. ProtoOpts = #{
  477. env => #{dispatch => Dispatch}
  478. },
  479. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  480. Port = ranch:get_port(?FUNCTION_NAME),
  481. ConnPid1 = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  482. Ref1 = gun:get(ConnPid1, "/delay_hello"),
  483. ConnPid2 = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  484. Ref2 = gun:get(ConnPid2, "/long_delay_hello"),
  485. %% Shutdown listener while the handlers are working.
  486. receive {request_received, <<"/delay_hello">>} -> ok end,
  487. receive {request_received, <<"/long_delay_hello">>} -> ok end,
  488. ok = cowboy:stop_listener(?FUNCTION_NAME),
  489. %% Check that the 1st request is handled before shutting down.
  490. {response, nofin, 200, RespHeaders} = gun:await(ConnPid1, Ref1),
  491. <<"close">> = proplists:get_value(<<"connection">>, RespHeaders),
  492. {ok, RespBody} = gun:await_body(ConnPid1, Ref1),
  493. <<"Hello world!">> = iolist_to_binary(RespBody),
  494. gun:close(ConnPid1),
  495. %% Check that the 2nd (very slow) request is not handled.
  496. {error, {stream_error, closed}} = gun:await(ConnPid2, Ref2),
  497. gun:close(ConnPid2).
  498. send_timeout_close(_Config) ->
  499. doc("Check that connections are closed on send timeout."),
  500. TransOpts = #{
  501. port => 0,
  502. socket_opts => [
  503. {send_timeout, 100},
  504. {send_timeout_close, true},
  505. {sndbuf, 10}
  506. ]
  507. },
  508. Dispatch = cowboy_router:compile([{"localhost", [
  509. {"/endless", loop_handler_endless_h, #{delay => 100}}
  510. ]}]),
  511. ProtoOpts = #{
  512. env => #{dispatch => Dispatch},
  513. idle_timeout => infinity
  514. },
  515. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, TransOpts, ProtoOpts),
  516. Port = ranch:get_port(?FUNCTION_NAME),
  517. try
  518. %% Connect a client that sends a request and waits indefinitely.
  519. {ok, ClientSocket} = gen_tcp:connect("localhost", Port,
  520. [{recbuf, 10}, {buffer, 10}, {active, false}, {packet, 0}]),
  521. ok = gen_tcp:send(ClientSocket, [
  522. "GET /endless HTTP/1.1\r\n",
  523. "Host: localhost:", integer_to_list(Port), "\r\n",
  524. "x-test-pid: ", pid_to_list(self()), "\r\n\r\n"
  525. ]),
  526. %% Wait for the handler to start then get its pid,
  527. %% the remote connection's pid and socket.
  528. StreamPid = receive
  529. {Self, StreamPid0, init} when Self =:= self() ->
  530. StreamPid0
  531. after 1000 ->
  532. error(timeout)
  533. end,
  534. ServerPid = ct_helper:get_remote_pid_tcp(ClientSocket),
  535. {links, ServerLinks} = process_info(ServerPid, links),
  536. [ServerSocket] = [PidOrPort || PidOrPort <- ServerLinks, is_port(PidOrPort)],
  537. %% Poll the socket repeatedly until it is closed by the server.
  538. WaitClosedFun =
  539. fun F(T) when T =< 0 ->
  540. error({status, prim_inet:getstatus(ServerSocket)});
  541. F(T) ->
  542. Snooze = 100,
  543. case inet:sockname(ServerSocket) of
  544. {error, _} ->
  545. timer:sleep(Snooze);
  546. {ok, _} ->
  547. timer:sleep(Snooze),
  548. F(T - Snooze)
  549. end
  550. end,
  551. ok = WaitClosedFun(2000),
  552. false = erlang:is_process_alive(StreamPid),
  553. false = erlang:is_process_alive(ServerPid)
  554. after
  555. cowboy:stop_listener(?FUNCTION_NAME)
  556. end.