NetworkManager.cs 19 KB

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