cowboy_http_req.erl 23 KB

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