BaseNetworkManager.cs 14 KB

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