cowboy_http_protocol.erl 20 KB

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