cowboy_req.erl 54 KB

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