cowboy_http_protocol.erl 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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_loop(Req, State).
  99. -spec handler_loop(Req::#http_req{}, State::#state{}) -> ok.
  100. handler_loop(Req, State=#state{handler={Handler, Opts}}) ->
  101. case Handler:handle(Opts, Req) of
  102. {reply, RCode, RHeaders, RBody} ->
  103. reply(RCode, RHeaders, RBody, State)
  104. %% @todo stream_reply, request_body, stream_request_body...
  105. end.
  106. -spec error_terminate(Code::http_status(), State::#state{}) -> ok.
  107. error_terminate(Code, State) ->
  108. reply(Code, [], [], State#state{connection=close}).
  109. -spec terminate(State::#state{}) -> ok.
  110. terminate(#state{socket=Socket, transport=Transport}) ->
  111. Transport:close(Socket),
  112. ok.
  113. -spec reply(Code::http_status(), Headers::http_headers(), Body::iolist(),
  114. State::#state{}) -> ok.
  115. %% @todo Don't be naive about the headers!
  116. reply(Code, Headers, Body, State=#state{socket=Socket,
  117. transport=TransportMod, connection=Connection}) ->
  118. StatusLine = ["HTTP/1.1 ", status(Code), "\r\n"],
  119. BaseHeaders = ["Connection: ", atom_to_connection(Connection),
  120. "\r\nContent-Length: ", integer_to_list(iolist_size(Body)), "\r\n"],
  121. TransportMod:send(Socket,
  122. [StatusLine, BaseHeaders, Headers, "\r\n", Body]),
  123. next_request(State).
  124. -spec next_request(State::#state{}) -> ok.
  125. next_request(State=#state{connection=keepalive}) ->
  126. wait_request(State);
  127. next_request(State=#state{connection=close}) ->
  128. terminate(State).
  129. %% Internal.
  130. -spec connection_to_atom(Connection::string()) -> keepalive | close.
  131. connection_to_atom(Connection) ->
  132. case string:to_lower(Connection) of
  133. "close" -> close;
  134. _Any -> keepalive
  135. end.
  136. -spec atom_to_connection(Atom::keepalive | close) -> string().
  137. atom_to_connection(keepalive) ->
  138. "keep-alive";
  139. atom_to_connection(close) ->
  140. "close".
  141. -spec status(Code::http_status()) -> string().
  142. status(100) -> "100 Continue";
  143. status(101) -> "101 Switching Protocols";
  144. status(102) -> "102 Processing";
  145. status(200) -> "200 OK";
  146. status(201) -> "201 Created";
  147. status(202) -> "202 Accepted";
  148. status(203) -> "203 Non-Authoritative Information";
  149. status(204) -> "204 No Content";
  150. status(205) -> "205 Reset Content";
  151. status(206) -> "206 Partial Content";
  152. status(207) -> "207 Multi-Status";
  153. status(226) -> "226 IM Used";
  154. status(300) -> "300 Multiple Choices";
  155. status(301) -> "301 Moved Permanently";
  156. status(302) -> "302 Found";
  157. status(303) -> "303 See Other";
  158. status(304) -> "304 Not Modified";
  159. status(305) -> "305 Use Proxy";
  160. status(306) -> "306 Switch Proxy";
  161. status(307) -> "307 Temporary Redirect";
  162. status(400) -> "400 Bad Request";
  163. status(401) -> "401 Unauthorized";
  164. status(402) -> "402 Payment Required";
  165. status(403) -> "403 Forbidden";
  166. status(404) -> "404 Not Found";
  167. status(405) -> "405 Method Not Allowed";
  168. status(406) -> "406 Not Acceptable";
  169. status(407) -> "407 Proxy Authentication Required";
  170. status(408) -> "408 Request Timeout";
  171. status(409) -> "409 Conflict";
  172. status(410) -> "410 Gone";
  173. status(411) -> "411 Length Required";
  174. status(412) -> "412 Precondition Failed";
  175. status(413) -> "413 Request Entity Too Large";
  176. status(414) -> "414 Request-URI Too Long";
  177. status(415) -> "415 Unsupported Media Type";
  178. status(416) -> "416 Requested Range Not Satisfiable";
  179. status(417) -> "417 Expectation Failed";
  180. status(418) -> "418 I'm a teapot";
  181. status(422) -> "422 Unprocessable Entity";
  182. status(423) -> "423 Locked";
  183. status(424) -> "424 Failed Dependency";
  184. status(425) -> "425 Unordered Collection";
  185. status(426) -> "426 Upgrade Required";
  186. status(500) -> "500 Internal Server Error";
  187. status(501) -> "501 Not Implemented";
  188. status(502) -> "502 Bad Gateway";
  189. status(503) -> "503 Service Unavailable";
  190. status(504) -> "504 Gateway Timeout";
  191. status(505) -> "505 HTTP Version Not Supported";
  192. status(506) -> "506 Variant Also Negotiates";
  193. status(507) -> "507 Insufficient Storage";
  194. status(510) -> "510 Not Extended";
  195. status(L) when is_list(L) -> L.