cowboy_handler.erl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. %% Copyright (c) 2011-2013, Loïc Hoguin <essen@ninenines.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. %% @doc Handler middleware.
  15. %%
  16. %% Execute the handler given by the <em>handler</em> and <em>handler_opts</em>
  17. %% environment values. The result of this execution is added to the
  18. %% environment under the <em>result</em> value.
  19. %%
  20. %% When using loop handlers, we are receiving data from the socket because we
  21. %% want to know when the socket gets closed. This is generally not an issue
  22. %% because these kinds of requests are generally not pipelined, and don't have
  23. %% a body. If they do have a body, this body is often read in the
  24. %% <em>init/3</em> callback and this is no problem. Otherwise, this data
  25. %% accumulates in a buffer until we reach a certain threshold of 5000 bytes
  26. %% by default. This can be configured through the <em>loop_max_buffer</em>
  27. %% environment value. The request will be terminated with an
  28. %% <em>{error, overflow}</em> reason if this threshold is reached.
  29. %%
  30. %% @see cowboy_http_handler
  31. -module(cowboy_handler).
  32. -behaviour(cowboy_middleware).
  33. -export([execute/2]).
  34. -export([handler_loop/4]).
  35. -record(state, {
  36. env :: cowboy_middleware:env(),
  37. hibernate = false :: boolean(),
  38. loop_buffer_size = 0 :: non_neg_integer(),
  39. loop_max_buffer = 5000 :: non_neg_integer() | infinity,
  40. loop_timeout = infinity :: timeout(),
  41. loop_timeout_ref = undefined :: undefined | reference(),
  42. resp_sent = false :: boolean()
  43. }).
  44. %% @private
  45. -spec execute(Req, Env)
  46. -> {ok, Req, Env} | {error, 500, Req}
  47. | {suspend, ?MODULE, handler_loop, [any()]}
  48. when Req::cowboy_req:req(), Env::cowboy_middleware:env().
  49. execute(Req, Env) ->
  50. {_, Handler} = lists:keyfind(handler, 1, Env),
  51. {_, HandlerOpts} = lists:keyfind(handler_opts, 1, Env),
  52. case lists:keyfind(loop_max_buffer, 1, Env) of
  53. false -> MaxBuffer = 5000, ok;
  54. {_, MaxBuffer} -> ok
  55. end,
  56. handler_init(Req, #state{env=Env, loop_max_buffer=MaxBuffer},
  57. Handler, HandlerOpts).
  58. -spec handler_init(Req, #state{}, module(), any())
  59. -> {ok, Req, cowboy_middleware:env()}
  60. | {error, 500, Req} | {suspend, module(), function(), [any()]}
  61. when Req::cowboy_req:req().
  62. handler_init(Req, State, Handler, HandlerOpts) ->
  63. Transport = cowboy_req:get(transport, Req),
  64. try Handler:init({Transport:name(), http}, Req, HandlerOpts) of
  65. {ok, Req2, HandlerState} ->
  66. handler_handle(Req2, State, Handler, HandlerState);
  67. {loop, Req2, HandlerState} ->
  68. handler_before_loop(Req2, State, Handler, HandlerState);
  69. {loop, Req2, HandlerState, hibernate} ->
  70. handler_before_loop(Req2, State#state{hibernate=true},
  71. Handler, HandlerState);
  72. {loop, Req2, HandlerState, Timeout} ->
  73. State2 = handler_loop_timeout(State#state{loop_timeout=Timeout}),
  74. handler_before_loop(Req2, State2, Handler, HandlerState);
  75. {loop, Req2, HandlerState, Timeout, hibernate} ->
  76. State2 = handler_loop_timeout(State#state{
  77. hibernate=true, loop_timeout=Timeout}),
  78. handler_before_loop(Req2, State2, Handler, HandlerState);
  79. {shutdown, Req2, HandlerState} ->
  80. terminate_request(Req2, State, Handler, HandlerState,
  81. {normal, shutdown});
  82. %% @todo {upgrade, transport, Module}
  83. {upgrade, protocol, Module} ->
  84. upgrade_protocol(Req, State, Handler, HandlerOpts, Module);
  85. {upgrade, protocol, Module, Req2, HandlerOpts2} ->
  86. upgrade_protocol(Req2, State, Handler, HandlerOpts2, Module)
  87. catch Class:Reason ->
  88. error_logger:error_msg(
  89. "** Cowboy handler ~p terminating in ~p/~p~n"
  90. " for the reason ~p:~p~n"
  91. "** Options were ~p~n"
  92. "** Request was ~p~n"
  93. "** Stacktrace: ~p~n~n",
  94. [Handler, init, 3, Class, Reason, HandlerOpts,
  95. cowboy_req:to_list(Req), erlang:get_stacktrace()]),
  96. error_terminate(Req, State)
  97. end.
  98. -spec upgrade_protocol(Req, #state{}, module(), any(), module())
  99. -> {ok, Req, Env}
  100. | {suspend, module(), atom(), any()}
  101. | {halt, Req}
  102. | {error, cowboy_http:status(), Req}
  103. when Req::cowboy_req:req(), Env::cowboy_middleware:env().
  104. upgrade_protocol(Req, #state{env=Env},
  105. Handler, HandlerOpts, Module) ->
  106. Module:upgrade(Req, Env, Handler, HandlerOpts).
  107. -spec handler_handle(Req, #state{}, module(), any())
  108. -> {ok, Req, cowboy_middleware:env()}
  109. | {error, 500, Req}
  110. when Req::cowboy_req:req().
  111. handler_handle(Req, State, Handler, HandlerState) ->
  112. try Handler:handle(Req, HandlerState) of
  113. {ok, Req2, HandlerState2} ->
  114. terminate_request(Req2, State, Handler, HandlerState2,
  115. {normal, shutdown})
  116. catch Class:Reason ->
  117. error_logger:error_msg(
  118. "** Cowboy handler ~p terminating in ~p/~p~n"
  119. " for the reason ~p:~p~n"
  120. "** Handler state was ~p~n"
  121. "** Request was ~p~n"
  122. "** Stacktrace: ~p~n~n",
  123. [Handler, handle, 2, Class, Reason, HandlerState,
  124. cowboy_req:to_list(Req), erlang:get_stacktrace()]),
  125. handler_terminate(Req, Handler, HandlerState, Reason),
  126. error_terminate(Req, State)
  127. end.
  128. %% We don't listen for Transport closes because that would force us
  129. %% to receive data and buffer it indefinitely.
  130. -spec handler_before_loop(Req, #state{}, module(), any())
  131. -> {ok, Req, cowboy_middleware:env()}
  132. | {error, 500, Req} | {suspend, module(), function(), [any()]}
  133. when Req::cowboy_req:req().
  134. handler_before_loop(Req, State=#state{hibernate=true}, Handler, HandlerState) ->
  135. [Socket, Transport] = cowboy_req:get([socket, transport], Req),
  136. Transport:setopts(Socket, [{active, once}]),
  137. {suspend, ?MODULE, handler_loop,
  138. [Req, State#state{hibernate=false}, Handler, HandlerState]};
  139. handler_before_loop(Req, State, Handler, HandlerState) ->
  140. [Socket, Transport] = cowboy_req:get([socket, transport], Req),
  141. Transport:setopts(Socket, [{active, once}]),
  142. handler_loop(Req, State, Handler, HandlerState).
  143. %% Almost the same code can be found in cowboy_websocket.
  144. -spec handler_loop_timeout(#state{}) -> #state{}.
  145. handler_loop_timeout(State=#state{loop_timeout=infinity}) ->
  146. State#state{loop_timeout_ref=undefined};
  147. handler_loop_timeout(State=#state{loop_timeout=Timeout,
  148. loop_timeout_ref=PrevRef}) ->
  149. _ = case PrevRef of
  150. undefined -> ignore;
  151. PrevRef -> erlang:cancel_timer(PrevRef)
  152. end,
  153. TRef = erlang:start_timer(Timeout, self(), ?MODULE),
  154. State#state{loop_timeout_ref=TRef}.
  155. %% @private
  156. -spec handler_loop(Req, #state{}, module(), any())
  157. -> {ok, Req, cowboy_middleware:env()}
  158. | {error, 500, Req} | {suspend, module(), function(), [any()]}
  159. when Req::cowboy_req:req().
  160. handler_loop(Req, State=#state{loop_buffer_size=NbBytes,
  161. loop_max_buffer=Threshold, loop_timeout_ref=TRef},
  162. Handler, HandlerState) ->
  163. [Socket, Transport] = cowboy_req:get([socket, transport], Req),
  164. {OK, Closed, Error} = Transport:messages(),
  165. receive
  166. {OK, Socket, Data} ->
  167. NbBytes2 = NbBytes + byte_size(Data),
  168. if NbBytes2 > Threshold ->
  169. _ = handler_terminate(Req, Handler, HandlerState,
  170. {error, overflow}),
  171. error_terminate(Req, State);
  172. true ->
  173. Req2 = cowboy_req:append_buffer(Data, Req),
  174. State2 = handler_loop_timeout(State#state{
  175. loop_buffer_size=NbBytes2}),
  176. handler_loop(Req2, State2, Handler, HandlerState)
  177. end;
  178. {Closed, Socket} ->
  179. terminate_request(Req, State, Handler, HandlerState,
  180. {error, closed});
  181. {Error, Socket, Reason} ->
  182. terminate_request(Req, State, Handler, HandlerState,
  183. {error, Reason});
  184. {cowboy_req, resp_sent} ->
  185. handler_before_loop(Req, State#state{resp_sent=true},
  186. Handler, HandlerState);
  187. {timeout, TRef, ?MODULE} ->
  188. handler_after_loop(Req, State, Handler, HandlerState,
  189. {normal, timeout});
  190. {timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) ->
  191. handler_before_loop(Req, State, Handler, HandlerState);
  192. Message ->
  193. handler_call(Req, State, Handler, HandlerState, Message)
  194. end.
  195. -spec handler_call(Req, #state{}, module(), any(), any())
  196. -> {ok, Req, cowboy_middleware:env()}
  197. | {error, 500, Req} | {suspend, module(), function(), [any()]}
  198. when Req::cowboy_req:req().
  199. handler_call(Req, State, Handler, HandlerState, Message) ->
  200. try Handler:info(Message, Req, HandlerState) of
  201. {ok, Req2, HandlerState2} ->
  202. handler_after_loop(Req2, State, Handler, HandlerState2,
  203. {normal, shutdown});
  204. {loop, Req2, HandlerState2} ->
  205. handler_before_loop(Req2, State, Handler, HandlerState2);
  206. {loop, Req2, HandlerState2, hibernate} ->
  207. handler_before_loop(Req2, State#state{hibernate=true},
  208. Handler, HandlerState2)
  209. catch Class:Reason ->
  210. error_logger:error_msg(
  211. "** Cowboy handler ~p terminating in ~p/~p~n"
  212. " for the reason ~p:~p~n"
  213. "** Handler state was ~p~n"
  214. "** Request was ~p~n"
  215. "** Stacktrace: ~p~n~n",
  216. [Handler, info, 3, Class, Reason, HandlerState,
  217. cowboy_req:to_list(Req), erlang:get_stacktrace()]),
  218. handler_terminate(Req, Handler, HandlerState, Reason),
  219. error_terminate(Req, State)
  220. end.
  221. %% It is sometimes important to make a socket passive as it was initially
  222. %% and as it is expected to be by cowboy_protocol, right after we're done
  223. %% with loop handling. The browser may freely pipeline a bunch of requests
  224. %% if previous one was, say, a JSONP long-polling request.
  225. -spec handler_after_loop(Req, #state{}, module(), any(),
  226. {normal, timeout | shutdown} | {error, atom()}) ->
  227. {ok, Req, cowboy_middleware:env()} when Req::cowboy_req:req().
  228. handler_after_loop(Req, State, Handler, HandlerState, Reason) ->
  229. [Socket, Transport] = cowboy_req:get([socket, transport], Req),
  230. Transport:setopts(Socket, [{active, false}]),
  231. {OK, _Closed, _Error} = Transport:messages(),
  232. Req2 = receive
  233. {OK, Socket, Data} ->
  234. cowboy_req:append_buffer(Data, Req)
  235. after 0 ->
  236. Req
  237. end,
  238. terminate_request(Req2, State, Handler, HandlerState, Reason).
  239. -spec terminate_request(Req, #state{}, module(), any(),
  240. {normal, timeout | shutdown} | {error, atom()}) ->
  241. {ok, Req, cowboy_middleware:env()} when Req::cowboy_req:req().
  242. terminate_request(Req, #state{env=Env}, Handler, HandlerState, Reason) ->
  243. HandlerRes = handler_terminate(Req, Handler, HandlerState, Reason),
  244. {ok, Req, [{result, HandlerRes}|Env]}.
  245. -spec handler_terminate(cowboy_req:req(), module(), any(),
  246. {normal, timeout | shutdown} | {error, atom()}) -> ok.
  247. handler_terminate(Req, Handler, HandlerState, Reason) ->
  248. try
  249. Handler:terminate(Reason, cowboy_req:lock(Req), HandlerState)
  250. catch Class:Reason2 ->
  251. error_logger:error_msg(
  252. "** Cowboy handler ~p terminating in ~p/~p~n"
  253. " for the reason ~p:~p~n"
  254. "** Handler state was ~p~n"
  255. "** Request was ~p~n"
  256. "** Stacktrace: ~p~n~n",
  257. [Handler, terminate, 3, Class, Reason2, HandlerState,
  258. cowboy_req:to_list(Req), erlang:get_stacktrace()])
  259. end.
  260. %% Only send an error reply if there is no resp_sent message.
  261. -spec error_terminate(Req, #state{})
  262. -> {error, 500, Req} | {halt, Req} when Req::cowboy_req:req().
  263. error_terminate(Req, #state{resp_sent=true}) ->
  264. %% Close the connection, but do not attempt sending a reply.
  265. {halt, cowboy_req:set([{connection, close}, {resp_state, done}], Req)};
  266. error_terminate(Req, _) ->
  267. {error, 500, Req}.