cowboy_http_protocol.erl 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.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(cowboy_http_protocol).
  15. -export([start_link/3]). %% API.
  16. -export([init/3]). %% FSM.
  17. -include("include/types.hrl").
  18. -include("include/http.hrl").
  19. -record(state, {
  20. socket :: socket(),
  21. transport :: module(),
  22. dispatch :: dispatch(),
  23. handler :: {Handler::module(), Opts::term()},
  24. timeout :: timeout(),
  25. connection = keepalive :: keepalive | close
  26. }).
  27. %% API.
  28. -spec start_link(Socket::socket(), Transport::module(), Opts::term())
  29. -> {ok, Pid::pid()}.
  30. start_link(Socket, Transport, Opts) ->
  31. Pid = spawn_link(?MODULE, init, [Socket, Transport, Opts]),
  32. {ok, Pid}.
  33. %% FSM.
  34. -spec init(Socket::socket(), Transport::module(), Opts::term())
  35. -> ok | {error, no_ammo}.
  36. init(Socket, Transport, Opts) ->
  37. Dispatch = proplists:get_value(dispatch, Opts, []),
  38. Timeout = proplists:get_value(timeout, Opts, 5000),
  39. wait_request(#state{socket=Socket, transport=Transport,
  40. dispatch=Dispatch, timeout=Timeout}).
  41. -spec wait_request(State::#state{}) -> ok.
  42. wait_request(State=#state{socket=Socket, transport=Transport, timeout=T}) ->
  43. Transport:setopts(Socket, [{packet, http}]),
  44. case Transport:recv(Socket, 0, T) of
  45. {ok, Request} -> request(Request, State);
  46. {error, timeout} -> error_terminate(408, State);
  47. {error, closed} -> terminate(State)
  48. end.
  49. -spec request({http_request, Method::http_method(), URI::http_uri(),
  50. Version::http_version()}, State::#state{}) -> ok.
  51. %% @todo We probably want to handle some things differently between versions.
  52. request({http_request, _Method, _URI, Version}, State)
  53. when Version =/= {1, 0}, Version =/= {1, 1} ->
  54. error_terminate(505, State);
  55. %% @todo We need to cleanup the URI properly.
  56. request({http_request, Method, {abs_path, AbsPath}, Version},
  57. State=#state{socket=Socket, transport=Transport}) ->
  58. {Path, Qs} = cowboy_dispatcher:split_path(AbsPath),
  59. {ok, Peer} = Transport:peername(Socket),
  60. wait_header(#http_req{method=Method, version=Version,
  61. peer=Peer, path=Path, raw_qs=Qs}, State).
  62. -spec wait_header(Req::#http_req{}, State::#state{}) -> ok.
  63. %% @todo We don't want to wait T at each header...
  64. %% We want to wait T total until we reach the body.
  65. wait_header(Req, State=#state{socket=Socket,
  66. transport=Transport, timeout=T}) ->
  67. case Transport:recv(Socket, 0, T) of
  68. {ok, Header} -> header(Header, Req, State);
  69. {error, timeout} -> error_terminate(408, State);
  70. {error, closed} -> terminate(State)
  71. end.
  72. -spec header({http_header, I::integer(), Field::http_header(), R::term(),
  73. Value::string()} | http_eoh, Req::#http_req{}, State::#state{}) -> ok.
  74. header({http_header, _I, 'Host', _R, Value}, Req=#http_req{path=Path},
  75. State=#state{dispatch=Dispatch}) ->
  76. Host = cowboy_dispatcher:split_host(Value),
  77. %% @todo We probably want to filter the Host and Path here to allow
  78. %% things like url rewriting.
  79. case cowboy_dispatcher:match(Host, Path, Dispatch) of
  80. {ok, Handler, Opts, Binds} ->
  81. wait_header(Req#http_req{host=Host, bindings=Binds,
  82. headers=[{'Host', Value}|Req#http_req.headers]},
  83. State#state{handler={Handler, Opts}});
  84. {error, notfound} ->
  85. error_terminate(404, State)
  86. end;
  87. header({http_header, _I, 'Connection', _R, Connection}, Req, State) ->
  88. wait_header(Req#http_req{
  89. headers=[{'Connection', Connection}|Req#http_req.headers]},
  90. State#state{connection=connection_to_atom(Connection)});
  91. header({http_header, _I, Field, _R, Value}, Req, State) ->
  92. wait_header(Req#http_req{headers=[{Field, Value}|Req#http_req.headers]},
  93. State);
  94. %% The Host header is required.
  95. header(http_eoh, #http_req{host=undefined}, State) ->
  96. error_terminate(400, State);
  97. header(http_eoh, Req, State) ->
  98. handler_init(Req, State).
  99. -spec handler_init(Req::#http_req{}, State::#state{}) -> ok.
  100. handler_init(Req, State=#state{handler={Handler, Opts}}) ->
  101. case Handler:init(Req, Opts) of
  102. {ok, Req, HandlerState} ->
  103. handler_loop(HandlerState, Req, State)
  104. %% @todo {mode, active}; {upgrade_protocol, Module}; {error, Reason}
  105. end.
  106. -spec handler_loop(HandlerState::term(), Req::#http_req{},
  107. State::#state{}) -> ok.
  108. handler_loop(HandlerState, Req, State=#state{handler={Handler, _Opts}}) ->
  109. case Handler:handle(Req, HandlerState) of
  110. %% @todo {ok, HandlerState}; {mode, active}
  111. %% @todo Move the reply code to the cowboy_http_req module.
  112. {reply, RCode, RHeaders, RBody} ->
  113. reply(RCode, RHeaders, RBody, State)
  114. end.
  115. -spec error_terminate(Code::http_status(), State::#state{}) -> ok.
  116. error_terminate(Code, State) ->
  117. reply(Code, [], [], State#state{connection=close}).
  118. -spec terminate(State::#state{}) -> ok.
  119. terminate(#state{socket=Socket, transport=Transport}) ->
  120. Transport:close(Socket),
  121. ok.
  122. -spec reply(Code::http_status(), Headers::http_headers(), Body::iolist(),
  123. State::#state{}) -> ok.
  124. %% @todo Don't be naive about the headers!
  125. reply(Code, Headers, Body, State=#state{socket=Socket,
  126. transport=TransportMod, connection=Connection}) ->
  127. StatusLine = ["HTTP/1.1 ", status(Code), "\r\n"],
  128. BaseHeaders = ["Connection: ", atom_to_connection(Connection),
  129. "\r\nContent-Length: ", integer_to_list(iolist_size(Body)), "\r\n"],
  130. TransportMod:send(Socket,
  131. [StatusLine, BaseHeaders, Headers, "\r\n", Body]),
  132. next_request(State).
  133. -spec next_request(State::#state{}) -> ok.
  134. next_request(State=#state{connection=keepalive}) ->
  135. wait_request(State);
  136. next_request(State=#state{connection=close}) ->
  137. terminate(State).
  138. %% Internal.
  139. -spec connection_to_atom(Connection::string()) -> keepalive | close.
  140. connection_to_atom(Connection) ->
  141. case string:to_lower(Connection) of
  142. "close" -> close;
  143. _Any -> keepalive
  144. end.
  145. -spec atom_to_connection(Atom::keepalive | close) -> string().
  146. atom_to_connection(keepalive) ->
  147. "keep-alive";
  148. atom_to_connection(close) ->
  149. "close".
  150. -spec status(Code::http_status()) -> string().
  151. status(100) -> "100 Continue";
  152. status(101) -> "101 Switching Protocols";
  153. status(102) -> "102 Processing";
  154. status(200) -> "200 OK";
  155. status(201) -> "201 Created";
  156. status(202) -> "202 Accepted";
  157. status(203) -> "203 Non-Authoritative Information";
  158. status(204) -> "204 No Content";
  159. status(205) -> "205 Reset Content";
  160. status(206) -> "206 Partial Content";
  161. status(207) -> "207 Multi-Status";
  162. status(226) -> "226 IM Used";
  163. status(300) -> "300 Multiple Choices";
  164. status(301) -> "301 Moved Permanently";
  165. status(302) -> "302 Found";
  166. status(303) -> "303 See Other";
  167. status(304) -> "304 Not Modified";
  168. status(305) -> "305 Use Proxy";
  169. status(306) -> "306 Switch Proxy";
  170. status(307) -> "307 Temporary Redirect";
  171. status(400) -> "400 Bad Request";
  172. status(401) -> "401 Unauthorized";
  173. status(402) -> "402 Payment Required";
  174. status(403) -> "403 Forbidden";
  175. status(404) -> "404 Not Found";
  176. status(405) -> "405 Method Not Allowed";
  177. status(406) -> "406 Not Acceptable";
  178. status(407) -> "407 Proxy Authentication Required";
  179. status(408) -> "408 Request Timeout";
  180. status(409) -> "409 Conflict";
  181. status(410) -> "410 Gone";
  182. status(411) -> "411 Length Required";
  183. status(412) -> "412 Precondition Failed";
  184. status(413) -> "413 Request Entity Too Large";
  185. status(414) -> "414 Request-URI Too Long";
  186. status(415) -> "415 Unsupported Media Type";
  187. status(416) -> "416 Requested Range Not Satisfiable";
  188. status(417) -> "417 Expectation Failed";
  189. status(418) -> "418 I'm a teapot";
  190. status(422) -> "422 Unprocessable Entity";
  191. status(423) -> "423 Locked";
  192. status(424) -> "424 Failed Dependency";
  193. status(425) -> "425 Unordered Collection";
  194. status(426) -> "426 Upgrade Required";
  195. status(500) -> "500 Internal Server Error";
  196. status(501) -> "501 Not Implemented";
  197. status(502) -> "502 Bad Gateway";
  198. status(503) -> "503 Service Unavailable";
  199. status(504) -> "504 Gateway Timeout";
  200. status(505) -> "505 HTTP Version Not Supported";
  201. status(506) -> "506 Variant Also Negotiates";
  202. status(507) -> "507 Insufficient Storage";
  203. status(510) -> "510 Not Extended";
  204. status(L) when is_list(L) -> L.