cowboy_protocol.erl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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/1]).
  40. -export([handler_loop/3]).
  41. -include("http.hrl").
  42. -include_lib("eunit/include/eunit.hrl").
  43. -record(state, {
  44. listener :: pid(),
  45. socket :: inet:socket(),
  46. transport :: module(),
  47. dispatch :: cowboy_dispatcher:dispatch_rules(),
  48. handler :: {module(), any()},
  49. onrequest :: undefined | fun((#http_req{}) -> #http_req{}),
  50. onresponse = undefined :: undefined | fun((cowboy_http:status(),
  51. cowboy_http:headers(), #http_req{}) -> #http_req{}),
  52. urldecode :: {fun((binary(), T) -> binary()), T},
  53. req_empty_lines = 0 :: integer(),
  54. max_empty_lines :: integer(),
  55. req_keepalive = 1 :: integer(),
  56. max_keepalive :: integer(),
  57. max_line_length :: integer(),
  58. timeout :: timeout(),
  59. buffer = <<>> :: binary(),
  60. host_tokens = undefined :: undefined | cowboy_dispatcher:tokens(),
  61. path_tokens = undefined :: undefined | '*' | cowboy_dispatcher:tokens(),
  62. hibernate = false :: boolean(),
  63. loop_timeout = infinity :: timeout(),
  64. loop_timeout_ref :: undefined | reference()
  65. }).
  66. %% API.
  67. %% @doc Start an HTTP protocol process.
  68. -spec start_link(pid(), inet:socket(), module(), any()) -> {ok, pid()}.
  69. start_link(ListenerPid, Socket, Transport, Opts) ->
  70. Pid = spawn_link(?MODULE, init, [ListenerPid, Socket, Transport, Opts]),
  71. {ok, Pid}.
  72. %% Internal.
  73. %% @private
  74. -spec init(pid(), inet:socket(), module(), any()) -> ok.
  75. init(ListenerPid, Socket, Transport, Opts) ->
  76. Dispatch = proplists:get_value(dispatch, Opts, []),
  77. MaxEmptyLines = proplists:get_value(max_empty_lines, Opts, 5),
  78. MaxKeepalive = proplists:get_value(max_keepalive, Opts, infinity),
  79. MaxLineLength = proplists:get_value(max_line_length, Opts, 4096),
  80. OnRequest = proplists:get_value(onrequest, Opts),
  81. OnResponse = proplists:get_value(onresponse, Opts),
  82. Timeout = proplists:get_value(timeout, Opts, 5000),
  83. URLDecDefault = {fun cowboy_http:urldecode/2, crash},
  84. URLDec = proplists:get_value(urldecode, Opts, URLDecDefault),
  85. ok = ranch:accept_ack(ListenerPid),
  86. wait_request(#state{listener=ListenerPid, socket=Socket, transport=Transport,
  87. dispatch=Dispatch, max_empty_lines=MaxEmptyLines,
  88. max_keepalive=MaxKeepalive, max_line_length=MaxLineLength,
  89. timeout=Timeout, onrequest=OnRequest, onresponse=OnResponse,
  90. urldecode=URLDec}).
  91. %% @private
  92. -spec parse_request(#state{}) -> ok.
  93. %% We limit the length of the Request-line to MaxLength to avoid endlessly
  94. %% reading from the socket and eventually crashing.
  95. parse_request(State=#state{buffer=Buffer, max_line_length=MaxLength}) ->
  96. case erlang:decode_packet(http_bin, Buffer, []) of
  97. {ok, Request, Rest} -> request(Request, State#state{buffer=Rest});
  98. {more, _Length} when byte_size(Buffer) > MaxLength ->
  99. error_terminate(413, State);
  100. {more, _Length} -> wait_request(State);
  101. {error, _Reason} -> error_terminate(400, State)
  102. end.
  103. -spec wait_request(#state{}) -> ok.
  104. wait_request(State=#state{socket=Socket, transport=Transport,
  105. timeout=T, buffer=Buffer}) ->
  106. case Transport:recv(Socket, 0, T) of
  107. {ok, Data} -> parse_request(State#state{
  108. buffer= << Buffer/binary, Data/binary >>});
  109. {error, _Reason} -> terminate(State)
  110. end.
  111. -spec request({http_request, cowboy_http:method(), cowboy_http:uri(),
  112. cowboy_http:version()}, #state{}) -> ok.
  113. request({http_request, _Method, _URI, Version}, State)
  114. when Version =/= {1, 0}, Version =/= {1, 1} ->
  115. error_terminate(505, State);
  116. %% We still receive the original Host header.
  117. request({http_request, Method, {absoluteURI, _Scheme, _Host, _Port, Path},
  118. Version}, State) ->
  119. request({http_request, Method, {abs_path, Path}, Version}, State);
  120. request({http_request, Method, {abs_path, AbsPath}, Version},
  121. State=#state{socket=Socket, transport=Transport,
  122. req_keepalive=Keepalive, max_keepalive=MaxKeepalive,
  123. onresponse=OnResponse, urldecode={URLDecFun, URLDecArg}=URLDec}) ->
  124. URLDecode = fun(Bin) -> URLDecFun(Bin, URLDecArg) end,
  125. {PathTokens, RawPath, Qs}
  126. = cowboy_dispatcher:split_path(AbsPath, URLDecode),
  127. ConnAtom = if Keepalive < MaxKeepalive -> version_to_connection(Version);
  128. true -> close
  129. end,
  130. parse_header(#http_req{socket=Socket, transport=Transport,
  131. connection=ConnAtom, pid=self(), method=Method, version=Version,
  132. path=RawPath, raw_qs=Qs, onresponse=OnResponse, urldecode=URLDec},
  133. State#state{path_tokens=PathTokens});
  134. request({http_request, Method, '*', Version},
  135. State=#state{socket=Socket, transport=Transport,
  136. req_keepalive=Keepalive, max_keepalive=MaxKeepalive,
  137. onresponse=OnResponse, urldecode=URLDec}) ->
  138. ConnAtom = if Keepalive < MaxKeepalive -> version_to_connection(Version);
  139. true -> close
  140. end,
  141. parse_header(#http_req{socket=Socket, transport=Transport,
  142. connection=ConnAtom, pid=self(), method=Method, version=Version,
  143. path= <<"*">>, raw_qs= <<>>, onresponse=OnResponse,
  144. urldecode=URLDec}, State#state{path_tokens='*'});
  145. request({http_request, _Method, _URI, _Version}, State) ->
  146. error_terminate(501, State);
  147. request({http_error, <<"\r\n">>},
  148. State=#state{req_empty_lines=N, max_empty_lines=N}) ->
  149. error_terminate(400, State);
  150. request({http_error, <<"\r\n">>}, State=#state{req_empty_lines=N}) ->
  151. parse_request(State#state{req_empty_lines=N + 1});
  152. request(_Any, State) ->
  153. error_terminate(400, State).
  154. -spec parse_header(#http_req{}, #state{}) -> ok.
  155. parse_header(Req, State=#state{buffer=Buffer, max_line_length=MaxLength}) ->
  156. case erlang:decode_packet(httph_bin, Buffer, []) of
  157. {ok, Header, Rest} -> header(Header, Req, State#state{buffer=Rest});
  158. {more, _Length} when byte_size(Buffer) > MaxLength ->
  159. error_terminate(413, State);
  160. {more, _Length} -> wait_header(Req, State);
  161. {error, _Reason} -> error_terminate(400, State)
  162. end.
  163. -spec wait_header(#http_req{}, #state{}) -> ok.
  164. wait_header(Req, State=#state{socket=Socket,
  165. transport=Transport, timeout=T, buffer=Buffer}) ->
  166. case Transport:recv(Socket, 0, T) of
  167. {ok, Data} -> parse_header(Req, State#state{
  168. buffer= << Buffer/binary, Data/binary >>});
  169. {error, timeout} -> error_terminate(408, State);
  170. {error, closed} -> terminate(State)
  171. end.
  172. -spec header({http_header, integer(), cowboy_http:header(), any(), binary()}
  173. | http_eoh, #http_req{}, #state{}) -> ok.
  174. header({http_header, _I, 'Host', _R, RawHost}, Req=#http_req{
  175. transport=Transport}, State=#state{host_tokens=undefined}) ->
  176. RawHost2 = cowboy_bstr:to_lower(RawHost),
  177. case catch cowboy_dispatcher:split_host(RawHost2) of
  178. {HostTokens, RawHost3, undefined} ->
  179. Port = default_port(Transport:name()),
  180. parse_header(Req#http_req{
  181. host=RawHost3, port=Port,
  182. headers=[{'Host', RawHost}|Req#http_req.headers]},
  183. State#state{host_tokens=HostTokens});
  184. {HostTokens, RawHost3, Port} ->
  185. parse_header(Req#http_req{
  186. host=RawHost3, port=Port,
  187. headers=[{'Host', RawHost}|Req#http_req.headers]},
  188. State#state{host_tokens=HostTokens});
  189. {'EXIT', _Reason} ->
  190. error_terminate(400, State)
  191. end;
  192. %% Ignore Host headers if we already have it.
  193. header({http_header, _I, 'Host', _R, _V}, Req, State) ->
  194. parse_header(Req, State);
  195. header({http_header, _I, 'Connection', _R, Connection},
  196. Req=#http_req{headers=Headers}, State=#state{
  197. req_keepalive=Keepalive, max_keepalive=MaxKeepalive})
  198. when Keepalive < MaxKeepalive ->
  199. Req2 = Req#http_req{headers=[{'Connection', Connection}|Headers]},
  200. {ConnTokens, Req3}
  201. = cowboy_req:parse_header('Connection', Req2),
  202. ConnAtom = cowboy_http:connection_to_atom(ConnTokens),
  203. parse_header(Req3#http_req{connection=ConnAtom}, State);
  204. header({http_header, _I, Field, _R, Value}, Req, State) ->
  205. Field2 = format_header(Field),
  206. parse_header(Req#http_req{headers=[{Field2, Value}|Req#http_req.headers]},
  207. State);
  208. %% The Host header is required in HTTP/1.1.
  209. header(http_eoh, #http_req{version={1, 1}},
  210. State=#state{host_tokens=undefined}) ->
  211. error_terminate(400, State);
  212. %% It is however optional in HTTP/1.0.
  213. header(http_eoh, Req=#http_req{version={1, 0}, transport=Transport},
  214. State=#state{buffer=Buffer, host_tokens=undefined}) ->
  215. Port = default_port(Transport:name()),
  216. onrequest(Req#http_req{host= <<>>, port=Port, buffer=Buffer},
  217. State#state{buffer= <<>>, host_tokens=[]});
  218. header(http_eoh, Req, State=#state{buffer=Buffer}) ->
  219. onrequest(Req#http_req{buffer=Buffer}, State#state{buffer= <<>>});
  220. header(_Any, _Req, State) ->
  221. error_terminate(400, State).
  222. %% Call the global onrequest callback. The callback can send a reply,
  223. %% in which case we consider the request handled and move on to the next
  224. %% one. Note that since we haven't dispatched yet, we don't know the
  225. %% handler, host_info, path_info or bindings yet.
  226. -spec onrequest(#http_req{}, #state{}) -> ok.
  227. onrequest(Req, State=#state{onrequest=undefined}) ->
  228. dispatch(Req, State);
  229. onrequest(Req, State=#state{onrequest=OnRequest}) ->
  230. Req2 = OnRequest(Req),
  231. case Req2#http_req.resp_state of
  232. waiting -> dispatch(Req2, State);
  233. _ -> next_request(Req2, State, ok)
  234. end.
  235. -spec dispatch(#http_req{}, #state{}) -> ok.
  236. dispatch(Req, State=#state{dispatch=Dispatch,
  237. host_tokens=HostTokens, path_tokens=PathTokens}) ->
  238. case cowboy_dispatcher:match(HostTokens, PathTokens, Dispatch) of
  239. {ok, Handler, Opts, Binds, HostInfo, PathInfo} ->
  240. handler_init(Req#http_req{host_info=HostInfo, path_info=PathInfo,
  241. bindings=Binds}, State#state{handler={Handler, Opts},
  242. host_tokens=undefined, path_tokens=undefined});
  243. {error, notfound, host} ->
  244. error_terminate(400, State);
  245. {error, notfound, path} ->
  246. error_terminate(404, State)
  247. end.
  248. -spec handler_init(#http_req{}, #state{}) -> ok.
  249. handler_init(Req, State=#state{transport=Transport,
  250. handler={Handler, Opts}}) ->
  251. try Handler:init({Transport:name(), http}, Req, Opts) of
  252. {ok, Req2, HandlerState} ->
  253. handler_handle(HandlerState, Req2, State);
  254. {loop, Req2, HandlerState} ->
  255. handler_before_loop(HandlerState, Req2, State);
  256. {loop, Req2, HandlerState, hibernate} ->
  257. handler_before_loop(HandlerState, Req2,
  258. State#state{hibernate=true});
  259. {loop, Req2, HandlerState, Timeout} ->
  260. handler_before_loop(HandlerState, Req2,
  261. State#state{loop_timeout=Timeout});
  262. {loop, Req2, HandlerState, Timeout, hibernate} ->
  263. handler_before_loop(HandlerState, Req2,
  264. State#state{hibernate=true, loop_timeout=Timeout});
  265. {shutdown, Req2, HandlerState} ->
  266. handler_terminate(HandlerState, Req2, State);
  267. %% @todo {upgrade, transport, Module}
  268. {upgrade, protocol, Module} ->
  269. upgrade_protocol(Req, State, Module)
  270. catch Class:Reason ->
  271. error_terminate(500, State),
  272. PLReq = lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))),
  273. error_logger:error_msg(
  274. "** Handler ~p terminating in init/3~n"
  275. " for the reason ~p:~p~n"
  276. "** Options were ~p~n"
  277. "** Request was ~p~n** Stacktrace: ~p~n~n",
  278. [Handler, Class, Reason, Opts, PLReq, erlang:get_stacktrace()])
  279. end.
  280. -spec upgrade_protocol(#http_req{}, #state{}, atom()) -> ok.
  281. upgrade_protocol(Req, State=#state{listener=ListenerPid,
  282. handler={Handler, Opts}}, Module) ->
  283. case Module:upgrade(ListenerPid, Handler, Opts, Req) of
  284. {UpgradeRes, Req2} -> next_request(Req2, State, UpgradeRes);
  285. _Any -> terminate(State)
  286. end.
  287. -spec handler_handle(any(), #http_req{}, #state{}) -> ok.
  288. handler_handle(HandlerState, Req, State=#state{handler={Handler, Opts}}) ->
  289. try Handler:handle(Req, HandlerState) of
  290. {ok, Req2, HandlerState2} ->
  291. terminate_request(HandlerState2, Req2, State)
  292. catch Class:Reason ->
  293. PLReq = lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))),
  294. error_logger:error_msg(
  295. "** Handler ~p terminating in handle/2~n"
  296. " for the reason ~p:~p~n"
  297. "** Options were ~p~n** Handler state was ~p~n"
  298. "** Request was ~p~n** Stacktrace: ~p~n~n",
  299. [Handler, Class, Reason, Opts,
  300. HandlerState, PLReq, erlang:get_stacktrace()]),
  301. handler_terminate(HandlerState, Req, State),
  302. error_terminate(500, State)
  303. end.
  304. %% We don't listen for Transport closes because that would force us
  305. %% to receive data and buffer it indefinitely.
  306. -spec handler_before_loop(any(), #http_req{}, #state{}) -> ok.
  307. handler_before_loop(HandlerState, Req, State=#state{hibernate=true}) ->
  308. State2 = handler_loop_timeout(State),
  309. catch erlang:hibernate(?MODULE, handler_loop,
  310. [HandlerState, Req, State2#state{hibernate=false}]),
  311. ok;
  312. handler_before_loop(HandlerState, Req, State) ->
  313. State2 = handler_loop_timeout(State),
  314. handler_loop(HandlerState, Req, State2).
  315. %% Almost the same code can be found in cowboy_websocket.
  316. -spec handler_loop_timeout(#state{}) -> #state{}.
  317. handler_loop_timeout(State=#state{loop_timeout=infinity}) ->
  318. State#state{loop_timeout_ref=undefined};
  319. handler_loop_timeout(State=#state{loop_timeout=Timeout,
  320. loop_timeout_ref=PrevRef}) ->
  321. _ = case PrevRef of undefined -> ignore; PrevRef ->
  322. erlang:cancel_timer(PrevRef) end,
  323. TRef = erlang:start_timer(Timeout, self(), ?MODULE),
  324. State#state{loop_timeout_ref=TRef}.
  325. -spec handler_loop(any(), #http_req{}, #state{}) -> ok.
  326. handler_loop(HandlerState, Req, State=#state{loop_timeout_ref=TRef}) ->
  327. receive
  328. {timeout, TRef, ?MODULE} ->
  329. terminate_request(HandlerState, Req, State);
  330. {timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) ->
  331. handler_loop(HandlerState, Req, State);
  332. Message ->
  333. handler_call(HandlerState, Req, State, Message)
  334. end.
  335. -spec handler_call(any(), #http_req{}, #state{}, any()) -> ok.
  336. handler_call(HandlerState, Req, State=#state{handler={Handler, Opts}},
  337. Message) ->
  338. try Handler:info(Message, Req, HandlerState) of
  339. {ok, Req2, HandlerState2} ->
  340. terminate_request(HandlerState2, Req2, State);
  341. {loop, Req2, HandlerState2} ->
  342. handler_before_loop(HandlerState2, Req2, State);
  343. {loop, Req2, HandlerState2, hibernate} ->
  344. handler_before_loop(HandlerState2, Req2,
  345. State#state{hibernate=true})
  346. catch Class:Reason ->
  347. PLReq = lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))),
  348. error_logger:error_msg(
  349. "** Handler ~p terminating in info/3~n"
  350. " for the reason ~p:~p~n"
  351. "** Options were ~p~n** Handler state was ~p~n"
  352. "** Request was ~p~n** Stacktrace: ~p~n~n",
  353. [Handler, Class, Reason, Opts,
  354. HandlerState, PLReq, erlang:get_stacktrace()]),
  355. handler_terminate(HandlerState, Req, State),
  356. error_terminate(500, State)
  357. end.
  358. -spec handler_terminate(any(), #http_req{}, #state{}) -> ok.
  359. handler_terminate(HandlerState, Req, #state{handler={Handler, Opts}}) ->
  360. try
  361. Handler:terminate(Req#http_req{resp_state=locked}, HandlerState)
  362. catch Class:Reason ->
  363. PLReq = lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))),
  364. error_logger:error_msg(
  365. "** Handler ~p terminating in terminate/2~n"
  366. " for the reason ~p:~p~n"
  367. "** Options were ~p~n** Handler state was ~p~n"
  368. "** Request was ~p~n** Stacktrace: ~p~n~n",
  369. [Handler, Class, Reason, Opts,
  370. HandlerState, PLReq, erlang:get_stacktrace()])
  371. end.
  372. -spec terminate_request(any(), #http_req{}, #state{}) -> ok.
  373. terminate_request(HandlerState, Req, State) ->
  374. HandlerRes = handler_terminate(HandlerState, Req, State),
  375. next_request(Req, State, HandlerRes).
  376. -spec next_request(#http_req{}, #state{}, any()) -> ok.
  377. next_request(Req=#http_req{connection=Conn}, State=#state{
  378. req_keepalive=Keepalive}, HandlerRes) ->
  379. RespRes = ensure_response(Req),
  380. {BodyRes, Buffer} = ensure_body_processed(Req),
  381. %% Flush the resp_sent message before moving on.
  382. receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,
  383. case {HandlerRes, BodyRes, RespRes, Conn} of
  384. {ok, ok, ok, keepalive} ->
  385. ?MODULE:parse_request(State#state{
  386. buffer=Buffer, host_tokens=undefined, path_tokens=undefined,
  387. req_empty_lines=0, req_keepalive=Keepalive + 1});
  388. _Closed ->
  389. terminate(State)
  390. end.
  391. -spec ensure_body_processed(#http_req{}) -> {ok | close, binary()}.
  392. ensure_body_processed(#http_req{body_state=done, buffer=Buffer}) ->
  393. {ok, Buffer};
  394. ensure_body_processed(Req=#http_req{body_state=waiting}) ->
  395. case cowboy_req:skip_body(Req) of
  396. {ok, Req2} -> {ok, Req2#http_req.buffer};
  397. {error, _Reason} -> {close, <<>>}
  398. end;
  399. ensure_body_processed(Req=#http_req{body_state={stream, _, _, _}}) ->
  400. {ok, Req2} = cowboy_req:multipart_skip(Req),
  401. ensure_body_processed(Req2).
  402. -spec ensure_response(#http_req{}) -> ok.
  403. %% The handler has already fully replied to the client.
  404. ensure_response(#http_req{resp_state=done}) ->
  405. ok;
  406. %% No response has been sent but everything apparently went fine.
  407. %% Reply with 204 No Content to indicate this.
  408. ensure_response(Req=#http_req{resp_state=waiting}) ->
  409. _ = cowboy_req:reply(204, [], [], Req),
  410. ok;
  411. %% Terminate the chunked body for HTTP/1.1 only.
  412. ensure_response(#http_req{method='HEAD', resp_state=chunks}) ->
  413. ok;
  414. ensure_response(#http_req{version={1, 0}, resp_state=chunks}) ->
  415. ok;
  416. ensure_response(#http_req{socket=Socket, transport=Transport,
  417. resp_state=chunks}) ->
  418. Transport:send(Socket, <<"0\r\n\r\n">>),
  419. ok.
  420. %% Only send an error reply if there is no resp_sent message.
  421. -spec error_terminate(cowboy_http:status(), #state{}) -> ok.
  422. error_terminate(Code, State=#state{socket=Socket, transport=Transport,
  423. onresponse=OnResponse}) ->
  424. receive
  425. {cowboy_req, resp_sent} -> ok
  426. after 0 ->
  427. _ = cowboy_req:reply(Code, #http_req{
  428. socket=Socket, transport=Transport, onresponse=OnResponse,
  429. connection=close, pid=self(), resp_state=waiting}),
  430. ok
  431. end,
  432. terminate(State).
  433. -spec terminate(#state{}) -> ok.
  434. terminate(#state{socket=Socket, transport=Transport}) ->
  435. Transport:close(Socket),
  436. ok.
  437. %% Internal.
  438. -spec version_to_connection(cowboy_http:version()) -> keepalive | close.
  439. version_to_connection({1, 1}) -> keepalive;
  440. version_to_connection(_Any) -> close.
  441. -spec default_port(atom()) -> 80 | 443.
  442. default_port(ssl) -> 443;
  443. default_port(_) -> 80.
  444. %% @todo While 32 should be enough for everybody, we should probably make
  445. %% this configurable or something.
  446. -spec format_header(atom()) -> atom(); (binary()) -> binary().
  447. format_header(Field) when is_atom(Field) ->
  448. Field;
  449. format_header(Field) when byte_size(Field) =< 20; byte_size(Field) > 32 ->
  450. Field;
  451. format_header(Field) ->
  452. format_header(Field, true, <<>>).
  453. -spec format_header(binary(), boolean(), binary()) -> binary().
  454. format_header(<<>>, _Any, Acc) ->
  455. Acc;
  456. %% Replicate a bug in OTP for compatibility reasons when there's a - right
  457. %% after another. Proper use should always be 'true' instead of 'not Bool'.
  458. format_header(<< $-, Rest/bits >>, Bool, Acc) ->
  459. format_header(Rest, not Bool, << Acc/binary, $- >>);
  460. format_header(<< C, Rest/bits >>, true, Acc) ->
  461. format_header(Rest, false, << Acc/binary, (cowboy_bstr:char_to_upper(C)) >>);
  462. format_header(<< C, Rest/bits >>, false, Acc) ->
  463. format_header(Rest, false, << Acc/binary, (cowboy_bstr:char_to_lower(C)) >>).
  464. %% Tests.
  465. -ifdef(TEST).
  466. format_header_test_() ->
  467. %% {Header, Result}
  468. Tests = [
  469. {<<"Sec-Websocket-Version">>, <<"Sec-Websocket-Version">>},
  470. {<<"Sec-WebSocket-Version">>, <<"Sec-Websocket-Version">>},
  471. {<<"sec-websocket-version">>, <<"Sec-Websocket-Version">>},
  472. {<<"SEC-WEBSOCKET-VERSION">>, <<"Sec-Websocket-Version">>},
  473. %% These last tests ensures we're formatting headers exactly like OTP.
  474. %% Even though it's dumb, it's better for compatibility reasons.
  475. {<<"Sec-WebSocket--Version">>, <<"Sec-Websocket--version">>},
  476. {<<"Sec-WebSocket---Version">>, <<"Sec-Websocket---Version">>}
  477. ],
  478. [{H, fun() -> R = format_header(H) end} || {H, R} <- Tests].
  479. -endif.