cowboy_req.erl 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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((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. 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(any(), 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. %% Flash player incorrectly sends an empty Cookie header.
  453. {error, badarg} ->
  454. {Default, Req#http_req{cookies=[]}}
  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(infinity, Req) ->
  667. case parse_header(<<"transfer-encoding">>, Req) of
  668. {ok, [<<"identity">>], Req2} ->
  669. read_body(Req2, <<>>);
  670. {ok, _, _} ->
  671. {error, chunked}
  672. end;
  673. body(MaxBodyLength, Req) ->
  674. case parse_header(<<"transfer-encoding">>, Req) of
  675. {ok, [<<"identity">>], Req2} ->
  676. {ok, Length, Req3} = parse_header(<<"content-length">>, Req2, 0),
  677. if Length > MaxBodyLength ->
  678. {error, badlength};
  679. true ->
  680. read_body(Req3, <<>>)
  681. end;
  682. {ok, _, _} ->
  683. {error, chunked}
  684. end.
  685. -spec read_body(Req, binary())
  686. -> {ok, binary(), Req} | {error, atom()} when Req::req().
  687. read_body(Req, Acc) ->
  688. case stream_body(Req) of
  689. {ok, Data, Req2} ->
  690. read_body(Req2, << Acc/binary, Data/binary >>);
  691. {done, Req2} ->
  692. {ok, Acc, Req2};
  693. {error, Reason} ->
  694. {error, Reason}
  695. end.
  696. -spec skip_body(Req) -> {ok, Req} | {error, atom()} when Req::req().
  697. skip_body(Req) ->
  698. case stream_body(Req) of
  699. {ok, _, Req2} -> skip_body(Req2);
  700. {done, Req2} -> {ok, Req2};
  701. {error, Reason} -> {error, Reason}
  702. end.
  703. %% @equiv body_qs(16000, Req)
  704. -spec body_qs(Req)
  705. -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
  706. when Req::req().
  707. body_qs(Req) ->
  708. body_qs(16000, Req).
  709. %% @doc Return the body sent with the request, parsed as an
  710. %% application/x-www-form-urlencoded string.
  711. %% Essentially a POST query string.
  712. -spec body_qs(non_neg_integer() | infinity, Req)
  713. -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
  714. when Req::req().
  715. body_qs(MaxBodyLength, Req) ->
  716. case body(MaxBodyLength, Req) of
  717. {ok, Body, Req2} ->
  718. {ok, cowboy_http:x_www_form_urlencoded(Body), Req2};
  719. {error, Reason} ->
  720. {error, Reason}
  721. end.
  722. %% Multipart Request API.
  723. %% @doc Return data from the multipart parser.
  724. %%
  725. %% Use this function for multipart streaming. For each part in the request,
  726. %% this function returns <em>{headers, Headers}</em> followed by a sequence of
  727. %% <em>{body, Data}</em> tuples and finally <em>end_of_part</em>. When there
  728. %% is no part to parse anymore, <em>eof</em> is returned.
  729. -spec multipart_data(Req)
  730. -> {headers, cowboy:http_headers(), Req} | {body, binary(), Req}
  731. | {end_of_part | eof, Req} when Req::req().
  732. multipart_data(Req=#http_req{body_state=waiting}) ->
  733. {ok, {<<"multipart">>, _SubType, Params}, Req2} =
  734. parse_header(<<"content-type">>, Req),
  735. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  736. {ok, Length, Req3} = parse_header(<<"content-length">>, Req2),
  737. multipart_data(Req3, Length, {more, cowboy_multipart:parser(Boundary)});
  738. multipart_data(Req=#http_req{multipart={Length, Cont}}) ->
  739. multipart_data(Req, Length, Cont());
  740. multipart_data(Req=#http_req{body_state=done}) ->
  741. {eof, Req}.
  742. multipart_data(Req, Length, {headers, Headers, Cont}) ->
  743. {headers, Headers, Req#http_req{multipart={Length, Cont}}};
  744. multipart_data(Req, Length, {body, Data, Cont}) ->
  745. {body, Data, Req#http_req{multipart={Length, Cont}}};
  746. multipart_data(Req, Length, {end_of_part, Cont}) ->
  747. {end_of_part, Req#http_req{multipart={Length, Cont}}};
  748. multipart_data(Req, 0, eof) ->
  749. {eof, Req#http_req{body_state=done, multipart=undefined}};
  750. multipart_data(Req=#http_req{socket=Socket, transport=Transport},
  751. Length, eof) ->
  752. %% We just want to skip so no need to stream data here.
  753. {ok, _Data} = Transport:recv(Socket, Length, 5000),
  754. {eof, Req#http_req{body_state=done, multipart=undefined}};
  755. multipart_data(Req, Length, {more, Parser}) when Length > 0 ->
  756. case stream_body(Req) of
  757. {ok, << Data:Length/binary, Buffer/binary >>, Req2} ->
  758. multipart_data(Req2#http_req{buffer=Buffer}, 0, Parser(Data));
  759. {ok, Data, Req2} ->
  760. multipart_data(Req2, Length - byte_size(Data), Parser(Data))
  761. end.
  762. %% @doc Skip a part returned by the multipart parser.
  763. %%
  764. %% This function repeatedly calls <em>multipart_data/1</em> until
  765. %% <em>end_of_part</em> or <em>eof</em> is parsed.
  766. -spec multipart_skip(Req) -> {ok, Req} when Req::req().
  767. multipart_skip(Req) ->
  768. case multipart_data(Req) of
  769. {end_of_part, Req2} -> {ok, Req2};
  770. {eof, Req2} -> {ok, Req2};
  771. {_, _, Req2} -> multipart_skip(Req2)
  772. end.
  773. %% Response API.
  774. %% @doc Add a cookie header to the response.
  775. %%
  776. %% The cookie name cannot contain any of the following characters:
  777. %% =,;\s\t\r\n\013\014
  778. %%
  779. %% The cookie value cannot contain any of the following characters:
  780. %% ,; \t\r\n\013\014
  781. -spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req)
  782. -> Req when Req::req().
  783. set_resp_cookie(Name, Value, Opts, Req) ->
  784. Cookie = cowboy_http:cookie_to_iodata(Name, Value, Opts),
  785. set_resp_header(<<"set-cookie">>, Cookie, Req).
  786. %% @doc Add a header to the response.
  787. -spec set_resp_header(binary(), iodata(), Req)
  788. -> Req when Req::req().
  789. set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
  790. Req#http_req{resp_headers=[{Name, Value}|RespHeaders]}.
  791. %% @doc Add a body to the response.
  792. %%
  793. %% The body set here is ignored if the response is later sent using
  794. %% anything other than reply/2 or reply/3. The response body is expected
  795. %% to be a binary or an iolist.
  796. -spec set_resp_body(iodata(), Req) -> Req when Req::req().
  797. set_resp_body(Body, Req) ->
  798. Req#http_req{resp_body=Body}.
  799. %% @doc Add a body stream function to the response.
  800. %%
  801. %% The body set here is ignored if the response is later sent using
  802. %% anything other than reply/2 or reply/3.
  803. %%
  804. %% Setting a response stream function without a length means that the
  805. %% body will be sent until the connection is closed. Cowboy will make
  806. %% sure that the connection is closed with no extra step required.
  807. %%
  808. %% To inform the client that a body has been sent with this request,
  809. %% Cowboy will add a "Transfer-Encoding: identity" header to the
  810. %% response.
  811. -spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req().
  812. set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) ->
  813. Req#http_req{resp_body=StreamFun}.
  814. %% @doc Add a body function to the response.
  815. %%
  816. %% The body set here is ignored if the response is later sent using
  817. %% anything other than reply/2 or reply/3.
  818. %%
  819. %% Cowboy will call the given response stream function after sending the
  820. %% headers. This function must send the specified number of bytes to the
  821. %% socket it will receive as argument.
  822. %%
  823. %% If the body function crashes while writing the response body or writes
  824. %% fewer bytes than declared the behaviour is undefined.
  825. -spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req)
  826. -> Req when Req::req();
  827. (chunked, resp_chunked_fun(), Req)
  828. -> Req when Req::req().
  829. set_resp_body_fun(StreamLen, StreamFun, Req)
  830. when is_integer(StreamLen), is_function(StreamFun) ->
  831. Req#http_req{resp_body={StreamLen, StreamFun}};
  832. set_resp_body_fun(chunked, StreamFun, Req)
  833. when is_function(StreamFun) ->
  834. Req#http_req{resp_body={chunked, StreamFun}}.
  835. %% @doc Return whether the given header has been set for the response.
  836. -spec has_resp_header(binary(), req()) -> boolean().
  837. has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
  838. lists:keymember(Name, 1, RespHeaders).
  839. %% @doc Return whether a body has been set for the response.
  840. -spec has_resp_body(req()) -> boolean().
  841. has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) ->
  842. true;
  843. has_resp_body(#http_req{resp_body={chunked, _}}) ->
  844. true;
  845. has_resp_body(#http_req{resp_body={Length, _}}) ->
  846. Length > 0;
  847. has_resp_body(#http_req{resp_body=RespBody}) ->
  848. iolist_size(RespBody) > 0.
  849. %% @doc Remove a header previously set for the response.
  850. -spec delete_resp_header(binary(), Req)
  851. -> Req when Req::req().
  852. delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) ->
  853. RespHeaders2 = lists:keydelete(Name, 1, RespHeaders),
  854. Req#http_req{resp_headers=RespHeaders2}.
  855. %% @equiv reply(Status, [], [], Req)
  856. -spec reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req().
  857. reply(Status, Req=#http_req{resp_body=Body}) ->
  858. reply(Status, [], Body, Req).
  859. %% @equiv reply(Status, Headers, [], Req)
  860. -spec reply(cowboy:http_status(), cowboy:http_headers(), Req)
  861. -> {ok, Req} when Req::req().
  862. reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
  863. reply(Status, Headers, Body, Req).
  864. %% @doc Send a reply to the client.
  865. -spec reply(cowboy:http_status(), cowboy:http_headers(),
  866. iodata() | {non_neg_integer() | resp_body_fun()}, Req)
  867. -> {ok, Req} when Req::req().
  868. reply(Status, Headers, Body, Req=#http_req{
  869. socket=Socket, transport=Transport,
  870. version=Version, connection=Connection,
  871. method=Method, resp_compress=Compress,
  872. resp_state=waiting, resp_headers=RespHeaders}) ->
  873. HTTP11Headers = if
  874. Transport =/= cowboy_spdy, Version =:= 'HTTP/1.1' ->
  875. [{<<"connection">>, atom_to_connection(Connection)}];
  876. true ->
  877. []
  878. end,
  879. Req3 = case Body of
  880. BodyFun when is_function(BodyFun) ->
  881. %% We stream the response body until we close the connection.
  882. RespConn = close,
  883. {RespType, Req2} = if
  884. Transport =:= cowboy_spdy ->
  885. response(Status, Headers, RespHeaders, [
  886. {<<"date">>, cowboy_clock:rfc1123()},
  887. {<<"server">>, <<"Cowboy">>}
  888. ], stream, Req);
  889. true ->
  890. response(Status, Headers, RespHeaders, [
  891. {<<"connection">>, <<"close">>},
  892. {<<"date">>, cowboy_clock:rfc1123()},
  893. {<<"server">>, <<"Cowboy">>},
  894. {<<"transfer-encoding">>, <<"identity">>}
  895. ], <<>>, Req)
  896. end,
  897. if RespType =/= hook, Method =/= <<"HEAD">> ->
  898. BodyFun(Socket, Transport);
  899. true -> ok
  900. end,
  901. Req2#http_req{connection=RespConn};
  902. {chunked, BodyFun} ->
  903. %% We stream the response body in chunks.
  904. {RespType, Req2} = chunked_response(Status, Headers, Req),
  905. if RespType =/= hook, Method =/= <<"HEAD">> ->
  906. ChunkFun = fun(IoData) -> chunk(IoData, Req2) end,
  907. BodyFun(ChunkFun),
  908. %% Terminate the chunked body for HTTP/1.1 only.
  909. case Version of
  910. 'HTTP/1.0' -> Req2;
  911. _ -> last_chunk(Req2)
  912. end;
  913. true -> Req2
  914. end;
  915. {ContentLength, BodyFun} ->
  916. %% We stream the response body for ContentLength bytes.
  917. RespConn = response_connection(Headers, Connection),
  918. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  919. {<<"content-length">>, integer_to_list(ContentLength)},
  920. {<<"date">>, cowboy_clock:rfc1123()},
  921. {<<"server">>, <<"Cowboy">>}
  922. |HTTP11Headers], stream, Req),
  923. if RespType =/= hook, Method =/= <<"HEAD">> ->
  924. BodyFun(Socket, Transport);
  925. true -> ok
  926. end,
  927. Req2#http_req{connection=RespConn};
  928. _ when Compress ->
  929. RespConn = response_connection(Headers, Connection),
  930. Req2 = reply_may_compress(Status, Headers, Body, Req,
  931. RespHeaders, HTTP11Headers, Method),
  932. Req2#http_req{connection=RespConn};
  933. _ ->
  934. RespConn = response_connection(Headers, Connection),
  935. Req2 = reply_no_compress(Status, Headers, Body, Req,
  936. RespHeaders, HTTP11Headers, Method, iolist_size(Body)),
  937. Req2#http_req{connection=RespConn}
  938. end,
  939. {ok, Req3#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  940. reply_may_compress(Status, Headers, Body, Req,
  941. RespHeaders, HTTP11Headers, Method) ->
  942. BodySize = iolist_size(Body),
  943. case parse_header(<<"accept-encoding">>, Req) of
  944. {ok, Encodings, Req2} ->
  945. CanGzip = (BodySize > 300)
  946. andalso (false =:= lists:keyfind(<<"content-encoding">>,
  947. 1, Headers))
  948. andalso (false =:= lists:keyfind(<<"content-encoding">>,
  949. 1, RespHeaders))
  950. andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  951. 1, Headers))
  952. andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  953. 1, RespHeaders))
  954. andalso (Encodings =/= undefined)
  955. andalso (false =/= lists:keyfind(<<"gzip">>, 1, Encodings)),
  956. case CanGzip of
  957. true ->
  958. GzBody = zlib:gzip(Body),
  959. {_, Req3} = response(Status, Headers, RespHeaders, [
  960. {<<"content-length">>, integer_to_list(byte_size(GzBody))},
  961. {<<"content-encoding">>, <<"gzip">>},
  962. {<<"date">>, cowboy_clock:rfc1123()},
  963. {<<"server">>, <<"Cowboy">>}
  964. |HTTP11Headers],
  965. case Method of <<"HEAD">> -> <<>>; _ -> GzBody end,
  966. Req2),
  967. Req3;
  968. false ->
  969. reply_no_compress(Status, Headers, Body, Req,
  970. RespHeaders, HTTP11Headers, Method, BodySize)
  971. end;
  972. {error, badarg} ->
  973. reply_no_compress(Status, Headers, Body, Req,
  974. RespHeaders, HTTP11Headers, Method, BodySize)
  975. end.
  976. reply_no_compress(Status, Headers, Body, Req,
  977. RespHeaders, HTTP11Headers, Method, BodySize) ->
  978. {_, Req2} = response(Status, Headers, RespHeaders, [
  979. {<<"content-length">>, integer_to_list(BodySize)},
  980. {<<"date">>, cowboy_clock:rfc1123()},
  981. {<<"server">>, <<"Cowboy">>}
  982. |HTTP11Headers],
  983. case Method of <<"HEAD">> -> <<>>; _ -> Body end,
  984. Req),
  985. Req2.
  986. %% @equiv chunked_reply(Status, [], Req)
  987. -spec chunked_reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req().
  988. chunked_reply(Status, Req) ->
  989. chunked_reply(Status, [], Req).
  990. %% @doc Initiate the sending of a chunked reply to the client.
  991. %% @see cowboy_req:chunk/2
  992. -spec chunked_reply(cowboy:http_status(), cowboy:http_headers(), Req)
  993. -> {ok, Req} when Req::req().
  994. chunked_reply(Status, Headers, Req) ->
  995. {_, Req2} = chunked_response(Status, Headers, Req),
  996. {ok, Req2}.
  997. %% @doc Send a chunk of data.
  998. %%
  999. %% A chunked reply must have been initiated before calling this function.
  1000. -spec chunk(iodata(), req()) -> ok | {error, atom()}.
  1001. chunk(_Data, #http_req{method= <<"HEAD">>}) ->
  1002. ok;
  1003. chunk(Data, #http_req{socket=Socket, transport=cowboy_spdy,
  1004. resp_state=chunks}) ->
  1005. cowboy_spdy:stream_data(Socket, Data);
  1006. chunk(Data, #http_req{socket=Socket, transport=Transport,
  1007. resp_state=chunks, version='HTTP/1.0'}) ->
  1008. Transport:send(Socket, Data);
  1009. chunk(Data, #http_req{socket=Socket, transport=Transport,
  1010. resp_state=chunks}) ->
  1011. Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
  1012. <<"\r\n">>, Data, <<"\r\n">>]).
  1013. %% @doc Finish the chunked reply.
  1014. %% @todo If ever made public, need to send nothing if HEAD.
  1015. -spec last_chunk(Req) -> Req when Req::req().
  1016. last_chunk(Req=#http_req{socket=Socket, transport=cowboy_spdy}) ->
  1017. _ = cowboy_spdy:stream_close(Socket),
  1018. Req#http_req{resp_state=done};
  1019. last_chunk(Req=#http_req{socket=Socket, transport=Transport}) ->
  1020. _ = Transport:send(Socket, <<"0\r\n\r\n">>),
  1021. Req#http_req{resp_state=done}.
  1022. %% @doc Send an upgrade reply.
  1023. %% @private
  1024. -spec upgrade_reply(cowboy:http_status(), cowboy:http_headers(), Req)
  1025. -> {ok, Req} when Req::req().
  1026. upgrade_reply(Status, Headers, Req=#http_req{transport=Transport,
  1027. resp_state=waiting, resp_headers=RespHeaders})
  1028. when Transport =/= cowboy_spdy ->
  1029. {_, Req2} = response(Status, Headers, RespHeaders, [
  1030. {<<"connection">>, <<"Upgrade">>}
  1031. ], <<>>, Req),
  1032. {ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  1033. %% @doc Ensure the response has been sent fully.
  1034. %% @private
  1035. -spec ensure_response(req(), cowboy:http_status()) -> ok.
  1036. %% The response has already been fully sent to the client.
  1037. ensure_response(#http_req{resp_state=done}, _) ->
  1038. ok;
  1039. %% No response has been sent but everything apparently went fine.
  1040. %% Reply with the status code found in the second argument.
  1041. ensure_response(Req=#http_req{resp_state=waiting}, Status) ->
  1042. _ = reply(Status, [], [], Req),
  1043. ok;
  1044. %% Terminate the chunked body for HTTP/1.1 only.
  1045. ensure_response(#http_req{method= <<"HEAD">>, resp_state=chunks}, _) ->
  1046. ok;
  1047. ensure_response(#http_req{version='HTTP/1.0', resp_state=chunks}, _) ->
  1048. ok;
  1049. ensure_response(Req=#http_req{resp_state=chunks}, _) ->
  1050. _ = last_chunk(Req),
  1051. ok.
  1052. %% Private setter/getter API.
  1053. %% @private
  1054. -spec append_buffer(binary(), Req) -> Req when Req::req().
  1055. append_buffer(Suffix, Req=#http_req{buffer=Buffer}) ->
  1056. Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}.
  1057. %% @private
  1058. -spec get(atom(), req()) -> any(); ([atom()], req()) -> any().
  1059. get(List, Req) when is_list(List) ->
  1060. [g(Atom, Req) || Atom <- List];
  1061. get(Atom, Req) when is_atom(Atom) ->
  1062. g(Atom, Req).
  1063. g(bindings, #http_req{bindings=Ret}) -> Ret;
  1064. g(body_state, #http_req{body_state=Ret}) -> Ret;
  1065. g(buffer, #http_req{buffer=Ret}) -> Ret;
  1066. g(connection, #http_req{connection=Ret}) -> Ret;
  1067. g(cookies, #http_req{cookies=Ret}) -> Ret;
  1068. g(headers, #http_req{headers=Ret}) -> Ret;
  1069. g(host, #http_req{host=Ret}) -> Ret;
  1070. g(host_info, #http_req{host_info=Ret}) -> Ret;
  1071. g(meta, #http_req{meta=Ret}) -> Ret;
  1072. g(method, #http_req{method=Ret}) -> Ret;
  1073. g(multipart, #http_req{multipart=Ret}) -> Ret;
  1074. g(onresponse, #http_req{onresponse=Ret}) -> Ret;
  1075. g(p_headers, #http_req{p_headers=Ret}) -> Ret;
  1076. g(path, #http_req{path=Ret}) -> Ret;
  1077. g(path_info, #http_req{path_info=Ret}) -> Ret;
  1078. g(peer, #http_req{peer=Ret}) -> Ret;
  1079. g(pid, #http_req{pid=Ret}) -> Ret;
  1080. g(port, #http_req{port=Ret}) -> Ret;
  1081. g(qs, #http_req{qs=Ret}) -> Ret;
  1082. g(qs_vals, #http_req{qs_vals=Ret}) -> Ret;
  1083. g(resp_body, #http_req{resp_body=Ret}) -> Ret;
  1084. g(resp_headers, #http_req{resp_headers=Ret}) -> Ret;
  1085. g(resp_state, #http_req{resp_state=Ret}) -> Ret;
  1086. g(socket, #http_req{socket=Ret}) -> Ret;
  1087. g(transport, #http_req{transport=Ret}) -> Ret;
  1088. g(version, #http_req{version=Ret}) -> Ret.
  1089. %% @private
  1090. -spec set([{atom(), any()}], Req) -> Req when Req::req().
  1091. set([], Req) -> Req;
  1092. set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val});
  1093. set([{body_state, Val}|Tail], Req) -> set(Tail, Req#http_req{body_state=Val});
  1094. set([{buffer, Val}|Tail], Req) -> set(Tail, Req#http_req{buffer=Val});
  1095. set([{connection, Val}|Tail], Req) -> set(Tail, Req#http_req{connection=Val});
  1096. set([{cookies, Val}|Tail], Req) -> set(Tail, Req#http_req{cookies=Val});
  1097. set([{headers, Val}|Tail], Req) -> set(Tail, Req#http_req{headers=Val});
  1098. set([{host, Val}|Tail], Req) -> set(Tail, Req#http_req{host=Val});
  1099. set([{host_info, Val}|Tail], Req) -> set(Tail, Req#http_req{host_info=Val});
  1100. set([{meta, Val}|Tail], Req) -> set(Tail, Req#http_req{meta=Val});
  1101. set([{method, Val}|Tail], Req) -> set(Tail, Req#http_req{method=Val});
  1102. set([{multipart, Val}|Tail], Req) -> set(Tail, Req#http_req{multipart=Val});
  1103. set([{onresponse, Val}|Tail], Req) -> set(Tail, Req#http_req{onresponse=Val});
  1104. set([{p_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{p_headers=Val});
  1105. set([{path, Val}|Tail], Req) -> set(Tail, Req#http_req{path=Val});
  1106. set([{path_info, Val}|Tail], Req) -> set(Tail, Req#http_req{path_info=Val});
  1107. set([{peer, Val}|Tail], Req) -> set(Tail, Req#http_req{peer=Val});
  1108. set([{pid, Val}|Tail], Req) -> set(Tail, Req#http_req{pid=Val});
  1109. set([{port, Val}|Tail], Req) -> set(Tail, Req#http_req{port=Val});
  1110. set([{qs, Val}|Tail], Req) -> set(Tail, Req#http_req{qs=Val});
  1111. set([{qs_vals, Val}|Tail], Req) -> set(Tail, Req#http_req{qs_vals=Val});
  1112. set([{resp_body, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_body=Val});
  1113. set([{resp_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_headers=Val});
  1114. set([{resp_state, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_state=Val});
  1115. set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val});
  1116. set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val});
  1117. set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}).
  1118. %% @private
  1119. -spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(),
  1120. cowboy_router:bindings(), Req) -> Req when Req::req().
  1121. set_bindings(HostInfo, PathInfo, Bindings, Req) ->
  1122. Req#http_req{host_info=HostInfo, path_info=PathInfo,
  1123. bindings=Bindings}.
  1124. %% Misc API.
  1125. %% @doc Compact the request data by removing all non-system information.
  1126. %%
  1127. %% This essentially removes the host and path info, query string, bindings,
  1128. %% headers and cookies.
  1129. %%
  1130. %% Use it when you really need to save up memory, for example when having
  1131. %% many concurrent long-running connections.
  1132. -spec compact(Req) -> Req when Req::req().
  1133. compact(Req) ->
  1134. Req#http_req{host_info=undefined,
  1135. path_info=undefined, qs_vals=undefined,
  1136. bindings=undefined, headers=[],
  1137. p_headers=[], cookies=[]}.
  1138. %% @doc Prevent any further responses.
  1139. %% @private
  1140. -spec lock(Req) -> Req when Req::req().
  1141. lock(Req) ->
  1142. Req#http_req{resp_state=locked}.
  1143. %% @doc Convert the Req object to a list of key/values.
  1144. -spec to_list(req()) -> [{atom(), any()}].
  1145. to_list(Req) ->
  1146. lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))).
  1147. %% Internal.
  1148. -spec chunked_response(cowboy:http_status(), cowboy:http_headers(), Req) ->
  1149. {normal | hook, Req} when Req::req().
  1150. chunked_response(Status, Headers, Req=#http_req{
  1151. transport=cowboy_spdy, resp_state=waiting,
  1152. resp_headers=RespHeaders}) ->
  1153. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  1154. {<<"date">>, cowboy_clock:rfc1123()},
  1155. {<<"server">>, <<"Cowboy">>}
  1156. ], stream, Req),
  1157. {RespType, Req2#http_req{resp_state=chunks,
  1158. resp_headers=[], resp_body= <<>>}};
  1159. chunked_response(Status, Headers, Req=#http_req{
  1160. version=Version, connection=Connection,
  1161. resp_state=waiting, resp_headers=RespHeaders}) ->
  1162. RespConn = response_connection(Headers, Connection),
  1163. HTTP11Headers = case Version of
  1164. 'HTTP/1.1' -> [
  1165. {<<"connection">>, atom_to_connection(Connection)},
  1166. {<<"transfer-encoding">>, <<"chunked">>}];
  1167. _ -> []
  1168. end,
  1169. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  1170. {<<"date">>, cowboy_clock:rfc1123()},
  1171. {<<"server">>, <<"Cowboy">>}
  1172. |HTTP11Headers], <<>>, Req),
  1173. {RespType, Req2#http_req{connection=RespConn, resp_state=chunks,
  1174. resp_headers=[], resp_body= <<>>}}.
  1175. -spec response(cowboy:http_status(), cowboy:http_headers(),
  1176. cowboy:http_headers(), cowboy:http_headers(), stream | iodata(), Req)
  1177. -> {normal | hook, Req} when Req::req().
  1178. response(Status, Headers, RespHeaders, DefaultHeaders, Body, Req=#http_req{
  1179. socket=Socket, transport=Transport, version=Version,
  1180. pid=ReqPid, onresponse=OnResponse}) ->
  1181. FullHeaders = case OnResponse of
  1182. already_called -> Headers;
  1183. _ -> response_merge_headers(Headers, RespHeaders, DefaultHeaders)
  1184. end,
  1185. Body2 = case Body of stream -> <<>>; _ -> Body end,
  1186. Req2 = case OnResponse of
  1187. already_called -> Req;
  1188. undefined -> Req;
  1189. OnResponse ->
  1190. OnResponse(Status, FullHeaders, Body2,
  1191. %% Don't call 'onresponse' from the hook itself.
  1192. Req#http_req{resp_headers=[], resp_body= <<>>,
  1193. onresponse=already_called})
  1194. end,
  1195. ReplyType = case Req2#http_req.resp_state of
  1196. waiting when Transport =:= cowboy_spdy, Body =:= stream ->
  1197. cowboy_spdy:stream_reply(Socket, status(Status), FullHeaders),
  1198. ReqPid ! {?MODULE, resp_sent},
  1199. normal;
  1200. waiting when Transport =:= cowboy_spdy ->
  1201. cowboy_spdy:reply(Socket, status(Status), FullHeaders, Body),
  1202. ReqPid ! {?MODULE, resp_sent},
  1203. normal;
  1204. waiting ->
  1205. HTTPVer = atom_to_binary(Version, latin1),
  1206. StatusLine = << HTTPVer/binary, " ",
  1207. (status(Status))/binary, "\r\n" >>,
  1208. HeaderLines = [[Key, <<": ">>, Value, <<"\r\n">>]
  1209. || {Key, Value} <- FullHeaders],
  1210. Transport:send(Socket, [StatusLine, HeaderLines, <<"\r\n">>, Body2]),
  1211. ReqPid ! {?MODULE, resp_sent},
  1212. normal;
  1213. _ ->
  1214. hook
  1215. end,
  1216. {ReplyType, Req2}.
  1217. -spec response_connection(cowboy:http_headers(), keepalive | close)
  1218. -> keepalive | close.
  1219. response_connection([], Connection) ->
  1220. Connection;
  1221. response_connection([{Name, Value}|Tail], Connection) ->
  1222. case Name of
  1223. <<"connection">> ->
  1224. Tokens = parse_connection_before(Value, []),
  1225. connection_to_atom(Tokens);
  1226. _ ->
  1227. response_connection(Tail, Connection)
  1228. end.
  1229. -spec response_merge_headers(cowboy:http_headers(), cowboy:http_headers(),
  1230. cowboy:http_headers()) -> cowboy:http_headers().
  1231. response_merge_headers(Headers, RespHeaders, DefaultHeaders) ->
  1232. Headers2 = [{Key, Value} || {Key, Value} <- Headers],
  1233. merge_headers(
  1234. merge_headers(Headers2, RespHeaders),
  1235. DefaultHeaders).
  1236. -spec merge_headers(cowboy:http_headers(), cowboy:http_headers())
  1237. -> cowboy:http_headers().
  1238. %% Merge headers by prepending the tuples in the second list to the
  1239. %% first list. It also handles Set-Cookie properly, which supports
  1240. %% duplicated entries. Notice that, while the RFC2109 does allow more
  1241. %% than one cookie to be set per Set-Cookie header, we are following
  1242. %% the implementation of common web servers and applications which
  1243. %% return many distinct headers per each Set-Cookie entry to avoid
  1244. %% issues with clients/browser which may not support it.
  1245. merge_headers(Headers, []) ->
  1246. Headers;
  1247. merge_headers(Headers, [{<<"set-cookie">>, Value}|Tail]) ->
  1248. merge_headers([{<<"set-cookie">>, Value}|Headers], Tail);
  1249. merge_headers(Headers, [{Name, Value}|Tail]) ->
  1250. Headers2 = case lists:keymember(Name, 1, Headers) of
  1251. true -> Headers;
  1252. false -> [{Name, Value}|Headers]
  1253. end,
  1254. merge_headers(Headers2, Tail).
  1255. -spec atom_to_connection(keepalive) -> <<_:80>>;
  1256. (close) -> <<_:40>>.
  1257. atom_to_connection(keepalive) ->
  1258. <<"keep-alive">>;
  1259. atom_to_connection(close) ->
  1260. <<"close">>.
  1261. %% Optimized parsing functions for the Connection header.
  1262. parse_connection_before(<<>>, Acc) ->
  1263. lists:reverse(Acc);
  1264. parse_connection_before(<< C, Rest/bits >>, Acc)
  1265. when C =:= $,; C =:= $\s; C =:= $\t ->
  1266. parse_connection_before(Rest, Acc);
  1267. parse_connection_before(Buffer, Acc) ->
  1268. parse_connection(Buffer, Acc, <<>>).
  1269. %% An evil block of code appeared!
  1270. parse_connection(<<>>, Acc, <<>>) ->
  1271. lists:reverse(Acc);
  1272. parse_connection(<<>>, Acc, Token) ->
  1273. lists:reverse([Token|Acc]);
  1274. parse_connection(<< C, Rest/bits >>, Acc, Token)
  1275. when C =:= $,; C =:= $\s; C =:= $\t ->
  1276. parse_connection_before(Rest, [Token|Acc]);
  1277. parse_connection(<< C, Rest/bits >>, Acc, Token) ->
  1278. case C of
  1279. $A -> parse_connection(Rest, Acc, << Token/binary, $a >>);
  1280. $B -> parse_connection(Rest, Acc, << Token/binary, $b >>);
  1281. $C -> parse_connection(Rest, Acc, << Token/binary, $c >>);
  1282. $D -> parse_connection(Rest, Acc, << Token/binary, $d >>);
  1283. $E -> parse_connection(Rest, Acc, << Token/binary, $e >>);
  1284. $F -> parse_connection(Rest, Acc, << Token/binary, $f >>);
  1285. $G -> parse_connection(Rest, Acc, << Token/binary, $g >>);
  1286. $H -> parse_connection(Rest, Acc, << Token/binary, $h >>);
  1287. $I -> parse_connection(Rest, Acc, << Token/binary, $i >>);
  1288. $J -> parse_connection(Rest, Acc, << Token/binary, $j >>);
  1289. $K -> parse_connection(Rest, Acc, << Token/binary, $k >>);
  1290. $L -> parse_connection(Rest, Acc, << Token/binary, $l >>);
  1291. $M -> parse_connection(Rest, Acc, << Token/binary, $m >>);
  1292. $N -> parse_connection(Rest, Acc, << Token/binary, $n >>);
  1293. $O -> parse_connection(Rest, Acc, << Token/binary, $o >>);
  1294. $P -> parse_connection(Rest, Acc, << Token/binary, $p >>);
  1295. $Q -> parse_connection(Rest, Acc, << Token/binary, $q >>);
  1296. $R -> parse_connection(Rest, Acc, << Token/binary, $r >>);
  1297. $S -> parse_connection(Rest, Acc, << Token/binary, $s >>);
  1298. $T -> parse_connection(Rest, Acc, << Token/binary, $t >>);
  1299. $U -> parse_connection(Rest, Acc, << Token/binary, $u >>);
  1300. $V -> parse_connection(Rest, Acc, << Token/binary, $v >>);
  1301. $W -> parse_connection(Rest, Acc, << Token/binary, $w >>);
  1302. $X -> parse_connection(Rest, Acc, << Token/binary, $x >>);
  1303. $Y -> parse_connection(Rest, Acc, << Token/binary, $y >>);
  1304. $Z -> parse_connection(Rest, Acc, << Token/binary, $z >>);
  1305. C -> parse_connection(Rest, Acc, << Token/binary, C >>)
  1306. end.
  1307. %% @doc Walk through a tokens list and return whether
  1308. %% the connection is keepalive or closed.
  1309. %%
  1310. %% We don't match on "keep-alive" since it is the default value.
  1311. -spec connection_to_atom([binary()]) -> keepalive | close.
  1312. connection_to_atom([]) ->
  1313. keepalive;
  1314. connection_to_atom([<<"close">>|_]) ->
  1315. close;
  1316. connection_to_atom([_|Tail]) ->
  1317. connection_to_atom(Tail).
  1318. -spec status(cowboy:http_status()) -> binary().
  1319. status(100) -> <<"100 Continue">>;
  1320. status(101) -> <<"101 Switching Protocols">>;
  1321. status(102) -> <<"102 Processing">>;
  1322. status(200) -> <<"200 OK">>;
  1323. status(201) -> <<"201 Created">>;
  1324. status(202) -> <<"202 Accepted">>;
  1325. status(203) -> <<"203 Non-Authoritative Information">>;
  1326. status(204) -> <<"204 No Content">>;
  1327. status(205) -> <<"205 Reset Content">>;
  1328. status(206) -> <<"206 Partial Content">>;
  1329. status(207) -> <<"207 Multi-Status">>;
  1330. status(226) -> <<"226 IM Used">>;
  1331. status(300) -> <<"300 Multiple Choices">>;
  1332. status(301) -> <<"301 Moved Permanently">>;
  1333. status(302) -> <<"302 Found">>;
  1334. status(303) -> <<"303 See Other">>;
  1335. status(304) -> <<"304 Not Modified">>;
  1336. status(305) -> <<"305 Use Proxy">>;
  1337. status(306) -> <<"306 Switch Proxy">>;
  1338. status(307) -> <<"307 Temporary Redirect">>;
  1339. status(400) -> <<"400 Bad Request">>;
  1340. status(401) -> <<"401 Unauthorized">>;
  1341. status(402) -> <<"402 Payment Required">>;
  1342. status(403) -> <<"403 Forbidden">>;
  1343. status(404) -> <<"404 Not Found">>;
  1344. status(405) -> <<"405 Method Not Allowed">>;
  1345. status(406) -> <<"406 Not Acceptable">>;
  1346. status(407) -> <<"407 Proxy Authentication Required">>;
  1347. status(408) -> <<"408 Request Timeout">>;
  1348. status(409) -> <<"409 Conflict">>;
  1349. status(410) -> <<"410 Gone">>;
  1350. status(411) -> <<"411 Length Required">>;
  1351. status(412) -> <<"412 Precondition Failed">>;
  1352. status(413) -> <<"413 Request Entity Too Large">>;
  1353. status(414) -> <<"414 Request-URI Too Long">>;
  1354. status(415) -> <<"415 Unsupported Media Type">>;
  1355. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  1356. status(417) -> <<"417 Expectation Failed">>;
  1357. status(418) -> <<"418 I'm a teapot">>;
  1358. status(422) -> <<"422 Unprocessable Entity">>;
  1359. status(423) -> <<"423 Locked">>;
  1360. status(424) -> <<"424 Failed Dependency">>;
  1361. status(425) -> <<"425 Unordered Collection">>;
  1362. status(426) -> <<"426 Upgrade Required">>;
  1363. status(428) -> <<"428 Precondition Required">>;
  1364. status(429) -> <<"429 Too Many Requests">>;
  1365. status(431) -> <<"431 Request Header Fields Too Large">>;
  1366. status(500) -> <<"500 Internal Server Error">>;
  1367. status(501) -> <<"501 Not Implemented">>;
  1368. status(502) -> <<"502 Bad Gateway">>;
  1369. status(503) -> <<"503 Service Unavailable">>;
  1370. status(504) -> <<"504 Gateway Timeout">>;
  1371. status(505) -> <<"505 HTTP Version Not Supported">>;
  1372. status(506) -> <<"506 Variant Also Negotiates">>;
  1373. status(507) -> <<"507 Insufficient Storage">>;
  1374. status(510) -> <<"510 Not Extended">>;
  1375. status(511) -> <<"511 Network Authentication Required">>;
  1376. status(B) when is_binary(B) -> B.
  1377. %% Tests.
  1378. -ifdef(TEST).
  1379. url_test() ->
  1380. {undefined, _} =
  1381. url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined,
  1382. path= <<>>, qs= <<>>, pid=self()}),
  1383. {<<"http://localhost/path">>, _ } =
  1384. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=80,
  1385. path= <<"/path">>, qs= <<>>, pid=self()}),
  1386. {<<"http://localhost:443/path">>, _} =
  1387. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=443,
  1388. path= <<"/path">>, qs= <<>>, pid=self()}),
  1389. {<<"http://localhost:8080/path">>, _} =
  1390. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1391. path= <<"/path">>, qs= <<>>, pid=self()}),
  1392. {<<"http://localhost:8080/path?dummy=2785">>, _} =
  1393. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1394. path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}),
  1395. {<<"https://localhost/path">>, _} =
  1396. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=443,
  1397. path= <<"/path">>, qs= <<>>, pid=self()}),
  1398. {<<"https://localhost:8443/path">>, _} =
  1399. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1400. path= <<"/path">>, qs= <<>>, pid=self()}),
  1401. {<<"https://localhost:8443/path?dummy=2785">>, _} =
  1402. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1403. path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}),
  1404. ok.
  1405. parse_connection_test_() ->
  1406. %% {Binary, Result}
  1407. Tests = [
  1408. {<<"close">>, [<<"close">>]},
  1409. {<<"ClOsE">>, [<<"close">>]},
  1410. {<<"Keep-Alive">>, [<<"keep-alive">>]},
  1411. {<<"keep-alive, Upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
  1412. ],
  1413. [{B, fun() -> R = parse_connection_before(B, []) end}
  1414. || {B, R} <- Tests].
  1415. connection_to_atom_test_() ->
  1416. %% {Tokens, Result}
  1417. Tests = [
  1418. {[<<"close">>], close},
  1419. {[<<"keep-alive">>], keepalive},
  1420. {[<<"keep-alive">>, <<"upgrade">>], keepalive}
  1421. ],
  1422. [{lists:flatten(io_lib:format("~p", [T])),
  1423. fun() -> R = connection_to_atom(T) end} || {T, R} <- Tests].
  1424. merge_headers_test_() ->
  1425. Tests = [
  1426. {[{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}],
  1427. [{<<"set-cookie">>,<<"foo=bar">>},{<<"content-length">>,<<"11">>}],
  1428. [{<<"set-cookie">>,<<"foo=bar">>},
  1429. {<<"content-length">>,<<"13">>},
  1430. {<<"server">>,<<"Cowboy">>}]},
  1431. {[{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}],
  1432. [{<<"set-cookie">>,<<"foo=bar">>},{<<"set-cookie">>,<<"bar=baz">>}],
  1433. [{<<"set-cookie">>,<<"bar=baz">>},
  1434. {<<"set-cookie">>,<<"foo=bar">>},
  1435. {<<"content-length">>,<<"13">>},
  1436. {<<"server">>,<<"Cowboy">>}]}
  1437. ],
  1438. [fun() -> Res = merge_headers(L,R) end || {L, R, Res} <- Tests].
  1439. -endif.