http_SUITE.erl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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, [raw_open/1]).
  22. -import(cowboy_test, [raw_send/2]).
  23. -import(cowboy_test, [raw_recv_head/1]).
  24. -import(cowboy_test, [raw_recv/3]).
  25. -import(cowboy_test, [raw_expect_recv/2]).
  26. all() -> [{group, clear}].
  27. groups() -> [{clear, [parallel], ct_helper:all(?MODULE)}].
  28. init_per_group(Name, Config) ->
  29. cowboy_test:init_http(Name, #{
  30. env => #{dispatch => init_dispatch(Config)}
  31. }, Config).
  32. end_per_group(Name, _) ->
  33. cowboy:stop_listener(Name).
  34. init_dispatch(_) ->
  35. cowboy_router:compile([{"localhost", [
  36. {"/", hello_h, []},
  37. {"/echo/:key", echo_h, []},
  38. {"/resp/:key[/:arg]", resp_h, []},
  39. {"/set_options/:key", set_options_h, []}
  40. ]}]).
  41. chunked_false(Config) ->
  42. doc("Confirm the option chunked => false disables chunked "
  43. "transfer-encoding for HTTP/1.1 connections."),
  44. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  45. env => #{dispatch => init_dispatch(Config)},
  46. chunked => false
  47. }),
  48. Port = ranch:get_port(?FUNCTION_NAME),
  49. try
  50. Request = "GET /resp/stream_reply2/200 HTTP/1.1\r\nhost: localhost\r\n\r\n",
  51. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  52. ok = raw_send(Client, Request),
  53. Rest = case catch raw_recv_head(Client) of
  54. {'EXIT', _} -> error(closed);
  55. Data ->
  56. %% Cowboy always advertises itself as HTTP/1.1.
  57. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  58. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  59. false = lists:keyfind(<<"content-length">>, 1, Headers),
  60. false = lists:keyfind(<<"transfer-encoding">>, 1, Headers),
  61. Rest1
  62. end,
  63. Bits = 8000000 - bit_size(Rest),
  64. raw_expect_recv(Client, <<0:Bits>>),
  65. {error, closed} = raw_recv(Client, 1, 1000)
  66. after
  67. cowboy:stop_listener(?FUNCTION_NAME)
  68. end.
  69. chunked_one_byte_at_a_time(Config) ->
  70. doc("Confirm that chunked transfer-encoding works when "
  71. "the body is received one byte at a time."),
  72. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  73. ChunkedBody = iolist_to_binary(do_chunked_body(50, Body, [])),
  74. Client = raw_open(Config),
  75. ok = raw_send(Client,
  76. "POST /echo/read_body HTTP/1.1\r\n"
  77. "Host: localhost\r\n"
  78. "Transfer-encoding: chunked\r\n\r\n"),
  79. _ = [begin
  80. raw_send(Client, <<C>>),
  81. timer:sleep(10)
  82. end || <<C>> <= ChunkedBody],
  83. Rest = case catch raw_recv_head(Client) of
  84. {'EXIT', _} -> error(closed);
  85. Data ->
  86. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  87. {_, Rest1} = cow_http:parse_headers(Rest0),
  88. Rest1
  89. end,
  90. RestSize = byte_size(Rest),
  91. <<Rest:RestSize/binary, Expect/bits>> = Body,
  92. raw_expect_recv(Client, Expect).
  93. chunked_one_chunk_at_a_time(Config) ->
  94. doc("Confirm that chunked transfer-encoding works when "
  95. "the body is received one chunk at a time."),
  96. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  97. Chunks = do_chunked_body(50, Body, []),
  98. Client = raw_open(Config),
  99. ok = raw_send(Client,
  100. "POST /echo/read_body HTTP/1.1\r\n"
  101. "Host: localhost\r\n"
  102. "Transfer-encoding: chunked\r\n\r\n"),
  103. _ = [begin
  104. raw_send(Client, Chunk),
  105. timer:sleep(10)
  106. end || Chunk <- Chunks],
  107. Rest = case catch raw_recv_head(Client) of
  108. {'EXIT', _} -> error(closed);
  109. Data ->
  110. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  111. {_, Rest1} = cow_http:parse_headers(Rest0),
  112. Rest1
  113. end,
  114. RestSize = byte_size(Rest),
  115. <<Rest:RestSize/binary, Expect/bits>> = Body,
  116. raw_expect_recv(Client, Expect).
  117. chunked_split_delay_in_chunk_body(Config) ->
  118. doc("Confirm that chunked transfer-encoding works when "
  119. "the body is received with a delay inside the chunks."),
  120. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  121. Chunks = do_chunked_body(50, Body, []),
  122. Client = raw_open(Config),
  123. ok = raw_send(Client,
  124. "POST /echo/read_body HTTP/1.1\r\n"
  125. "Host: localhost\r\n"
  126. "Transfer-encoding: chunked\r\n\r\n"),
  127. _ = [begin
  128. case Chunk of
  129. <<"0\r\n\r\n">> ->
  130. raw_send(Client, Chunk);
  131. _ ->
  132. [Size, ChunkBody, <<>>] = binary:split(Chunk, <<"\r\n">>, [global]),
  133. PartASize = rand:uniform(byte_size(ChunkBody)),
  134. <<PartA:PartASize/binary, PartB/binary>> = ChunkBody,
  135. raw_send(Client, [Size, <<"\r\n">>, PartA]),
  136. timer:sleep(10),
  137. raw_send(Client, [PartB, <<"\r\n">>])
  138. end
  139. end || Chunk <- Chunks],
  140. Rest = case catch raw_recv_head(Client) of
  141. {'EXIT', _} -> error(closed);
  142. Data ->
  143. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  144. {_, Rest1} = cow_http:parse_headers(Rest0),
  145. Rest1
  146. end,
  147. RestSize = byte_size(Rest),
  148. <<Rest:RestSize/binary, Expect/bits>> = Body,
  149. raw_expect_recv(Client, Expect).
  150. chunked_split_delay_in_chunk_crlf(Config) ->
  151. doc("Confirm that chunked transfer-encoding works when "
  152. "the body is received with a delay inside the chunks end CRLF."),
  153. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  154. Chunks = do_chunked_body(50, Body, []),
  155. Client = raw_open(Config),
  156. ok = raw_send(Client,
  157. "POST /echo/read_body HTTP/1.1\r\n"
  158. "Host: localhost\r\n"
  159. "Transfer-encoding: chunked\r\n\r\n"),
  160. _ = [begin
  161. Len = byte_size(Chunk) - (rand:uniform(2) - 1),
  162. <<Begin:Len/binary, End/binary>> = Chunk,
  163. raw_send(Client, Begin),
  164. timer:sleep(10),
  165. raw_send(Client, End)
  166. end || Chunk <- Chunks],
  167. Rest = case catch raw_recv_head(Client) of
  168. {'EXIT', _} -> error(closed);
  169. Data ->
  170. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  171. {_, Rest1} = cow_http:parse_headers(Rest0),
  172. Rest1
  173. end,
  174. RestSize = byte_size(Rest),
  175. <<Rest:RestSize/binary, Expect/bits>> = Body,
  176. raw_expect_recv(Client, Expect).
  177. do_chunked_body(_, <<>>, Acc) ->
  178. lists:reverse([cow_http_te:last_chunk()|Acc]);
  179. do_chunked_body(ChunkSize0, Data, Acc) ->
  180. ChunkSize = min(byte_size(Data), ChunkSize0),
  181. <<Chunk:ChunkSize/binary, Rest/binary>> = Data,
  182. do_chunked_body(ChunkSize, Rest,
  183. [iolist_to_binary(cow_http_te:chunk(Chunk))|Acc]).
  184. http10_keepalive_false(Config) ->
  185. doc("Confirm the option http10_keepalive => false disables keep-alive "
  186. "completely for HTTP/1.0 connections."),
  187. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  188. env => #{dispatch => init_dispatch(Config)},
  189. http10_keepalive => false
  190. }),
  191. Port = ranch:get_port(?FUNCTION_NAME),
  192. try
  193. Keepalive = "GET / HTTP/1.0\r\nhost: localhost\r\nConnection: keep-alive\r\n\r\n",
  194. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  195. ok = raw_send(Client, Keepalive),
  196. _ = case catch raw_recv_head(Client) of
  197. {'EXIT', _} -> error(closed);
  198. Data ->
  199. %% Cowboy always advertises itself as HTTP/1.1.
  200. {'HTTP/1.1', 200, _, Rest} = cow_http:parse_status_line(Data),
  201. {Headers, _} = cow_http:parse_headers(Rest),
  202. {_, <<"close">>} = lists:keyfind(<<"connection">>, 1, Headers)
  203. end,
  204. ok = raw_send(Client, Keepalive),
  205. case catch raw_recv_head(Client) of
  206. {'EXIT', _} -> closed;
  207. _ -> error(not_closed)
  208. end
  209. after
  210. cowboy:stop_listener(?FUNCTION_NAME)
  211. end.
  212. idle_timeout_infinity(Config) ->
  213. doc("Ensure the idle_timeout option accepts the infinity value."),
  214. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  215. env => #{dispatch => init_dispatch(Config)},
  216. request_timeout => 500,
  217. idle_timeout => infinity
  218. }),
  219. Port = ranch:get_port(?FUNCTION_NAME),
  220. try
  221. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  222. {ok, http} = gun:await_up(ConnPid),
  223. _ = gun:post(ConnPid, "/echo/read_body",
  224. [{<<"content-type">>, <<"text/plain">>}]),
  225. #{socket := Socket} = gun:info(ConnPid),
  226. Pid = get_remote_pid_tcp(Socket),
  227. Ref = erlang:monitor(process, Pid),
  228. receive
  229. {'DOWN', Ref, process, Pid, Reason} ->
  230. error(Reason)
  231. after 1000 ->
  232. ok
  233. end
  234. after
  235. cowboy:stop_listener(?FUNCTION_NAME)
  236. end.
  237. request_timeout_infinity(Config) ->
  238. doc("Ensure the request_timeout option accepts the infinity value."),
  239. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  240. env => #{dispatch => init_dispatch(Config)},
  241. request_timeout => infinity
  242. }),
  243. Port = ranch:get_port(?FUNCTION_NAME),
  244. try
  245. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  246. {ok, http} = gun:await_up(ConnPid),
  247. #{socket := Socket} = gun:info(ConnPid),
  248. Pid = get_remote_pid_tcp(Socket),
  249. Ref = erlang:monitor(process, Pid),
  250. receive
  251. {'DOWN', Ref, process, Pid, Reason} ->
  252. error(Reason)
  253. after 1000 ->
  254. ok
  255. end
  256. after
  257. cowboy:stop_listener(?FUNCTION_NAME)
  258. end.
  259. set_options_chunked_false(Config) ->
  260. doc("Confirm the option chunked can be dynamically set to disable "
  261. "chunked transfer-encoding. This results in the closing of the "
  262. "connection after the current request."),
  263. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  264. env => #{dispatch => init_dispatch(Config)},
  265. chunked => true
  266. }),
  267. Port = ranch:get_port(?FUNCTION_NAME),
  268. try
  269. Request = "GET /set_options/chunked_false HTTP/1.1\r\nhost: localhost\r\n\r\n",
  270. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  271. ok = raw_send(Client, Request),
  272. Rest = case catch raw_recv_head(Client) of
  273. {'EXIT', _} -> error(closed);
  274. Data ->
  275. %% Cowboy always advertises itself as HTTP/1.1.
  276. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  277. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  278. false = lists:keyfind(<<"content-length">>, 1, Headers),
  279. false = lists:keyfind(<<"transfer-encoding">>, 1, Headers),
  280. Rest1
  281. end,
  282. Bits = 8000000 - bit_size(Rest),
  283. raw_expect_recv(Client, <<0:Bits>>),
  284. {error, closed} = raw_recv(Client, 1, 1000)
  285. after
  286. cowboy:stop_listener(?FUNCTION_NAME)
  287. end.
  288. set_options_chunked_false_ignored(Config) ->
  289. doc("Confirm the option chunked can be dynamically set to disable "
  290. "chunked transfer-encoding, and that it is ignored if the "
  291. "response is not streamed."),
  292. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  293. env => #{dispatch => init_dispatch(Config)},
  294. chunked => true
  295. }),
  296. Port = ranch:get_port(?FUNCTION_NAME),
  297. try
  298. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  299. %% We do a first request setting the option but not
  300. %% using chunked transfer-encoding in the response.
  301. StreamRef1 = gun:get(ConnPid, "/set_options/chunked_false_ignored"),
  302. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef1),
  303. {ok, <<"Hello world!">>} = gun:await_body(ConnPid, StreamRef1),
  304. %% We then do a second request to confirm that chunked
  305. %% is not disabled for that second request.
  306. StreamRef2 = gun:get(ConnPid, "/resp/stream_reply2/200"),
  307. {response, nofin, 200, Headers} = gun:await(ConnPid, StreamRef2),
  308. {_, <<"chunked">>} = lists:keyfind(<<"transfer-encoding">>, 1, Headers)
  309. after
  310. cowboy:stop_listener(?FUNCTION_NAME)
  311. end.
  312. set_options_idle_timeout(Config) ->
  313. doc("Confirm that the idle_timeout option can be dynamically "
  314. "set to change how long Cowboy will wait before it closes the connection."),
  315. %% We start with a long timeout and then cut it short.
  316. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  317. env => #{dispatch => init_dispatch(Config)},
  318. idle_timeout => 60000
  319. }),
  320. Port = ranch:get_port(?FUNCTION_NAME),
  321. try
  322. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  323. {ok, http} = gun:await_up(ConnPid),
  324. _ = gun:post(ConnPid, "/set_options/idle_timeout_short",
  325. [{<<"content-type">>, <<"text/plain">>}]),
  326. #{socket := Socket} = gun:info(ConnPid),
  327. Pid = get_remote_pid_tcp(Socket),
  328. Ref = erlang:monitor(process, Pid),
  329. receive
  330. {'DOWN', Ref, process, Pid, _} ->
  331. ok
  332. after 2000 ->
  333. error(timeout)
  334. end
  335. after
  336. cowboy:stop_listener(?FUNCTION_NAME)
  337. end.
  338. set_options_idle_timeout_only_applies_to_current_request(Config) ->
  339. doc("Confirm that changes to the idle_timeout option only apply to the current stream."),
  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 => 500
  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. StreamRef = gun:post(ConnPid, "/set_options/idle_timeout_long",
  350. [{<<"content-type">>, <<"text/plain">>}]),
  351. #{socket := Socket} = gun:info(ConnPid),
  352. Pid = get_remote_pid_tcp(Socket),
  353. Ref = erlang:monitor(process, Pid),
  354. receive
  355. {'DOWN', Ref, process, Pid, Reason} ->
  356. error(Reason)
  357. after 2000 ->
  358. ok
  359. end,
  360. %% Finish the first request and start a second one to confirm
  361. %% the idle_timeout option is back to normal.
  362. gun:data(ConnPid, StreamRef, fin, <<"Hello!">>),
  363. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef),
  364. {ok, <<"Hello!">>} = gun:await_body(ConnPid, StreamRef),
  365. _ = gun:post(ConnPid, "/echo/read_body",
  366. [{<<"content-type">>, <<"text/plain">>}]),
  367. receive
  368. {'DOWN', Ref, process, Pid, _} ->
  369. ok
  370. after 2000 ->
  371. error(timeout)
  372. end
  373. after
  374. cowboy:stop_listener(?FUNCTION_NAME)
  375. end.
  376. switch_protocol_flush(Config) ->
  377. doc("Confirm that switch_protocol does not flush unrelated messages."),
  378. ProtoOpts = #{
  379. env => #{dispatch => init_dispatch(Config)},
  380. stream_handlers => [switch_protocol_flush_h]
  381. },
  382. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  383. Port = ranch:get_port(?FUNCTION_NAME),
  384. try
  385. Self = self(),
  386. ConnPid = gun_open([{port, Port}, {type, tcp}, {protocol, http}|Config]),
  387. _ = gun:get(ConnPid, "/", [
  388. {<<"x-test-pid">>, pid_to_list(Self)}
  389. ]),
  390. receive
  391. {Self, Events} ->
  392. switch_protocol_flush_h:validate(Events)
  393. after 5000 ->
  394. error(timeout)
  395. end
  396. after
  397. cowboy:stop_listener(?FUNCTION_NAME)
  398. end.