cowboy_http_req.erl 38 KB

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