NetworkUtil.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 log4net;
  34. namespace OpenSim.Framework
  35. {
  36. /// <summary>
  37. /// Handles NAT translation in a 'manner of speaking'
  38. /// Allows you to return multiple different external
  39. /// hostnames depending on the requestors network
  40. ///
  41. /// This enables standard port forwarding techniques
  42. /// to work correctly with OpenSim.
  43. /// </summary>
  44. public static class NetworkUtil
  45. {
  46. // Logger
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. private static bool m_disabled = true;
  49. public static bool Enabled
  50. {
  51. set { m_disabled = value; }
  52. get { return m_disabled; }
  53. }
  54. // IPv4Address, Subnet
  55. static readonly Dictionary<IPAddress,IPAddress> m_subnets = new Dictionary<IPAddress, IPAddress>();
  56. public static IPAddress GetIPFor(IPAddress user, IPAddress simulator)
  57. {
  58. if (m_disabled)
  59. return simulator;
  60. // Check if we're accessing localhost.
  61. foreach (IPAddress host in Dns.GetHostAddresses(Dns.GetHostName()))
  62. {
  63. if (host.Equals(user) && host.AddressFamily == AddressFamily.InterNetwork)
  64. {
  65. m_log.Info("[NetworkUtil] Localhost user detected, sending them '" + host + "' instead of '" + simulator + "'");
  66. return host;
  67. }
  68. }
  69. // Check for same LAN segment
  70. foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets)
  71. {
  72. byte[] subnetBytes = subnet.Value.GetAddressBytes();
  73. byte[] localBytes = subnet.Key.GetAddressBytes();
  74. byte[] destBytes = user.GetAddressBytes();
  75. if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length)
  76. return null;
  77. bool valid = true;
  78. for (int i = 0; i < subnetBytes.Length; i++)
  79. {
  80. if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i]))
  81. {
  82. valid = false;
  83. break;
  84. }
  85. }
  86. if (subnet.Key.AddressFamily != AddressFamily.InterNetwork)
  87. valid = false;
  88. if (valid)
  89. {
  90. m_log.Info("[NetworkUtil] Local LAN user detected, sending them '" + subnet.Key + "' instead of '" + simulator + "'");
  91. return subnet.Key;
  92. }
  93. }
  94. // Otherwise, return outside address
  95. return simulator;
  96. }
  97. private static IPAddress GetExternalIPFor(IPAddress destination, string defaultHostname)
  98. {
  99. // Adds IPv6 Support (Not that any of the major protocols supports it...)
  100. if (destination.AddressFamily == AddressFamily.InterNetworkV6)
  101. {
  102. foreach (IPAddress host in Dns.GetHostAddresses(defaultHostname))
  103. {
  104. if (host.AddressFamily == AddressFamily.InterNetworkV6)
  105. {
  106. m_log.Info("[NetworkUtil] Localhost user detected, sending them '" + host + "' instead of '" + defaultHostname + "'");
  107. return host;
  108. }
  109. }
  110. }
  111. if (destination.AddressFamily != AddressFamily.InterNetwork)
  112. return null;
  113. // Check if we're accessing localhost.
  114. foreach (KeyValuePair<IPAddress, IPAddress> pair in m_subnets)
  115. {
  116. IPAddress host = pair.Value;
  117. if (host.Equals(destination) && host.AddressFamily == AddressFamily.InterNetwork)
  118. {
  119. m_log.Info("[NATROUTING] Localhost user detected, sending them '" + host + "' instead of '" + defaultHostname + "'");
  120. return destination;
  121. }
  122. }
  123. // Check for same LAN segment
  124. foreach (KeyValuePair<IPAddress, IPAddress> subnet in m_subnets)
  125. {
  126. byte[] subnetBytes = subnet.Value.GetAddressBytes();
  127. byte[] localBytes = subnet.Key.GetAddressBytes();
  128. byte[] destBytes = destination.GetAddressBytes();
  129. if (subnetBytes.Length != destBytes.Length || subnetBytes.Length != localBytes.Length)
  130. return null;
  131. bool valid = true;
  132. for (int i=0;i<subnetBytes.Length;i++)
  133. {
  134. if ((localBytes[i] & subnetBytes[i]) != (destBytes[i] & subnetBytes[i]))
  135. {
  136. valid = false;
  137. break;
  138. }
  139. }
  140. if (subnet.Key.AddressFamily != AddressFamily.InterNetwork)
  141. valid = false;
  142. if (valid)
  143. {
  144. m_log.Info("[NetworkUtil] Local LAN user detected, sending them '" + subnet.Key + "' instead of '" + defaultHostname + "'");
  145. return subnet.Key;
  146. }
  147. }
  148. // Check to see if we can find a IPv4 address.
  149. foreach (IPAddress host in Dns.GetHostAddresses(defaultHostname))
  150. {
  151. if (host.AddressFamily == AddressFamily.InterNetwork)
  152. return host;
  153. }
  154. // Unable to find anything.
  155. throw new ArgumentException("[NetworkUtil] Unable to resolve defaultHostname to an IPv4 address for an IPv4 client");
  156. }
  157. static NetworkUtil()
  158. {
  159. try
  160. {
  161. foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
  162. {
  163. foreach (UnicastIPAddressInformation address in ni.GetIPProperties().UnicastAddresses)
  164. {
  165. if (address.Address.AddressFamily == AddressFamily.InterNetwork)
  166. {
  167. if (address.IPv4Mask != null)
  168. {
  169. m_subnets.Add(address.Address, address.IPv4Mask);
  170. }
  171. }
  172. }
  173. }
  174. }
  175. catch (NotImplementedException)
  176. {
  177. // Mono Sucks.
  178. }
  179. }
  180. public static IPAddress GetIPFor(IPEndPoint user, string defaultHostname)
  181. {
  182. if (!m_disabled)
  183. {
  184. // Try subnet matching
  185. IPAddress rtn = GetExternalIPFor(user.Address, defaultHostname);
  186. if (rtn != null)
  187. return rtn;
  188. }
  189. // Otherwise use the old algorithm
  190. IPAddress ia;
  191. if (IPAddress.TryParse(defaultHostname, out ia))
  192. return ia;
  193. ia = null;
  194. foreach (IPAddress Adr in Dns.GetHostAddresses(defaultHostname))
  195. {
  196. if (Adr.AddressFamily == AddressFamily.InterNetwork)
  197. {
  198. ia = Adr;
  199. break;
  200. }
  201. }
  202. return ia;
  203. }
  204. public static string GetHostFor(IPAddress user, string defaultHostname)
  205. {
  206. if (!m_disabled)
  207. {
  208. IPAddress rtn = GetExternalIPFor(user, defaultHostname);
  209. if (rtn != null)
  210. return rtn.ToString();
  211. }
  212. return defaultHostname;
  213. }
  214. }
  215. }