cowboy_dispatcher.erl 12 KB

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