http_SUITE.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. idle_timeout => infinity
  217. }),
  218. Port = ranch:get_port(?FUNCTION_NAME),
  219. try
  220. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  221. {ok, http} = gun:await_up(ConnPid),
  222. timer:sleep(500),
  223. #{socket := Socket} = gun:info(ConnPid),
  224. Pid = get_remote_pid_tcp(Socket),
  225. _ = gun:post(ConnPid, "/echo/read_body",
  226. [{<<"content-type">>, <<"text/plain">>}]),
  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. persistent_term_router(Config) ->
  238. doc("The router can retrieve the routes from persistent_term storage."),
  239. case erlang:function_exported(persistent_term, get, 1) of
  240. true -> do_persistent_term_router(Config);
  241. false -> {skip, "This test uses the persistent_term functionality added in Erlang/OTP 21.2."}
  242. end.
  243. do_persistent_term_router(Config) ->
  244. persistent_term:put(?FUNCTION_NAME, init_dispatch(Config)),
  245. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  246. env => #{dispatch => {persistent_term, ?FUNCTION_NAME}}
  247. }),
  248. Port = ranch:get_port(?FUNCTION_NAME),
  249. try
  250. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  251. {ok, http} = gun:await_up(ConnPid),
  252. StreamRef = gun:get(ConnPid, "/"),
  253. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef),
  254. gun:close(ConnPid)
  255. after
  256. cowboy:stop_listener(?FUNCTION_NAME)
  257. end.
  258. request_timeout_infinity(Config) ->
  259. doc("Ensure the request_timeout option accepts the infinity value."),
  260. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  261. env => #{dispatch => init_dispatch(Config)},
  262. request_timeout => infinity
  263. }),
  264. Port = ranch:get_port(?FUNCTION_NAME),
  265. try
  266. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  267. {ok, http} = gun:await_up(ConnPid),
  268. timer:sleep(500),
  269. #{socket := Socket} = gun:info(ConnPid),
  270. Pid = get_remote_pid_tcp(Socket),
  271. Ref = erlang:monitor(process, Pid),
  272. receive
  273. {'DOWN', Ref, process, Pid, Reason} ->
  274. error(Reason)
  275. after 1000 ->
  276. ok
  277. end
  278. after
  279. cowboy:stop_listener(?FUNCTION_NAME)
  280. end.
  281. set_options_chunked_false(Config) ->
  282. doc("Confirm the option chunked can be dynamically set to disable "
  283. "chunked transfer-encoding. This results in the closing of the "
  284. "connection after the current request."),
  285. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  286. env => #{dispatch => init_dispatch(Config)},
  287. chunked => true
  288. }),
  289. Port = ranch:get_port(?FUNCTION_NAME),
  290. try
  291. Request = "GET /set_options/chunked_false HTTP/1.1\r\nhost: localhost\r\n\r\n",
  292. Client = raw_open([{type, tcp}, {port, Port}, {opts, []}|Config]),
  293. ok = raw_send(Client, Request),
  294. Rest = case catch raw_recv_head(Client) of
  295. {'EXIT', _} -> error(closed);
  296. Data ->
  297. %% Cowboy always advertises itself as HTTP/1.1.
  298. {'HTTP/1.1', 200, _, Rest0} = cow_http:parse_status_line(Data),
  299. {Headers, Rest1} = cow_http:parse_headers(Rest0),
  300. false = lists:keyfind(<<"content-length">>, 1, Headers),
  301. false = lists:keyfind(<<"transfer-encoding">>, 1, Headers),
  302. Rest1
  303. end,
  304. Bits = 8000000 - bit_size(Rest),
  305. raw_expect_recv(Client, <<0:Bits>>),
  306. {error, closed} = raw_recv(Client, 1, 1000)
  307. after
  308. cowboy:stop_listener(?FUNCTION_NAME)
  309. end.
  310. set_options_chunked_false_ignored(Config) ->
  311. doc("Confirm the option chunked can be dynamically set to disable "
  312. "chunked transfer-encoding, and that it is ignored if the "
  313. "response is not streamed."),
  314. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  315. env => #{dispatch => init_dispatch(Config)},
  316. chunked => true
  317. }),
  318. Port = ranch:get_port(?FUNCTION_NAME),
  319. try
  320. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  321. %% We do a first request setting the option but not
  322. %% using chunked transfer-encoding in the response.
  323. StreamRef1 = gun:get(ConnPid, "/set_options/chunked_false_ignored"),
  324. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef1),
  325. {ok, <<"Hello world!">>} = gun:await_body(ConnPid, StreamRef1),
  326. %% We then do a second request to confirm that chunked
  327. %% is not disabled for that second request.
  328. StreamRef2 = gun:get(ConnPid, "/resp/stream_reply2/200"),
  329. {response, nofin, 200, Headers} = gun:await(ConnPid, StreamRef2),
  330. {_, <<"chunked">>} = lists:keyfind(<<"transfer-encoding">>, 1, Headers)
  331. after
  332. cowboy:stop_listener(?FUNCTION_NAME)
  333. end.
  334. set_options_idle_timeout(Config) ->
  335. doc("Confirm that the idle_timeout option can be dynamically "
  336. "set to change how long Cowboy will wait before it closes the connection."),
  337. %% We start with a long timeout and then cut it short.
  338. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  339. env => #{dispatch => init_dispatch(Config)},
  340. idle_timeout => 60000
  341. }),
  342. Port = ranch:get_port(?FUNCTION_NAME),
  343. try
  344. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  345. {ok, http} = gun:await_up(ConnPid),
  346. timer:sleep(500),
  347. #{socket := Socket} = gun:info(ConnPid),
  348. Pid = get_remote_pid_tcp(Socket),
  349. _ = gun:post(ConnPid, "/set_options/idle_timeout_short",
  350. [{<<"content-type">>, <<"text/plain">>}]),
  351. Ref = erlang:monitor(process, Pid),
  352. receive
  353. {'DOWN', Ref, process, Pid, _} ->
  354. ok
  355. after 2000 ->
  356. error(timeout)
  357. end
  358. after
  359. cowboy:stop_listener(?FUNCTION_NAME)
  360. end.
  361. set_options_idle_timeout_only_applies_to_current_request(Config) ->
  362. doc("Confirm that changes to the idle_timeout option only apply to the current stream."),
  363. %% We start with a long timeout and then cut it short.
  364. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], #{
  365. env => #{dispatch => init_dispatch(Config)},
  366. idle_timeout => 500
  367. }),
  368. Port = ranch:get_port(?FUNCTION_NAME),
  369. try
  370. ConnPid = gun_open([{type, tcp}, {protocol, http}, {port, Port}|Config]),
  371. {ok, http} = gun:await_up(ConnPid),
  372. timer:sleep(500),
  373. #{socket := Socket} = gun:info(ConnPid),
  374. Pid = get_remote_pid_tcp(Socket),
  375. StreamRef = gun:post(ConnPid, "/set_options/idle_timeout_long",
  376. [{<<"content-type">>, <<"text/plain">>}]),
  377. Ref = erlang:monitor(process, Pid),
  378. receive
  379. {'DOWN', Ref, process, Pid, Reason} ->
  380. error(Reason)
  381. after 2000 ->
  382. ok
  383. end,
  384. %% Finish the first request and start a second one to confirm
  385. %% the idle_timeout option is back to normal.
  386. gun:data(ConnPid, StreamRef, fin, <<"Hello!">>),
  387. {response, nofin, 200, _} = gun:await(ConnPid, StreamRef),
  388. {ok, <<"Hello!">>} = gun:await_body(ConnPid, StreamRef),
  389. _ = gun:post(ConnPid, "/echo/read_body",
  390. [{<<"content-type">>, <<"text/plain">>}]),
  391. receive
  392. {'DOWN', Ref, process, Pid, _} ->
  393. ok
  394. after 2000 ->
  395. error(timeout)
  396. end
  397. after
  398. cowboy:stop_listener(?FUNCTION_NAME)
  399. end.
  400. switch_protocol_flush(Config) ->
  401. doc("Confirm that switch_protocol does not flush unrelated messages."),
  402. ProtoOpts = #{
  403. env => #{dispatch => init_dispatch(Config)},
  404. stream_handlers => [switch_protocol_flush_h]
  405. },
  406. {ok, _} = cowboy:start_clear(?FUNCTION_NAME, [{port, 0}], ProtoOpts),
  407. Port = ranch:get_port(?FUNCTION_NAME),
  408. try
  409. Self = self(),
  410. ConnPid = gun_open([{port, Port}, {type, tcp}, {protocol, http}|Config]),
  411. _ = gun:get(ConnPid, "/", [
  412. {<<"x-test-pid">>, pid_to_list(Self)}
  413. ]),
  414. receive
  415. {Self, Events} ->
  416. switch_protocol_flush_h:validate(Events)
  417. after 5000 ->
  418. error(timeout)
  419. end
  420. after
  421. cowboy:stop_listener(?FUNCTION_NAME)
  422. end.