cowboy_req.erl 54 KB

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