NetworkManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. // ipv6
  68. if (endpoint.Split('.').Length > 4)
  69. {
  70. // Handle ipv4 mapped to ipv6
  71. var originalEndpoint = endpoint;
  72. endpoint = endpoint.Replace("::ffff:", string.Empty);
  73. if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
  74. {
  75. return false;
  76. }
  77. }
  78. // Private address space:
  79. // http://en.wikipedia.org/wiki/Private_network
  80. if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase))
  81. {
  82. return Is172AddressPrivate(endpoint);
  83. }
  84. return endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  85. endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  86. endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase) ||
  87. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase) ||
  88. IsInPrivateAddressSpaceAndLocalSubnet(endpoint);
  89. }
  90. public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
  91. {
  92. var endpointFirstPart = endpoint.Split('.')[0];
  93. if (
  94. endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  95. endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  96. endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase) ||
  97. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase)
  98. )
  99. {
  100. var subnets = GetSubnets(endpointFirstPart);
  101. foreach (var subnet_Match in subnets)
  102. {
  103. //Logger.Debug("subnet_Match:" + subnet_Match);
  104. if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase))
  105. {
  106. return true;
  107. }
  108. }
  109. }
  110. return false;
  111. }
  112. private Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
  113. private List<string> GetSubnets(string endpointFirstPart)
  114. {
  115. List<string> subnets;
  116. lock (_subnetLookup)
  117. {
  118. if (_subnetLookup.TryGetValue(endpointFirstPart, out subnets))
  119. {
  120. return subnets;
  121. }
  122. subnets = new List<string>();
  123. foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
  124. {
  125. foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
  126. {
  127. if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork && endpointFirstPart == unicastIPAddressInformation.Address.ToString().Split('.')[0])
  128. {
  129. int subnet_Test = 0;
  130. foreach (string part in unicastIPAddressInformation.IPv4Mask.ToString().Split('.'))
  131. {
  132. if (part.Equals("0")) break;
  133. subnet_Test++;
  134. }
  135. var subnet_Match = String.Join(".", unicastIPAddressInformation.Address.ToString().Split('.').Take(subnet_Test).ToArray());
  136. // TODO: Is this check necessary?
  137. if (adapter.OperationalStatus == OperationalStatus.Up)
  138. {
  139. subnets.Add(subnet_Match);
  140. }
  141. }
  142. }
  143. }
  144. _subnetLookup[endpointFirstPart] = subnets;
  145. return subnets;
  146. }
  147. }
  148. private bool Is172AddressPrivate(string endpoint)
  149. {
  150. for (var i = 16; i <= 31; i++)
  151. {
  152. if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
  153. {
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. public bool IsInLocalNetwork(string endpoint)
  160. {
  161. return IsInLocalNetworkInternal(endpoint, true);
  162. }
  163. public bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
  164. {
  165. if (string.IsNullOrWhiteSpace(endpoint))
  166. {
  167. throw new ArgumentNullException("endpoint");
  168. }
  169. IPAddress address;
  170. if (IPAddress.TryParse(endpoint, out address))
  171. {
  172. var addressString = address.ToString();
  173. int lengthMatch = 100;
  174. if (address.AddressFamily == AddressFamily.InterNetwork)
  175. {
  176. lengthMatch = 4;
  177. if (IsInPrivateAddressSpace(addressString))
  178. {
  179. return true;
  180. }
  181. }
  182. else if (address.AddressFamily == AddressFamily.InterNetworkV6)
  183. {
  184. lengthMatch = 10;
  185. if (IsInPrivateAddressSpace(endpoint))
  186. {
  187. return true;
  188. }
  189. }
  190. // Should be even be doing this with ipv6?
  191. if (addressString.Length >= lengthMatch)
  192. {
  193. var prefix = addressString.Substring(0, lengthMatch);
  194. if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  195. {
  196. return true;
  197. }
  198. }
  199. }
  200. else if (resolveHost)
  201. {
  202. Uri uri;
  203. if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out uri))
  204. {
  205. try
  206. {
  207. var host = uri.DnsSafeHost;
  208. Logger.Debug("Resolving host {0}", host);
  209. address = GetIpAddresses(host).Result.FirstOrDefault();
  210. if (address != null)
  211. {
  212. Logger.Debug("{0} resolved to {1}", host, address);
  213. return IsInLocalNetworkInternal(address.ToString(), false);
  214. }
  215. }
  216. catch (InvalidOperationException)
  217. {
  218. // Can happen with reverse proxy or IIS url rewriting
  219. }
  220. catch (Exception ex)
  221. {
  222. Logger.ErrorException("Error resovling hostname", ex);
  223. }
  224. }
  225. }
  226. return false;
  227. }
  228. private Task<IPAddress[]> GetIpAddresses(string hostName)
  229. {
  230. return Dns.GetHostAddressesAsync(hostName);
  231. }
  232. private List<IPAddress> GetIPsDefault()
  233. {
  234. NetworkInterface[] interfaces;
  235. try
  236. {
  237. var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown };
  238. interfaces = NetworkInterface.GetAllNetworkInterfaces()
  239. .Where(i => validStatuses.Contains(i.OperationalStatus))
  240. .ToArray();
  241. }
  242. catch (Exception ex)
  243. {
  244. Logger.ErrorException("Error in GetAllNetworkInterfaces", ex);
  245. return new List<IPAddress>();
  246. }
  247. return interfaces.SelectMany(network =>
  248. {
  249. try
  250. {
  251. // suppress logging because it might be causing nas device wake up
  252. //Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
  253. var ipProperties = network.GetIPProperties();
  254. // Try to exclude virtual adapters
  255. // http://stackoverflow.com/questions/8089685/c-sharp-finding-my-machines-local-ip-address-and-not-the-vms
  256. var addr = ipProperties.GatewayAddresses.FirstOrDefault();
  257. if (addr == null || string.Equals(addr.Address.ToString(), "0.0.0.0", StringComparison.OrdinalIgnoreCase))
  258. {
  259. return new List<IPAddress>();
  260. }
  261. //if (!_validNetworkInterfaceTypes.Contains(network.NetworkInterfaceType))
  262. //{
  263. // return new List<IPAddress>();
  264. //}
  265. return ipProperties.UnicastAddresses
  266. //.Where(i => i.IsDnsEligible)
  267. .Select(i => i.Address)
  268. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  269. .ToList();
  270. }
  271. catch (Exception ex)
  272. {
  273. Logger.ErrorException("Error querying network interface", ex);
  274. return new List<IPAddress>();
  275. }
  276. }).DistinctBy(i => i.ToString())
  277. .ToList();
  278. }
  279. private async Task<IEnumerable<IPAddress>> GetLocalIpAddressesFallback()
  280. {
  281. var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false);
  282. // Reverse them because the last one is usually the correct one
  283. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  284. return host.AddressList
  285. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  286. .Reverse();
  287. }
  288. /// <summary>
  289. /// Gets a random port number that is currently available
  290. /// </summary>
  291. /// <returns>System.Int32.</returns>
  292. public int GetRandomUnusedTcpPort()
  293. {
  294. var listener = new TcpListener(IPAddress.Any, 0);
  295. listener.Start();
  296. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  297. listener.Stop();
  298. return port;
  299. }
  300. public int GetRandomUnusedUdpPort()
  301. {
  302. IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);
  303. using (var udpClient = new UdpClient(localEndPoint))
  304. {
  305. var port = ((IPEndPoint)(udpClient.Client.LocalEndPoint)).Port;
  306. return port;
  307. }
  308. }
  309. /// <summary>
  310. /// Returns MAC Address from first Network Card in Computer
  311. /// </summary>
  312. /// <returns>[string] MAC Address</returns>
  313. public string GetMacAddress()
  314. {
  315. return NetworkInterface.GetAllNetworkInterfaces()
  316. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  317. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  318. .FirstOrDefault();
  319. }
  320. /// <summary>
  321. /// Parses the specified endpointstring.
  322. /// </summary>
  323. /// <param name="endpointstring">The endpointstring.</param>
  324. /// <returns>IPEndPoint.</returns>
  325. public IPEndPoint Parse(string endpointstring)
  326. {
  327. return Parse(endpointstring, -1).Result;
  328. }
  329. /// <summary>
  330. /// Parses the specified endpointstring.
  331. /// </summary>
  332. /// <param name="endpointstring">The endpointstring.</param>
  333. /// <param name="defaultport">The defaultport.</param>
  334. /// <returns>IPEndPoint.</returns>
  335. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  336. /// <exception cref="System.FormatException"></exception>
  337. private static async Task<IPEndPoint> Parse(string endpointstring, int defaultport)
  338. {
  339. if (String.IsNullOrEmpty(endpointstring)
  340. || endpointstring.Trim().Length == 0)
  341. {
  342. throw new ArgumentException("Endpoint descriptor may not be empty.");
  343. }
  344. if (defaultport != -1 &&
  345. (defaultport < IPEndPoint.MinPort
  346. || defaultport > IPEndPoint.MaxPort))
  347. {
  348. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  349. }
  350. string[] values = endpointstring.Split(new char[] { ':' });
  351. IPAddress ipaddy;
  352. int port = -1;
  353. //check if we have an IPv6 or ports
  354. if (values.Length <= 2) // ipv4 or hostname
  355. {
  356. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  357. //try to use the address as IPv4, otherwise get hostname
  358. if (!IPAddress.TryParse(values[0], out ipaddy))
  359. ipaddy = await GetIPfromHost(values[0]).ConfigureAwait(false);
  360. }
  361. else if (values.Length > 2) //ipv6
  362. {
  363. //could [a:b:c]:d
  364. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  365. {
  366. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  367. ipaddy = IPAddress.Parse(ipaddressstring);
  368. port = GetPort(values[values.Length - 1]);
  369. }
  370. else //[a:b:c] or a:b:c
  371. {
  372. ipaddy = IPAddress.Parse(endpointstring);
  373. port = defaultport;
  374. }
  375. }
  376. else
  377. {
  378. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  379. }
  380. if (port == -1)
  381. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  382. return new IPEndPoint(ipaddy, port);
  383. }
  384. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  385. /// <summary>
  386. /// Gets the port.
  387. /// </summary>
  388. /// <param name="p">The p.</param>
  389. /// <returns>System.Int32.</returns>
  390. /// <exception cref="System.FormatException"></exception>
  391. private static int GetPort(string p)
  392. {
  393. int port;
  394. if (!Int32.TryParse(p, out port)
  395. || port < IPEndPoint.MinPort
  396. || port > IPEndPoint.MaxPort)
  397. {
  398. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  399. }
  400. return port;
  401. }
  402. /// <summary>
  403. /// Gets the I pfrom host.
  404. /// </summary>
  405. /// <param name="p">The p.</param>
  406. /// <returns>IPAddress.</returns>
  407. /// <exception cref="System.ArgumentException"></exception>
  408. private static async Task<IPAddress> GetIPfromHost(string p)
  409. {
  410. var hosts = await Dns.GetHostAddressesAsync(p).ConfigureAwait(false);
  411. if (hosts == null || hosts.Length == 0)
  412. throw new ArgumentException(String.Format("Host not found: {0}", p));
  413. return hosts[0];
  414. }
  415. public IpAddressInfo ParseIpAddress(string ipAddress)
  416. {
  417. IpAddressInfo info;
  418. if (TryParseIpAddress(ipAddress, out info))
  419. {
  420. return info;
  421. }
  422. throw new ArgumentException("Invalid ip address: " + ipAddress);
  423. }
  424. public bool TryParseIpAddress(string ipAddress, out IpAddressInfo ipAddressInfo)
  425. {
  426. IPAddress address;
  427. if (IPAddress.TryParse(ipAddress, out address))
  428. {
  429. ipAddressInfo = ToIpAddressInfo(address);
  430. return true;
  431. }
  432. ipAddressInfo = null;
  433. return false;
  434. }
  435. public static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  436. {
  437. if (endpoint == null)
  438. {
  439. return null;
  440. }
  441. return new IpEndPointInfo(ToIpAddressInfo(endpoint.Address), endpoint.Port);
  442. }
  443. public static IPEndPoint ToIPEndPoint(IpEndPointInfo endpoint)
  444. {
  445. if (endpoint == null)
  446. {
  447. return null;
  448. }
  449. return new IPEndPoint(ToIPAddress(endpoint.IpAddress), endpoint.Port);
  450. }
  451. public static IPAddress ToIPAddress(IpAddressInfo address)
  452. {
  453. if (address.Equals(IpAddressInfo.Any))
  454. {
  455. return IPAddress.Any;
  456. }
  457. if (address.Equals(IpAddressInfo.IPv6Any))
  458. {
  459. return IPAddress.IPv6Any;
  460. }
  461. if (address.Equals(IpAddressInfo.Loopback))
  462. {
  463. return IPAddress.Loopback;
  464. }
  465. if (address.Equals(IpAddressInfo.IPv6Loopback))
  466. {
  467. return IPAddress.IPv6Loopback;
  468. }
  469. return IPAddress.Parse(address.Address);
  470. }
  471. public static IpAddressInfo ToIpAddressInfo(IPAddress address)
  472. {
  473. if (address.Equals(IPAddress.Any))
  474. {
  475. return IpAddressInfo.Any;
  476. }
  477. if (address.Equals(IPAddress.IPv6Any))
  478. {
  479. return IpAddressInfo.IPv6Any;
  480. }
  481. if (address.Equals(IPAddress.Loopback))
  482. {
  483. return IpAddressInfo.Loopback;
  484. }
  485. if (address.Equals(IPAddress.IPv6Loopback))
  486. {
  487. return IpAddressInfo.IPv6Loopback;
  488. }
  489. return new IpAddressInfo(address.ToString(), address.AddressFamily == AddressFamily.InterNetworkV6 ? IpAddressFamily.InterNetworkV6 : IpAddressFamily.InterNetwork);
  490. }
  491. public async Task<IpAddressInfo[]> GetHostAddressesAsync(string host)
  492. {
  493. var addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
  494. return addresses.Select(ToIpAddressInfo).ToArray(addresses.Length);
  495. }
  496. /// <summary>
  497. /// Gets the network shares.
  498. /// </summary>
  499. /// <param name="path">The path.</param>
  500. /// <returns>IEnumerable{NetworkShare}.</returns>
  501. public virtual IEnumerable<NetworkShare> GetNetworkShares(string path)
  502. {
  503. return new List<NetworkShare>();
  504. }
  505. /// <summary>
  506. /// Gets available devices within the domain
  507. /// </summary>
  508. /// <returns>PC's in the Domain</returns>
  509. public virtual IEnumerable<FileSystemEntryInfo> GetNetworkDevices()
  510. {
  511. return new List<FileSystemEntryInfo>();
  512. }
  513. }
  514. }