cowboy_req.erl 54 KB

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