req_SUITE.erl 44 KB

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