cowboy_protocol.erl 24 KB

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