cowboy_http_protocol.erl 20 KB

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