NetworkManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.NetworkInformation;
  7. using System.Net.Sockets;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Model.Extensions;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.Net;
  14. namespace Emby.Server.Implementations.Networking
  15. {
  16. public class NetworkManager : INetworkManager
  17. {
  18. protected ILogger Logger { get; private set; }
  19. private DateTime _lastRefresh;
  20. public NetworkManager(ILogger logger)
  21. {
  22. Logger = logger;
  23. }
  24. private List<IpAddressInfo> _localIpAddresses;
  25. private readonly object _localIpAddressSyncLock = new object();
  26. public List<IpAddressInfo> GetLocalIpAddresses()
  27. {
  28. const int cacheMinutes = 10;
  29. lock (_localIpAddressSyncLock)
  30. {
  31. var forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= cacheMinutes;
  32. if (_localIpAddresses == null || forceRefresh)
  33. {
  34. var addresses = GetLocalIpAddressesInternal().Select(ToIpAddressInfo).ToList();
  35. _localIpAddresses = addresses;
  36. _lastRefresh = DateTime.UtcNow;
  37. return addresses;
  38. }
  39. }
  40. return _localIpAddresses;
  41. }
  42. private IEnumerable<IPAddress> GetLocalIpAddressesInternal()
  43. {
  44. var list = GetIPsDefault()
  45. .ToList();
  46. if (list.Count == 0)
  47. {
  48. list.AddRange(GetLocalIpAddressesFallback().Result);
  49. }
  50. return list.Where(FilterIpAddress).DistinctBy(i => i.ToString());
  51. }
  52. private bool FilterIpAddress(IPAddress address)
  53. {
  54. var addressString = address.ToString();
  55. if (addressString.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
  56. {
  57. return false;
  58. }
  59. return true;
  60. }
  61. public bool IsInPrivateAddressSpace(string endpoint)
  62. {
  63. if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
  64. {
  65. return true;
  66. }
  67. // Handle ipv4 mapped to ipv6
  68. endpoint = endpoint.Replace("::ffff:", string.Empty);
  69. // Private address space:
  70. // http://en.wikipedia.org/wiki/Private_network
  71. if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase))
  72. {
  73. return Is172AddressPrivate(endpoint);
  74. }
  75. return
  76. endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  77. endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  78. endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  79. endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase) ||
  80. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  81. }
  82. private bool Is172AddressPrivate(string endpoint)
  83. {
  84. for (var i = 16; i <= 31; i++)
  85. {
  86. if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
  87. {
  88. return true;
  89. }
  90. }
  91. return false;
  92. }
  93. public bool IsInLocalNetwork(string endpoint)
  94. {
  95. return IsInLocalNetworkInternal(endpoint, true);
  96. }
  97. public bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
  98. {
  99. if (string.IsNullOrWhiteSpace(endpoint))
  100. {
  101. throw new ArgumentNullException("endpoint");
  102. }
  103. IPAddress address;
  104. if (IPAddress.TryParse(endpoint, out address))
  105. {
  106. var addressString = address.ToString();
  107. int lengthMatch = 100;
  108. if (address.AddressFamily == AddressFamily.InterNetwork)
  109. {
  110. lengthMatch = 4;
  111. if (IsInPrivateAddressSpace(addressString))
  112. {
  113. return true;
  114. }
  115. }
  116. else if (address.AddressFamily == AddressFamily.InterNetworkV6)
  117. {
  118. lengthMatch = 10;
  119. if (IsInPrivateAddressSpace(endpoint))
  120. {
  121. return true;
  122. }
  123. }
  124. // Should be even be doing this with ipv6?
  125. if (addressString.Length >= lengthMatch)
  126. {
  127. var prefix = addressString.Substring(0, lengthMatch);
  128. if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  129. {
  130. return true;
  131. }
  132. }
  133. }
  134. else if (resolveHost)
  135. {
  136. Uri uri;
  137. if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out uri))
  138. {
  139. try
  140. {
  141. var host = uri.DnsSafeHost;
  142. Logger.Debug("Resolving host {0}", host);
  143. address = GetIpAddresses(host).Result.FirstOrDefault();
  144. if (address != null)
  145. {
  146. Logger.Debug("{0} resolved to {1}", host, address);
  147. return IsInLocalNetworkInternal(address.ToString(), false);
  148. }
  149. }
  150. catch (InvalidOperationException)
  151. {
  152. // Can happen with reverse proxy or IIS url rewriting
  153. }
  154. catch (Exception ex)
  155. {
  156. Logger.ErrorException("Error resovling hostname", ex);
  157. }
  158. }
  159. }
  160. return false;
  161. }
  162. private Task<IPAddress[]> GetIpAddresses(string hostName)
  163. {
  164. return Dns.GetHostAddressesAsync(hostName);
  165. }
  166. private List<IPAddress> GetIPsDefault()
  167. {
  168. NetworkInterface[] interfaces;
  169. try
  170. {
  171. var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown };
  172. interfaces = NetworkInterface.GetAllNetworkInterfaces()
  173. .Where(i => validStatuses.Contains(i.OperationalStatus))
  174. .ToArray();
  175. }
  176. catch (Exception ex)
  177. {
  178. Logger.ErrorException("Error in GetAllNetworkInterfaces", ex);
  179. return new List<IPAddress>();
  180. }
  181. return interfaces.SelectMany(network =>
  182. {
  183. try
  184. {
  185. // suppress logging because it might be causing nas device wake up
  186. //Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
  187. var ipProperties = network.GetIPProperties();
  188. // Try to exclude virtual adapters
  189. // http://stackoverflow.com/questions/8089685/c-sharp-finding-my-machines-local-ip-address-and-not-the-vms
  190. var addr = ipProperties.GatewayAddresses.FirstOrDefault();
  191. if (addr == null || string.Equals(addr.Address.ToString(), "0.0.0.0", StringComparison.OrdinalIgnoreCase))
  192. {
  193. return new List<IPAddress>();
  194. }
  195. //if (!_validNetworkInterfaceTypes.Contains(network.NetworkInterfaceType))
  196. //{
  197. // return new List<IPAddress>();
  198. //}
  199. return ipProperties.UnicastAddresses
  200. //.Where(i => i.IsDnsEligible)
  201. .Select(i => i.Address)
  202. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  203. .ToList();
  204. }
  205. catch (Exception ex)
  206. {
  207. Logger.ErrorException("Error querying network interface", ex);
  208. return new List<IPAddress>();
  209. }
  210. }).DistinctBy(i => i.ToString())
  211. .ToList();
  212. }
  213. private async Task<IEnumerable<IPAddress>> GetLocalIpAddressesFallback()
  214. {
  215. var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false);
  216. // Reverse them because the last one is usually the correct one
  217. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  218. return host.AddressList
  219. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  220. .Reverse();
  221. }
  222. /// <summary>
  223. /// Gets a random port number that is currently available
  224. /// </summary>
  225. /// <returns>System.Int32.</returns>
  226. public int GetRandomUnusedTcpPort()
  227. {
  228. var listener = new TcpListener(IPAddress.Any, 0);
  229. listener.Start();
  230. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  231. listener.Stop();
  232. return port;
  233. }
  234. public int GetRandomUnusedUdpPort()
  235. {
  236. IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);
  237. using (var udpClient = new UdpClient(localEndPoint))
  238. {
  239. var port = ((IPEndPoint)(udpClient.Client.LocalEndPoint)).Port;
  240. return port;
  241. }
  242. }
  243. /// <summary>
  244. /// Returns MAC Address from first Network Card in Computer
  245. /// </summary>
  246. /// <returns>[string] MAC Address</returns>
  247. public string GetMacAddress()
  248. {
  249. return NetworkInterface.GetAllNetworkInterfaces()
  250. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  251. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  252. .FirstOrDefault();
  253. }
  254. /// <summary>
  255. /// Parses the specified endpointstring.
  256. /// </summary>
  257. /// <param name="endpointstring">The endpointstring.</param>
  258. /// <returns>IPEndPoint.</returns>
  259. public IPEndPoint Parse(string endpointstring)
  260. {
  261. return Parse(endpointstring, -1).Result;
  262. }
  263. /// <summary>
  264. /// Parses the specified endpointstring.
  265. /// </summary>
  266. /// <param name="endpointstring">The endpointstring.</param>
  267. /// <param name="defaultport">The defaultport.</param>
  268. /// <returns>IPEndPoint.</returns>
  269. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  270. /// <exception cref="System.FormatException"></exception>
  271. private static async Task<IPEndPoint> Parse(string endpointstring, int defaultport)
  272. {
  273. if (String.IsNullOrEmpty(endpointstring)
  274. || endpointstring.Trim().Length == 0)
  275. {
  276. throw new ArgumentException("Endpoint descriptor may not be empty.");
  277. }
  278. if (defaultport != -1 &&
  279. (defaultport < IPEndPoint.MinPort
  280. || defaultport > IPEndPoint.MaxPort))
  281. {
  282. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  283. }
  284. string[] values = endpointstring.Split(new char[] { ':' });
  285. IPAddress ipaddy;
  286. int port = -1;
  287. //check if we have an IPv6 or ports
  288. if (values.Length <= 2) // ipv4 or hostname
  289. {
  290. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  291. //try to use the address as IPv4, otherwise get hostname
  292. if (!IPAddress.TryParse(values[0], out ipaddy))
  293. ipaddy = await GetIPfromHost(values[0]).ConfigureAwait(false);
  294. }
  295. else if (values.Length > 2) //ipv6
  296. {
  297. //could [a:b:c]:d
  298. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  299. {
  300. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  301. ipaddy = IPAddress.Parse(ipaddressstring);
  302. port = GetPort(values[values.Length - 1]);
  303. }
  304. else //[a:b:c] or a:b:c
  305. {
  306. ipaddy = IPAddress.Parse(endpointstring);
  307. port = defaultport;
  308. }
  309. }
  310. else
  311. {
  312. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  313. }
  314. if (port == -1)
  315. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  316. return new IPEndPoint(ipaddy, port);
  317. }
  318. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  319. /// <summary>
  320. /// Gets the port.
  321. /// </summary>
  322. /// <param name="p">The p.</param>
  323. /// <returns>System.Int32.</returns>
  324. /// <exception cref="System.FormatException"></exception>
  325. private static int GetPort(string p)
  326. {
  327. int port;
  328. if (!Int32.TryParse(p, out port)
  329. || port < IPEndPoint.MinPort
  330. || port > IPEndPoint.MaxPort)
  331. {
  332. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  333. }
  334. return port;
  335. }
  336. /// <summary>
  337. /// Gets the I pfrom host.
  338. /// </summary>
  339. /// <param name="p">The p.</param>
  340. /// <returns>IPAddress.</returns>
  341. /// <exception cref="System.ArgumentException"></exception>
  342. private static async Task<IPAddress> GetIPfromHost(string p)
  343. {
  344. var hosts = await Dns.GetHostAddressesAsync(p).ConfigureAwait(false);
  345. if (hosts == null || hosts.Length == 0)
  346. throw new ArgumentException(String.Format("Host not found: {0}", p));
  347. return hosts[0];
  348. }
  349. public IpAddressInfo ParseIpAddress(string ipAddress)
  350. {
  351. IpAddressInfo info;
  352. if (TryParseIpAddress(ipAddress, out info))
  353. {
  354. return info;
  355. }
  356. throw new ArgumentException("Invalid ip address: " + ipAddress);
  357. }
  358. public bool TryParseIpAddress(string ipAddress, out IpAddressInfo ipAddressInfo)
  359. {
  360. IPAddress address;
  361. if (IPAddress.TryParse(ipAddress, out address))
  362. {
  363. ipAddressInfo = ToIpAddressInfo(address);
  364. return true;
  365. }
  366. ipAddressInfo = null;
  367. return false;
  368. }
  369. public static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  370. {
  371. if (endpoint == null)
  372. {
  373. return null;
  374. }
  375. return new IpEndPointInfo(ToIpAddressInfo(endpoint.Address), endpoint.Port);
  376. }
  377. public static IPEndPoint ToIPEndPoint(IpEndPointInfo endpoint)
  378. {
  379. if (endpoint == null)
  380. {
  381. return null;
  382. }
  383. return new IPEndPoint(ToIPAddress(endpoint.IpAddress), endpoint.Port);
  384. }
  385. public static IPAddress ToIPAddress(IpAddressInfo address)
  386. {
  387. if (address.Equals(IpAddressInfo.Any))
  388. {
  389. return IPAddress.Any;
  390. }
  391. if (address.Equals(IpAddressInfo.IPv6Any))
  392. {
  393. return IPAddress.IPv6Any;
  394. }
  395. if (address.Equals(IpAddressInfo.Loopback))
  396. {
  397. return IPAddress.Loopback;
  398. }
  399. if (address.Equals(IpAddressInfo.IPv6Loopback))
  400. {
  401. return IPAddress.IPv6Loopback;
  402. }
  403. return IPAddress.Parse(address.Address);
  404. }
  405. public static IpAddressInfo ToIpAddressInfo(IPAddress address)
  406. {
  407. if (address.Equals(IPAddress.Any))
  408. {
  409. return IpAddressInfo.Any;
  410. }
  411. if (address.Equals(IPAddress.IPv6Any))
  412. {
  413. return IpAddressInfo.IPv6Any;
  414. }
  415. if (address.Equals(IPAddress.Loopback))
  416. {
  417. return IpAddressInfo.Loopback;
  418. }
  419. if (address.Equals(IPAddress.IPv6Loopback))
  420. {
  421. return IpAddressInfo.IPv6Loopback;
  422. }
  423. return new IpAddressInfo(address.ToString(), address.AddressFamily == AddressFamily.InterNetworkV6 ? IpAddressFamily.InterNetworkV6 : IpAddressFamily.InterNetwork);
  424. }
  425. public async Task<IpAddressInfo[]> GetHostAddressesAsync(string host)
  426. {
  427. var addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
  428. return addresses.Select(ToIpAddressInfo).ToArray(addresses.Length);
  429. }
  430. /// <summary>
  431. /// Gets the network shares.
  432. /// </summary>
  433. /// <param name="path">The path.</param>
  434. /// <returns>IEnumerable{NetworkShare}.</returns>
  435. public virtual IEnumerable<NetworkShare> GetNetworkShares(string path)
  436. {
  437. return new List<NetworkShare>();
  438. }
  439. /// <summary>
  440. /// Gets available devices within the domain
  441. /// </summary>
  442. /// <returns>PC's in the Domain</returns>
  443. public virtual IEnumerable<FileSystemEntryInfo> GetNetworkDevices()
  444. {
  445. return new List<FileSystemEntryInfo>();
  446. }
  447. }
  448. }