cowboy_http_protocol.erl 8.5 KB

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