cowboy_req.erl 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. %% Copyright (c) 2011-2014, 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. -module(cowboy_req).
  16. %% Request API.
  17. -export([new/14]).
  18. -export([method/1]).
  19. -export([version/1]).
  20. -export([peer/1]).
  21. -export([host/1]).
  22. -export([host_info/1]).
  23. -export([port/1]).
  24. -export([path/1]).
  25. -export([path_info/1]).
  26. -export([qs/1]).
  27. -export([qs_val/2]).
  28. -export([qs_val/3]).
  29. -export([qs_vals/1]).
  30. -export([host_url/1]).
  31. -export([url/1]).
  32. -export([binding/2]).
  33. -export([binding/3]).
  34. -export([bindings/1]).
  35. -export([header/2]).
  36. -export([header/3]).
  37. -export([headers/1]).
  38. -export([parse_header/2]).
  39. -export([parse_header/3]).
  40. -export([cookie/2]).
  41. -export([cookie/3]).
  42. -export([cookies/1]).
  43. -export([meta/2]).
  44. -export([meta/3]).
  45. -export([set_meta/3]).
  46. %% Request body API.
  47. -export([has_body/1]).
  48. -export([body_length/1]).
  49. -export([body/1]).
  50. -export([body/2]).
  51. -export([body_qs/1]).
  52. -export([body_qs/2]).
  53. %% Multipart API.
  54. -export([part/1]).
  55. -export([part_body/1]).
  56. -export([part_body/2]).
  57. %% Response API.
  58. -export([set_resp_cookie/4]).
  59. -export([set_resp_header/3]).
  60. -export([set_resp_body/2]).
  61. -export([set_resp_body_fun/2]).
  62. -export([set_resp_body_fun/3]).
  63. -export([has_resp_header/2]).
  64. -export([has_resp_body/1]).
  65. -export([delete_resp_header/2]).
  66. -export([reply/2]).
  67. -export([reply/3]).
  68. -export([reply/4]).
  69. -export([chunked_reply/2]).
  70. -export([chunked_reply/3]).
  71. -export([chunk/2]).
  72. -export([upgrade_reply/3]).
  73. -export([continue/1]).
  74. -export([maybe_reply/2]).
  75. -export([ensure_response/2]).
  76. %% Private setter/getter API.
  77. -export([append_buffer/2]).
  78. -export([get/2]).
  79. -export([set/2]).
  80. -export([set_bindings/4]).
  81. %% Misc API.
  82. -export([compact/1]).
  83. -export([lock/1]).
  84. -export([to_list/1]).
  85. %% Deprecated API.
  86. -export([init_stream/4]).
  87. -deprecated({init_stream, 4}).
  88. -export([stream_body/1]).
  89. -deprecated({stream_body, 1}).
  90. -export([stream_body/2]).
  91. -deprecated({stream_body, 2}).
  92. -export([skip_body/1]).
  93. -deprecated({skip_body, 1}).
  94. -type cookie_opts() :: cow_cookie:cookie_opts().
  95. -export_type([cookie_opts/0]).
  96. -type content_decode_fun() :: fun((binary())
  97. -> {ok, binary()}
  98. | {error, atom()}).
  99. -type transfer_decode_fun() :: fun((binary(), any())
  100. -> cow_http_te:decode_ret()).
  101. -type body_opts() :: [{continue, boolean()}
  102. | {length, non_neg_integer()}
  103. | {read_length, non_neg_integer()}
  104. | {read_timeout, timeout()}
  105. | {transfer_decode, transfer_decode_fun(), any()}
  106. | {content_decode, content_decode_fun()}].
  107. -export_type([body_opts/0]).
  108. -type resp_body_fun() :: fun((any(), module()) -> ok).
  109. -type send_chunk_fun() :: fun((iodata()) -> ok | {error, atom()}).
  110. -type resp_chunked_fun() :: fun((send_chunk_fun()) -> ok).
  111. -record(http_req, {
  112. %% Transport.
  113. socket = undefined :: any(),
  114. transport = undefined :: undefined | module(),
  115. connection = keepalive :: keepalive | close,
  116. %% Request.
  117. pid = undefined :: pid(),
  118. method = <<"GET">> :: binary(),
  119. version = 'HTTP/1.1' :: cowboy:http_version(),
  120. peer = undefined :: undefined | {inet:ip_address(), inet:port_number()},
  121. host = undefined :: undefined | binary(),
  122. host_info = undefined :: undefined | cowboy_router:tokens(),
  123. port = undefined :: undefined | inet:port_number(),
  124. path = undefined :: binary(),
  125. path_info = undefined :: undefined | cowboy_router:tokens(),
  126. qs = undefined :: binary(),
  127. qs_vals = undefined :: undefined | list({binary(), binary() | true}),
  128. bindings = undefined :: undefined | cowboy_router:bindings(),
  129. headers = [] :: cowboy:http_headers(),
  130. p_headers = [] :: [any()], %% @todo Improve those specs.
  131. cookies = undefined :: undefined | [{binary(), binary()}],
  132. meta = [] :: [{atom(), any()}],
  133. %% Request body.
  134. body_state = waiting :: waiting | done | {stream, non_neg_integer(),
  135. transfer_decode_fun(), any(), content_decode_fun()},
  136. buffer = <<>> :: binary(),
  137. multipart = undefined :: undefined | {binary(), binary()},
  138. %% Response.
  139. resp_compress = false :: boolean(),
  140. resp_state = waiting :: locked | waiting | waiting_stream
  141. | chunks | stream | done,
  142. resp_headers = [] :: cowboy:http_headers(),
  143. resp_body = <<>> :: iodata() | resp_body_fun()
  144. | {non_neg_integer(), resp_body_fun()}
  145. | {chunked, resp_chunked_fun()},
  146. %% Functions.
  147. onresponse = undefined :: undefined | already_called
  148. | cowboy:onresponse_fun()
  149. }).
  150. -opaque req() :: #http_req{}.
  151. -export_type([req/0]).
  152. %% Request API.
  153. -spec new(any(), module(),
  154. undefined | {inet:ip_address(), inet:port_number()},
  155. binary(), binary(), binary(),
  156. cowboy:http_version(), cowboy:http_headers(), binary(),
  157. inet:port_number() | undefined, binary(), boolean(), boolean(),
  158. undefined | cowboy:onresponse_fun())
  159. -> req().
  160. new(Socket, Transport, Peer, Method, Path, Query,
  161. Version, Headers, Host, Port, Buffer, CanKeepalive,
  162. Compress, OnResponse) ->
  163. Req = #http_req{socket=Socket, transport=Transport, pid=self(), peer=Peer,
  164. method=Method, path=Path, qs=Query, version=Version,
  165. headers=Headers, host=Host, port=Port, buffer=Buffer,
  166. resp_compress=Compress, onresponse=OnResponse},
  167. case CanKeepalive and (Version =:= 'HTTP/1.1') of
  168. false ->
  169. Req#http_req{connection=close};
  170. true ->
  171. case lists:keyfind(<<"connection">>, 1, Headers) of
  172. false ->
  173. Req; %% keepalive
  174. {_, ConnectionHeader} ->
  175. Tokens = cow_http_hd:parse_connection(ConnectionHeader),
  176. Connection = connection_to_atom(Tokens),
  177. Req#http_req{connection=Connection,
  178. p_headers=[{<<"connection">>, Tokens}]}
  179. end
  180. end.
  181. -spec method(Req) -> {binary(), Req} when Req::req().
  182. method(Req) ->
  183. {Req#http_req.method, Req}.
  184. -spec version(Req) -> {cowboy:http_version(), Req} when Req::req().
  185. version(Req) ->
  186. {Req#http_req.version, Req}.
  187. -spec peer(Req)
  188. -> {{inet:ip_address(), inet:port_number()}, Req}
  189. when Req::req().
  190. peer(Req) ->
  191. {Req#http_req.peer, Req}.
  192. -spec host(Req) -> {binary(), Req} when Req::req().
  193. host(Req) ->
  194. {Req#http_req.host, Req}.
  195. -spec host_info(Req)
  196. -> {cowboy_router:tokens() | undefined, Req} when Req::req().
  197. host_info(Req) ->
  198. {Req#http_req.host_info, Req}.
  199. -spec port(Req) -> {inet:port_number(), Req} when Req::req().
  200. port(Req) ->
  201. {Req#http_req.port, Req}.
  202. -spec path(Req) -> {binary(), Req} when Req::req().
  203. path(Req) ->
  204. {Req#http_req.path, Req}.
  205. -spec path_info(Req)
  206. -> {cowboy_router:tokens() | undefined, Req} when Req::req().
  207. path_info(Req) ->
  208. {Req#http_req.path_info, Req}.
  209. -spec qs(Req) -> {binary(), Req} when Req::req().
  210. qs(Req) ->
  211. {Req#http_req.qs, Req}.
  212. -spec qs_val(binary(), Req)
  213. -> {binary() | true | undefined, Req} when Req::req().
  214. qs_val(Name, Req) when is_binary(Name) ->
  215. qs_val(Name, Req, undefined).
  216. -spec qs_val(binary(), Req, Default)
  217. -> {binary() | true | Default, Req} when Req::req(), Default::any().
  218. qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default)
  219. when is_binary(Name) ->
  220. QsVals = cow_qs:parse_qs(RawQs),
  221. qs_val(Name, Req#http_req{qs_vals=QsVals}, Default);
  222. qs_val(Name, Req, Default) ->
  223. case lists:keyfind(Name, 1, Req#http_req.qs_vals) of
  224. {Name, Value} -> {Value, Req};
  225. false -> {Default, Req}
  226. end.
  227. -spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
  228. qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) ->
  229. QsVals = cow_qs:parse_qs(RawQs),
  230. qs_vals(Req#http_req{qs_vals=QsVals});
  231. qs_vals(Req=#http_req{qs_vals=QsVals}) ->
  232. {QsVals, Req}.
  233. %% The URL includes the scheme, host and port only.
  234. -spec host_url(Req) -> {undefined | binary(), Req} when Req::req().
  235. host_url(Req=#http_req{port=undefined}) ->
  236. {undefined, Req};
  237. host_url(Req=#http_req{transport=Transport, host=Host, port=Port}) ->
  238. TransportName = Transport:name(),
  239. Secure = case TransportName of
  240. ssl -> <<"s">>;
  241. _ -> <<>>
  242. end,
  243. PortBin = case {TransportName, Port} of
  244. {ssl, 443} -> <<>>;
  245. {tcp, 80} -> <<>>;
  246. _ -> << ":", (list_to_binary(integer_to_list(Port)))/binary >>
  247. end,
  248. {<< "http", Secure/binary, "://", Host/binary, PortBin/binary >>, Req}.
  249. %% The URL includes the scheme, host, port, path and query string.
  250. -spec url(Req) -> {undefined | binary(), Req} when Req::req().
  251. url(Req=#http_req{}) ->
  252. {HostURL, Req2} = host_url(Req),
  253. url(HostURL, Req2).
  254. url(undefined, Req=#http_req{}) ->
  255. {undefined, Req};
  256. url(HostURL, Req=#http_req{path=Path, qs=QS}) ->
  257. QS2 = case QS of
  258. <<>> -> <<>>;
  259. _ -> << "?", QS/binary >>
  260. end,
  261. {<< HostURL/binary, Path/binary, QS2/binary >>, Req}.
  262. -spec binding(atom(), Req) -> {any() | undefined, Req} when Req::req().
  263. binding(Name, Req) when is_atom(Name) ->
  264. binding(Name, Req, undefined).
  265. -spec binding(atom(), Req, Default)
  266. -> {any() | Default, Req} when Req::req(), Default::any().
  267. binding(Name, Req, Default) when is_atom(Name) ->
  268. case lists:keyfind(Name, 1, Req#http_req.bindings) of
  269. {Name, Value} -> {Value, Req};
  270. false -> {Default, Req}
  271. end.
  272. -spec bindings(Req) -> {[{atom(), any()}], Req} when Req::req().
  273. bindings(Req) ->
  274. {Req#http_req.bindings, Req}.
  275. -spec header(binary(), Req)
  276. -> {binary() | undefined, Req} when Req::req().
  277. header(Name, Req) ->
  278. header(Name, Req, undefined).
  279. -spec header(binary(), Req, Default)
  280. -> {binary() | Default, Req} when Req::req(), Default::any().
  281. header(Name, Req, Default) ->
  282. case lists:keyfind(Name, 1, Req#http_req.headers) of
  283. {Name, Value} -> {Value, Req};
  284. false -> {Default, Req}
  285. end.
  286. -spec headers(Req) -> {cowboy:http_headers(), Req} when Req::req().
  287. headers(Req) ->
  288. {Req#http_req.headers, Req}.
  289. -spec parse_header(binary(), Req)
  290. -> {ok, any(), Req} | {undefined, binary(), Req}
  291. | {error, badarg} when Req::req().
  292. parse_header(Name, Req=#http_req{p_headers=PHeaders}) ->
  293. case lists:keyfind(Name, 1, PHeaders) of
  294. false -> parse_header(Name, Req, parse_header_default(Name));
  295. {Name, Value} -> {ok, Value, Req}
  296. end.
  297. -spec parse_header_default(binary()) -> any().
  298. parse_header_default(<<"transfer-encoding">>) -> [<<"identity">>];
  299. parse_header_default(_Name) -> undefined.
  300. -spec parse_header(binary(), Req, any())
  301. -> {ok, any(), Req} | {undefined, binary(), Req}
  302. | {error, badarg} when Req::req().
  303. parse_header(Name = <<"accept">>, Req, Default) ->
  304. parse_header(Name, Req, Default,
  305. fun (Value) ->
  306. cowboy_http:list(Value, fun cowboy_http:media_range/2)
  307. end);
  308. parse_header(Name = <<"accept-charset">>, Req, Default) ->
  309. parse_header(Name, Req, Default,
  310. fun (Value) ->
  311. cowboy_http:nonempty_list(Value, fun cowboy_http:conneg/2)
  312. end);
  313. parse_header(Name = <<"accept-encoding">>, Req, Default) ->
  314. parse_header(Name, Req, Default,
  315. fun (Value) ->
  316. cowboy_http:list(Value, fun cowboy_http:conneg/2)
  317. end);
  318. parse_header(Name = <<"accept-language">>, Req, Default) ->
  319. parse_header(Name, Req, Default,
  320. fun (Value) ->
  321. cowboy_http:nonempty_list(Value, fun cowboy_http:language_range/2)
  322. end);
  323. parse_header(Name = <<"authorization">>, Req, Default) ->
  324. parse_header(Name, Req, Default,
  325. fun (Value) ->
  326. cowboy_http:token_ci(Value, fun cowboy_http:authorization/2)
  327. end);
  328. parse_header(Name = <<"content-length">>, Req, Default) ->
  329. parse_header(Name, Req, Default, fun cow_http_hd:parse_content_length/1);
  330. parse_header(Name = <<"content-type">>, Req, Default) ->
  331. parse_header(Name, Req, Default, fun cowboy_http:content_type/1);
  332. parse_header(Name = <<"cookie">>, Req, Default) ->
  333. parse_header(Name, Req, Default, fun cow_cookie:parse_cookie/1);
  334. parse_header(Name = <<"expect">>, Req, Default) ->
  335. parse_header(Name, Req, Default,
  336. fun (Value) ->
  337. cowboy_http:nonempty_list(Value, fun cowboy_http:expectation/2)
  338. end);
  339. parse_header(Name, Req, Default)
  340. when Name =:= <<"if-match">>;
  341. Name =:= <<"if-none-match">> ->
  342. parse_header(Name, Req, Default, fun cowboy_http:entity_tag_match/1);
  343. parse_header(Name, Req, Default)
  344. when Name =:= <<"if-modified-since">>;
  345. Name =:= <<"if-unmodified-since">> ->
  346. parse_header(Name, Req, Default, fun cowboy_http:http_date/1);
  347. parse_header(Name = <<"range">>, Req, Default) ->
  348. parse_header(Name, Req, Default, fun cowboy_http:range/1);
  349. parse_header(Name, Req, Default)
  350. when Name =:= <<"sec-websocket-protocol">>;
  351. Name =:= <<"x-forwarded-for">> ->
  352. parse_header(Name, Req, Default,
  353. fun (Value) ->
  354. cowboy_http:nonempty_list(Value, fun cowboy_http:token/2)
  355. end);
  356. parse_header(Name = <<"transfer-encoding">>, Req, Default) ->
  357. parse_header(Name, Req, Default, fun cow_http_hd:parse_transfer_encoding/1);
  358. %% @todo Product version.
  359. parse_header(Name = <<"upgrade">>, Req, Default) ->
  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 = <<"sec-websocket-extensions">>, Req, Default) ->
  365. parse_header(Name, Req, Default, fun cowboy_http:parameterized_tokens/1);
  366. parse_header(Name, Req, Default) ->
  367. {Value, Req2} = header(Name, Req, Default),
  368. {undefined, Value, Req2}.
  369. parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) ->
  370. case header(Name, Req) of
  371. {undefined, Req2} ->
  372. {ok, Default, Req2#http_req{p_headers=[{Name, Default}|PHeaders]}};
  373. {Value, Req2} ->
  374. case Fun(Value) of
  375. {error, badarg} ->
  376. {error, badarg};
  377. P ->
  378. {ok, P, Req2#http_req{p_headers=[{Name, P}|PHeaders]}}
  379. end
  380. end.
  381. -spec cookie(binary(), Req)
  382. -> {binary() | undefined, Req} when Req::req().
  383. cookie(Name, Req) when is_binary(Name) ->
  384. cookie(Name, Req, undefined).
  385. -spec cookie(binary(), Req, Default)
  386. -> {binary() | Default, Req} when Req::req(), Default::any().
  387. cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) ->
  388. case parse_header(<<"cookie">>, Req) of
  389. {ok, undefined, Req2} ->
  390. {Default, Req2#http_req{cookies=[]}};
  391. {ok, Cookies, Req2} ->
  392. cookie(Name, Req2#http_req{cookies=Cookies}, Default)
  393. end;
  394. cookie(Name, Req, Default) ->
  395. case lists:keyfind(Name, 1, Req#http_req.cookies) of
  396. {Name, Value} -> {Value, Req};
  397. false -> {Default, Req}
  398. end.
  399. -spec cookies(Req) -> {list({binary(), binary()}), Req} when Req::req().
  400. cookies(Req=#http_req{cookies=undefined}) ->
  401. case parse_header(<<"cookie">>, Req) of
  402. {ok, undefined, Req2} ->
  403. {[], Req2#http_req{cookies=[]}};
  404. {ok, Cookies, Req2} ->
  405. cookies(Req2#http_req{cookies=Cookies});
  406. %% Flash player incorrectly sends an empty Cookie header.
  407. {error, badarg} ->
  408. {[], Req#http_req{cookies=[]}}
  409. end;
  410. cookies(Req=#http_req{cookies=Cookies}) ->
  411. {Cookies, Req}.
  412. -spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req().
  413. meta(Name, Req) ->
  414. meta(Name, Req, undefined).
  415. -spec meta(atom(), Req, any()) -> {any(), Req} when Req::req().
  416. meta(Name, Req, Default) ->
  417. case lists:keyfind(Name, 1, Req#http_req.meta) of
  418. {Name, Value} -> {Value, Req};
  419. false -> {Default, Req}
  420. end.
  421. -spec set_meta(atom(), any(), Req) -> Req when Req::req().
  422. set_meta(Name, Value, Req=#http_req{meta=Meta}) ->
  423. Req#http_req{meta=lists:keystore(Name, 1, Meta, {Name, Value})}.
  424. %% Request Body API.
  425. -spec has_body(req()) -> boolean().
  426. has_body(Req) ->
  427. case lists:keyfind(<<"content-length">>, 1, Req#http_req.headers) of
  428. {_, <<"0">>} ->
  429. false;
  430. {_, _} ->
  431. true;
  432. _ ->
  433. lists:keymember(<<"transfer-encoding">>, 1, Req#http_req.headers)
  434. end.
  435. %% The length may not be known if Transfer-Encoding is not identity,
  436. %% and the body hasn't been read at the time of the call.
  437. -spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req().
  438. body_length(Req) ->
  439. case parse_header(<<"transfer-encoding">>, Req) of
  440. {ok, [<<"identity">>], Req2} ->
  441. {ok, Length, Req3} = parse_header(<<"content-length">>, Req2, 0),
  442. {Length, Req3};
  443. {ok, _, Req2} ->
  444. {undefined, Req2}
  445. end.
  446. -spec body(Req)
  447. -> {ok, binary(), Req} | {more, binary(), Req}
  448. | {error, atom()} when Req::req().
  449. body(Req) ->
  450. body(Req, []).
  451. -spec body(Req, body_opts())
  452. -> {ok, binary(), Req} | {more, binary(), Req}
  453. | {error, atom()} when Req::req().
  454. %% @todo This clause is kept for compatibility reasons, to be removed in 1.0.
  455. body(MaxBodyLength, Req) when is_integer(MaxBodyLength) ->
  456. body(Req, [{length, MaxBodyLength}]);
  457. body(Req=#http_req{body_state=waiting}, Opts) ->
  458. %% Send a 100 continue if needed (enabled by default).
  459. Req1 = case lists:keyfind(continue, 1, Opts) of
  460. {_, false} ->
  461. Req;
  462. _ ->
  463. {ok, ExpectHeader, Req0} = parse_header(<<"expect">>, Req),
  464. ok = case ExpectHeader of
  465. [<<"100-continue">>] -> continue(Req0);
  466. _ -> ok
  467. end,
  468. Req0
  469. end,
  470. %% Initialize body streaming state.
  471. CFun = case lists:keyfind(content_decode, 1, Opts) of
  472. false ->
  473. fun cowboy_http:ce_identity/1;
  474. {_, CFun0} ->
  475. CFun0
  476. end,
  477. case lists:keyfind(transfer_decode, 1, Opts) of
  478. false ->
  479. case parse_header(<<"transfer-encoding">>, Req1) of
  480. {ok, [<<"chunked">>], Req2} ->
  481. body(Req2#http_req{body_state={stream, 0,
  482. fun cow_http_te:stream_chunked/2, {0, 0}, CFun}}, Opts);
  483. {ok, [<<"identity">>], Req2} ->
  484. {Len, Req3} = body_length(Req2),
  485. case Len of
  486. 0 ->
  487. {ok, <<>>, Req3#http_req{body_state=done}};
  488. _ ->
  489. body(Req3#http_req{body_state={stream, Len,
  490. fun cow_http_te:stream_identity/2, {0, Len},
  491. CFun}}, Opts)
  492. end
  493. end;
  494. {_, TFun, TState} ->
  495. body(Req1#http_req{body_state={stream, 0,
  496. TFun, TState, CFun}}, Opts)
  497. end;
  498. body(Req=#http_req{body_state=done}, _) ->
  499. {ok, <<>>, Req};
  500. body(Req, Opts) ->
  501. ChunkLen = case lists:keyfind(length, 1, Opts) of
  502. false -> 8000000;
  503. {_, ChunkLen0} -> ChunkLen0
  504. end,
  505. ReadLen = case lists:keyfind(read_length, 1, Opts) of
  506. false -> 1000000;
  507. {_, ReadLen0} -> ReadLen0
  508. end,
  509. ReadTimeout = case lists:keyfind(read_timeout, 1, Opts) of
  510. false -> 15000;
  511. {_, ReadTimeout0} -> ReadTimeout0
  512. end,
  513. body_loop(Req, ReadTimeout, ReadLen, ChunkLen, <<>>).
  514. body_loop(Req=#http_req{buffer=Buffer, body_state={stream, Length, _, _, _}},
  515. ReadTimeout, ReadLength, ChunkLength, Acc) ->
  516. {Tag, Res, Req2} = case Buffer of
  517. <<>> ->
  518. body_recv(Req, ReadTimeout, min(Length, ReadLength));
  519. _ ->
  520. body_decode(Req, ReadTimeout)
  521. end,
  522. case {Tag, Res} of
  523. {ok, {ok, Data}} ->
  524. {ok, << Acc/binary, Data/binary >>, Req2};
  525. {more, {ok, Data}} ->
  526. Acc2 = << Acc/binary, Data/binary >>,
  527. case byte_size(Acc2) >= ChunkLength of
  528. true -> {more, Acc2, Req2};
  529. false -> body_loop(Req2, ReadTimeout, ReadLength, ChunkLength, Acc2)
  530. end;
  531. _ -> %% Error.
  532. Res
  533. end.
  534. body_recv(Req=#http_req{transport=Transport, socket=Socket, buffer=Buffer},
  535. ReadTimeout, ReadLength) ->
  536. case Transport:recv(Socket, ReadLength, ReadTimeout) of
  537. {ok, Data} ->
  538. body_decode(Req#http_req{buffer= << Buffer/binary, Data/binary >>},
  539. ReadTimeout);
  540. Error = {error, _} ->
  541. {error, Error, Req}
  542. end.
  543. %% Two decodings happen. First a decoding function is applied to the
  544. %% transferred data, and then another is applied to the actual content.
  545. %%
  546. %% Transfer encoding is generally used for chunked bodies. The decoding
  547. %% function uses a state to keep track of how much it has read, which is
  548. %% also initialized through this function.
  549. %%
  550. %% Content encoding is generally used for compression.
  551. %%
  552. %% @todo Handle chunked after-the-facts headers.
  553. %% @todo Depending on the length returned we might want to 0 or +5 it.
  554. body_decode(Req=#http_req{buffer=Data, body_state={stream, _,
  555. TDecode, TState, CDecode}}, ReadTimeout) ->
  556. case TDecode(Data, TState) of
  557. more ->
  558. body_recv(Req#http_req{body_state={stream, 0,
  559. TDecode, TState, CDecode}}, ReadTimeout, 0);
  560. {more, Data2, TState2} ->
  561. {more, CDecode(Data2), Req#http_req{body_state={stream, 0,
  562. TDecode, TState2, CDecode}, buffer= <<>>}};
  563. {more, Data2, Length, TState2} when is_integer(Length) ->
  564. {more, CDecode(Data2), Req#http_req{body_state={stream, Length,
  565. TDecode, TState2, CDecode}, buffer= <<>>}};
  566. {more, Data2, Rest, TState2} ->
  567. {more, CDecode(Data2), Req#http_req{body_state={stream, 0,
  568. TDecode, TState2, CDecode}, buffer=Rest}};
  569. {done, TotalLength, Rest} ->
  570. {ok, {ok, <<>>}, body_decode_end(Req, TotalLength, Rest)};
  571. {done, Data2, TotalLength, Rest} ->
  572. {ok, CDecode(Data2), body_decode_end(Req, TotalLength, Rest)}
  573. end.
  574. body_decode_end(Req=#http_req{headers=Headers, p_headers=PHeaders},
  575. TotalLength, Rest) ->
  576. Headers2 = lists:keystore(<<"content-length">>, 1, Headers,
  577. {<<"content-length">>, list_to_binary(integer_to_list(TotalLength))}),
  578. %% At this point we just assume TEs were all decoded.
  579. Headers3 = lists:keydelete(<<"transfer-encoding">>, 1, Headers2),
  580. PHeaders2 = lists:keystore(<<"content-length">>, 1, PHeaders,
  581. {<<"content-length">>, TotalLength}),
  582. PHeaders3 = lists:keydelete(<<"transfer-encoding">>, 1, PHeaders2),
  583. Req#http_req{buffer=Rest, body_state=done,
  584. headers=Headers3, p_headers=PHeaders3}.
  585. -spec body_qs(Req)
  586. -> {ok, [{binary(), binary() | true}], Req} | {error, atom()}
  587. when Req::req().
  588. body_qs(Req) ->
  589. body_qs(Req, [
  590. {length, 64000},
  591. {read_length, 64000},
  592. {read_timeout, 5000}]).
  593. -spec body_qs(Req, body_opts()) -> {ok, [{binary(), binary() | true}], Req}
  594. | {badlength, Req} | {error, atom()} when Req::req().
  595. %% @todo This clause is kept for compatibility reasons, to be removed in 1.0.
  596. body_qs(MaxBodyLength, Req) when is_integer(MaxBodyLength) ->
  597. body_qs(Req, [{length, MaxBodyLength}]);
  598. body_qs(Req, Opts) ->
  599. case body(Req, Opts) of
  600. {ok, Body, Req2} ->
  601. {ok, cow_qs:parse_qs(Body), Req2};
  602. {more, _, Req2} ->
  603. {badlength, Req2};
  604. {error, Reason} ->
  605. {error, Reason}
  606. end.
  607. %% Deprecated body API.
  608. %% @todo The following 4 functions will be removed in Cowboy 1.0.
  609. -spec init_stream(transfer_decode_fun(), any(), content_decode_fun(), Req)
  610. -> {ok, Req} when Req::req().
  611. init_stream(TransferDecode, TransferState, ContentDecode, Req) ->
  612. {ok, Req#http_req{body_state=
  613. {stream, 0, TransferDecode, TransferState, ContentDecode}}}.
  614. -spec stream_body(Req) -> {ok, binary(), Req}
  615. | {done, Req} | {error, atom()} when Req::req().
  616. stream_body(Req) ->
  617. stream_body(1000000, Req).
  618. -spec stream_body(non_neg_integer(), Req) -> {ok, binary(), Req}
  619. | {done, Req} | {error, atom()} when Req::req().
  620. stream_body(ChunkLength, Req) ->
  621. case body(Req, [{length, ChunkLength}]) of
  622. {ok, <<>>, Req2} ->
  623. {done, Req2};
  624. {ok, Data, Req2} ->
  625. {ok, Data, Req2};
  626. {more, Data, Req2} ->
  627. {ok, Data, Req2};
  628. Error = {error, _} ->
  629. Error
  630. end.
  631. -spec skip_body(Req) -> {ok, Req} | {error, atom()} when Req::req().
  632. skip_body(Req) ->
  633. case stream_body(Req) of
  634. {ok, _, Req2} -> skip_body(Req2);
  635. {done, Req2} -> {ok, Req2};
  636. {error, Reason} -> {error, Reason}
  637. end.
  638. %% Multipart API.
  639. -spec part(Req)
  640. -> {ok, cow_multipart:headers(), Req} | {done, Req}
  641. when Req::req().
  642. part(Req) ->
  643. part(Req, [
  644. {length, 64000},
  645. {read_length, 64000},
  646. {read_timeout, 5000}]).
  647. -spec part(Req, body_opts())
  648. -> {ok, cow_multipart:headers(), Req} | {done, Req}
  649. when Req::req().
  650. part(Req=#http_req{multipart=undefined}, Opts) ->
  651. part(init_multipart(Req), Opts);
  652. part(Req, Opts) ->
  653. {Data, Req2} = stream_multipart(Req, Opts),
  654. part(Data, Opts, Req2).
  655. part(Buffer, Opts, Req=#http_req{multipart={Boundary, _}}) ->
  656. case cow_multipart:parse_headers(Buffer, Boundary) of
  657. more ->
  658. {Data, Req2} = stream_multipart(Req, Opts),
  659. part(<< Buffer/binary, Data/binary >>, Opts, Req2);
  660. {more, Buffer2} ->
  661. {Data, Req2} = stream_multipart(Req, Opts),
  662. part(<< Buffer2/binary, Data/binary >>, Opts, Req2);
  663. {ok, Headers, Rest} ->
  664. {ok, Headers, Req#http_req{multipart={Boundary, Rest}}};
  665. %% Ignore epilogue.
  666. {done, _} ->
  667. {done, Req#http_req{multipart=undefined}}
  668. end.
  669. -spec part_body(Req)
  670. -> {ok, binary(), Req} | {more, binary(), Req}
  671. when Req::req().
  672. part_body(Req) ->
  673. part_body(Req, []).
  674. -spec part_body(Req, body_opts())
  675. -> {ok, binary(), Req} | {more, binary(), Req}
  676. when Req::req().
  677. part_body(Req=#http_req{multipart=undefined}, Opts) ->
  678. part_body(init_multipart(Req), Opts);
  679. part_body(Req, Opts) ->
  680. part_body(<<>>, Opts, Req, <<>>).
  681. part_body(Buffer, Opts, Req=#http_req{multipart={Boundary, _}}, Acc) ->
  682. ChunkLen = case lists:keyfind(length, 1, Opts) of
  683. false -> 8000000;
  684. {_, ChunkLen0} -> ChunkLen0
  685. end,
  686. case byte_size(Acc) > ChunkLen of
  687. true ->
  688. {more, Acc, Req#http_req{multipart={Boundary, Buffer}}};
  689. false ->
  690. {Data, Req2} = stream_multipart(Req, Opts),
  691. case cow_multipart:parse_body(<< Buffer/binary, Data/binary >>, Boundary) of
  692. {ok, Body} ->
  693. part_body(<<>>, Opts, Req2, << Acc/binary, Body/binary >>);
  694. {ok, Body, Rest} ->
  695. part_body(Rest, Opts, Req2, << Acc/binary, Body/binary >>);
  696. done ->
  697. {ok, Acc, Req2};
  698. {done, Body} ->
  699. {ok, << Acc/binary, Body/binary >>, Req2};
  700. {done, Body, Rest} ->
  701. {ok, << Acc/binary, Body/binary >>,
  702. Req2#http_req{multipart={Boundary, Rest}}}
  703. end
  704. end.
  705. init_multipart(Req) ->
  706. {ok, {<<"multipart">>, _, Params}, Req2}
  707. = parse_header(<<"content-type">>, Req),
  708. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  709. Req2#http_req{multipart={Boundary, <<>>}}.
  710. stream_multipart(Req=#http_req{body_state=BodyState, multipart={_, <<>>}}, Opts) ->
  711. true = BodyState =/= done,
  712. {_, Data, Req2} = body(Req, Opts),
  713. {Data, Req2};
  714. stream_multipart(Req=#http_req{multipart={Boundary, Buffer}}, _) ->
  715. {Buffer, Req#http_req{multipart={Boundary, <<>>}}}.
  716. %% Response API.
  717. %% The cookie name cannot contain any of the following characters:
  718. %% =,;\s\t\r\n\013\014
  719. %%
  720. %% The cookie value cannot contain any of the following characters:
  721. %% ,; \t\r\n\013\014
  722. -spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req)
  723. -> Req when Req::req().
  724. set_resp_cookie(Name, Value, Opts, Req) ->
  725. Cookie = cow_cookie:setcookie(Name, Value, Opts),
  726. set_resp_header(<<"set-cookie">>, Cookie, Req).
  727. -spec set_resp_header(binary(), iodata(), Req)
  728. -> Req when Req::req().
  729. set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
  730. Req#http_req{resp_headers=[{Name, Value}|RespHeaders]}.
  731. -spec set_resp_body(iodata(), Req) -> Req when Req::req().
  732. set_resp_body(Body, Req) ->
  733. Req#http_req{resp_body=Body}.
  734. -spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req().
  735. set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) ->
  736. Req#http_req{resp_body=StreamFun}.
  737. %% If the body function crashes while writing the response body or writes
  738. %% fewer bytes than declared the behaviour is undefined.
  739. -spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req)
  740. -> Req when Req::req();
  741. (chunked, resp_chunked_fun(), Req)
  742. -> Req when Req::req().
  743. set_resp_body_fun(StreamLen, StreamFun, Req)
  744. when is_integer(StreamLen), is_function(StreamFun) ->
  745. Req#http_req{resp_body={StreamLen, StreamFun}};
  746. set_resp_body_fun(chunked, StreamFun, Req)
  747. when is_function(StreamFun) ->
  748. Req#http_req{resp_body={chunked, StreamFun}}.
  749. -spec has_resp_header(binary(), req()) -> boolean().
  750. has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
  751. lists:keymember(Name, 1, RespHeaders).
  752. -spec has_resp_body(req()) -> boolean().
  753. has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) ->
  754. true;
  755. has_resp_body(#http_req{resp_body={chunked, _}}) ->
  756. true;
  757. has_resp_body(#http_req{resp_body={Length, _}}) ->
  758. Length > 0;
  759. has_resp_body(#http_req{resp_body=RespBody}) ->
  760. iolist_size(RespBody) > 0.
  761. -spec delete_resp_header(binary(), Req)
  762. -> Req when Req::req().
  763. delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) ->
  764. RespHeaders2 = lists:keydelete(Name, 1, RespHeaders),
  765. Req#http_req{resp_headers=RespHeaders2}.
  766. -spec reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req().
  767. reply(Status, Req=#http_req{resp_body=Body}) ->
  768. reply(Status, [], Body, Req).
  769. -spec reply(cowboy:http_status(), cowboy:http_headers(), Req)
  770. -> {ok, Req} when Req::req().
  771. reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
  772. reply(Status, Headers, Body, Req).
  773. -spec reply(cowboy:http_status(), cowboy:http_headers(),
  774. iodata() | {non_neg_integer() | resp_body_fun()}, Req)
  775. -> {ok, Req} when Req::req().
  776. reply(Status, Headers, Body, Req=#http_req{
  777. socket=Socket, transport=Transport,
  778. version=Version, connection=Connection,
  779. method=Method, resp_compress=Compress,
  780. resp_state=RespState, resp_headers=RespHeaders})
  781. when RespState =:= waiting; RespState =:= waiting_stream ->
  782. HTTP11Headers = if
  783. Transport =/= cowboy_spdy, Version =:= 'HTTP/1.1' ->
  784. [{<<"connection">>, atom_to_connection(Connection)}];
  785. true ->
  786. []
  787. end,
  788. Req3 = case Body of
  789. BodyFun when is_function(BodyFun) ->
  790. %% We stream the response body until we close the connection.
  791. RespConn = close,
  792. {RespType, Req2} = if
  793. Transport =:= cowboy_spdy ->
  794. response(Status, Headers, RespHeaders, [
  795. {<<"date">>, cowboy_clock:rfc1123()},
  796. {<<"server">>, <<"Cowboy">>}
  797. ], stream, Req);
  798. true ->
  799. response(Status, Headers, RespHeaders, [
  800. {<<"connection">>, <<"close">>},
  801. {<<"date">>, cowboy_clock:rfc1123()},
  802. {<<"server">>, <<"Cowboy">>},
  803. {<<"transfer-encoding">>, <<"identity">>}
  804. ], <<>>, Req)
  805. end,
  806. if RespType =/= hook, Method =/= <<"HEAD">> ->
  807. BodyFun(Socket, Transport);
  808. true -> ok
  809. end,
  810. Req2#http_req{connection=RespConn};
  811. {chunked, BodyFun} ->
  812. %% We stream the response body in chunks.
  813. {RespType, Req2} = chunked_response(Status, Headers, Req),
  814. if RespType =/= hook, Method =/= <<"HEAD">> ->
  815. ChunkFun = fun(IoData) -> chunk(IoData, Req2) end,
  816. BodyFun(ChunkFun),
  817. %% Send the last chunk if chunked encoding was used.
  818. if
  819. Version =:= 'HTTP/1.0'; RespState =:= waiting_stream ->
  820. Req2;
  821. true ->
  822. last_chunk(Req2)
  823. end;
  824. true -> Req2
  825. end;
  826. {ContentLength, BodyFun} ->
  827. %% We stream the response body for ContentLength bytes.
  828. RespConn = response_connection(Headers, Connection),
  829. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  830. {<<"content-length">>, integer_to_list(ContentLength)},
  831. {<<"date">>, cowboy_clock:rfc1123()},
  832. {<<"server">>, <<"Cowboy">>}
  833. |HTTP11Headers], stream, Req),
  834. if RespType =/= hook, Method =/= <<"HEAD">> ->
  835. BodyFun(Socket, Transport);
  836. true -> ok
  837. end,
  838. Req2#http_req{connection=RespConn};
  839. _ when Compress ->
  840. RespConn = response_connection(Headers, Connection),
  841. Req2 = reply_may_compress(Status, Headers, Body, Req,
  842. RespHeaders, HTTP11Headers, Method),
  843. Req2#http_req{connection=RespConn};
  844. _ ->
  845. RespConn = response_connection(Headers, Connection),
  846. Req2 = reply_no_compress(Status, Headers, Body, Req,
  847. RespHeaders, HTTP11Headers, Method, iolist_size(Body)),
  848. Req2#http_req{connection=RespConn}
  849. end,
  850. {ok, Req3#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  851. reply_may_compress(Status, Headers, Body, Req,
  852. RespHeaders, HTTP11Headers, Method) ->
  853. BodySize = iolist_size(Body),
  854. case parse_header(<<"accept-encoding">>, Req) of
  855. {ok, Encodings, Req2} ->
  856. CanGzip = (BodySize > 300)
  857. andalso (false =:= lists:keyfind(<<"content-encoding">>,
  858. 1, Headers))
  859. andalso (false =:= lists:keyfind(<<"content-encoding">>,
  860. 1, RespHeaders))
  861. andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  862. 1, Headers))
  863. andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  864. 1, RespHeaders))
  865. andalso (Encodings =/= undefined)
  866. andalso (false =/= lists:keyfind(<<"gzip">>, 1, Encodings)),
  867. case CanGzip of
  868. true ->
  869. GzBody = zlib:gzip(Body),
  870. {_, Req3} = response(Status, Headers, RespHeaders, [
  871. {<<"content-length">>, integer_to_list(byte_size(GzBody))},
  872. {<<"content-encoding">>, <<"gzip">>},
  873. {<<"date">>, cowboy_clock:rfc1123()},
  874. {<<"server">>, <<"Cowboy">>}
  875. |HTTP11Headers],
  876. case Method of <<"HEAD">> -> <<>>; _ -> GzBody end,
  877. Req2),
  878. Req3;
  879. false ->
  880. reply_no_compress(Status, Headers, Body, Req,
  881. RespHeaders, HTTP11Headers, Method, BodySize)
  882. end;
  883. {error, badarg} ->
  884. reply_no_compress(Status, Headers, Body, Req,
  885. RespHeaders, HTTP11Headers, Method, BodySize)
  886. end.
  887. reply_no_compress(Status, Headers, Body, Req,
  888. RespHeaders, HTTP11Headers, Method, BodySize) ->
  889. {_, Req2} = response(Status, Headers, RespHeaders, [
  890. {<<"content-length">>, integer_to_list(BodySize)},
  891. {<<"date">>, cowboy_clock:rfc1123()},
  892. {<<"server">>, <<"Cowboy">>}
  893. |HTTP11Headers],
  894. case Method of <<"HEAD">> -> <<>>; _ -> Body end,
  895. Req),
  896. Req2.
  897. -spec chunked_reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req().
  898. chunked_reply(Status, Req) ->
  899. chunked_reply(Status, [], Req).
  900. -spec chunked_reply(cowboy:http_status(), cowboy:http_headers(), Req)
  901. -> {ok, Req} when Req::req().
  902. chunked_reply(Status, Headers, Req) ->
  903. {_, Req2} = chunked_response(Status, Headers, Req),
  904. {ok, Req2}.
  905. -spec chunk(iodata(), req()) -> ok | {error, atom()}.
  906. chunk(_Data, #http_req{method= <<"HEAD">>}) ->
  907. ok;
  908. chunk(Data, #http_req{socket=Socket, transport=cowboy_spdy,
  909. resp_state=chunks}) ->
  910. cowboy_spdy:stream_data(Socket, Data);
  911. chunk(Data, #http_req{socket=Socket, transport=Transport,
  912. resp_state=stream}) ->
  913. Transport:send(Socket, Data);
  914. chunk(Data, #http_req{socket=Socket, transport=Transport,
  915. resp_state=chunks}) ->
  916. Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
  917. <<"\r\n">>, Data, <<"\r\n">>]).
  918. %% If ever made public, need to send nothing if HEAD.
  919. -spec last_chunk(Req) -> Req when Req::req().
  920. last_chunk(Req=#http_req{socket=Socket, transport=cowboy_spdy}) ->
  921. _ = cowboy_spdy:stream_close(Socket),
  922. Req#http_req{resp_state=done};
  923. last_chunk(Req=#http_req{socket=Socket, transport=Transport}) ->
  924. _ = Transport:send(Socket, <<"0\r\n\r\n">>),
  925. Req#http_req{resp_state=done}.
  926. -spec upgrade_reply(cowboy:http_status(), cowboy:http_headers(), Req)
  927. -> {ok, Req} when Req::req().
  928. upgrade_reply(Status, Headers, Req=#http_req{transport=Transport,
  929. resp_state=waiting, resp_headers=RespHeaders})
  930. when Transport =/= cowboy_spdy ->
  931. {_, Req2} = response(Status, Headers, RespHeaders, [
  932. {<<"connection">>, <<"Upgrade">>}
  933. ], <<>>, Req),
  934. {ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  935. -spec continue(req()) -> ok | {error, atom()}.
  936. continue(#http_req{socket=Socket, transport=Transport,
  937. version=Version}) ->
  938. HTTPVer = atom_to_binary(Version, latin1),
  939. Transport:send(Socket,
  940. << HTTPVer/binary, " ", (status(100))/binary, "\r\n\r\n" >>).
  941. %% Meant to be used internally for sending errors after crashes.
  942. -spec maybe_reply(cowboy:http_status(), req()) -> ok.
  943. maybe_reply(Status, Req) ->
  944. receive
  945. {cowboy_req, resp_sent} -> ok
  946. after 0 ->
  947. _ = cowboy_req:reply(Status, Req),
  948. ok
  949. end.
  950. -spec ensure_response(req(), cowboy:http_status()) -> ok.
  951. %% The response has already been fully sent to the client.
  952. ensure_response(#http_req{resp_state=done}, _) ->
  953. ok;
  954. %% No response has been sent but everything apparently went fine.
  955. %% Reply with the status code found in the second argument.
  956. ensure_response(Req=#http_req{resp_state=RespState}, Status)
  957. when RespState =:= waiting; RespState =:= waiting_stream ->
  958. _ = reply(Status, [], [], Req),
  959. ok;
  960. %% Terminate the chunked body for HTTP/1.1 only.
  961. ensure_response(#http_req{method= <<"HEAD">>}, _) ->
  962. ok;
  963. ensure_response(Req=#http_req{resp_state=chunks}, _) ->
  964. _ = last_chunk(Req),
  965. ok;
  966. ensure_response(#http_req{}, _) ->
  967. ok.
  968. %% Private setter/getter API.
  969. -spec append_buffer(binary(), Req) -> Req when Req::req().
  970. append_buffer(Suffix, Req=#http_req{buffer=Buffer}) ->
  971. Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}.
  972. -spec get(atom(), req()) -> any(); ([atom()], req()) -> any().
  973. get(List, Req) when is_list(List) ->
  974. [g(Atom, Req) || Atom <- List];
  975. get(Atom, Req) when is_atom(Atom) ->
  976. g(Atom, Req).
  977. g(bindings, #http_req{bindings=Ret}) -> Ret;
  978. g(body_state, #http_req{body_state=Ret}) -> Ret;
  979. g(buffer, #http_req{buffer=Ret}) -> Ret;
  980. g(connection, #http_req{connection=Ret}) -> Ret;
  981. g(cookies, #http_req{cookies=Ret}) -> Ret;
  982. g(headers, #http_req{headers=Ret}) -> Ret;
  983. g(host, #http_req{host=Ret}) -> Ret;
  984. g(host_info, #http_req{host_info=Ret}) -> Ret;
  985. g(meta, #http_req{meta=Ret}) -> Ret;
  986. g(method, #http_req{method=Ret}) -> Ret;
  987. g(multipart, #http_req{multipart=Ret}) -> Ret;
  988. g(onresponse, #http_req{onresponse=Ret}) -> Ret;
  989. g(p_headers, #http_req{p_headers=Ret}) -> Ret;
  990. g(path, #http_req{path=Ret}) -> Ret;
  991. g(path_info, #http_req{path_info=Ret}) -> Ret;
  992. g(peer, #http_req{peer=Ret}) -> Ret;
  993. g(pid, #http_req{pid=Ret}) -> Ret;
  994. g(port, #http_req{port=Ret}) -> Ret;
  995. g(qs, #http_req{qs=Ret}) -> Ret;
  996. g(qs_vals, #http_req{qs_vals=Ret}) -> Ret;
  997. g(resp_body, #http_req{resp_body=Ret}) -> Ret;
  998. g(resp_compress, #http_req{resp_compress=Ret}) -> Ret;
  999. g(resp_headers, #http_req{resp_headers=Ret}) -> Ret;
  1000. g(resp_state, #http_req{resp_state=Ret}) -> Ret;
  1001. g(socket, #http_req{socket=Ret}) -> Ret;
  1002. g(transport, #http_req{transport=Ret}) -> Ret;
  1003. g(version, #http_req{version=Ret}) -> Ret.
  1004. -spec set([{atom(), any()}], Req) -> Req when Req::req().
  1005. set([], Req) -> Req;
  1006. set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val});
  1007. set([{body_state, Val}|Tail], Req) -> set(Tail, Req#http_req{body_state=Val});
  1008. set([{buffer, Val}|Tail], Req) -> set(Tail, Req#http_req{buffer=Val});
  1009. set([{connection, Val}|Tail], Req) -> set(Tail, Req#http_req{connection=Val});
  1010. set([{cookies, Val}|Tail], Req) -> set(Tail, Req#http_req{cookies=Val});
  1011. set([{headers, Val}|Tail], Req) -> set(Tail, Req#http_req{headers=Val});
  1012. set([{host, Val}|Tail], Req) -> set(Tail, Req#http_req{host=Val});
  1013. set([{host_info, Val}|Tail], Req) -> set(Tail, Req#http_req{host_info=Val});
  1014. set([{meta, Val}|Tail], Req) -> set(Tail, Req#http_req{meta=Val});
  1015. set([{method, Val}|Tail], Req) -> set(Tail, Req#http_req{method=Val});
  1016. set([{multipart, Val}|Tail], Req) -> set(Tail, Req#http_req{multipart=Val});
  1017. set([{onresponse, Val}|Tail], Req) -> set(Tail, Req#http_req{onresponse=Val});
  1018. set([{p_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{p_headers=Val});
  1019. set([{path, Val}|Tail], Req) -> set(Tail, Req#http_req{path=Val});
  1020. set([{path_info, Val}|Tail], Req) -> set(Tail, Req#http_req{path_info=Val});
  1021. set([{peer, Val}|Tail], Req) -> set(Tail, Req#http_req{peer=Val});
  1022. set([{pid, Val}|Tail], Req) -> set(Tail, Req#http_req{pid=Val});
  1023. set([{port, Val}|Tail], Req) -> set(Tail, Req#http_req{port=Val});
  1024. set([{qs, Val}|Tail], Req) -> set(Tail, Req#http_req{qs=Val});
  1025. set([{qs_vals, Val}|Tail], Req) -> set(Tail, Req#http_req{qs_vals=Val});
  1026. set([{resp_body, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_body=Val});
  1027. set([{resp_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_headers=Val});
  1028. set([{resp_state, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_state=Val});
  1029. set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val});
  1030. set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val});
  1031. set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}).
  1032. -spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(),
  1033. cowboy_router:bindings(), Req) -> Req when Req::req().
  1034. set_bindings(HostInfo, PathInfo, Bindings, Req) ->
  1035. Req#http_req{host_info=HostInfo, path_info=PathInfo,
  1036. bindings=Bindings}.
  1037. %% Misc API.
  1038. -spec compact(Req) -> Req when Req::req().
  1039. compact(Req) ->
  1040. Req#http_req{host_info=undefined,
  1041. path_info=undefined, qs_vals=undefined,
  1042. bindings=undefined, headers=[],
  1043. p_headers=[], cookies=[]}.
  1044. -spec lock(Req) -> Req when Req::req().
  1045. lock(Req) ->
  1046. Req#http_req{resp_state=locked}.
  1047. -spec to_list(req()) -> [{atom(), any()}].
  1048. to_list(Req) ->
  1049. lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))).
  1050. %% Internal.
  1051. -spec chunked_response(cowboy:http_status(), cowboy:http_headers(), Req) ->
  1052. {normal | hook, Req} when Req::req().
  1053. chunked_response(Status, Headers, Req=#http_req{
  1054. transport=cowboy_spdy, resp_state=waiting,
  1055. resp_headers=RespHeaders}) ->
  1056. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  1057. {<<"date">>, cowboy_clock:rfc1123()},
  1058. {<<"server">>, <<"Cowboy">>}
  1059. ], stream, Req),
  1060. {RespType, Req2#http_req{resp_state=chunks,
  1061. resp_headers=[], resp_body= <<>>}};
  1062. chunked_response(Status, Headers, Req=#http_req{
  1063. version=Version, connection=Connection,
  1064. resp_state=RespState, resp_headers=RespHeaders})
  1065. when RespState =:= waiting; RespState =:= waiting_stream ->
  1066. RespConn = response_connection(Headers, Connection),
  1067. HTTP11Headers = if
  1068. Version =:= 'HTTP/1.0' -> [];
  1069. true ->
  1070. MaybeTE = if
  1071. RespState =:= waiting_stream -> [];
  1072. true -> [{<<"transfer-encoding">>, <<"chunked">>}]
  1073. end,
  1074. [{<<"connection">>, atom_to_connection(Connection)}|MaybeTE]
  1075. end,
  1076. RespState2 = if
  1077. Version =:= 'HTTP/1.1', RespState =:= 'waiting' -> chunks;
  1078. true -> stream
  1079. end,
  1080. {RespType, Req2} = response(Status, Headers, RespHeaders, [
  1081. {<<"date">>, cowboy_clock:rfc1123()},
  1082. {<<"server">>, <<"Cowboy">>}
  1083. |HTTP11Headers], <<>>, Req),
  1084. {RespType, Req2#http_req{connection=RespConn, resp_state=RespState2,
  1085. resp_headers=[], resp_body= <<>>}}.
  1086. -spec response(cowboy:http_status(), cowboy:http_headers(),
  1087. cowboy:http_headers(), cowboy:http_headers(), stream | iodata(), Req)
  1088. -> {normal | hook, Req} when Req::req().
  1089. response(Status, Headers, RespHeaders, DefaultHeaders, Body, Req=#http_req{
  1090. socket=Socket, transport=Transport, version=Version,
  1091. pid=ReqPid, onresponse=OnResponse}) ->
  1092. FullHeaders = case OnResponse of
  1093. already_called -> Headers;
  1094. _ -> response_merge_headers(Headers, RespHeaders, DefaultHeaders)
  1095. end,
  1096. Body2 = case Body of stream -> <<>>; _ -> Body end,
  1097. {Status2, FullHeaders2, Req2} = case OnResponse of
  1098. already_called -> {Status, FullHeaders, Req};
  1099. undefined -> {Status, FullHeaders, Req};
  1100. OnResponse ->
  1101. case OnResponse(Status, FullHeaders, Body2,
  1102. %% Don't call 'onresponse' from the hook itself.
  1103. Req#http_req{resp_headers=[], resp_body= <<>>,
  1104. onresponse=already_called}) of
  1105. StHdReq = {_, _, _} ->
  1106. StHdReq;
  1107. Req1 ->
  1108. {Status, FullHeaders, Req1}
  1109. end
  1110. end,
  1111. ReplyType = case Req2#http_req.resp_state of
  1112. waiting when Transport =:= cowboy_spdy, Body =:= stream ->
  1113. cowboy_spdy:stream_reply(Socket, status(Status2), FullHeaders2),
  1114. ReqPid ! {?MODULE, resp_sent},
  1115. normal;
  1116. waiting when Transport =:= cowboy_spdy ->
  1117. cowboy_spdy:reply(Socket, status(Status2), FullHeaders2, Body),
  1118. ReqPid ! {?MODULE, resp_sent},
  1119. normal;
  1120. RespState when RespState =:= waiting; RespState =:= waiting_stream ->
  1121. HTTPVer = atom_to_binary(Version, latin1),
  1122. StatusLine = << HTTPVer/binary, " ",
  1123. (status(Status2))/binary, "\r\n" >>,
  1124. HeaderLines = [[Key, <<": ">>, Value, <<"\r\n">>]
  1125. || {Key, Value} <- FullHeaders2],
  1126. Transport:send(Socket, [StatusLine, HeaderLines, <<"\r\n">>, Body2]),
  1127. ReqPid ! {?MODULE, resp_sent},
  1128. normal;
  1129. _ ->
  1130. hook
  1131. end,
  1132. {ReplyType, Req2}.
  1133. -spec response_connection(cowboy:http_headers(), keepalive | close)
  1134. -> keepalive | close.
  1135. response_connection([], Connection) ->
  1136. Connection;
  1137. response_connection([{Name, Value}|Tail], Connection) ->
  1138. case Name of
  1139. <<"connection">> ->
  1140. Tokens = cow_http_hd:parse_connection(Value),
  1141. connection_to_atom(Tokens);
  1142. _ ->
  1143. response_connection(Tail, Connection)
  1144. end.
  1145. -spec response_merge_headers(cowboy:http_headers(), cowboy:http_headers(),
  1146. cowboy:http_headers()) -> cowboy:http_headers().
  1147. response_merge_headers(Headers, RespHeaders, DefaultHeaders) ->
  1148. Headers2 = [{Key, Value} || {Key, Value} <- Headers],
  1149. merge_headers(
  1150. merge_headers(Headers2, RespHeaders),
  1151. DefaultHeaders).
  1152. -spec merge_headers(cowboy:http_headers(), cowboy:http_headers())
  1153. -> cowboy:http_headers().
  1154. %% Merge headers by prepending the tuples in the second list to the
  1155. %% first list. It also handles Set-Cookie properly, which supports
  1156. %% duplicated entries. Notice that, while the RFC2109 does allow more
  1157. %% than one cookie to be set per Set-Cookie header, we are following
  1158. %% the implementation of common web servers and applications which
  1159. %% return many distinct headers per each Set-Cookie entry to avoid
  1160. %% issues with clients/browser which may not support it.
  1161. merge_headers(Headers, []) ->
  1162. Headers;
  1163. merge_headers(Headers, [{<<"set-cookie">>, Value}|Tail]) ->
  1164. merge_headers([{<<"set-cookie">>, Value}|Headers], Tail);
  1165. merge_headers(Headers, [{Name, Value}|Tail]) ->
  1166. Headers2 = case lists:keymember(Name, 1, Headers) of
  1167. true -> Headers;
  1168. false -> [{Name, Value}|Headers]
  1169. end,
  1170. merge_headers(Headers2, Tail).
  1171. -spec atom_to_connection(keepalive) -> <<_:80>>;
  1172. (close) -> <<_:40>>.
  1173. atom_to_connection(keepalive) ->
  1174. <<"keep-alive">>;
  1175. atom_to_connection(close) ->
  1176. <<"close">>.
  1177. %% We don't match on "keep-alive" since it is the default value.
  1178. -spec connection_to_atom([binary()]) -> keepalive | close.
  1179. connection_to_atom([]) ->
  1180. keepalive;
  1181. connection_to_atom([<<"close">>|_]) ->
  1182. close;
  1183. connection_to_atom([_|Tail]) ->
  1184. connection_to_atom(Tail).
  1185. -spec status(cowboy:http_status()) -> binary().
  1186. status(100) -> <<"100 Continue">>;
  1187. status(101) -> <<"101 Switching Protocols">>;
  1188. status(102) -> <<"102 Processing">>;
  1189. status(200) -> <<"200 OK">>;
  1190. status(201) -> <<"201 Created">>;
  1191. status(202) -> <<"202 Accepted">>;
  1192. status(203) -> <<"203 Non-Authoritative Information">>;
  1193. status(204) -> <<"204 No Content">>;
  1194. status(205) -> <<"205 Reset Content">>;
  1195. status(206) -> <<"206 Partial Content">>;
  1196. status(207) -> <<"207 Multi-Status">>;
  1197. status(226) -> <<"226 IM Used">>;
  1198. status(300) -> <<"300 Multiple Choices">>;
  1199. status(301) -> <<"301 Moved Permanently">>;
  1200. status(302) -> <<"302 Found">>;
  1201. status(303) -> <<"303 See Other">>;
  1202. status(304) -> <<"304 Not Modified">>;
  1203. status(305) -> <<"305 Use Proxy">>;
  1204. status(306) -> <<"306 Switch Proxy">>;
  1205. status(307) -> <<"307 Temporary Redirect">>;
  1206. status(400) -> <<"400 Bad Request">>;
  1207. status(401) -> <<"401 Unauthorized">>;
  1208. status(402) -> <<"402 Payment Required">>;
  1209. status(403) -> <<"403 Forbidden">>;
  1210. status(404) -> <<"404 Not Found">>;
  1211. status(405) -> <<"405 Method Not Allowed">>;
  1212. status(406) -> <<"406 Not Acceptable">>;
  1213. status(407) -> <<"407 Proxy Authentication Required">>;
  1214. status(408) -> <<"408 Request Timeout">>;
  1215. status(409) -> <<"409 Conflict">>;
  1216. status(410) -> <<"410 Gone">>;
  1217. status(411) -> <<"411 Length Required">>;
  1218. status(412) -> <<"412 Precondition Failed">>;
  1219. status(413) -> <<"413 Request Entity Too Large">>;
  1220. status(414) -> <<"414 Request-URI Too Long">>;
  1221. status(415) -> <<"415 Unsupported Media Type">>;
  1222. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  1223. status(417) -> <<"417 Expectation Failed">>;
  1224. status(418) -> <<"418 I'm a teapot">>;
  1225. status(422) -> <<"422 Unprocessable Entity">>;
  1226. status(423) -> <<"423 Locked">>;
  1227. status(424) -> <<"424 Failed Dependency">>;
  1228. status(425) -> <<"425 Unordered Collection">>;
  1229. status(426) -> <<"426 Upgrade Required">>;
  1230. status(428) -> <<"428 Precondition Required">>;
  1231. status(429) -> <<"429 Too Many Requests">>;
  1232. status(431) -> <<"431 Request Header Fields Too Large">>;
  1233. status(500) -> <<"500 Internal Server Error">>;
  1234. status(501) -> <<"501 Not Implemented">>;
  1235. status(502) -> <<"502 Bad Gateway">>;
  1236. status(503) -> <<"503 Service Unavailable">>;
  1237. status(504) -> <<"504 Gateway Timeout">>;
  1238. status(505) -> <<"505 HTTP Version Not Supported">>;
  1239. status(506) -> <<"506 Variant Also Negotiates">>;
  1240. status(507) -> <<"507 Insufficient Storage">>;
  1241. status(510) -> <<"510 Not Extended">>;
  1242. status(511) -> <<"511 Network Authentication Required">>;
  1243. status(B) when is_binary(B) -> B.
  1244. %% Tests.
  1245. -ifdef(TEST).
  1246. url_test() ->
  1247. {undefined, _} =
  1248. url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined,
  1249. path= <<>>, qs= <<>>, pid=self()}),
  1250. {<<"http://localhost/path">>, _ } =
  1251. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=80,
  1252. path= <<"/path">>, qs= <<>>, pid=self()}),
  1253. {<<"http://localhost:443/path">>, _} =
  1254. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=443,
  1255. path= <<"/path">>, qs= <<>>, pid=self()}),
  1256. {<<"http://localhost:8080/path">>, _} =
  1257. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1258. path= <<"/path">>, qs= <<>>, pid=self()}),
  1259. {<<"http://localhost:8080/path?dummy=2785">>, _} =
  1260. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1261. path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}),
  1262. {<<"https://localhost/path">>, _} =
  1263. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=443,
  1264. path= <<"/path">>, qs= <<>>, pid=self()}),
  1265. {<<"https://localhost:8443/path">>, _} =
  1266. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1267. path= <<"/path">>, qs= <<>>, pid=self()}),
  1268. {<<"https://localhost:8443/path?dummy=2785">>, _} =
  1269. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1270. path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}),
  1271. ok.
  1272. connection_to_atom_test_() ->
  1273. Tests = [
  1274. {[<<"close">>], close},
  1275. {[<<"keep-alive">>], keepalive},
  1276. {[<<"keep-alive">>, <<"upgrade">>], keepalive}
  1277. ],
  1278. [{lists:flatten(io_lib:format("~p", [T])),
  1279. fun() -> R = connection_to_atom(T) end} || {T, R} <- Tests].
  1280. merge_headers_test_() ->
  1281. Tests = [
  1282. {[{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}],
  1283. [{<<"set-cookie">>,<<"foo=bar">>},{<<"content-length">>,<<"11">>}],
  1284. [{<<"set-cookie">>,<<"foo=bar">>},
  1285. {<<"content-length">>,<<"13">>},
  1286. {<<"server">>,<<"Cowboy">>}]},
  1287. {[{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}],
  1288. [{<<"set-cookie">>,<<"foo=bar">>},{<<"set-cookie">>,<<"bar=baz">>}],
  1289. [{<<"set-cookie">>,<<"bar=baz">>},
  1290. {<<"set-cookie">>,<<"foo=bar">>},
  1291. {<<"content-length">>,<<"13">>},
  1292. {<<"server">>,<<"Cowboy">>}]}
  1293. ],
  1294. [fun() -> Res = merge_headers(L,R) end || {L, R, Res} <- Tests].
  1295. -endif.