1
0

NetworkUtil.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 NetworkUtil()
  159. {
  160. try
  161. {
  162. foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
  163. {
  164. foreach (UnicastIPAddressInformation address in ni.GetIPProperties().UnicastAddresses)
  165. {
  166. if (address.Address.AddressFamily == AddressFamily.InterNetwork)
  167. {
  168. if (address.IPv4Mask != null)
  169. {
  170. m_subnets.Add(address.Address, address.IPv4Mask);
  171. }
  172. }
  173. }
  174. }
  175. }
  176. catch (NotImplementedException)
  177. {
  178. // Mono Sucks.
  179. }
  180. }
  181. public static IPAddress GetIPFor(IPEndPoint user, string defaultHostname)
  182. {
  183. if (!m_disabled)
  184. {
  185. // Try subnet matching
  186. IPAddress rtn = GetExternalIPFor(user.Address, defaultHostname);
  187. if (rtn != null)
  188. return rtn;
  189. }
  190. // Otherwise use the old algorithm
  191. IPAddress ia;
  192. if (IPAddress.TryParse(defaultHostname, out ia))
  193. return ia;
  194. ia = null;
  195. foreach (IPAddress Adr in Dns.GetHostAddresses(defaultHostname))
  196. {
  197. if (Adr.AddressFamily == AddressFamily.InterNetwork)
  198. {
  199. ia = Adr;
  200. break;
  201. }
  202. }
  203. return ia;
  204. }
  205. public static string GetHostFor(IPAddress user, string defaultHostname)
  206. {
  207. if (!m_disabled)
  208. {
  209. IPAddress rtn = GetExternalIPFor(user, defaultHostname);
  210. if (rtn != null)
  211. return rtn.ToString();
  212. }
  213. return defaultHostname;
  214. }
  215. }
  216. }