NetworkManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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.Tasks;
  10. using MediaBrowser.Model.Extensions;
  11. using MediaBrowser.Model.Net;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Common.Net;
  14. namespace Emby.Common.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 = 5;
  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 readonly List<NetworkInterfaceType> _validNetworkInterfaceTypes = new List<NetworkInterfaceType>
  167. {
  168. NetworkInterfaceType.Ethernet,
  169. NetworkInterfaceType.Wireless80211
  170. };
  171. private List<IPAddress> GetIPsDefault()
  172. {
  173. NetworkInterface[] interfaces;
  174. try
  175. {
  176. var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown };
  177. interfaces = NetworkInterface.GetAllNetworkInterfaces()
  178. .Where(i => validStatuses.Contains(i.OperationalStatus))
  179. .ToArray();
  180. }
  181. catch (Exception ex)
  182. {
  183. Logger.ErrorException("Error in GetAllNetworkInterfaces", ex);
  184. return new List<IPAddress>();
  185. }
  186. return interfaces.SelectMany(network =>
  187. {
  188. try
  189. {
  190. Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
  191. var ipProperties = network.GetIPProperties();
  192. // Try to exclude virtual adapters
  193. // http://stackoverflow.com/questions/8089685/c-sharp-finding-my-machines-local-ip-address-and-not-the-vms
  194. var addr = ipProperties.GatewayAddresses.FirstOrDefault();
  195. if (addr == null|| string.Equals(addr.Address.ToString(), "0.0.0.0", StringComparison.OrdinalIgnoreCase))
  196. {
  197. return new List<IPAddress>();
  198. }
  199. //if (!_validNetworkInterfaceTypes.Contains(network.NetworkInterfaceType))
  200. //{
  201. // return new List<IPAddress>();
  202. //}
  203. return ipProperties.UnicastAddresses
  204. //.Where(i => i.IsDnsEligible)
  205. .Select(i => i.Address)
  206. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  207. .ToList();
  208. }
  209. catch (Exception ex)
  210. {
  211. Logger.ErrorException("Error querying network interface", ex);
  212. return new List<IPAddress>();
  213. }
  214. }).DistinctBy(i => i.ToString())
  215. .ToList();
  216. }
  217. private async Task<IEnumerable<IPAddress>> GetLocalIpAddressesFallback()
  218. {
  219. var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false);
  220. // Reverse them because the last one is usually the correct one
  221. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  222. return host.AddressList
  223. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  224. .Reverse();
  225. }
  226. /// <summary>
  227. /// Gets a random port number that is currently available
  228. /// </summary>
  229. /// <returns>System.Int32.</returns>
  230. public int GetRandomUnusedPort()
  231. {
  232. var listener = new TcpListener(IPAddress.Any, 0);
  233. listener.Start();
  234. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  235. listener.Stop();
  236. return port;
  237. }
  238. /// <summary>
  239. /// Returns MAC Address from first Network Card in Computer
  240. /// </summary>
  241. /// <returns>[string] MAC Address</returns>
  242. public string GetMacAddress()
  243. {
  244. return NetworkInterface.GetAllNetworkInterfaces()
  245. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  246. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  247. .FirstOrDefault();
  248. }
  249. /// <summary>
  250. /// Parses the specified endpointstring.
  251. /// </summary>
  252. /// <param name="endpointstring">The endpointstring.</param>
  253. /// <returns>IPEndPoint.</returns>
  254. public IPEndPoint Parse(string endpointstring)
  255. {
  256. return Parse(endpointstring, -1).Result;
  257. }
  258. /// <summary>
  259. /// Parses the specified endpointstring.
  260. /// </summary>
  261. /// <param name="endpointstring">The endpointstring.</param>
  262. /// <param name="defaultport">The defaultport.</param>
  263. /// <returns>IPEndPoint.</returns>
  264. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  265. /// <exception cref="System.FormatException"></exception>
  266. private static async Task<IPEndPoint> Parse(string endpointstring, int defaultport)
  267. {
  268. if (String.IsNullOrEmpty(endpointstring)
  269. || endpointstring.Trim().Length == 0)
  270. {
  271. throw new ArgumentException("Endpoint descriptor may not be empty.");
  272. }
  273. if (defaultport != -1 &&
  274. (defaultport < IPEndPoint.MinPort
  275. || defaultport > IPEndPoint.MaxPort))
  276. {
  277. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  278. }
  279. string[] values = endpointstring.Split(new char[] { ':' });
  280. IPAddress ipaddy;
  281. int port = -1;
  282. //check if we have an IPv6 or ports
  283. if (values.Length <= 2) // ipv4 or hostname
  284. {
  285. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  286. //try to use the address as IPv4, otherwise get hostname
  287. if (!IPAddress.TryParse(values[0], out ipaddy))
  288. ipaddy = await GetIPfromHost(values[0]).ConfigureAwait(false);
  289. }
  290. else if (values.Length > 2) //ipv6
  291. {
  292. //could [a:b:c]:d
  293. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  294. {
  295. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  296. ipaddy = IPAddress.Parse(ipaddressstring);
  297. port = GetPort(values[values.Length - 1]);
  298. }
  299. else //[a:b:c] or a:b:c
  300. {
  301. ipaddy = IPAddress.Parse(endpointstring);
  302. port = defaultport;
  303. }
  304. }
  305. else
  306. {
  307. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  308. }
  309. if (port == -1)
  310. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  311. return new IPEndPoint(ipaddy, port);
  312. }
  313. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  314. /// <summary>
  315. /// Gets the port.
  316. /// </summary>
  317. /// <param name="p">The p.</param>
  318. /// <returns>System.Int32.</returns>
  319. /// <exception cref="System.FormatException"></exception>
  320. private static int GetPort(string p)
  321. {
  322. int port;
  323. if (!Int32.TryParse(p, out port)
  324. || port < IPEndPoint.MinPort
  325. || port > IPEndPoint.MaxPort)
  326. {
  327. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  328. }
  329. return port;
  330. }
  331. /// <summary>
  332. /// Gets the I pfrom host.
  333. /// </summary>
  334. /// <param name="p">The p.</param>
  335. /// <returns>IPAddress.</returns>
  336. /// <exception cref="System.ArgumentException"></exception>
  337. private static async Task<IPAddress> GetIPfromHost(string p)
  338. {
  339. var hosts = await Dns.GetHostAddressesAsync(p).ConfigureAwait(false);
  340. if (hosts == null || hosts.Length == 0)
  341. throw new ArgumentException(String.Format("Host not found: {0}", p));
  342. return hosts[0];
  343. }
  344. public IpAddressInfo ParseIpAddress(string ipAddress)
  345. {
  346. IpAddressInfo info;
  347. if (TryParseIpAddress(ipAddress, out info))
  348. {
  349. return info;
  350. }
  351. throw new ArgumentException("Invalid ip address: " + ipAddress);
  352. }
  353. public bool TryParseIpAddress(string ipAddress, out IpAddressInfo ipAddressInfo)
  354. {
  355. IPAddress address;
  356. if (IPAddress.TryParse(ipAddress, out address))
  357. {
  358. ipAddressInfo = ToIpAddressInfo(address);
  359. return true;
  360. }
  361. ipAddressInfo = null;
  362. return false;
  363. }
  364. public static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  365. {
  366. if (endpoint == null)
  367. {
  368. return null;
  369. }
  370. return new IpEndPointInfo(ToIpAddressInfo(endpoint.Address), endpoint.Port);
  371. }
  372. public static IPEndPoint ToIPEndPoint(IpEndPointInfo endpoint)
  373. {
  374. if (endpoint == null)
  375. {
  376. return null;
  377. }
  378. return new IPEndPoint(ToIPAddress(endpoint.IpAddress), endpoint.Port);
  379. }
  380. public static IPAddress ToIPAddress(IpAddressInfo address)
  381. {
  382. if (address.Equals(IpAddressInfo.Any))
  383. {
  384. return IPAddress.Any;
  385. }
  386. if (address.Equals(IpAddressInfo.IPv6Any))
  387. {
  388. return IPAddress.IPv6Any;
  389. }
  390. if (address.Equals(IpAddressInfo.Loopback))
  391. {
  392. return IPAddress.Loopback;
  393. }
  394. if (address.Equals(IpAddressInfo.IPv6Loopback))
  395. {
  396. return IPAddress.IPv6Loopback;
  397. }
  398. return IPAddress.Parse(address.Address);
  399. }
  400. public static IpAddressInfo ToIpAddressInfo(IPAddress address)
  401. {
  402. if (address.Equals(IPAddress.Any))
  403. {
  404. return IpAddressInfo.Any;
  405. }
  406. if (address.Equals(IPAddress.IPv6Any))
  407. {
  408. return IpAddressInfo.IPv6Any;
  409. }
  410. if (address.Equals(IPAddress.Loopback))
  411. {
  412. return IpAddressInfo.Loopback;
  413. }
  414. if (address.Equals(IPAddress.IPv6Loopback))
  415. {
  416. return IpAddressInfo.IPv6Loopback;
  417. }
  418. return new IpAddressInfo
  419. {
  420. Address = address.ToString(),
  421. AddressFamily = address.AddressFamily == AddressFamily.InterNetworkV6 ? IpAddressFamily.InterNetworkV6 : IpAddressFamily.InterNetwork
  422. };
  423. }
  424. public async Task<IpAddressInfo[]> GetHostAddressesAsync(string host)
  425. {
  426. var addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
  427. return addresses.Select(ToIpAddressInfo).ToArray();
  428. }
  429. /// <summary>
  430. /// Gets the network shares.
  431. /// </summary>
  432. /// <param name="path">The path.</param>
  433. /// <returns>IEnumerable{NetworkShare}.</returns>
  434. public virtual IEnumerable<NetworkShare> GetNetworkShares(string path)
  435. {
  436. return new List<NetworkShare>();
  437. }
  438. /// <summary>
  439. /// Gets available devices within the domain
  440. /// </summary>
  441. /// <returns>PC's in the Domain</returns>
  442. public virtual IEnumerable<FileSystemEntryInfo> GetNetworkDevices()
  443. {
  444. return new List<FileSystemEntryInfo>();
  445. }
  446. }
  447. }