req_SUITE.erl 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. %% Copyright (c) 2016-2017, 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(req_SUITE).
  15. -compile(export_all).
  16. -compile(nowarn_export_all).
  17. -import(ct_helper, [config/2]).
  18. -import(ct_helper, [doc/1]).
  19. -import(cowboy_test, [gun_open/1]).
  20. %% ct.
  21. all() ->
  22. cowboy_test:common_all().
  23. groups() ->
  24. cowboy_test:common_groups(ct_helper:all(?MODULE)).
  25. init_per_suite(Config) ->
  26. ct_helper:create_static_dir(config(priv_dir, Config) ++ "/static"),
  27. Config.
  28. end_per_suite(Config) ->
  29. ct_helper:delete_static_dir(config(priv_dir, Config) ++ "/static").
  30. init_per_group(Name, Config) ->
  31. cowboy_test:init_common_groups(Name, Config, ?MODULE).
  32. end_per_group(Name, _) ->
  33. cowboy:stop_listener(Name).
  34. %% Routes.
  35. init_dispatch(Config) ->
  36. cowboy_router:compile([{"[...]", [
  37. {"/static/[...]", cowboy_static, {dir, config(priv_dir, Config) ++ "/static"}},
  38. %% @todo Seriously InitialState should be optional.
  39. {"/resp/:key[/:arg]", resp_h, []},
  40. {"/multipart[/:key]", multipart_h, []},
  41. {"/args/:key/:arg[/:default]", echo_h, []},
  42. {"/crash/:key/period", echo_h, #{length => 999999999, period => 1000, crash => true}},
  43. {"/no-opts/:key", echo_h, #{crash => true}},
  44. {"/opts/:key/length", echo_h, #{length => 1000}},
  45. {"/opts/:key/period", echo_h, #{length => 999999999, period => 2000}},
  46. {"/opts/:key/timeout", echo_h, #{timeout => 1000, crash => true}},
  47. {"/100-continue/:key", echo_h, []},
  48. {"/full/:key", echo_h, []},
  49. {"/spawn/:key", echo_h, []},
  50. {"/no/:key", echo_h, []},
  51. {"/direct/:key/[...]", echo_h, []},
  52. {"/:key/[...]", echo_h, []}
  53. ]}]).
  54. %% Internal.
  55. do_body(Method, Path, Config) ->
  56. do_body(Method, Path, [], Config).
  57. do_body(Method, Path, Headers, Config) ->
  58. do_body(Method, Path, Headers, <<>>, Config).
  59. do_body(Method, Path, Headers0, Body, Config) ->
  60. ConnPid = gun_open(Config),
  61. Headers = [{<<"accept-encoding">>, <<"gzip">>}|Headers0],
  62. Ref = gun:request(ConnPid, Method, Path, Headers, Body),
  63. {response, IsFin, 200, RespHeaders} = gun:await(ConnPid, Ref, 10000),
  64. {ok, RespBody} = case IsFin of
  65. nofin -> gun:await_body(ConnPid, Ref);
  66. fin -> {ok, <<>>}
  67. end,
  68. gun:close(ConnPid),
  69. do_decode(RespHeaders, RespBody).
  70. do_body_error(Method, Path, Headers0, Body, Config) ->
  71. ConnPid = gun_open(Config),
  72. Headers = [{<<"accept-encoding">>, <<"gzip">>}|Headers0],
  73. Ref = gun:request(ConnPid, Method, Path, Headers, Body),
  74. {response, _, Status, RespHeaders} = gun:await(ConnPid, Ref),
  75. gun:close(ConnPid),
  76. {Status, RespHeaders}.
  77. do_get(Path, Config) ->
  78. do_get(Path, [], Config).
  79. do_get(Path, Headers, Config) ->
  80. ConnPid = gun_open(Config),
  81. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}|Headers]),
  82. {response, IsFin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  83. {ok, RespBody} = case IsFin of
  84. nofin -> gun:await_body(ConnPid, Ref, 30000);
  85. fin -> {ok, <<>>}
  86. end,
  87. gun:close(ConnPid),
  88. {Status, RespHeaders, do_decode(RespHeaders, RespBody)}.
  89. do_get_body(Path, Config) ->
  90. do_get_body(Path, [], Config).
  91. do_get_body(Path, Headers, Config) ->
  92. do_body("GET", Path, Headers, Config).
  93. do_get_inform(Path, Config) ->
  94. ConnPid = gun_open(Config),
  95. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  96. case gun:await(ConnPid, Ref) of
  97. {response, _, RespStatus, RespHeaders} ->
  98. %% We don't care about the body.
  99. gun:close(ConnPid),
  100. {RespStatus, RespHeaders};
  101. {inform, InfoStatus, InfoHeaders} ->
  102. {response, IsFin, RespStatus, RespHeaders}
  103. = case gun:await(ConnPid, Ref) of
  104. {inform, InfoStatus, InfoHeaders} ->
  105. gun:await(ConnPid, Ref);
  106. Response ->
  107. Response
  108. end,
  109. {ok, RespBody} = case IsFin of
  110. nofin -> gun:await_body(ConnPid, Ref);
  111. fin -> {ok, <<>>}
  112. end,
  113. gun:close(ConnPid),
  114. {InfoStatus, InfoHeaders, RespStatus, RespHeaders, do_decode(RespHeaders, RespBody)}
  115. end.
  116. do_decode(Headers, Body) ->
  117. case lists:keyfind(<<"content-encoding">>, 1, Headers) of
  118. {_, <<"gzip">>} -> zlib:gunzip(Body);
  119. _ -> Body
  120. end.
  121. do_get_error(Path, Config) ->
  122. do_get_error(Path, [], Config).
  123. do_get_error(Path, Headers, Config) ->
  124. ConnPid = gun_open(Config),
  125. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}|Headers]),
  126. {response, IsFin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  127. Result = case IsFin of
  128. nofin -> gun:await_body(ConnPid, Ref);
  129. fin -> {ok, <<>>}
  130. end,
  131. case Result of
  132. {ok, RespBody} -> {Status, RespHeaders, do_decode(RespHeaders, RespBody)};
  133. _ -> Result
  134. end.
  135. %% Tests: Request.
  136. binding(Config) ->
  137. doc("Value bound from request URI path with/without default."),
  138. <<"binding">> = do_get_body("/args/binding/key", Config),
  139. <<"binding">> = do_get_body("/args/binding/key/default", Config),
  140. <<"default">> = do_get_body("/args/binding/undefined/default", Config),
  141. ok.
  142. bindings(Config) ->
  143. doc("Values bound from request URI path."),
  144. <<"#{key => <<\"bindings\">>}">> = do_get_body("/bindings", Config),
  145. ok.
  146. cert(Config) ->
  147. case config(type, Config) of
  148. tcp -> doc("TLS certificates can only be provided over TLS.");
  149. ssl -> do_cert(Config)
  150. end.
  151. do_cert(Config0) ->
  152. doc("A client TLS certificate was provided."),
  153. {CaCert, Cert, Key} = ct_helper:make_certs(),
  154. Config = [{tls_opts, [
  155. {cert, Cert},
  156. {key, Key},
  157. {cacerts, [CaCert]}
  158. ]}|Config0],
  159. Cert = do_get_body("/cert", Config),
  160. Cert = do_get_body("/direct/cert", Config),
  161. ok.
  162. cert_undefined(Config) ->
  163. doc("No client TLS certificate was provided."),
  164. <<"undefined">> = do_get_body("/cert", Config),
  165. <<"undefined">> = do_get_body("/direct/cert", Config),
  166. ok.
  167. header(Config) ->
  168. doc("Request header with/without default."),
  169. <<"value">> = do_get_body("/args/header/defined", [{<<"defined">>, "value"}], Config),
  170. <<"value">> = do_get_body("/args/header/defined/default", [{<<"defined">>, "value"}], Config),
  171. <<"default">> = do_get_body("/args/header/undefined/default", [{<<"defined">>, "value"}], Config),
  172. ok.
  173. headers(Config) ->
  174. doc("Request headers."),
  175. do_headers("/headers", Config),
  176. do_headers("/direct/headers", Config).
  177. do_headers(Path, Config) ->
  178. %% We always send accept-encoding with this test suite's requests.
  179. <<"#{<<\"accept-encoding\">> => <<\"gzip\">>,"
  180. "<<\"content-length\">> => <<\"0\">>,"
  181. "<<\"header\">> => <<\"value\">>", _/bits>>
  182. = do_get_body(Path, [{<<"header">>, "value"}], Config),
  183. ok.
  184. host(Config) ->
  185. doc("Request URI host."),
  186. <<"localhost">> = do_get_body("/host", Config),
  187. <<"localhost">> = do_get_body("/direct/host", Config),
  188. ok.
  189. host_info(Config) ->
  190. doc("Request host_info."),
  191. <<"[<<\"localhost\">>]">> = do_get_body("/host_info", Config),
  192. ok.
  193. %% @todo Actually write the related unit tests.
  194. match_cookies(Config) ->
  195. doc("Matched request cookies."),
  196. <<"#{}">> = do_get_body("/match/cookies", [{<<"cookie">>, "a=b; c=d"}], Config),
  197. <<"#{a => <<\"b\">>}">> = do_get_body("/match/cookies/a", [{<<"cookie">>, "a=b; c=d"}], Config),
  198. <<"#{c => <<\"d\">>}">> = do_get_body("/match/cookies/c", [{<<"cookie">>, "a=b; c=d"}], Config),
  199. <<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/cookies/a/c",
  200. [{<<"cookie">>, "a=b; c=d"}], Config),
  201. %% Ensure match errors result in a 400 response.
  202. {400, _, _} = do_get("/match/cookies/a/c",
  203. [{<<"cookie">>, "a=b"}], Config),
  204. %% This function is tested more extensively through unit tests.
  205. ok.
  206. %% @todo Actually write the related unit tests.
  207. match_qs(Config) ->
  208. doc("Matched request URI query string."),
  209. <<"#{}">> = do_get_body("/match/qs?a=b&c=d", Config),
  210. <<"#{a => <<\"b\">>}">> = do_get_body("/match/qs/a?a=b&c=d", Config),
  211. <<"#{c => <<\"d\">>}">> = do_get_body("/match/qs/c?a=b&c=d", Config),
  212. <<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a=b&c=d", Config),
  213. <<"#{a => <<\"b\">>,c => true}">> = do_get_body("/match/qs/a/c?a=b&c", Config),
  214. <<"#{a => true,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a&c=d", Config),
  215. %% Ensure match errors result in a 400 response.
  216. {400, _, _} = do_get("/match/qs/a/c?a=b", [], Config),
  217. %% This function is tested more extensively through unit tests.
  218. ok.
  219. method(Config) ->
  220. doc("Request method."),
  221. do_method("/method", Config),
  222. do_method("/direct/method", Config).
  223. do_method(Path, Config) ->
  224. <<"GET">> = do_body("GET", Path, Config),
  225. <<>> = do_body("HEAD", Path, Config),
  226. <<"OPTIONS">> = do_body("OPTIONS", Path, Config),
  227. <<"PATCH">> = do_body("PATCH", Path, Config),
  228. <<"POST">> = do_body("POST", Path, Config),
  229. <<"PUT">> = do_body("PUT", Path, Config),
  230. <<"ZZZZZZZZ">> = do_body("ZZZZZZZZ", Path, Config),
  231. ok.
  232. parse_cookies(Config) ->
  233. doc("Request cookies."),
  234. <<"[]">> = do_get_body("/parse_cookies", Config),
  235. <<"[{<<\"cake\">>,<<\"strawberry\">>}]">>
  236. = do_get_body("/parse_cookies", [{<<"cookie">>, "cake=strawberry"}], Config),
  237. <<"[{<<\"cake\">>,<<\"strawberry\">>},{<<\"color\">>,<<\"blue\">>}]">>
  238. = do_get_body("/parse_cookies", [{<<"cookie">>, "cake=strawberry; color=blue"}], Config),
  239. <<"[{<<\"cake\">>,<<\"strawberry\">>},{<<\"color\">>,<<\"blue\">>}]">>
  240. = do_get_body("/parse_cookies",
  241. [{<<"cookie">>, "cake=strawberry"}, {<<"cookie">>, "color=blue"}], Config),
  242. %% Ensure parse errors result in a 400 response.
  243. {400, _, _} = do_get("/parse_cookies",
  244. [{<<"cookie">>, "bad name=strawberry"}], Config),
  245. {400, _, _} = do_get("/parse_cookies",
  246. [{<<"cookie">>, "goodname=strawberry\tmilkshake"}], Config),
  247. ok.
  248. parse_header(Config) ->
  249. doc("Parsed request header with/without default."),
  250. <<"[{{<<\"text\">>,<<\"html\">>,[]},1000,[]}]">>
  251. = do_get_body("/args/parse_header/accept", [{<<"accept">>, "text/html"}], Config),
  252. <<"[{{<<\"text\">>,<<\"html\">>,[]},1000,[]}]">>
  253. = do_get_body("/args/parse_header/accept/default", [{<<"accept">>, "text/html"}], Config),
  254. %% Header not in request but with default defined by Cowboy.
  255. <<"0">> = do_get_body("/args/parse_header/content-length", Config),
  256. %% Header not in request and no default from Cowboy.
  257. <<"undefined">> = do_get_body("/args/parse_header/upgrade", Config),
  258. %% Header in request and with default provided.
  259. <<"100-continue">> = do_get_body("/args/parse_header/expect/100-continue", Config),
  260. %% Ensure parse errors result in a 400 response.
  261. {400, _, _} = do_get("/args/parse_header/accept",
  262. [{<<"accept">>, "bad media type"}], Config),
  263. ok.
  264. parse_qs(Config) ->
  265. doc("Parsed request URI query string."),
  266. <<"[]">> = do_get_body("/parse_qs", Config),
  267. <<"[{<<\"abc\">>,true}]">> = do_get_body("/parse_qs?abc", Config),
  268. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">> = do_get_body("/parse_qs?a=b&c=d+e", Config),
  269. %% Ensure parse errors result in a 400 response.
  270. {400, _, _} = do_get("/parse_qs?%%%%%%%", Config),
  271. ok.
  272. path(Config) ->
  273. doc("Request URI path."),
  274. do_path("/path", Config),
  275. do_path("/direct/path", Config).
  276. do_path(Path0, Config) ->
  277. Path = list_to_binary(Path0 ++ "/to/the/resource"),
  278. Path = do_get_body(Path, Config),
  279. Path = do_get_body([Path, "?query"], Config),
  280. Path = do_get_body([Path, "?query#fragment"], Config),
  281. Path = do_get_body([Path, "#fragment"], Config),
  282. ok.
  283. path_info(Config) ->
  284. doc("Request path_info."),
  285. <<"undefined">> = do_get_body("/no/path_info", Config),
  286. <<"[]">> = do_get_body("/path_info", Config),
  287. <<"[]">> = do_get_body("/path_info/", Config),
  288. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource", Config),
  289. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource?query", Config),
  290. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource?query#fragment", Config),
  291. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource#fragment", Config),
  292. ok.
  293. peer(Config) ->
  294. doc("Remote socket address."),
  295. <<"{{127,0,0,1},", _/bits >> = do_get_body("/peer", Config),
  296. <<"{{127,0,0,1},", _/bits >> = do_get_body("/direct/peer", Config),
  297. ok.
  298. port(Config) ->
  299. doc("Request URI port."),
  300. Port = integer_to_binary(config(port, Config)),
  301. Port = do_get_body("/port", Config),
  302. Port = do_get_body("/direct/port", Config),
  303. ExpectedPort = case config(type, Config) of
  304. tcp -> <<"80">>;
  305. ssl -> <<"443">>
  306. end,
  307. ExpectedPort = do_get_body("/port", [{<<"host">>, <<"localhost">>}], Config),
  308. ExpectedPort = do_get_body("/direct/port", [{<<"host">>, <<"localhost">>}], Config),
  309. ok.
  310. qs(Config) ->
  311. doc("Request URI query string."),
  312. do_qs("/qs", Config),
  313. do_qs("/direct/qs", Config).
  314. do_qs(Path, Config) ->
  315. <<>> = do_get_body(Path, Config),
  316. <<"abc">> = do_get_body(Path ++ "?abc", Config),
  317. <<"a=b&c=d+e">> = do_get_body(Path ++ "?a=b&c=d+e", Config),
  318. ok.
  319. scheme(Config) ->
  320. doc("Request URI scheme."),
  321. do_scheme("/scheme", Config),
  322. do_scheme("/direct/scheme", Config).
  323. do_scheme(Path, Config) ->
  324. Transport = config(type, Config),
  325. case do_get_body(Path, Config) of
  326. <<"http">> when Transport =:= tcp -> ok;
  327. <<"https">> when Transport =:= ssl -> ok
  328. end.
  329. sock(Config) ->
  330. doc("Local socket address."),
  331. <<"{{127,0,0,1},", _/bits >> = do_get_body("/sock", Config),
  332. <<"{{127,0,0,1},", _/bits >> = do_get_body("/direct/sock", Config),
  333. ok.
  334. uri(Config) ->
  335. doc("Request URI building/modification."),
  336. Scheme = case config(type, Config) of
  337. tcp -> <<"http">>;
  338. ssl -> <<"https">>
  339. end,
  340. SLen = byte_size(Scheme),
  341. Port = integer_to_binary(config(port, Config)),
  342. PLen = byte_size(Port),
  343. %% Absolute form.
  344. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary, "/uri?qs" >>
  345. = do_get_body("/uri?qs", Config),
  346. %% Origin form.
  347. << "/uri/origin?qs" >> = do_get_body("/uri/origin?qs", Config),
  348. %% Protocol relative.
  349. << "//localhost:", Port:PLen/binary, "/uri/protocol-relative?qs" >>
  350. = do_get_body("/uri/protocol-relative?qs", Config),
  351. %% No query string.
  352. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary, "/uri/no-qs" >>
  353. = do_get_body("/uri/no-qs?qs", Config),
  354. %% No path or query string.
  355. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary >>
  356. = do_get_body("/uri/no-path?qs", Config),
  357. %% Changed port.
  358. << Scheme:SLen/binary, "://localhost:123/uri/set-port?qs" >>
  359. = do_get_body("/uri/set-port?qs", Config),
  360. %% This function is tested more extensively through unit tests.
  361. ok.
  362. version(Config) ->
  363. doc("Request HTTP version."),
  364. do_version("/version", Config),
  365. do_version("/direct/version", Config).
  366. do_version(Path, Config) ->
  367. Protocol = config(protocol, Config),
  368. case do_get_body(Path, Config) of
  369. <<"HTTP/1.1">> when Protocol =:= http -> ok;
  370. <<"HTTP/2">> when Protocol =:= http2 -> ok
  371. end.
  372. %% Tests: Request body.
  373. body_length(Config) ->
  374. doc("Request body length."),
  375. <<"0">> = do_get_body("/body_length", Config),
  376. <<"12">> = do_body("POST", "/body_length", [], "hello world!", Config),
  377. ok.
  378. has_body(Config) ->
  379. doc("Has a request body?"),
  380. <<"false">> = do_get_body("/has_body", Config),
  381. <<"true">> = do_body("POST", "/has_body", [], "hello world!", Config),
  382. ok.
  383. read_body(Config) ->
  384. doc("Request body."),
  385. <<>> = do_get_body("/read_body", Config),
  386. <<"hello world!">> = do_body("POST", "/read_body", [], "hello world!", Config),
  387. %% We expect to have read *at least* 1000 bytes.
  388. <<0:8000, _/bits>> = do_body("POST", "/opts/read_body/length", [], <<0:8000000>>, Config),
  389. %% The timeout value is set too low on purpose to ensure a crash occurs.
  390. ok = do_read_body_timeout("/opts/read_body/timeout", <<0:8000000>>, Config),
  391. %% 10MB body larger than default length.
  392. <<0:80000000>> = do_body("POST", "/full/read_body", [], <<0:80000000>>, Config),
  393. ok.
  394. read_body_mtu(Config) ->
  395. case os:type() of
  396. {win32, _} ->
  397. {skip, "Loopback MTU size is 0xFFFFFFFF on Windows."};
  398. {unix, _} ->
  399. doc("Request body whose sizes are around the MTU."),
  400. MTU = ct_helper:get_loopback_mtu(),
  401. _ = [begin
  402. Body = <<0:Size/unit:8>>,
  403. Body = do_body("POST", "/full/read_body", [], Body, Config)
  404. end || Size <- lists:seq(MTU - 10, MTU + 10)],
  405. ok
  406. end.
  407. read_body_period(Config) ->
  408. doc("Read the request body for at most 2 seconds."),
  409. ConnPid = gun_open(Config),
  410. Body = <<0:8000000>>,
  411. Ref = gun:headers(ConnPid, "POST", "/opts/read_body/period", [
  412. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  413. ]),
  414. %% The body is sent twice, first with nofin, then wait 3 seconds, then again with fin.
  415. gun:data(ConnPid, Ref, nofin, Body),
  416. timer:sleep(3000),
  417. gun:data(ConnPid, Ref, fin, Body),
  418. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  419. {ok, Body} = gun:await_body(ConnPid, Ref),
  420. gun:close(ConnPid).
  421. %% We expect a crash.
  422. do_read_body_timeout(Path, Body, Config) ->
  423. ConnPid = gun_open(Config),
  424. Ref = gun:headers(ConnPid, "POST", Path, [
  425. {<<"content-length">>, integer_to_binary(byte_size(Body))}
  426. ]),
  427. {response, _, 500, _} = gun:await(ConnPid, Ref),
  428. gun:close(ConnPid).
  429. read_body_spawn(Config) ->
  430. doc("Confirm we can use cowboy_req:read_body/1,2 from another process."),
  431. <<"hello world!">> = do_body("POST", "/spawn/read_body", [], "hello world!", Config),
  432. ok.
  433. read_body_expect_100_continue(Config) ->
  434. doc("Request body with a 100-continue expect header."),
  435. do_read_body_expect_100_continue("/read_body", Config).
  436. read_body_expect_100_continue_user_sent(Config) ->
  437. doc("Request body with a 100-continue expect header, 100 response sent by handler."),
  438. do_read_body_expect_100_continue("/100-continue/read_body", Config).
  439. do_read_body_expect_100_continue(Path, Config) ->
  440. ConnPid = gun_open(Config),
  441. Body = <<0:8000000>>,
  442. Headers = [
  443. {<<"accept-encoding">>, <<"gzip">>},
  444. {<<"expect">>, <<"100-continue">>},
  445. {<<"content-length">>, integer_to_binary(byte_size(Body))}
  446. ],
  447. Ref = gun:post(ConnPid, Path, Headers),
  448. {inform, 100, []} = gun:await(ConnPid, Ref),
  449. gun:data(ConnPid, Ref, fin, Body),
  450. {response, IsFin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  451. {ok, RespBody} = case IsFin of
  452. nofin -> gun:await_body(ConnPid, Ref);
  453. fin -> {ok, <<>>}
  454. end,
  455. gun:close(ConnPid),
  456. do_decode(RespHeaders, RespBody).
  457. read_urlencoded_body(Config) ->
  458. doc("application/x-www-form-urlencoded request body."),
  459. <<"[]">> = do_body("POST", "/read_urlencoded_body", [], <<>>, Config),
  460. <<"[{<<\"abc\">>,true}]">> = do_body("POST", "/read_urlencoded_body", [], "abc", Config),
  461. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">>
  462. = do_body("POST", "/read_urlencoded_body", [], "a=b&c=d+e", Config),
  463. %% The timeout value is set too low on purpose to ensure a crash occurs.
  464. ok = do_read_body_timeout("/opts/read_urlencoded_body/timeout", <<"abc">>, Config),
  465. %% Ensure parse errors result in a 400 response.
  466. {400, _} = do_body_error("POST", "/read_urlencoded_body", [], "%%%%%", Config),
  467. ok.
  468. read_urlencoded_body_too_large(Config) ->
  469. doc("application/x-www-form-urlencoded request body too large. "
  470. "Send a 10MB body, larger than the default length, to ensure a crash occurs."),
  471. do_read_urlencoded_body_too_large("/no-opts/read_urlencoded_body",
  472. string:chars($a, 10000000), Config).
  473. %% We expect a crash.
  474. do_read_urlencoded_body_too_large(Path, Body, Config) ->
  475. ConnPid = gun_open(Config),
  476. Ref = gun:headers(ConnPid, "POST", Path, [
  477. {<<"content-length">>, integer_to_binary(iolist_size(Body))}
  478. ]),
  479. gun:data(ConnPid, Ref, fin, Body),
  480. {response, _, 413, _} = gun:await(ConnPid, Ref),
  481. gun:close(ConnPid).
  482. read_urlencoded_body_too_long(Config) ->
  483. doc("application/x-www-form-urlencoded request body sent too slow. "
  484. "The body is sent twice with 2s wait in-between. It is read by the handler "
  485. "for at most 1 second. A crash occurs because we don't have the full body."),
  486. do_read_urlencoded_body_too_long("/crash/read_urlencoded_body/period", <<"abc">>, Config).
  487. %% We expect a crash.
  488. do_read_urlencoded_body_too_long(Path, Body, Config) ->
  489. ConnPid = gun_open(Config),
  490. Ref = gun:headers(ConnPid, "POST", Path, [
  491. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  492. ]),
  493. gun:data(ConnPid, Ref, nofin, Body),
  494. timer:sleep(2000),
  495. gun:data(ConnPid, Ref, fin, Body),
  496. {response, _, 408, RespHeaders} = gun:await(ConnPid, Ref),
  497. _ = case config(protocol, Config) of
  498. http ->
  499. %% 408 error responses should close HTTP/1.1 connections.
  500. {_, <<"close">>} = lists:keyfind(<<"connection">>, 1, RespHeaders);
  501. http2 ->
  502. ok
  503. end,
  504. gun:close(ConnPid).
  505. read_and_match_urlencoded_body(Config) ->
  506. doc("Read and match an application/x-www-form-urlencoded request body."),
  507. <<"#{}">> = do_body("POST", "/match/body_qs", [], "a=b&c=d", Config),
  508. <<"#{a => <<\"b\">>}">> = do_body("POST", "/match/body_qs/a", [], "a=b&c=d", Config),
  509. <<"#{c => <<\"d\">>}">> = do_body("POST", "/match/body_qs/c", [], "a=b&c=d", Config),
  510. <<"#{a => <<\"b\">>,c => <<\"d\">>}">>
  511. = do_body("POST", "/match/body_qs/a/c", [], "a=b&c=d", Config),
  512. <<"#{a => <<\"b\">>,c => true}">> = do_body("POST", "/match/body_qs/a/c", [], "a=b&c", Config),
  513. <<"#{a => true,c => <<\"d\">>}">> = do_body("POST", "/match/body_qs/a/c", [], "a&c=d", Config),
  514. %% Ensure match errors result in a 400 response.
  515. {400, _} = do_body_error("POST", "/match/body_qs/a/c", [], "a=b", Config),
  516. %% Ensure parse errors result in a 400 response.
  517. {400, _} = do_body_error("POST", "/match/body_qs", [], "%%%%%", Config),
  518. %% The timeout value is set too low on purpose to ensure a crash occurs.
  519. ok = do_read_body_timeout("/opts/read_and_match_urlencoded_body/timeout", <<"abc">>, Config),
  520. ok.
  521. read_and_match_urlencoded_body_too_large(Config) ->
  522. doc("Read and match an application/x-www-form-urlencoded request body too large. "
  523. "Send a 10MB body, larger than the default length, to ensure a crash occurs."),
  524. do_read_urlencoded_body_too_large(
  525. "/no-opts/read_and_match_urlencoded_body",
  526. string:chars($a, 10000000), Config).
  527. read_and_match_urlencoded_body_too_long(Config) ->
  528. doc("Read and match an application/x-www-form-urlencoded request body sent too slow. "
  529. "The body is sent twice with 2s wait in-between. It is read by the handler "
  530. "for at most 1 second. A crash occurs because we don't have the full body."),
  531. do_read_urlencoded_body_too_long(
  532. "/crash/read_and_match_urlencoded_body/period", <<"abc">>, Config).
  533. multipart(Config) ->
  534. doc("Multipart request body."),
  535. do_multipart("/multipart", Config).
  536. do_multipart(Path, Config) ->
  537. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  538. ReqBody = [
  539. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  540. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  541. "--deadbeef--"
  542. ],
  543. RespBody = do_body("POST", Path, [
  544. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  545. ], ReqBody, Config),
  546. [
  547. {#{<<"content-type">> := <<"text/plain">>}, <<"Cowboy is an HTTP server.">>},
  548. {LargeHeaders, LargeBody}
  549. ] = binary_to_term(RespBody),
  550. #{
  551. <<"content-type">> := <<"application/octet-stream">>,
  552. <<"x-custom">> := <<"value">>
  553. } = LargeHeaders,
  554. ok.
  555. multipart_error_empty(Config) ->
  556. doc("Multipart request body is empty."),
  557. %% We use an empty list as a body to make sure Gun knows
  558. %% we want to send an empty body.
  559. %% @todo This is a terrible hack. Improve Gun!
  560. Body = [],
  561. %% Ensure an empty body results in a 400 error.
  562. {400, _} = do_body_error("POST", "/multipart", [
  563. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  564. ], Body, Config),
  565. ok.
  566. multipart_error_preamble_only(Config) ->
  567. doc("Multipart request body only contains a preamble."),
  568. %% Ensure an empty body results in a 400 error.
  569. {400, _} = do_body_error("POST", "/multipart", [
  570. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  571. ], <<"Preamble.">>, Config),
  572. ok.
  573. multipart_error_headers(Config) ->
  574. doc("Multipart request body with invalid part headers."),
  575. ReqBody = [
  576. "--deadbeef\r\nbad-header text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  577. "--deadbeef--"
  578. ],
  579. %% Ensure parse errors result in a 400 response.
  580. {400, _} = do_body_error("POST", "/multipart", [
  581. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  582. ], ReqBody, Config),
  583. ok.
  584. %% The function to parse the multipart body currently does not crash,
  585. %% as far as I can tell. There is therefore no test for it.
  586. multipart_error_no_final_boundary(Config) ->
  587. doc("Multipart request body with no final boundary."),
  588. ReqBody = [
  589. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  590. ],
  591. %% Ensure parse errors result in a 400 response.
  592. {400, _} = do_body_error("POST", "/multipart", [
  593. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  594. ], ReqBody, Config),
  595. ok.
  596. multipart_missing_boundary(Config) ->
  597. doc("Multipart request body without a boundary in the media type."),
  598. ReqBody = [
  599. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  600. "--deadbeef--"
  601. ],
  602. %% Ensure parse errors result in a 400 response.
  603. {400, _} = do_body_error("POST", "/multipart", [
  604. {<<"content-type">>, <<"multipart/mixed">>}
  605. ], ReqBody, Config),
  606. ok.
  607. read_part_skip_body(Config) ->
  608. doc("Multipart request body skipping part bodies."),
  609. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  610. ReqBody = [
  611. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  612. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  613. "--deadbeef--"
  614. ],
  615. RespBody = do_body("POST", "/multipart/skip_body", [
  616. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  617. ], ReqBody, Config),
  618. [
  619. #{<<"content-type">> := <<"text/plain">>},
  620. LargeHeaders
  621. ] = binary_to_term(RespBody),
  622. #{
  623. <<"content-type">> := <<"application/octet-stream">>,
  624. <<"x-custom">> := <<"value">>
  625. } = LargeHeaders,
  626. ok.
  627. %% @todo When reading a multipart body, length and period
  628. %% only apply to a single read_body call. We may want a
  629. %% separate option to know how many reads we want to do
  630. %% before we give up.
  631. read_part2(Config) ->
  632. doc("Multipart request body using read_part/2."),
  633. %% Override the length and period values only, making
  634. %% the request process use more read_body calls.
  635. %%
  636. %% We do not try a custom timeout value since this would
  637. %% be the same test as read_body/2.
  638. do_multipart("/multipart/read_part2", Config).
  639. read_part_body2(Config) ->
  640. doc("Multipart request body using read_part_body/2."),
  641. %% Override the length and period values only, making
  642. %% the request process use more read_body calls.
  643. %%
  644. %% We do not try a custom timeout value since this would
  645. %% be the same test as read_body/2.
  646. do_multipart("/multipart/read_part_body2", Config).
  647. %% Tests: Response.
  648. %% @todo We want to crash when calling set_resp_* or related
  649. %% functions after the reply has been sent.
  650. set_resp_cookie(Config) ->
  651. doc("Response using set_resp_cookie."),
  652. %% Single cookie, no options.
  653. {200, Headers1, _} = do_get("/resp/set_resp_cookie3", Config),
  654. {_, <<"mycookie=myvalue; Version=1">>}
  655. = lists:keyfind(<<"set-cookie">>, 1, Headers1),
  656. %% Single cookie, with options.
  657. {200, Headers2, _} = do_get("/resp/set_resp_cookie4", Config),
  658. {_, <<"mycookie=myvalue; Version=1; Path=/resp/set_resp_cookie4">>}
  659. = lists:keyfind(<<"set-cookie">>, 1, Headers2),
  660. %% Multiple cookies.
  661. {200, Headers3, _} = do_get("/resp/set_resp_cookie3/multiple", Config),
  662. [_, _] = [H || H={<<"set-cookie">>, _} <- Headers3],
  663. %% Overwrite previously set cookie.
  664. {200, Headers4, _} = do_get("/resp/set_resp_cookie3/overwrite", Config),
  665. {_, <<"mycookie=overwrite; Version=1">>}
  666. = lists:keyfind(<<"set-cookie">>, 1, Headers4),
  667. ok.
  668. set_resp_header(Config) ->
  669. doc("Response using set_resp_header."),
  670. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_header", Config),
  671. true = lists:keymember(<<"content-type">>, 1, Headers),
  672. ok.
  673. set_resp_headers(Config) ->
  674. doc("Response using set_resp_headers."),
  675. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_headers", Config),
  676. true = lists:keymember(<<"content-type">>, 1, Headers),
  677. true = lists:keymember(<<"content-encoding">>, 1, Headers),
  678. ok.
  679. resp_header(Config) ->
  680. doc("Response header with/without default."),
  681. {200, _, <<"OK">>} = do_get("/resp/resp_header_defined", Config),
  682. {200, _, <<"OK">>} = do_get("/resp/resp_header_default", Config),
  683. ok.
  684. resp_headers(Config) ->
  685. doc("Get all response headers."),
  686. {200, _, <<"OK">>} = do_get("/resp/resp_headers", Config),
  687. {200, _, <<"OK">>} = do_get("/resp/resp_headers_empty", Config),
  688. ok.
  689. set_resp_body(Config) ->
  690. doc("Response using set_resp_body."),
  691. {200, _, <<"OK">>} = do_get("/resp/set_resp_body", Config),
  692. {200, _, <<"OVERRIDE">>} = do_get("/resp/set_resp_body/override", Config),
  693. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  694. {200, _, AppFile} = do_get("/resp/set_resp_body/sendfile", Config),
  695. ok.
  696. set_resp_body_sendfile0(Config) ->
  697. doc("Response using set_resp_body with a sendfile of length 0."),
  698. Path = "/resp/set_resp_body/sendfile0",
  699. ConnPid = gun_open(Config),
  700. %% First request.
  701. Ref1 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  702. {response, IsFin, 200, _} = gun:await(ConnPid, Ref1),
  703. {ok, <<>>} = case IsFin of
  704. nofin -> gun:await_body(ConnPid, Ref1);
  705. fin -> {ok, <<>>}
  706. end,
  707. %% Second request will confirm everything works as intended.
  708. Ref2 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  709. {response, IsFin, 200, _} = gun:await(ConnPid, Ref2),
  710. {ok, <<>>} = case IsFin of
  711. nofin -> gun:await_body(ConnPid, Ref2);
  712. fin -> {ok, <<>>}
  713. end,
  714. gun:close(ConnPid),
  715. ok.
  716. has_resp_header(Config) ->
  717. doc("Has response header?"),
  718. {200, Headers, <<"OK">>} = do_get("/resp/has_resp_header", Config),
  719. true = lists:keymember(<<"content-type">>, 1, Headers),
  720. ok.
  721. has_resp_body(Config) ->
  722. doc("Has response body?"),
  723. {200, _, <<"OK">>} = do_get("/resp/has_resp_body", Config),
  724. {200, _, <<"OK">>} = do_get("/resp/has_resp_body/sendfile", Config),
  725. ok.
  726. delete_resp_header(Config) ->
  727. doc("Delete response header."),
  728. {200, Headers, <<"OK">>} = do_get("/resp/delete_resp_header", Config),
  729. false = lists:keymember(<<"content-type">>, 1, Headers),
  730. ok.
  731. inform2(Config) ->
  732. doc("Informational response(s) without headers, followed by the real response."),
  733. {102, [], 200, _, _} = do_get_inform("/resp/inform2/102", Config),
  734. {102, [], 200, _, _} = do_get_inform("/resp/inform2/binary", Config),
  735. {500, _} = do_get_inform("/resp/inform2/error", Config),
  736. {102, [], 200, _, _} = do_get_inform("/resp/inform2/twice", Config),
  737. ok.
  738. inform3(Config) ->
  739. doc("Informational response(s) with headers, followed by the real response."),
  740. Headers = [{<<"ext-header">>, <<"ext-value">>}],
  741. {102, Headers, 200, _, _} = do_get_inform("/resp/inform3/102", Config),
  742. {102, Headers, 200, _, _} = do_get_inform("/resp/inform3/binary", Config),
  743. {500, _} = do_get_inform("/resp/inform3/error", Config),
  744. {102, Headers, 200, _, _} = do_get_inform("/resp/inform3/twice", Config),
  745. ok.
  746. reply2(Config) ->
  747. doc("Response with default headers and no body."),
  748. {200, _, _} = do_get("/resp/reply2/200", Config),
  749. {201, _, _} = do_get("/resp/reply2/201", Config),
  750. {404, _, _} = do_get("/resp/reply2/404", Config),
  751. {200, _, _} = do_get("/resp/reply2/binary", Config),
  752. {500, _, _} = do_get("/resp/reply2/error", Config),
  753. %% @todo We want to crash when reply or stream_reply is called twice.
  754. %% How to test this properly? This isn't enough.
  755. {200, _, _} = do_get("/resp/reply2/twice", Config),
  756. ok.
  757. reply3(Config) ->
  758. doc("Response with additional headers and no body."),
  759. {200, Headers1, _} = do_get("/resp/reply3/200", Config),
  760. true = lists:keymember(<<"content-type">>, 1, Headers1),
  761. {201, Headers2, _} = do_get("/resp/reply3/201", Config),
  762. true = lists:keymember(<<"content-type">>, 1, Headers2),
  763. {404, Headers3, _} = do_get("/resp/reply3/404", Config),
  764. true = lists:keymember(<<"content-type">>, 1, Headers3),
  765. {500, _, _} = do_get("/resp/reply3/error", Config),
  766. ok.
  767. reply4(Config) ->
  768. doc("Response with additional headers and body."),
  769. {200, _, <<"OK">>} = do_get("/resp/reply4/200", Config),
  770. {201, _, <<"OK">>} = do_get("/resp/reply4/201", Config),
  771. {404, _, <<"OK">>} = do_get("/resp/reply4/404", Config),
  772. {500, _, _} = do_get("/resp/reply4/error", Config),
  773. ok.
  774. %% @todo Crash when stream_reply is called twice.
  775. stream_reply2(Config) ->
  776. doc("Response with default headers and streamed body."),
  777. Body = <<0:8000000>>,
  778. {200, _, Body} = do_get("/resp/stream_reply2/200", Config),
  779. {201, _, Body} = do_get("/resp/stream_reply2/201", Config),
  780. {404, _, Body} = do_get("/resp/stream_reply2/404", Config),
  781. {200, _, Body} = do_get("/resp/stream_reply2/binary", Config),
  782. {500, _, _} = do_get("/resp/stream_reply2/error", Config),
  783. ok.
  784. stream_reply3(Config) ->
  785. doc("Response with additional headers and streamed body."),
  786. Body = <<0:8000000>>,
  787. {200, Headers1, Body} = do_get("/resp/stream_reply3/200", Config),
  788. true = lists:keymember(<<"content-type">>, 1, Headers1),
  789. {201, Headers2, Body} = do_get("/resp/stream_reply3/201", Config),
  790. true = lists:keymember(<<"content-type">>, 1, Headers2),
  791. {404, Headers3, Body} = do_get("/resp/stream_reply3/404", Config),
  792. true = lists:keymember(<<"content-type">>, 1, Headers3),
  793. {500, _, _} = do_get("/resp/stream_reply3/error", Config),
  794. ok.
  795. stream_body_fin0(Config) ->
  796. doc("Streamed body with last chunk of size 0."),
  797. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/fin0", Config),
  798. ok.
  799. stream_body_multiple(Config) ->
  800. doc("Streamed body via multiple calls."),
  801. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/multiple", Config),
  802. ok.
  803. stream_body_loop(Config) ->
  804. doc("Streamed body via a fast loop."),
  805. {200, _, <<0:32000000/unit:8>>} = do_get("/resp/stream_body/loop", Config),
  806. ok.
  807. stream_body_nofin(Config) ->
  808. doc("Unfinished streamed body."),
  809. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/nofin", Config),
  810. ok.
  811. stream_body_sendfile(Config) ->
  812. doc("Streamed body via multiple calls, including sendfile calls."),
  813. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  814. ExpectedBody = iolist_to_binary([
  815. <<"Hello ">>,
  816. AppFile,
  817. <<" interspersed ">>,
  818. AppFile,
  819. <<" world!">>
  820. ]),
  821. {200, _, ExpectedBody} = do_get("/resp/stream_body/sendfile", Config),
  822. ok.
  823. stream_body_sendfile_fin(Config) ->
  824. doc("Streamed body via multiple calls, including a sendfile final call."),
  825. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  826. ExpectedBody = iolist_to_binary([
  827. <<"Hello! ">>,
  828. AppFile
  829. ]),
  830. {200, _, ExpectedBody} = do_get("/resp/stream_body/sendfile_fin", Config),
  831. ok.
  832. stream_body_spawn(Config) ->
  833. doc("Confirm we can use cowboy_req:stream_body/3 from another process."),
  834. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/spawn", Config),
  835. ok.
  836. stream_body_content_length_multiple(Config) ->
  837. doc("Streamed body via multiple calls."),
  838. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/multiple", Config),
  839. ok.
  840. stream_body_content_length_fin0(Config) ->
  841. doc("Streamed body with last chunk of size 0."),
  842. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/fin0", Config),
  843. ok.
  844. stream_body_content_length_nofin(Config) ->
  845. doc("Unfinished streamed body."),
  846. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/nofin", Config),
  847. ok.
  848. stream_body_content_length_nofin_error(Config) ->
  849. doc("Not all of the response body sent."),
  850. case config(protocol, Config) of
  851. http ->
  852. case do_get_error("/resp/stream_body_content_length/nofin-error", Config) of
  853. %% When compression is used content-length is not sent.
  854. {200, Headers, <<"Hello">>} ->
  855. {_, <<"gzip">>} = lists:keyfind(<<"content-encoding">>, 1, Headers);
  856. %% The server closes the connection when the body couldn't be sent fully.
  857. {error, {stream_error, closed}} ->
  858. receive
  859. {gun_down, ConnPid, _, _, _} ->
  860. gun:close(ConnPid)
  861. after 1000 ->
  862. error(timeout)
  863. end
  864. end;
  865. http2 ->
  866. %% @todo HTTP2 should have the same content-length checks
  867. ok
  868. end.
  869. %% @todo Crash when calling stream_body after the fin flag has been set.
  870. %% @todo Crash when calling stream_body after calling reply.
  871. %% @todo Crash when calling stream_body before calling stream_reply.
  872. stream_events_single(Config) ->
  873. doc("Streamed event."),
  874. {200, Headers, <<
  875. "event: add_comment\n"
  876. "data: Comment text.\n"
  877. "data: With many lines.\n"
  878. "\n"
  879. >>} = do_get("/resp/stream_events/single", Config),
  880. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  881. ok.
  882. stream_events_list(Config) ->
  883. doc("Streamed list of events."),
  884. {200, Headers, <<
  885. "event: add_comment\n"
  886. "data: Comment text.\n"
  887. "data: With many lines.\n"
  888. "\n"
  889. ": Set retry higher\n"
  890. ": with many lines also.\n"
  891. "retry: 10000\n"
  892. "\n"
  893. "id: 123\n"
  894. "event: add_comment\n"
  895. "data: Closing!\n"
  896. "\n"
  897. >>} = do_get("/resp/stream_events/list", Config),
  898. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  899. ok.
  900. stream_events_multiple(Config) ->
  901. doc("Streamed events via multiple calls."),
  902. {200, Headers, <<
  903. "event: add_comment\n"
  904. "data: Comment text.\n"
  905. "data: With many lines.\n"
  906. "\n"
  907. ": Set retry higher\n"
  908. ": with many lines also.\n"
  909. "retry: 10000\n"
  910. "\n"
  911. "id: 123\n"
  912. "event: add_comment\n"
  913. "data: Closing!\n"
  914. "\n"
  915. >>} = do_get("/resp/stream_events/multiple", Config),
  916. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  917. ok.
  918. stream_trailers(Config) ->
  919. doc("Stream body followed by trailer headers."),
  920. {200, RespHeaders, <<"Hello world!">>, [
  921. {<<"grpc-status">>, <<"0">>}
  922. ]} = do_trailers("/resp/stream_trailers", Config),
  923. {_, <<"grpc-status">>} = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  924. ok.
  925. stream_trailers_large(Config) ->
  926. doc("Stream large body followed by trailer headers."),
  927. {200, RespHeaders, <<0:800000>>, [
  928. {<<"grpc-status">>, <<"0">>}
  929. ]} = do_trailers("/resp/stream_trailers/large", Config),
  930. {_, <<"grpc-status">>} = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  931. ok.
  932. stream_trailers_no_te(Config) ->
  933. doc("Stream body followed by trailer headers without a te header in the request."),
  934. ConnPid = gun_open(Config),
  935. Ref = gun:get(ConnPid, "/resp/stream_trailers", [
  936. {<<"accept-encoding">>, <<"gzip">>}
  937. ]),
  938. {response, nofin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  939. %% @todo Do we want to remove the trailer header automatically?
  940. % false = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  941. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  942. <<"Hello world!">> = do_decode(RespHeaders, RespBody),
  943. gun:close(ConnPid).
  944. do_trailers(Path, Config) ->
  945. ConnPid = gun_open(Config),
  946. Ref = gun:get(ConnPid, Path, [
  947. {<<"accept-encoding">>, <<"gzip">>},
  948. {<<"te">>, <<"trailers">>}
  949. ]),
  950. {response, nofin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  951. {ok, RespBody, Trailers} = gun:await_body(ConnPid, Ref),
  952. gun:close(ConnPid),
  953. {Status, RespHeaders, do_decode(RespHeaders, RespBody), Trailers}.
  954. %% @todo Crash when calling stream_trailers twice.
  955. %% @todo Crash when calling stream_trailers after the fin flag has been set.
  956. %% @todo Crash when calling stream_trailers after calling reply.
  957. %% @todo Crash when calling stream_trailers before calling stream_reply.
  958. %% Tests: Push.
  959. %% @todo We want to crash when push is called after reply has been initiated.
  960. push(Config) ->
  961. case config(protocol, Config) of
  962. http -> do_push_http("/resp/push", Config);
  963. http2 -> do_push_http2(Config)
  964. end.
  965. push_method(Config) ->
  966. case config(protocol, Config) of
  967. http -> do_push_http("/resp/push/method", Config);
  968. http2 -> do_push_http2_method(Config)
  969. end.
  970. push_origin(Config) ->
  971. case config(protocol, Config) of
  972. http -> do_push_http("/resp/push/origin", Config);
  973. http2 -> do_push_http2_origin(Config)
  974. end.
  975. push_qs(Config) ->
  976. case config(protocol, Config) of
  977. http -> do_push_http("/resp/push/qs", Config);
  978. http2 -> do_push_http2_qs(Config)
  979. end.
  980. do_push_http(Path, Config) ->
  981. doc("Ignore pushed responses when protocol is HTTP/1.1."),
  982. ConnPid = gun_open(Config),
  983. Ref = gun:get(ConnPid, Path, []),
  984. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  985. ok.
  986. do_push_http2(Config) ->
  987. doc("Pushed responses."),
  988. ConnPid = gun_open(Config),
  989. Ref = gun:get(ConnPid, "/resp/push", []),
  990. %% We expect two pushed resources.
  991. Origin = iolist_to_binary([
  992. case config(type, Config) of
  993. tcp -> "http";
  994. ssl -> "https"
  995. end,
  996. "://localhost:",
  997. integer_to_binary(config(port, Config))
  998. ]),
  999. OriginLen = byte_size(Origin),
  1000. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css">>,
  1001. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  1002. {push, PushTXT, <<"GET">>, <<Origin:OriginLen/binary, "/static/plain.txt">>,
  1003. [{<<"accept">>,<<"text/plain">>}]} = gun:await(ConnPid, Ref),
  1004. %% Pushed CSS.
  1005. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  1006. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  1007. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  1008. %% Pushed TXT is 406 because the pushed accept header uses an undefined type.
  1009. {response, fin, 406, _} = gun:await(ConnPid, PushTXT),
  1010. %% Let's not forget about the response to the client's request.
  1011. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1012. gun:close(ConnPid).
  1013. do_push_http2_method(Config) ->
  1014. doc("Pushed response with non-GET method."),
  1015. ConnPid = gun_open(Config),
  1016. Ref = gun:get(ConnPid, "/resp/push/method", []),
  1017. %% Pushed CSS.
  1018. {push, PushCSS, <<"HEAD">>, _, [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  1019. {response, fin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  1020. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  1021. %% Let's not forget about the response to the client's request.
  1022. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1023. gun:close(ConnPid).
  1024. do_push_http2_origin(Config) ->
  1025. doc("Pushed response with custom scheme/host/port."),
  1026. ConnPid = gun_open(Config),
  1027. Ref = gun:get(ConnPid, "/resp/push/origin", []),
  1028. %% Pushed CSS.
  1029. {push, PushCSS, <<"GET">>, <<"ftp://127.0.0.1:21/static/style.css">>,
  1030. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  1031. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  1032. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  1033. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  1034. %% Let's not forget about the response to the client's request.
  1035. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1036. gun:close(ConnPid).
  1037. do_push_http2_qs(Config) ->
  1038. doc("Pushed response with query string."),
  1039. ConnPid = gun_open(Config),
  1040. Ref = gun:get(ConnPid, "/resp/push/qs", []),
  1041. %% Pushed CSS.
  1042. Origin = iolist_to_binary([
  1043. case config(type, Config) of
  1044. tcp -> "http";
  1045. ssl -> "https"
  1046. end,
  1047. "://localhost:",
  1048. integer_to_binary(config(port, Config))
  1049. ]),
  1050. OriginLen = byte_size(Origin),
  1051. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css?server=cowboy&version=2.0">>,
  1052. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  1053. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  1054. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  1055. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  1056. %% Let's not forget about the response to the client's request.
  1057. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1058. gun:close(ConnPid).