cowboy_req.erl 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 request manipulation API.
  16. %%
  17. %% Almost all functions in this module return a new <em>Req</em> variable.
  18. %% It should always be used instead of the one used in your function call
  19. %% because it keeps the state of the request. It also allows Cowboy to do
  20. %% some lazy evaluation and cache results where possible.
  21. -module(cowboy_req).
  22. %% Request API.
  23. -export([method/1]).
  24. -export([version/1]).
  25. -export([peer/1]).
  26. -export([peer_addr/1]).
  27. -export([host/1]).
  28. -export([host_info/1]).
  29. -export([port/1]).
  30. -export([path/1]).
  31. -export([path_info/1]).
  32. -export([qs_val/2]).
  33. -export([qs_val/3]).
  34. -export([qs_vals/1]).
  35. -export([raw_qs/1]).
  36. -export([binding/2]).
  37. -export([binding/3]).
  38. -export([bindings/1]).
  39. -export([header/2]).
  40. -export([header/3]).
  41. -export([headers/1]).
  42. -export([parse_header/2]).
  43. -export([parse_header/3]).
  44. -export([cookie/2]).
  45. -export([cookie/3]).
  46. -export([cookies/1]).
  47. -export([meta/2]).
  48. -export([meta/3]).
  49. %% Request body API.
  50. -export([has_body/1]).
  51. -export([body_length/1]).
  52. -export([init_stream/4]).
  53. -export([stream_body/1]).
  54. -export([skip_body/1]).
  55. -export([body/1]).
  56. -export([body/2]).
  57. -export([body_qs/1]).
  58. -export([multipart_data/1]).
  59. -export([multipart_skip/1]).
  60. %% Response API.
  61. -export([set_resp_cookie/4]).
  62. -export([set_resp_header/3]).
  63. -export([set_resp_body/2]).
  64. -export([set_resp_body_fun/3]).
  65. -export([has_resp_header/2]).
  66. -export([has_resp_body/1]).
  67. -export([reply/2]).
  68. -export([reply/3]).
  69. -export([reply/4]).
  70. -export([chunked_reply/2]).
  71. -export([chunked_reply/3]).
  72. -export([chunk/2]).
  73. -export([upgrade_reply/3]).
  74. %% Misc API.
  75. -export([compact/1]).
  76. -export([to_list/1]).
  77. -export([transport/1]).
  78. -include("http.hrl").
  79. -type req() :: #http_req{}.
  80. -export_type([req/0]).
  81. %% Request API.
  82. %% @doc Return the HTTP method of the request.
  83. -spec method(Req) -> {cowboy_http:method(), Req} when Req::req().
  84. method(Req) ->
  85. {Req#http_req.method, Req}.
  86. %% @doc Return the HTTP version used for the request.
  87. -spec version(Req) -> {cowboy_http:version(), Req} when Req::req().
  88. version(Req) ->
  89. {Req#http_req.version, Req}.
  90. %% @doc Return the peer address and port number of the remote host.
  91. -spec peer(Req)
  92. -> {{inet:ip_address(), inet:port_number()}, Req} when Req::req().
  93. peer(Req=#http_req{socket=Socket, transport=Transport, peer=undefined}) ->
  94. {ok, Peer} = Transport:peername(Socket),
  95. {Peer, Req#http_req{peer=Peer}};
  96. peer(Req) ->
  97. {Req#http_req.peer, Req}.
  98. %% @doc Returns the peer address calculated from headers.
  99. -spec peer_addr(Req) -> {inet:ip_address(), Req} when Req::req().
  100. peer_addr(Req = #http_req{}) ->
  101. {RealIp, Req1} = header(<<"X-Real-Ip">>, Req),
  102. {ForwardedForRaw, Req2} = header(<<"X-Forwarded-For">>, Req1),
  103. {{PeerIp, _PeerPort}, Req3} = peer(Req2),
  104. ForwardedFor = case ForwardedForRaw of
  105. undefined ->
  106. undefined;
  107. ForwardedForRaw ->
  108. case re:run(ForwardedForRaw, "^(?<first_ip>[^\\,]+)",
  109. [{capture, [first_ip], binary}]) of
  110. {match, [FirstIp]} -> FirstIp;
  111. _Any -> undefined
  112. end
  113. end,
  114. {ok, PeerAddr} = if
  115. is_binary(RealIp) -> inet_parse:address(binary_to_list(RealIp));
  116. is_binary(ForwardedFor) -> inet_parse:address(binary_to_list(ForwardedFor));
  117. true -> {ok, PeerIp}
  118. end,
  119. {PeerAddr, Req3}.
  120. %% @doc Return the host binary string.
  121. -spec host(Req) -> {binary(), Req} when Req::req().
  122. host(Req) ->
  123. {Req#http_req.host, Req}.
  124. %% @doc Return the extra host information obtained from partially matching
  125. %% the hostname using <em>'...'</em>.
  126. -spec host_info(Req)
  127. -> {cowboy_dispatcher:tokens() | undefined, Req} when Req::req().
  128. host_info(Req) ->
  129. {Req#http_req.host_info, Req}.
  130. %% @doc Return the port used for this request.
  131. -spec port(Req) -> {inet:port_number(), Req} when Req::req().
  132. port(Req) ->
  133. {Req#http_req.port, Req}.
  134. %% @doc Return the path binary string.
  135. -spec path(Req) -> {binary(), Req} when Req::req().
  136. path(Req) ->
  137. {Req#http_req.path, Req}.
  138. %% @doc Return the extra path information obtained from partially matching
  139. %% the patch using <em>'...'</em>.
  140. -spec path_info(Req)
  141. -> {cowboy_dispatcher:tokens() | undefined, Req} when Req::req().
  142. path_info(Req) ->
  143. {Req#http_req.path_info, Req}.
  144. %% @equiv qs_val(Name, Req, undefined)
  145. -spec qs_val(binary(), Req)
  146. -> {binary() | true | undefined, Req} when Req::req().
  147. qs_val(Name, Req) when is_binary(Name) ->
  148. qs_val(Name, Req, undefined).
  149. %% @doc Return the query string value for the given key, or a default if
  150. %% missing.
  151. -spec qs_val(binary(), Req, Default)
  152. -> {binary() | true | Default, Req} when Req::req(), Default::any().
  153. qs_val(Name, Req=#http_req{raw_qs=RawQs, qs_vals=undefined,
  154. urldecode={URLDecFun, URLDecArg}}, Default) when is_binary(Name) ->
  155. QsVals = cowboy_http:x_www_form_urlencoded(
  156. RawQs, fun(Bin) -> URLDecFun(Bin, URLDecArg) end),
  157. qs_val(Name, Req#http_req{qs_vals=QsVals}, Default);
  158. qs_val(Name, Req, Default) ->
  159. case lists:keyfind(Name, 1, Req#http_req.qs_vals) of
  160. {Name, Value} -> {Value, Req};
  161. false -> {Default, Req}
  162. end.
  163. %% @doc Return the full list of query string values.
  164. -spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
  165. qs_vals(Req=#http_req{raw_qs=RawQs, qs_vals=undefined,
  166. urldecode={URLDecFun, URLDecArg}}) ->
  167. QsVals = cowboy_http:x_www_form_urlencoded(
  168. RawQs, fun(Bin) -> URLDecFun(Bin, URLDecArg) end),
  169. qs_vals(Req#http_req{qs_vals=QsVals});
  170. qs_vals(Req=#http_req{qs_vals=QsVals}) ->
  171. {QsVals, Req}.
  172. %% @doc Return the raw query string directly taken from the request.
  173. -spec raw_qs(Req) -> {binary(), Req} when Req::req().
  174. raw_qs(Req) ->
  175. {Req#http_req.raw_qs, Req}.
  176. %% @equiv binding(Name, Req, undefined)
  177. -spec binding(atom(), Req) -> {binary() | undefined, Req} when Req::req().
  178. binding(Name, Req) when is_atom(Name) ->
  179. binding(Name, Req, undefined).
  180. %% @doc Return the binding value for the given key obtained when matching
  181. %% the host and path against the dispatch list, or a default if missing.
  182. -spec binding(atom(), Req, Default)
  183. -> {binary() | Default, Req} when Req::req(), Default::any().
  184. binding(Name, Req, Default) when is_atom(Name) ->
  185. case lists:keyfind(Name, 1, Req#http_req.bindings) of
  186. {Name, Value} -> {Value, Req};
  187. false -> {Default, Req}
  188. end.
  189. %% @doc Return the full list of binding values.
  190. -spec bindings(Req) -> {list({atom(), binary()}), Req} when Req::req().
  191. bindings(Req) ->
  192. {Req#http_req.bindings, Req}.
  193. %% @equiv header(Name, Req, undefined)
  194. -spec header(atom() | binary(), Req)
  195. -> {binary() | undefined, Req} when Req::req().
  196. header(Name, Req) when is_atom(Name) orelse is_binary(Name) ->
  197. header(Name, Req, undefined).
  198. %% @doc Return the header value for the given key, or a default if missing.
  199. -spec header(atom() | binary(), Req, Default)
  200. -> {binary() | Default, Req} when Req::req(), Default::any().
  201. header(Name, Req, Default) when is_atom(Name) orelse is_binary(Name) ->
  202. case lists:keyfind(Name, 1, Req#http_req.headers) of
  203. {Name, Value} -> {Value, Req};
  204. false -> {Default, Req}
  205. end.
  206. %% @doc Return the full list of headers.
  207. -spec headers(Req) -> {cowboy_http:headers(), Req} when Req::req().
  208. headers(Req) ->
  209. {Req#http_req.headers, Req}.
  210. %% @doc Semantically parse headers.
  211. %%
  212. %% When the value isn't found, a proper default value for the type
  213. %% returned is used as a return value.
  214. %% @see parse_header/3
  215. -spec parse_header(cowboy_http:header(), Req)
  216. -> {any(), Req} | {undefined, binary(), Req}
  217. | {error, badarg} when Req::req().
  218. parse_header(Name, Req=#http_req{p_headers=PHeaders}) ->
  219. case lists:keyfind(Name, 1, PHeaders) of
  220. false -> parse_header(Name, Req, parse_header_default(Name));
  221. {Name, Value} -> {Value, Req}
  222. end.
  223. %% @doc Default values for semantic header parsing.
  224. -spec parse_header_default(cowboy_http:header()) -> any().
  225. parse_header_default('Connection') -> [];
  226. parse_header_default('Transfer-Encoding') -> [<<"identity">>];
  227. parse_header_default(_Name) -> undefined.
  228. %% @doc Semantically parse headers.
  229. %%
  230. %% When the header is unknown, the value is returned directly without parsing.
  231. -spec parse_header(cowboy_http:header(), Req, any())
  232. -> {any(), Req} | {undefined, binary(), Req}
  233. | {error, badarg} when Req::req().
  234. parse_header(Name, Req, Default) when Name =:= 'Accept' ->
  235. parse_header(Name, Req, Default,
  236. fun (Value) ->
  237. cowboy_http:list(Value, fun cowboy_http:media_range/2)
  238. end);
  239. parse_header(Name, Req, Default) when Name =:= 'Accept-Charset' ->
  240. parse_header(Name, Req, Default,
  241. fun (Value) ->
  242. cowboy_http:nonempty_list(Value, fun cowboy_http:conneg/2)
  243. end);
  244. parse_header(Name, Req, Default) when Name =:= 'Accept-Encoding' ->
  245. parse_header(Name, Req, Default,
  246. fun (Value) ->
  247. cowboy_http:list(Value, fun cowboy_http:conneg/2)
  248. end);
  249. parse_header(Name, Req, Default) when Name =:= 'Accept-Language' ->
  250. parse_header(Name, Req, Default,
  251. fun (Value) ->
  252. cowboy_http:nonempty_list(Value, fun cowboy_http:language_range/2)
  253. end);
  254. parse_header(Name, Req, Default) when Name =:= 'Connection' ->
  255. parse_header(Name, Req, Default,
  256. fun (Value) ->
  257. cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2)
  258. end);
  259. parse_header(Name, Req, Default) when Name =:= 'Content-Length' ->
  260. parse_header(Name, Req, Default,
  261. fun (Value) ->
  262. cowboy_http:digits(Value)
  263. end);
  264. parse_header(Name, Req, Default) when Name =:= 'Content-Type' ->
  265. parse_header(Name, Req, Default,
  266. fun (Value) ->
  267. cowboy_http:content_type(Value)
  268. end);
  269. parse_header(Name, Req, Default) when Name =:= <<"Expect">> ->
  270. parse_header(Name, Req, Default,
  271. fun (Value) ->
  272. cowboy_http:nonempty_list(Value, fun cowboy_http:expectation/2)
  273. end);
  274. parse_header(Name, Req, Default)
  275. when Name =:= 'If-Match'; Name =:= 'If-None-Match' ->
  276. parse_header(Name, Req, Default,
  277. fun (Value) ->
  278. cowboy_http:entity_tag_match(Value)
  279. end);
  280. parse_header(Name, Req, Default)
  281. when Name =:= 'If-Modified-Since'; Name =:= 'If-Unmodified-Since' ->
  282. parse_header(Name, Req, Default,
  283. fun (Value) ->
  284. cowboy_http:http_date(Value)
  285. end);
  286. %% @todo Extension parameters.
  287. parse_header(Name, Req, Default) when Name =:= 'Transfer-Encoding' ->
  288. parse_header(Name, Req, Default,
  289. fun (Value) ->
  290. cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2)
  291. end);
  292. parse_header(Name, Req, Default) when Name =:= 'Upgrade' ->
  293. parse_header(Name, Req, Default,
  294. fun (Value) ->
  295. cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2)
  296. end);
  297. parse_header(Name, Req, Default) ->
  298. {Value, Req2} = header(Name, Req, Default),
  299. {undefined, Value, Req2}.
  300. parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) ->
  301. case lists:keyfind(Name, 1, PHeaders) of
  302. {Name, P} ->
  303. {P, Req};
  304. false ->
  305. parse_header_no_cache(Name, Req, Default, Fun)
  306. end.
  307. parse_header_no_cache(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) ->
  308. case header(Name, Req) of
  309. {undefined, Req2} ->
  310. {Default, Req2#http_req{p_headers=[{Name, Default}|PHeaders]}};
  311. {Value, Req2} ->
  312. case Fun(Value) of
  313. {error, badarg} ->
  314. {error, badarg};
  315. P ->
  316. {P, Req2#http_req{p_headers=[{Name, P}|PHeaders]}}
  317. end
  318. end.
  319. %% @equiv cookie(Name, Req, undefined)
  320. -spec cookie(binary(), Req)
  321. -> {binary() | true | undefined, Req} when Req::req().
  322. cookie(Name, Req) when is_binary(Name) ->
  323. cookie(Name, Req, undefined).
  324. %% @doc Return the cookie value for the given key, or a default if
  325. %% missing.
  326. -spec cookie(binary(), Req, Default)
  327. -> {binary() | true | Default, Req} when Req::req(), Default::any().
  328. cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) ->
  329. case header('Cookie', Req) of
  330. {undefined, Req2} ->
  331. {Default, Req2#http_req{cookies=[]}};
  332. {RawCookie, Req2} ->
  333. Cookies = cowboy_cookies:parse_cookie(RawCookie),
  334. cookie(Name, Req2#http_req{cookies=Cookies}, Default)
  335. end;
  336. cookie(Name, Req, Default) ->
  337. case lists:keyfind(Name, 1, Req#http_req.cookies) of
  338. {Name, Value} -> {Value, Req};
  339. false -> {Default, Req}
  340. end.
  341. %% @doc Return the full list of cookie values.
  342. -spec cookies(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
  343. cookies(Req=#http_req{cookies=undefined}) ->
  344. case header('Cookie', Req) of
  345. {undefined, Req2} ->
  346. {[], Req2#http_req{cookies=[]}};
  347. {RawCookie, Req2} ->
  348. Cookies = cowboy_cookies:parse_cookie(RawCookie),
  349. cookies(Req2#http_req{cookies=Cookies})
  350. end;
  351. cookies(Req=#http_req{cookies=Cookies}) ->
  352. {Cookies, Req}.
  353. %% @equiv meta(Name, Req, undefined)
  354. -spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req().
  355. meta(Name, Req) ->
  356. meta(Name, Req, undefined).
  357. %% @doc Return metadata information about the request.
  358. %%
  359. %% Metadata information varies from one protocol to another. Websockets
  360. %% would define the protocol version here, while REST would use it to
  361. %% indicate which media type, language and charset were retained.
  362. -spec meta(atom(), Req, any()) -> {any(), Req} when Req::req().
  363. meta(Name, Req, Default) ->
  364. case lists:keyfind(Name, 1, Req#http_req.meta) of
  365. {Name, Value} -> {Value, Req};
  366. false -> {Default, Req}
  367. end.
  368. %% Request Body API.
  369. %% @doc Return whether the request message has a body.
  370. -spec has_body(Req) -> {boolean(), Req} when Req::req().
  371. has_body(Req) ->
  372. Has = lists:keymember('Content-Length', 1, Req#http_req.headers) orelse
  373. lists:keymember('Transfer-Encoding', 1, Req#http_req.headers),
  374. {Has, Req}.
  375. %% @doc Return the request message body length, if known.
  376. %%
  377. %% The length may not be known if Transfer-Encoding is not identity,
  378. %% and the body hasn't been read at the time of the call.
  379. -spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req().
  380. body_length(Req) ->
  381. case lists:keymember('Transfer-Encoding', 1, Req#http_req.headers) of
  382. true -> {undefined, Req};
  383. false -> parse_header('Content-Length', Req, 0)
  384. end.
  385. %% @doc Initialize body streaming and set custom decoding functions.
  386. %%
  387. %% Calling this function is optional. It should only be used if you
  388. %% need to override the default behavior of Cowboy. Otherwise you
  389. %% should call stream_body/1 directly.
  390. %%
  391. %% Two decodings happen. First a decoding function is applied to the
  392. %% transferred data, and then another is applied to the actual content.
  393. %%
  394. %% Transfer encoding is generally used for chunked bodies. The decoding
  395. %% function uses a state to keep track of how much it has read, which is
  396. %% also initialized through this function.
  397. %%
  398. %% Content encoding is generally used for compression.
  399. %%
  400. %% Standard encodings can be found in cowboy_http.
  401. -spec init_stream(fun(), any(), fun(), Req) -> {ok, Req} when Req::req().
  402. init_stream(TransferDecode, TransferState, ContentDecode, Req) ->
  403. {ok, Req#http_req{body_state=
  404. {stream, TransferDecode, TransferState, ContentDecode}}}.
  405. %% @doc Stream the request's body.
  406. %%
  407. %% This is the most low level function to read the request body.
  408. %%
  409. %% In most cases, if they weren't defined before using stream_body/4,
  410. %% this function will guess which transfer and content encodings were
  411. %% used for building the request body, and configure the decoding
  412. %% functions that will be used when streaming.
  413. %%
  414. %% It then starts streaming the body, returning {ok, Data, Req}
  415. %% for each streamed part, and {done, Req} when it's finished streaming.
  416. -spec stream_body(Req) -> {ok, binary(), Req}
  417. | {done, Req} | {error, atom()} when Req::req().
  418. stream_body(Req=#http_req{body_state=waiting,
  419. version=Version, transport=Transport, socket=Socket}) ->
  420. case parse_header(<<"Expect">>, Req) of
  421. {[<<"100-continue">>], Req1} ->
  422. HTTPVer = cowboy_http:version_to_binary(Version),
  423. Transport:send(Socket,
  424. << HTTPVer/binary, " ", (status(100))/binary, "\r\n\r\n" >>);
  425. {undefined, Req1} ->
  426. ok;
  427. {undefined, _, Req1} ->
  428. ok
  429. end,
  430. case parse_header('Transfer-Encoding', Req1) of
  431. {[<<"chunked">>], Req2} ->
  432. stream_body(Req2#http_req{body_state=
  433. {stream, fun cowboy_http:te_chunked/2, {0, 0},
  434. fun cowboy_http:ce_identity/1}});
  435. {[<<"identity">>], Req2} ->
  436. {Length, Req3} = body_length(Req2),
  437. case Length of
  438. 0 ->
  439. {done, Req3#http_req{body_state=done}};
  440. Length ->
  441. stream_body(Req3#http_req{body_state=
  442. {stream, fun cowboy_http:te_identity/2, {0, Length},
  443. fun cowboy_http:ce_identity/1}})
  444. end
  445. end;
  446. stream_body(Req=#http_req{buffer=Buffer, body_state={stream, _, _, _}})
  447. when Buffer =/= <<>> ->
  448. transfer_decode(Buffer, Req#http_req{buffer= <<>>});
  449. stream_body(Req=#http_req{body_state={stream, _, _, _}}) ->
  450. stream_body_recv(Req);
  451. stream_body(Req=#http_req{body_state=done}) ->
  452. {done, Req}.
  453. -spec stream_body_recv(Req)
  454. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  455. stream_body_recv(Req=#http_req{
  456. transport=Transport, socket=Socket, buffer=Buffer}) ->
  457. %% @todo Allow configuring the timeout.
  458. case Transport:recv(Socket, 0, 5000) of
  459. {ok, Data} -> transfer_decode(<< Buffer/binary, Data/binary >>, Req);
  460. {error, Reason} -> {error, Reason}
  461. end.
  462. -spec transfer_decode(binary(), Req)
  463. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  464. transfer_decode(Data, Req=#http_req{
  465. body_state={stream, TransferDecode, TransferState, ContentDecode}}) ->
  466. case TransferDecode(Data, TransferState) of
  467. {ok, Data2, TransferState2} ->
  468. content_decode(ContentDecode, Data2, Req#http_req{body_state=
  469. {stream, TransferDecode, TransferState2, ContentDecode}});
  470. {ok, Data2, Rest, TransferState2} ->
  471. content_decode(ContentDecode, Data2, Req#http_req{
  472. buffer=Rest, body_state=
  473. {stream, TransferDecode, TransferState2, ContentDecode}});
  474. %% @todo {header(s) for chunked
  475. more ->
  476. stream_body_recv(Req#http_req{buffer=Data});
  477. {done, Length, Rest} ->
  478. Req2 = transfer_decode_done(Length, Rest, Req),
  479. {done, Req2};
  480. {done, Data2, Length, Rest} ->
  481. Req2 = transfer_decode_done(Length, Rest, Req),
  482. content_decode(ContentDecode, Data2, Req2);
  483. {error, Reason} ->
  484. {error, Reason}
  485. end.
  486. -spec transfer_decode_done(non_neg_integer(), binary(), Req)
  487. -> Req when Req::req().
  488. transfer_decode_done(Length, Rest, Req=#http_req{
  489. headers=Headers, p_headers=PHeaders}) ->
  490. Headers2 = lists:keystore('Content-Length', 1, Headers,
  491. {'Content-Length', list_to_binary(integer_to_list(Length))}),
  492. %% At this point we just assume TEs were all decoded.
  493. Headers3 = lists:keydelete('Transfer-Encoding', 1, Headers2),
  494. PHeaders2 = lists:keystore('Content-Length', 1, PHeaders,
  495. {'Content-Length', Length}),
  496. PHeaders3 = lists:keydelete('Transfer-Encoding', 1, PHeaders2),
  497. Req#http_req{buffer=Rest, body_state=done,
  498. headers=Headers3, p_headers=PHeaders3}.
  499. %% @todo Probably needs a Rest.
  500. -spec content_decode(fun(), binary(), Req)
  501. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  502. content_decode(ContentDecode, Data, Req) ->
  503. case ContentDecode(Data) of
  504. {ok, Data2} -> {ok, Data2, Req};
  505. {error, Reason} -> {error, Reason}
  506. end.
  507. %% @doc Return the full body sent with the request.
  508. -spec body(Req) -> {ok, binary(), Req} | {error, atom()} when Req::req().
  509. body(Req) ->
  510. read_body(infinity, Req, <<>>).
  511. %% @doc Return the full body sent with the request as long as the body
  512. %% length doesn't go over MaxLength.
  513. %%
  514. %% This is most useful to quickly be able to get the full body while
  515. %% avoiding filling your memory with huge request bodies when you're
  516. %% not expecting it.
  517. -spec body(non_neg_integer() | infinity, Req)
  518. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  519. body(MaxLength, Req) ->
  520. read_body(MaxLength, Req, <<>>).
  521. -spec read_body(non_neg_integer() | infinity, Req, binary())
  522. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  523. read_body(MaxLength, Req, Acc) when MaxLength > byte_size(Acc) ->
  524. case stream_body(Req) of
  525. {ok, Data, Req2} ->
  526. read_body(MaxLength, Req2, << Acc/binary, Data/binary >>);
  527. {done, Req2} ->
  528. {ok, Acc, Req2};
  529. {error, Reason} ->
  530. {error, Reason}
  531. end.
  532. -spec skip_body(Req) -> {ok, Req} | {error, atom()} when Req::req().
  533. skip_body(Req) ->
  534. case stream_body(Req) of
  535. {ok, _, Req2} -> skip_body(Req2);
  536. {done, Req2} -> {ok, Req2};
  537. {error, Reason} -> {error, Reason}
  538. end.
  539. %% @doc Return the full body sent with the reqest, parsed as an
  540. %% application/x-www-form-urlencoded string. Essentially a POST query string.
  541. %% @todo We need an option to limit the size of the body for QS too.
  542. -spec body_qs(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
  543. body_qs(Req=#http_req{urldecode={URLDecFun, URLDecArg}}) ->
  544. {ok, Body, Req2} = body(Req),
  545. {cowboy_http:x_www_form_urlencoded(
  546. Body, fun(Bin) -> URLDecFun(Bin, URLDecArg) end), Req2}.
  547. %% Multipart Request API.
  548. %% @doc Return data from the multipart parser.
  549. %%
  550. %% Use this function for multipart streaming. For each part in the request,
  551. %% this function returns <em>{headers, Headers}</em> followed by a sequence of
  552. %% <em>{body, Data}</em> tuples and finally <em>end_of_part</em>. When there
  553. %% is no part to parse anymore, <em>eof</em> is returned.
  554. %%
  555. %% If the request Content-Type is not a multipart one, <em>{error, badarg}</em>
  556. %% is returned.
  557. -spec multipart_data(Req)
  558. -> {{headers, cowboy_http:headers()} | {body, binary()}
  559. | end_of_part | eof, Req} when Req::req().
  560. multipart_data(Req=#http_req{body_state=waiting}) ->
  561. {{<<"multipart">>, _SubType, Params}, Req2} =
  562. parse_header('Content-Type', Req),
  563. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  564. {Length, Req3} = parse_header('Content-Length', Req2),
  565. multipart_data(Req3, Length, {more, cowboy_multipart:parser(Boundary)});
  566. multipart_data(Req=#http_req{multipart={Length, Cont}}) ->
  567. multipart_data(Req, Length, Cont());
  568. multipart_data(Req=#http_req{body_state=done}) ->
  569. {eof, Req}.
  570. %% @todo Typespecs.
  571. multipart_data(Req, Length, {headers, Headers, Cont}) ->
  572. {{headers, Headers}, Req#http_req{multipart={Length, Cont}}};
  573. multipart_data(Req, Length, {body, Data, Cont}) ->
  574. {{body, Data}, Req#http_req{multipart={Length, Cont}}};
  575. multipart_data(Req, Length, {end_of_part, Cont}) ->
  576. {end_of_part, Req#http_req{multipart={Length, Cont}}};
  577. multipart_data(Req, 0, eof) ->
  578. {eof, Req#http_req{body_state=done, multipart=undefined}};
  579. multipart_data(Req=#http_req{socket=Socket, transport=Transport},
  580. Length, eof) ->
  581. %% We just want to skip so no need to stream data here.
  582. {ok, _Data} = Transport:recv(Socket, Length, 5000),
  583. {eof, Req#http_req{body_state=done, multipart=undefined}};
  584. multipart_data(Req, Length, {more, Parser}) when Length > 0 ->
  585. case stream_body(Req) of
  586. {ok, << Data:Length/binary, Buffer/binary >>, Req2} ->
  587. multipart_data(Req2#http_req{buffer=Buffer}, 0, Parser(Data));
  588. {ok, Data, Req2} ->
  589. multipart_data(Req2, Length - byte_size(Data), Parser(Data))
  590. end.
  591. %% @doc Skip a part returned by the multipart parser.
  592. %%
  593. %% This function repeatedly calls <em>multipart_data/1</em> until
  594. %% <em>end_of_part</em> or <em>eof</em> is parsed.
  595. -spec multipart_skip(Req) -> {ok, Req} when Req::req().
  596. multipart_skip(Req) ->
  597. case multipart_data(Req) of
  598. {end_of_part, Req2} -> {ok, Req2};
  599. {eof, Req2} -> {ok, Req2};
  600. {_Other, Req2} -> multipart_skip(Req2)
  601. end.
  602. %% Response API.
  603. %% @doc Add a cookie header to the response.
  604. -spec set_resp_cookie(binary(), binary(),
  605. [cowboy_cookies:cookie_option()], Req) -> {ok, Req} when Req::req().
  606. set_resp_cookie(Name, Value, Options, Req) ->
  607. {HeaderName, HeaderValue} = cowboy_cookies:cookie(Name, Value, Options),
  608. set_resp_header(HeaderName, HeaderValue, Req).
  609. %% @doc Add a header to the response.
  610. -spec set_resp_header(cowboy_http:header(), iodata(), Req)
  611. -> {ok, Req} when Req::req().
  612. set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
  613. NameBin = header_to_binary(Name),
  614. {ok, Req#http_req{resp_headers=[{NameBin, Value}|RespHeaders]}}.
  615. %% @doc Add a body to the response.
  616. %%
  617. %% The body set here is ignored if the response is later sent using
  618. %% anything other than reply/2 or reply/3. The response body is expected
  619. %% to be a binary or an iolist.
  620. -spec set_resp_body(iodata(), Req) -> {ok, Req} when Req::req().
  621. set_resp_body(Body, Req) ->
  622. {ok, Req#http_req{resp_body=Body}}.
  623. %% @doc Add a body function to the response.
  624. %%
  625. %% The response body may also be set to a content-length - stream-function pair.
  626. %% If the response body is of this type normal response headers will be sent.
  627. %% After the response headers has been sent the body function is applied.
  628. %% The body function is expected to write the response body directly to the
  629. %% socket using the transport module.
  630. %%
  631. %% If the body function crashes while writing the response body or writes fewer
  632. %% bytes than declared the behaviour is undefined. The body set here is ignored
  633. %% if the response is later sent using anything other than `reply/2' or
  634. %% `reply/3'.
  635. %%
  636. %% @see cowboy_req:transport/1.
  637. -spec set_resp_body_fun(non_neg_integer(),
  638. fun(() -> {sent, non_neg_integer()}), Req) -> {ok, Req} when Req::req().
  639. set_resp_body_fun(StreamLen, StreamFun, Req) ->
  640. {ok, Req#http_req{resp_body={StreamLen, StreamFun}}}.
  641. %% @doc Return whether the given header has been set for the response.
  642. -spec has_resp_header(cowboy_http:header(), req()) -> boolean().
  643. has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
  644. NameBin = header_to_binary(Name),
  645. lists:keymember(NameBin, 1, RespHeaders).
  646. %% @doc Return whether a body has been set for the response.
  647. -spec has_resp_body(req()) -> boolean().
  648. has_resp_body(#http_req{resp_body={Length, _}}) ->
  649. Length > 0;
  650. has_resp_body(#http_req{resp_body=RespBody}) ->
  651. iolist_size(RespBody) > 0.
  652. %% @equiv reply(Status, [], [], Req)
  653. -spec reply(cowboy_http:status(), Req) -> {ok, Req} when Req::req().
  654. reply(Status, Req=#http_req{resp_body=Body}) ->
  655. reply(Status, [], Body, Req).
  656. %% @equiv reply(Status, Headers, [], Req)
  657. -spec reply(cowboy_http:status(), cowboy_http:headers(), Req)
  658. -> {ok, Req} when Req::req().
  659. reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
  660. reply(Status, Headers, Body, Req).
  661. %% @doc Send a reply to the client.
  662. -spec reply(cowboy_http:status(), cowboy_http:headers(), iodata(), Req)
  663. -> {ok, Req} when Req::req().
  664. reply(Status, Headers, Body, Req=#http_req{socket=Socket, transport=Transport,
  665. version=Version, connection=Connection,
  666. method=Method, resp_state=waiting, resp_headers=RespHeaders}) ->
  667. RespConn = response_connection(Headers, Connection),
  668. ContentLen = case Body of {CL, _} -> CL; _ -> iolist_size(Body) end,
  669. HTTP11Headers = case Version of
  670. {1, 1} -> [{<<"Connection">>, atom_to_connection(Connection)}];
  671. _ -> []
  672. end,
  673. {ReplyType, Req2} = response(Status, Headers, RespHeaders, [
  674. {<<"Content-Length">>, integer_to_list(ContentLen)},
  675. {<<"Date">>, cowboy_clock:rfc1123()},
  676. {<<"Server">>, <<"Cowboy">>}
  677. |HTTP11Headers], Req),
  678. if Method =:= 'HEAD' -> ok;
  679. ReplyType =:= hook -> ok; %% Hook replied for us, stop there.
  680. true ->
  681. case Body of
  682. {_, StreamFun} -> StreamFun();
  683. _ -> Transport:send(Socket, Body)
  684. end
  685. end,
  686. {ok, Req2#http_req{connection=RespConn, resp_state=done,
  687. resp_headers=[], resp_body= <<>>}}.
  688. %% @equiv chunked_reply(Status, [], Req)
  689. -spec chunked_reply(cowboy_http:status(), Req) -> {ok, Req} when Req::req().
  690. chunked_reply(Status, Req) ->
  691. chunked_reply(Status, [], Req).
  692. %% @doc Initiate the sending of a chunked reply to the client.
  693. %% @see cowboy_req:chunk/2
  694. -spec chunked_reply(cowboy_http:status(), cowboy_http:headers(), Req)
  695. -> {ok, Req} when Req::req().
  696. chunked_reply(Status, Headers, Req=#http_req{
  697. version=Version, connection=Connection,
  698. resp_state=waiting, resp_headers=RespHeaders}) ->
  699. RespConn = response_connection(Headers, Connection),
  700. HTTP11Headers = case Version of
  701. {1, 1} -> [
  702. {<<"Connection">>, atom_to_connection(Connection)},
  703. {<<"Transfer-Encoding">>, <<"chunked">>}];
  704. _ -> []
  705. end,
  706. {_, Req2} = response(Status, Headers, RespHeaders, [
  707. {<<"Date">>, cowboy_clock:rfc1123()},
  708. {<<"Server">>, <<"Cowboy">>}
  709. |HTTP11Headers], Req),
  710. {ok, Req2#http_req{connection=RespConn, resp_state=chunks,
  711. resp_headers=[], resp_body= <<>>}}.
  712. %% @doc Send a chunk of data.
  713. %%
  714. %% A chunked reply must have been initiated before calling this function.
  715. -spec chunk(iodata(), req()) -> ok | {error, atom()}.
  716. chunk(_Data, #http_req{socket=_Socket, transport=_Transport, method='HEAD'}) ->
  717. ok;
  718. chunk(Data, #http_req{socket=Socket, transport=Transport, version={1, 0}}) ->
  719. Transport:send(Socket, Data);
  720. chunk(Data, #http_req{socket=Socket, transport=Transport, resp_state=chunks}) ->
  721. Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
  722. <<"\r\n">>, Data, <<"\r\n">>]).
  723. %% @doc Send an upgrade reply.
  724. %% @private
  725. -spec upgrade_reply(cowboy_http:status(), cowboy_http:headers(), Req)
  726. -> {ok, Req} when Req::req().
  727. upgrade_reply(Status, Headers, Req=#http_req{
  728. resp_state=waiting, resp_headers=RespHeaders}) ->
  729. {_, Req2} = response(Status, Headers, RespHeaders, [
  730. {<<"Connection">>, <<"Upgrade">>}
  731. ], Req),
  732. {ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  733. %% Misc API.
  734. %% @doc Compact the request data by removing all non-system information.
  735. %%
  736. %% This essentially removes the host and path info, query string, bindings,
  737. %% headers and cookies.
  738. %%
  739. %% Use it when you really need to save up memory, for example when having
  740. %% many concurrent long-running connections.
  741. -spec compact(Req) -> Req when Req::req().
  742. compact(Req) ->
  743. Req#http_req{host_info=undefined,
  744. path_info=undefined, qs_vals=undefined,
  745. bindings=undefined, headers=[],
  746. p_headers=[], cookies=[]}.
  747. %% @doc Convert the Req object to a list of key/values.
  748. -spec to_list(req()) -> [{atom(), any()}].
  749. to_list(Req) ->
  750. lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))).
  751. %% @doc Return the transport module and socket associated with a request.
  752. %%
  753. %% This exposes the same socket interface used internally by the HTTP protocol
  754. %% implementation to developers that needs low level access to the socket.
  755. %%
  756. %% It is preferred to use this in conjuction with the stream function support
  757. %% in `set_resp_body_fun/3' if this is used to write a response body directly
  758. %% to the socket. This ensures that the response headers are set correctly.
  759. -spec transport(req()) -> {ok, module(), inet:socket()}.
  760. transport(#http_req{transport=Transport, socket=Socket}) ->
  761. {ok, Transport, Socket}.
  762. %% Internal.
  763. -spec response(cowboy_http:status(), cowboy_http:headers(),
  764. cowboy_http:headers(), cowboy_http:headers(), Req)
  765. -> {normal | hook, Req} when Req::req().
  766. response(Status, Headers, RespHeaders, DefaultHeaders, Req=#http_req{
  767. socket=Socket, transport=Transport, version=Version,
  768. pid=ReqPid, onresponse=OnResponse}) ->
  769. FullHeaders = response_merge_headers(Headers, RespHeaders, DefaultHeaders),
  770. Req2 = case OnResponse of
  771. undefined -> Req;
  772. OnResponse -> OnResponse(Status, FullHeaders,
  773. %% Don't call 'onresponse' from the hook itself.
  774. Req#http_req{resp_headers=[], resp_body= <<>>,
  775. onresponse=undefined})
  776. end,
  777. ReplyType = case Req2#http_req.resp_state of
  778. waiting ->
  779. HTTPVer = cowboy_http:version_to_binary(Version),
  780. StatusLine = << HTTPVer/binary, " ",
  781. (status(Status))/binary, "\r\n" >>,
  782. HeaderLines = [[Key, <<": ">>, Value, <<"\r\n">>]
  783. || {Key, Value} <- FullHeaders],
  784. Transport:send(Socket, [StatusLine, HeaderLines, <<"\r\n">>]),
  785. ReqPid ! {?MODULE, resp_sent},
  786. normal;
  787. _ ->
  788. hook
  789. end,
  790. {ReplyType, Req2}.
  791. -spec response_connection(cowboy_http:headers(), keepalive | close)
  792. -> keepalive | close.
  793. response_connection([], Connection) ->
  794. Connection;
  795. response_connection([{Name, Value}|Tail], Connection) ->
  796. case Name of
  797. 'Connection' -> response_connection_parse(Value);
  798. Name when is_atom(Name) -> response_connection(Tail, Connection);
  799. Name ->
  800. Name2 = cowboy_bstr:to_lower(Name),
  801. case Name2 of
  802. <<"connection">> -> response_connection_parse(Value);
  803. _Any -> response_connection(Tail, Connection)
  804. end
  805. end.
  806. -spec response_connection_parse(binary()) -> keepalive | close.
  807. response_connection_parse(ReplyConn) ->
  808. Tokens = cowboy_http:nonempty_list(ReplyConn, fun cowboy_http:token/2),
  809. cowboy_http:connection_to_atom(Tokens).
  810. -spec response_merge_headers(cowboy_http:headers(), cowboy_http:headers(),
  811. cowboy_http:headers()) -> cowboy_http:headers().
  812. response_merge_headers(Headers, RespHeaders, DefaultHeaders) ->
  813. Headers2 = [{header_to_binary(Key), Value} || {Key, Value} <- Headers],
  814. merge_headers(
  815. merge_headers(Headers2, RespHeaders),
  816. DefaultHeaders).
  817. -spec merge_headers(cowboy_http:headers(), cowboy_http:headers())
  818. -> cowboy_http:headers().
  819. merge_headers(Headers, []) ->
  820. Headers;
  821. merge_headers(Headers, [{Name, Value}|Tail]) ->
  822. Headers2 = case lists:keymember(Name, 1, Headers) of
  823. true -> Headers;
  824. false -> Headers ++ [{Name, Value}]
  825. end,
  826. merge_headers(Headers2, Tail).
  827. -spec atom_to_connection(keepalive) -> <<_:80>>;
  828. (close) -> <<_:40>>.
  829. atom_to_connection(keepalive) ->
  830. <<"keep-alive">>;
  831. atom_to_connection(close) ->
  832. <<"close">>.
  833. -spec status(cowboy_http:status()) -> binary().
  834. status(100) -> <<"100 Continue">>;
  835. status(101) -> <<"101 Switching Protocols">>;
  836. status(102) -> <<"102 Processing">>;
  837. status(200) -> <<"200 OK">>;
  838. status(201) -> <<"201 Created">>;
  839. status(202) -> <<"202 Accepted">>;
  840. status(203) -> <<"203 Non-Authoritative Information">>;
  841. status(204) -> <<"204 No Content">>;
  842. status(205) -> <<"205 Reset Content">>;
  843. status(206) -> <<"206 Partial Content">>;
  844. status(207) -> <<"207 Multi-Status">>;
  845. status(226) -> <<"226 IM Used">>;
  846. status(300) -> <<"300 Multiple Choices">>;
  847. status(301) -> <<"301 Moved Permanently">>;
  848. status(302) -> <<"302 Found">>;
  849. status(303) -> <<"303 See Other">>;
  850. status(304) -> <<"304 Not Modified">>;
  851. status(305) -> <<"305 Use Proxy">>;
  852. status(306) -> <<"306 Switch Proxy">>;
  853. status(307) -> <<"307 Temporary Redirect">>;
  854. status(400) -> <<"400 Bad Request">>;
  855. status(401) -> <<"401 Unauthorized">>;
  856. status(402) -> <<"402 Payment Required">>;
  857. status(403) -> <<"403 Forbidden">>;
  858. status(404) -> <<"404 Not Found">>;
  859. status(405) -> <<"405 Method Not Allowed">>;
  860. status(406) -> <<"406 Not Acceptable">>;
  861. status(407) -> <<"407 Proxy Authentication Required">>;
  862. status(408) -> <<"408 Request Timeout">>;
  863. status(409) -> <<"409 Conflict">>;
  864. status(410) -> <<"410 Gone">>;
  865. status(411) -> <<"411 Length Required">>;
  866. status(412) -> <<"412 Precondition Failed">>;
  867. status(413) -> <<"413 Request Entity Too Large">>;
  868. status(414) -> <<"414 Request-URI Too Long">>;
  869. status(415) -> <<"415 Unsupported Media Type">>;
  870. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  871. status(417) -> <<"417 Expectation Failed">>;
  872. status(418) -> <<"418 I'm a teapot">>;
  873. status(422) -> <<"422 Unprocessable Entity">>;
  874. status(423) -> <<"423 Locked">>;
  875. status(424) -> <<"424 Failed Dependency">>;
  876. status(425) -> <<"425 Unordered Collection">>;
  877. status(426) -> <<"426 Upgrade Required">>;
  878. status(428) -> <<"428 Precondition Required">>;
  879. status(429) -> <<"429 Too Many Requests">>;
  880. status(431) -> <<"431 Request Header Fields Too Large">>;
  881. status(500) -> <<"500 Internal Server Error">>;
  882. status(501) -> <<"501 Not Implemented">>;
  883. status(502) -> <<"502 Bad Gateway">>;
  884. status(503) -> <<"503 Service Unavailable">>;
  885. status(504) -> <<"504 Gateway Timeout">>;
  886. status(505) -> <<"505 HTTP Version Not Supported">>;
  887. status(506) -> <<"506 Variant Also Negotiates">>;
  888. status(507) -> <<"507 Insufficient Storage">>;
  889. status(510) -> <<"510 Not Extended">>;
  890. status(511) -> <<"511 Network Authentication Required">>;
  891. status(B) when is_binary(B) -> B.
  892. -spec header_to_binary(cowboy_http:header()) -> binary().
  893. header_to_binary('Cache-Control') -> <<"Cache-Control">>;
  894. header_to_binary('Connection') -> <<"Connection">>;
  895. header_to_binary('Date') -> <<"Date">>;
  896. header_to_binary('Pragma') -> <<"Pragma">>;
  897. header_to_binary('Transfer-Encoding') -> <<"Transfer-Encoding">>;
  898. header_to_binary('Upgrade') -> <<"Upgrade">>;
  899. header_to_binary('Via') -> <<"Via">>;
  900. header_to_binary('Accept') -> <<"Accept">>;
  901. header_to_binary('Accept-Charset') -> <<"Accept-Charset">>;
  902. header_to_binary('Accept-Encoding') -> <<"Accept-Encoding">>;
  903. header_to_binary('Accept-Language') -> <<"Accept-Language">>;
  904. header_to_binary('Authorization') -> <<"Authorization">>;
  905. header_to_binary('From') -> <<"From">>;
  906. header_to_binary('Host') -> <<"Host">>;
  907. header_to_binary('If-Modified-Since') -> <<"If-Modified-Since">>;
  908. header_to_binary('If-Match') -> <<"If-Match">>;
  909. header_to_binary('If-None-Match') -> <<"If-None-Match">>;
  910. header_to_binary('If-Range') -> <<"If-Range">>;
  911. header_to_binary('If-Unmodified-Since') -> <<"If-Unmodified-Since">>;
  912. header_to_binary('Max-Forwards') -> <<"Max-Forwards">>;
  913. header_to_binary('Proxy-Authorization') -> <<"Proxy-Authorization">>;
  914. header_to_binary('Range') -> <<"Range">>;
  915. header_to_binary('Referer') -> <<"Referer">>;
  916. header_to_binary('User-Agent') -> <<"User-Agent">>;
  917. header_to_binary('Age') -> <<"Age">>;
  918. header_to_binary('Location') -> <<"Location">>;
  919. header_to_binary('Proxy-Authenticate') -> <<"Proxy-Authenticate">>;
  920. header_to_binary('Public') -> <<"Public">>;
  921. header_to_binary('Retry-After') -> <<"Retry-After">>;
  922. header_to_binary('Server') -> <<"Server">>;
  923. header_to_binary('Vary') -> <<"Vary">>;
  924. header_to_binary('Warning') -> <<"Warning">>;
  925. header_to_binary('Www-Authenticate') -> <<"Www-Authenticate">>;
  926. header_to_binary('Allow') -> <<"Allow">>;
  927. header_to_binary('Content-Base') -> <<"Content-Base">>;
  928. header_to_binary('Content-Encoding') -> <<"Content-Encoding">>;
  929. header_to_binary('Content-Language') -> <<"Content-Language">>;
  930. header_to_binary('Content-Length') -> <<"Content-Length">>;
  931. header_to_binary('Content-Location') -> <<"Content-Location">>;
  932. header_to_binary('Content-Md5') -> <<"Content-Md5">>;
  933. header_to_binary('Content-Range') -> <<"Content-Range">>;
  934. header_to_binary('Content-Type') -> <<"Content-Type">>;
  935. header_to_binary('Etag') -> <<"Etag">>;
  936. header_to_binary('Expires') -> <<"Expires">>;
  937. header_to_binary('Last-Modified') -> <<"Last-Modified">>;
  938. header_to_binary('Accept-Ranges') -> <<"Accept-Ranges">>;
  939. header_to_binary('Set-Cookie') -> <<"Set-Cookie">>;
  940. header_to_binary('Set-Cookie2') -> <<"Set-Cookie2">>;
  941. header_to_binary('X-Forwarded-For') -> <<"X-Forwarded-For">>;
  942. header_to_binary('Cookie') -> <<"Cookie">>;
  943. header_to_binary('Keep-Alive') -> <<"Keep-Alive">>;
  944. header_to_binary('Proxy-Connection') -> <<"Proxy-Connection">>;
  945. header_to_binary(B) when is_binary(B) -> B.