cowboy_req.erl 46 KB

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