cowboy_req.erl 39 KB

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