cowboy_http_req.erl 37 KB

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