cowboy_protocol.erl 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. %% Copyright (c) 2011-2012, Loïc Hoguin <essen@ninenines.eu>
  2. %% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. %% @doc HTTP protocol handler.
  16. %%
  17. %% The available options are:
  18. %% <dl>
  19. %% <dt>dispatch</dt><dd>The dispatch list for this protocol.</dd>
  20. %% <dt>max_empty_lines</dt><dd>Max number of empty lines before a request.
  21. %% Defaults to 5.</dd>
  22. %% <dt>max_header_name_length</dt><dd>Max length allowed for header names.
  23. %% Defaults to 64.</dd>
  24. %% <dt>max_header_value_length</dt><dd>Max length allowed for header values.
  25. %% Defaults to 4096.</dd>
  26. %% <dt>max_keepalive</dt><dd>Max number of requests allowed in a single
  27. %% keep-alive session. Defaults to infinity.</dd>
  28. %% <dt>max_request_line_length</dt><dd>Max length allowed for the request
  29. %% line. Defaults to 4096.</dd>
  30. %% <dt>onrequest</dt><dd>Optional fun that allows Req interaction before
  31. %% any dispatching is done. Host info, path info and bindings are thus
  32. %% not available at this point.</dd>
  33. %% <dt>onresponse</dt><dd>Optional fun that allows replacing a response
  34. %% sent by the application based on its status code or headers.</dd>
  35. %% <dt>timeout</dt><dd>Time in milliseconds before an idle
  36. %% connection is closed. Defaults to 5000 milliseconds.</dd>
  37. %% </dl>
  38. %%
  39. %% Note that there is no need to monitor these processes when using Cowboy as
  40. %% an application as it already supervises them under the listener supervisor.
  41. %%
  42. %% @see cowboy_dispatcher
  43. %% @see cowboy_http_handler
  44. -module(cowboy_protocol).
  45. %% API.
  46. -export([start_link/4]).
  47. %% Internal.
  48. -export([init/4]).
  49. -export([parse_request/3]).
  50. -export([handler_loop/4]).
  51. -type onrequest_fun() :: fun((Req) -> Req).
  52. -type onresponse_fun() ::
  53. fun((cowboy_http:status(), cowboy_http:headers(), Req) -> Req).
  54. -export_type([onrequest_fun/0]).
  55. -export_type([onresponse_fun/0]).
  56. -record(state, {
  57. listener :: pid(),
  58. socket :: inet:socket(),
  59. transport :: module(),
  60. dispatch :: cowboy_dispatcher:dispatch_rules(),
  61. onrequest :: undefined | onrequest_fun(),
  62. onresponse = undefined :: undefined | onresponse_fun(),
  63. max_empty_lines :: integer(),
  64. req_keepalive = 1 :: integer(),
  65. max_keepalive :: integer(),
  66. max_request_line_length :: integer(),
  67. max_header_name_length :: integer(),
  68. max_header_value_length :: integer(),
  69. timeout :: timeout(),
  70. hibernate = false :: boolean(),
  71. loop_timeout = infinity :: timeout(),
  72. loop_timeout_ref :: undefined | reference()
  73. }).
  74. %% API.
  75. %% @doc Start an HTTP protocol process.
  76. -spec start_link(pid(), inet:socket(), module(), any()) -> {ok, pid()}.
  77. start_link(ListenerPid, Socket, Transport, Opts) ->
  78. Pid = spawn_link(?MODULE, init, [ListenerPid, Socket, Transport, Opts]),
  79. {ok, Pid}.
  80. %% Internal.
  81. %% @doc Faster alternative to proplists:get_value/3.
  82. %% @private
  83. get_value(Key, Opts, Default) ->
  84. case lists:keyfind(Key, 1, Opts) of
  85. {_, Value} -> Value;
  86. _ -> Default
  87. end.
  88. %% @private
  89. -spec init(pid(), inet:socket(), module(), any()) -> ok.
  90. init(ListenerPid, Socket, Transport, Opts) ->
  91. Dispatch = get_value(dispatch, Opts, []),
  92. MaxEmptyLines = get_value(max_empty_lines, Opts, 5),
  93. MaxHeaderNameLength = get_value(max_header_name_length, Opts, 64),
  94. MaxHeaderValueLength = get_value(max_header_value_length, Opts, 4096),
  95. MaxKeepalive = get_value(max_keepalive, Opts, infinity),
  96. MaxRequestLineLength = get_value(max_request_line_length, Opts, 4096),
  97. OnRequest = get_value(onrequest, Opts, undefined),
  98. OnResponse = get_value(onresponse, Opts, undefined),
  99. Timeout = get_value(timeout, Opts, 5000),
  100. ok = ranch:accept_ack(ListenerPid),
  101. wait_request(<<>>, #state{listener=ListenerPid, socket=Socket,
  102. transport=Transport, dispatch=Dispatch,
  103. max_empty_lines=MaxEmptyLines, max_keepalive=MaxKeepalive,
  104. max_request_line_length=MaxRequestLineLength,
  105. max_header_name_length=MaxHeaderNameLength,
  106. max_header_value_length=MaxHeaderValueLength,
  107. timeout=Timeout, onrequest=OnRequest, onresponse=OnResponse}, 0).
  108. %% Request parsing.
  109. %%
  110. %% The next set of functions is the request parsing code. All of it
  111. %% runs using a single binary match context. This optimization ends
  112. %% right after the header parsing is finished and the code becomes
  113. %% more interesting past that point.
  114. -spec wait_request(binary(), #state{}, non_neg_integer()) -> ok.
  115. wait_request(Buffer, State=#state{socket=Socket, transport=Transport,
  116. timeout=Timeout}, ReqEmpty) ->
  117. case Transport:recv(Socket, 0, Timeout) of
  118. {ok, Data} ->
  119. parse_request(<< Buffer/binary, Data/binary >>, State, ReqEmpty);
  120. {error, _} ->
  121. terminate(State)
  122. end.
  123. %% @private
  124. -spec parse_request(binary(), #state{}, non_neg_integer()) -> ok.
  125. %% Empty lines must be using \r\n.
  126. parse_request(<< $\n, _/binary >>, State, _) ->
  127. error_terminate(400, State);
  128. %% We limit the length of the Request-line to MaxLength to avoid endlessly
  129. %% reading from the socket and eventually crashing.
  130. parse_request(Buffer, State=#state{max_request_line_length=MaxLength,
  131. max_empty_lines=MaxEmpty}, ReqEmpty) ->
  132. case binary:match(Buffer, <<"\n">>) of
  133. nomatch when byte_size(Buffer) > MaxLength ->
  134. error_terminate(413, State);
  135. nomatch ->
  136. wait_request(Buffer, State, ReqEmpty);
  137. {1, _} when ReqEmpty =:= MaxEmpty ->
  138. error_terminate(400, State);
  139. {1, _} ->
  140. << _:16, Rest/binary >> = Buffer,
  141. parse_request(Rest, State, ReqEmpty + 1);
  142. {_, _} ->
  143. parse_method(Buffer, State, <<>>)
  144. end.
  145. parse_method(<< C, Rest/bits >>, State, SoFar) ->
  146. case C of
  147. $\r -> error_terminate(400, State);
  148. $\s -> parse_uri(Rest, State, SoFar);
  149. _ -> parse_method(Rest, State, << SoFar/binary, C >>)
  150. end.
  151. parse_uri(<< $\r, _/bits >>, State, _) ->
  152. error_terminate(400, State);
  153. parse_uri(<< "* ", Rest/bits >>, State, Method) ->
  154. parse_version(Rest, State, Method, <<"*">>, <<>>, <<>>);
  155. parse_uri(<< "http://", Rest/bits >>, State, Method) ->
  156. parse_uri_skip_host(Rest, State, Method);
  157. parse_uri(<< "https://", Rest/bits >>, State, Method) ->
  158. parse_uri_skip_host(Rest, State, Method);
  159. parse_uri(Buffer, State, Method) ->
  160. parse_uri_path(Buffer, State, Method, <<>>).
  161. parse_uri_skip_host(<< C, Rest/bits >>, State, Method) ->
  162. case C of
  163. $\r -> error_terminate(400, State);
  164. $/ -> parse_uri_path(Rest, State, Method, <<"/">>);
  165. _ -> parse_uri_skip_host(Rest, State, Method)
  166. end.
  167. parse_uri_path(<< C, Rest/bits >>, State, Method, SoFar) ->
  168. case C of
  169. $\r -> error_terminate(400, State);
  170. $\s -> parse_version(Rest, State, Method, SoFar, <<>>, <<>>);
  171. $? -> parse_uri_query(Rest, State, Method, SoFar, <<>>);
  172. $# -> parse_uri_fragment(Rest, State, Method, SoFar, <<>>, <<>>);
  173. _ -> parse_uri_path(Rest, State, Method, << SoFar/binary, C >>)
  174. end.
  175. parse_uri_query(<< C, Rest/bits >>, S, M, P, SoFar) ->
  176. case C of
  177. $\r -> error_terminate(400, S);
  178. $\s -> parse_version(Rest, S, M, P, SoFar, <<>>);
  179. $# -> parse_uri_fragment(Rest, S, M, P, SoFar, <<>>);
  180. _ -> parse_uri_query(Rest, S, M, P, << SoFar/binary, C >>)
  181. end.
  182. parse_uri_fragment(<< C, Rest/bits >>, S, M, P, Q, SoFar) ->
  183. case C of
  184. $\r -> error_terminate(400, S);
  185. $\s -> parse_version(Rest, S, M, P, Q, SoFar);
  186. _ -> parse_uri_fragment(Rest, S, M, P, Q, << SoFar/binary, C >>)
  187. end.
  188. parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, S, M, P, Q, F) ->
  189. parse_header(Rest, S, M, P, Q, F, {1, 1}, []);
  190. parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, S, M, P, Q, F) ->
  191. parse_header(Rest, S, M, P, Q, F, {1, 0}, []);
  192. parse_version(_, State, _, _, _, _) ->
  193. error_terminate(505, State).
  194. wait_header(Buffer, State=#state{socket=Socket, transport=Transport,
  195. timeout=Timeout}, M, P, Q, F, V, H) ->
  196. case Transport:recv(Socket, 0, Timeout) of
  197. {ok, Data} ->
  198. parse_header(<< Buffer/binary, Data/binary >>,
  199. State, M, P, Q, F, V, H);
  200. {error, timeout} ->
  201. error_terminate(408, State);
  202. {error, _} ->
  203. terminate(State)
  204. end.
  205. parse_header(<< $\r, $\n, Rest/bits >>, S, M, P, Q, F, V, Headers) ->
  206. request(Rest, S, M, P, Q, F, V, lists:reverse(Headers));
  207. parse_header(Buffer, State=#state{max_header_name_length=MaxLength},
  208. M, P, Q, F, V, H) ->
  209. case binary:match(Buffer, <<":">>) of
  210. nomatch when byte_size(Buffer) > MaxLength ->
  211. error_terminate(413, State);
  212. nomatch ->
  213. wait_header(Buffer, State, M, P, Q, F, V, H);
  214. {_, _} ->
  215. parse_hd_name(Buffer, State, M, P, Q, F, V, H, <<>>)
  216. end.
  217. %% I know, this isn't exactly pretty. But this is the most critical
  218. %% code path and as such needs to be optimized to death.
  219. %%
  220. %% ... Sorry for your eyes.
  221. %%
  222. %% But let's be honest, that's still pretty readable.
  223. parse_hd_name(<< C, Rest/bits >>, S, M, P, Q, F, V, H, SoFar) ->
  224. case C of
  225. $: -> parse_hd_before_value(Rest, S, M, P, Q, F, V, H, SoFar);
  226. $\s -> parse_hd_name_ws(Rest, S, M, P, Q, F, V, H, SoFar);
  227. $\t -> parse_hd_name_ws(Rest, S, M, P, Q, F, V, H, SoFar);
  228. $A -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $a >>);
  229. $B -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $b >>);
  230. $C -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $c >>);
  231. $D -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $d >>);
  232. $E -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $e >>);
  233. $F -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $f >>);
  234. $G -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $g >>);
  235. $H -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $h >>);
  236. $I -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $i >>);
  237. $J -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $j >>);
  238. $K -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $k >>);
  239. $L -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $l >>);
  240. $M -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $m >>);
  241. $N -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $n >>);
  242. $O -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $o >>);
  243. $P -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $p >>);
  244. $Q -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $q >>);
  245. $R -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $r >>);
  246. $S -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $s >>);
  247. $T -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $t >>);
  248. $U -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $u >>);
  249. $V -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $v >>);
  250. $W -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $w >>);
  251. $X -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $x >>);
  252. $Y -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $y >>);
  253. $Z -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, $z >>);
  254. C -> parse_hd_name(Rest, S, M, P, Q, F, V, H, << SoFar/binary, C >>)
  255. end.
  256. parse_hd_name_ws(<< C, Rest/bits >>, S, M, P, Q, F, V, H, Name) ->
  257. case C of
  258. $\s -> parse_hd_name_ws(Rest, S, M, P, Q, F, V, H, Name);
  259. $\t -> parse_hd_name_ws(Rest, S, M, P, Q, F, V, H, Name);
  260. $: -> parse_hd_before_value(Rest, S, M, P, Q, F, V, H, Name)
  261. end.
  262. wait_hd_before_value(Buffer, State=#state{
  263. socket=Socket, transport=Transport, timeout=Timeout},
  264. M, P, Q, F, V, H, N) ->
  265. case Transport:recv(Socket, 0, Timeout) of
  266. {ok, Data} ->
  267. parse_hd_before_value(<< Buffer/binary, Data/binary >>,
  268. State, M, P, Q, F, V, H, N);
  269. {error, timeout} ->
  270. error_terminate(408, State);
  271. {error, _} ->
  272. terminate(State)
  273. end.
  274. parse_hd_before_value(<< $\s, Rest/bits >>, S, M, P, Q, F, V, H, N) ->
  275. parse_hd_before_value(Rest, S, M, P, Q, F, V, H, N);
  276. parse_hd_before_value(<< $\t, Rest/bits >>, S, M, P, Q, F, V, H, N) ->
  277. parse_hd_before_value(Rest, S, M, P, Q, F, V, H, N);
  278. parse_hd_before_value(Buffer, State=#state{
  279. max_header_value_length=MaxLength}, M, P, Q, F, V, H, N) ->
  280. case binary:match(Buffer, <<"\n">>) of
  281. nomatch when byte_size(Buffer) > MaxLength ->
  282. error_terminate(413, State);
  283. nomatch ->
  284. wait_hd_before_value(Buffer, State, M, P, Q, F, V, H, N);
  285. {_, _} ->
  286. parse_hd_value(Buffer, State, M, P, Q, F, V, H, N, <<>>)
  287. end.
  288. %% We completely ignore the first argument which is always
  289. %% the empty binary. We keep it there because we don't want
  290. %% to change the other arguments' position and trigger costy
  291. %% operations for no reasons.
  292. wait_hd_value(_, State=#state{
  293. socket=Socket, transport=Transport, timeout=Timeout},
  294. M, P, Q, F, V, H, N, SoFar) ->
  295. case Transport:recv(Socket, 0, Timeout) of
  296. {ok, Data} ->
  297. parse_hd_value(Data, State, M, P, Q, F, V, H, N, SoFar);
  298. {error, timeout} ->
  299. error_terminate(408, State);
  300. {error, _} ->
  301. terminate(State)
  302. end.
  303. %% Pushing back as much as we could the retrieval of new data
  304. %% to check for multilines allows us to avoid a few tests in
  305. %% the critical path, but forces us to have a special function.
  306. wait_hd_value_nl(_, State=#state{
  307. socket=Socket, transport=Transport, timeout=Timeout},
  308. M, P, Q, F, V, Headers, Name, SoFar) ->
  309. case Transport:recv(Socket, 0, Timeout) of
  310. {ok, << C, Data/bits >>} when C =:= $\s; C =:= $\t ->
  311. parse_hd_value(Data, State, M, P, Q, F, V, Headers, Name, SoFar);
  312. {ok, Data} ->
  313. parse_header(Data, State, M, P, Q, F, V, [{Name, SoFar}|Headers]);
  314. {error, timeout} ->
  315. error_terminate(408, State);
  316. {error, _} ->
  317. terminate(State)
  318. end.
  319. parse_hd_value(<< $\r, Rest/bits >>, S, M, P, Q, F, V, Headers, Name, SoFar) ->
  320. case Rest of
  321. << $\n >> ->
  322. wait_hd_value_nl(<<>>, S, M, P, Q, F, V, Headers, Name, SoFar);
  323. << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t ->
  324. parse_hd_value(Rest2, S, M, P, Q, F, V, Headers, Name, SoFar);
  325. << $\n, Rest2/bits >> ->
  326. parse_header(Rest2, S, M, P, Q, F, V, [{Name, SoFar}|Headers])
  327. end;
  328. parse_hd_value(<< C, Rest/bits >>, S, M, P, Q, F, V, H, N, SoFar) ->
  329. parse_hd_value(Rest, S, M, P, Q, F, V, H, N, << SoFar/binary, C >>);
  330. parse_hd_value(<<>>, State=#state{max_header_value_length=MaxLength},
  331. _, _, _, _, _, _, _, SoFar) when byte_size(SoFar) > MaxLength ->
  332. error_terminate(413, State);
  333. parse_hd_value(<<>>, S, M, P, Q, F, V, H, N, SoFar) ->
  334. wait_hd_value(<<>>, S, M, P, Q, F, V, H, N, SoFar).
  335. request(B, State=#state{transport=Transport}, M, P, Q, F, Version, Headers) ->
  336. case lists:keyfind(<<"host">>, 1, Headers) of
  337. false when Version =:= {1, 1} ->
  338. error_terminate(400, State);
  339. false ->
  340. request(B, State, M, P, Q, F, Version, Headers,
  341. <<>>, default_port(Transport:name()));
  342. {_, RawHost} ->
  343. case parse_host(RawHost, <<>>) of
  344. {Host, undefined} ->
  345. request(B, State, M, P, Q, F, Version, Headers,
  346. Host, default_port(Transport:name()));
  347. {Host, Port} ->
  348. request(B, State, M, P, Q, F, Version, Headers,
  349. Host, Port)
  350. end
  351. end.
  352. -spec default_port(atom()) -> 80 | 443.
  353. default_port(ssl) -> 443;
  354. default_port(_) -> 80.
  355. %% Another hurtful block of code. :)
  356. parse_host(<<>>, Acc) ->
  357. {Acc, undefined};
  358. parse_host(<< $:, Rest/bits >>, Acc) ->
  359. {Acc, list_to_integer(binary_to_list(Rest))};
  360. parse_host(<< C, Rest/bits >>, Acc) ->
  361. case C of
  362. $A -> parse_host(Rest, << Acc/binary, $a >>);
  363. $B -> parse_host(Rest, << Acc/binary, $b >>);
  364. $C -> parse_host(Rest, << Acc/binary, $c >>);
  365. $D -> parse_host(Rest, << Acc/binary, $d >>);
  366. $E -> parse_host(Rest, << Acc/binary, $e >>);
  367. $F -> parse_host(Rest, << Acc/binary, $f >>);
  368. $G -> parse_host(Rest, << Acc/binary, $g >>);
  369. $H -> parse_host(Rest, << Acc/binary, $h >>);
  370. $I -> parse_host(Rest, << Acc/binary, $i >>);
  371. $J -> parse_host(Rest, << Acc/binary, $j >>);
  372. $K -> parse_host(Rest, << Acc/binary, $k >>);
  373. $L -> parse_host(Rest, << Acc/binary, $l >>);
  374. $M -> parse_host(Rest, << Acc/binary, $m >>);
  375. $N -> parse_host(Rest, << Acc/binary, $n >>);
  376. $O -> parse_host(Rest, << Acc/binary, $o >>);
  377. $P -> parse_host(Rest, << Acc/binary, $p >>);
  378. $Q -> parse_host(Rest, << Acc/binary, $q >>);
  379. $R -> parse_host(Rest, << Acc/binary, $r >>);
  380. $S -> parse_host(Rest, << Acc/binary, $s >>);
  381. $T -> parse_host(Rest, << Acc/binary, $t >>);
  382. $U -> parse_host(Rest, << Acc/binary, $u >>);
  383. $V -> parse_host(Rest, << Acc/binary, $v >>);
  384. $W -> parse_host(Rest, << Acc/binary, $w >>);
  385. $X -> parse_host(Rest, << Acc/binary, $x >>);
  386. $Y -> parse_host(Rest, << Acc/binary, $y >>);
  387. $Z -> parse_host(Rest, << Acc/binary, $z >>);
  388. _ -> parse_host(Rest, << Acc/binary, C >>)
  389. end.
  390. %% End of request parsing.
  391. %%
  392. %% We create the Req object and start handling the request.
  393. request(Buffer, State=#state{socket=Socket, transport=Transport,
  394. req_keepalive=ReqKeepalive, max_keepalive=MaxKeepalive,
  395. onresponse=OnResponse},
  396. Method, Path, Query, Fragment, Version, Headers, Host, Port) ->
  397. Req = cowboy_req:new(Socket, Transport, Method, Path, Query, Fragment,
  398. Version, Headers, Host, Port, Buffer, ReqKeepalive < MaxKeepalive,
  399. OnResponse),
  400. onrequest(Req, State, Host, Path).
  401. %% Call the global onrequest callback. The callback can send a reply,
  402. %% in which case we consider the request handled and move on to the next
  403. %% one. Note that since we haven't dispatched yet, we don't know the
  404. %% handler, host_info, path_info or bindings yet.
  405. -spec onrequest(cowboy_req:req(), #state{}, binary(), binary()) -> ok.
  406. onrequest(Req, State=#state{onrequest=undefined}, Host, Path) ->
  407. dispatch(Req, State, Host, Path);
  408. onrequest(Req, State=#state{onrequest=OnRequest}, Host, Path) ->
  409. Req2 = OnRequest(Req),
  410. case cowboy_req:get(resp_state, Req2) of
  411. waiting -> dispatch(Req2, State, Host, Path);
  412. _ -> next_request(Req2, State, ok)
  413. end.
  414. -spec dispatch(cowboy_req:req(), #state{}, binary(), binary()) -> ok.
  415. dispatch(Req, State=#state{dispatch=Dispatch}, Host, Path) ->
  416. case cowboy_dispatcher:match(Dispatch, Host, Path) of
  417. {ok, Handler, Opts, Bindings, HostInfo, PathInfo} ->
  418. Req2 = cowboy_req:set_bindings(HostInfo, PathInfo, Bindings, Req),
  419. handler_init(Req2, State, Handler, Opts);
  420. {error, notfound, host} ->
  421. error_terminate(400, State);
  422. {error, notfound, path} ->
  423. error_terminate(404, State)
  424. end.
  425. -spec handler_init(cowboy_req:req(), #state{}, module(), any()) -> ok.
  426. handler_init(Req, State=#state{transport=Transport}, Handler, Opts) ->
  427. try Handler:init({Transport:name(), http}, Req, Opts) of
  428. {ok, Req2, HandlerState} ->
  429. handler_handle(Req2, State, Handler, HandlerState);
  430. {loop, Req2, HandlerState} ->
  431. handler_before_loop(Req2, State#state{hibernate=false},
  432. Handler, HandlerState);
  433. {loop, Req2, HandlerState, hibernate} ->
  434. handler_before_loop(Req2, State#state{hibernate=true},
  435. Handler, HandlerState);
  436. {loop, Req2, HandlerState, Timeout} ->
  437. handler_before_loop(Req2, State#state{loop_timeout=Timeout},
  438. Handler, HandlerState);
  439. {loop, Req2, HandlerState, Timeout, hibernate} ->
  440. handler_before_loop(Req2, State#state{
  441. hibernate=true, loop_timeout=Timeout}, Handler, HandlerState);
  442. {shutdown, Req2, HandlerState} ->
  443. handler_terminate(Req2, Handler, HandlerState);
  444. %% @todo {upgrade, transport, Module}
  445. {upgrade, protocol, Module} ->
  446. upgrade_protocol(Req, State, Handler, Opts, Module)
  447. catch Class:Reason ->
  448. error_terminate(500, State),
  449. error_logger:error_msg(
  450. "** Handler ~p terminating in init/3~n"
  451. " for the reason ~p:~p~n"
  452. "** Options were ~p~n"
  453. "** Request was ~p~n"
  454. "** Stacktrace: ~p~n~n",
  455. [Handler, Class, Reason, Opts,
  456. cowboy_req:to_list(Req), erlang:get_stacktrace()])
  457. end.
  458. -spec upgrade_protocol(cowboy_req:req(), #state{}, module(), any(), module())
  459. -> ok.
  460. upgrade_protocol(Req, State=#state{listener=ListenerPid},
  461. Handler, Opts, Module) ->
  462. case Module:upgrade(ListenerPid, Handler, Opts, Req) of
  463. {UpgradeRes, Req2} -> next_request(Req2, State, UpgradeRes);
  464. _Any -> terminate(State)
  465. end.
  466. -spec handler_handle(cowboy_req:req(), #state{}, module(), any()) -> ok.
  467. handler_handle(Req, State, Handler, HandlerState) ->
  468. try Handler:handle(Req, HandlerState) of
  469. {ok, Req2, HandlerState2} ->
  470. terminate_request(Req2, State, Handler, HandlerState2)
  471. catch Class:Reason ->
  472. error_logger:error_msg(
  473. "** Handler ~p terminating in handle/2~n"
  474. " for the reason ~p:~p~n"
  475. "** Handler state was ~p~n"
  476. "** Request was ~p~n"
  477. "** Stacktrace: ~p~n~n",
  478. [Handler, Class, Reason, HandlerState,
  479. cowboy_req:to_list(Req), erlang:get_stacktrace()]),
  480. handler_terminate(Req, Handler, HandlerState),
  481. error_terminate(500, State)
  482. end.
  483. %% We don't listen for Transport closes because that would force us
  484. %% to receive data and buffer it indefinitely.
  485. -spec handler_before_loop(cowboy_req:req(), #state{}, module(), any()) -> ok.
  486. handler_before_loop(Req, State=#state{hibernate=true}, Handler, HandlerState) ->
  487. State2 = handler_loop_timeout(State),
  488. catch erlang:hibernate(?MODULE, handler_loop,
  489. [Req, State2#state{hibernate=false}, Handler, HandlerState]),
  490. ok;
  491. handler_before_loop(Req, State, Handler, HandlerState) ->
  492. State2 = handler_loop_timeout(State),
  493. handler_loop(Req, State2, Handler, HandlerState).
  494. %% Almost the same code can be found in cowboy_websocket.
  495. -spec handler_loop_timeout(#state{}) -> #state{}.
  496. handler_loop_timeout(State=#state{loop_timeout=infinity}) ->
  497. State#state{loop_timeout_ref=undefined};
  498. handler_loop_timeout(State=#state{loop_timeout=Timeout,
  499. loop_timeout_ref=PrevRef}) ->
  500. _ = case PrevRef of undefined -> ignore; PrevRef ->
  501. erlang:cancel_timer(PrevRef) end,
  502. TRef = erlang:start_timer(Timeout, self(), ?MODULE),
  503. State#state{loop_timeout_ref=TRef}.
  504. %% @private
  505. -spec handler_loop(cowboy_req:req(), #state{}, module(), any()) -> ok.
  506. handler_loop(Req, State=#state{loop_timeout_ref=TRef}, Handler, HandlerState) ->
  507. receive
  508. {timeout, TRef, ?MODULE} ->
  509. terminate_request(Req, State, Handler, HandlerState);
  510. {timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) ->
  511. handler_loop(Req, State, Handler, HandlerState);
  512. Message ->
  513. handler_call(Req, State, Handler, HandlerState, Message)
  514. end.
  515. -spec handler_call(cowboy_req:req(), #state{}, module(), any(), any()) -> ok.
  516. handler_call(Req, State, Handler, HandlerState, Message) ->
  517. try Handler:info(Message, Req, HandlerState) of
  518. {ok, Req2, HandlerState2} ->
  519. terminate_request(Req2, State, Handler, HandlerState2);
  520. {loop, Req2, HandlerState2} ->
  521. handler_before_loop(Req2, State, Handler, HandlerState2);
  522. {loop, Req2, HandlerState2, hibernate} ->
  523. handler_before_loop(Req2, State#state{hibernate=true},
  524. Handler, HandlerState2)
  525. catch Class:Reason ->
  526. error_logger:error_msg(
  527. "** Handler ~p terminating in info/3~n"
  528. " for the reason ~p:~p~n"
  529. "** Handler state was ~p~n"
  530. "** Request was ~p~n"
  531. "** Stacktrace: ~p~n~n",
  532. [Handler, Class, Reason, HandlerState,
  533. cowboy_req:to_list(Req), erlang:get_stacktrace()]),
  534. handler_terminate(Req, Handler, HandlerState),
  535. error_terminate(500, State)
  536. end.
  537. -spec handler_terminate(cowboy_req:req(), module(), any()) -> ok.
  538. handler_terminate(Req, Handler, HandlerState) ->
  539. try
  540. Handler:terminate(cowboy_req:lock(Req), HandlerState)
  541. catch Class:Reason ->
  542. error_logger:error_msg(
  543. "** Handler ~p terminating in terminate/2~n"
  544. " for the reason ~p:~p~n"
  545. "** Handler state was ~p~n"
  546. "** Request was ~p~n"
  547. "** Stacktrace: ~p~n~n",
  548. [Handler, Class, Reason, HandlerState,
  549. cowboy_req:to_list(Req), erlang:get_stacktrace()])
  550. end.
  551. -spec terminate_request(cowboy_req:req(), #state{}, module(), any()) -> ok.
  552. terminate_request(Req, State, Handler, HandlerState) ->
  553. HandlerRes = handler_terminate(Req, Handler, HandlerState),
  554. next_request(Req, State, HandlerRes).
  555. -spec next_request(cowboy_req:req(), #state{}, any()) -> ok.
  556. next_request(Req, State=#state{req_keepalive=Keepalive}, HandlerRes) ->
  557. cowboy_req:ensure_response(Req, 204),
  558. {BodyRes, [Buffer, Connection]} = case cowboy_req:skip_body(Req) of
  559. {ok, Req2} -> {ok, cowboy_req:get([buffer, connection], Req2)};
  560. {error, _} -> {close, [<<>>, close]}
  561. end,
  562. %% Flush the resp_sent message before moving on.
  563. receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,
  564. case {HandlerRes, BodyRes, Connection} of
  565. {ok, ok, keepalive} ->
  566. ?MODULE:parse_request(Buffer, State#state{
  567. req_keepalive=Keepalive + 1}, 0);
  568. _Closed ->
  569. terminate(State)
  570. end.
  571. %% Only send an error reply if there is no resp_sent message.
  572. -spec error_terminate(cowboy_http:status(), #state{}) -> ok.
  573. error_terminate(Code, State=#state{socket=Socket, transport=Transport,
  574. onresponse=OnResponse}) ->
  575. receive
  576. {cowboy_req, resp_sent} -> ok
  577. after 0 ->
  578. _ = cowboy_req:reply(Code, cowboy_req:new(Socket, Transport,
  579. <<"GET">>, <<>>, <<>>, <<>>, {1, 1}, [], <<>>, undefined,
  580. <<>>, false, OnResponse)),
  581. ok
  582. end,
  583. terminate(State).
  584. -spec terminate(#state{}) -> ok.
  585. terminate(#state{socket=Socket, transport=Transport}) ->
  586. Transport:close(Socket),
  587. ok.