cowboy_req.erl 53 KB

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