cowboy_req.erl 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. %% Copyright (c) 2011-2013, 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. %% The functions in this module try to follow this pattern for their
  18. %% return types:
  19. %% <dl>
  20. %% <dt>access:</dt>
  21. %% <dd><em>{Value, Req}</em></dd>
  22. %% <dt>action:</dt>
  23. %% <dd><em>{Result, Req} | {Result, Value, Req} | {error, atom()}</em></dd>
  24. %% <dt>modification:</dt>
  25. %% <dd><em>Req</em></dd>
  26. %% <dt>question (<em>has_*</em> or <em>is_*</em>):</dt>
  27. %% <dd><em>boolean()</em></dd>
  28. %% </dl>
  29. %%
  30. %% Exceptions include <em>chunk/2</em> which always returns <em>'ok'</em>,
  31. %% <em>to_list/1</em> which returns a list of key/values,
  32. %% and <em>transport/1</em> which returns <em>{ok, Transport, Socket}</em>.
  33. %%
  34. %% Also note that all body reading functions perform actions, as Cowboy
  35. %% doesn't read the request body until they are called.
  36. %%
  37. %% Whenever <em>Req</em> is returned, it should always be kept in place of
  38. %% the one given as argument in your function call, because it keeps
  39. %% track of the request and response state. Doing so allows Cowboy to do
  40. %% some lazy evaluation and cache results when possible.
  41. -module(cowboy_req).
  42. %% Request API.
  43. -export([new/15]).
  44. -export([method/1]).
  45. -export([version/1]).
  46. -export([peer/1]).
  47. -export([peer_addr/1]).
  48. -export([host/1]).
  49. -export([host_info/1]).
  50. -export([port/1]).
  51. -export([path/1]).
  52. -export([path_info/1]).
  53. -export([qs/1]).
  54. -export([qs_val/2]).
  55. -export([qs_val/3]).
  56. -export([qs_vals/1]).
  57. -export([fragment/1]).
  58. -export([host_url/1]).
  59. -export([url/1]).
  60. -export([binding/2]).
  61. -export([binding/3]).
  62. -export([bindings/1]).
  63. -export([header/2]).
  64. -export([header/3]).
  65. -export([headers/1]).
  66. -export([parse_header/2]).
  67. -export([parse_header/3]).
  68. -export([cookie/2]).
  69. -export([cookie/3]).
  70. -export([cookies/1]).
  71. -export([meta/2]).
  72. -export([meta/3]).
  73. -export([set_meta/3]).
  74. %% Request body API.
  75. -export([has_body/1]).
  76. -export([body_length/1]).
  77. -export([init_stream/4]).
  78. -export([init_stream/5]).
  79. -export([stream_body/1]).
  80. -export([skip_body/1]).
  81. -export([body/1]).
  82. -export([body/2]).
  83. -export([body_qs/1]).
  84. -export([body_qs/2]).
  85. -export([multipart_data/1]).
  86. -export([multipart_skip/1]).
  87. %% Response API.
  88. -export([set_resp_cookie/4]).
  89. -export([set_resp_header/3]).
  90. -export([set_resp_body/2]).
  91. -export([set_resp_body_fun/2]).
  92. -export([set_resp_body_fun/3]).
  93. -export([has_resp_header/2]).
  94. -export([has_resp_body/1]).
  95. -export([delete_resp_header/2]).
  96. -export([reply/2]).
  97. -export([reply/3]).
  98. -export([reply/4]).
  99. -export([chunked_reply/2]).
  100. -export([chunked_reply/3]).
  101. -export([chunk/2]).
  102. -export([upgrade_reply/3]).
  103. -export([ensure_response/2]).
  104. %% Private setter/getter API.
  105. -export([append_buffer/2]).
  106. -export([get/2]).
  107. -export([set/2]).
  108. -export([set_bindings/4]).
  109. %% Misc API.
  110. -export([compact/1]).
  111. -export([lock/1]).
  112. -export([to_list/1]).
  113. -ifdef(TEST).
  114. -include_lib("eunit/include/eunit.hrl").
  115. -endif.
  116. -type cookie_option() :: {max_age, non_neg_integer()}
  117. | {domain, binary()} | {path, binary()}
  118. | {secure, boolean()} | {http_only, boolean()}.
  119. -type cookie_opts() :: [cookie_option()].
  120. -export_type([cookie_opts/0]).
  121. -type resp_body_fun() :: fun((inet:socket(), module()) -> ok).
  122. -record(http_req, {
  123. %% Transport.
  124. socket = undefined :: undefined | inet:socket(),
  125. transport = undefined :: undefined | module(),
  126. connection = keepalive :: keepalive | close,
  127. %% Request.
  128. pid = undefined :: pid(),
  129. method = <<"GET">> :: binary(),
  130. version = {1, 1} :: cowboy_http:version(),
  131. peer = undefined :: undefined | {inet:ip_address(), inet:port_number()},
  132. host = undefined :: undefined | binary(),
  133. host_info = undefined :: undefined | cowboy_router:tokens(),
  134. port = undefined :: undefined | inet:port_number(),
  135. path = undefined :: binary(),
  136. path_info = undefined :: undefined | cowboy_router:tokens(),
  137. qs = undefined :: binary(),
  138. qs_vals = undefined :: undefined | list({binary(), binary() | true}),
  139. fragment = undefined :: binary(),
  140. bindings = undefined :: undefined | cowboy_router:bindings(),
  141. headers = [] :: cowboy_http:headers(),
  142. p_headers = [] :: [any()], %% @todo Improve those specs.
  143. cookies = undefined :: undefined | [{binary(), binary()}],
  144. meta = [] :: [{atom(), any()}],
  145. %% Request body.
  146. body_state = waiting :: waiting | done | {stream,
  147. non_neg_integer(), non_neg_integer(), fun(), any(), fun()},
  148. multipart = undefined :: undefined | {non_neg_integer(), fun()},
  149. buffer = <<>> :: binary(),
  150. %% Response.
  151. resp_compress = false :: boolean(),
  152. resp_state = waiting :: locked | waiting | chunks | done,
  153. resp_headers = [] :: cowboy_http:headers(),
  154. resp_body = <<>> :: iodata() | resp_body_fun()
  155. | {non_neg_integer(), resp_body_fun()},
  156. %% Functions.
  157. onresponse = undefined :: undefined | already_called
  158. | cowboy_protocol:onresponse_fun()
  159. }).
  160. -opaque req() :: #http_req{}.
  161. -export_type([req/0]).
  162. %% Request API.
  163. %% @doc Create a new HTTP Req object.
  164. %%
  165. %% This function takes care of setting the owner's pid to self().
  166. %% @private
  167. %%
  168. %% Since we always need to parse the Connection header, we do it
  169. %% in an optimized way and add the parsed value to p_headers' cache.
  170. -spec new(inet:socket(), module(),
  171. undefined | {inet:ip_address(), inet:port_number()},
  172. binary(), binary(), binary(), binary(),
  173. cowboy_http:version(), cowboy_http:headers(), binary(),
  174. inet:port_number() | undefined, binary(), boolean(), boolean(),
  175. undefined | cowboy_protocol:onresponse_fun())
  176. -> req().
  177. new(Socket, Transport, Peer, Method, Path, Query, Fragment,
  178. Version, Headers, Host, Port, Buffer, CanKeepalive,
  179. Compress, OnResponse) ->
  180. Req = #http_req{socket=Socket, transport=Transport, pid=self(), peer=Peer,
  181. method=Method, path=Path, qs=Query, fragment=Fragment, version=Version,
  182. headers=Headers, host=Host, port=Port, buffer=Buffer,
  183. resp_compress=Compress, onresponse=OnResponse},
  184. case CanKeepalive and (Version =:= {1, 1}) of
  185. false ->
  186. Req#http_req{connection=close};
  187. true ->
  188. case lists:keyfind(<<"connection">>, 1, Headers) of
  189. false ->
  190. Req; %% keepalive
  191. {_, ConnectionHeader} ->
  192. Tokens = parse_connection_before(ConnectionHeader, []),
  193. Connection = connection_to_atom(Tokens),
  194. Req#http_req{connection=Connection,
  195. p_headers=[{<<"connection">>, Tokens}]}
  196. end
  197. end.
  198. %% @doc Return the HTTP method of the request.
  199. -spec method(Req) -> {binary(), Req} when Req::req().
  200. method(Req) ->
  201. {Req#http_req.method, Req}.
  202. %% @doc Return the HTTP version used for the request.
  203. -spec version(Req) -> {cowboy_http:version(), Req} when Req::req().
  204. version(Req) ->
  205. {Req#http_req.version, Req}.
  206. %% @doc Return the peer address and port number of the remote host.
  207. -spec peer(Req)
  208. -> {undefined | {inet:ip_address(), inet:port_number()}, Req}
  209. when Req::req().
  210. peer(Req) ->
  211. {Req#http_req.peer, Req}.
  212. %% @doc Returns the peer address calculated from headers.
  213. -spec peer_addr(Req) -> {inet:ip_address(), Req} when Req::req().
  214. peer_addr(Req = #http_req{}) ->
  215. {RealIp, Req1} = header(<<"x-real-ip">>, Req),
  216. {ForwardedForRaw, Req2} = header(<<"x-forwarded-for">>, Req1),
  217. {{PeerIp, _PeerPort}, Req3} = peer(Req2),
  218. ForwardedFor = case ForwardedForRaw of
  219. undefined ->
  220. undefined;
  221. ForwardedForRaw ->
  222. case re:run(ForwardedForRaw, "^(?<first_ip>[^\\,]+)",
  223. [{capture, [first_ip], binary}]) of
  224. {match, [FirstIp]} -> FirstIp;
  225. _Any -> undefined
  226. end
  227. end,
  228. {ok, PeerAddr} = if
  229. is_binary(RealIp) -> inet_parse:address(binary_to_list(RealIp));
  230. is_binary(ForwardedFor) -> inet_parse:address(binary_to_list(ForwardedFor));
  231. true -> {ok, PeerIp}
  232. end,
  233. {PeerAddr, Req3}.
  234. %% @doc Return the host binary string.
  235. -spec host(Req) -> {binary(), Req} when Req::req().
  236. host(Req) ->
  237. {Req#http_req.host, Req}.
  238. %% @doc Return the extra host information obtained from partially matching
  239. %% the hostname using <em>'...'</em>.
  240. -spec host_info(Req)
  241. -> {cowboy_router:tokens() | undefined, Req} when Req::req().
  242. host_info(Req) ->
  243. {Req#http_req.host_info, Req}.
  244. %% @doc Return the port used for this request.
  245. -spec port(Req) -> {inet:port_number(), Req} when Req::req().
  246. port(Req) ->
  247. {Req#http_req.port, Req}.
  248. %% @doc Return the path binary string.
  249. -spec path(Req) -> {binary(), Req} when Req::req().
  250. path(Req) ->
  251. {Req#http_req.path, Req}.
  252. %% @doc Return the extra path information obtained from partially matching
  253. %% the patch using <em>'...'</em>.
  254. -spec path_info(Req)
  255. -> {cowboy_router:tokens() | undefined, Req} when Req::req().
  256. path_info(Req) ->
  257. {Req#http_req.path_info, Req}.
  258. %% @doc Return the raw query string directly taken from the request.
  259. -spec qs(Req) -> {binary(), Req} when Req::req().
  260. qs(Req) ->
  261. {Req#http_req.qs, Req}.
  262. %% @equiv qs_val(Name, Req, undefined)
  263. -spec qs_val(binary(), Req)
  264. -> {binary() | true | undefined, Req} when Req::req().
  265. qs_val(Name, Req) when is_binary(Name) ->
  266. qs_val(Name, Req, undefined).
  267. %% @doc Return the query string value for the given key, or a default if
  268. %% missing.
  269. -spec qs_val(binary(), Req, Default)
  270. -> {binary() | true | Default, Req} when Req::req(), Default::any().
  271. qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default)
  272. when is_binary(Name) ->
  273. QsVals = cowboy_http:x_www_form_urlencoded(RawQs),
  274. qs_val(Name, Req#http_req{qs_vals=QsVals}, Default);
  275. qs_val(Name, Req, Default) ->
  276. case lists:keyfind(Name, 1, Req#http_req.qs_vals) of
  277. {Name, Value} -> {Value, Req};
  278. false -> {Default, Req}
  279. end.
  280. %% @doc Return the full list of query string values.
  281. -spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
  282. qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) ->
  283. QsVals = cowboy_http:x_www_form_urlencoded(RawQs),
  284. qs_vals(Req#http_req{qs_vals=QsVals});
  285. qs_vals(Req=#http_req{qs_vals=QsVals}) ->
  286. {QsVals, Req}.
  287. %% @doc Return the raw fragment directly taken from the request.
  288. -spec fragment(Req) -> {binary(), Req} when Req::req().
  289. fragment(Req) ->
  290. {Req#http_req.fragment, Req}.
  291. %% @doc Return the request URL as a binary without the path and query string.
  292. %%
  293. %% The URL includes the scheme, host and port only.
  294. %% @see cowboy_req:url/1
  295. -spec host_url(Req) -> {undefined | binary(), Req} when Req::req().
  296. host_url(Req=#http_req{port=undefined}) ->
  297. {undefined, Req};
  298. host_url(Req=#http_req{transport=Transport, host=Host, port=Port}) ->
  299. TransportName = Transport:name(),
  300. Secure = case TransportName of
  301. ssl -> <<"s">>;
  302. _ -> <<>>
  303. end,
  304. PortBin = case {TransportName, Port} of
  305. {ssl, 443} -> <<>>;
  306. {tcp, 80} -> <<>>;
  307. _ -> << ":", (list_to_binary(integer_to_list(Port)))/binary >>
  308. end,
  309. {<< "http", Secure/binary, "://", Host/binary, PortBin/binary >>, Req}.
  310. %% @doc Return the full request URL as a binary.
  311. %%
  312. %% The URL includes the scheme, host, port, path, query string and fragment.
  313. -spec url(Req) -> {undefined | binary(), Req} when Req::req().
  314. url(Req=#http_req{}) ->
  315. {HostURL, Req2} = host_url(Req),
  316. url(HostURL, Req2).
  317. url(undefined, Req=#http_req{}) ->
  318. {undefined, Req};
  319. url(HostURL, Req=#http_req{path=Path, qs=QS, fragment=Fragment}) ->
  320. QS2 = case QS of
  321. <<>> -> <<>>;
  322. _ -> << "?", QS/binary >>
  323. end,
  324. Fragment2 = case Fragment of
  325. <<>> -> <<>>;
  326. _ -> << "#", Fragment/binary >>
  327. end,
  328. {<< HostURL/binary, Path/binary, QS2/binary, Fragment2/binary >>, Req}.
  329. %% @equiv binding(Name, Req, undefined)
  330. -spec binding(atom(), Req) -> {binary() | undefined, Req} when Req::req().
  331. binding(Name, Req) when is_atom(Name) ->
  332. binding(Name, Req, undefined).
  333. %% @doc Return the binding value for the given key obtained when matching
  334. %% the host and path against the dispatch list, or a default if missing.
  335. -spec binding(atom(), Req, Default)
  336. -> {binary() | Default, Req} when Req::req(), Default::any().
  337. binding(Name, Req, Default) when is_atom(Name) ->
  338. case lists:keyfind(Name, 1, Req#http_req.bindings) of
  339. {Name, Value} -> {Value, Req};
  340. false -> {Default, Req}
  341. end.
  342. %% @doc Return the full list of binding values.
  343. -spec bindings(Req) -> {list({atom(), binary()}), Req} when Req::req().
  344. bindings(Req) ->
  345. {Req#http_req.bindings, Req}.
  346. %% @equiv header(Name, Req, undefined)
  347. -spec header(binary(), Req)
  348. -> {binary() | undefined, Req} when Req::req().
  349. header(Name, Req) ->
  350. header(Name, Req, undefined).
  351. %% @doc Return the header value for the given key, or a default if missing.
  352. -spec header(binary(), Req, Default)
  353. -> {binary() | Default, Req} when Req::req(), Default::any().
  354. header(Name, Req, Default) ->
  355. case lists:keyfind(Name, 1, Req#http_req.headers) of
  356. {Name, Value} -> {Value, Req};
  357. false -> {Default, Req}
  358. end.
  359. %% @doc Return the full list of headers.
  360. -spec headers(Req) -> {cowboy_http:headers(), Req} when Req::req().
  361. headers(Req) ->
  362. {Req#http_req.headers, Req}.
  363. %% @doc Semantically parse headers.
  364. %%
  365. %% When the value isn't found, a proper default value for the type
  366. %% returned is used as a return value.
  367. %% @see parse_header/3
  368. -spec parse_header(binary(), Req)
  369. -> {ok, any(), Req} | {undefined, binary(), Req}
  370. | {error, badarg} when Req::req().
  371. parse_header(Name, Req=#http_req{p_headers=PHeaders}) ->
  372. case lists:keyfind(Name, 1, PHeaders) of
  373. false -> parse_header(Name, Req, parse_header_default(Name));
  374. {Name, Value} -> {ok, Value, Req}
  375. end.
  376. %% @doc Default values for semantic header parsing.
  377. -spec parse_header_default(binary()) -> any().
  378. parse_header_default(<<"transfer-encoding">>) -> [<<"identity">>];
  379. parse_header_default(_Name) -> undefined.
  380. %% @doc Semantically parse headers.
  381. %%
  382. %% When the header is unknown, the value is returned directly without parsing.
  383. -spec parse_header(binary(), Req, any())
  384. -> {ok, any(), Req} | {undefined, binary(), Req}
  385. | {error, badarg} when Req::req().
  386. parse_header(Name, Req, Default) when Name =:= <<"accept">> ->
  387. parse_header(Name, Req, Default,
  388. fun (Value) ->
  389. cowboy_http:list(Value, fun cowboy_http:media_range/2)
  390. end);
  391. parse_header(Name, Req, Default) when Name =:= <<"accept-charset">> ->
  392. parse_header(Name, Req, Default,
  393. fun (Value) ->
  394. cowboy_http:nonempty_list(Value, fun cowboy_http:conneg/2)
  395. end);
  396. parse_header(Name, Req, Default) when Name =:= <<"accept-encoding">> ->
  397. parse_header(Name, Req, Default,
  398. fun (Value) ->
  399. cowboy_http:list(Value, fun cowboy_http:conneg/2)
  400. end);
  401. parse_header(Name, Req, Default) when Name =:= <<"accept-language">> ->
  402. parse_header(Name, Req, Default,
  403. fun (Value) ->
  404. cowboy_http:nonempty_list(Value, fun cowboy_http:language_range/2)
  405. end);
  406. parse_header(Name, Req, Default) when Name =:= <<"authorization">> ->
  407. parse_header(Name, Req, Default,
  408. fun (Value) ->
  409. cowboy_http:token_ci(Value, fun cowboy_http:authorization/2)
  410. end);
  411. parse_header(Name, Req, Default) when Name =:= <<"content-length">> ->
  412. parse_header(Name, Req, Default, fun cowboy_http:digits/1);
  413. parse_header(Name, Req, Default) when Name =:= <<"content-type">> ->
  414. parse_header(Name, Req, Default, fun cowboy_http:content_type/1);
  415. parse_header(Name = <<"cookie">>, Req, Default) ->
  416. parse_header(Name, Req, Default, fun cowboy_http:cookie_list/1);
  417. parse_header(Name, Req, Default) when Name =:= <<"expect">> ->
  418. parse_header(Name, Req, Default,
  419. fun (Value) ->
  420. cowboy_http:nonempty_list(Value, fun cowboy_http:expectation/2)
  421. end);
  422. parse_header(Name, Req, Default)
  423. when Name =:= <<"if-match">>; Name =:= <<"if-none-match">> ->
  424. parse_header(Name, Req, Default, fun cowboy_http:entity_tag_match/1);
  425. parse_header(Name, Req, Default)
  426. when Name =:= <<"if-modified-since">>;
  427. Name =:= <<"if-unmodified-since">> ->
  428. parse_header(Name, Req, Default, fun cowboy_http:http_date/1);
  429. parse_header(Name, Req, Default) when Name =:= <<"sec-websocket-protocol">> ->
  430. parse_header(Name, Req, Default,
  431. fun (Value) ->
  432. cowboy_http:nonempty_list(Value, fun cowboy_http:token/2)
  433. end);
  434. %% @todo Extension parameters.
  435. parse_header(Name, Req, Default) when Name =:= <<"transfer-encoding">> ->
  436. parse_header(Name, Req, Default,
  437. fun (Value) ->
  438. cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2)
  439. end);
  440. parse_header(Name, Req, Default) when Name =:= <<"upgrade">> ->
  441. parse_header(Name, Req, Default,
  442. fun (Value) ->
  443. cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2)
  444. end);
  445. parse_header(Name, Req, Default) ->
  446. {Value, Req2} = header(Name, Req, Default),
  447. {undefined, Value, Req2}.
  448. parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) ->
  449. case header(Name, Req) of
  450. {undefined, Req2} ->
  451. {ok, Default, Req2#http_req{p_headers=[{Name, Default}|PHeaders]}};
  452. {Value, Req2} ->
  453. case Fun(Value) of
  454. {error, badarg} ->
  455. {error, badarg};
  456. P ->
  457. {ok, P, Req2#http_req{p_headers=[{Name, P}|PHeaders]}}
  458. end
  459. end.
  460. %% @equiv cookie(Name, Req, undefined)
  461. -spec cookie(binary(), Req)
  462. -> {binary() | true | undefined, Req} when Req::req().
  463. cookie(Name, Req) when is_binary(Name) ->
  464. cookie(Name, Req, undefined).
  465. %% @doc Return the cookie value for the given key, or a default if
  466. %% missing.
  467. -spec cookie(binary(), Req, Default)
  468. -> {binary() | true | Default, Req} when Req::req(), Default::any().
  469. cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) ->
  470. case parse_header(<<"cookie">>, Req) of
  471. {ok, undefined, Req2} ->
  472. {Default, Req2#http_req{cookies=[]}};
  473. {ok, Cookies, Req2} ->
  474. cookie(Name, Req2#http_req{cookies=Cookies}, Default)
  475. end;
  476. cookie(Name, Req, Default) ->
  477. case lists:keyfind(Name, 1, Req#http_req.cookies) of
  478. {Name, Value} -> {Value, Req};
  479. false -> {Default, Req}
  480. end.
  481. %% @doc Return the full list of cookie values.
  482. -spec cookies(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
  483. cookies(Req=#http_req{cookies=undefined}) ->
  484. case parse_header(<<"cookie">>, Req) of
  485. {ok, undefined, Req2} ->
  486. {[], Req2#http_req{cookies=[]}};
  487. {ok, Cookies, Req2} ->
  488. cookies(Req2#http_req{cookies=Cookies})
  489. end;
  490. cookies(Req=#http_req{cookies=Cookies}) ->
  491. {Cookies, Req}.
  492. %% @equiv meta(Name, Req, undefined)
  493. -spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req().
  494. meta(Name, Req) ->
  495. meta(Name, Req, undefined).
  496. %% @doc Return metadata information about the request.
  497. %%
  498. %% Metadata information varies from one protocol to another. Websockets
  499. %% would define the protocol version here, while REST would use it to
  500. %% indicate which media type, language and charset were retained.
  501. -spec meta(atom(), Req, any()) -> {any(), Req} when Req::req().
  502. meta(Name, Req, Default) ->
  503. case lists:keyfind(Name, 1, Req#http_req.meta) of
  504. {Name, Value} -> {Value, Req};
  505. false -> {Default, Req}
  506. end.
  507. %% @doc Set metadata information.
  508. %%
  509. %% You can use this function to attach information about the request.
  510. %%
  511. %% If the value already exists it will be overwritten.
  512. -spec set_meta(atom(), any(), Req) -> Req when Req::req().
  513. set_meta(Name, Value, Req=#http_req{meta=Meta}) ->
  514. Req#http_req{meta=[{Name, Value}|lists:keydelete(Name, 1, Meta)]}.
  515. %% Request Body API.
  516. %% @doc Return whether the request message has a body.
  517. -spec has_body(cowboy_req:req()) -> boolean().
  518. has_body(Req) ->
  519. case lists:keyfind(<<"content-length">>, 1, Req#http_req.headers) of
  520. {_, <<"0">>} ->
  521. false;
  522. {_, _} ->
  523. true;
  524. _ ->
  525. lists:keymember(<<"transfer-encoding">>, 1, Req#http_req.headers)
  526. end.
  527. %% @doc Return the request message body length, if known.
  528. %%
  529. %% The length may not be known if Transfer-Encoding is not identity,
  530. %% and the body hasn't been read at the time of the call.
  531. -spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req().
  532. body_length(Req) ->
  533. case parse_header(<<"transfer-encoding">>, Req) of
  534. {ok, [<<"identity">>], Req2} ->
  535. {ok, Length, Req3} = parse_header(<<"content-length">>, Req2, 0),
  536. {Length, Req3};
  537. {ok, _, Req2} ->
  538. {undefined, Req2}
  539. end.
  540. %% @equiv init_stream(1000000, TransferDecode, TransferState, ContentDecode, Req)
  541. -spec init_stream(fun(), any(), fun(), Req)
  542. -> {ok, Req} when Req::req().
  543. init_stream(TransferDecode, TransferState, ContentDecode, Req) ->
  544. init_stream(1000000, TransferDecode, TransferState, ContentDecode, Req).
  545. %% @doc Initialize body streaming and set custom decoding functions.
  546. %%
  547. %% Calling this function is optional. It should only be used if you
  548. %% need to override the default behavior of Cowboy. Otherwise you
  549. %% should call stream_body/1 directly.
  550. %%
  551. %% Two decodings happen. First a decoding function is applied to the
  552. %% transferred data, and then another is applied to the actual content.
  553. %%
  554. %% Transfer encoding is generally used for chunked bodies. The decoding
  555. %% function uses a state to keep track of how much it has read, which is
  556. %% also initialized through this function.
  557. %%
  558. %% Content encoding is generally used for compression.
  559. %%
  560. %% Standard encodings can be found in cowboy_http.
  561. -spec init_stream(non_neg_integer(), fun(), any(), fun(), Req)
  562. -> {ok, Req} when Req::req().
  563. init_stream(MaxLength, TransferDecode, TransferState, ContentDecode, Req) ->
  564. {ok, Req#http_req{body_state=
  565. {stream, 0, MaxLength, TransferDecode, TransferState, ContentDecode}}}.
  566. %% @doc Stream the request's body.
  567. %%
  568. %% This is the most low level function to read the request body.
  569. %%
  570. %% In most cases, if they weren't defined before using stream_body/4,
  571. %% this function will guess which transfer and content encodings were
  572. %% used for building the request body, and configure the decoding
  573. %% functions that will be used when streaming.
  574. %%
  575. %% It then starts streaming the body, returning {ok, Data, Req}
  576. %% for each streamed part, and {done, Req} when it's finished streaming.
  577. -spec stream_body(Req) -> {ok, binary(), Req}
  578. | {done, Req} | {error, atom()} when Req::req().
  579. stream_body(Req=#http_req{body_state=waiting,
  580. version=Version, transport=Transport, socket=Socket}) ->
  581. {ok, ExpectHeader, Req1} = parse_header(<<"expect">>, Req),
  582. case ExpectHeader of
  583. [<<"100-continue">>] ->
  584. HTTPVer = cowboy_http:version_to_binary(Version),
  585. Transport:send(Socket,
  586. << HTTPVer/binary, " ", (status(100))/binary, "\r\n\r\n" >>);
  587. undefined ->
  588. ok
  589. end,
  590. case parse_header(<<"transfer-encoding">>, Req1) of
  591. {ok, [<<"chunked">>], Req2} ->
  592. stream_body(Req2#http_req{body_state=
  593. {stream, 0, 1000000,
  594. fun cowboy_http:te_chunked/2, {0, 0},
  595. fun cowboy_http:ce_identity/1}});
  596. {ok, [<<"identity">>], Req2} ->
  597. {Length, Req3} = body_length(Req2),
  598. case Length of
  599. 0 ->
  600. {done, Req3#http_req{body_state=done}};
  601. Length ->
  602. stream_body(Req3#http_req{body_state=
  603. {stream, Length, 1000000,
  604. fun cowboy_http:te_identity/2, {0, Length},
  605. fun cowboy_http:ce_identity/1}})
  606. end
  607. end;
  608. stream_body(Req=#http_req{body_state=done}) ->
  609. {done, Req};
  610. stream_body(Req=#http_req{buffer=Buffer})
  611. when Buffer =/= <<>> ->
  612. transfer_decode(Buffer, Req#http_req{buffer= <<>>});
  613. stream_body(Req) ->
  614. stream_body_recv(Req).
  615. -spec stream_body_recv(Req)
  616. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  617. stream_body_recv(Req=#http_req{
  618. transport=Transport, socket=Socket, buffer=Buffer,
  619. body_state={stream, Length, MaxLength, _, _, _}}) ->
  620. %% @todo Allow configuring the timeout.
  621. case Transport:recv(Socket, min(Length, MaxLength), 5000) of
  622. {ok, Data} -> transfer_decode(<< Buffer/binary, Data/binary >>,
  623. Req#http_req{buffer= <<>>});
  624. {error, Reason} -> {error, Reason}
  625. end.
  626. -spec transfer_decode(binary(), Req)
  627. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  628. transfer_decode(Data, Req=#http_req{body_state={stream, _, MaxLength,
  629. TransferDecode, TransferState, ContentDecode}}) ->
  630. case TransferDecode(Data, TransferState) of
  631. {ok, Data2, Rest, TransferState2} ->
  632. content_decode(ContentDecode, Data2,
  633. Req#http_req{buffer=Rest, body_state={stream, 0, MaxLength,
  634. TransferDecode, TransferState2, ContentDecode}});
  635. %% @todo {header(s) for chunked
  636. more ->
  637. stream_body_recv(Req#http_req{buffer=Data, body_state={stream,
  638. 0, MaxLength, TransferDecode, TransferState, ContentDecode}});
  639. {more, Length, Data2, TransferState2} ->
  640. content_decode(ContentDecode, Data2,
  641. Req#http_req{body_state={stream, Length, MaxLength,
  642. TransferDecode, TransferState2, ContentDecode}});
  643. {done, Length, Rest} ->
  644. Req2 = transfer_decode_done(Length, Rest, Req),
  645. {done, Req2};
  646. {done, Data2, Length, Rest} ->
  647. Req2 = transfer_decode_done(Length, Rest, Req),
  648. content_decode(ContentDecode, Data2, Req2);
  649. {error, Reason} ->
  650. {error, Reason}
  651. end.
  652. -spec transfer_decode_done(non_neg_integer(), binary(), Req)
  653. -> Req when Req::req().
  654. transfer_decode_done(Length, Rest, Req=#http_req{
  655. headers=Headers, p_headers=PHeaders}) ->
  656. Headers2 = lists:keystore(<<"content-length">>, 1, Headers,
  657. {<<"content-length">>, list_to_binary(integer_to_list(Length))}),
  658. %% At this point we just assume TEs were all decoded.
  659. Headers3 = lists:keydelete(<<"transfer-encoding">>, 1, Headers2),
  660. PHeaders2 = lists:keystore(<<"content-length">>, 1, PHeaders,
  661. {<<"content-length">>, Length}),
  662. PHeaders3 = lists:keydelete(<<"transfer-encoding">>, 1, PHeaders2),
  663. Req#http_req{buffer=Rest, body_state=done,
  664. headers=Headers3, p_headers=PHeaders3}.
  665. %% @todo Probably needs a Rest.
  666. -spec content_decode(fun(), binary(), Req)
  667. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  668. content_decode(ContentDecode, Data, Req) ->
  669. case ContentDecode(Data) of
  670. {ok, Data2} -> {ok, Data2, Req};
  671. {error, Reason} -> {error, Reason}
  672. end.
  673. %% @equiv body(8000000, Req)
  674. -spec body(Req) -> {ok, binary(), Req} | {error, atom()} when Req::req().
  675. body(Req) ->
  676. body(8000000, Req).
  677. %% @doc Return the body sent with the request.
  678. -spec body(non_neg_integer() | infinity, Req)
  679. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  680. body(infinity, Req) ->
  681. case parse_header(<<"transfer-encoding">>, Req) of
  682. {ok, [<<"identity">>], Req2} ->
  683. read_body(Req2, <<>>);
  684. {ok, _, _} ->
  685. {error, chunked}
  686. end;
  687. body(MaxBodyLength, Req) ->
  688. case parse_header(<<"transfer-encoding">>, Req) of
  689. {ok, [<<"identity">>], Req2} ->
  690. {ok, Length, Req3} = parse_header(<<"content-length">>, Req2, 0),
  691. if Length > MaxBodyLength ->
  692. {error, badlength};
  693. true ->
  694. read_body(Req3, <<>>)
  695. end;
  696. {ok, _, _} ->
  697. {error, chunked}
  698. end.
  699. -spec read_body(Req, binary())
  700. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  701. read_body(Req, Acc) ->
  702. case stream_body(Req) of
  703. {ok, Data, Req2} ->
  704. read_body(Req2, << Acc/binary, Data/binary >>);
  705. {done, Req2} ->
  706. {ok, Acc, Req2};
  707. {error, Reason} ->
  708. {error, Reason}
  709. end.
  710. -spec skip_body(Req) -> {ok, Req} | {error, atom()} when Req::req().
  711. skip_body(Req) ->
  712. case stream_body(Req) of
  713. {ok, _, Req2} -> skip_body(Req2);
  714. {done, Req2} -> {ok, Req2};
  715. {error, Reason} -> {error, Reason}
  716. end.
  717. %% @equiv body_qs(16000, Req)
  718. -spec body_qs(Req)
  719. -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
  720. when Req::req().
  721. body_qs(Req) ->
  722. body_qs(16000, Req).
  723. %% @doc Return the body sent with the request, parsed as an
  724. %% application/x-www-form-urlencoded string.
  725. %% Essentially a POST query string.
  726. -spec body_qs(non_neg_integer() | infinity, Req)
  727. -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
  728. when Req::req().
  729. body_qs(MaxBodyLength, Req) ->
  730. case body(MaxBodyLength, Req) of
  731. {ok, Body, Req2} ->
  732. {ok, cowboy_http:x_www_form_urlencoded(Body), Req2};
  733. {error, Reason} ->
  734. {error, Reason}
  735. end.
  736. %% Multipart Request API.
  737. %% @doc Return data from the multipart parser.
  738. %%
  739. %% Use this function for multipart streaming. For each part in the request,
  740. %% this function returns <em>{headers, Headers}</em> followed by a sequence of
  741. %% <em>{body, Data}</em> tuples and finally <em>end_of_part</em>. When there
  742. %% is no part to parse anymore, <em>eof</em> is returned.
  743. %%
  744. %% If the request Content-Type is not a multipart one, <em>{error, badarg}</em>
  745. %% is returned.
  746. -spec multipart_data(Req)
  747. -> {headers, cowboy_http:headers(), Req} | {body, binary(), Req}
  748. | {end_of_part | eof, Req} when Req::req().
  749. multipart_data(Req=#http_req{body_state=waiting}) ->
  750. {ok, {<<"multipart">>, _SubType, Params}, Req2} =
  751. parse_header(<<"content-type">>, Req),
  752. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  753. {ok, Length, Req3} = parse_header(<<"content-length">>, Req2),
  754. multipart_data(Req3, Length, {more, cowboy_multipart:parser(Boundary)});
  755. multipart_data(Req=#http_req{multipart={Length, Cont}}) ->
  756. multipart_data(Req, Length, Cont());
  757. multipart_data(Req=#http_req{body_state=done}) ->
  758. {eof, Req}.
  759. multipart_data(Req, Length, {headers, Headers, Cont}) ->
  760. {headers, Headers, Req#http_req{multipart={Length, Cont}}};
  761. multipart_data(Req, Length, {body, Data, Cont}) ->
  762. {body, Data, Req#http_req{multipart={Length, Cont}}};
  763. multipart_data(Req, Length, {end_of_part, Cont}) ->
  764. {end_of_part, Req#http_req{multipart={Length, Cont}}};
  765. multipart_data(Req, 0, eof) ->
  766. {eof, Req#http_req{body_state=done, multipart=undefined}};
  767. multipart_data(Req=#http_req{socket=Socket, transport=Transport},
  768. Length, eof) ->
  769. %% We just want to skip so no need to stream data here.
  770. {ok, _Data} = Transport:recv(Socket, Length, 5000),
  771. {eof, Req#http_req{body_state=done, multipart=undefined}};
  772. multipart_data(Req, Length, {more, Parser}) when Length > 0 ->
  773. case stream_body(Req) of
  774. {ok, << Data:Length/binary, Buffer/binary >>, Req2} ->
  775. multipart_data(Req2#http_req{buffer=Buffer}, 0, Parser(Data));
  776. {ok, Data, Req2} ->
  777. multipart_data(Req2, Length - byte_size(Data), Parser(Data))
  778. end.
  779. %% @doc Skip a part returned by the multipart parser.
  780. %%
  781. %% This function repeatedly calls <em>multipart_data/1</em> until
  782. %% <em>end_of_part</em> or <em>eof</em> is parsed.
  783. -spec multipart_skip(Req) -> {ok, Req} when Req::req().
  784. multipart_skip(Req) ->
  785. case multipart_data(Req) of
  786. {end_of_part, Req2} -> {ok, Req2};
  787. {eof, Req2} -> {ok, Req2};
  788. {_, _, Req2} -> multipart_skip(Req2)
  789. end.
  790. %% Response API.
  791. %% @doc Add a cookie header to the response.
  792. %%
  793. %% The cookie name cannot contain any of the following characters:
  794. %% =,;\s\t\r\n\013\014
  795. %%
  796. %% The cookie value cannot contain any of the following characters:
  797. %% ,; \t\r\n\013\014
  798. -spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req)
  799. -> Req when Req::req().
  800. set_resp_cookie(Name, Value, Opts, Req) ->
  801. Cookie = cowboy_http:cookie_to_iodata(Name, Value, Opts),
  802. set_resp_header(<<"set-cookie">>, Cookie, Req).
  803. %% @doc Add a header to the response.
  804. -spec set_resp_header(binary(), iodata(), Req)
  805. -> Req when Req::req().
  806. set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
  807. Req#http_req{resp_headers=[{Name, Value}|RespHeaders]}.
  808. %% @doc Add a body to the response.
  809. %%
  810. %% The body set here is ignored if the response is later sent using
  811. %% anything other than reply/2 or reply/3. The response body is expected
  812. %% to be a binary or an iolist.
  813. -spec set_resp_body(iodata(), Req) -> Req when Req::req().
  814. set_resp_body(Body, Req) ->
  815. Req#http_req{resp_body=Body}.
  816. %% @doc Add a body stream function to the response.
  817. %%
  818. %% The body set here is ignored if the response is later sent using
  819. %% anything other than reply/2 or reply/3.
  820. %%
  821. %% Setting a response stream function without a length means that the
  822. %% body will be sent until the connection is closed. Cowboy will make
  823. %% sure that the connection is closed with no extra step required.
  824. %%
  825. %% To inform the client that a body has been sent with this request,
  826. %% Cowboy will add a "Transfer-Encoding: identity" header to the
  827. %% response.
  828. -spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req().
  829. set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) ->
  830. Req#http_req{resp_body=StreamFun}.
  831. %% @doc Add a body function to the response.
  832. %%
  833. %% The body set here is ignored if the response is later sent using
  834. %% anything other than reply/2 or reply/3.
  835. %%
  836. %% Cowboy will call the given response stream function after sending the
  837. %% headers. This function must send the specified number of bytes to the
  838. %% socket it will receive as argument.
  839. %%
  840. %% If the body function crashes while writing the response body or writes
  841. %% fewer bytes than declared the behaviour is undefined.
  842. -spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req)
  843. -> Req when Req::req().
  844. set_resp_body_fun(StreamLen, StreamFun, Req)
  845. when is_integer(StreamLen), is_function(StreamFun) ->
  846. Req#http_req{resp_body={StreamLen, StreamFun}}.
  847. %% @doc Return whether the given header has been set for the response.
  848. -spec has_resp_header(binary(), req()) -> boolean().
  849. has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
  850. lists:keymember(Name, 1, RespHeaders).
  851. %% @doc Return whether a body has been set for the response.
  852. -spec has_resp_body(req()) -> boolean().
  853. has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) ->
  854. true;
  855. has_resp_body(#http_req{resp_body={Length, _}}) ->
  856. Length > 0;
  857. has_resp_body(#http_req{resp_body=RespBody}) ->
  858. iolist_size(RespBody) > 0.
  859. %% Remove a header previously set for the response.
  860. -spec delete_resp_header(binary(), Req)
  861. -> Req when Req::req().
  862. delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) ->
  863. RespHeaders2 = lists:keydelete(Name, 1, RespHeaders),
  864. Req#http_req{resp_headers=RespHeaders2}.
  865. %% @equiv reply(Status, [], [], Req)
  866. -spec reply(cowboy_http:status(), Req) -> {ok, Req} when Req::req().
  867. reply(Status, Req=#http_req{resp_body=Body}) ->
  868. reply(Status, [], Body, Req).
  869. %% @equiv reply(Status, Headers, [], Req)
  870. -spec reply(cowboy_http:status(), cowboy_http:headers(), Req)
  871. -> {ok, Req} when Req::req().
  872. reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
  873. reply(Status, Headers, Body, Req).
  874. %% @doc Send a reply to the client.
  875. -spec reply(cowboy_http:status(), cowboy_http:headers(),
  876. iodata() | {non_neg_integer() | resp_body_fun()}, Req)
  877. -> {ok, Req} when Req::req().
  878. reply(Status, Headers, Body, Req=#http_req{
  879. socket=Socket, transport=Transport,
  880. version=Version, connection=Connection,
  881. method=Method, resp_compress=Compress,
  882. resp_state=waiting, resp_headers=RespHeaders}) ->
  883. HTTP11Headers = case Version of
  884. {1, 1} -> [{<<"connection">>, atom_to_connection(Connection)}];
  885. _ -> []
  886. end,
  887. Req3 = case Body of
  888. BodyFun when is_function(BodyFun) ->
  889. %% We stream the response body until we close the connection.
  890. RespConn = close,
  891. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  892. {<<"connection">>, <<"close">>},
  893. {<<"date">>, cowboy_clock:rfc1123()},
  894. {<<"server">>, <<"Cowboy">>},
  895. {<<"transfer-encoding">>, <<"identity">>}
  896. ], <<>>, Req),
  897. if RespType =/= hook, Method =/= <<"HEAD">> ->
  898. BodyFun(Socket, Transport);
  899. true -> ok
  900. end,
  901. Req2#http_req{connection=RespConn};
  902. {ContentLength, BodyFun} ->
  903. %% We stream the response body for ContentLength bytes.
  904. RespConn = response_connection(Headers, Connection),
  905. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  906. {<<"content-length">>, integer_to_list(ContentLength)},
  907. {<<"date">>, cowboy_clock:rfc1123()},
  908. {<<"server">>, <<"Cowboy">>}
  909. |HTTP11Headers], <<>>, Req),
  910. if RespType =/= hook, Method =/= <<"HEAD">> ->
  911. BodyFun(Socket, Transport);
  912. true -> ok
  913. end,
  914. Req2#http_req{connection=RespConn};
  915. _ when Compress ->
  916. RespConn = response_connection(Headers, Connection),
  917. Req2 = reply_may_compress(Status, Headers, Body, Req,
  918. RespHeaders, HTTP11Headers, Method),
  919. Req2#http_req{connection=RespConn};
  920. _ ->
  921. RespConn = response_connection(Headers, Connection),
  922. Req2 = reply_no_compress(Status, Headers, Body, Req,
  923. RespHeaders, HTTP11Headers, Method, iolist_size(Body)),
  924. Req2#http_req{connection=RespConn}
  925. end,
  926. {ok, Req3#http_req{resp_state=done,resp_headers=[], resp_body= <<>>}}.
  927. reply_may_compress(Status, Headers, Body, Req,
  928. RespHeaders, HTTP11Headers, Method) ->
  929. BodySize = iolist_size(Body),
  930. {ok, Encodings, Req2}
  931. = cowboy_req:parse_header(<<"accept-encoding">>, Req),
  932. CanGzip = (BodySize > 300)
  933. andalso (false =:= lists:keyfind(<<"content-encoding">>,
  934. 1, Headers))
  935. andalso (false =:= lists:keyfind(<<"content-encoding">>,
  936. 1, RespHeaders))
  937. andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  938. 1, Headers))
  939. andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  940. 1, RespHeaders))
  941. andalso (Encodings =/= undefined)
  942. andalso (false =/= lists:keyfind(<<"gzip">>, 1, Encodings)),
  943. case CanGzip of
  944. true ->
  945. GzBody = zlib:gzip(Body),
  946. {_, Req3} = response(Status, Headers, RespHeaders, [
  947. {<<"content-length">>, integer_to_list(byte_size(GzBody))},
  948. {<<"content-encoding">>, <<"gzip">>},
  949. {<<"date">>, cowboy_clock:rfc1123()},
  950. {<<"server">>, <<"Cowboy">>}
  951. |HTTP11Headers],
  952. case Method of <<"HEAD">> -> <<>>; _ -> GzBody end,
  953. Req2),
  954. Req3;
  955. false ->
  956. reply_no_compress(Status, Headers, Body, Req,
  957. RespHeaders, HTTP11Headers, Method, BodySize)
  958. end.
  959. reply_no_compress(Status, Headers, Body, Req,
  960. RespHeaders, HTTP11Headers, Method, BodySize) ->
  961. {_, Req2} = response(Status, Headers, RespHeaders, [
  962. {<<"content-length">>, integer_to_list(BodySize)},
  963. {<<"date">>, cowboy_clock:rfc1123()},
  964. {<<"server">>, <<"Cowboy">>}
  965. |HTTP11Headers],
  966. case Method of <<"HEAD">> -> <<>>; _ -> Body end,
  967. Req),
  968. Req2.
  969. %% @equiv chunked_reply(Status, [], Req)
  970. -spec chunked_reply(cowboy_http:status(), Req) -> {ok, Req} when Req::req().
  971. chunked_reply(Status, Req) ->
  972. chunked_reply(Status, [], Req).
  973. %% @doc Initiate the sending of a chunked reply to the client.
  974. %% @see cowboy_req:chunk/2
  975. -spec chunked_reply(cowboy_http:status(), cowboy_http:headers(), Req)
  976. -> {ok, Req} when Req::req().
  977. chunked_reply(Status, Headers, Req=#http_req{
  978. version=Version, connection=Connection,
  979. resp_state=waiting, resp_headers=RespHeaders}) ->
  980. RespConn = response_connection(Headers, Connection),
  981. HTTP11Headers = case Version of
  982. {1, 1} -> [
  983. {<<"connection">>, atom_to_connection(Connection)},
  984. {<<"transfer-encoding">>, <<"chunked">>}];
  985. _ -> []
  986. end,
  987. {_, Req2} = response(Status, Headers, RespHeaders, [
  988. {<<"date">>, cowboy_clock:rfc1123()},
  989. {<<"server">>, <<"Cowboy">>}
  990. |HTTP11Headers], <<>>, Req),
  991. {ok, Req2#http_req{connection=RespConn, resp_state=chunks,
  992. resp_headers=[], resp_body= <<>>}}.
  993. %% @doc Send a chunk of data.
  994. %%
  995. %% A chunked reply must have been initiated before calling this function.
  996. -spec chunk(iodata(), req()) -> ok | {error, atom()}.
  997. chunk(_Data, #http_req{method= <<"HEAD">>}) ->
  998. ok;
  999. chunk(Data, #http_req{socket=Socket, transport=Transport, version={1, 0}}) ->
  1000. Transport:send(Socket, Data);
  1001. chunk(Data, #http_req{socket=Socket, transport=Transport, resp_state=chunks}) ->
  1002. Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
  1003. <<"\r\n">>, Data, <<"\r\n">>]).
  1004. %% @doc Send an upgrade reply.
  1005. %% @private
  1006. -spec upgrade_reply(cowboy_http:status(), cowboy_http:headers(), Req)
  1007. -> {ok, Req} when Req::req().
  1008. upgrade_reply(Status, Headers, Req=#http_req{
  1009. resp_state=waiting, resp_headers=RespHeaders}) ->
  1010. {_, Req2} = response(Status, Headers, RespHeaders, [
  1011. {<<"connection">>, <<"Upgrade">>}
  1012. ], <<>>, Req),
  1013. {ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  1014. %% @doc Ensure the response has been sent fully.
  1015. %% @private
  1016. -spec ensure_response(req(), cowboy_http:status()) -> ok.
  1017. %% The response has already been fully sent to the client.
  1018. ensure_response(#http_req{resp_state=done}, _) ->
  1019. ok;
  1020. %% No response has been sent but everything apparently went fine.
  1021. %% Reply with the status code found in the second argument.
  1022. ensure_response(Req=#http_req{resp_state=waiting}, Status) ->
  1023. _ = reply(Status, [], [], Req),
  1024. ok;
  1025. %% Terminate the chunked body for HTTP/1.1 only.
  1026. ensure_response(#http_req{method= <<"HEAD">>, resp_state=chunks}, _) ->
  1027. ok;
  1028. ensure_response(#http_req{version={1, 0}, resp_state=chunks}, _) ->
  1029. ok;
  1030. ensure_response(#http_req{socket=Socket, transport=Transport,
  1031. resp_state=chunks}, _) ->
  1032. Transport:send(Socket, <<"0\r\n\r\n">>),
  1033. ok.
  1034. %% Private setter/getter API.
  1035. %% @private
  1036. -spec append_buffer(binary(), Req) -> Req when Req::req().
  1037. append_buffer(Suffix, Req=#http_req{buffer=Buffer}) ->
  1038. Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}.
  1039. %% @private
  1040. -spec get(atom(), req()) -> any(); ([atom()], req()) -> any().
  1041. get(List, Req) when is_list(List) ->
  1042. [g(Atom, Req) || Atom <- List];
  1043. get(Atom, Req) when is_atom(Atom) ->
  1044. g(Atom, Req).
  1045. g(bindings, #http_req{bindings=Ret}) -> Ret;
  1046. g(body_state, #http_req{body_state=Ret}) -> Ret;
  1047. g(buffer, #http_req{buffer=Ret}) -> Ret;
  1048. g(connection, #http_req{connection=Ret}) -> Ret;
  1049. g(cookies, #http_req{cookies=Ret}) -> Ret;
  1050. g(fragment, #http_req{fragment=Ret}) -> Ret;
  1051. g(headers, #http_req{headers=Ret}) -> Ret;
  1052. g(host, #http_req{host=Ret}) -> Ret;
  1053. g(host_info, #http_req{host_info=Ret}) -> Ret;
  1054. g(meta, #http_req{meta=Ret}) -> Ret;
  1055. g(method, #http_req{method=Ret}) -> Ret;
  1056. g(multipart, #http_req{multipart=Ret}) -> Ret;
  1057. g(onresponse, #http_req{onresponse=Ret}) -> Ret;
  1058. g(p_headers, #http_req{p_headers=Ret}) -> Ret;
  1059. g(path, #http_req{path=Ret}) -> Ret;
  1060. g(path_info, #http_req{path_info=Ret}) -> Ret;
  1061. g(peer, #http_req{peer=Ret}) -> Ret;
  1062. g(pid, #http_req{pid=Ret}) -> Ret;
  1063. g(port, #http_req{port=Ret}) -> Ret;
  1064. g(qs, #http_req{qs=Ret}) -> Ret;
  1065. g(qs_vals, #http_req{qs_vals=Ret}) -> Ret;
  1066. g(resp_body, #http_req{resp_body=Ret}) -> Ret;
  1067. g(resp_headers, #http_req{resp_headers=Ret}) -> Ret;
  1068. g(resp_state, #http_req{resp_state=Ret}) -> Ret;
  1069. g(socket, #http_req{socket=Ret}) -> Ret;
  1070. g(transport, #http_req{transport=Ret}) -> Ret;
  1071. g(version, #http_req{version=Ret}) -> Ret.
  1072. %% @private
  1073. -spec set([{atom(), any()}], Req) -> Req when Req::req().
  1074. set([], Req) -> Req;
  1075. set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val});
  1076. set([{body_state, Val}|Tail], Req) -> set(Tail, Req#http_req{body_state=Val});
  1077. set([{buffer, Val}|Tail], Req) -> set(Tail, Req#http_req{buffer=Val});
  1078. set([{connection, Val}|Tail], Req) -> set(Tail, Req#http_req{connection=Val});
  1079. set([{cookies, Val}|Tail], Req) -> set(Tail, Req#http_req{cookies=Val});
  1080. set([{fragment, Val}|Tail], Req) -> set(Tail, Req#http_req{fragment=Val});
  1081. set([{headers, Val}|Tail], Req) -> set(Tail, Req#http_req{headers=Val});
  1082. set([{host, Val}|Tail], Req) -> set(Tail, Req#http_req{host=Val});
  1083. set([{host_info, Val}|Tail], Req) -> set(Tail, Req#http_req{host_info=Val});
  1084. set([{meta, Val}|Tail], Req) -> set(Tail, Req#http_req{meta=Val});
  1085. set([{method, Val}|Tail], Req) -> set(Tail, Req#http_req{method=Val});
  1086. set([{multipart, Val}|Tail], Req) -> set(Tail, Req#http_req{multipart=Val});
  1087. set([{onresponse, Val}|Tail], Req) -> set(Tail, Req#http_req{onresponse=Val});
  1088. set([{p_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{p_headers=Val});
  1089. set([{path, Val}|Tail], Req) -> set(Tail, Req#http_req{path=Val});
  1090. set([{path_info, Val}|Tail], Req) -> set(Tail, Req#http_req{path_info=Val});
  1091. set([{peer, Val}|Tail], Req) -> set(Tail, Req#http_req{peer=Val});
  1092. set([{pid, Val}|Tail], Req) -> set(Tail, Req#http_req{pid=Val});
  1093. set([{port, Val}|Tail], Req) -> set(Tail, Req#http_req{port=Val});
  1094. set([{qs, Val}|Tail], Req) -> set(Tail, Req#http_req{qs=Val});
  1095. set([{qs_vals, Val}|Tail], Req) -> set(Tail, Req#http_req{qs_vals=Val});
  1096. set([{resp_body, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_body=Val});
  1097. set([{resp_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_headers=Val});
  1098. set([{resp_state, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_state=Val});
  1099. set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val});
  1100. set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val});
  1101. set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}).
  1102. %% @private
  1103. -spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(),
  1104. cowboy_router:bindings(), Req) -> Req when Req::req().
  1105. set_bindings(HostInfo, PathInfo, Bindings, Req) ->
  1106. Req#http_req{host_info=HostInfo, path_info=PathInfo,
  1107. bindings=Bindings}.
  1108. %% Misc API.
  1109. %% @doc Compact the request data by removing all non-system information.
  1110. %%
  1111. %% This essentially removes the host and path info, query string, bindings,
  1112. %% headers and cookies.
  1113. %%
  1114. %% Use it when you really need to save up memory, for example when having
  1115. %% many concurrent long-running connections.
  1116. -spec compact(Req) -> Req when Req::req().
  1117. compact(Req) ->
  1118. Req#http_req{host_info=undefined,
  1119. path_info=undefined, qs_vals=undefined,
  1120. bindings=undefined, headers=[],
  1121. p_headers=[], cookies=[]}.
  1122. %% @doc Prevent any further responses.
  1123. %% @private
  1124. -spec lock(Req) -> Req when Req::req().
  1125. lock(Req) ->
  1126. Req#http_req{resp_state=locked}.
  1127. %% @doc Convert the Req object to a list of key/values.
  1128. -spec to_list(req()) -> [{atom(), any()}].
  1129. to_list(Req) ->
  1130. lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))).
  1131. %% Internal.
  1132. -spec response(cowboy_http:status(), cowboy_http:headers(),
  1133. cowboy_http:headers(), cowboy_http:headers(), iodata(), Req)
  1134. -> {normal | hook, Req} when Req::req().
  1135. response(Status, Headers, RespHeaders, DefaultHeaders, Body, Req=#http_req{
  1136. socket=Socket, transport=Transport, version=Version,
  1137. pid=ReqPid, onresponse=OnResponse}) ->
  1138. FullHeaders = case OnResponse of
  1139. already_called -> Headers;
  1140. _ -> response_merge_headers(Headers, RespHeaders, DefaultHeaders)
  1141. end,
  1142. Req2 = case OnResponse of
  1143. already_called -> Req;
  1144. undefined -> Req;
  1145. OnResponse -> OnResponse(Status, FullHeaders, Body,
  1146. %% Don't call 'onresponse' from the hook itself.
  1147. Req#http_req{resp_headers=[], resp_body= <<>>,
  1148. onresponse=already_called})
  1149. end,
  1150. ReplyType = case Req2#http_req.resp_state of
  1151. waiting ->
  1152. HTTPVer = cowboy_http:version_to_binary(Version),
  1153. StatusLine = << HTTPVer/binary, " ",
  1154. (status(Status))/binary, "\r\n" >>,
  1155. HeaderLines = [[Key, <<": ">>, Value, <<"\r\n">>]
  1156. || {Key, Value} <- FullHeaders],
  1157. Transport:send(Socket, [StatusLine, HeaderLines, <<"\r\n">>, Body]),
  1158. ReqPid ! {?MODULE, resp_sent},
  1159. normal;
  1160. _ ->
  1161. hook
  1162. end,
  1163. {ReplyType, Req2}.
  1164. -spec response_connection(cowboy_http:headers(), keepalive | close)
  1165. -> keepalive | close.
  1166. response_connection([], Connection) ->
  1167. Connection;
  1168. response_connection([{Name, Value}|Tail], Connection) ->
  1169. case Name of
  1170. <<"connection">> ->
  1171. Tokens = parse_connection_before(Value, []),
  1172. connection_to_atom(Tokens);
  1173. _ ->
  1174. response_connection(Tail, Connection)
  1175. end.
  1176. -spec response_merge_headers(cowboy_http:headers(), cowboy_http:headers(),
  1177. cowboy_http:headers()) -> cowboy_http:headers().
  1178. response_merge_headers(Headers, RespHeaders, DefaultHeaders) ->
  1179. Headers2 = [{Key, Value} || {Key, Value} <- Headers],
  1180. merge_headers(
  1181. merge_headers(Headers2, RespHeaders),
  1182. DefaultHeaders).
  1183. -spec merge_headers(cowboy_http:headers(), cowboy_http:headers())
  1184. -> cowboy_http:headers().
  1185. %% Merge headers by prepending the tuples in the second list to the
  1186. %% first list. It also handles Set-Cookie properly, which supports
  1187. %% duplicated entries. Notice that, while the RFC2109 does allow more
  1188. %% than one cookie to be set per Set-Cookie header, we are following
  1189. %% the implementation of common web servers and applications which
  1190. %% return many distinct headers per each Set-Cookie entry to avoid
  1191. %% issues with clients/browser which may not support it.
  1192. merge_headers(Headers, []) ->
  1193. Headers;
  1194. merge_headers(Headers, [{<<"set-cookie">>, Value}|Tail]) ->
  1195. merge_headers([{<<"set-cookie">>, Value}|Headers], Tail);
  1196. merge_headers(Headers, [{Name, Value}|Tail]) ->
  1197. Headers2 = case lists:keymember(Name, 1, Headers) of
  1198. true -> Headers;
  1199. false -> [{Name, Value}|Headers]
  1200. end,
  1201. merge_headers(Headers2, Tail).
  1202. -spec atom_to_connection(keepalive) -> <<_:80>>;
  1203. (close) -> <<_:40>>.
  1204. atom_to_connection(keepalive) ->
  1205. <<"keep-alive">>;
  1206. atom_to_connection(close) ->
  1207. <<"close">>.
  1208. %% Optimized parsing functions for the Connection header.
  1209. parse_connection_before(<<>>, Acc) ->
  1210. lists:reverse(Acc);
  1211. parse_connection_before(<< C, Rest/bits >>, Acc)
  1212. when C =:= $,; C =:= $\s; C =:= $\t ->
  1213. parse_connection_before(Rest, Acc);
  1214. parse_connection_before(Buffer, Acc) ->
  1215. parse_connection(Buffer, Acc, <<>>).
  1216. %% An evil block of code appeared!
  1217. parse_connection(<<>>, Acc, <<>>) ->
  1218. lists:reverse(Acc);
  1219. parse_connection(<<>>, Acc, Token) ->
  1220. lists:reverse([Token|Acc]);
  1221. parse_connection(<< C, Rest/bits >>, Acc, Token)
  1222. when C =:= $,; C =:= $\s; C =:= $\t ->
  1223. parse_connection_before(Rest, [Token|Acc]);
  1224. parse_connection(<< C, Rest/bits >>, Acc, Token) ->
  1225. case C of
  1226. $A -> parse_connection(Rest, Acc, << Token/binary, $a >>);
  1227. $B -> parse_connection(Rest, Acc, << Token/binary, $b >>);
  1228. $C -> parse_connection(Rest, Acc, << Token/binary, $c >>);
  1229. $D -> parse_connection(Rest, Acc, << Token/binary, $d >>);
  1230. $E -> parse_connection(Rest, Acc, << Token/binary, $e >>);
  1231. $F -> parse_connection(Rest, Acc, << Token/binary, $f >>);
  1232. $G -> parse_connection(Rest, Acc, << Token/binary, $g >>);
  1233. $H -> parse_connection(Rest, Acc, << Token/binary, $h >>);
  1234. $I -> parse_connection(Rest, Acc, << Token/binary, $i >>);
  1235. $J -> parse_connection(Rest, Acc, << Token/binary, $j >>);
  1236. $K -> parse_connection(Rest, Acc, << Token/binary, $k >>);
  1237. $L -> parse_connection(Rest, Acc, << Token/binary, $l >>);
  1238. $M -> parse_connection(Rest, Acc, << Token/binary, $m >>);
  1239. $N -> parse_connection(Rest, Acc, << Token/binary, $n >>);
  1240. $O -> parse_connection(Rest, Acc, << Token/binary, $o >>);
  1241. $P -> parse_connection(Rest, Acc, << Token/binary, $p >>);
  1242. $Q -> parse_connection(Rest, Acc, << Token/binary, $q >>);
  1243. $R -> parse_connection(Rest, Acc, << Token/binary, $r >>);
  1244. $S -> parse_connection(Rest, Acc, << Token/binary, $s >>);
  1245. $T -> parse_connection(Rest, Acc, << Token/binary, $t >>);
  1246. $U -> parse_connection(Rest, Acc, << Token/binary, $u >>);
  1247. $V -> parse_connection(Rest, Acc, << Token/binary, $v >>);
  1248. $W -> parse_connection(Rest, Acc, << Token/binary, $w >>);
  1249. $X -> parse_connection(Rest, Acc, << Token/binary, $x >>);
  1250. $Y -> parse_connection(Rest, Acc, << Token/binary, $y >>);
  1251. $Z -> parse_connection(Rest, Acc, << Token/binary, $z >>);
  1252. C -> parse_connection(Rest, Acc, << Token/binary, C >>)
  1253. end.
  1254. %% @doc Walk through a tokens list and return whether
  1255. %% the connection is keepalive or closed.
  1256. %%
  1257. %% We don't match on "keep-alive" since it is the default value.
  1258. -spec connection_to_atom([binary()]) -> keepalive | close.
  1259. connection_to_atom([]) ->
  1260. keepalive;
  1261. connection_to_atom([<<"close">>|_]) ->
  1262. close;
  1263. connection_to_atom([_|Tail]) ->
  1264. connection_to_atom(Tail).
  1265. -spec status(cowboy_http:status()) -> binary().
  1266. status(100) -> <<"100 Continue">>;
  1267. status(101) -> <<"101 Switching Protocols">>;
  1268. status(102) -> <<"102 Processing">>;
  1269. status(200) -> <<"200 OK">>;
  1270. status(201) -> <<"201 Created">>;
  1271. status(202) -> <<"202 Accepted">>;
  1272. status(203) -> <<"203 Non-Authoritative Information">>;
  1273. status(204) -> <<"204 No Content">>;
  1274. status(205) -> <<"205 Reset Content">>;
  1275. status(206) -> <<"206 Partial Content">>;
  1276. status(207) -> <<"207 Multi-Status">>;
  1277. status(226) -> <<"226 IM Used">>;
  1278. status(300) -> <<"300 Multiple Choices">>;
  1279. status(301) -> <<"301 Moved Permanently">>;
  1280. status(302) -> <<"302 Found">>;
  1281. status(303) -> <<"303 See Other">>;
  1282. status(304) -> <<"304 Not Modified">>;
  1283. status(305) -> <<"305 Use Proxy">>;
  1284. status(306) -> <<"306 Switch Proxy">>;
  1285. status(307) -> <<"307 Temporary Redirect">>;
  1286. status(400) -> <<"400 Bad Request">>;
  1287. status(401) -> <<"401 Unauthorized">>;
  1288. status(402) -> <<"402 Payment Required">>;
  1289. status(403) -> <<"403 Forbidden">>;
  1290. status(404) -> <<"404 Not Found">>;
  1291. status(405) -> <<"405 Method Not Allowed">>;
  1292. status(406) -> <<"406 Not Acceptable">>;
  1293. status(407) -> <<"407 Proxy Authentication Required">>;
  1294. status(408) -> <<"408 Request Timeout">>;
  1295. status(409) -> <<"409 Conflict">>;
  1296. status(410) -> <<"410 Gone">>;
  1297. status(411) -> <<"411 Length Required">>;
  1298. status(412) -> <<"412 Precondition Failed">>;
  1299. status(413) -> <<"413 Request Entity Too Large">>;
  1300. status(414) -> <<"414 Request-URI Too Long">>;
  1301. status(415) -> <<"415 Unsupported Media Type">>;
  1302. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  1303. status(417) -> <<"417 Expectation Failed">>;
  1304. status(418) -> <<"418 I'm a teapot">>;
  1305. status(422) -> <<"422 Unprocessable Entity">>;
  1306. status(423) -> <<"423 Locked">>;
  1307. status(424) -> <<"424 Failed Dependency">>;
  1308. status(425) -> <<"425 Unordered Collection">>;
  1309. status(426) -> <<"426 Upgrade Required">>;
  1310. status(428) -> <<"428 Precondition Required">>;
  1311. status(429) -> <<"429 Too Many Requests">>;
  1312. status(431) -> <<"431 Request Header Fields Too Large">>;
  1313. status(500) -> <<"500 Internal Server Error">>;
  1314. status(501) -> <<"501 Not Implemented">>;
  1315. status(502) -> <<"502 Bad Gateway">>;
  1316. status(503) -> <<"503 Service Unavailable">>;
  1317. status(504) -> <<"504 Gateway Timeout">>;
  1318. status(505) -> <<"505 HTTP Version Not Supported">>;
  1319. status(506) -> <<"506 Variant Also Negotiates">>;
  1320. status(507) -> <<"507 Insufficient Storage">>;
  1321. status(510) -> <<"510 Not Extended">>;
  1322. status(511) -> <<"511 Network Authentication Required">>;
  1323. status(B) when is_binary(B) -> B.
  1324. %% Tests.
  1325. -ifdef(TEST).
  1326. url_test() ->
  1327. {undefined, _} =
  1328. url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined,
  1329. path= <<>>, qs= <<>>, fragment= <<>>, pid=self()}),
  1330. {<<"http://localhost/path">>, _ } =
  1331. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=80,
  1332. path= <<"/path">>, qs= <<>>, fragment= <<>>, pid=self()}),
  1333. {<<"http://localhost:443/path">>, _} =
  1334. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=443,
  1335. path= <<"/path">>, qs= <<>>, fragment= <<>>, pid=self()}),
  1336. {<<"http://localhost:8080/path">>, _} =
  1337. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1338. path= <<"/path">>, qs= <<>>, fragment= <<>>, pid=self()}),
  1339. {<<"http://localhost:8080/path?dummy=2785">>, _} =
  1340. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1341. path= <<"/path">>, qs= <<"dummy=2785">>, fragment= <<>>,
  1342. pid=self()}),
  1343. {<<"http://localhost:8080/path?dummy=2785#fragment">>, _} =
  1344. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1345. path= <<"/path">>, qs= <<"dummy=2785">>, fragment= <<"fragment">>,
  1346. pid=self()}),
  1347. {<<"https://localhost/path">>, _} =
  1348. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=443,
  1349. path= <<"/path">>, qs= <<>>, fragment= <<>>, pid=self()}),
  1350. {<<"https://localhost:8443/path">>, _} =
  1351. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1352. path= <<"/path">>, qs= <<>>, fragment= <<>>, pid=self()}),
  1353. {<<"https://localhost:8443/path?dummy=2785">>, _} =
  1354. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1355. path= <<"/path">>, qs= <<"dummy=2785">>, fragment= <<>>,
  1356. pid=self()}),
  1357. {<<"https://localhost:8443/path?dummy=2785#fragment">>, _} =
  1358. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1359. path= <<"/path">>, qs= <<"dummy=2785">>, fragment= <<"fragment">>,
  1360. pid=self()}),
  1361. ok.
  1362. parse_connection_test_() ->
  1363. %% {Binary, Result}
  1364. Tests = [
  1365. {<<"close">>, [<<"close">>]},
  1366. {<<"ClOsE">>, [<<"close">>]},
  1367. {<<"Keep-Alive">>, [<<"keep-alive">>]},
  1368. {<<"keep-alive, Upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
  1369. ],
  1370. [{B, fun() -> R = parse_connection_before(B, []) end}
  1371. || {B, R} <- Tests].
  1372. connection_to_atom_test_() ->
  1373. %% {Tokens, Result}
  1374. Tests = [
  1375. {[<<"close">>], close},
  1376. {[<<"keep-alive">>], keepalive},
  1377. {[<<"keep-alive">>, <<"upgrade">>], keepalive}
  1378. ],
  1379. [{lists:flatten(io_lib:format("~p", [T])),
  1380. fun() -> R = connection_to_atom(T) end} || {T, R} <- Tests].
  1381. merge_headers_test() ->
  1382. Left0 = [{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}],
  1383. Right0 = [{<<"set-cookie">>,<<"foo=bar">>},{<<"content-length">>,<<"11">>}],
  1384. ?assertMatch(
  1385. [{<<"set-cookie">>,<<"foo=bar">>},
  1386. {<<"content-length">>,<<"13">>},
  1387. {<<"server">>,<<"Cowboy">>}],
  1388. merge_headers(Left0, Right0)),
  1389. Left1 = [{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}],
  1390. Right1 = [{<<"set-cookie">>,<<"foo=bar">>},{<<"set-cookie">>,<<"bar=baz">>}],
  1391. ?assertMatch(
  1392. [{<<"set-cookie">>,<<"bar=baz">>},
  1393. {<<"set-cookie">>,<<"foo=bar">>},
  1394. {<<"content-length">>,<<"13">>},
  1395. {<<"server">>,<<"Cowboy">>}],
  1396. merge_headers(Left1, Right1)),
  1397. ok.
  1398. -endif.