Commits

Anonymous committed 5a6d89b

Better handling of Webmachine hostspecs.

When to setup the Mochiweb socket listeners, we may get into problems
if the hostspecs consists of wildcards and "variables".

We'll try and do the best we can by filtering out sane Hostnames and
by checking that the corresponding IP addresses can be found.

Comments (0)

Files changed (1)

src/webmachine_mochiweb.erl

             Port = getenv("WEBMACHINE_PORT", "8000"),
             [[{loop, fun loop/1},
               {ip, Ip},
-              {port, list_to_integer(Port)} | Options]];
+              {port, l2i(Port)} | Options]];
         IpPorts ->
             [[{loop, fun loop/1},
-              {ip, host2ip(Ip)},
+              {ip, Ip},
               {port, Port} | Options] 
-             || {Ip, Port} <- IpPorts]
+             || {Ip, Port} <- sanitize_ipports(IpPorts)]
     end.
 
+%% Nb: We may get into problems here if the host spec
+%% consists of wildcards and "variables". We'll try and
+%% do the best we can by filtering out sane Hosts and
+%% check that the corresponding IP address can be found.
+sanitize_ipports(IpPorts) -> 
+    sanitize_ipports(IpPorts, ordsets:new()).
+    
+sanitize_ipports([{HostSpec,Port}|Tail], Dict) ->
+    Host = string:join([E || E <- HostSpec,is_list(E),E /= "*"], "."),
+    case host2ip(Host) of
+        {ok, Ip} ->
+            sanitize_ipports(Tail, ordsets:add_element({Ip,l2i(Port)},Dict));
+        {error, X} ->
+            error_logger:info_msg(
+              "~p(~p): failed to lookup Host=~p, ignoring this hostspec...~n",
+              [?MODULE,?LINE,X]),
+            sanitize_ipports(Tail, Dict)
+    end;
+sanitize_ipports([], Dict) ->
+    ordsets:to_list(Dict).
+
+l2i(L) when is_list(L)    -> list_to_integer(L);
+l2i(I) when is_integer(I) -> I.
+        
+
 getenv(Var, Default) ->
     case os:getenv(Var) of false -> Default; Any -> Any end.
 
 %% Try to return an IP address since that is what mochiweb wants.
 host2ip(X) ->
     case inet_parse:address(X) of
-        {ok, _IpTuple} -> X;
+        {ok, _IpTuple} -> {ok,X};
         _ ->
             case inet:gethostbyname(X) of
-                {ok,#hostent{h_addr_list=[Ip|_]}} -> Ip;
-                _                                 -> X
+                {ok,#hostent{h_addr_list=[Ip|_]}} -> {ok,Ip};
+                _                                 -> {error,X}
             end
     end.