http_SUITE.erl 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.eu>
  2. %% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. -module(http_SUITE).
  16. -include_lib("common_test/include/ct.hrl").
  17. -export([all/0, groups/0, init_per_suite/1, end_per_suite/1,
  18. init_per_group/2, end_per_group/2]). %% ct.
  19. -export([chunked_response/1, headers_dupe/1, headers_huge/1,
  20. keepalive_nl/1, max_keepalive/1, nc_rand/1, nc_zero/1,
  21. pipeline/1, raw/1, set_resp_header/1, set_resp_overwrite/1,
  22. set_resp_body/1, stream_body_set_resp/1, response_as_req/1,
  23. static_mimetypes_function/1, static_attribute_etag/1,
  24. static_function_etag/1, multipart/1, te_identity/1,
  25. te_chunked/1, te_chunked_delayed/1]). %% http.
  26. -export([http_200/1, http_404/1, handler_errors/1,
  27. file_200/1, file_403/1, dir_403/1, file_404/1,
  28. file_400/1]). %% http and https.
  29. -export([http_10_hostless/1, http_10_chunkless/1]). %% misc.
  30. -export([rest_simple/1, rest_keepalive/1, rest_keepalive_post/1,
  31. rest_nodelete/1, rest_resource_etags/1]). %% rest.
  32. -export([onrequest/1, onrequest_reply/1]). %% hooks.
  33. %% ct.
  34. all() ->
  35. [{group, http}, {group, https}, {group, misc}, {group, rest},
  36. {group, hooks}].
  37. groups() ->
  38. BaseTests = [http_200, http_404, handler_errors,
  39. file_200, file_403, dir_403, file_404, file_400],
  40. [{http, [], [chunked_response, headers_dupe, headers_huge,
  41. keepalive_nl, max_keepalive, nc_rand, nc_zero, pipeline, raw,
  42. set_resp_header, set_resp_overwrite,
  43. set_resp_body, response_as_req, stream_body_set_resp,
  44. static_mimetypes_function, static_attribute_etag,
  45. static_function_etag, multipart, te_identity, te_chunked,
  46. te_chunked_delayed] ++ BaseTests},
  47. {https, [], BaseTests},
  48. {misc, [], [http_10_hostless, http_10_chunkless]},
  49. {rest, [], [rest_simple, rest_keepalive, rest_keepalive_post,
  50. rest_nodelete, rest_resource_etags]},
  51. {hooks, [], [onrequest, onrequest_reply]}].
  52. init_per_suite(Config) ->
  53. application:start(inets),
  54. application:start(cowboy),
  55. Config.
  56. end_per_suite(_Config) ->
  57. application:stop(cowboy),
  58. application:stop(inets),
  59. ok.
  60. init_per_group(http, Config) ->
  61. Port = 33080,
  62. Config1 = init_static_dir(Config),
  63. cowboy:start_listener(http, 100,
  64. cowboy_tcp_transport, [{port, Port}],
  65. cowboy_http_protocol, [{max_keepalive, 50},
  66. {dispatch, init_http_dispatch(Config1)}]
  67. ),
  68. [{scheme, "http"}, {port, Port}|Config1];
  69. init_per_group(https, Config) ->
  70. Port = 33081,
  71. Config1 = init_static_dir(Config),
  72. application:start(crypto),
  73. application:start(public_key),
  74. application:start(ssl),
  75. DataDir = ?config(data_dir, Config),
  76. {ok,_} = cowboy:start_listener(https, 100,
  77. cowboy_ssl_transport, [
  78. {port, Port}, {certfile, DataDir ++ "cert.pem"},
  79. {keyfile, DataDir ++ "key.pem"}, {password, "cowboy"}],
  80. cowboy_http_protocol, [{dispatch, init_https_dispatch(Config1)}]
  81. ),
  82. [{scheme, "https"}, {port, Port}|Config1];
  83. init_per_group(misc, Config) ->
  84. Port = 33082,
  85. {ok,_} = cowboy:start_listener(misc, 100,
  86. cowboy_tcp_transport, [{port, Port}],
  87. cowboy_http_protocol, [{dispatch, [{'_', [
  88. {[<<"chunked_response">>], chunked_handler, []},
  89. {[], http_handler, []}
  90. ]}]}]),
  91. [{port, Port}|Config];
  92. init_per_group(rest, Config) ->
  93. Port = 33083,
  94. {ok,_} = cowboy:start_listener(rest, 100,
  95. cowboy_tcp_transport, [{port, Port}],
  96. cowboy_http_protocol, [{dispatch, [{'_', [
  97. {[<<"simple">>], rest_simple_resource, []},
  98. {[<<"forbidden_post">>], rest_forbidden_resource, [true]},
  99. {[<<"simple_post">>], rest_forbidden_resource, [false]},
  100. {[<<"nodelete">>], rest_nodelete_resource, []},
  101. {[<<"resetags">>], rest_resource_etags, []}
  102. ]}]}]),
  103. [{scheme, "http"},{port, Port}|Config];
  104. init_per_group(hooks, Config) ->
  105. Port = 33084,
  106. {ok, _} = cowboy:start_listener(hooks, 100,
  107. cowboy_tcp_transport, [{port, Port}],
  108. cowboy_http_protocol, [
  109. {dispatch, init_http_dispatch(Config)},
  110. {onrequest, fun onrequest_hook/1}
  111. ]),
  112. [{scheme, "http"}, {port, Port}|Config].
  113. end_per_group(https, Config) ->
  114. cowboy:stop_listener(https),
  115. application:stop(ssl),
  116. application:stop(public_key),
  117. application:stop(crypto),
  118. end_static_dir(Config),
  119. ok;
  120. end_per_group(http, Config) ->
  121. cowboy:stop_listener(http),
  122. end_static_dir(Config);
  123. end_per_group(Listener, _Config) ->
  124. cowboy:stop_listener(Listener),
  125. ok.
  126. %% Dispatch configuration.
  127. init_http_dispatch(Config) ->
  128. [
  129. {[<<"localhost">>], [
  130. {[<<"chunked_response">>], chunked_handler, []},
  131. {[<<"init_shutdown">>], http_handler_init_shutdown, []},
  132. {[<<"long_polling">>], http_handler_long_polling, []},
  133. {[<<"headers">>, <<"dupe">>], http_handler,
  134. [{headers, [{<<"Connection">>, <<"close">>}]}]},
  135. {[<<"set_resp">>, <<"header">>], http_handler_set_resp,
  136. [{headers, [{<<"Vary">>, <<"Accept">>}]}]},
  137. {[<<"set_resp">>, <<"overwrite">>], http_handler_set_resp,
  138. [{headers, [{<<"Server">>, <<"DesireDrive/1.0">>}]}]},
  139. {[<<"set_resp">>, <<"body">>], http_handler_set_resp,
  140. [{body, <<"A flameless dance does not equal a cycle">>}]},
  141. {[<<"stream_body">>, <<"set_resp">>], http_handler_stream_body,
  142. [{reply, set_resp}, {body, <<"stream_body_set_resp">>}]},
  143. {[<<"static">>, '...'], cowboy_http_static,
  144. [{directory, ?config(static_dir, Config)},
  145. {mimetypes, [{<<".css">>, [<<"text/css">>]}]}]},
  146. {[<<"static_mimetypes_function">>, '...'], cowboy_http_static,
  147. [{directory, ?config(static_dir, Config)},
  148. {mimetypes, {fun(Path, data) when is_binary(Path) ->
  149. [<<"text/html">>] end, data}}]},
  150. {[<<"handler_errors">>], http_handler_errors, []},
  151. {[<<"static_attribute_etag">>, '...'], cowboy_http_static,
  152. [{directory, ?config(static_dir, Config)},
  153. {etag, {attributes, [filepath, filesize, inode, mtime]}}]},
  154. {[<<"static_function_etag">>, '...'], cowboy_http_static,
  155. [{directory, ?config(static_dir, Config)},
  156. {etag, {fun static_function_etag/2, etag_data}}]},
  157. {[<<"multipart">>], http_handler_multipart, []},
  158. {[<<"echo">>, <<"body">>], http_handler_echo_body, []},
  159. {[], http_handler, []}
  160. ]}
  161. ].
  162. init_https_dispatch(Config) ->
  163. init_http_dispatch(Config).
  164. init_static_dir(Config) ->
  165. Dir = filename:join(?config(priv_dir, Config), "static"),
  166. Level1 = fun(Name) -> filename:join(Dir, Name) end,
  167. ok = file:make_dir(Dir),
  168. ok = file:write_file(Level1("test_file"), "test_file\n"),
  169. ok = file:write_file(Level1("test_file.css"), "test_file.css\n"),
  170. ok = file:write_file(Level1("test_noread"), "test_noread\n"),
  171. ok = file:change_mode(Level1("test_noread"), 8#0333),
  172. ok = file:write_file(Level1("test.html"), "test.html\n"),
  173. ok = file:make_dir(Level1("test_dir")),
  174. [{static_dir, Dir}|Config].
  175. end_static_dir(Config) ->
  176. Dir = ?config(static_dir, Config),
  177. Level1 = fun(Name) -> filename:join(Dir, Name) end,
  178. ok = file:delete(Level1("test_file")),
  179. ok = file:delete(Level1("test_file.css")),
  180. ok = file:delete(Level1("test_noread")),
  181. ok = file:delete(Level1("test.html")),
  182. ok = file:del_dir(Level1("test_dir")),
  183. ok = file:del_dir(Dir),
  184. Config.
  185. %% http.
  186. chunked_response(Config) ->
  187. {ok, {{"HTTP/1.1", 200, "OK"}, _Headers, "chunked_handler\r\nworks fine!"}} =
  188. httpc:request(build_url("/chunked_response", Config)).
  189. headers_dupe(Config) ->
  190. {port, Port} = lists:keyfind(port, 1, Config),
  191. {ok, Socket} = gen_tcp:connect("localhost", Port,
  192. [binary, {active, false}, {packet, raw}]),
  193. ok = gen_tcp:send(Socket, "GET /headers/dupe HTTP/1.1\r\n"
  194. "Host: localhost\r\nConnection: keep-alive\r\n\r\n"),
  195. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  196. {_Start, _Length} = binary:match(Data, <<"Connection: close">>),
  197. nomatch = binary:match(Data, <<"Connection: keep-alive">>),
  198. {error, closed} = gen_tcp:recv(Socket, 0, 1000).
  199. headers_huge(Config) ->
  200. Cookie = lists:flatten(["whatever_man_biiiiiiiiiiiig_cookie_me_want_77="
  201. "Wed Apr 06 2011 10:38:52 GMT-0500 (CDT)" || _N <- lists:seq(1, 40)]),
  202. {_Packet, 200} = raw_req(["GET / HTTP/1.0\r\nHost: localhost\r\n"
  203. "Set-Cookie: ", Cookie, "\r\n\r\n"], Config).
  204. keepalive_nl(Config) ->
  205. {port, Port} = lists:keyfind(port, 1, Config),
  206. {ok, Socket} = gen_tcp:connect("localhost", Port,
  207. [binary, {active, false}, {packet, raw}]),
  208. ok = keepalive_nl_loop(Socket, 10),
  209. ok = gen_tcp:close(Socket).
  210. keepalive_nl_loop(_Socket, 0) ->
  211. ok;
  212. keepalive_nl_loop(Socket, N) ->
  213. ok = gen_tcp:send(Socket, "GET / HTTP/1.1\r\n"
  214. "Host: localhost\r\nConnection: keep-alive\r\n\r\n"),
  215. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  216. {0, 12} = binary:match(Data, <<"HTTP/1.1 200">>),
  217. nomatch = binary:match(Data, <<"Connection: close">>),
  218. ok = gen_tcp:send(Socket, "\r\n"), %% extra nl
  219. keepalive_nl_loop(Socket, N - 1).
  220. max_keepalive(Config) ->
  221. {port, Port} = lists:keyfind(port, 1, Config),
  222. {ok, Socket} = gen_tcp:connect("localhost", Port,
  223. [binary, {active, false}, {packet, raw}]),
  224. ok = max_keepalive_loop(Socket, 50),
  225. {error, closed} = gen_tcp:recv(Socket, 0, 1000).
  226. max_keepalive_loop(_Socket, 0) ->
  227. ok;
  228. max_keepalive_loop(Socket, N) ->
  229. ok = gen_tcp:send(Socket, "GET / HTTP/1.1\r\n"
  230. "Host: localhost\r\nConnection: keep-alive\r\n\r\n"),
  231. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  232. {0, 12} = binary:match(Data, <<"HTTP/1.1 200">>),
  233. case N of
  234. 1 -> {_, _} = binary:match(Data, <<"Connection: close">>);
  235. N -> nomatch = binary:match(Data, <<"Connection: close">>)
  236. end,
  237. keepalive_nl_loop(Socket, N - 1).
  238. multipart(Config) ->
  239. Url = build_url("/multipart", Config),
  240. Body = <<
  241. "This is a preamble."
  242. "\r\n--OHai\r\nX-Name:answer\r\n\r\n42"
  243. "\r\n--OHai\r\nServer:Cowboy\r\n\r\nIt rocks!\r\n"
  244. "\r\n--OHai--"
  245. "This is an epiloque."
  246. >>,
  247. Request = {Url, [], "multipart/x-makes-no-sense; boundary=OHai", Body},
  248. {ok, {{"HTTP/1.1", 200, "OK"}, _Headers, Response}} =
  249. httpc:request(post, Request, [], [{body_format, binary}]),
  250. Parts = binary_to_term(Response),
  251. Parts = [
  252. {[{<<"X-Name">>, <<"answer">>}], <<"42">>},
  253. {[{'Server', <<"Cowboy">>}], <<"It rocks!\r\n">>}
  254. ].
  255. nc_rand(Config) ->
  256. nc_reqs(Config, "/dev/urandom").
  257. nc_zero(Config) ->
  258. nc_reqs(Config, "/dev/zero").
  259. nc_reqs(Config, Input) ->
  260. Cat = os:find_executable("cat"),
  261. Nc = os:find_executable("nc"),
  262. case {Cat, Nc} of
  263. {false, _} ->
  264. {skip, {notfound, cat}};
  265. {_, false} ->
  266. {skip, {notfound, nc}};
  267. _Good ->
  268. %% Throw garbage at the server then check if it's still up.
  269. {port, Port} = lists:keyfind(port, 1, Config),
  270. [nc_run_req(Port, Input) || _N <- lists:seq(1, 100)],
  271. Packet = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n",
  272. {Packet, 200} = raw_req(Packet, Config)
  273. end.
  274. nc_run_req(Port, Input) ->
  275. os:cmd("cat " ++ Input ++ " | nc localhost " ++ integer_to_list(Port)).
  276. pipeline(Config) ->
  277. {port, Port} = lists:keyfind(port, 1, Config),
  278. {ok, Socket} = gen_tcp:connect("localhost", Port,
  279. [binary, {active, false}, {packet, raw}]),
  280. ok = gen_tcp:send(Socket,
  281. "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n"
  282. "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n"
  283. "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n"
  284. "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n"
  285. "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"),
  286. Data = pipeline_recv(Socket, <<>>),
  287. Reqs = binary:split(Data, << "\r\n\r\nhttp_handler" >>, [global, trim]),
  288. 5 = length(Reqs),
  289. pipeline_check(Reqs).
  290. pipeline_check([]) ->
  291. ok;
  292. pipeline_check([Req|Tail]) ->
  293. << "HTTP/1.1 200", _Rest/bits >> = Req,
  294. pipeline_check(Tail).
  295. pipeline_recv(Socket, SoFar) ->
  296. case gen_tcp:recv(Socket, 0, 6000) of
  297. {ok, Data} ->
  298. pipeline_recv(Socket, << SoFar/binary, Data/binary >>);
  299. {error, closed} ->
  300. ok = gen_tcp:close(Socket),
  301. SoFar
  302. end.
  303. raw_req(Packet, Config) ->
  304. {port, Port} = lists:keyfind(port, 1, Config),
  305. {ok, Socket} = gen_tcp:connect("localhost", Port,
  306. [binary, {active, false}, {packet, raw}]),
  307. ok = gen_tcp:send(Socket, Packet),
  308. Res = case gen_tcp:recv(Socket, 0, 6000) of
  309. {ok, << "HTTP/1.1 ", Str:24/bits, _Rest/bits >>} ->
  310. list_to_integer(binary_to_list(Str));
  311. {error, Reason} ->
  312. Reason
  313. end,
  314. gen_tcp:close(Socket),
  315. {Packet, Res}.
  316. %% Send a raw request. Return the response code and the full response.
  317. raw_resp(Request, Config) ->
  318. {port, Port} = lists:keyfind(port, 1, Config),
  319. Transport = case ?config(scheme, Config) of
  320. "http" -> gen_tcp;
  321. "https" -> ssl
  322. end,
  323. {ok, Socket} = Transport:connect("localhost", Port,
  324. [binary, {active, false}, {packet, raw}]),
  325. ok = Transport:send(Socket, Request),
  326. {StatusCode, Response} = case recv_loop(Transport, Socket, <<>>) of
  327. {ok, << "HTTP/1.1 ", Str:24/bits, _Rest/bits >> = Bin} ->
  328. {list_to_integer(binary_to_list(Str)), Bin};
  329. {ok, Bin} ->
  330. {badresp, Bin};
  331. {error, Reason} ->
  332. {Reason, <<>>}
  333. end,
  334. Transport:close(Socket),
  335. {Response, StatusCode}.
  336. recv_loop(Transport, Socket, Acc) ->
  337. case Transport:recv(Socket, 0, 6000) of
  338. {ok, Data} ->
  339. recv_loop(Transport, Socket, <<Acc/binary, Data/binary>>);
  340. {error, closed} ->
  341. ok = Transport:close(Socket),
  342. {ok, Acc};
  343. {error, Reason} ->
  344. {error, Reason}
  345. end.
  346. raw(Config) ->
  347. Huge = [$0 || _N <- lists:seq(1, 5000)],
  348. Tests = [
  349. {"\r\n\r\n\r\n\r\n\r\nGET / HTTP/1.1\r\nHost: localhost\r\n\r\n", 200},
  350. {"\n", 400},
  351. {"Garbage\r\n\r\n", 400},
  352. {"\r\n\r\n\r\n\r\n\r\n\r\n", 400},
  353. {"GET / HTTP/1.1\r\nHost: dev-extend.eu\r\n\r\n", 400},
  354. {"", closed},
  355. {"\r\n", closed},
  356. {"\r\n\r\n", closed},
  357. {"GET / HTTP/1.1", closed},
  358. {"GET / HTTP/1.1\r\n", 408},
  359. {"GET / HTTP/1.1\r\nHost: localhost", 408},
  360. {"GET / HTTP/1.1\r\nHost: localhost\r\n", 408},
  361. {"GET / HTTP/1.1\r\nHost: localhost\r\n\r", 408},
  362. {"GET http://proxy/ HTTP/1.1\r\n\r\n", 400},
  363. {"GET http://proxy/ HTTP/1.1\r\nHost: localhost\r\n\r\n", 200},
  364. {"GET / HTTP/1.2\r\nHost: localhost\r\n\r\n", 505},
  365. {"GET /init_shutdown HTTP/1.1\r\nHost: localhost\r\n\r\n", 666},
  366. {"GET /long_polling HTTP/1.1\r\nHost: localhost\r\n\r\n", 102},
  367. {Huge, 413},
  368. {"GET / HTTP/1.1\r\n" ++ Huge, 413}
  369. ],
  370. [{Packet, StatusCode} = raw_req(Packet, Config)
  371. || {Packet, StatusCode} <- Tests].
  372. set_resp_header(Config) ->
  373. {port, Port} = lists:keyfind(port, 1, Config),
  374. {ok, Socket} = gen_tcp:connect("localhost", Port,
  375. [binary, {active, false}, {packet, raw}]),
  376. ok = gen_tcp:send(Socket, "GET /set_resp/header HTTP/1.1\r\n"
  377. "Host: localhost\r\nConnection: close\r\n\r\n"),
  378. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  379. {_, _} = binary:match(Data, <<"Vary: Accept">>),
  380. {_, _} = binary:match(Data, <<"Set-Cookie: ">>).
  381. set_resp_overwrite(Config) ->
  382. {port, Port} = lists:keyfind(port, 1, Config),
  383. {ok, Socket} = gen_tcp:connect("localhost", Port,
  384. [binary, {active, false}, {packet, raw}]),
  385. ok = gen_tcp:send(Socket, "GET /set_resp/overwrite HTTP/1.1\r\n"
  386. "Host: localhost\r\nConnection: close\r\n\r\n"),
  387. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  388. {_Start, _Length} = binary:match(Data, <<"Server: DesireDrive/1.0">>).
  389. set_resp_body(Config) ->
  390. {port, Port} = lists:keyfind(port, 1, Config),
  391. {ok, Socket} = gen_tcp:connect("localhost", Port,
  392. [binary, {active, false}, {packet, raw}]),
  393. ok = gen_tcp:send(Socket, "GET /set_resp/body HTTP/1.1\r\n"
  394. "Host: localhost\r\nConnection: close\r\n\r\n"),
  395. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  396. {_Start, _Length} = binary:match(Data, <<"\r\n\r\n"
  397. "A flameless dance does not equal a cycle">>).
  398. response_as_req(Config) ->
  399. Packet =
  400. "HTTP/1.0 302 Found
  401. Location: http://www.google.co.il/
  402. Cache-Control: private
  403. Content-Type: text/html; charset=UTF-8
  404. Set-Cookie: PREF=ID=568f67013d4a7afa:FF=0:TM=1323014101:LM=1323014101:S=XqctDWC65MzKT0zC; expires=Tue, 03-Dec-2013 15:55:01 GMT; path=/; domain=.google.com
  405. Date: Sun, 04 Dec 2011 15:55:01 GMT
  406. Server: gws
  407. Content-Length: 221
  408. X-XSS-Protection: 1; mode=block
  409. X-Frame-Options: SAMEORIGIN
  410. <HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">
  411. <TITLE>302 Moved</TITLE></HEAD><BODY>
  412. <H1>302 Moved</H1>
  413. The document has moved
  414. <A HREF=\"http://www.google.co.il/\">here</A>.
  415. </BODY></HTML>",
  416. {Packet, 400} = raw_req(Packet, Config).
  417. stream_body_set_resp(Config) ->
  418. {Packet, 200} = raw_resp(
  419. "GET /stream_body/set_resp HTTP/1.1\r\n"
  420. "Host: localhost\r\nConnection: close\r\n\r\n", Config),
  421. {_Start, _Length} = binary:match(Packet, <<"stream_body_set_resp">>).
  422. static_mimetypes_function(Config) ->
  423. TestURL = build_url("/static_mimetypes_function/test.html", Config),
  424. {ok, {{"HTTP/1.1", 200, "OK"}, Headers1, "test.html\n"}} =
  425. httpc:request(TestURL),
  426. "text/html" = ?config("content-type", Headers1).
  427. handler_errors(Config) ->
  428. Request = fun(Case) ->
  429. raw_resp(["GET /handler_errors?case=", Case, " HTTP/1.1\r\n",
  430. "Host: localhost\r\n\r\n"], Config) end,
  431. {_Packet1, 500} = Request("init_before_reply"),
  432. {Packet2, 200} = Request("init_after_reply"),
  433. nomatch = binary:match(Packet2, <<"HTTP/1.1 500">>),
  434. {Packet3, 200} = Request("init_reply_handle_error"),
  435. nomatch = binary:match(Packet3, <<"HTTP/1.1 500">>),
  436. {_Packet4, 500} = Request("handle_before_reply"),
  437. {Packet5, 200} = Request("handle_after_reply"),
  438. nomatch = binary:match(Packet5, <<"HTTP/1.1 500">>),
  439. {Packet6, 200} = raw_resp([
  440. "GET / HTTP/1.1\r\n",
  441. "Host: localhost\r\n",
  442. "Connection: keep-alive\r\n\r\n",
  443. "GET /handler_errors?case=handle_after_reply\r\n",
  444. "Host: localhost\r\n\r\n"], Config),
  445. nomatch = binary:match(Packet6, <<"HTTP/1.1 500">>),
  446. {Packet7, 200} = raw_resp([
  447. "GET / HTTP/1.1\r\n",
  448. "Host: localhost\r\n",
  449. "Connection: keep-alive\r\n\r\n",
  450. "GET /handler_errors?case=handle_before_reply HTTP/1.1\r\n",
  451. "Host: localhost\r\n\r\n"], Config),
  452. {{_, _}, _} = {binary:match(Packet7, <<"HTTP/1.1 500">>), Packet7},
  453. done.
  454. static_attribute_etag(Config) ->
  455. TestURL = build_url("/static_attribute_etag/test.html", Config),
  456. {ok, {{"HTTP/1.1", 200, "OK"}, Headers1, "test.html\n"}} =
  457. httpc:request(TestURL),
  458. false = ?config("etag", Headers1) =:= undefined,
  459. {ok, {{"HTTP/1.1", 200, "OK"}, Headers2, "test.html\n"}} =
  460. httpc:request(TestURL),
  461. true = ?config("etag", Headers1) =:= ?config("etag", Headers2).
  462. static_function_etag(Config) ->
  463. TestURL = build_url("/static_function_etag/test.html", Config),
  464. {ok, {{"HTTP/1.1", 200, "OK"}, Headers1, "test.html\n"}} =
  465. httpc:request(TestURL),
  466. false = ?config("etag", Headers1) =:= undefined,
  467. {ok, {{"HTTP/1.1", 200, "OK"}, Headers2, "test.html\n"}} =
  468. httpc:request(TestURL),
  469. true = ?config("etag", Headers1) =:= ?config("etag", Headers2).
  470. static_function_etag(Arguments, etag_data) ->
  471. {_, Filepath} = lists:keyfind(filepath, 1, Arguments),
  472. {_, _Filesize} = lists:keyfind(filesize, 1, Arguments),
  473. {_, _INode} = lists:keyfind(inode, 1, Arguments),
  474. {_, _Modified} = lists:keyfind(mtime, 1, Arguments),
  475. ChecksumCommand = lists:flatten(io_lib:format("sha1sum ~s", [Filepath])),
  476. [Checksum|_] = string:tokens(os:cmd(ChecksumCommand), " "),
  477. {strong, iolist_to_binary(Checksum)}.
  478. te_identity(Config) ->
  479. {port, Port} = lists:keyfind(port, 1, Config),
  480. {ok, Socket} = gen_tcp:connect("localhost", Port,
  481. [binary, {active, false}, {packet, raw}]),
  482. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  483. StrLen = integer_to_list(byte_size(Body)),
  484. ok = gen_tcp:send(Socket, ["GET /echo/body HTTP/1.1\r\n"
  485. "Host: localhost\r\nConnection: close\r\n"
  486. "Content-Length: ", StrLen, "\r\n\r\n", Body]),
  487. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  488. {_, _} = binary:match(Data, Body).
  489. te_chunked(Config) ->
  490. {port, Port} = lists:keyfind(port, 1, Config),
  491. {ok, Socket} = gen_tcp:connect("localhost", Port,
  492. [binary, {active, false}, {packet, raw}]),
  493. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  494. Chunks = body_to_chunks(50, Body, []),
  495. ok = gen_tcp:send(Socket, ["GET /echo/body HTTP/1.1\r\n"
  496. "Host: localhost\r\nConnection: close\r\n"
  497. "Transfer-Encoding: chunked\r\n\r\n", Chunks]),
  498. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  499. {_, _} = binary:match(Data, Body).
  500. te_chunked_delayed(Config) ->
  501. {port, Port} = lists:keyfind(port, 1, Config),
  502. {ok, Socket} = gen_tcp:connect("localhost", Port,
  503. [binary, {active, false}, {packet, raw}]),
  504. Body = list_to_binary(io_lib:format("~p", [lists:seq(1, 100)])),
  505. Chunks = body_to_chunks(50, Body, []),
  506. ok = gen_tcp:send(Socket, ["GET /echo/body HTTP/1.1\r\n"
  507. "Host: localhost\r\nConnection: close\r\n"
  508. "Transfer-Encoding: chunked\r\n\r\n"]),
  509. _ = [begin ok = gen_tcp:send(Socket, Chunk), ok = timer:sleep(10) end
  510. || Chunk <- Chunks],
  511. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  512. {_, _} = binary:match(Data, Body).
  513. body_to_chunks(_, <<>>, Acc) ->
  514. lists:reverse([<<"0\r\n\r\n">>|Acc]);
  515. body_to_chunks(ChunkSize, Body, Acc) ->
  516. BodySize = byte_size(Body),
  517. ChunkSize2 = case BodySize < ChunkSize of
  518. true -> BodySize;
  519. false -> ChunkSize
  520. end,
  521. << Chunk:ChunkSize2/binary, Rest/binary >> = Body,
  522. ChunkSizeBin = list_to_binary(integer_to_list(ChunkSize2, 16)),
  523. body_to_chunks(ChunkSize, Rest,
  524. [<< ChunkSizeBin/binary, "\r\n", Chunk/binary, "\r\n" >>|Acc]).
  525. %% http and https.
  526. build_url(Path, Config) ->
  527. {scheme, Scheme} = lists:keyfind(scheme, 1, Config),
  528. {port, Port} = lists:keyfind(port, 1, Config),
  529. Scheme ++ "://localhost:" ++ integer_to_list(Port) ++ Path.
  530. http_200(Config) ->
  531. {ok, {{"HTTP/1.1", 200, "OK"}, _Headers, "http_handler"}} =
  532. httpc:request(build_url("/", Config)).
  533. http_404(Config) ->
  534. {ok, {{"HTTP/1.1", 404, "Not Found"}, _Headers, _Body}} =
  535. httpc:request(build_url("/not/found", Config)).
  536. file_200(Config) ->
  537. {ok, {{"HTTP/1.1", 200, "OK"}, Headers, "test_file\n"}} =
  538. httpc:request(build_url("/static/test_file", Config)),
  539. "application/octet-stream" = ?config("content-type", Headers),
  540. {ok, {{"HTTP/1.1", 200, "OK"}, Headers1, "test_file.css\n"}} =
  541. httpc:request(build_url("/static/test_file.css", Config)),
  542. "text/css" = ?config("content-type", Headers1).
  543. file_403(Config) ->
  544. {ok, {{"HTTP/1.1", 403, "Forbidden"}, _Headers, _Body}} =
  545. httpc:request(build_url("/static/test_noread", Config)).
  546. dir_403(Config) ->
  547. {ok, {{"HTTP/1.1", 403, "Forbidden"}, _Headers, _Body}} =
  548. httpc:request(build_url("/static/test_dir", Config)),
  549. {ok, {{"HTTP/1.1", 403, "Forbidden"}, _Headers, _Body}} =
  550. httpc:request(build_url("/static/test_dir/", Config)).
  551. file_404(Config) ->
  552. {ok, {{"HTTP/1.1", 404, "Not Found"}, _Headers, _Body}} =
  553. httpc:request(build_url("/static/not_found", Config)).
  554. file_400(Config) ->
  555. {ok, {{"HTTP/1.1", 400, "Bad Request"}, _Headers, _Body}} =
  556. httpc:request(build_url("/static/%2f", Config)),
  557. {ok, {{"HTTP/1.1", 400, "Bad Request"}, _Headers1, _Body1}} =
  558. httpc:request(build_url("/static/%2e", Config)),
  559. {ok, {{"HTTP/1.1", 400, "Bad Request"}, _Headers2, _Body2}} =
  560. httpc:request(build_url("/static/%2e%2e", Config)).
  561. %% misc.
  562. http_10_hostless(Config) ->
  563. Packet = "GET / HTTP/1.0\r\n\r\n",
  564. {Packet, 200} = raw_req(Packet, Config).
  565. http_10_chunkless(Config) ->
  566. {port, Port} = lists:keyfind(port, 1, Config),
  567. {ok, Socket} = gen_tcp:connect("localhost", Port,
  568. [binary, {active, false}, {packet, raw}]),
  569. Packet = "GET /chunked_response HTTP/1.0\r\nContent-Length: 0\r\n\r\n",
  570. ok = gen_tcp:send(Socket, Packet),
  571. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  572. nomatch = binary:match(Data, <<"Transfer-Encoding">>),
  573. {_, _} = binary:match(Data, <<"chunked_handler\r\nworks fine!">>),
  574. ok = gen_tcp:close(Socket).
  575. %% rest.
  576. rest_simple(Config) ->
  577. Packet = "GET /simple HTTP/1.1\r\nHost: localhost\r\n\r\n",
  578. {Packet, 200} = raw_req(Packet, Config).
  579. rest_keepalive(Config) ->
  580. {port, Port} = lists:keyfind(port, 1, Config),
  581. {ok, Socket} = gen_tcp:connect("localhost", Port,
  582. [binary, {active, false}, {packet, raw}]),
  583. ok = rest_keepalive_loop(Socket, 100),
  584. ok = gen_tcp:close(Socket).
  585. rest_keepalive_loop(_Socket, 0) ->
  586. ok;
  587. rest_keepalive_loop(Socket, N) ->
  588. ok = gen_tcp:send(Socket, "GET /simple HTTP/1.1\r\n"
  589. "Host: localhost\r\nConnection: keep-alive\r\n\r\n"),
  590. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  591. {0, 12} = binary:match(Data, <<"HTTP/1.1 200">>),
  592. nomatch = binary:match(Data, <<"Connection: close">>),
  593. rest_keepalive_loop(Socket, N - 1).
  594. rest_keepalive_post(Config) ->
  595. {port, Port} = lists:keyfind(port, 1, Config),
  596. {ok, Socket} = gen_tcp:connect("localhost", Port,
  597. [binary, {active, false}, {packet, raw}]),
  598. ok = rest_keepalive_post_loop(Socket, 10, forbidden_post),
  599. ok = gen_tcp:close(Socket).
  600. rest_keepalive_post_loop(_Socket, 0, _) ->
  601. ok;
  602. rest_keepalive_post_loop(Socket, N, simple_post) ->
  603. ok = gen_tcp:send(Socket, "POST /simple_post HTTP/1.1\r\n"
  604. "Host: localhost\r\nConnection: keep-alive\r\n"
  605. "Content-Length: 5\r\nContent-Type: text/plain\r\n\r\n12345"),
  606. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  607. {0, 12} = binary:match(Data, <<"HTTP/1.1 303">>),
  608. nomatch = binary:match(Data, <<"Connection: close">>),
  609. rest_keepalive_post_loop(Socket, N - 1, forbidden_post);
  610. rest_keepalive_post_loop(Socket, N, forbidden_post) ->
  611. ok = gen_tcp:send(Socket, "POST /forbidden_post HTTP/1.1\r\n"
  612. "Host: localhost\r\nConnection: keep-alive\r\n"
  613. "Content-Length: 5\r\nContent-Type: text/plain\r\n\r\n12345"),
  614. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  615. {0, 12} = binary:match(Data, <<"HTTP/1.1 403">>),
  616. nomatch = binary:match(Data, <<"Connection: close">>),
  617. rest_keepalive_post_loop(Socket, N - 1, simple_post).
  618. rest_nodelete(Config) ->
  619. {port, Port} = lists:keyfind(port, 1, Config),
  620. {ok, Socket} = gen_tcp:connect("localhost", Port,
  621. [binary, {active, false}, {packet, raw}]),
  622. Request = "DELETE /nodelete HTTP/1.1\r\nHost: localhost\r\n\r\n",
  623. ok = gen_tcp:send(Socket, Request),
  624. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  625. {0, 12} = binary:match(Data, <<"HTTP/1.1 500">>),
  626. ok = gen_tcp:close(Socket).
  627. rest_resource_etags(Config) ->
  628. %% The Etag header should be set to the return value of generate_etag/2.
  629. fun() ->
  630. %% Correct return values from generate_etag/2.
  631. {Packet1, 200} = raw_resp([
  632. "GET /resetags?type=tuple-weak HTTP/1.1\r\n",
  633. "Host: localhost\r\n", "Connection: close\r\n", "\r\n"], Config),
  634. {_,_} = binary:match(Packet1, <<"ETag: W/\"etag-header-value\"\r\n">>),
  635. {Packet2, 200} = raw_resp([
  636. "GET /resetags?type=tuple-strong HTTP/1.1\r\n",
  637. "Host: localhost\r\n", "Connection: close\r\n", "\r\n"], Config),
  638. {_,_} = binary:match(Packet2, <<"ETag: \"etag-header-value\"\r\n">>),
  639. %% Backwards compatible return values from generate_etag/2.
  640. {Packet3, 200} = raw_resp([
  641. "GET /resetags?type=binary-weak-quoted HTTP/1.1\r\n",
  642. "Host: localhost\r\n", "Connection: close\r\n", "\r\n"], Config),
  643. {_,_} = binary:match(Packet3, <<"ETag: W/\"etag-header-value\"\r\n">>),
  644. {Packet4, 200} = raw_resp([
  645. "GET /resetags?type=binary-strong-quoted HTTP/1.1\r\n",
  646. "Host: localhost\r\n", "Connection: close\r\n", "\r\n"], Config),
  647. {_,_} = binary:match(Packet4, <<"ETag: \"etag-header-value\"\r\n">>),
  648. %% Invalid return values from generate_etag/2.
  649. {_Packet5, 500} = raw_resp([
  650. "GET /resetags?type=binary-strong-unquoted HTTP/1.1\r\n",
  651. "Host: localhost\r\n", "Connection: close\r\n", "\r\n"], Config),
  652. {_Packet6, 500} = raw_resp([
  653. "GET /resetags?type=binary-weak-unquoted HTTP/1.1\r\n",
  654. "Host: localhost\r\n", "Connection: close\r\n", "\r\n"], Config)
  655. end(),
  656. %% The return value of generate_etag/2 should match the request header.
  657. fun() ->
  658. %% Correct return values from generate_etag/2.
  659. {_Packet1, 304} = raw_resp([
  660. "GET /resetags?type=tuple-weak HTTP/1.1\r\n",
  661. "Host: localhost\r\n", "Connection: close\r\n",
  662. "If-None-Match: W/\"etag-header-value\"\r\n", "\r\n"], Config),
  663. {_Packet2, 304} = raw_resp([
  664. "GET /resetags?type=tuple-strong HTTP/1.1\r\n",
  665. "Host: localhost\r\n", "Connection: close\r\n",
  666. "If-None-Match: \"etag-header-value\"\r\n", "\r\n"], Config),
  667. %% Backwards compatible return values from generate_etag/2.
  668. {_Packet3, 304} = raw_resp([
  669. "GET /resetags?type=binary-weak-quoted HTTP/1.1\r\n",
  670. "Host: localhost\r\n", "Connection: close\r\n",
  671. "If-None-Match: W/\"etag-header-value\"\r\n", "\r\n"], Config),
  672. {_Packet4, 304} = raw_resp([
  673. "GET /resetags?type=binary-strong-quoted HTTP/1.1\r\n",
  674. "Host: localhost\r\n", "Connection: close\r\n",
  675. "If-None-Match: \"etag-header-value\"\r\n", "\r\n"], Config)
  676. end().
  677. onrequest(Config) ->
  678. {port, Port} = lists:keyfind(port, 1, Config),
  679. {ok, Socket} = gen_tcp:connect("localhost", Port,
  680. [binary, {active, false}, {packet, raw}]),
  681. ok = gen_tcp:send(Socket, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"),
  682. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  683. {_, _} = binary:match(Data, <<"Server: Serenity">>),
  684. {_, _} = binary:match(Data, <<"http_handler">>),
  685. gen_tcp:close(Socket).
  686. onrequest_reply(Config) ->
  687. {port, Port} = lists:keyfind(port, 1, Config),
  688. {ok, Socket} = gen_tcp:connect("localhost", Port,
  689. [binary, {active, false}, {packet, raw}]),
  690. ok = gen_tcp:send(Socket, "GET /?reply=1 HTTP/1.1\r\nHost: localhost\r\n\r\n"),
  691. {ok, Data} = gen_tcp:recv(Socket, 0, 6000),
  692. {_, _} = binary:match(Data, <<"Server: Cowboy">>),
  693. nomatch = binary:match(Data, <<"http_handler">>),
  694. {_, _} = binary:match(Data, <<"replied!">>),
  695. gen_tcp:close(Socket).
  696. onrequest_hook(Req) ->
  697. case cowboy_http_req:qs_val(<<"reply">>, Req) of
  698. {undefined, Req2} ->
  699. {ok, Req3} = cowboy_http_req:set_resp_header(
  700. 'Server', <<"Serenity">>, Req2),
  701. Req3;
  702. {_, Req2} ->
  703. {ok, Req3} = cowboy_http_req:reply(
  704. 200, [], <<"replied!">>, Req2),
  705. Req3
  706. end.