cowboy_http_req.erl 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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{
  417. transport=Transport, socket=Socket, buffer=Buffer}) ->
  418. %% @todo Allow configuring the timeout.
  419. case Transport:recv(Socket, 0, 5000) of
  420. {ok, Data} -> transfer_decode(<< Buffer/binary, Data/binary >>, Req);
  421. {error, Reason} -> {error, Reason}
  422. end.
  423. -spec transfer_decode(binary(), #http_req{})
  424. -> {ok, binary(), #http_req{}} | {error, atom()}.
  425. transfer_decode(Data, Req=#http_req{
  426. body_state={stream, TransferDecode, TransferState, ContentDecode}}) ->
  427. case TransferDecode(Data, TransferState) of
  428. {ok, Data2, TransferState2} ->
  429. content_decode(ContentDecode, Data2, Req#http_req{body_state=
  430. {stream, TransferDecode, TransferState2, ContentDecode}});
  431. {ok, Data2, Rest, TransferState2} ->
  432. content_decode(ContentDecode, Data2, Req#http_req{
  433. buffer=Rest, body_state=
  434. {stream, TransferDecode, TransferState2, ContentDecode}});
  435. %% @todo {header(s) for chunked
  436. more ->
  437. stream_body_recv(Req#http_req{buffer=Data});
  438. {done, Length, Rest} ->
  439. Req2 = transfer_decode_done(Length, Rest, Req),
  440. {done, Req2};
  441. {done, Data2, Length, Rest} ->
  442. Req2 = transfer_decode_done(Length, Rest, Req),
  443. content_decode(ContentDecode, Data2, Req2);
  444. {error, Reason} ->
  445. {error, Reason}
  446. end.
  447. -spec transfer_decode_done(non_neg_integer(), binary(), #http_req{})
  448. -> #http_req{}.
  449. transfer_decode_done(Length, Rest, Req=#http_req{
  450. headers=Headers, p_headers=PHeaders}) ->
  451. Headers2 = lists:keystore('Content-Length', 1, Headers,
  452. {'Content-Length', list_to_binary(integer_to_list(Length))}),
  453. %% At this point we just assume TEs were all decoded.
  454. Headers3 = lists:keydelete('Transfer-Encoding', 1, Headers2),
  455. PHeaders2 = lists:keystore('Content-Length', 1, PHeaders,
  456. {'Content-Length', Length}),
  457. PHeaders3 = lists:keydelete('Transfer-Encoding', 1, PHeaders2),
  458. Req#http_req{buffer=Rest, body_state=done,
  459. headers=Headers3, p_headers=PHeaders3}.
  460. %% @todo Probably needs a Rest.
  461. -spec content_decode(fun(), binary(), #http_req{})
  462. -> {ok, binary(), #http_req{}} | {error, atom()}.
  463. content_decode(ContentDecode, Data, Req) ->
  464. case ContentDecode(Data) of
  465. {ok, Data2} -> {ok, Data2, Req};
  466. {error, Reason} -> {error, Reason}
  467. end.
  468. %% @doc Return the full body sent with the request.
  469. -spec body(#http_req{}) -> {ok, binary(), #http_req{}} | {error, atom()}.
  470. body(Req) ->
  471. read_body(infinity, Req, <<>>).
  472. %% @doc Return the full body sent with the request as long as the body
  473. %% length doesn't go over MaxLength.
  474. %%
  475. %% This is most useful to quickly be able to get the full body while
  476. %% avoiding filling your memory with huge request bodies when you're
  477. %% not expecting it.
  478. -spec body(non_neg_integer() | infinity, #http_req{})
  479. -> {ok, binary(), #http_req{}} | {error, atom()}.
  480. body(MaxLength, Req) ->
  481. read_body(MaxLength, Req, <<>>).
  482. -spec read_body(non_neg_integer() | infinity, #http_req{}, binary())
  483. -> {ok, binary(), #http_req{}} | {error, atom()}.
  484. read_body(MaxLength, Req, Acc) when MaxLength > byte_size(Acc) ->
  485. case stream_body(Req) of
  486. {ok, Data, Req2} ->
  487. read_body(MaxLength, Req2, << Acc/binary, Data/binary >>);
  488. {done, Req2} ->
  489. {ok, Acc, Req2};
  490. {error, Reason} ->
  491. {error, Reason}
  492. end.
  493. -spec skip_body(#http_req{}) -> {ok, #http_req{}} | {error, atom()}.
  494. skip_body(Req) ->
  495. case stream_body(Req) of
  496. {ok, _, Req2} -> skip_body(Req2);
  497. {done, Req2} -> {ok, Req2};
  498. {error, Reason} -> {error, Reason}
  499. end.
  500. %% @doc Return the full body sent with the reqest, parsed as an
  501. %% application/x-www-form-urlencoded string. Essentially a POST query string.
  502. %% @todo We need an option to limit the size of the body for QS too.
  503. -spec body_qs(#http_req{}) -> {list({binary(), binary() | true}), #http_req{}}.
  504. body_qs(Req=#http_req{urldecode={URLDecFun, URLDecArg}}) ->
  505. {ok, Body, Req2} = body(Req),
  506. {cowboy_http:x_www_form_urlencoded(
  507. Body, fun(Bin) -> URLDecFun(Bin, URLDecArg) end), Req2}.
  508. %% Multipart Request API.
  509. %% @doc Return data from the multipart parser.
  510. %%
  511. %% Use this function for multipart streaming. For each part in the request,
  512. %% this function returns <em>{headers, Headers}</em> followed by a sequence of
  513. %% <em>{body, Data}</em> tuples and finally <em>end_of_part</em>. When there
  514. %% is no part to parse anymore, <em>eof</em> is returned.
  515. %%
  516. %% If the request Content-Type is not a multipart one, <em>{error, badarg}</em>
  517. %% is returned.
  518. -spec multipart_data(#http_req{})
  519. -> {{headers, cowboy_http:headers()}
  520. | {body, binary()} | end_of_part | eof,
  521. #http_req{}}.
  522. multipart_data(Req=#http_req{body_state=waiting}) ->
  523. {{<<"multipart">>, _SubType, Params}, Req2} =
  524. parse_header('Content-Type', Req),
  525. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  526. {Length, Req3=#http_req{buffer=Buffer}} =
  527. parse_header('Content-Length', Req2),
  528. multipart_data(Req3, Length, cowboy_multipart:parser(Boundary), Buffer);
  529. multipart_data(Req=#http_req{body_state={multipart, Length, Cont}}) ->
  530. multipart_data(Req, Length, Cont());
  531. multipart_data(Req=#http_req{body_state=done}) ->
  532. {eof, Req}.
  533. multipart_data(Req, Length, Parser, Buffer) when byte_size(Buffer) >= Length ->
  534. << Data:Length/binary, Rest/binary >> = Buffer,
  535. multipart_data(Req#http_req{buffer=Rest}, 0, Parser(Data));
  536. multipart_data(Req, Length, Parser, Buffer) ->
  537. NewLength = Length - byte_size(Buffer),
  538. multipart_data(Req#http_req{buffer= <<>>}, NewLength, Parser(Buffer)).
  539. multipart_data(Req, Length, {headers, Headers, Cont}) ->
  540. {{headers, Headers}, Req#http_req{body_state={multipart, Length, Cont}}};
  541. multipart_data(Req, Length, {body, Data, Cont}) ->
  542. {{body, Data}, Req#http_req{body_state={multipart, Length, Cont}}};
  543. multipart_data(Req, Length, {end_of_part, Cont}) ->
  544. {end_of_part, Req#http_req{body_state={multipart, Length, Cont}}};
  545. multipart_data(Req, 0, eof) ->
  546. {eof, Req#http_req{body_state=done}};
  547. multipart_data(Req=#http_req{socket=Socket, transport=Transport},
  548. Length, eof) ->
  549. {ok, _Data} = Transport:recv(Socket, Length, 5000),
  550. {eof, Req#http_req{body_state=done}};
  551. multipart_data(Req=#http_req{socket=Socket, transport=Transport},
  552. Length, {more, Parser}) when Length > 0 ->
  553. case Transport:recv(Socket, 0, 5000) of
  554. {ok, << Data:Length/binary, Buffer/binary >>} ->
  555. multipart_data(Req#http_req{buffer=Buffer}, 0, Parser(Data));
  556. {ok, Data} ->
  557. multipart_data(Req, Length - byte_size(Data), Parser(Data))
  558. end.
  559. %% @doc Skip a part returned by the multipart parser.
  560. %%
  561. %% This function repeatedly calls <em>multipart_data/1</em> until
  562. %% <em>end_of_part</em> or <em>eof</em> is parsed.
  563. multipart_skip(Req) ->
  564. case multipart_data(Req) of
  565. {end_of_part, Req2} -> {ok, Req2};
  566. {eof, Req2} -> {ok, Req2};
  567. {_Other, Req2} -> multipart_skip(Req2)
  568. end.
  569. %% Response API.
  570. %% @doc Add a cookie header to the response.
  571. -spec set_resp_cookie(binary(), binary(), [cowboy_cookies:cookie_option()],
  572. #http_req{}) -> {ok, #http_req{}}.
  573. set_resp_cookie(Name, Value, Options, Req) ->
  574. {HeaderName, HeaderValue} = cowboy_cookies:cookie(Name, Value, Options),
  575. set_resp_header(HeaderName, HeaderValue, Req).
  576. %% @doc Add a header to the response.
  577. -spec set_resp_header(cowboy_http:header(), iodata(), #http_req{})
  578. -> {ok, #http_req{}}.
  579. set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
  580. NameBin = header_to_binary(Name),
  581. {ok, Req#http_req{resp_headers=[{NameBin, Value}|RespHeaders]}}.
  582. %% @doc Add a body to the response.
  583. %%
  584. %% The body set here is ignored if the response is later sent using
  585. %% anything other than reply/2 or reply/3. The response body is expected
  586. %% to be a binary or an iolist.
  587. -spec set_resp_body(iodata(), #http_req{}) -> {ok, #http_req{}}.
  588. set_resp_body(Body, Req) ->
  589. {ok, Req#http_req{resp_body=Body}}.
  590. %% @doc Add a body function to the response.
  591. %%
  592. %% The response body may also be set to a content-length - stream-function pair.
  593. %% If the response body is of this type normal response headers will be sent.
  594. %% After the response headers has been sent the body function is applied.
  595. %% The body function is expected to write the response body directly to the
  596. %% socket using the transport module.
  597. %%
  598. %% If the body function crashes while writing the response body or writes fewer
  599. %% bytes than declared the behaviour is undefined. The body set here is ignored
  600. %% if the response is later sent using anything other than `reply/2' or
  601. %% `reply/3'.
  602. %%
  603. %% @see cowboy_http_req:transport/1.
  604. -spec set_resp_body_fun(non_neg_integer(), fun(() -> {sent, non_neg_integer()}),
  605. #http_req{}) -> {ok, #http_req{}}.
  606. set_resp_body_fun(StreamLen, StreamFun, Req) ->
  607. {ok, Req#http_req{resp_body={StreamLen, StreamFun}}}.
  608. %% @doc Return whether the given header has been set for the response.
  609. -spec has_resp_header(cowboy_http:header(), #http_req{}) -> boolean().
  610. has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
  611. NameBin = header_to_binary(Name),
  612. lists:keymember(NameBin, 1, RespHeaders).
  613. %% @doc Return whether a body has been set for the response.
  614. -spec has_resp_body(#http_req{}) -> boolean().
  615. has_resp_body(#http_req{resp_body={Length, _}}) ->
  616. Length > 0;
  617. has_resp_body(#http_req{resp_body=RespBody}) ->
  618. iolist_size(RespBody) > 0.
  619. %% @equiv reply(Status, [], [], Req)
  620. -spec reply(cowboy_http:status(), #http_req{}) -> {ok, #http_req{}}.
  621. reply(Status, Req=#http_req{resp_body=Body}) ->
  622. reply(Status, [], Body, Req).
  623. %% @equiv reply(Status, Headers, [], Req)
  624. -spec reply(cowboy_http:status(), cowboy_http:headers(), #http_req{})
  625. -> {ok, #http_req{}}.
  626. reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
  627. reply(Status, Headers, Body, Req).
  628. %% @doc Send a reply to the client.
  629. -spec reply(cowboy_http:status(), cowboy_http:headers(), iodata(), #http_req{})
  630. -> {ok, #http_req{}}.
  631. reply(Status, Headers, Body, Req=#http_req{socket=Socket, transport=Transport,
  632. version=Version, connection=Connection,
  633. method=Method, resp_state=waiting, resp_headers=RespHeaders}) ->
  634. RespConn = response_connection(Headers, Connection),
  635. ContentLen = case Body of {CL, _} -> CL; _ -> iolist_size(Body) end,
  636. HTTP11Headers = case Version of
  637. {1, 1} -> [{<<"Connection">>, atom_to_connection(Connection)}];
  638. _ -> []
  639. end,
  640. {ReplyType, Req2} = response(Status, Headers, RespHeaders, [
  641. {<<"Content-Length">>, integer_to_list(ContentLen)},
  642. {<<"Date">>, cowboy_clock:rfc1123()},
  643. {<<"Server">>, <<"Cowboy">>}
  644. |HTTP11Headers], Req),
  645. if Method =:= 'HEAD' -> ok;
  646. ReplyType =:= hook -> ok; %% Hook replied for us, stop there.
  647. true ->
  648. case Body of
  649. {_, StreamFun} -> StreamFun();
  650. _ -> Transport:send(Socket, Body)
  651. end
  652. end,
  653. {ok, Req2#http_req{connection=RespConn, resp_state=done,
  654. resp_headers=[], resp_body= <<>>}}.
  655. %% @equiv chunked_reply(Status, [], Req)
  656. -spec chunked_reply(cowboy_http:status(), #http_req{}) -> {ok, #http_req{}}.
  657. chunked_reply(Status, Req) ->
  658. chunked_reply(Status, [], Req).
  659. %% @doc Initiate the sending of a chunked reply to the client.
  660. %% @see cowboy_http_req:chunk/2
  661. -spec chunked_reply(cowboy_http:status(), cowboy_http:headers(), #http_req{})
  662. -> {ok, #http_req{}}.
  663. chunked_reply(Status, Headers, Req=#http_req{
  664. version=Version, connection=Connection,
  665. resp_state=waiting, resp_headers=RespHeaders}) ->
  666. RespConn = response_connection(Headers, Connection),
  667. HTTP11Headers = case Version of
  668. {1, 1} -> [
  669. {<<"Connection">>, atom_to_connection(Connection)},
  670. {<<"Transfer-Encoding">>, <<"chunked">>}];
  671. _ -> []
  672. end,
  673. {_, Req2} = response(Status, Headers, RespHeaders, [
  674. {<<"Date">>, cowboy_clock:rfc1123()},
  675. {<<"Server">>, <<"Cowboy">>}
  676. |HTTP11Headers], Req),
  677. {ok, Req2#http_req{connection=RespConn, resp_state=chunks,
  678. resp_headers=[], resp_body= <<>>}}.
  679. %% @doc Send a chunk of data.
  680. %%
  681. %% A chunked reply must have been initiated before calling this function.
  682. -spec chunk(iodata(), #http_req{}) -> ok | {error, atom()}.
  683. chunk(_Data, #http_req{socket=_Socket, transport=_Transport, method='HEAD'}) ->
  684. ok;
  685. chunk(Data, #http_req{socket=Socket, transport=Transport, version={1, 0}}) ->
  686. Transport:send(Socket, Data);
  687. chunk(Data, #http_req{socket=Socket, transport=Transport, resp_state=chunks}) ->
  688. Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
  689. <<"\r\n">>, Data, <<"\r\n">>]).
  690. %% @doc Send an upgrade reply.
  691. %% @private
  692. -spec upgrade_reply(cowboy_http:status(), cowboy_http:headers(), #http_req{})
  693. -> {ok, #http_req{}}.
  694. upgrade_reply(Status, Headers, Req=#http_req{
  695. resp_state=waiting, resp_headers=RespHeaders}) ->
  696. {_, Req2} = response(Status, Headers, RespHeaders, [
  697. {<<"Connection">>, <<"Upgrade">>}
  698. ], Req),
  699. {ok, Req2#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(cowboy_http:status(), cowboy_http:headers(),
  725. cowboy_http:headers(), cowboy_http:headers(), #http_req{})
  726. -> {normal | hook, #http_req{}}.
  727. response(Status, Headers, RespHeaders, DefaultHeaders, Req=#http_req{
  728. socket=Socket, transport=Transport, version=Version,
  729. pid=ReqPid, onresponse=OnResponse}) ->
  730. FullHeaders = response_merge_headers(Headers, RespHeaders, DefaultHeaders),
  731. Req2 = case OnResponse of
  732. undefined -> Req;
  733. OnResponse -> OnResponse(Status, FullHeaders,
  734. %% Don't call 'onresponse' from the hook itself.
  735. Req#http_req{resp_headers=[], resp_body= <<>>,
  736. onresponse=undefined})
  737. end,
  738. ReplyType = case Req2#http_req.resp_state of
  739. waiting ->
  740. HTTPVer = cowboy_http:version_to_binary(Version),
  741. StatusLine = << HTTPVer/binary, " ",
  742. (status(Status))/binary, "\r\n" >>,
  743. HeaderLines = [[Key, <<": ">>, Value, <<"\r\n">>]
  744. || {Key, Value} <- FullHeaders],
  745. Transport:send(Socket, [StatusLine, HeaderLines, <<"\r\n">>]),
  746. ReqPid ! {?MODULE, resp_sent},
  747. normal;
  748. _ ->
  749. hook
  750. end,
  751. {ReplyType, Req2}.
  752. -spec response_connection(cowboy_http:headers(), keepalive | close)
  753. -> keepalive | close.
  754. response_connection([], Connection) ->
  755. Connection;
  756. response_connection([{Name, Value}|Tail], Connection) ->
  757. case Name of
  758. 'Connection' -> response_connection_parse(Value);
  759. Name when is_atom(Name) -> response_connection(Tail, Connection);
  760. Name ->
  761. Name2 = cowboy_bstr:to_lower(Name),
  762. case Name2 of
  763. <<"connection">> -> response_connection_parse(Value);
  764. _Any -> response_connection(Tail, Connection)
  765. end
  766. end.
  767. -spec response_connection_parse(binary()) -> keepalive | close.
  768. response_connection_parse(ReplyConn) ->
  769. Tokens = cowboy_http:nonempty_list(ReplyConn, fun cowboy_http:token/2),
  770. cowboy_http:connection_to_atom(Tokens).
  771. -spec response_merge_headers(cowboy_http:headers(), cowboy_http:headers(),
  772. cowboy_http:headers()) -> cowboy_http:headers().
  773. response_merge_headers(Headers, RespHeaders, DefaultHeaders) ->
  774. Headers2 = [{header_to_binary(Key), Value} || {Key, Value} <- Headers],
  775. merge_headers(
  776. merge_headers(Headers2, RespHeaders),
  777. DefaultHeaders).
  778. -spec merge_headers(cowboy_http:headers(), cowboy_http:headers())
  779. -> cowboy_http:headers().
  780. merge_headers(Headers, []) ->
  781. Headers;
  782. merge_headers(Headers, [{Name, Value}|Tail]) ->
  783. Headers2 = case lists:keymember(Name, 1, Headers) of
  784. true -> Headers;
  785. false -> Headers ++ [{Name, Value}]
  786. end,
  787. merge_headers(Headers2, Tail).
  788. -spec atom_to_connection(keepalive) -> <<_:80>>;
  789. (close) -> <<_:40>>.
  790. atom_to_connection(keepalive) ->
  791. <<"keep-alive">>;
  792. atom_to_connection(close) ->
  793. <<"close">>.
  794. -spec status(cowboy_http:status()) -> binary().
  795. status(100) -> <<"100 Continue">>;
  796. status(101) -> <<"101 Switching Protocols">>;
  797. status(102) -> <<"102 Processing">>;
  798. status(200) -> <<"200 OK">>;
  799. status(201) -> <<"201 Created">>;
  800. status(202) -> <<"202 Accepted">>;
  801. status(203) -> <<"203 Non-Authoritative Information">>;
  802. status(204) -> <<"204 No Content">>;
  803. status(205) -> <<"205 Reset Content">>;
  804. status(206) -> <<"206 Partial Content">>;
  805. status(207) -> <<"207 Multi-Status">>;
  806. status(226) -> <<"226 IM Used">>;
  807. status(300) -> <<"300 Multiple Choices">>;
  808. status(301) -> <<"301 Moved Permanently">>;
  809. status(302) -> <<"302 Found">>;
  810. status(303) -> <<"303 See Other">>;
  811. status(304) -> <<"304 Not Modified">>;
  812. status(305) -> <<"305 Use Proxy">>;
  813. status(306) -> <<"306 Switch Proxy">>;
  814. status(307) -> <<"307 Temporary Redirect">>;
  815. status(400) -> <<"400 Bad Request">>;
  816. status(401) -> <<"401 Unauthorized">>;
  817. status(402) -> <<"402 Payment Required">>;
  818. status(403) -> <<"403 Forbidden">>;
  819. status(404) -> <<"404 Not Found">>;
  820. status(405) -> <<"405 Method Not Allowed">>;
  821. status(406) -> <<"406 Not Acceptable">>;
  822. status(407) -> <<"407 Proxy Authentication Required">>;
  823. status(408) -> <<"408 Request Timeout">>;
  824. status(409) -> <<"409 Conflict">>;
  825. status(410) -> <<"410 Gone">>;
  826. status(411) -> <<"411 Length Required">>;
  827. status(412) -> <<"412 Precondition Failed">>;
  828. status(413) -> <<"413 Request Entity Too Large">>;
  829. status(414) -> <<"414 Request-URI Too Long">>;
  830. status(415) -> <<"415 Unsupported Media Type">>;
  831. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  832. status(417) -> <<"417 Expectation Failed">>;
  833. status(418) -> <<"418 I'm a teapot">>;
  834. status(422) -> <<"422 Unprocessable Entity">>;
  835. status(423) -> <<"423 Locked">>;
  836. status(424) -> <<"424 Failed Dependency">>;
  837. status(425) -> <<"425 Unordered Collection">>;
  838. status(426) -> <<"426 Upgrade Required">>;
  839. status(500) -> <<"500 Internal Server Error">>;
  840. status(501) -> <<"501 Not Implemented">>;
  841. status(502) -> <<"502 Bad Gateway">>;
  842. status(503) -> <<"503 Service Unavailable">>;
  843. status(504) -> <<"504 Gateway Timeout">>;
  844. status(505) -> <<"505 HTTP Version Not Supported">>;
  845. status(506) -> <<"506 Variant Also Negotiates">>;
  846. status(507) -> <<"507 Insufficient Storage">>;
  847. status(510) -> <<"510 Not Extended">>;
  848. status(B) when is_binary(B) -> B.
  849. -spec header_to_binary(cowboy_http:header()) -> binary().
  850. header_to_binary('Cache-Control') -> <<"Cache-Control">>;
  851. header_to_binary('Connection') -> <<"Connection">>;
  852. header_to_binary('Date') -> <<"Date">>;
  853. header_to_binary('Pragma') -> <<"Pragma">>;
  854. header_to_binary('Transfer-Encoding') -> <<"Transfer-Encoding">>;
  855. header_to_binary('Upgrade') -> <<"Upgrade">>;
  856. header_to_binary('Via') -> <<"Via">>;
  857. header_to_binary('Accept') -> <<"Accept">>;
  858. header_to_binary('Accept-Charset') -> <<"Accept-Charset">>;
  859. header_to_binary('Accept-Encoding') -> <<"Accept-Encoding">>;
  860. header_to_binary('Accept-Language') -> <<"Accept-Language">>;
  861. header_to_binary('Authorization') -> <<"Authorization">>;
  862. header_to_binary('From') -> <<"From">>;
  863. header_to_binary('Host') -> <<"Host">>;
  864. header_to_binary('If-Modified-Since') -> <<"If-Modified-Since">>;
  865. header_to_binary('If-Match') -> <<"If-Match">>;
  866. header_to_binary('If-None-Match') -> <<"If-None-Match">>;
  867. header_to_binary('If-Range') -> <<"If-Range">>;
  868. header_to_binary('If-Unmodified-Since') -> <<"If-Unmodified-Since">>;
  869. header_to_binary('Max-Forwards') -> <<"Max-Forwards">>;
  870. header_to_binary('Proxy-Authorization') -> <<"Proxy-Authorization">>;
  871. header_to_binary('Range') -> <<"Range">>;
  872. header_to_binary('Referer') -> <<"Referer">>;
  873. header_to_binary('User-Agent') -> <<"User-Agent">>;
  874. header_to_binary('Age') -> <<"Age">>;
  875. header_to_binary('Location') -> <<"Location">>;
  876. header_to_binary('Proxy-Authenticate') -> <<"Proxy-Authenticate">>;
  877. header_to_binary('Public') -> <<"Public">>;
  878. header_to_binary('Retry-After') -> <<"Retry-After">>;
  879. header_to_binary('Server') -> <<"Server">>;
  880. header_to_binary('Vary') -> <<"Vary">>;
  881. header_to_binary('Warning') -> <<"Warning">>;
  882. header_to_binary('Www-Authenticate') -> <<"Www-Authenticate">>;
  883. header_to_binary('Allow') -> <<"Allow">>;
  884. header_to_binary('Content-Base') -> <<"Content-Base">>;
  885. header_to_binary('Content-Encoding') -> <<"Content-Encoding">>;
  886. header_to_binary('Content-Language') -> <<"Content-Language">>;
  887. header_to_binary('Content-Length') -> <<"Content-Length">>;
  888. header_to_binary('Content-Location') -> <<"Content-Location">>;
  889. header_to_binary('Content-Md5') -> <<"Content-Md5">>;
  890. header_to_binary('Content-Range') -> <<"Content-Range">>;
  891. header_to_binary('Content-Type') -> <<"Content-Type">>;
  892. header_to_binary('Etag') -> <<"Etag">>;
  893. header_to_binary('Expires') -> <<"Expires">>;
  894. header_to_binary('Last-Modified') -> <<"Last-Modified">>;
  895. header_to_binary('Accept-Ranges') -> <<"Accept-Ranges">>;
  896. header_to_binary('Set-Cookie') -> <<"Set-Cookie">>;
  897. header_to_binary('Set-Cookie2') -> <<"Set-Cookie2">>;
  898. header_to_binary('X-Forwarded-For') -> <<"X-Forwarded-For">>;
  899. header_to_binary('Cookie') -> <<"Cookie">>;
  900. header_to_binary('Keep-Alive') -> <<"Keep-Alive">>;
  901. header_to_binary('Proxy-Connection') -> <<"Proxy-Connection">>;
  902. header_to_binary(B) when is_binary(B) -> B.