cowboy_req.erl 55 KB

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