req_SUITE.erl 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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, 30000);
  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_loop(Config) ->
  791. doc("Streamed body via a fast loop."),
  792. {200, _, <<0:32000000/unit:8>>} = do_get("/resp/stream_body/loop", Config),
  793. ok.
  794. stream_body_nofin(Config) ->
  795. doc("Unfinished streamed body."),
  796. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body/nofin", Config),
  797. ok.
  798. stream_body_sendfile(Config) ->
  799. doc("Streamed body via multiple calls, including sendfile calls."),
  800. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  801. ExpectedBody = iolist_to_binary([
  802. <<"Hello ">>,
  803. AppFile,
  804. <<" interspersed ">>,
  805. AppFile,
  806. <<" world!">>
  807. ]),
  808. {200, _, ExpectedBody} = do_get("/resp/stream_body/sendfile", Config),
  809. ok.
  810. stream_body_sendfile_fin(Config) ->
  811. doc("Streamed body via multiple calls, including a sendfile final call."),
  812. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  813. ExpectedBody = iolist_to_binary([
  814. <<"Hello! ">>,
  815. AppFile
  816. ]),
  817. {200, _, ExpectedBody} = do_get("/resp/stream_body/sendfile_fin", Config),
  818. ok.
  819. stream_body_content_length_multiple(Config) ->
  820. doc("Streamed body via multiple calls."),
  821. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/multiple", Config),
  822. ok.
  823. stream_body_content_length_fin0(Config) ->
  824. doc("Streamed body with last chunk of size 0."),
  825. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/fin0", Config),
  826. ok.
  827. stream_body_content_length_nofin(Config) ->
  828. doc("Unfinished streamed body."),
  829. {200, _, <<"Hello world!">>} = do_get("/resp/stream_body_content_length/nofin", Config),
  830. ok.
  831. stream_body_content_length_nofin_error(Config) ->
  832. doc("Not all of body sent."),
  833. case config(protocol, Config) of
  834. http ->
  835. case do_get_error("/resp/stream_body_content_length/nofin-error", Config) of
  836. {200, Headers, <<"Hello">>} ->
  837. {_, <<"gzip">>} = lists:keyfind(<<"content-encoding">>, 1, Headers);
  838. {error, {stream_error, closed}} ->
  839. ok;
  840. {error, timeout} ->
  841. ok
  842. end;
  843. http2 ->
  844. %% @todo HTTP2 should have the same content-length checks
  845. ok
  846. end.
  847. %% @todo Crash when calling stream_body after the fin flag has been set.
  848. %% @todo Crash when calling stream_body after calling reply.
  849. %% @todo Crash when calling stream_body before calling stream_reply.
  850. stream_events_single(Config) ->
  851. doc("Streamed event."),
  852. {200, Headers, <<
  853. "event: add_comment\n"
  854. "data: Comment text.\n"
  855. "data: With many lines.\n"
  856. "\n"
  857. >>} = do_get("/resp/stream_events/single", Config),
  858. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  859. ok.
  860. stream_events_list(Config) ->
  861. doc("Streamed list of events."),
  862. {200, Headers, <<
  863. "event: add_comment\n"
  864. "data: Comment text.\n"
  865. "data: With many lines.\n"
  866. "\n"
  867. ": Set retry higher\n"
  868. ": with many lines also.\n"
  869. "retry: 10000\n"
  870. "\n"
  871. "id: 123\n"
  872. "event: add_comment\n"
  873. "data: Closing!\n"
  874. "\n"
  875. >>} = do_get("/resp/stream_events/list", Config),
  876. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  877. ok.
  878. stream_events_multiple(Config) ->
  879. doc("Streamed events via multiple calls."),
  880. {200, Headers, <<
  881. "event: add_comment\n"
  882. "data: Comment text.\n"
  883. "data: With many lines.\n"
  884. "\n"
  885. ": Set retry higher\n"
  886. ": with many lines also.\n"
  887. "retry: 10000\n"
  888. "\n"
  889. "id: 123\n"
  890. "event: add_comment\n"
  891. "data: Closing!\n"
  892. "\n"
  893. >>} = do_get("/resp/stream_events/multiple", Config),
  894. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  895. ok.
  896. stream_trailers(Config) ->
  897. doc("Stream body followed by trailer headers."),
  898. {200, RespHeaders, <<"Hello world!">>, [
  899. {<<"grpc-status">>, <<"0">>}
  900. ]} = do_trailers("/resp/stream_trailers", Config),
  901. {_, <<"grpc-status">>} = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  902. ok.
  903. stream_trailers_large(Config) ->
  904. doc("Stream large body followed by trailer headers."),
  905. {200, RespHeaders, <<0:800000>>, [
  906. {<<"grpc-status">>, <<"0">>}
  907. ]} = do_trailers("/resp/stream_trailers/large", Config),
  908. {_, <<"grpc-status">>} = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  909. ok.
  910. stream_trailers_no_te(Config) ->
  911. doc("Stream body followed by trailer headers without a te header in the request."),
  912. ConnPid = gun_open(Config),
  913. Ref = gun:get(ConnPid, "/resp/stream_trailers", [
  914. {<<"accept-encoding">>, <<"gzip">>}
  915. ]),
  916. {response, nofin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  917. %% @todo Do we want to remove the trailer header automatically?
  918. % false = lists:keyfind(<<"trailer">>, 1, RespHeaders),
  919. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  920. <<"Hello world!">> = do_decode(RespHeaders, RespBody),
  921. gun:close(ConnPid).
  922. do_trailers(Path, Config) ->
  923. ConnPid = gun_open(Config),
  924. Ref = gun:get(ConnPid, Path, [
  925. {<<"accept-encoding">>, <<"gzip">>},
  926. {<<"te">>, <<"trailers">>}
  927. ]),
  928. {response, nofin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  929. {ok, RespBody, Trailers} = gun:await_body(ConnPid, Ref),
  930. gun:close(ConnPid),
  931. {Status, RespHeaders, do_decode(RespHeaders, RespBody), Trailers}.
  932. %% @todo Crash when calling stream_trailers twice.
  933. %% @todo Crash when calling stream_trailers after the fin flag has been set.
  934. %% @todo Crash when calling stream_trailers after calling reply.
  935. %% @todo Crash when calling stream_trailers before calling stream_reply.
  936. %% Tests: Push.
  937. %% @todo We want to crash when push is called after reply has been initiated.
  938. push(Config) ->
  939. case config(protocol, Config) of
  940. http -> do_push_http("/resp/push", Config);
  941. http2 -> do_push_http2(Config)
  942. end.
  943. push_method(Config) ->
  944. case config(protocol, Config) of
  945. http -> do_push_http("/resp/push/method", Config);
  946. http2 -> do_push_http2_method(Config)
  947. end.
  948. push_origin(Config) ->
  949. case config(protocol, Config) of
  950. http -> do_push_http("/resp/push/origin", Config);
  951. http2 -> do_push_http2_origin(Config)
  952. end.
  953. push_qs(Config) ->
  954. case config(protocol, Config) of
  955. http -> do_push_http("/resp/push/qs", Config);
  956. http2 -> do_push_http2_qs(Config)
  957. end.
  958. do_push_http(Path, Config) ->
  959. doc("Ignore pushed responses when protocol is HTTP/1.1."),
  960. ConnPid = gun_open(Config),
  961. Ref = gun:get(ConnPid, Path, []),
  962. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  963. ok.
  964. do_push_http2(Config) ->
  965. doc("Pushed responses."),
  966. ConnPid = gun_open(Config),
  967. Ref = gun:get(ConnPid, "/resp/push", []),
  968. %% We expect two pushed resources.
  969. Origin = iolist_to_binary([
  970. case config(type, Config) of
  971. tcp -> "http";
  972. ssl -> "https"
  973. end,
  974. "://localhost:",
  975. integer_to_binary(config(port, Config))
  976. ]),
  977. OriginLen = byte_size(Origin),
  978. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css">>,
  979. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  980. {push, PushTXT, <<"GET">>, <<Origin:OriginLen/binary, "/static/plain.txt">>,
  981. [{<<"accept">>,<<"text/plain">>}]} = gun:await(ConnPid, Ref),
  982. %% Pushed CSS.
  983. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  984. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  985. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  986. %% Pushed TXT is 406 because the pushed accept header uses an undefined type.
  987. {response, fin, 406, _} = gun:await(ConnPid, PushTXT),
  988. %% Let's not forget about the response to the client's request.
  989. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  990. gun:close(ConnPid).
  991. do_push_http2_method(Config) ->
  992. doc("Pushed response with non-GET method."),
  993. ConnPid = gun_open(Config),
  994. Ref = gun:get(ConnPid, "/resp/push/method", []),
  995. %% Pushed CSS.
  996. {push, PushCSS, <<"HEAD">>, _, [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  997. {response, fin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  998. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  999. %% Let's not forget about the response to the client's request.
  1000. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1001. gun:close(ConnPid).
  1002. do_push_http2_origin(Config) ->
  1003. doc("Pushed response with custom scheme/host/port."),
  1004. ConnPid = gun_open(Config),
  1005. Ref = gun:get(ConnPid, "/resp/push/origin", []),
  1006. %% Pushed CSS.
  1007. {push, PushCSS, <<"GET">>, <<"ftp://127.0.0.1:21/static/style.css">>,
  1008. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  1009. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  1010. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  1011. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  1012. %% Let's not forget about the response to the client's request.
  1013. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  1014. gun:close(ConnPid).
  1015. do_push_http2_qs(Config) ->
  1016. doc("Pushed response with query string."),
  1017. ConnPid = gun_open(Config),
  1018. Ref = gun:get(ConnPid, "/resp/push/qs", []),
  1019. %% Pushed CSS.
  1020. Origin = iolist_to_binary([
  1021. case config(type, Config) of
  1022. tcp -> "http";
  1023. ssl -> "https"
  1024. end,
  1025. "://localhost:",
  1026. integer_to_binary(config(port, Config))
  1027. ]),
  1028. OriginLen = byte_size(Origin),
  1029. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css?server=cowboy&version=2.0">>,
  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).