cowboy_req.erl 54 KB

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