cowboy_req.erl 49 KB

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