cowboy_protocol.erl 22 KB

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