cowboy_http_req.erl 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.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. %% Almost all functions in this module return a new <em>Req</em> variable.
  18. %% It should always be used instead of the one used in your function call
  19. %% because it keeps the state of the request. It also allows Cowboy to do
  20. %% some lazy evaluation and cache results where possible.
  21. -module(cowboy_http_req).
  22. -export([
  23. method/1, version/1, peer/1,
  24. host/1, host_info/1, raw_host/1, port/1,
  25. path/1, path_info/1, raw_path/1,
  26. qs_val/2, qs_val/3, qs_vals/1, raw_qs/1,
  27. binding/2, binding/3, bindings/1,
  28. header/2, header/3, headers/1,
  29. parse_header/2, parse_header/3,
  30. cookie/2, cookie/3, cookies/1
  31. ]). %% Request API.
  32. -export([
  33. body/1, body/2, body_qs/1
  34. ]). %% Request Body API.
  35. -export([
  36. set_resp_header/3, set_resp_body/2,
  37. has_resp_header/2, has_resp_body/1,
  38. reply/2, reply/3, reply/4,
  39. chunked_reply/2, chunked_reply/3, chunk/2,
  40. upgrade_reply/3
  41. ]). %% Response API.
  42. -export([
  43. compact/1
  44. ]). %% Misc API.
  45. -include("include/http.hrl").
  46. -include_lib("eunit/include/eunit.hrl").
  47. %% Request API.
  48. %% @doc Return the HTTP method of the request.
  49. -spec method(#http_req{}) -> {http_method(), #http_req{}}.
  50. method(Req) ->
  51. {Req#http_req.method, Req}.
  52. %% @doc Return the HTTP version used for the request.
  53. -spec version(#http_req{}) -> {http_version(), #http_req{}}.
  54. version(Req) ->
  55. {Req#http_req.version, Req}.
  56. %% @doc Return the peer address and port number of the remote host.
  57. -spec peer(#http_req{}) -> {{inet:ip_address(), inet:ip_port()}, #http_req{}}.
  58. peer(Req=#http_req{socket=Socket, transport=Transport, peer=undefined}) ->
  59. {ok, Peer} = Transport:peername(Socket),
  60. {Peer, Req#http_req{peer=Peer}};
  61. peer(Req) ->
  62. {Req#http_req.peer, Req}.
  63. %% @doc Return the tokens for the hostname requested.
  64. -spec host(#http_req{}) -> {cowboy_dispatcher:tokens(), #http_req{}}.
  65. host(Req) ->
  66. {Req#http_req.host, Req}.
  67. %% @doc Return the extra host information obtained from partially matching
  68. %% the hostname using <em>'...'</em>.
  69. -spec host_info(#http_req{})
  70. -> {cowboy_dispatcher:tokens() | undefined, #http_req{}}.
  71. host_info(Req) ->
  72. {Req#http_req.host_info, Req}.
  73. %% @doc Return the raw host directly taken from the request.
  74. -spec raw_host(#http_req{}) -> {binary(), #http_req{}}.
  75. raw_host(Req) ->
  76. {Req#http_req.raw_host, Req}.
  77. %% @doc Return the port used for this request.
  78. -spec port(#http_req{}) -> {inet:ip_port(), #http_req{}}.
  79. port(Req) ->
  80. {Req#http_req.port, Req}.
  81. %% @doc Return the path segments for the path requested.
  82. %%
  83. %% Following RFC2396, this function may return path segments containing any
  84. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  85. %% and part of a path segment in the path requested.
  86. -spec path(#http_req{}) -> {cowboy_dispatcher:tokens(), #http_req{}}.
  87. path(Req) ->
  88. {Req#http_req.path, Req}.
  89. %% @doc Return the extra path information obtained from partially matching
  90. %% the patch using <em>'...'</em>.
  91. -spec path_info(#http_req{})
  92. -> {cowboy_dispatcher:tokens() | undefined, #http_req{}}.
  93. path_info(Req) ->
  94. {Req#http_req.path_info, Req}.
  95. %% @doc Return the raw path directly taken from the request.
  96. -spec raw_path(#http_req{}) -> {binary(), #http_req{}}.
  97. raw_path(Req) ->
  98. {Req#http_req.raw_path, Req}.
  99. %% @equiv qs_val(Name, Req, undefined)
  100. -spec qs_val(binary(), #http_req{})
  101. -> {binary() | true | undefined, #http_req{}}.
  102. qs_val(Name, Req) when is_binary(Name) ->
  103. qs_val(Name, Req, undefined).
  104. %% @doc Return the query string value for the given key, or a default if
  105. %% missing.
  106. -spec qs_val(binary(), #http_req{}, Default)
  107. -> {binary() | true | Default, #http_req{}} when Default::any().
  108. qs_val(Name, Req=#http_req{raw_qs=RawQs, qs_vals=undefined}, Default)
  109. when is_binary(Name) ->
  110. QsVals = parse_qs(RawQs),
  111. qs_val(Name, Req#http_req{qs_vals=QsVals}, Default);
  112. qs_val(Name, Req, Default) ->
  113. case lists:keyfind(Name, 1, Req#http_req.qs_vals) of
  114. {Name, Value} -> {Value, Req};
  115. false -> {Default, Req}
  116. end.
  117. %% @doc Return the full list of query string values.
  118. -spec qs_vals(#http_req{}) -> {list({binary(), binary() | true}), #http_req{}}.
  119. qs_vals(Req=#http_req{raw_qs=RawQs, qs_vals=undefined}) ->
  120. QsVals = parse_qs(RawQs),
  121. qs_vals(Req#http_req{qs_vals=QsVals});
  122. qs_vals(Req=#http_req{qs_vals=QsVals}) ->
  123. {QsVals, Req}.
  124. %% @doc Return the raw query string directly taken from the request.
  125. -spec raw_qs(#http_req{}) -> {binary(), #http_req{}}.
  126. raw_qs(Req) ->
  127. {Req#http_req.raw_qs, Req}.
  128. %% @equiv binding(Name, Req, undefined)
  129. -spec binding(atom(), #http_req{}) -> {binary() | undefined, #http_req{}}.
  130. binding(Name, Req) when is_atom(Name) ->
  131. binding(Name, Req, undefined).
  132. %% @doc Return the binding value for the given key obtained when matching
  133. %% the host and path against the dispatch list, or a default if missing.
  134. -spec binding(atom(), #http_req{}, Default)
  135. -> {binary() | Default, #http_req{}} when Default::any().
  136. binding(Name, Req, Default) when is_atom(Name) ->
  137. case lists:keyfind(Name, 1, Req#http_req.bindings) of
  138. {Name, Value} -> {Value, Req};
  139. false -> {Default, Req}
  140. end.
  141. %% @doc Return the full list of binding values.
  142. -spec bindings(#http_req{}) -> {list({atom(), binary()}), #http_req{}}.
  143. bindings(Req) ->
  144. {Req#http_req.bindings, Req}.
  145. %% @equiv header(Name, Req, undefined)
  146. -spec header(atom() | binary(), #http_req{})
  147. -> {binary() | undefined, #http_req{}}.
  148. header(Name, Req) when is_atom(Name) orelse is_binary(Name) ->
  149. header(Name, Req, undefined).
  150. %% @doc Return the header value for the given key, or a default if missing.
  151. -spec header(atom() | binary(), #http_req{}, Default)
  152. -> {binary() | Default, #http_req{}} when Default::any().
  153. header(Name, Req, Default) when is_atom(Name) orelse is_binary(Name) ->
  154. case lists:keyfind(Name, 1, Req#http_req.headers) of
  155. {Name, Value} -> {Value, Req};
  156. false -> {Default, Req}
  157. end.
  158. %% @doc Return the full list of headers.
  159. -spec headers(#http_req{}) -> {http_headers(), #http_req{}}.
  160. headers(Req) ->
  161. {Req#http_req.headers, Req}.
  162. %% @doc Semantically parse headers.
  163. %%
  164. %% When the value isn't found, a proper default value for the type
  165. %% returned is used as a return value.
  166. %% @see parse_header/3
  167. -spec parse_header(http_header(), #http_req{})
  168. -> {any(), #http_req{}} | {error, badarg}.
  169. parse_header(Name, Req=#http_req{p_headers=PHeaders}) ->
  170. case lists:keyfind(Name, 1, PHeaders) of
  171. false -> parse_header(Name, Req, parse_header_default(Name));
  172. {Name, Value} -> {Value, Req}
  173. end.
  174. %% @doc Default values for semantic header parsing.
  175. -spec parse_header_default(http_header()) -> any().
  176. parse_header_default('Accept') -> undefined;
  177. parse_header_default('Accept-Charset') -> undefined;
  178. parse_header_default('Accept-Encoding') -> undefined;
  179. parse_header_default('Accept-Language') -> undefined;
  180. parse_header_default('Connection') -> [];
  181. parse_header_default('If-Match') -> undefined;
  182. parse_header_default('If-None-Match') -> undefined;
  183. parse_header_default(_Name) -> undefined.
  184. %% @doc Semantically parse headers.
  185. %%
  186. %% When the header is unknown, the value is returned directly without parsing.
  187. -spec parse_header(http_header(), #http_req{}, any())
  188. -> {any(), #http_req{}} | {error, badarg}.
  189. parse_header(Name, Req, Default) when Name =:= 'Accept' ->
  190. parse_header(Name, Req, Default,
  191. fun (Value) ->
  192. cowboy_http:list(Value, fun cowboy_http:media_range/2)
  193. end);
  194. parse_header(Name, Req, Default) when Name =:= 'Accept-Charset' ->
  195. parse_header(Name, Req, Default,
  196. fun (Value) ->
  197. cowboy_http:nonempty_list(Value, fun cowboy_http:conneg/2)
  198. end);
  199. parse_header(Name, Req, Default) when Name =:= 'Accept-Encoding' ->
  200. parse_header(Name, Req, Default,
  201. fun (Value) ->
  202. cowboy_http:list(Value, fun cowboy_http:conneg/2)
  203. end);
  204. parse_header(Name, Req, Default) when Name =:= 'Accept-Language' ->
  205. parse_header(Name, Req, Default,
  206. fun (Value) ->
  207. cowboy_http:nonempty_list(Value, fun cowboy_http:language_range/2)
  208. end);
  209. parse_header(Name, Req, Default) when Name =:= 'Connection' ->
  210. parse_header(Name, Req, Default,
  211. fun (Value) ->
  212. cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2)
  213. end);
  214. parse_header(Name, Req, Default) when Name =:= 'Content-Length' ->
  215. parse_header(Name, Req, Default,
  216. fun (Value) ->
  217. cowboy_http:digits(Value)
  218. end);
  219. parse_header(Name, Req, Default) when Name =:= 'Content-Type' ->
  220. parse_header(Name, Req, Default,
  221. fun (Value) ->
  222. cowboy_http:content_type(Value)
  223. end);
  224. parse_header(Name, Req, Default)
  225. when Name =:= 'If-Match'; Name =:= 'If-None-Match' ->
  226. parse_header(Name, Req, Default,
  227. fun (Value) ->
  228. cowboy_http:entity_tag_match(Value)
  229. end);
  230. parse_header(Name, Req, Default)
  231. when Name =:= 'If-Modified-Since'; Name =:= 'If-Unmodified-Since' ->
  232. parse_header(Name, Req, Default,
  233. fun (Value) ->
  234. cowboy_http:http_date(Value)
  235. end);
  236. parse_header(Name, Req, Default) ->
  237. {Value, Req2} = header(Name, Req, Default),
  238. {undefined, Value, Req2}.
  239. parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) ->
  240. case header(Name, Req) of
  241. {undefined, Req2} ->
  242. {Default, Req2#http_req{p_headers=[{Name, Default}|PHeaders]}};
  243. {Value, Req2} ->
  244. case Fun(Value) of
  245. {error, badarg} ->
  246. {error, badarg};
  247. P ->
  248. {P, Req2#http_req{p_headers=[{Name, P}|PHeaders]}}
  249. end
  250. end.
  251. %% @equiv cookie(Name, Req, undefined)
  252. -spec cookie(binary(), #http_req{})
  253. -> {binary() | true | undefined, #http_req{}}.
  254. cookie(Name, Req) when is_binary(Name) ->
  255. cookie(Name, Req, undefined).
  256. %% @doc Return the cookie value for the given key, or a default if
  257. %% missing.
  258. -spec cookie(binary(), #http_req{}, Default)
  259. -> {binary() | true | Default, #http_req{}} when Default::any().
  260. cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) ->
  261. case header('Cookie', Req) of
  262. {undefined, Req2} ->
  263. {Default, Req2#http_req{cookies=[]}};
  264. {RawCookie, Req2} ->
  265. Cookies = cowboy_cookies:parse_cookie(RawCookie),
  266. cookie(Name, Req2#http_req{cookies=Cookies}, Default)
  267. end;
  268. cookie(Name, Req, Default) ->
  269. case lists:keyfind(Name, 1, Req#http_req.cookies) of
  270. {Name, Value} -> {Value, Req};
  271. false -> {Default, Req}
  272. end.
  273. %% @doc Return the full list of cookie values.
  274. -spec cookies(#http_req{}) -> {list({binary(), binary() | true}), #http_req{}}.
  275. cookies(Req=#http_req{cookies=undefined}) ->
  276. case header('Cookie', Req) of
  277. {undefined, Req2} ->
  278. {[], Req2#http_req{cookies=[]}};
  279. {RawCookie, Req2} ->
  280. Cookies = cowboy_cookies:parse_cookie(RawCookie),
  281. cookies(Req2#http_req{cookies=Cookies})
  282. end;
  283. cookies(Req=#http_req{cookies=Cookies}) ->
  284. {Cookies, Req}.
  285. %% Request Body API.
  286. %% @doc Return the full body sent with the request, or <em>{error, badarg}</em>
  287. %% if no <em>Content-Length</em> is available.
  288. %% @todo We probably want to allow a max length.
  289. -spec body(#http_req{}) -> {ok, binary(), #http_req{}} | {error, atom()}.
  290. body(Req) ->
  291. {Length, Req2} = cowboy_http_req:parse_header('Content-Length', Req),
  292. case Length of
  293. undefined -> {error, badarg};
  294. {error, badarg} -> {error, badarg};
  295. _Any ->
  296. body(Length, Req2)
  297. end.
  298. %% @doc Return <em>Length</em> bytes of the request body.
  299. %%
  300. %% You probably shouldn't be calling this function directly, as it expects the
  301. %% <em>Length</em> argument to be the full size of the body, and will consider
  302. %% the body to be fully read from the socket.
  303. %% @todo We probably want to configure the timeout.
  304. -spec body(non_neg_integer(), #http_req{})
  305. -> {ok, binary(), #http_req{}} | {error, atom()}.
  306. body(Length, Req=#http_req{body_state=waiting, buffer=Buffer})
  307. when is_integer(Length) andalso Length =< byte_size(Buffer) ->
  308. << Body:Length/binary, Rest/bits >> = Buffer,
  309. {ok, Body, Req#http_req{body_state=done, buffer=Rest}};
  310. body(Length, Req=#http_req{socket=Socket, transport=Transport,
  311. body_state=waiting, buffer=Buffer}) ->
  312. case Transport:recv(Socket, Length - byte_size(Buffer), 5000) of
  313. {ok, Body} -> {ok, << Buffer/binary, Body/binary >>,
  314. Req#http_req{body_state=done, buffer= <<>>}};
  315. {error, Reason} -> {error, Reason}
  316. end.
  317. %% @doc Return the full body sent with the reqest, parsed as an
  318. %% application/x-www-form-urlencoded string. Essentially a POST query string.
  319. -spec body_qs(#http_req{}) -> {list({binary(), binary() | true}), #http_req{}}.
  320. body_qs(Req) ->
  321. {ok, Body, Req2} = body(Req),
  322. {parse_qs(Body), Req2}.
  323. %% Response API.
  324. %% @doc Add a header to the response.
  325. -spec set_resp_header(http_header(), iodata(), #http_req{})
  326. -> {ok, #http_req{}}.
  327. set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) ->
  328. NameBin = header_to_binary(Name),
  329. {ok, Req#http_req{resp_headers=[{NameBin, Value}|RespHeaders]}}.
  330. %% @doc Add a body to the response.
  331. %%
  332. %% The body set here is ignored if the response is later sent using
  333. %% anything other than reply/2 or reply/3.
  334. -spec set_resp_body(iodata(), #http_req{}) -> {ok, #http_req{}}.
  335. set_resp_body(Body, Req) ->
  336. {ok, Req#http_req{resp_body=Body}}.
  337. %% @doc Return whether the given header has been set for the response.
  338. -spec has_resp_header(http_header(), #http_req{}) -> boolean().
  339. has_resp_header(Name, #http_req{resp_headers=RespHeaders}) ->
  340. NameBin = header_to_binary(Name),
  341. lists:keymember(NameBin, 1, RespHeaders).
  342. %% @doc Return whether a body has been set for the response.
  343. -spec has_resp_body(#http_req{}) -> boolean().
  344. has_resp_body(#http_req{resp_body=RespBody}) ->
  345. byte_size(RespBody) > 0.
  346. %% @equiv reply(Status, [], [], Req)
  347. -spec reply(http_status(), #http_req{}) -> {ok, #http_req{}}.
  348. reply(Status, Req=#http_req{resp_body=Body}) ->
  349. reply(Status, [], Body, Req).
  350. %% @equiv reply(Status, Headers, [], Req)
  351. -spec reply(http_status(), http_headers(), #http_req{}) -> {ok, #http_req{}}.
  352. reply(Status, Headers, Req=#http_req{resp_body=Body}) ->
  353. reply(Status, Headers, Body, Req).
  354. %% @doc Send a reply to the client.
  355. -spec reply(http_status(), http_headers(), iodata(), #http_req{})
  356. -> {ok, #http_req{}}.
  357. reply(Status, Headers, Body, Req=#http_req{socket=Socket,
  358. transport=Transport, connection=Connection,
  359. method=Method, resp_state=waiting, resp_headers=RespHeaders}) ->
  360. RespConn = response_connection(Headers, Connection),
  361. Head = response_head(Status, Headers, RespHeaders, [
  362. {<<"Connection">>, atom_to_connection(Connection)},
  363. {<<"Content-Length">>,
  364. list_to_binary(integer_to_list(iolist_size(Body)))},
  365. {<<"Date">>, cowboy_clock:rfc1123()},
  366. {<<"Server">>, <<"Cowboy">>}
  367. ]),
  368. case Method of
  369. 'HEAD' -> Transport:send(Socket, Head);
  370. _ -> Transport:send(Socket, [Head, Body])
  371. end,
  372. {ok, Req#http_req{connection=RespConn, resp_state=done,
  373. resp_headers=[], resp_body= <<>>}}.
  374. %% @equiv chunked_reply(Status, [], Req)
  375. -spec chunked_reply(http_status(), #http_req{}) -> {ok, #http_req{}}.
  376. chunked_reply(Status, Req) ->
  377. chunked_reply(Status, [], Req).
  378. %% @doc Initiate the sending of a chunked reply to the client.
  379. %% @see cowboy_http_req:chunk/2
  380. -spec chunked_reply(http_status(), http_headers(), #http_req{})
  381. -> {ok, #http_req{}}.
  382. chunked_reply(Status, Headers, Req=#http_req{socket=Socket, transport=Transport,
  383. connection=Connection, resp_state=waiting, resp_headers=RespHeaders}) ->
  384. RespConn = response_connection(Headers, Connection),
  385. Head = response_head(Status, Headers, RespHeaders, [
  386. {<<"Connection">>, atom_to_connection(Connection)},
  387. {<<"Transfer-Encoding">>, <<"chunked">>},
  388. {<<"Date">>, cowboy_clock:rfc1123()},
  389. {<<"Server">>, <<"Cowboy">>}
  390. ]),
  391. Transport:send(Socket, Head),
  392. {ok, Req#http_req{connection=RespConn, resp_state=chunks,
  393. resp_headers=[], resp_body= <<>>}}.
  394. %% @doc Send a chunk of data.
  395. %%
  396. %% A chunked reply must have been initiated before calling this function.
  397. -spec chunk(iodata(), #http_req{}) -> ok | {error, atom()}.
  398. chunk(_Data, #http_req{socket=_Socket, transport=_Transport, method='HEAD'}) ->
  399. ok;
  400. chunk(Data, #http_req{socket=Socket, transport=Transport, resp_state=chunks}) ->
  401. Transport:send(Socket, [integer_to_list(iolist_size(Data), 16),
  402. <<"\r\n">>, Data, <<"\r\n">>]).
  403. %% @doc Send an upgrade reply.
  404. -spec upgrade_reply(http_status(), http_headers(), #http_req{})
  405. -> {ok, #http_req{}}.
  406. upgrade_reply(Status, Headers, Req=#http_req{socket=Socket, transport=Transport,
  407. resp_state=waiting, resp_headers=RespHeaders}) ->
  408. Head = response_head(Status, Headers, RespHeaders, [
  409. {<<"Connection">>, <<"Upgrade">>}
  410. ]),
  411. Transport:send(Socket, Head),
  412. {ok, Req#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}.
  413. %% Misc API.
  414. %% @doc Compact the request data by removing all non-system information.
  415. %%
  416. %% This essentially removes the host, path, query string, bindings and headers.
  417. %% Use it when you really need to save up memory, for example when having
  418. %% many concurrent long-running connections.
  419. -spec compact(#http_req{}) -> #http_req{}.
  420. compact(Req) ->
  421. Req#http_req{host=undefined, host_info=undefined, path=undefined,
  422. path_info=undefined, qs_vals=undefined,
  423. bindings=undefined, headers=[]}.
  424. %% Internal.
  425. -spec parse_qs(binary()) -> list({binary(), binary() | true}).
  426. parse_qs(<<>>) ->
  427. [];
  428. parse_qs(Qs) ->
  429. Tokens = binary:split(Qs, <<"&">>, [global, trim]),
  430. [case binary:split(Token, <<"=">>) of
  431. [Token] -> {quoted:from_url(Token), true};
  432. [Name, Value] -> {quoted:from_url(Name), quoted:from_url(Value)}
  433. end || Token <- Tokens].
  434. -spec response_connection(http_headers(), keepalive | close)
  435. -> keepalive | close.
  436. response_connection([], Connection) ->
  437. Connection;
  438. response_connection([{Name, Value}|Tail], Connection) ->
  439. case Name of
  440. 'Connection' -> response_connection_parse(Value);
  441. Name when is_atom(Name) -> response_connection(Tail, Connection);
  442. Name ->
  443. Name2 = cowboy_bstr:to_lower(Name),
  444. case Name2 of
  445. <<"connection">> -> response_connection_parse(Value);
  446. _Any -> response_connection(Tail, Connection)
  447. end
  448. end.
  449. -spec response_connection_parse(binary()) -> keepalive | close.
  450. response_connection_parse(ReplyConn) ->
  451. Tokens = cowboy_http:nonempty_list(ReplyConn, fun cowboy_http:token/2),
  452. cowboy_http:connection_to_atom(Tokens).
  453. -spec response_head(http_status(), http_headers(), http_headers(),
  454. http_headers()) -> iolist().
  455. response_head(Status, Headers, RespHeaders, DefaultHeaders) ->
  456. StatusLine = <<"HTTP/1.1 ", (status(Status))/binary, "\r\n">>,
  457. Headers2 = [{header_to_binary(Key), Value} || {Key, Value} <- Headers],
  458. Headers3 = merge_headers(
  459. merge_headers(Headers2, RespHeaders),
  460. DefaultHeaders),
  461. Headers4 = [[Key, <<": ">>, Value, <<"\r\n">>]
  462. || {Key, Value} <- Headers3],
  463. [StatusLine, Headers4, <<"\r\n">>].
  464. -spec merge_headers(http_headers(), http_headers()) -> http_headers().
  465. merge_headers(Headers, []) ->
  466. Headers;
  467. merge_headers(Headers, [{Name, Value}|Tail]) ->
  468. Headers2 = case lists:keymember(Name, 1, Headers) of
  469. true -> Headers;
  470. false -> Headers ++ [{Name, Value}]
  471. end,
  472. merge_headers(Headers2, Tail).
  473. -spec atom_to_connection(keepalive) -> <<_:80>>;
  474. (close) -> <<_:40>>.
  475. atom_to_connection(keepalive) ->
  476. <<"keep-alive">>;
  477. atom_to_connection(close) ->
  478. <<"close">>.
  479. -spec status(http_status()) -> binary().
  480. status(100) -> <<"100 Continue">>;
  481. status(101) -> <<"101 Switching Protocols">>;
  482. status(102) -> <<"102 Processing">>;
  483. status(200) -> <<"200 OK">>;
  484. status(201) -> <<"201 Created">>;
  485. status(202) -> <<"202 Accepted">>;
  486. status(203) -> <<"203 Non-Authoritative Information">>;
  487. status(204) -> <<"204 No Content">>;
  488. status(205) -> <<"205 Reset Content">>;
  489. status(206) -> <<"206 Partial Content">>;
  490. status(207) -> <<"207 Multi-Status">>;
  491. status(226) -> <<"226 IM Used">>;
  492. status(300) -> <<"300 Multiple Choices">>;
  493. status(301) -> <<"301 Moved Permanently">>;
  494. status(302) -> <<"302 Found">>;
  495. status(303) -> <<"303 See Other">>;
  496. status(304) -> <<"304 Not Modified">>;
  497. status(305) -> <<"305 Use Proxy">>;
  498. status(306) -> <<"306 Switch Proxy">>;
  499. status(307) -> <<"307 Temporary Redirect">>;
  500. status(400) -> <<"400 Bad Request">>;
  501. status(401) -> <<"401 Unauthorized">>;
  502. status(402) -> <<"402 Payment Required">>;
  503. status(403) -> <<"403 Forbidden">>;
  504. status(404) -> <<"404 Not Found">>;
  505. status(405) -> <<"405 Method Not Allowed">>;
  506. status(406) -> <<"406 Not Acceptable">>;
  507. status(407) -> <<"407 Proxy Authentication Required">>;
  508. status(408) -> <<"408 Request Timeout">>;
  509. status(409) -> <<"409 Conflict">>;
  510. status(410) -> <<"410 Gone">>;
  511. status(411) -> <<"411 Length Required">>;
  512. status(412) -> <<"412 Precondition Failed">>;
  513. status(413) -> <<"413 Request Entity Too Large">>;
  514. status(414) -> <<"414 Request-URI Too Long">>;
  515. status(415) -> <<"415 Unsupported Media Type">>;
  516. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  517. status(417) -> <<"417 Expectation Failed">>;
  518. status(418) -> <<"418 I'm a teapot">>;
  519. status(422) -> <<"422 Unprocessable Entity">>;
  520. status(423) -> <<"423 Locked">>;
  521. status(424) -> <<"424 Failed Dependency">>;
  522. status(425) -> <<"425 Unordered Collection">>;
  523. status(426) -> <<"426 Upgrade Required">>;
  524. status(500) -> <<"500 Internal Server Error">>;
  525. status(501) -> <<"501 Not Implemented">>;
  526. status(502) -> <<"502 Bad Gateway">>;
  527. status(503) -> <<"503 Service Unavailable">>;
  528. status(504) -> <<"504 Gateway Timeout">>;
  529. status(505) -> <<"505 HTTP Version Not Supported">>;
  530. status(506) -> <<"506 Variant Also Negotiates">>;
  531. status(507) -> <<"507 Insufficient Storage">>;
  532. status(510) -> <<"510 Not Extended">>;
  533. status(B) when is_binary(B) -> B.
  534. -spec header_to_binary(http_header()) -> binary().
  535. header_to_binary('Cache-Control') -> <<"Cache-Control">>;
  536. header_to_binary('Connection') -> <<"Connection">>;
  537. header_to_binary('Date') -> <<"Date">>;
  538. header_to_binary('Pragma') -> <<"Pragma">>;
  539. header_to_binary('Transfer-Encoding') -> <<"Transfer-Encoding">>;
  540. header_to_binary('Upgrade') -> <<"Upgrade">>;
  541. header_to_binary('Via') -> <<"Via">>;
  542. header_to_binary('Accept') -> <<"Accept">>;
  543. header_to_binary('Accept-Charset') -> <<"Accept-Charset">>;
  544. header_to_binary('Accept-Encoding') -> <<"Accept-Encoding">>;
  545. header_to_binary('Accept-Language') -> <<"Accept-Language">>;
  546. header_to_binary('Authorization') -> <<"Authorization">>;
  547. header_to_binary('From') -> <<"From">>;
  548. header_to_binary('Host') -> <<"Host">>;
  549. header_to_binary('If-Modified-Since') -> <<"If-Modified-Since">>;
  550. header_to_binary('If-Match') -> <<"If-Match">>;
  551. header_to_binary('If-None-Match') -> <<"If-None-Match">>;
  552. header_to_binary('If-Range') -> <<"If-Range">>;
  553. header_to_binary('If-Unmodified-Since') -> <<"If-Unmodified-Since">>;
  554. header_to_binary('Max-Forwards') -> <<"Max-Forwards">>;
  555. header_to_binary('Proxy-Authorization') -> <<"Proxy-Authorization">>;
  556. header_to_binary('Range') -> <<"Range">>;
  557. header_to_binary('Referer') -> <<"Referer">>;
  558. header_to_binary('User-Agent') -> <<"User-Agent">>;
  559. header_to_binary('Age') -> <<"Age">>;
  560. header_to_binary('Location') -> <<"Location">>;
  561. header_to_binary('Proxy-Authenticate') -> <<"Proxy-Authenticate">>;
  562. header_to_binary('Public') -> <<"Public">>;
  563. header_to_binary('Retry-After') -> <<"Retry-After">>;
  564. header_to_binary('Server') -> <<"Server">>;
  565. header_to_binary('Vary') -> <<"Vary">>;
  566. header_to_binary('Warning') -> <<"Warning">>;
  567. header_to_binary('Www-Authenticate') -> <<"Www-Authenticate">>;
  568. header_to_binary('Allow') -> <<"Allow">>;
  569. header_to_binary('Content-Base') -> <<"Content-Base">>;
  570. header_to_binary('Content-Encoding') -> <<"Content-Encoding">>;
  571. header_to_binary('Content-Language') -> <<"Content-Language">>;
  572. header_to_binary('Content-Length') -> <<"Content-Length">>;
  573. header_to_binary('Content-Location') -> <<"Content-Location">>;
  574. header_to_binary('Content-Md5') -> <<"Content-Md5">>;
  575. header_to_binary('Content-Range') -> <<"Content-Range">>;
  576. header_to_binary('Content-Type') -> <<"Content-Type">>;
  577. header_to_binary('Etag') -> <<"Etag">>;
  578. header_to_binary('Expires') -> <<"Expires">>;
  579. header_to_binary('Last-Modified') -> <<"Last-Modified">>;
  580. header_to_binary('Accept-Ranges') -> <<"Accept-Ranges">>;
  581. header_to_binary('Set-Cookie') -> <<"Set-Cookie">>;
  582. header_to_binary('Set-Cookie2') -> <<"Set-Cookie2">>;
  583. header_to_binary('X-Forwarded-For') -> <<"X-Forwarded-For">>;
  584. header_to_binary('Cookie') -> <<"Cookie">>;
  585. header_to_binary('Keep-Alive') -> <<"Keep-Alive">>;
  586. header_to_binary('Proxy-Connection') -> <<"Proxy-Connection">>;
  587. header_to_binary(B) when is_binary(B) -> B.
  588. %% Tests.
  589. -ifdef(TEST).
  590. parse_qs_test_() ->
  591. %% {Qs, Result}
  592. Tests = [
  593. {<<"">>, []},
  594. {<<"a=b">>, [{<<"a">>, <<"b">>}]},
  595. {<<"aaa=bbb">>, [{<<"aaa">>, <<"bbb">>}]},
  596. {<<"a&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
  597. {<<"a=b&c&d=e">>, [{<<"a">>, <<"b">>},
  598. {<<"c">>, true}, {<<"d">>, <<"e">>}]},
  599. {<<"a=b=c=d=e&f=g">>, [{<<"a">>, <<"b=c=d=e">>}, {<<"f">>, <<"g">>}]},
  600. {<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]}
  601. ],
  602. [{Qs, fun() -> R = parse_qs(Qs) end} || {Qs, R} <- Tests].
  603. -endif.