BaseNetworkManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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(i => !IPAddress.IsLoopback(i)).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("Found interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
  192. var properties = network.GetIPProperties();
  193. var ipV4 = properties.GetIPv4Properties();
  194. if (null == ipV4)
  195. return new List<IPAddress>();
  196. return properties.UnicastAddresses
  197. .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i.Address))
  198. .Select(i => i.Address)
  199. .ToList();
  200. }
  201. catch (Exception ex)
  202. {
  203. Logger.ErrorException("Error querying network interface", ex);
  204. return new List<IPAddress>();
  205. }
  206. }).DistinctBy(i => i.ToString())
  207. .ToList();
  208. }
  209. private IEnumerable<IPAddress> GetLocalIpAddressesFallback()
  210. {
  211. var host = Dns.GetHostEntry(Dns.GetHostName());
  212. // Reverse them because the last one is usually the correct one
  213. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  214. return host.AddressList
  215. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  216. .Reverse();
  217. }
  218. /// <summary>
  219. /// Gets a random port number that is currently available
  220. /// </summary>
  221. /// <returns>System.Int32.</returns>
  222. public int GetRandomUnusedPort()
  223. {
  224. var listener = new TcpListener(IPAddress.Any, 0);
  225. listener.Start();
  226. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  227. listener.Stop();
  228. return port;
  229. }
  230. /// <summary>
  231. /// Returns MAC Address from first Network Card in Computer
  232. /// </summary>
  233. /// <returns>[string] MAC Address</returns>
  234. public string GetMacAddress()
  235. {
  236. return NetworkInterface.GetAllNetworkInterfaces()
  237. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  238. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  239. .FirstOrDefault();
  240. }
  241. /// <summary>
  242. /// Parses the specified endpointstring.
  243. /// </summary>
  244. /// <param name="endpointstring">The endpointstring.</param>
  245. /// <returns>IPEndPoint.</returns>
  246. public IPEndPoint Parse(string endpointstring)
  247. {
  248. return Parse(endpointstring, -1);
  249. }
  250. /// <summary>
  251. /// Parses the specified endpointstring.
  252. /// </summary>
  253. /// <param name="endpointstring">The endpointstring.</param>
  254. /// <param name="defaultport">The defaultport.</param>
  255. /// <returns>IPEndPoint.</returns>
  256. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  257. /// <exception cref="System.FormatException"></exception>
  258. private static IPEndPoint Parse(string endpointstring, int defaultport)
  259. {
  260. if (String.IsNullOrEmpty(endpointstring)
  261. || endpointstring.Trim().Length == 0)
  262. {
  263. throw new ArgumentException("Endpoint descriptor may not be empty.");
  264. }
  265. if (defaultport != -1 &&
  266. (defaultport < IPEndPoint.MinPort
  267. || defaultport > IPEndPoint.MaxPort))
  268. {
  269. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  270. }
  271. string[] values = endpointstring.Split(new char[] { ':' });
  272. IPAddress ipaddy;
  273. int port = -1;
  274. //check if we have an IPv6 or ports
  275. if (values.Length <= 2) // ipv4 or hostname
  276. {
  277. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  278. //try to use the address as IPv4, otherwise get hostname
  279. if (!IPAddress.TryParse(values[0], out ipaddy))
  280. ipaddy = GetIPfromHost(values[0]);
  281. }
  282. else if (values.Length > 2) //ipv6
  283. {
  284. //could [a:b:c]:d
  285. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  286. {
  287. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  288. ipaddy = IPAddress.Parse(ipaddressstring);
  289. port = GetPort(values[values.Length - 1]);
  290. }
  291. else //[a:b:c] or a:b:c
  292. {
  293. ipaddy = IPAddress.Parse(endpointstring);
  294. port = defaultport;
  295. }
  296. }
  297. else
  298. {
  299. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  300. }
  301. if (port == -1)
  302. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  303. return new IPEndPoint(ipaddy, port);
  304. }
  305. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  306. /// <summary>
  307. /// Gets the port.
  308. /// </summary>
  309. /// <param name="p">The p.</param>
  310. /// <returns>System.Int32.</returns>
  311. /// <exception cref="System.FormatException"></exception>
  312. private static int GetPort(string p)
  313. {
  314. int port;
  315. if (!Int32.TryParse(p, out port)
  316. || port < IPEndPoint.MinPort
  317. || port > IPEndPoint.MaxPort)
  318. {
  319. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  320. }
  321. return port;
  322. }
  323. /// <summary>
  324. /// Gets the I pfrom host.
  325. /// </summary>
  326. /// <param name="p">The p.</param>
  327. /// <returns>IPAddress.</returns>
  328. /// <exception cref="System.ArgumentException"></exception>
  329. private static IPAddress GetIPfromHost(string p)
  330. {
  331. var hosts = Dns.GetHostAddresses(p);
  332. if (hosts == null || hosts.Length == 0)
  333. throw new ArgumentException(String.Format("Host not found: {0}", p));
  334. return hosts[0];
  335. }
  336. }
  337. }