cow_http.erl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. %% Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(cow_http).
  15. %% @todo parse_request_line
  16. -export([parse_status_line/1]).
  17. -export([parse_headers/1]).
  18. -export([parse_fullpath/1]).
  19. -export([parse_version/1]).
  20. -export([request/4]).
  21. -export([response/3]).
  22. -export([version/1]).
  23. -type version() :: 'HTTP/1.0' | 'HTTP/1.1'.
  24. -type status() :: 100..999.
  25. -type headers() :: [{binary(), iodata()}].
  26. -include("cow_inline.hrl").
  27. %% @doc Parse the status line.
  28. -spec parse_status_line(binary()) -> {version(), status(), binary(), binary()}.
  29. parse_status_line(<< "HTTP/1.1 200 OK\r\n", Rest/bits >>) ->
  30. {'HTTP/1.1', 200, <<"OK">>, Rest};
  31. parse_status_line(<< "HTTP/1.1 404 Not Found\r\n", Rest/bits >>) ->
  32. {'HTTP/1.1', 404, <<"Not Found">>, Rest};
  33. parse_status_line(<< "HTTP/1.1 500 Internal Server Error\r\n", Rest/bits >>) ->
  34. {'HTTP/1.1', 500, <<"Internal Server Error">>, Rest};
  35. parse_status_line(<< "HTTP/1.1 ", Status/bits >>) ->
  36. parse_status_line(Status, 'HTTP/1.1');
  37. parse_status_line(<< "HTTP/1.0 ", Status/bits >>) ->
  38. parse_status_line(Status, 'HTTP/1.0').
  39. parse_status_line(<< H, T, U, " ", Rest/bits >>, Version)
  40. when $0 =< H, H =< $9, $0 =< T, T =< $9, $0 =< U, U =< $9 ->
  41. Status = (H - $0) * 100 + (T - $0) * 10 + (U - $0),
  42. {Pos, _} = binary:match(Rest, <<"\r">>),
  43. << StatusStr:Pos/binary, "\r\n", Rest2/bits >> = Rest,
  44. {Version, Status, StatusStr, Rest2}.
  45. -ifdef(TEST).
  46. parse_status_line_test_() ->
  47. Tests = [
  48. {<<"HTTP/1.1 200 OK\r\nRest">>,
  49. {'HTTP/1.1', 200, <<"OK">>, <<"Rest">>}},
  50. {<<"HTTP/1.0 404 Not Found\r\nRest">>,
  51. {'HTTP/1.0', 404, <<"Not Found">>, <<"Rest">>}},
  52. {<<"HTTP/1.1 500 Something very funny here\r\nRest">>,
  53. {'HTTP/1.1', 500, <<"Something very funny here">>, <<"Rest">>}},
  54. {<<"HTTP/1.1 200 \r\nRest">>,
  55. {'HTTP/1.1', 200, <<>>, <<"Rest">>}}
  56. ],
  57. [{V, fun() -> R = parse_status_line(V) end}
  58. || {V, R} <- Tests].
  59. parse_status_line_error_test_() ->
  60. Tests = [
  61. <<>>,
  62. <<"HTTP/1.1">>,
  63. <<"HTTP/1.1 200\r\n">>,
  64. <<"HTTP/1.1 200 OK">>,
  65. <<"HTTP/1.1 200 OK\r">>,
  66. <<"HTTP/1.1 200 OK\n">>,
  67. <<"HTTP/0.9 200 OK\r\n">>,
  68. <<"HTTP/1.1 42 Answer\r\n">>,
  69. <<"HTTP/1.1 999999999 More than OK\r\n">>,
  70. <<"content-type: text/plain\r\n">>,
  71. <<0:80, "\r\n">>
  72. ],
  73. [{V, fun() -> {'EXIT', _} = (catch parse_status_line(V)) end}
  74. || V <- Tests].
  75. horse_parse_status_line_200() ->
  76. horse:repeat(200000,
  77. parse_status_line(<<"HTTP/1.1 200 OK\r\n">>)
  78. ).
  79. horse_parse_status_line_404() ->
  80. horse:repeat(200000,
  81. parse_status_line(<<"HTTP/1.1 404 Not Found\r\n">>)
  82. ).
  83. horse_parse_status_line_500() ->
  84. horse:repeat(200000,
  85. parse_status_line(<<"HTTP/1.1 500 Internal Server Error\r\n">>)
  86. ).
  87. horse_parse_status_line_other() ->
  88. horse:repeat(200000,
  89. parse_status_line(<<"HTTP/1.1 416 Requested range not satisfiable\r\n">>)
  90. ).
  91. -endif.
  92. %% @doc Parse the list of headers.
  93. -spec parse_headers(binary()) -> {[{binary(), binary()}], binary()}.
  94. parse_headers(Data) ->
  95. parse_header(Data, []).
  96. parse_header(<< $\r, $\n, Rest/bits >>, Acc) ->
  97. {lists:reverse(Acc), Rest};
  98. parse_header(Data, Acc) ->
  99. parse_hd_name(Data, Acc, <<>>).
  100. parse_hd_name(<< C, Rest/bits >>, Acc, SoFar) ->
  101. case C of
  102. $: -> parse_hd_before_value(Rest, Acc, SoFar);
  103. $\s -> parse_hd_name_ws(Rest, Acc, SoFar);
  104. $\t -> parse_hd_name_ws(Rest, Acc, SoFar);
  105. _ -> ?LOWER(parse_hd_name, Rest, Acc, SoFar)
  106. end.
  107. parse_hd_name_ws(<< C, Rest/bits >>, Acc, Name) ->
  108. case C of
  109. $: -> parse_hd_before_value(Rest, Acc, Name);
  110. $\s -> parse_hd_name_ws(Rest, Acc, Name);
  111. $\t -> parse_hd_name_ws(Rest, Acc, Name)
  112. end.
  113. parse_hd_before_value(<< $\s, Rest/bits >>, Acc, Name) ->
  114. parse_hd_before_value(Rest, Acc, Name);
  115. parse_hd_before_value(<< $\t, Rest/bits >>, Acc, Name) ->
  116. parse_hd_before_value(Rest, Acc, Name);
  117. parse_hd_before_value(Data, Acc, Name) ->
  118. parse_hd_value(Data, Acc, Name, <<>>).
  119. parse_hd_value(<< $\r, Rest/bits >>, Acc, Name, SoFar) ->
  120. case Rest of
  121. << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t ->
  122. parse_hd_value(Rest2, Acc, Name, << SoFar/binary, C >>);
  123. << $\n, Rest2/bits >> ->
  124. parse_header(Rest2, [{Name, SoFar}|Acc])
  125. end;
  126. parse_hd_value(<< C, Rest/bits >>, Acc, Name, SoFar) ->
  127. parse_hd_value(Rest, Acc, Name, << SoFar/binary, C >>).
  128. -ifdef(TEST).
  129. parse_headers_test_() ->
  130. Tests = [
  131. {<<"\r\nRest">>,
  132. {[], <<"Rest">>}},
  133. {<<"Server: Erlang/R17\r\n"
  134. "Date: Sun, 23 Feb 2014 09:30:39 GMT\r\n"
  135. "Multiline-Header: why hello!\r\n"
  136. " I didn't see you all the way over there!\r\n"
  137. "Content-Length: 12\r\n"
  138. "Content-Type: text/plain\r\n"
  139. "\r\nRest">>,
  140. {[{<<"server">>, <<"Erlang/R17">>},
  141. {<<"date">>, <<"Sun, 23 Feb 2014 09:30:39 GMT">>},
  142. {<<"multiline-header">>,
  143. <<"why hello! I didn't see you all the way over there!">>},
  144. {<<"content-length">>, <<"12">>},
  145. {<<"content-type">>, <<"text/plain">>}],
  146. <<"Rest">>}}
  147. ],
  148. [{V, fun() -> R = parse_headers(V) end}
  149. || {V, R} <- Tests].
  150. parse_headers_error_test_() ->
  151. Tests = [
  152. <<>>,
  153. <<"\r">>,
  154. <<"Malformed\r\n\r\n">>,
  155. <<"content-type: text/plain\r\nMalformed\r\n\r\n">>,
  156. <<"HTTP/1.1 200 OK\r\n\r\n">>,
  157. <<0:80, "\r\n\r\n">>,
  158. <<"content-type: text/plain\r\ncontent-length: 12\r\n">>
  159. ],
  160. [{V, fun() -> {'EXIT', _} = (catch parse_headers(V)) end}
  161. || V <- Tests].
  162. horse_parse_headers() ->
  163. horse:repeat(50000,
  164. parse_headers(<<"Server: Erlang/R17\r\n"
  165. "Date: Sun, 23 Feb 2014 09:30:39 GMT\r\n"
  166. "Multiline-Header: why hello!\r\n"
  167. " I didn't see you all the way over there!\r\n"
  168. "Content-Length: 12\r\n"
  169. "Content-Type: text/plain\r\n"
  170. "\r\nRest">>)
  171. ).
  172. -endif.
  173. %% @doc Extract path and query string from a binary,
  174. %% removing any fragment component.
  175. -spec parse_fullpath(binary()) -> {binary(), binary()}.
  176. parse_fullpath(Fullpath) ->
  177. parse_fullpath(Fullpath, <<>>).
  178. parse_fullpath(<<>>, Path) -> {Path, <<>>};
  179. parse_fullpath(<< $#, _/bits >>, Path) -> {Path, <<>>};
  180. parse_fullpath(<< $?, Qs/bits >>, Path) -> parse_fullpath_query(Qs, Path, <<>>);
  181. parse_fullpath(<< C, Rest/bits >>, SoFar) -> parse_fullpath(Rest, << SoFar/binary, C >>).
  182. parse_fullpath_query(<<>>, Path, Query) -> {Path, Query};
  183. parse_fullpath_query(<< $#, _/bits >>, Path, Query) -> {Path, Query};
  184. parse_fullpath_query(<< C, Rest/bits >>, Path, SoFar) ->
  185. parse_fullpath_query(Rest, Path, << SoFar/binary, C >>).
  186. -ifdef(TEST).
  187. parse_fullpath_test() ->
  188. {<<"*">>, <<>>} = parse_fullpath(<<"*">>),
  189. {<<"/">>, <<>>} = parse_fullpath(<<"/">>),
  190. {<<"/path/to/resource">>, <<>>} = parse_fullpath(<<"/path/to/resource#fragment">>),
  191. {<<"/path/to/resource">>, <<>>} = parse_fullpath(<<"/path/to/resource">>),
  192. {<<"/">>, <<>>} = parse_fullpath(<<"/?">>),
  193. {<<"/">>, <<"q=cowboy">>} = parse_fullpath(<<"/?q=cowboy#fragment">>),
  194. {<<"/">>, <<"q=cowboy">>} = parse_fullpath(<<"/?q=cowboy">>),
  195. {<<"/path/to/resource">>, <<"q=cowboy">>}
  196. = parse_fullpath(<<"/path/to/resource?q=cowboy">>),
  197. ok.
  198. -endif.
  199. %% @doc Convert an HTTP version to atom.
  200. -spec parse_version(binary()) -> version().
  201. parse_version(<<"HTTP/1.1">>) -> 'HTTP/1.1';
  202. parse_version(<<"HTTP/1.0">>) -> 'HTTP/1.0'.
  203. -ifdef(TEST).
  204. parse_version_test() ->
  205. 'HTTP/1.1' = parse_version(<<"HTTP/1.1">>),
  206. 'HTTP/1.0' = parse_version(<<"HTTP/1.0">>),
  207. {'EXIT', _} = (catch parse_version(<<"HTTP/1.2">>)),
  208. ok.
  209. -endif.
  210. %% @doc Return formatted request-line and headers.
  211. %% @todo Add tests when the corresponding reverse functions are added.
  212. -spec request(binary(), iodata(), version(), headers()) -> iodata().
  213. request(Method, Path, Version, Headers) ->
  214. [Method, <<" ">>, Path, <<" ">>, version(Version), <<"\r\n">>,
  215. [[N, <<": ">>, V, <<"\r\n">>] || {N, V} <- Headers],
  216. <<"\r\n">>].
  217. -spec response(status() | binary(), version(), headers()) -> iodata().
  218. response(Status, Version, Headers) ->
  219. [version(Version), <<" ">>, status(Status), <<"\r\n">>,
  220. [[N, <<": ">>, V, <<"\r\n">>] || {N, V} <- Headers],
  221. <<"\r\n">>].
  222. %% @doc Return the version as a binary.
  223. -spec version(version()) -> binary().
  224. version('HTTP/1.1') -> <<"HTTP/1.1">>;
  225. version('HTTP/1.0') -> <<"HTTP/1.0">>.
  226. -ifdef(TEST).
  227. version_test() ->
  228. <<"HTTP/1.1">> = version('HTTP/1.1'),
  229. <<"HTTP/1.0">> = version('HTTP/1.0'),
  230. {'EXIT', _} = (catch version('HTTP/1.2')),
  231. ok.
  232. -endif.
  233. %% @doc Return the status code and string as binary.
  234. -spec status(status() | binary()) -> binary().
  235. status(100) -> <<"100 Continue">>;
  236. status(101) -> <<"101 Switching Protocols">>;
  237. status(102) -> <<"102 Processing">>;
  238. status(200) -> <<"200 OK">>;
  239. status(201) -> <<"201 Created">>;
  240. status(202) -> <<"202 Accepted">>;
  241. status(203) -> <<"203 Non-Authoritative Information">>;
  242. status(204) -> <<"204 No Content">>;
  243. status(205) -> <<"205 Reset Content">>;
  244. status(206) -> <<"206 Partial Content">>;
  245. status(207) -> <<"207 Multi-Status">>;
  246. status(226) -> <<"226 IM Used">>;
  247. status(300) -> <<"300 Multiple Choices">>;
  248. status(301) -> <<"301 Moved Permanently">>;
  249. status(302) -> <<"302 Found">>;
  250. status(303) -> <<"303 See Other">>;
  251. status(304) -> <<"304 Not Modified">>;
  252. status(305) -> <<"305 Use Proxy">>;
  253. status(306) -> <<"306 Switch Proxy">>;
  254. status(307) -> <<"307 Temporary Redirect">>;
  255. status(400) -> <<"400 Bad Request">>;
  256. status(401) -> <<"401 Unauthorized">>;
  257. status(402) -> <<"402 Payment Required">>;
  258. status(403) -> <<"403 Forbidden">>;
  259. status(404) -> <<"404 Not Found">>;
  260. status(405) -> <<"405 Method Not Allowed">>;
  261. status(406) -> <<"406 Not Acceptable">>;
  262. status(407) -> <<"407 Proxy Authentication Required">>;
  263. status(408) -> <<"408 Request Timeout">>;
  264. status(409) -> <<"409 Conflict">>;
  265. status(410) -> <<"410 Gone">>;
  266. status(411) -> <<"411 Length Required">>;
  267. status(412) -> <<"412 Precondition Failed">>;
  268. status(413) -> <<"413 Request Entity Too Large">>;
  269. status(414) -> <<"414 Request-URI Too Long">>;
  270. status(415) -> <<"415 Unsupported Media Type">>;
  271. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  272. status(417) -> <<"417 Expectation Failed">>;
  273. status(418) -> <<"418 I'm a teapot">>;
  274. status(422) -> <<"422 Unprocessable Entity">>;
  275. status(423) -> <<"423 Locked">>;
  276. status(424) -> <<"424 Failed Dependency">>;
  277. status(425) -> <<"425 Unordered Collection">>;
  278. status(426) -> <<"426 Upgrade Required">>;
  279. status(428) -> <<"428 Precondition Required">>;
  280. status(429) -> <<"429 Too Many Requests">>;
  281. status(431) -> <<"431 Request Header Fields Too Large">>;
  282. status(500) -> <<"500 Internal Server Error">>;
  283. status(501) -> <<"501 Not Implemented">>;
  284. status(502) -> <<"502 Bad Gateway">>;
  285. status(503) -> <<"503 Service Unavailable">>;
  286. status(504) -> <<"504 Gateway Timeout">>;
  287. status(505) -> <<"505 HTTP Version Not Supported">>;
  288. status(506) -> <<"506 Variant Also Negotiates">>;
  289. status(507) -> <<"507 Insufficient Storage">>;
  290. status(510) -> <<"510 Not Extended">>;
  291. status(511) -> <<"511 Network Authentication Required">>;
  292. status(B) when is_binary(B) -> B.