cowboy_http_req.erl 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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(cowboy_http_req).
  16. -export([
  17. method/1, version/1, peer/1,
  18. host/1, raw_host/1,
  19. path/1, raw_path/1,
  20. qs_val/2, qs_val/3, qs_vals/1, raw_qs/1,
  21. binding/2, binding/3, bindings/1,
  22. header/2, header/3, headers/1
  23. %% cookie/2, cookie/3, cookies/1 @todo
  24. ]). %% Request API.
  25. -export([
  26. body/1, body/2, body_qs/1
  27. ]). %% Request Body API.
  28. -export([
  29. reply/4
  30. ]). %% Response API.
  31. -include("include/types.hrl").
  32. -include("include/http.hrl").
  33. -include_lib("eunit/include/eunit.hrl").
  34. %% Request API.
  35. -spec method(Req::#http_req{}) -> {Method::http_method(), Req::#http_req{}}.
  36. method(Req) ->
  37. {Req#http_req.method, Req}.
  38. -spec version(Req::#http_req{}) -> {Version::http_version(), Req::#http_req{}}.
  39. version(Req) ->
  40. {Req#http_req.version, Req}.
  41. -spec peer(Req::#http_req{})
  42. -> {{Address::ip_address(), Port::port_number()}, Req::#http_req{}}.
  43. peer(Req=#http_req{socket=Socket, transport=Transport, peer=undefined}) ->
  44. {ok, Peer} = Transport:peername(Socket),
  45. {Peer, Req#http_req{peer=Peer}};
  46. peer(Req) ->
  47. {Req#http_req.peer, Req}.
  48. -spec host(Req::#http_req{}) -> {Host::path_tokens(), Req::#http_req{}}.
  49. host(Req) ->
  50. {Req#http_req.host, Req}.
  51. -spec raw_host(Req::#http_req{}) -> {RawHost::string(), Req::#http_req{}}.
  52. raw_host(Req) ->
  53. {Req#http_req.raw_host, Req}.
  54. -spec path(Req::#http_req{}) -> {Path::path_tokens(), Req::#http_req{}}.
  55. path(Req) ->
  56. {Req#http_req.path, Req}.
  57. -spec raw_path(Req::#http_req{}) -> {RawPath::string(), Req::#http_req{}}.
  58. raw_path(Req) ->
  59. {Req#http_req.raw_path, Req}.
  60. -spec qs_val(Name::string(), Req::#http_req{})
  61. -> {Value::string() | true | undefined, Req::#http_req{}}.
  62. %% @equiv qs_val(Name, Req) -> qs_val(Name, Req, undefined)
  63. qs_val(Name, Req) ->
  64. qs_val(Name, Req, undefined).
  65. -spec qs_val(Name::string(), Req::#http_req{}, Default)
  66. -> {Value::string() | true | Default, Req::#http_req{}}
  67. when Default::term().
  68. qs_val(Name, Req=#http_req{raw_qs=RawQs, qs_vals=undefined}, Default) ->
  69. QsVals = parse_qs(RawQs),
  70. qs_val(Name, Req#http_req{qs_vals=QsVals}, Default);
  71. qs_val(Name, Req, Default) ->
  72. case lists:keyfind(Name, 1, Req#http_req.qs_vals) of
  73. {Name, Value} -> {Value, Req};
  74. false -> {Default, Req}
  75. end.
  76. -spec qs_vals(Req::#http_req{})
  77. -> {list({Name::string(), Value::string() | true}), Req::#http_req{}}.
  78. qs_vals(Req=#http_req{raw_qs=RawQs, qs_vals=undefined}) ->
  79. QsVals = parse_qs(RawQs),
  80. qs_vals(Req#http_req{qs_vals=QsVals});
  81. qs_vals(Req=#http_req{qs_vals=QsVals}) ->
  82. {QsVals, Req}.
  83. -spec raw_qs(Req::#http_req{}) -> {RawQs::string(), Req::#http_req{}}.
  84. raw_qs(Req) ->
  85. {Req#http_req.raw_qs, Req}.
  86. -spec binding(Name::atom(), Req::#http_req{})
  87. -> {Value::string() | undefined, Req::#http_req{}}.
  88. %% @equiv binding(Name, Req) -> binding(Name, Req, undefined)
  89. binding(Name, Req) ->
  90. binding(Name, Req, undefined).
  91. -spec binding(Name::atom(), Req::#http_req{}, Default)
  92. -> {Value::string() | Default, Req::#http_req{}} when Default::term().
  93. binding(Name, Req, Default) ->
  94. case lists:keyfind(Name, 1, Req#http_req.bindings) of
  95. {Name, Value} -> {Value, Req};
  96. false -> {Default, Req}
  97. end.
  98. -spec bindings(Req::#http_req{})
  99. -> {list({Name::atom(), Value::string()}), Req::#http_req{}}.
  100. bindings(Req) ->
  101. {Req#http_req.bindings, Req}.
  102. -spec header(Name::atom() | string(), Req::#http_req{})
  103. -> {Value::string() | undefined, Req::#http_req{}}.
  104. %% @equiv header(Name, Req) -> header(Name, Req, undefined)
  105. header(Name, Req) ->
  106. header(Name, Req, undefined).
  107. -spec header(Name::atom() | string(), Req::#http_req{}, Default)
  108. -> {Value::string() | Default, Req::#http_req{}} when Default::term().
  109. header(Name, Req, Default) ->
  110. case lists:keyfind(Name, 1, Req#http_req.headers) of
  111. {Name, Value} -> {Value, Req};
  112. false -> {Default, Req}
  113. end.
  114. -spec headers(Req::#http_req{})
  115. -> {list({Name::atom() | string(), Value::string()}), Req::#http_req{}}.
  116. headers(Req) ->
  117. {Req#http_req.headers, Req}.
  118. %% Request Body API.
  119. %% @todo We probably want to allow a max length.
  120. -spec body(Req::#http_req{})
  121. -> {ok, Body::binary(), Req::#http_req{}} | {error, Reason::posix()}.
  122. body(Req) ->
  123. {Length, Req2} = cowboy_http_req:header('Content-Length', Req),
  124. case Length of
  125. undefined -> {error, badarg};
  126. _Any ->
  127. Length2 = list_to_integer(Length),
  128. body(Length2, Req2)
  129. end.
  130. %% @todo We probably want to configure the timeout.
  131. -spec body(Length::non_neg_integer(), Req::#http_req{})
  132. -> {ok, Body::binary(), Req::#http_req{}} | {error, Reason::posix()}.
  133. body(Length, Req=#http_req{socket=Socket, transport=Transport,
  134. body_state=waiting}) ->
  135. Transport:setopts(Socket, [{packet, raw}]),
  136. case Transport:recv(Socket, Length, 5000) of
  137. {ok, Body} -> {ok, Body, Req#http_req{body_state=done}};
  138. {error, Reason} -> {error, Reason}
  139. end.
  140. -spec body_qs(Req::#http_req{})
  141. -> {list({Name::string(), Value::string() | true}), Req::#http_req{}}.
  142. body_qs(Req) ->
  143. {ok, Body, Req2} = body(Req),
  144. {parse_qs(binary_to_list(Body)), Req2}.
  145. %% Response API.
  146. -spec reply(Code::http_status(), Headers::http_headers(),
  147. Body::iolist(), Req::#http_req{}) -> {ok, Req::#http_req{}}.
  148. reply(Code, Headers, Body, Req=#http_req{socket=Socket,
  149. transport=Transport, connection=Connection,
  150. resp_state=waiting}) ->
  151. StatusLine = ["HTTP/1.1 ", status(Code), "\r\n"],
  152. DefaultHeaders = [
  153. {"Connection", atom_to_connection(Connection)},
  154. {"Content-Length", integer_to_list(iolist_size(Body))}
  155. ],
  156. Headers2 = lists:keysort(1, Headers),
  157. Headers3 = lists:ukeymerge(1, Headers2, DefaultHeaders),
  158. Headers4 = [[Key, ": ", Value, "\r\n"] || {Key, Value} <- Headers3],
  159. Transport:send(Socket, [StatusLine, Headers4, "\r\n", Body]),
  160. {ok, Req#http_req{resp_state=done}}.
  161. %% Internal.
  162. -spec parse_qs(Qs::string()) -> list({Name::string(), Value::string() | true}).
  163. parse_qs(Qs) ->
  164. Tokens = string:tokens(Qs, "&"),
  165. [case string:chr(Token, $=) of
  166. 0 ->
  167. {Token, true};
  168. N ->
  169. {Name, [$=|Value]} = lists:split(N - 1, Token),
  170. {Name, Value}
  171. end || Token <- Tokens].
  172. -spec atom_to_connection(Atom::keepalive | close) -> string().
  173. atom_to_connection(keepalive) ->
  174. "keep-alive";
  175. atom_to_connection(close) ->
  176. "close".
  177. -spec status(Code::http_status()) -> string().
  178. status(100) -> "100 Continue";
  179. status(101) -> "101 Switching Protocols";
  180. status(102) -> "102 Processing";
  181. status(200) -> "200 OK";
  182. status(201) -> "201 Created";
  183. status(202) -> "202 Accepted";
  184. status(203) -> "203 Non-Authoritative Information";
  185. status(204) -> "204 No Content";
  186. status(205) -> "205 Reset Content";
  187. status(206) -> "206 Partial Content";
  188. status(207) -> "207 Multi-Status";
  189. status(226) -> "226 IM Used";
  190. status(300) -> "300 Multiple Choices";
  191. status(301) -> "301 Moved Permanently";
  192. status(302) -> "302 Found";
  193. status(303) -> "303 See Other";
  194. status(304) -> "304 Not Modified";
  195. status(305) -> "305 Use Proxy";
  196. status(306) -> "306 Switch Proxy";
  197. status(307) -> "307 Temporary Redirect";
  198. status(400) -> "400 Bad Request";
  199. status(401) -> "401 Unauthorized";
  200. status(402) -> "402 Payment Required";
  201. status(403) -> "403 Forbidden";
  202. status(404) -> "404 Not Found";
  203. status(405) -> "405 Method Not Allowed";
  204. status(406) -> "406 Not Acceptable";
  205. status(407) -> "407 Proxy Authentication Required";
  206. status(408) -> "408 Request Timeout";
  207. status(409) -> "409 Conflict";
  208. status(410) -> "410 Gone";
  209. status(411) -> "411 Length Required";
  210. status(412) -> "412 Precondition Failed";
  211. status(413) -> "413 Request Entity Too Large";
  212. status(414) -> "414 Request-URI Too Long";
  213. status(415) -> "415 Unsupported Media Type";
  214. status(416) -> "416 Requested Range Not Satisfiable";
  215. status(417) -> "417 Expectation Failed";
  216. status(418) -> "418 I'm a teapot";
  217. status(422) -> "422 Unprocessable Entity";
  218. status(423) -> "423 Locked";
  219. status(424) -> "424 Failed Dependency";
  220. status(425) -> "425 Unordered Collection";
  221. status(426) -> "426 Upgrade Required";
  222. status(500) -> "500 Internal Server Error";
  223. status(501) -> "501 Not Implemented";
  224. status(502) -> "502 Bad Gateway";
  225. status(503) -> "503 Service Unavailable";
  226. status(504) -> "504 Gateway Timeout";
  227. status(505) -> "505 HTTP Version Not Supported";
  228. status(506) -> "506 Variant Also Negotiates";
  229. status(507) -> "507 Insufficient Storage";
  230. status(510) -> "510 Not Extended";
  231. status(L) when is_list(L) -> L.
  232. %% Tests.
  233. -ifdef(TEST).
  234. parse_qs_test_() ->
  235. %% {Qs, Result}
  236. Tests = [
  237. {"", []},
  238. {"a=b", [{"a", "b"}]},
  239. {"aaa=bbb", [{"aaa", "bbb"}]},
  240. {"a&b", [{"a", true}, {"b", true}]},
  241. {"a=b&c&d=e", [{"a", "b"}, {"c", true}, {"d", "e"}]},
  242. {"a=b=c=d=e&f=g", [{"a", "b=c=d=e"}, {"f", "g"}]}
  243. ],
  244. [{Qs, fun() -> R = parse_qs(Qs) end} || {Qs, R} <- Tests].
  245. -endif.