req_SUITE.erl 42 KB

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