cowboy_req.erl 57 KB

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