cowboy_http_req.erl 26 KB

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