BaseNetworkManager.cs 13 KB

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