BaseNetworkManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. int lengthMatch = 100;
  118. if (address.AddressFamily == AddressFamily.InterNetwork)
  119. {
  120. lengthMatch = 4;
  121. if (IsInPrivateAddressSpaceIpv4(endpoint))
  122. {
  123. return true;
  124. }
  125. }
  126. else if (address.AddressFamily == AddressFamily.InterNetworkV6)
  127. {
  128. lengthMatch = 10;
  129. if (IsInPrivateAddressSpaceIpv6(endpoint))
  130. {
  131. return true;
  132. }
  133. }
  134. // Should be even be doing this with ipv6?
  135. if (endpoint.Length >= lengthMatch)
  136. {
  137. var prefix = endpoint.Substring(0, lengthMatch);
  138. if (GetLocalIpAddresses()
  139. .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  140. {
  141. return true;
  142. }
  143. }
  144. }
  145. if (resolveHost && !IPAddress.TryParse(endpoint, out address))
  146. {
  147. Uri uri;
  148. if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out uri))
  149. {
  150. try
  151. {
  152. var host = uri.DnsSafeHost;
  153. Logger.Debug("Resolving host {0}", host);
  154. address = GetIpAddresses(host).FirstOrDefault();
  155. if (address != null)
  156. {
  157. Logger.Debug("{0} resolved to {1}", host, address);
  158. return IsInLocalNetworkInternal(address.ToString(), false);
  159. }
  160. }
  161. catch (InvalidOperationException)
  162. {
  163. // Can happen with reverse proxy or IIS url rewriting
  164. }
  165. catch (Exception ex)
  166. {
  167. Logger.ErrorException("Error resovling hostname", ex);
  168. }
  169. }
  170. }
  171. return false;
  172. }
  173. public IEnumerable<IPAddress> GetIpAddresses(string hostName)
  174. {
  175. return Dns.GetHostAddresses(hostName);
  176. }
  177. private IEnumerable<IPAddress> GetIPsDefault()
  178. {
  179. foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
  180. {
  181. var props = adapter.GetIPProperties();
  182. var gateways = from ga in props.GatewayAddresses
  183. where !ga.Address.Equals(IPAddress.Any)
  184. select true;
  185. if (!gateways.Any())
  186. {
  187. continue;
  188. }
  189. foreach (var uni in props.UnicastAddresses)
  190. {
  191. var address = uni.Address;
  192. if (address.AddressFamily != AddressFamily.InterNetwork)
  193. {
  194. continue;
  195. }
  196. yield return address;
  197. }
  198. }
  199. }
  200. private IEnumerable<string> GetLocalIpAddressesFallback()
  201. {
  202. var host = Dns.GetHostEntry(Dns.GetHostName());
  203. // Reverse them because the last one is usually the correct one
  204. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  205. return host.AddressList
  206. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  207. .Select(i => i.ToString())
  208. .Reverse();
  209. }
  210. /// <summary>
  211. /// Gets a random port number that is currently available
  212. /// </summary>
  213. /// <returns>System.Int32.</returns>
  214. public int GetRandomUnusedPort()
  215. {
  216. var listener = new TcpListener(IPAddress.Any, 0);
  217. listener.Start();
  218. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  219. listener.Stop();
  220. return port;
  221. }
  222. /// <summary>
  223. /// Returns MAC Address from first Network Card in Computer
  224. /// </summary>
  225. /// <returns>[string] MAC Address</returns>
  226. public string GetMacAddress()
  227. {
  228. return NetworkInterface.GetAllNetworkInterfaces()
  229. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  230. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  231. .FirstOrDefault();
  232. }
  233. /// <summary>
  234. /// Parses the specified endpointstring.
  235. /// </summary>
  236. /// <param name="endpointstring">The endpointstring.</param>
  237. /// <returns>IPEndPoint.</returns>
  238. public IPEndPoint Parse(string endpointstring)
  239. {
  240. return Parse(endpointstring, -1);
  241. }
  242. /// <summary>
  243. /// Parses the specified endpointstring.
  244. /// </summary>
  245. /// <param name="endpointstring">The endpointstring.</param>
  246. /// <param name="defaultport">The defaultport.</param>
  247. /// <returns>IPEndPoint.</returns>
  248. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  249. /// <exception cref="System.FormatException"></exception>
  250. private static IPEndPoint Parse(string endpointstring, int defaultport)
  251. {
  252. if (String.IsNullOrEmpty(endpointstring)
  253. || endpointstring.Trim().Length == 0)
  254. {
  255. throw new ArgumentException("Endpoint descriptor may not be empty.");
  256. }
  257. if (defaultport != -1 &&
  258. (defaultport < IPEndPoint.MinPort
  259. || defaultport > IPEndPoint.MaxPort))
  260. {
  261. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  262. }
  263. string[] values = endpointstring.Split(new char[] { ':' });
  264. IPAddress ipaddy;
  265. int port = -1;
  266. //check if we have an IPv6 or ports
  267. if (values.Length <= 2) // ipv4 or hostname
  268. {
  269. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  270. //try to use the address as IPv4, otherwise get hostname
  271. if (!IPAddress.TryParse(values[0], out ipaddy))
  272. ipaddy = GetIPfromHost(values[0]);
  273. }
  274. else if (values.Length > 2) //ipv6
  275. {
  276. //could [a:b:c]:d
  277. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  278. {
  279. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  280. ipaddy = IPAddress.Parse(ipaddressstring);
  281. port = GetPort(values[values.Length - 1]);
  282. }
  283. else //[a:b:c] or a:b:c
  284. {
  285. ipaddy = IPAddress.Parse(endpointstring);
  286. port = defaultport;
  287. }
  288. }
  289. else
  290. {
  291. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  292. }
  293. if (port == -1)
  294. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  295. return new IPEndPoint(ipaddy, port);
  296. }
  297. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  298. /// <summary>
  299. /// Gets the port.
  300. /// </summary>
  301. /// <param name="p">The p.</param>
  302. /// <returns>System.Int32.</returns>
  303. /// <exception cref="System.FormatException"></exception>
  304. private static int GetPort(string p)
  305. {
  306. int port;
  307. if (!Int32.TryParse(p, out port)
  308. || port < IPEndPoint.MinPort
  309. || port > IPEndPoint.MaxPort)
  310. {
  311. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  312. }
  313. return port;
  314. }
  315. /// <summary>
  316. /// Gets the I pfrom host.
  317. /// </summary>
  318. /// <param name="p">The p.</param>
  319. /// <returns>IPAddress.</returns>
  320. /// <exception cref="System.ArgumentException"></exception>
  321. private static IPAddress GetIPfromHost(string p)
  322. {
  323. var hosts = Dns.GetHostAddresses(p);
  324. if (hosts == null || hosts.Length == 0)
  325. throw new ArgumentException(String.Format("Host not found: {0}", p));
  326. return hosts[0];
  327. }
  328. }
  329. }