req_SUITE.erl 42 KB

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