cowboy_req.erl 47 KB

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