cowboy_req.erl 44 KB

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