BaseNetworkManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.NetworkInformation;
  8. using System.Net.Sockets;
  9. using System.Threading;
  10. namespace MediaBrowser.Common.Implementations.Networking
  11. {
  12. public abstract class BaseNetworkManager
  13. {
  14. protected ILogger Logger { get; private set; }
  15. private Timer _clearCacheTimer;
  16. protected BaseNetworkManager(ILogger logger)
  17. {
  18. Logger = logger;
  19. // Can't use network change events due to a crash in Linux
  20. _clearCacheTimer = new Timer(ClearCacheTimerCallback, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
  21. }
  22. private void ClearCacheTimerCallback(object state)
  23. {
  24. lock (_localIpAddressSyncLock)
  25. {
  26. _localIpAddresses = null;
  27. }
  28. }
  29. private volatile List<string> _localIpAddresses;
  30. private readonly object _localIpAddressSyncLock = new object();
  31. /// <summary>
  32. /// Gets the machine's local ip address
  33. /// </summary>
  34. /// <returns>IPAddress.</returns>
  35. public IEnumerable<string> GetLocalIpAddresses()
  36. {
  37. if (_localIpAddresses == null)
  38. {
  39. lock (_localIpAddressSyncLock)
  40. {
  41. if (_localIpAddresses == null)
  42. {
  43. var addresses = GetLocalIpAddressesInternal().ToList();
  44. _localIpAddresses = addresses;
  45. return addresses;
  46. }
  47. }
  48. }
  49. return _localIpAddresses;
  50. }
  51. private IEnumerable<string> GetLocalIpAddressesInternal()
  52. {
  53. var list = GetIPsDefault()
  54. .Where(i => !IPAddress.IsLoopback(i))
  55. .Select(i => i.ToString())
  56. .Where(FilterIpAddress)
  57. .ToList();
  58. if (list.Count > 0)
  59. {
  60. return list;
  61. }
  62. return GetLocalIpAddressesFallback().Where(FilterIpAddress);
  63. }
  64. private bool FilterIpAddress(string address)
  65. {
  66. if (address.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
  67. {
  68. return false;
  69. }
  70. return true;
  71. }
  72. private bool IsInPrivateAddressSpaceIpv6(string endpoint)
  73. {
  74. return
  75. // If url was requested with computer name, we may see this
  76. string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase);
  77. }
  78. private bool IsInPrivateAddressSpaceIpv4(string endpoint)
  79. {
  80. // Private address space:
  81. // http://en.wikipedia.org/wiki/Private_network
  82. if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase))
  83. {
  84. return Is172AddressPrivate(endpoint);
  85. }
  86. return
  87. endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  88. endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  89. endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  90. endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase) ||
  91. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  92. }
  93. private bool Is172AddressPrivate(string endpoint)
  94. {
  95. for (var i = 16; i <= 31; i++)
  96. {
  97. if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
  98. {
  99. return true;
  100. }
  101. }
  102. return false;
  103. }
  104. public bool IsInLocalNetwork(string endpoint)
  105. {
  106. return IsInLocalNetworkInternal(endpoint, true);
  107. }
  108. public bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
  109. {
  110. if (string.IsNullOrWhiteSpace(endpoint))
  111. {
  112. throw new ArgumentNullException("endpoint");
  113. }
  114. IPAddress address;
  115. if (IPAddress.TryParse(endpoint, out address))
  116. {
  117. var addressString = address.ToString();
  118. int lengthMatch = 100;
  119. if (address.AddressFamily == AddressFamily.InterNetwork)
  120. {
  121. lengthMatch = 4;
  122. if (IsInPrivateAddressSpaceIpv4(addressString))
  123. {
  124. return true;
  125. }
  126. }
  127. else if (address.AddressFamily == AddressFamily.InterNetworkV6)
  128. {
  129. lengthMatch = 10;
  130. if (IsInPrivateAddressSpaceIpv6(endpoint))
  131. {
  132. return true;
  133. }
  134. }
  135. // Should be even be doing this with ipv6?
  136. if (addressString.Length >= lengthMatch)
  137. {
  138. var prefix = addressString.Substring(0, lengthMatch);
  139. if (GetLocalIpAddresses()
  140. .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  141. {
  142. return true;
  143. }
  144. }
  145. }
  146. else if (resolveHost)
  147. {
  148. Uri uri;
  149. if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out uri))
  150. {
  151. try
  152. {
  153. var host = uri.DnsSafeHost;
  154. Logger.Debug("Resolving host {0}", host);
  155. address = GetIpAddresses(host).FirstOrDefault();
  156. if (address != null)
  157. {
  158. Logger.Debug("{0} resolved to {1}", host, address);
  159. return IsInLocalNetworkInternal(address.ToString(), false);
  160. }
  161. }
  162. catch (InvalidOperationException)
  163. {
  164. // Can happen with reverse proxy or IIS url rewriting
  165. }
  166. catch (Exception ex)
  167. {
  168. Logger.ErrorException("Error resovling hostname", ex);
  169. }
  170. }
  171. }
  172. return false;
  173. }
  174. public IEnumerable<IPAddress> GetIpAddresses(string hostName)
  175. {
  176. return Dns.GetHostAddresses(hostName);
  177. }
  178. private IEnumerable<IPAddress> GetIPsDefault()
  179. {
  180. foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
  181. {
  182. var props = adapter.GetIPProperties();
  183. var gateways = from ga in props.GatewayAddresses
  184. where !ga.Address.Equals(IPAddress.Any)
  185. select true;
  186. if (!gateways.Any())
  187. {
  188. continue;
  189. }
  190. foreach (var uni in props.UnicastAddresses)
  191. {
  192. var address = uni.Address;
  193. if (address.AddressFamily != AddressFamily.InterNetwork)
  194. {
  195. continue;
  196. }
  197. yield return address;
  198. }
  199. }
  200. }
  201. private IEnumerable<string> GetLocalIpAddressesFallback()
  202. {
  203. var host = Dns.GetHostEntry(Dns.GetHostName());
  204. // Reverse them because the last one is usually the correct one
  205. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  206. return host.AddressList
  207. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  208. .Select(i => i.ToString())
  209. .Reverse();
  210. }
  211. /// <summary>
  212. /// Gets a random port number that is currently available
  213. /// </summary>
  214. /// <returns>System.Int32.</returns>
  215. public int GetRandomUnusedPort()
  216. {
  217. var listener = new TcpListener(IPAddress.Any, 0);
  218. listener.Start();
  219. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  220. listener.Stop();
  221. return port;
  222. }
  223. /// <summary>
  224. /// Returns MAC Address from first Network Card in Computer
  225. /// </summary>
  226. /// <returns>[string] MAC Address</returns>
  227. public string GetMacAddress()
  228. {
  229. return NetworkInterface.GetAllNetworkInterfaces()
  230. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  231. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  232. .FirstOrDefault();
  233. }
  234. /// <summary>
  235. /// Parses the specified endpointstring.
  236. /// </summary>
  237. /// <param name="endpointstring">The endpointstring.</param>
  238. /// <returns>IPEndPoint.</returns>
  239. public IPEndPoint Parse(string endpointstring)
  240. {
  241. return Parse(endpointstring, -1);
  242. }
  243. /// <summary>
  244. /// Parses the specified endpointstring.
  245. /// </summary>
  246. /// <param name="endpointstring">The endpointstring.</param>
  247. /// <param name="defaultport">The defaultport.</param>
  248. /// <returns>IPEndPoint.</returns>
  249. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  250. /// <exception cref="System.FormatException"></exception>
  251. private static IPEndPoint Parse(string endpointstring, int defaultport)
  252. {
  253. if (String.IsNullOrEmpty(endpointstring)
  254. || endpointstring.Trim().Length == 0)
  255. {
  256. throw new ArgumentException("Endpoint descriptor may not be empty.");
  257. }
  258. if (defaultport != -1 &&
  259. (defaultport < IPEndPoint.MinPort
  260. || defaultport > IPEndPoint.MaxPort))
  261. {
  262. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  263. }
  264. string[] values = endpointstring.Split(new char[] { ':' });
  265. IPAddress ipaddy;
  266. int port = -1;
  267. //check if we have an IPv6 or ports
  268. if (values.Length <= 2) // ipv4 or hostname
  269. {
  270. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  271. //try to use the address as IPv4, otherwise get hostname
  272. if (!IPAddress.TryParse(values[0], out ipaddy))
  273. ipaddy = GetIPfromHost(values[0]);
  274. }
  275. else if (values.Length > 2) //ipv6
  276. {
  277. //could [a:b:c]:d
  278. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  279. {
  280. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  281. ipaddy = IPAddress.Parse(ipaddressstring);
  282. port = GetPort(values[values.Length - 1]);
  283. }
  284. else //[a:b:c] or a:b:c
  285. {
  286. ipaddy = IPAddress.Parse(endpointstring);
  287. port = defaultport;
  288. }
  289. }
  290. else
  291. {
  292. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  293. }
  294. if (port == -1)
  295. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  296. return new IPEndPoint(ipaddy, port);
  297. }
  298. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  299. /// <summary>
  300. /// Gets the port.
  301. /// </summary>
  302. /// <param name="p">The p.</param>
  303. /// <returns>System.Int32.</returns>
  304. /// <exception cref="System.FormatException"></exception>
  305. private static int GetPort(string p)
  306. {
  307. int port;
  308. if (!Int32.TryParse(p, out port)
  309. || port < IPEndPoint.MinPort
  310. || port > IPEndPoint.MaxPort)
  311. {
  312. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  313. }
  314. return port;
  315. }
  316. /// <summary>
  317. /// Gets the I pfrom host.
  318. /// </summary>
  319. /// <param name="p">The p.</param>
  320. /// <returns>IPAddress.</returns>
  321. /// <exception cref="System.ArgumentException"></exception>
  322. private static IPAddress GetIPfromHost(string p)
  323. {
  324. var hosts = Dns.GetHostAddresses(p);
  325. if (hosts == null || hosts.Length == 0)
  326. throw new ArgumentException(String.Format("Host not found: {0}", p));
  327. return hosts[0];
  328. }
  329. }
  330. }