NetworkUtil.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Net.Sockets;
  30. using System.Net;
  31. using System.Net.NetworkInformation;
  32. using System.Reflection;
  33. using System.Text;
  34. using log4net;
  35. namespace OpenSim.Framework
  36. {
  37. /// <summary>
  38. /// Handles NAT translation in a 'manner of speaking'
  39. /// Allows you to return multiple different external
  40. /// hostnames depending on the requestors network
  41. ///
  42. /// This enables standard port forwarding techniques
  43. /// to work correctly with OpenSim.
  44. /// </summary>
  45. public static class NetworkUtil
  46. {
  47. // Logger
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private static bool m_disabled = true;
  50. public static bool Enabled
  51. {
  52. set { m_disabled = value; }
  53. get { return m_disabled; }
  54. }
  55. // IPv4Address, Subnet
  56. static readonly Dictionary<IPAddress,IPAddress> m_subnets = new Dictionary<IPAddress, IPAddress>();
  57. public static IPAddress GetIPFor(IPAddress user, IPAddress simulator)
  58. {
  59. if (m_disabled)
  60. return simulator;
  61. // Check if we're accessing localhost.
  62. foreach (IPAddress host in Dns.GetHostAddresses(Dns.GetHostName()))
  63. {
  64. if (host.Equals(user) && host.AddressFamily == AddressFamily.InterNetwork)
  65. {
  66. m_log.Info("[NetworkUtil] Localhost user detected, sending them '" + host + "' instead of '" + simulator + "'");
  67. return host;
  68. }
  69. }
  70. // Check for same LAN segment
  71. foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets)
  72. {
  73. byte[] subnetBytes = subnet.Value.GetAddressBytes();
  74. byte[] localBytes = subnet.Key.GetAddressBytes();
  75. byte[] destBytes = user.GetAddressBytes();
  76. if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length)
  77. return null;
  78. bool valid = true;
  79. for (int i = 0; i < subnetBytes.Length; i++)
  80. {
  81. if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i]))
  82. {
  83. valid = false;
  84. break;
  85. }
  86. }
  87. if (subnet.Key.AddressFamily != AddressFamily.InterNetwork)
  88. valid = false;
  89. if (valid)
  90. {
  91. m_log.Info("[NetworkUtil] Local LAN user detected, sending them '" + subnet.Key + "' instead of '" + simulator + "'");
  92. return subnet.Key;
  93. }
  94. }
  95. // Otherwise, return outside address
  96. return simulator;
  97. }
  98. private static IPAddress GetExternalIPFor(IPAddress destination, string defaultHostname)
  99. {
  100. // Adds IPv6 Support (Not that any of the major protocols supports it...)
  101. if (destination.AddressFamily == AddressFamily.InterNetworkV6)
  102. {
  103. foreach (IPAddress host in Dns.GetHostAddresses(defaultHostname))
  104. {
  105. if (host.AddressFamily == AddressFamily.InterNetworkV6)
  106. {
  107. m_log.Info("[NetworkUtil] Localhost user detected, sending them '" + host + "' instead of '" + defaultHostname + "'");
  108. return host;
  109. }
  110. }
  111. }
  112. if (destination.AddressFamily != AddressFamily.InterNetwork)
  113. return null;
  114. // Check if we're accessing localhost.
  115. foreach (KeyValuePair<IPAddress, IPAddress> pair in m_subnets)
  116. {
  117. IPAddress host = pair.Value;
  118. if (host.Equals(destination) && host.AddressFamily == AddressFamily.InterNetwork)
  119. {
  120. m_log.Info("[NATROUTING] Localhost user detected, sending them '" + host + "' instead of '" + defaultHostname + "'");
  121. return destination;
  122. }
  123. }
  124. // Check for same LAN segment
  125. foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets)
  126. {
  127. byte[] subnetBytes = subnet.Value.GetAddressBytes();
  128. byte[] localBytes = subnet.Key.GetAddressBytes();
  129. byte[] destBytes = destination.GetAddressBytes();
  130. if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length)
  131. return null;
  132. bool valid = true;
  133. for (int i=0;i<subnetBytes.Length;i++)
  134. {
  135. if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i]))
  136. {
  137. valid = false;
  138. break;
  139. }
  140. }
  141. if (subnet.Key.AddressFamily != AddressFamily.InterNetwork)
  142. valid = false;
  143. if (valid)
  144. {
  145. m_log.Info("[NetworkUtil] Local LAN user detected, sending them '" + subnet.Key + "' instead of '" + defaultHostname + "'");
  146. return subnet.Key;
  147. }
  148. }
  149. // Check to see if we can find a IPv4 address.
  150. foreach (IPAddress host in Dns.GetHostAddresses(defaultHostname))
  151. {
  152. if (host.AddressFamily == AddressFamily.InterNetwork)
  153. return host;
  154. }
  155. // Unable to find anything.
  156. throw new ArgumentException("[NetworkUtil] Unable to resolve defaultHostname to an IPv4 address for an IPv4 client");
  157. }
  158. static IPAddress externalIPAddress;
  159. static NetworkUtil()
  160. {
  161. try
  162. {
  163. externalIPAddress = GetExternalIP();
  164. }
  165. catch { /* ignore */ }
  166. try
  167. {
  168. foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
  169. {
  170. foreach (UnicastIPAddressInformation address in ni.GetIPProperties().UnicastAddresses)
  171. {
  172. if (address.Address.AddressFamily == AddressFamily.InterNetwork)
  173. {
  174. if (address.IPv4Mask != null)
  175. {
  176. m_subnets.Add(address.Address, address.IPv4Mask);
  177. }
  178. }
  179. }
  180. }
  181. }
  182. catch (NotImplementedException)
  183. {
  184. // Mono Sucks.
  185. }
  186. }
  187. public static IPAddress GetIPFor(IPEndPoint user, string defaultHostname)
  188. {
  189. if (!m_disabled)
  190. {
  191. // Try subnet matching
  192. IPAddress rtn = GetExternalIPFor(user.Address, defaultHostname);
  193. if (rtn != null)
  194. return rtn;
  195. }
  196. // Otherwise use the old algorithm
  197. IPAddress ia;
  198. if (IPAddress.TryParse(defaultHostname, out ia))
  199. return ia;
  200. ia = null;
  201. foreach (IPAddress Adr in Dns.GetHostAddresses(defaultHostname))
  202. {
  203. if (Adr.AddressFamily == AddressFamily.InterNetwork)
  204. {
  205. ia = Adr;
  206. break;
  207. }
  208. }
  209. return ia;
  210. }
  211. public static string GetHostFor(IPAddress user, string defaultHostname)
  212. {
  213. if (!m_disabled)
  214. {
  215. IPAddress rtn = GetExternalIPFor(user, defaultHostname);
  216. if (rtn != null)
  217. return rtn.ToString();
  218. }
  219. return defaultHostname;
  220. }
  221. public static IPAddress GetExternalIPOf(IPAddress user)
  222. {
  223. if (externalIPAddress == null)
  224. return user;
  225. if (user.ToString() == "127.0.0.1")
  226. {
  227. m_log.Info("[NetworkUtil] 127.0.0.1 user detected, sending '" + externalIPAddress + "' instead of '" + user + "'");
  228. return externalIPAddress;
  229. }
  230. // Check if we're accessing localhost.
  231. foreach (IPAddress host in Dns.GetHostAddresses(Dns.GetHostName()))
  232. {
  233. if (host.Equals(user) && host.AddressFamily == AddressFamily.InterNetwork)
  234. {
  235. m_log.Info("[NetworkUtil] Localhost user detected, sending '" + externalIPAddress + "' instead of '" + user + "'");
  236. return externalIPAddress;
  237. }
  238. }
  239. // Check for same LAN segment
  240. foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets)
  241. {
  242. byte[] subnetBytes = subnet.Value.GetAddressBytes();
  243. byte[] localBytes = subnet.Key.GetAddressBytes();
  244. byte[] destBytes = user.GetAddressBytes();
  245. if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length)
  246. return user;
  247. bool valid = true;
  248. for (int i = 0; i < subnetBytes.Length; i++)
  249. {
  250. if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i]))
  251. {
  252. valid = false;
  253. break;
  254. }
  255. }
  256. if (subnet.Key.AddressFamily != AddressFamily.InterNetwork)
  257. valid = false;
  258. if (valid)
  259. {
  260. m_log.Info("[NetworkUtil] Local LAN user detected, sending '" + externalIPAddress + "' instead of '" + user + "'");
  261. return externalIPAddress;
  262. }
  263. }
  264. // Otherwise, return user address
  265. return user;
  266. }
  267. private static IPAddress GetExternalIP()
  268. {
  269. string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp";
  270. WebClient wc = new WebClient();
  271. UTF8Encoding utf8 = new UTF8Encoding();
  272. string requestHtml = "";
  273. try
  274. {
  275. requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
  276. }
  277. catch (WebException we)
  278. {
  279. m_log.Info("[NetworkUtil]: Exception in GetExternalIP: " + we.ToString());
  280. return null;
  281. }
  282. IPAddress externalIp = IPAddress.Parse(requestHtml);
  283. return externalIp;
  284. }
  285. }
  286. }