cowboy_protocol.erl 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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((cowboy_req:req()) -> cowboy_req:req()),
  50. onresponse = undefined :: undefined | fun((cowboy_http:status(),
  51. cowboy_http:headers(), cowboy_req:req()) -> cowboy_req: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(cowboy_req:new(Socket, Transport, ConnAtom, Method, Version,
  131. RawPath, Qs, OnResponse, URLDec), State#state{path_tokens=PathTokens});
  132. request({http_request, Method, '*', Version},
  133. State=#state{socket=Socket, transport=Transport,
  134. req_keepalive=Keepalive, max_keepalive=MaxKeepalive,
  135. onresponse=OnResponse, urldecode=URLDec}) ->
  136. ConnAtom = if Keepalive < MaxKeepalive -> version_to_connection(Version);
  137. true -> close
  138. end,
  139. parse_header(cowboy_req:new(Socket, Transport, ConnAtom, Method, Version,
  140. <<"*">>, <<>>, OnResponse, URLDec), State#state{path_tokens='*'});
  141. request({http_request, _Method, _URI, _Version}, State) ->
  142. error_terminate(501, State);
  143. request({http_error, <<"\r\n">>},
  144. State=#state{req_empty_lines=N, max_empty_lines=N}) ->
  145. error_terminate(400, State);
  146. request({http_error, <<"\r\n">>}, State=#state{req_empty_lines=N}) ->
  147. parse_request(State#state{req_empty_lines=N + 1});
  148. request(_Any, State) ->
  149. error_terminate(400, State).
  150. -spec parse_header(cowboy_req:req(), #state{}) -> ok.
  151. parse_header(Req, State=#state{buffer=Buffer, max_line_length=MaxLength}) ->
  152. case erlang:decode_packet(httph_bin, Buffer, []) of
  153. {ok, Header, Rest} -> header(Header, Req, State#state{buffer=Rest});
  154. {more, _Length} when byte_size(Buffer) > MaxLength ->
  155. error_terminate(413, State);
  156. {more, _Length} -> wait_header(Req, State);
  157. {error, _Reason} -> error_terminate(400, State)
  158. end.
  159. -spec wait_header(cowboy_req:req(), #state{}) -> ok.
  160. wait_header(Req, State=#state{socket=Socket,
  161. transport=Transport, timeout=T, buffer=Buffer}) ->
  162. case Transport:recv(Socket, 0, T) of
  163. {ok, Data} -> parse_header(Req, State#state{
  164. buffer= << Buffer/binary, Data/binary >>});
  165. {error, timeout} -> error_terminate(408, State);
  166. {error, closed} -> terminate(State)
  167. end.
  168. -spec header({http_header, integer(), cowboy_http:header(), any(), binary()}
  169. | http_eoh, cowboy_req:req(), #state{}) -> ok.
  170. header({http_header, _I, 'Host', _R, RawHost}, Req,
  171. State=#state{host_tokens=undefined, transport=Transport}) ->
  172. RawHost2 = cowboy_bstr:to_lower(RawHost),
  173. case catch cowboy_dispatcher:split_host(RawHost2) of
  174. {HostTokens, Host, undefined} ->
  175. Port = default_port(Transport:name()),
  176. parse_header(cowboy_req:set_host(Host, Port, RawHost, Req),
  177. State#state{host_tokens=HostTokens});
  178. {HostTokens, Host, Port} ->
  179. parse_header(cowboy_req:set_host(Host, Port, RawHost, Req),
  180. State#state{host_tokens=HostTokens});
  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. {ok, ConnTokens, Req3}
  193. = cowboy_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 and optional in HTTP/1.0.
  201. header(http_eoh, Req, State=#state{host_tokens=undefined,
  202. buffer=Buffer, transport=Transport}) ->
  203. case cowboy_req:version(Req) of
  204. {{1, 1}, _} ->
  205. error_terminate(400, State);
  206. {{1, 0}, Req2} ->
  207. Port = default_port(Transport:name()),
  208. onrequest(Req2#http_req{host= <<>>, port=Port, buffer=Buffer},
  209. State#state{buffer= <<>>, host_tokens=[]})
  210. end;
  211. header(http_eoh, Req, State=#state{buffer=Buffer}) ->
  212. onrequest(Req#http_req{buffer=Buffer}, State#state{buffer= <<>>});
  213. header(_Any, _Req, State) ->
  214. error_terminate(400, State).
  215. %% Call the global onrequest callback. The callback can send a reply,
  216. %% in which case we consider the request handled and move on to the next
  217. %% one. Note that since we haven't dispatched yet, we don't know the
  218. %% handler, host_info, path_info or bindings yet.
  219. -spec onrequest(cowboy_req:req(), #state{}) -> ok.
  220. onrequest(Req, State=#state{onrequest=undefined}) ->
  221. dispatch(Req, State);
  222. onrequest(Req, State=#state{onrequest=OnRequest}) ->
  223. Req2 = OnRequest(Req),
  224. case Req2#http_req.resp_state of
  225. waiting -> dispatch(Req2, State);
  226. _ -> next_request(Req2, State, ok)
  227. end.
  228. -spec dispatch(cowboy_req:req(), #state{}) -> ok.
  229. dispatch(Req, State=#state{dispatch=Dispatch,
  230. host_tokens=HostTokens, path_tokens=PathTokens}) ->
  231. case cowboy_dispatcher:match(HostTokens, PathTokens, Dispatch) of
  232. {ok, Handler, Opts, Binds, HostInfo, PathInfo} ->
  233. handler_init(Req#http_req{host_info=HostInfo, path_info=PathInfo,
  234. bindings=Binds}, State#state{handler={Handler, Opts},
  235. host_tokens=undefined, path_tokens=undefined});
  236. {error, notfound, host} ->
  237. error_terminate(400, State);
  238. {error, notfound, path} ->
  239. error_terminate(404, State)
  240. end.
  241. -spec handler_init(cowboy_req:req(), #state{}) -> ok.
  242. handler_init(Req, State=#state{transport=Transport,
  243. handler={Handler, Opts}}) ->
  244. try Handler:init({Transport:name(), http}, Req, Opts) of
  245. {ok, Req2, HandlerState} ->
  246. handler_handle(HandlerState, Req2, State);
  247. {loop, Req2, HandlerState} ->
  248. handler_before_loop(HandlerState, Req2, State);
  249. {loop, Req2, HandlerState, hibernate} ->
  250. handler_before_loop(HandlerState, Req2,
  251. State#state{hibernate=true});
  252. {loop, Req2, HandlerState, Timeout} ->
  253. handler_before_loop(HandlerState, Req2,
  254. State#state{loop_timeout=Timeout});
  255. {loop, Req2, HandlerState, Timeout, hibernate} ->
  256. handler_before_loop(HandlerState, Req2,
  257. State#state{hibernate=true, loop_timeout=Timeout});
  258. {shutdown, Req2, HandlerState} ->
  259. handler_terminate(HandlerState, Req2, State);
  260. %% @todo {upgrade, transport, Module}
  261. {upgrade, protocol, Module} ->
  262. upgrade_protocol(Req, State, Module)
  263. catch Class:Reason ->
  264. error_terminate(500, State),
  265. PLReq = cowboy_req:to_list(Req),
  266. error_logger:error_msg(
  267. "** Handler ~p terminating in init/3~n"
  268. " for the reason ~p:~p~n"
  269. "** Options were ~p~n"
  270. "** Request was ~p~n** Stacktrace: ~p~n~n",
  271. [Handler, Class, Reason, Opts, PLReq, erlang:get_stacktrace()])
  272. end.
  273. -spec upgrade_protocol(cowboy_req:req(), #state{}, atom()) -> ok.
  274. upgrade_protocol(Req, State=#state{listener=ListenerPid,
  275. handler={Handler, Opts}}, Module) ->
  276. case Module:upgrade(ListenerPid, Handler, Opts, Req) of
  277. {UpgradeRes, Req2} -> next_request(Req2, State, UpgradeRes);
  278. _Any -> terminate(State)
  279. end.
  280. -spec handler_handle(any(), cowboy_req:req(), #state{}) -> ok.
  281. handler_handle(HandlerState, Req, State=#state{handler={Handler, Opts}}) ->
  282. try Handler:handle(Req, HandlerState) of
  283. {ok, Req2, HandlerState2} ->
  284. terminate_request(HandlerState2, Req2, State)
  285. catch Class:Reason ->
  286. PLReq = cowboy_req:to_list(Req),
  287. error_logger:error_msg(
  288. "** Handler ~p terminating in handle/2~n"
  289. " for the reason ~p:~p~n"
  290. "** Options were ~p~n** Handler state was ~p~n"
  291. "** Request was ~p~n** Stacktrace: ~p~n~n",
  292. [Handler, Class, Reason, Opts,
  293. HandlerState, PLReq, erlang:get_stacktrace()]),
  294. handler_terminate(HandlerState, Req, State),
  295. error_terminate(500, State)
  296. end.
  297. %% We don't listen for Transport closes because that would force us
  298. %% to receive data and buffer it indefinitely.
  299. -spec handler_before_loop(any(), cowboy_req:req(), #state{}) -> ok.
  300. handler_before_loop(HandlerState, Req, State=#state{hibernate=true}) ->
  301. State2 = handler_loop_timeout(State),
  302. catch erlang:hibernate(?MODULE, handler_loop,
  303. [HandlerState, Req, State2#state{hibernate=false}]),
  304. ok;
  305. handler_before_loop(HandlerState, Req, State) ->
  306. State2 = handler_loop_timeout(State),
  307. handler_loop(HandlerState, Req, State2).
  308. %% Almost the same code can be found in cowboy_websocket.
  309. -spec handler_loop_timeout(#state{}) -> #state{}.
  310. handler_loop_timeout(State=#state{loop_timeout=infinity}) ->
  311. State#state{loop_timeout_ref=undefined};
  312. handler_loop_timeout(State=#state{loop_timeout=Timeout,
  313. loop_timeout_ref=PrevRef}) ->
  314. _ = case PrevRef of undefined -> ignore; PrevRef ->
  315. erlang:cancel_timer(PrevRef) end,
  316. TRef = erlang:start_timer(Timeout, self(), ?MODULE),
  317. State#state{loop_timeout_ref=TRef}.
  318. -spec handler_loop(any(), cowboy_req:req(), #state{}) -> ok.
  319. handler_loop(HandlerState, Req, State=#state{loop_timeout_ref=TRef}) ->
  320. receive
  321. {timeout, TRef, ?MODULE} ->
  322. terminate_request(HandlerState, Req, State);
  323. {timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) ->
  324. handler_loop(HandlerState, Req, State);
  325. Message ->
  326. handler_call(HandlerState, Req, State, Message)
  327. end.
  328. -spec handler_call(any(), cowboy_req:req(), #state{}, any()) -> ok.
  329. handler_call(HandlerState, Req, State=#state{handler={Handler, Opts}},
  330. Message) ->
  331. try Handler:info(Message, Req, HandlerState) of
  332. {ok, Req2, HandlerState2} ->
  333. terminate_request(HandlerState2, Req2, State);
  334. {loop, Req2, HandlerState2} ->
  335. handler_before_loop(HandlerState2, Req2, State);
  336. {loop, Req2, HandlerState2, hibernate} ->
  337. handler_before_loop(HandlerState2, Req2,
  338. State#state{hibernate=true})
  339. catch Class:Reason ->
  340. PLReq = cowboy_req:to_list(Req),
  341. error_logger:error_msg(
  342. "** Handler ~p terminating in info/3~n"
  343. " for the reason ~p:~p~n"
  344. "** Options were ~p~n** Handler state was ~p~n"
  345. "** Request was ~p~n** Stacktrace: ~p~n~n",
  346. [Handler, Class, Reason, Opts,
  347. HandlerState, PLReq, erlang:get_stacktrace()]),
  348. handler_terminate(HandlerState, Req, State),
  349. error_terminate(500, State)
  350. end.
  351. -spec handler_terminate(any(), cowboy_req:req(), #state{}) -> ok.
  352. handler_terminate(HandlerState, Req, #state{handler={Handler, Opts}}) ->
  353. try
  354. Handler:terminate(cowboy_req:lock(Req), HandlerState)
  355. catch Class:Reason ->
  356. PLReq = cowboy_req:to_list(Req),
  357. error_logger:error_msg(
  358. "** Handler ~p terminating in terminate/2~n"
  359. " for the reason ~p:~p~n"
  360. "** Options were ~p~n** Handler state was ~p~n"
  361. "** Request was ~p~n** Stacktrace: ~p~n~n",
  362. [Handler, Class, Reason, Opts,
  363. HandlerState, PLReq, erlang:get_stacktrace()])
  364. end.
  365. -spec terminate_request(any(), cowboy_req:req(), #state{}) -> ok.
  366. terminate_request(HandlerState, Req, State) ->
  367. HandlerRes = handler_terminate(HandlerState, Req, State),
  368. next_request(Req, State, HandlerRes).
  369. -spec next_request(cowboy_req:req(), #state{}, any()) -> ok.
  370. next_request(Req=#http_req{connection=Conn}, State=#state{
  371. req_keepalive=Keepalive}, HandlerRes) ->
  372. cowboy_req:ensure_response(Req, 204),
  373. {BodyRes, Buffer} = case cowboy_req:skip_body(Req) of
  374. {ok, Req2} -> {ok, Req2#http_req.buffer};
  375. {error, _} -> {close, <<>>}
  376. end,
  377. %% Flush the resp_sent message before moving on.
  378. receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,
  379. case {HandlerRes, BodyRes, Conn} of
  380. {ok, ok, keepalive} ->
  381. ?MODULE:parse_request(State#state{
  382. buffer=Buffer, host_tokens=undefined, path_tokens=undefined,
  383. req_empty_lines=0, req_keepalive=Keepalive + 1});
  384. _Closed ->
  385. terminate(State)
  386. end.
  387. %% Only send an error reply if there is no resp_sent message.
  388. -spec error_terminate(cowboy_http:status(), #state{}) -> ok.
  389. error_terminate(Code, State=#state{socket=Socket, transport=Transport,
  390. onresponse=OnResponse}) ->
  391. receive
  392. {cowboy_req, resp_sent} -> ok
  393. after 0 ->
  394. _ = cowboy_req:reply(Code, cowboy_req:new(Socket, Transport,
  395. close, 'GET', {1, 1}, <<>>, <<>>, OnResponse, undefined)),
  396. ok
  397. end,
  398. terminate(State).
  399. -spec terminate(#state{}) -> ok.
  400. terminate(#state{socket=Socket, transport=Transport}) ->
  401. Transport:close(Socket),
  402. ok.
  403. %% Internal.
  404. -spec version_to_connection(cowboy_http:version()) -> keepalive | close.
  405. version_to_connection({1, 1}) -> keepalive;
  406. version_to_connection(_Any) -> close.
  407. -spec default_port(atom()) -> 80 | 443.
  408. default_port(ssl) -> 443;
  409. default_port(_) -> 80.
  410. %% @todo While 32 should be enough for everybody, we should probably make
  411. %% this configurable or something.
  412. -spec format_header(atom()) -> atom(); (binary()) -> binary().
  413. format_header(Field) when is_atom(Field) ->
  414. Field;
  415. format_header(Field) when byte_size(Field) =< 20; byte_size(Field) > 32 ->
  416. Field;
  417. format_header(Field) ->
  418. format_header(Field, true, <<>>).
  419. -spec format_header(binary(), boolean(), binary()) -> binary().
  420. format_header(<<>>, _Any, Acc) ->
  421. Acc;
  422. %% Replicate a bug in OTP for compatibility reasons when there's a - right
  423. %% after another. Proper use should always be 'true' instead of 'not Bool'.
  424. format_header(<< $-, Rest/bits >>, Bool, Acc) ->
  425. format_header(Rest, not Bool, << Acc/binary, $- >>);
  426. format_header(<< C, Rest/bits >>, true, Acc) ->
  427. format_header(Rest, false, << Acc/binary, (cowboy_bstr:char_to_upper(C)) >>);
  428. format_header(<< C, Rest/bits >>, false, Acc) ->
  429. format_header(Rest, false, << Acc/binary, (cowboy_bstr:char_to_lower(C)) >>).
  430. %% Tests.
  431. -ifdef(TEST).
  432. format_header_test_() ->
  433. %% {Header, Result}
  434. Tests = [
  435. {<<"Sec-Websocket-Version">>, <<"Sec-Websocket-Version">>},
  436. {<<"Sec-WebSocket-Version">>, <<"Sec-Websocket-Version">>},
  437. {<<"sec-websocket-version">>, <<"Sec-Websocket-Version">>},
  438. {<<"SEC-WEBSOCKET-VERSION">>, <<"Sec-Websocket-Version">>},
  439. %% These last tests ensures we're formatting headers exactly like OTP.
  440. %% Even though it's dumb, it's better for compatibility reasons.
  441. {<<"Sec-WebSocket--Version">>, <<"Sec-Websocket--version">>},
  442. {<<"Sec-WebSocket---Version">>, <<"Sec-Websocket---Version">>}
  443. ],
  444. [{H, fun() -> R = format_header(H) end} || {H, R} <- Tests].
  445. -endif.