BaseNetworkManager.cs 13 KB

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