cowboy_http_protocol.erl 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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, wait_request/1]). %% 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()) -> ok.
  35. init(Socket, Transport, Opts) ->
  36. Dispatch = proplists:get_value(dispatch, Opts, []),
  37. Timeout = proplists:get_value(timeout, Opts, 5000),
  38. wait_request(#state{socket=Socket, transport=Transport,
  39. dispatch=Dispatch, timeout=Timeout}).
  40. -spec wait_request(State::#state{}) -> ok.
  41. wait_request(State=#state{socket=Socket, transport=Transport, timeout=T}) ->
  42. Transport:setopts(Socket, [{packet, http}]),
  43. case Transport:recv(Socket, 0, T) of
  44. {ok, Request} -> request(Request, State);
  45. {error, timeout} -> error_terminate(408, State);
  46. {error, closed} -> terminate(State)
  47. end.
  48. -spec request({http_request, Method::http_method(), URI::http_uri(),
  49. Version::http_version()}, State::#state{}) -> ok.
  50. %% @todo We probably want to handle some things differently between versions.
  51. request({http_request, _Method, _URI, Version}, State)
  52. when Version =/= {1, 0}, Version =/= {1, 1} ->
  53. error_terminate(505, State);
  54. %% @todo We need to cleanup the URI properly.
  55. request({http_request, Method, {abs_path, AbsPath}, Version},
  56. State=#state{socket=Socket, transport=Transport}) ->
  57. {Path, RawPath, Qs} = cowboy_dispatcher:split_path(AbsPath),
  58. ConnAtom = version_to_connection(Version),
  59. wait_header(#http_req{socket=Socket, transport=Transport,
  60. connection=ConnAtom, method=Method, version=Version,
  61. path=Path, raw_path=RawPath, raw_qs=Qs}, State);
  62. request({http_request, Method, '*', Version},
  63. State=#state{socket=Socket, transport=Transport}) ->
  64. {ok, Peer} = Transport:peername(Socket),
  65. ConnAtom = version_to_connection(Version),
  66. wait_header(#http_req{socket=Socket, transport=Transport,
  67. connection=ConnAtom, method=Method, version=Version,
  68. peer=Peer, path='*', raw_path="*", raw_qs=[]}, State);
  69. request({http_request, _Method, _URI, _Version}, State) ->
  70. error_terminate(501, State);
  71. request({http_error, "\r\n"}, State) ->
  72. wait_request(State);
  73. request({http_error, _Any}, State) ->
  74. error_terminate(400, State).
  75. -spec wait_header(Req::#http_req{}, State::#state{}) -> ok.
  76. %% @todo We don't want to wait T at each header...
  77. %% We want to wait T total until we reach the body.
  78. wait_header(Req, State=#state{socket=Socket,
  79. transport=Transport, timeout=T}) ->
  80. case Transport:recv(Socket, 0, T) of
  81. {ok, Header} -> header(Header, Req, State);
  82. {error, timeout} -> error_terminate(408, State);
  83. {error, closed} -> terminate(State)
  84. end.
  85. -spec header({http_header, I::integer(), Field::http_header(), R::term(),
  86. Value::string()} | http_eoh, Req::#http_req{}, State::#state{}) -> ok.
  87. header({http_header, _I, 'Host', _R, RawHost}, Req=#http_req{path=Path,
  88. host=undefined}, State=#state{dispatch=Dispatch}) ->
  89. RawHost2 = string:to_lower(RawHost),
  90. Host = cowboy_dispatcher:split_host(RawHost2),
  91. %% @todo We probably want to filter the Host and Path here to allow
  92. %% things like url rewriting.
  93. case cowboy_dispatcher:match(Host, Path, Dispatch) of
  94. {ok, Handler, Opts, Binds} ->
  95. wait_header(Req#http_req{
  96. host=Host, raw_host=RawHost2, bindings=Binds,
  97. headers=[{'Host', RawHost2}|Req#http_req.headers]},
  98. State#state{handler={Handler, Opts}});
  99. {error, notfound, host} ->
  100. error_terminate(400, State);
  101. {error, notfound, path} ->
  102. error_terminate(404, State)
  103. end;
  104. %% Ignore Host headers if we already have it.
  105. header({http_header, _I, 'Host', _R, _V}, Req, State) ->
  106. wait_header(Req, State);
  107. header({http_header, _I, 'Connection', _R, Connection}, Req, State) ->
  108. ConnAtom = connection_to_atom(Connection),
  109. wait_header(Req#http_req{connection=ConnAtom,
  110. headers=[{'Connection', Connection}|Req#http_req.headers]},
  111. State#state{connection=ConnAtom});
  112. header({http_header, _I, Field, _R, Value}, Req, State) ->
  113. wait_header(Req#http_req{headers=[{Field, Value}|Req#http_req.headers]},
  114. State);
  115. %% The Host header is required.
  116. header(http_eoh, #http_req{host=undefined}, State) ->
  117. error_terminate(400, State);
  118. header(http_eoh, Req, State) ->
  119. handler_init(Req, State).
  120. -spec handler_init(Req::#http_req{}, State::#state{}) -> ok.
  121. handler_init(Req, State=#state{
  122. transport=Transport, handler={Handler, Opts}}) ->
  123. case catch Handler:init({Transport:name(), http}, Req, Opts) of
  124. {ok, Req, HandlerState} ->
  125. handler_loop(HandlerState, Req, State);
  126. %% @todo {upgrade, transport, Module}
  127. {upgrade, protocol, Module} ->
  128. Module:upgrade(Handler, Opts, Req);
  129. {'EXIT', _Reason} ->
  130. error_terminate(500, State)
  131. end.
  132. -spec handler_loop(HandlerState::term(), Req::#http_req{},
  133. State::#state{}) -> ok.
  134. handler_loop(HandlerState, Req, State=#state{handler={Handler, _Opts}}) ->
  135. case catch Handler:handle(Req#http_req{resp_state=waiting},
  136. HandlerState) of
  137. {ok, Req2, HandlerState2} ->
  138. handler_terminate(HandlerState2, Req2, State);
  139. {'EXIT', _Reason} ->
  140. terminate(State)
  141. end.
  142. -spec handler_terminate(HandlerState::term(), Req::#http_req{},
  143. State::#state{}) -> ok.
  144. handler_terminate(HandlerState, Req, State=#state{handler={Handler, _Opts}}) ->
  145. HandlerRes = (catch Handler:terminate(
  146. Req#http_req{resp_state=locked}, HandlerState)),
  147. BodyRes = ensure_body_processed(Req),
  148. ensure_response(Req, State),
  149. case {HandlerRes, BodyRes, State#state.connection} of
  150. {ok, ok, keepalive} -> next_request(State);
  151. _Closed -> terminate(State)
  152. end.
  153. -spec ensure_body_processed(Req::#http_req{}) -> ok | close.
  154. ensure_body_processed(#http_req{body_state=done}) ->
  155. ok;
  156. ensure_body_processed(Req=#http_req{body_state=waiting}) ->
  157. case cowboy_http_req:body(Req) of
  158. {error, badarg} -> ok; %% No body.
  159. {error, _Reason} -> close;
  160. _Any -> ok
  161. end.
  162. -spec ensure_response(Req::#http_req{}, State::#state{}) -> ok.
  163. %% The handler has already fully replied to the client.
  164. ensure_response(#http_req{resp_state=done}, _State) ->
  165. ok;
  166. %% No response has been sent but everything apparently went fine.
  167. %% Reply with 204 No Content to indicate this.
  168. ensure_response(#http_req{resp_state=waiting}, State) ->
  169. error_response(204, State).
  170. -spec error_response(Code::http_status(), State::#state{}) -> ok.
  171. error_response(Code, #state{socket=Socket,
  172. transport=Transport, connection=Connection}) ->
  173. _ = cowboy_http_req:reply(Code, [], [], #http_req{
  174. socket=Socket, transport=Transport,
  175. connection=Connection, resp_state=waiting}),
  176. ok.
  177. -spec error_terminate(Code::http_status(), State::#state{}) -> ok.
  178. error_terminate(Code, State) ->
  179. error_response(Code, State#state{connection=close}),
  180. terminate(State).
  181. -spec terminate(State::#state{}) -> ok.
  182. terminate(#state{socket=Socket, transport=Transport}) ->
  183. Transport:close(Socket),
  184. ok.
  185. -spec next_request(State::#state{}) -> ok.
  186. next_request(State=#state{connection=keepalive}) ->
  187. ?MODULE:wait_request(State);
  188. next_request(State=#state{connection=close}) ->
  189. terminate(State).
  190. %% Internal.
  191. -spec version_to_connection(Version::http_version()) -> keepalive | close.
  192. version_to_connection({1, 1}) -> keepalive;
  193. version_to_connection(_Any) -> close.
  194. -spec connection_to_atom(Connection::string()) -> keepalive | close.
  195. connection_to_atom("keep-alive") ->
  196. keepalive;
  197. connection_to_atom("close") ->
  198. close;
  199. connection_to_atom(Connection) ->
  200. case string:to_lower(Connection) of
  201. "close" -> close;
  202. _Any -> keepalive
  203. end.