cowboy_dispatcher.erl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 Dispatch requests according to a hostname and path.
  16. -module(cowboy_dispatcher).
  17. -export([split_host/1, split_path/2, match/3]). %% API.
  18. -type bindings() :: list({atom(), binary()}).
  19. -type tokens() :: list(binary()).
  20. -type match_rule() :: '_' | '*' | list(binary() | '_' | '...' | atom()).
  21. -type dispatch_path() :: list({match_rule(), module(), any()}).
  22. -type dispatch_rule() :: {Host::match_rule(), Path::dispatch_path()}.
  23. -type dispatch_rules() :: list(dispatch_rule()).
  24. -export_type([bindings/0, tokens/0, dispatch_rules/0]).
  25. -include_lib("eunit/include/eunit.hrl").
  26. %% API.
  27. %% @doc Split a hostname into a list of tokens.
  28. -spec split_host(binary())
  29. -> {tokens(), binary(), undefined | inet:ip_port()}.
  30. split_host(<<>>) ->
  31. {[], <<>>, undefined};
  32. split_host(Host) ->
  33. case binary:split(Host, <<":">>) of
  34. [Host] ->
  35. {binary:split(Host, <<".">>, [global, trim]), Host, undefined};
  36. [Host2, Port] ->
  37. {binary:split(Host2, <<".">>, [global, trim]), Host2,
  38. list_to_integer(binary_to_list(Port))}
  39. end.
  40. %% @doc Split a path into a list of path segments.
  41. %%
  42. %% Following RFC2396, this function may return path segments containing any
  43. %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped
  44. %% and part of a path segment.
  45. -spec split_path(binary(), fun((binary()) -> binary())) ->
  46. {tokens(), binary(), binary()}.
  47. split_path(Path, URLDec) ->
  48. case binary:split(Path, <<"?">>) of
  49. [Path] -> {do_split_path(Path, <<"/">>, URLDec), Path, <<>>};
  50. [<<>>, Qs] -> {[], <<>>, Qs};
  51. [Path2, Qs] -> {do_split_path(Path2, <<"/">>, URLDec), Path2, Qs}
  52. end.
  53. -spec do_split_path(binary(), <<_:8>>, fun((binary()) -> binary())) -> tokens().
  54. do_split_path(RawPath, Separator, URLDec) ->
  55. EncodedPath = case binary:split(RawPath, Separator, [global, trim]) of
  56. [<<>>|Path] -> Path;
  57. Path -> Path
  58. end,
  59. [URLDec(Token) || Token <- EncodedPath].
  60. %% @doc Match hostname tokens and path tokens against dispatch rules.
  61. %%
  62. %% It is typically used for matching tokens for the hostname and path of
  63. %% the request against a global dispatch rule for your listener.
  64. %%
  65. %% Dispatch rules are a list of <em>{Hostname, PathRules}</em> tuples, with
  66. %% <em>PathRules</em> being a list of <em>{Path, HandlerMod, HandlerOpts}</em>.
  67. %%
  68. %% <em>Hostname</em> and <em>Path</em> are match rules and can be either the
  69. %% atom <em>'_'</em>, which matches everything for a single token, the atom
  70. %% <em>'*'</em>, which matches everything for the rest of the tokens, or a
  71. %% list of tokens. Each token can be either a binary, the atom <em>'_'</em>,
  72. %% the atom '...' or a named atom. A binary token must match exactly,
  73. %% <em>'_'</em> matches everything for a single token, <em>'...'</em> matches
  74. %% everything for the rest of the tokens and a named atom will bind the
  75. %% corresponding token value and return it.
  76. %%
  77. %% The list of hostname tokens is reversed before matching. For example, if
  78. %% we were to match "www.dev-extend.eu", we would first match "eu", then
  79. %% "dev-extend", then "www". This means that in the context of hostnames,
  80. %% the <em>'...'</em> atom matches properly the lower levels of the domain
  81. %% as would be expected.
  82. %%
  83. %% When a result is found, this function will return the handler module and
  84. %% options found in the dispatch list, a key-value list of bindings and
  85. %% the tokens that were matched by the <em>'...'</em> atom for both the
  86. %% hostname and path.
  87. -spec match(Host::tokens(), Path::tokens(), dispatch_rules())
  88. -> {ok, module(), any(), bindings(),
  89. HostInfo::undefined | tokens(),
  90. PathInfo::undefined | tokens()}
  91. | {error, notfound, host} | {error, notfound, path}.
  92. match(_Host, _Path, []) ->
  93. {error, notfound, host};
  94. match(_Host, Path, [{'_', PathMatchs}|_Tail]) ->
  95. match_path(Path, PathMatchs, [], undefined);
  96. match(Host, Path, [{HostMatch, PathMatchs}|Tail]) ->
  97. case try_match(host, Host, HostMatch) of
  98. false ->
  99. match(Host, Path, Tail);
  100. {true, HostBinds, undefined} ->
  101. match_path(Path, PathMatchs, HostBinds, undefined);
  102. {true, HostBinds, HostInfo} ->
  103. match_path(Path, PathMatchs, HostBinds, lists:reverse(HostInfo))
  104. end.
  105. -spec match_path(tokens(), dispatch_path(), bindings(),
  106. HostInfo::undefined | tokens())
  107. -> {ok, module(), any(), bindings(),
  108. HostInfo::undefined | tokens(),
  109. PathInfo::undefined | tokens()}
  110. | {error, notfound, path}.
  111. match_path(_Path, [], _HostBinds, _HostInfo) ->
  112. {error, notfound, path};
  113. match_path(_Path, [{'_', Handler, Opts}|_Tail], HostBinds, HostInfo) ->
  114. {ok, Handler, Opts, HostBinds, HostInfo, undefined};
  115. match_path('*', [{'*', Handler, Opts}|_Tail], HostBinds, HostInfo) ->
  116. {ok, Handler, Opts, HostBinds, HostInfo, undefined};
  117. match_path(Path, [{PathMatch, Handler, Opts}|Tail], HostBinds, HostInfo) ->
  118. case try_match(path, Path, PathMatch) of
  119. false ->
  120. match_path(Path, Tail, HostBinds, HostInfo);
  121. {true, PathBinds, PathInfo} ->
  122. {ok, Handler, Opts, HostBinds ++ PathBinds, HostInfo, PathInfo}
  123. end.
  124. %% Internal.
  125. -spec try_match(host | path, tokens(), match_rule())
  126. -> {true, bindings(), undefined | tokens()} | false.
  127. try_match(host, List, Match) ->
  128. list_match(lists:reverse(List), lists:reverse(Match), []);
  129. try_match(path, List, Match) ->
  130. list_match(List, Match, []).
  131. -spec list_match(tokens(), match_rule(), bindings())
  132. -> {true, bindings(), undefined | tokens()} | false.
  133. %% Atom '...' matches any trailing path, stop right now.
  134. list_match(List, ['...'], Binds) ->
  135. {true, Binds, List};
  136. %% Atom '_' matches anything, continue.
  137. list_match([_E|Tail], ['_'|TailMatch], Binds) ->
  138. list_match(Tail, TailMatch, Binds);
  139. %% Both values match, continue.
  140. list_match([E|Tail], [E|TailMatch], Binds) ->
  141. list_match(Tail, TailMatch, Binds);
  142. %% Bind E to the variable name V and continue.
  143. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) ->
  144. list_match(Tail, TailMatch, [{V, E}|Binds]);
  145. %% Match complete.
  146. list_match([], [], Binds) ->
  147. {true, Binds, undefined};
  148. %% Values don't match, stop.
  149. list_match(_List, _Match, _Binds) ->
  150. false.
  151. %% Tests.
  152. -ifdef(TEST).
  153. split_host_test_() ->
  154. %% {Host, Result}
  155. Tests = [
  156. {<<"">>, {[], <<"">>, undefined}},
  157. {<<".........">>, {[], <<".........">>, undefined}},
  158. {<<"*">>, {[<<"*">>], <<"*">>, undefined}},
  159. {<<"cowboy.dev-extend.eu">>,
  160. {[<<"cowboy">>, <<"dev-extend">>, <<"eu">>],
  161. <<"cowboy.dev-extend.eu">>, undefined}},
  162. {<<"dev-extend..eu">>,
  163. {[<<"dev-extend">>, <<>>, <<"eu">>],
  164. <<"dev-extend..eu">>, undefined}},
  165. {<<"dev-extend.eu">>,
  166. {[<<"dev-extend">>, <<"eu">>], <<"dev-extend.eu">>, undefined}},
  167. {<<"dev-extend.eu:8080">>,
  168. {[<<"dev-extend">>, <<"eu">>], <<"dev-extend.eu">>, 8080}},
  169. {<<"a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z">>,
  170. {[<<"a">>, <<"b">>, <<"c">>, <<"d">>, <<"e">>, <<"f">>, <<"g">>,
  171. <<"h">>, <<"i">>, <<"j">>, <<"k">>, <<"l">>, <<"m">>, <<"n">>,
  172. <<"o">>, <<"p">>, <<"q">>, <<"r">>, <<"s">>, <<"t">>, <<"u">>,
  173. <<"v">>, <<"w">>, <<"x">>, <<"y">>, <<"z">>],
  174. <<"a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z">>,
  175. undefined}}
  176. ],
  177. [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests].
  178. split_host_fail_test_() ->
  179. Tests = [
  180. <<"dev-extend.eu:owns">>,
  181. <<"dev-extend.eu: owns">>,
  182. <<"dev-extend.eu:42fun">>,
  183. <<"dev-extend.eu: 42fun">>,
  184. <<"dev-extend.eu:42 fun">>,
  185. <<"dev-extend.eu:fun 42">>,
  186. <<"dev-extend.eu: 42">>,
  187. <<":owns">>,
  188. <<":42 fun">>
  189. ],
  190. [{H, fun() -> case catch split_host(H) of
  191. {'EXIT', _Reason} -> ok
  192. end end} || H <- Tests].
  193. split_path_test_() ->
  194. %% {Path, Result, QueryString}
  195. Tests = [
  196. {<<"?">>, [], <<"">>, <<"">>},
  197. {<<"???">>, [], <<"">>, <<"??">>},
  198. {<<"/">>, [], <<"/">>, <<"">>},
  199. {<<"/users">>, [<<"users">>], <<"/users">>, <<"">>},
  200. {<<"/users?">>, [<<"users">>], <<"/users">>, <<"">>},
  201. {<<"/users?a">>, [<<"users">>], <<"/users">>, <<"a">>},
  202. {<<"/users/42/friends?a=b&c=d&e=notsure?whatever">>,
  203. [<<"users">>, <<"42">>, <<"friends">>],
  204. <<"/users/42/friends">>, <<"a=b&c=d&e=notsure?whatever">>},
  205. {<<"/users/a+b/c%21d?e+f=g+h">>,
  206. [<<"users">>, <<"a b">>, <<"c!d">>],
  207. <<"/users/a+b/c%21d">>, <<"e+f=g+h">>}
  208. ],
  209. URLDecode = fun(Bin) -> cowboy_http:urldecode(Bin, crash) end,
  210. [{P, fun() -> {R, RawP, Qs} = split_path(P, URLDecode) end}
  211. || {P, R, RawP, Qs} <- Tests].
  212. match_test_() ->
  213. Dispatch = [
  214. {[<<"www">>, '_', <<"dev-extend">>, <<"eu">>], [
  215. {[<<"users">>, '_', <<"mails">>], match_any_subdomain_users, []}
  216. ]},
  217. {[<<"dev-extend">>, <<"eu">>], [
  218. {[<<"users">>, id, <<"friends">>], match_extend_users_friends, []},
  219. {'_', match_extend, []}
  220. ]},
  221. {[<<"dev-extend">>, var], [
  222. {[<<"threads">>, var], match_duplicate_vars,
  223. [we, {expect, two}, var, here]}
  224. ]},
  225. {[<<"erlang">>, ext], [
  226. {'_', match_erlang_ext, []}
  227. ]},
  228. {'_', [
  229. {[<<"users">>, id, <<"friends">>], match_users_friends, []},
  230. {'_', match_any, []}
  231. ]}
  232. ],
  233. %% {Host, Path, Result}
  234. Tests = [
  235. {[<<"any">>], [], {ok, match_any, [], []}},
  236. {[<<"www">>, <<"any">>, <<"dev-extend">>, <<"eu">>],
  237. [<<"users">>, <<"42">>, <<"mails">>],
  238. {ok, match_any_subdomain_users, [], []}},
  239. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  240. [<<"users">>, <<"42">>, <<"mails">>], {ok, match_any, [], []}},
  241. {[<<"www">>, <<"dev-extend">>, <<"eu">>], [], {ok, match_any, [], []}},
  242. {[<<"www">>, <<"any">>, <<"dev-extend">>, <<"eu">>],
  243. [<<"not_users">>, <<"42">>, <<"mails">>], {error, notfound, path}},
  244. {[<<"dev-extend">>, <<"eu">>], [], {ok, match_extend, [], []}},
  245. {[<<"dev-extend">>, <<"eu">>], [<<"users">>, <<"42">>, <<"friends">>],
  246. {ok, match_extend_users_friends, [], [{id, <<"42">>}]}},
  247. {[<<"erlang">>, <<"fr">>], '_',
  248. {ok, match_erlang_ext, [], [{ext, <<"fr">>}]}},
  249. {[<<"any">>], [<<"users">>, <<"444">>, <<"friends">>],
  250. {ok, match_users_friends, [], [{id, <<"444">>}]}},
  251. {[<<"dev-extend">>, <<"fr">>], [<<"threads">>, <<"987">>],
  252. {ok, match_duplicate_vars, [we, {expect, two}, var, here],
  253. [{var, <<"fr">>}, {var, <<"987">>}]}}
  254. ],
  255. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  256. {ok, Handler, Opts, Binds, undefined, undefined} = match(H, P, Dispatch)
  257. end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests].
  258. match_info_test_() ->
  259. Dispatch = [
  260. {[<<"www">>, <<"dev-extend">>, <<"eu">>], [
  261. {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], match_path, []}
  262. ]},
  263. {['...', <<"dev-extend">>, <<"eu">>], [
  264. {'_', match_any, []}
  265. ]}
  266. ],
  267. Tests = [
  268. {[<<"dev-extend">>, <<"eu">>], [],
  269. {ok, match_any, [], [], [], undefined}},
  270. {[<<"bugs">>, <<"dev-extend">>, <<"eu">>], [],
  271. {ok, match_any, [], [], [<<"bugs">>], undefined}},
  272. {[<<"cowboy">>, <<"bugs">>, <<"dev-extend">>, <<"eu">>], [],
  273. {ok, match_any, [], [], [<<"cowboy">>, <<"bugs">>], undefined}},
  274. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  275. [<<"pathinfo">>, <<"is">>, <<"next">>],
  276. {ok, match_path, [], [], undefined, []}},
  277. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  278. [<<"pathinfo">>, <<"is">>, <<"next">>, <<"path_info">>],
  279. {ok, match_path, [], [], undefined, [<<"path_info">>]}},
  280. {[<<"www">>, <<"dev-extend">>, <<"eu">>],
  281. [<<"pathinfo">>, <<"is">>, <<"next">>, <<"foo">>, <<"bar">>],
  282. {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}}
  283. ],
  284. [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() ->
  285. R = match(H, P, Dispatch)
  286. end} || {H, P, R} <- Tests].
  287. -endif.