req_SUITE.erl 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 => 1000}},
  46. {"/opts/:key/timeout", echo_h, #{timeout => 1000, crash => true}},
  47. {"/100-continue/:key", echo_h, []},
  48. {"/full/:key", echo_h, []},
  49. {"/no/:key", echo_h, []},
  50. {"/direct/:key/[...]", echo_h, []},
  51. {"/:key/[...]", echo_h, []}
  52. ]}]).
  53. %% Internal.
  54. do_body(Method, Path, Config) ->
  55. do_body(Method, Path, [], Config).
  56. do_body(Method, Path, Headers, Config) ->
  57. do_body(Method, Path, Headers, <<>>, Config).
  58. do_body(Method, Path, Headers0, Body, Config) ->
  59. ConnPid = gun_open(Config),
  60. Headers = [{<<"accept-encoding">>, <<"gzip">>}|Headers0],
  61. Ref = gun:request(ConnPid, Method, Path, Headers, Body),
  62. {response, IsFin, 200, RespHeaders} = gun:await(ConnPid, Ref, 10000),
  63. {ok, RespBody} = case IsFin of
  64. nofin -> gun:await_body(ConnPid, Ref);
  65. fin -> {ok, <<>>}
  66. end,
  67. gun:close(ConnPid),
  68. do_decode(RespHeaders, RespBody).
  69. do_body_error(Method, Path, Headers0, Body, Config) ->
  70. ConnPid = gun_open(Config),
  71. Headers = [{<<"accept-encoding">>, <<"gzip">>}|Headers0],
  72. Ref = gun:request(ConnPid, Method, Path, Headers, Body),
  73. {response, _, Status, RespHeaders} = gun:await(ConnPid, Ref),
  74. gun:close(ConnPid),
  75. {Status, RespHeaders}.
  76. do_get(Path, Config) ->
  77. do_get(Path, [], Config).
  78. do_get(Path, Headers, Config) ->
  79. ConnPid = gun_open(Config),
  80. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}|Headers]),
  81. {response, IsFin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  82. {ok, RespBody} = case IsFin of
  83. nofin -> gun:await_body(ConnPid, Ref);
  84. fin -> {ok, <<>>}
  85. end,
  86. gun:close(ConnPid),
  87. {Status, RespHeaders, do_decode(RespHeaders, RespBody)}.
  88. do_get_body(Path, Config) ->
  89. do_get_body(Path, [], Config).
  90. do_get_body(Path, Headers, Config) ->
  91. do_body("GET", Path, Headers, Config).
  92. do_get_inform(Path, Config) ->
  93. ConnPid = gun_open(Config),
  94. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  95. case gun:await(ConnPid, Ref) of
  96. {response, _, RespStatus, RespHeaders} ->
  97. %% We don't care about the body.
  98. gun:close(ConnPid),
  99. {RespStatus, RespHeaders};
  100. {inform, InfoStatus, InfoHeaders} ->
  101. {response, IsFin, RespStatus, RespHeaders}
  102. = case gun:await(ConnPid, Ref) of
  103. {inform, InfoStatus, InfoHeaders} ->
  104. gun:await(ConnPid, Ref);
  105. Response ->
  106. Response
  107. end,
  108. {ok, RespBody} = case IsFin of
  109. nofin -> gun:await_body(ConnPid, Ref);
  110. fin -> {ok, <<>>}
  111. end,
  112. gun:close(ConnPid),
  113. {InfoStatus, InfoHeaders, RespStatus, RespHeaders, do_decode(RespHeaders, RespBody)}
  114. end.
  115. do_decode(Headers, Body) ->
  116. case lists:keyfind(<<"content-encoding">>, 1, Headers) of
  117. {_, <<"gzip">>} -> zlib:gunzip(Body);
  118. _ -> Body
  119. end.
  120. do_get_error(Path, Config) ->
  121. do_get_error(Path, [], Config).
  122. do_get_error(Path, Headers, Config) ->
  123. ConnPid = gun_open(Config),
  124. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}|Headers]),
  125. {response, IsFin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  126. Result = case IsFin of
  127. nofin -> gun:await_body(ConnPid, Ref);
  128. fin -> {ok, <<>>}
  129. end,
  130. gun:close(ConnPid),
  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. doc("Request body whose sizes are around the MTU."),
  396. MTU = ct_helper:get_loopback_mtu(),
  397. _ = [begin
  398. Body = <<0:Size/unit:8>>,
  399. Body = do_body("POST", "/full/read_body", [], Body, Config)
  400. end || Size <- lists:seq(MTU - 10, MTU + 10)],
  401. ok.
  402. read_body_period(Config) ->
  403. doc("Read the request body for at most 1 second."),
  404. ConnPid = gun_open(Config),
  405. Body = <<0:8000000>>,
  406. Ref = gun:headers(ConnPid, "POST", "/opts/read_body/period", [
  407. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  408. ]),
  409. %% The body is sent twice, first with nofin, then wait 2 seconds, then again with fin.
  410. gun:data(ConnPid, Ref, nofin, Body),
  411. timer:sleep(2000),
  412. gun:data(ConnPid, Ref, fin, Body),
  413. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  414. {ok, Body} = gun:await_body(ConnPid, Ref),
  415. gun:close(ConnPid).
  416. %% We expect a crash.
  417. do_read_body_timeout(Path, Body, Config) ->
  418. ConnPid = gun_open(Config),
  419. Ref = gun:headers(ConnPid, "POST", Path, [
  420. {<<"content-length">>, integer_to_binary(byte_size(Body))}
  421. ]),
  422. {response, _, 500, _} = gun:await(ConnPid, Ref),
  423. gun:close(ConnPid).
  424. read_body_expect_100_continue(Config) ->
  425. doc("Request body with a 100-continue expect header."),
  426. do_read_body_expect_100_continue("/read_body", Config).
  427. read_body_expect_100_continue_user_sent(Config) ->
  428. doc("Request body with a 100-continue expect header, 100 response sent by handler."),
  429. do_read_body_expect_100_continue("/100-continue/read_body", Config).
  430. do_read_body_expect_100_continue(Path, Config) ->
  431. ConnPid = gun_open(Config),
  432. Body = <<0:8000000>>,
  433. Headers = [
  434. {<<"accept-encoding">>, <<"gzip">>},
  435. {<<"expect">>, <<"100-continue">>},
  436. {<<"content-length">>, integer_to_binary(byte_size(Body))}
  437. ],
  438. Ref = gun:post(ConnPid, Path, Headers),
  439. {inform, 100, []} = gun:await(ConnPid, Ref),
  440. gun:data(ConnPid, Ref, fin, Body),
  441. {response, IsFin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  442. {ok, RespBody} = case IsFin of
  443. nofin -> gun:await_body(ConnPid, Ref);
  444. fin -> {ok, <<>>}
  445. end,
  446. gun:close(ConnPid),
  447. do_decode(RespHeaders, RespBody).
  448. read_urlencoded_body(Config) ->
  449. doc("application/x-www-form-urlencoded request body."),
  450. <<"[]">> = do_body("POST", "/read_urlencoded_body", [], <<>>, Config),
  451. <<"[{<<\"abc\">>,true}]">> = do_body("POST", "/read_urlencoded_body", [], "abc", Config),
  452. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">>
  453. = do_body("POST", "/read_urlencoded_body", [], "a=b&c=d+e", Config),
  454. %% Send a 10MB body, larger than the default length, to ensure a crash occurs.
  455. ok = do_read_urlencoded_body_too_large("/no-opts/read_urlencoded_body",
  456. string:chars($a, 10000000), Config),
  457. %% We read any length for at most 1 second.
  458. %%
  459. %% The body is sent twice, first with nofin, then wait 1.1 second, then again with fin.
  460. %% We expect the handler to crash because read_urlencoded_body expects the full body.
  461. ok = do_read_urlencoded_body_too_long("/crash/read_urlencoded_body/period", <<"abc">>, Config),
  462. %% The timeout value is set too low on purpose to ensure a crash occurs.
  463. ok = do_read_body_timeout("/opts/read_urlencoded_body/timeout", <<"abc">>, Config),
  464. %% Ensure parse errors result in a 400 response.
  465. {400, _} = do_body_error("POST", "/read_urlencoded_body", [], "%%%%%", Config),
  466. ok.
  467. %% We expect a crash.
  468. do_read_urlencoded_body_too_large(Path, Body, Config) ->
  469. ConnPid = gun_open(Config),
  470. Ref = gun:headers(ConnPid, "POST", Path, [
  471. {<<"content-length">>, integer_to_binary(iolist_size(Body))}
  472. ]),
  473. gun:data(ConnPid, Ref, fin, Body),
  474. {response, _, 413, _} = gun:await(ConnPid, Ref),
  475. gun:close(ConnPid).
  476. %% We expect a crash.
  477. do_read_urlencoded_body_too_long(Path, Body, Config) ->
  478. ConnPid = gun_open(Config),
  479. Ref = gun:headers(ConnPid, "POST", Path, [
  480. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  481. ]),
  482. gun:data(ConnPid, Ref, nofin, Body),
  483. timer:sleep(2000),
  484. gun:data(ConnPid, Ref, fin, Body),
  485. {response, _, 408, RespHeaders} = gun:await(ConnPid, Ref),
  486. _ = case config(protocol, Config) of
  487. http ->
  488. %% 408 error responses should close HTTP/1.1 connections.
  489. {_, <<"close">>} = lists:keyfind(<<"connection">>, 1, RespHeaders);
  490. http2 ->
  491. ok
  492. end,
  493. gun:close(ConnPid).
  494. read_and_match_urlencoded_body(Config) ->
  495. doc("Read and match an application/x-www-form-urlencoded request body."),
  496. <<"#{}">> = do_body("POST", "/match/body_qs", [], "a=b&c=d", Config),
  497. <<"#{a => <<\"b\">>}">> = do_body("POST", "/match/body_qs/a", [], "a=b&c=d", Config),
  498. <<"#{c => <<\"d\">>}">> = do_body("POST", "/match/body_qs/c", [], "a=b&c=d", Config),
  499. <<"#{a => <<\"b\">>,c => <<\"d\">>}">>
  500. = do_body("POST", "/match/body_qs/a/c", [], "a=b&c=d", Config),
  501. <<"#{a => <<\"b\">>,c => true}">> = do_body("POST", "/match/body_qs/a/c", [], "a=b&c", Config),
  502. <<"#{a => true,c => <<\"d\">>}">> = do_body("POST", "/match/body_qs/a/c", [], "a&c=d", Config),
  503. %% Ensure match errors result in a 400 response.
  504. {400, _} = do_body_error("POST", "/match/body_qs/a/c", [], "a=b", Config),
  505. %% Ensure parse errors result in a 400 response.
  506. {400, _} = do_body_error("POST", "/match/body_qs", [], "%%%%%", Config),
  507. %% Send a 10MB body, larger than the default length, to ensure a crash occurs.
  508. ok = do_read_urlencoded_body_too_large(
  509. "/no-opts/read_and_match_urlencoded_body",
  510. string:chars($a, 10000000), Config),
  511. %% We read any length for at most 1 second.
  512. %%
  513. %% The body is sent twice, first with nofin, then wait 1.1 second, then again with fin.
  514. %% We expect the handler to crash because read_and_match_urlencoded_body expects the full body.
  515. ok = do_read_urlencoded_body_too_long(
  516. "/crash/read_and_match_urlencoded_body/period", <<"abc">>, Config),
  517. %% The timeout value is set too low on purpose to ensure a crash occurs.
  518. ok = do_read_body_timeout("/opts/read_and_match_urlencoded_body/timeout", <<"abc">>, Config),
  519. ok.
  520. multipart(Config) ->
  521. doc("Multipart request body."),
  522. do_multipart("/multipart", Config).
  523. do_multipart(Path, Config) ->
  524. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  525. ReqBody = [
  526. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  527. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  528. "--deadbeef--"
  529. ],
  530. RespBody = do_body("POST", Path, [
  531. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  532. ], ReqBody, Config),
  533. [
  534. {#{<<"content-type">> := <<"text/plain">>}, <<"Cowboy is an HTTP server.">>},
  535. {LargeHeaders, LargeBody}
  536. ] = binary_to_term(RespBody),
  537. #{
  538. <<"content-type">> := <<"application/octet-stream">>,
  539. <<"x-custom">> := <<"value">>
  540. } = LargeHeaders,
  541. ok.
  542. multipart_error_empty(Config) ->
  543. doc("Multipart request body is empty."),
  544. %% We use an empty list as a body to make sure Gun knows
  545. %% we want to send an empty body.
  546. %% @todo This is a terrible hack. Improve Gun!
  547. Body = [],
  548. %% Ensure an empty body results in a 400 error.
  549. {400, _} = do_body_error("POST", "/multipart", [
  550. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  551. ], Body, Config),
  552. ok.
  553. multipart_error_preamble_only(Config) ->
  554. doc("Multipart request body only contains a preamble."),
  555. %% Ensure an empty body results in a 400 error.
  556. {400, _} = do_body_error("POST", "/multipart", [
  557. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  558. ], <<"Preamble.">>, Config),
  559. ok.
  560. multipart_error_headers(Config) ->
  561. doc("Multipart request body with invalid part headers."),
  562. ReqBody = [
  563. "--deadbeef\r\nbad-header text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  564. "--deadbeef--"
  565. ],
  566. %% Ensure parse errors result in a 400 response.
  567. {400, _} = do_body_error("POST", "/multipart", [
  568. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  569. ], ReqBody, Config),
  570. ok.
  571. %% The function to parse the multipart body currently does not crash,
  572. %% as far as I can tell. There is therefore no test for it.
  573. multipart_error_no_final_boundary(Config) ->
  574. doc("Multipart request body with no final boundary."),
  575. ReqBody = [
  576. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  577. ],
  578. %% Ensure parse errors result in a 400 response.
  579. {400, _} = do_body_error("POST", "/multipart", [
  580. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  581. ], ReqBody, Config),
  582. ok.
  583. multipart_missing_boundary(Config) ->
  584. doc("Multipart request body without a boundary in the media type."),
  585. ReqBody = [
  586. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  587. "--deadbeef--"
  588. ],
  589. %% Ensure parse errors result in a 400 response.
  590. {400, _} = do_body_error("POST", "/multipart", [
  591. {<<"content-type">>, <<"multipart/mixed">>}
  592. ], ReqBody, Config),
  593. ok.
  594. read_part_skip_body(Config) ->
  595. doc("Multipart request body skipping part bodies."),
  596. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  597. ReqBody = [
  598. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  599. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  600. "--deadbeef--"
  601. ],
  602. RespBody = do_body("POST", "/multipart/skip_body", [
  603. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  604. ], ReqBody, Config),
  605. [
  606. #{<<"content-type">> := <<"text/plain">>},
  607. LargeHeaders
  608. ] = binary_to_term(RespBody),
  609. #{
  610. <<"content-type">> := <<"application/octet-stream">>,
  611. <<"x-custom">> := <<"value">>
  612. } = LargeHeaders,
  613. ok.
  614. %% @todo When reading a multipart body, length and period
  615. %% only apply to a single read_body call. We may want a
  616. %% separate option to know how many reads we want to do
  617. %% before we give up.
  618. read_part2(Config) ->
  619. doc("Multipart request body using read_part/2."),
  620. %% Override the length and period values only, making
  621. %% the request process use more read_body calls.
  622. %%
  623. %% We do not try a custom timeout value since this would
  624. %% be the same test as read_body/2.
  625. do_multipart("/multipart/read_part2", Config).
  626. read_part_body2(Config) ->
  627. doc("Multipart request body using read_part_body/2."),
  628. %% Override the length and period values only, making
  629. %% the request process use more read_body calls.
  630. %%
  631. %% We do not try a custom timeout value since this would
  632. %% be the same test as read_body/2.
  633. do_multipart("/multipart/read_part_body2", Config).
  634. %% Tests: Response.
  635. %% @todo We want to crash when calling set_resp_* or related
  636. %% functions after the reply has been sent.
  637. set_resp_cookie(Config) ->
  638. doc("Response using set_resp_cookie."),
  639. %% Single cookie, no options.
  640. {200, Headers1, _} = do_get("/resp/set_resp_cookie3", Config),
  641. {_, <<"mycookie=myvalue; Version=1">>}
  642. = lists:keyfind(<<"set-cookie">>, 1, Headers1),
  643. %% Single cookie, with options.
  644. {200, Headers2, _} = do_get("/resp/set_resp_cookie4", Config),
  645. {_, <<"mycookie=myvalue; Version=1; Path=/resp/set_resp_cookie4">>}
  646. = lists:keyfind(<<"set-cookie">>, 1, Headers2),
  647. %% Multiple cookies.
  648. {200, Headers3, _} = do_get("/resp/set_resp_cookie3/multiple", Config),
  649. [_, _] = [H || H={<<"set-cookie">>, _} <- Headers3],
  650. %% Overwrite previously set cookie.
  651. {200, Headers4, _} = do_get("/resp/set_resp_cookie3/overwrite", Config),
  652. {_, <<"mycookie=overwrite; Version=1">>}
  653. = lists:keyfind(<<"set-cookie">>, 1, Headers4),
  654. ok.
  655. set_resp_header(Config) ->
  656. doc("Response using set_resp_header."),
  657. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_header", Config),
  658. true = lists:keymember(<<"content-type">>, 1, Headers),
  659. ok.
  660. set_resp_headers(Config) ->
  661. doc("Response using set_resp_headers."),
  662. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_headers", Config),
  663. true = lists:keymember(<<"content-type">>, 1, Headers),
  664. true = lists:keymember(<<"content-encoding">>, 1, Headers),
  665. ok.
  666. resp_header(Config) ->
  667. doc("Response header with/without default."),
  668. {200, _, <<"OK">>} = do_get("/resp/resp_header_defined", Config),
  669. {200, _, <<"OK">>} = do_get("/resp/resp_header_default", Config),
  670. ok.
  671. resp_headers(Config) ->
  672. doc("Get all response headers."),
  673. {200, _, <<"OK">>} = do_get("/resp/resp_headers", Config),
  674. {200, _, <<"OK">>} = do_get("/resp/resp_headers_empty", Config),
  675. ok.
  676. set_resp_body(Config) ->
  677. doc("Response using set_resp_body."),
  678. {200, _, <<"OK">>} = do_get("/resp/set_resp_body", Config),
  679. {200, _, <<"OVERRIDE">>} = do_get("/resp/set_resp_body/override", Config),
  680. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  681. {200, _, AppFile} = do_get("/resp/set_resp_body/sendfile", Config),
  682. ok.
  683. set_resp_body_sendfile0(Config) ->
  684. doc("Response using set_resp_body with a sendfile of length 0."),
  685. Path = "/resp/set_resp_body/sendfile0",
  686. ConnPid = gun_open(Config),
  687. %% First request.
  688. Ref1 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  689. {response, IsFin, 200, _} = gun:await(ConnPid, Ref1),
  690. {ok, <<>>} = case IsFin of
  691. nofin -> gun:await_body(ConnPid, Ref1);
  692. fin -> {ok, <<>>}
  693. end,
  694. %% Second request will confirm everything works as intended.
  695. Ref2 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  696. {response, IsFin, 200, _} = gun:await(ConnPid, Ref2),
  697. {ok, <<>>} = case IsFin of
  698. nofin -> gun:await_body(ConnPid, Ref2);
  699. fin -> {ok, <<>>}
  700. end,
  701. gun:close(ConnPid),
  702. ok.
  703. has_resp_header(Config) ->
  704. doc("Has response header?"),
  705. {200, Headers, <<"OK">>} = do_get("/resp/has_resp_header", Config),
  706. true = lists:keymember(<<"content-type">>, 1, Headers),
  707. ok.
  708. has_resp_body(Config) ->
  709. doc("Has response body?"),
  710. {200, _, <<"OK">>} = do_get("/resp/has_resp_body", Config),
  711. {200, _, <<"OK">>} = do_get("/resp/has_resp_body/sendfile", Config),
  712. ok.
  713. delete_resp_header(Config) ->
  714. doc("Delete response header."),
  715. {200, Headers, <<"OK">>} = do_get("/resp/delete_resp_header", Config),
  716. false = lists:keymember(<<"content-type">>, 1, Headers),
  717. ok.
  718. inform2(Config) ->
  719. doc("Informational response(s) without headers, followed by the real response."),
  720. {102, [], 200, _, _} = do_get_inform("/resp/inform2/102", Config),
  721. {102, [], 200, _, _} = do_get_inform("/resp/inform2/binary", Config),
  722. {500, _} = do_get_inform("/resp/inform2/error", Config),
  723. {102, [], 200, _, _} = do_get_inform("/resp/inform2/twice", Config),
  724. ok.
  725. inform3(Config) ->
  726. doc("Informational response(s) with headers, followed by the real response."),
  727. Headers = [{<<"ext-header">>, <<"ext-value">>}],
  728. {102, Headers, 200, _, _} = do_get_inform("/resp/inform3/102", Config),
  729. {102, Headers, 200, _, _} = do_get_inform("/resp/inform3/binary", Config),
  730. {500, _} = do_get_inform("/resp/inform3/error", Config),
  731. {102, Headers, 200, _, _} = do_get_inform("/resp/inform3/twice", Config),
  732. ok.
  733. reply2(Config) ->
  734. doc("Response with default headers and no body."),
  735. {200, _, _} = do_get("/resp/reply2/200", Config),
  736. {201, _, _} = do_get("/resp/reply2/201", Config),
  737. {404, _, _} = do_get("/resp/reply2/404", Config),
  738. {200, _, _} = do_get("/resp/reply2/binary", Config),
  739. {500, _, _} = do_get("/resp/reply2/error", Config),
  740. %% @todo We want to crash when reply or stream_reply is called twice.
  741. %% How to test this properly? This isn't enough.
  742. {200, _, _} = do_get("/resp/reply2/twice", Config),
  743. ok.
  744. reply3(Config) ->
  745. doc("Response with additional headers and no body."),
  746. {200, Headers1, _} = do_get("/resp/reply3/200", Config),
  747. true = lists:keymember(<<"content-type">>, 1, Headers1),
  748. {201, Headers2, _} = do_get("/resp/reply3/201", Config),
  749. true = lists:keymember(<<"content-type">>, 1, Headers2),
  750. {404, Headers3, _} = do_get("/resp/reply3/404", Config),
  751. true = lists:keymember(<<"content-type">>, 1, Headers3),
  752. {500, _, _} = do_get("/resp/reply3/error", Config),
  753. ok.
  754. reply4(Config) ->
  755. doc("Response with additional headers and body."),
  756. {200, _, <<"OK">>} = do_get("/resp/reply4/200", Config),
  757. {201, _, <<"OK">>} = do_get("/resp/reply4/201", Config),
  758. {404, _, <<"OK">>} = do_get("/resp/reply4/404", Config),
  759. {500, _, _} = do_get("/resp/reply4/error", Config),
  760. ok.
  761. %% @todo Crash when stream_reply is called twice.
  762. stream_reply2(Config) ->
  763. doc("Response with default headers and streamed body."),
  764. Body = <<0:8000000>>,
  765. {200, _, Body} = do_get("/resp/stream_reply2/200", Config),
  766. {201, _, Body} = do_get("/resp/stream_reply2/201", Config),
  767. {404, _, Body} = do_get("/resp/stream_reply2/404", Config),
  768. {200, _, Body} = do_get("/resp/stream_reply2/binary", Config),
  769. {500, _, _} = do_get("/resp/stream_reply2/error", Config),
  770. ok.
  771. stream_reply3(Config) ->
  772. doc("Response with additional headers and streamed body."),
  773. Body = <<0:8000000>>,
  774. {200, Headers1, Body} = do_get("/resp/stream_reply3/200", Config),
  775. true = lists:keymember(<<"content-type">>, 1, Headers1),
  776. {201, Headers2, Body} = do_get("/resp/stream_reply3/201", Config),
  777. true = lists:keymember(<<"content-type">>, 1, Headers2),
  778. {404, Headers3, Body} = do_get("/resp/stream_reply3/404", Config),
  779. true = lists:keymember(<<"content-type">>, 1, Headers3),
  780. {500, _, _} = do_get("/resp/stream_reply3/error", Config),
  781. ok.
  782. stream_body_fin0(Config) ->
  783. doc("Streamed body with last chunk of size 0."),
  784. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/fin0", Config),
  785. ok.
  786. stream_body_multiple(Config) ->
  787. doc("Streamed body via multiple calls."),
  788. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/multiple", Config),
  789. ok.
  790. stream_body_nofin(Config) ->
  791. doc("Unfinished streamed body."),
  792. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/nofin", Config),
  793. ok.
  794. stream_body_sendfile(Config) ->
  795. doc("Streamed body via multiple calls, including sendfile calls."),
  796. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  797. ExpectedBody = iolist_to_binary([
  798. <<"Hello ">>,
  799. AppFile,
  800. <<" interspersed ">>,
  801. AppFile,
  802. <<" world!">>
  803. ]),
  804. {200, _, ExpectedBody} = do_get("/resp/stream_body/sendfile", Config),
  805. ok.
  806. stream_body_sendfile_fin(Config) ->
  807. doc("Streamed body via multiple calls, including a sendfile final call."),
  808. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  809. ExpectedBody = iolist_to_binary([
  810. <<"Hello! ">>,
  811. AppFile
  812. ]),
  813. {200, _, ExpectedBody} = do_get("/resp/stream_body/sendfile_fin", Config),
  814. ok.
  815. stream_body_content_length_multiple(Config) ->
  816. doc("Streamed body via multiple calls."),
  817. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/multiple", Config),
  818. ok.
  819. stream_body_content_length_fin0(Config) ->
  820. doc("Streamed body with last chunk of size 0."),
  821. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/fin0", Config),
  822. ok.
  823. stream_body_content_length_nofin(Config) ->
  824. doc("Unfinished streamed body."),
  825. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/nofin", Config),
  826. ok.
  827. stream_body_content_length_nofin_error(Config) ->
  828. doc("Not all of body sent."),
  829. case config(protocol, Config) of
  830. http ->
  831. case do_get_error("/resp/stream_body_content_length/nofin-error", Config) of
  832. {200, Headers, <<"Hello">>} ->
  833. {_, <<"gzip">>} = lists:keyfind(<<"content-encoding">>, 1, Headers);
  834. {error, {stream_error, closed}} ->
  835. ok;
  836. {error, timeout} ->
  837. ok
  838. end;
  839. http2 ->
  840. %% @todo HTTP2 should have the same content-length checks
  841. ok
  842. end.
  843. %% @todo Crash when calling stream_body after the fin flag has been set.
  844. %% @todo Crash when calling stream_body after calling reply.
  845. %% @todo Crash when calling stream_body before calling stream_reply.
  846. stream_events_single(Config) ->
  847. doc("Streamed event."),
  848. {200, Headers, <<
  849. "event: add_comment\n"
  850. "data: Comment text.\n"
  851. "data: With many lines.\n"
  852. "\n"
  853. >>} = do_get("/resp/stream_events/single", Config),
  854. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  855. ok.
  856. stream_events_list(Config) ->
  857. doc("Streamed list of events."),
  858. {200, Headers, <<
  859. "event: add_comment\n"
  860. "data: Comment text.\n"
  861. "data: With many lines.\n"
  862. "\n"
  863. ": Set retry higher\n"
  864. ": with many lines also.\n"
  865. "retry: 10000\n"
  866. "\n"
  867. "id: 123\n"
  868. "event: add_comment\n"
  869. "data: Closing!\n"
  870. "\n"
  871. >>} = do_get("/resp/stream_events/list", Config),
  872. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  873. ok.
  874. stream_events_multiple(Config) ->
  875. doc("Streamed events via multiple calls."),
  876. {200, Headers, <<
  877. "event: add_comment\n"
  878. "data: Comment text.\n"
  879. "data: With many lines.\n"
  880. "\n"
  881. ": Set retry higher\n"
  882. ": with many lines also.\n"
  883. "retry: 10000\n"
  884. "\n"
  885. "id: 123\n"
  886. "event: add_comment\n"
  887. "data: Closing!\n"
  888. "\n"
  889. >>} = do_get("/resp/stream_events/multiple", Config),
  890. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  891. ok.
  892. stream_trailers(Config) ->
  893. doc("Stream body followed by trailer headers."),
  894. {200, RespHeaders, <<"Hello world!">>, [
  895. {<<"grpc-status">>, <<"0">>}
  896. ]} = do_trailers("/resp/stream_trailers", Config),
  897. {_, <<"grpc-status">>} = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  898. ok.
  899. stream_trailers_large(Config) ->
  900. doc("Stream large body followed by trailer headers."),
  901. {200, RespHeaders, <<0:800000>>, [
  902. {<<"grpc-status">>, <<"0">>}
  903. ]} = do_trailers("/resp/stream_trailers/large", Config),
  904. {_, <<"grpc-status">>} = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  905. ok.
  906. stream_trailers_no_te(Config) ->
  907. doc("Stream body followed by trailer headers without a te header in the request."),
  908. ConnPid = gun_open(Config),
  909. Ref = gun:get(ConnPid, "/resp/stream_trailers", [
  910. {<<"accept-encoding">>, <<"gzip">>}
  911. ]),
  912. {response, nofin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  913. %% @todo Do we want to remove the trailer header automatically?
  914. % false = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  915. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  916. <<"Hello world!">> = do_decode(RespHeaders, RespBody),
  917. gun:close(ConnPid).
  918. do_trailers(Path, Config) ->
  919. ConnPid = gun_open(Config),
  920. Ref = gun:get(ConnPid, Path, [
  921. {<<"accept-encoding">>, <<"gzip">>},
  922. {<<"te">>, <<"trailers">>}
  923. ]),
  924. {response, nofin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  925. {ok, RespBody, Trailers} = gun:await_body(ConnPid, Ref),
  926. gun:close(ConnPid),
  927. {Status, RespHeaders, do_decode(RespHeaders, RespBody), Trailers}.
  928. %% @todo Crash when calling stream_trailers twice.
  929. %% @todo Crash when calling stream_trailers after the fin flag has been set.
  930. %% @todo Crash when calling stream_trailers after calling reply.
  931. %% @todo Crash when calling stream_trailers before calling stream_reply.
  932. %% Tests: Push.
  933. %% @todo We want to crash when push is called after reply has been initiated.
  934. push(Config) ->
  935. case config(protocol, Config) of
  936. http -> do_push_http("/resp/push", Config);
  937. http2 -> do_push_http2(Config)
  938. end.
  939. push_method(Config) ->
  940. case config(protocol, Config) of
  941. http -> do_push_http("/resp/push/method", Config);
  942. http2 -> do_push_http2_method(Config)
  943. end.
  944. push_origin(Config) ->
  945. case config(protocol, Config) of
  946. http -> do_push_http("/resp/push/origin", Config);
  947. http2 -> do_push_http2_origin(Config)
  948. end.
  949. push_qs(Config) ->
  950. case config(protocol, Config) of
  951. http -> do_push_http("/resp/push/qs", Config);
  952. http2 -> do_push_http2_qs(Config)
  953. end.
  954. do_push_http(Path, Config) ->
  955. doc("Ignore pushed responses when protocol is HTTP/1.1."),
  956. ConnPid = gun_open(Config),
  957. Ref = gun:get(ConnPid, Path, []),
  958. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  959. ok.
  960. do_push_http2(Config) ->
  961. doc("Pushed responses."),
  962. ConnPid = gun_open(Config),
  963. Ref = gun:get(ConnPid, "/resp/push", []),
  964. %% We expect two pushed resources.
  965. Origin = iolist_to_binary([
  966. case config(type, Config) of
  967. tcp -> "http";
  968. ssl -> "https"
  969. end,
  970. "://localhost:",
  971. integer_to_binary(config(port, Config))
  972. ]),
  973. OriginLen = byte_size(Origin),
  974. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css">>,
  975. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  976. {push, PushTXT, <<"GET">>, <<Origin:OriginLen/binary, "/static/plain.txt">>,
  977. [{<<"accept">>,<<"text/plain">>}]} = gun:await(ConnPid, Ref),
  978. %% Pushed CSS.
  979. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  980. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  981. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  982. %% Pushed TXT is 406 because the pushed accept header uses an undefined type.
  983. {response, fin, 406, _} = gun:await(ConnPid, PushTXT),
  984. %% Let's not forget about the response to the client's request.
  985. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  986. gun:close(ConnPid).
  987. do_push_http2_method(Config) ->
  988. doc("Pushed response with non-GET method."),
  989. ConnPid = gun_open(Config),
  990. Ref = gun:get(ConnPid, "/resp/push/method", []),
  991. %% Pushed CSS.
  992. {push, PushCSS, <<"HEAD">>, _, [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  993. {response, fin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  994. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  995. %% Let's not forget about the response to the client's request.
  996. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  997. gun:close(ConnPid).
  998. do_push_http2_origin(Config) ->
  999. doc("Pushed response with custom scheme/host/port."),
  1000. ConnPid = gun_open(Config),
  1001. Ref = gun:get(ConnPid, "/resp/push/origin", []),
  1002. %% Pushed CSS.
  1003. {push, PushCSS, <<"GET">>, <<"ftp://127.0.0.1:21/static/style.css">>,
  1004. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  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. %% Let's not forget about the response to the client's request.
  1009. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1010. gun:close(ConnPid).
  1011. do_push_http2_qs(Config) ->
  1012. doc("Pushed response with query string."),
  1013. ConnPid = gun_open(Config),
  1014. Ref = gun:get(ConnPid, "/resp/push/qs", []),
  1015. %% Pushed CSS.
  1016. Origin = iolist_to_binary([
  1017. case config(type, Config) of
  1018. tcp -> "http";
  1019. ssl -> "https"
  1020. end,
  1021. "://localhost:",
  1022. integer_to_binary(config(port, Config))
  1023. ]),
  1024. OriginLen = byte_size(Origin),
  1025. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css?server=cowboy&version=2.0">>,
  1026. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  1027. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  1028. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  1029. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  1030. %% Let's not forget about the response to the client's request.
  1031. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1032. gun:close(ConnPid).