IPHost.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text.RegularExpressions;
  7. using System.Threading.Tasks;
  8. namespace MediaBrowser.Common.Net
  9. {
  10. /// <summary>
  11. /// Object that holds a host name.
  12. /// </summary>
  13. public class IPHost : IPObject
  14. {
  15. /// <summary>
  16. /// Gets or sets timeout value before resolve required, in minutes.
  17. /// </summary>
  18. public const int Timeout = 30;
  19. /// <summary>
  20. /// Represents an IPHost that has no value.
  21. /// </summary>
  22. public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
  23. /// <summary>
  24. /// Time when last resolved in ticks.
  25. /// </summary>
  26. private DateTime? _lastResolved = null;
  27. /// <summary>
  28. /// Gets the IP Addresses, attempting to resolve the name, if there are none.
  29. /// </summary>
  30. private IPAddress[] _addresses;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="IPHost"/> class.
  33. /// </summary>
  34. /// <param name="name">Host name to assign.</param>
  35. public IPHost(string name)
  36. {
  37. HostName = name ?? throw new ArgumentNullException(nameof(name));
  38. _addresses = Array.Empty<IPAddress>();
  39. Resolved = false;
  40. }
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="IPHost"/> class.
  43. /// </summary>
  44. /// <param name="name">Host name to assign.</param>
  45. /// <param name="address">Address to assign.</param>
  46. private IPHost(string name, IPAddress address)
  47. {
  48. HostName = name ?? throw new ArgumentNullException(nameof(name));
  49. _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) };
  50. Resolved = !address.Equals(IPAddress.None);
  51. }
  52. /// <summary>
  53. /// Gets or sets the object's first IP address.
  54. /// </summary>
  55. public override IPAddress Address
  56. {
  57. get
  58. {
  59. return ResolveHost() ? this[0] : IPAddress.None;
  60. }
  61. set
  62. {
  63. // Not implemented, as a host's address is determined by DNS.
  64. throw new NotImplementedException("The address of a host is determined by DNS.");
  65. }
  66. }
  67. /// <summary>
  68. /// Gets or sets the object's first IP's subnet prefix.
  69. /// The setter does nothing, but shouldn't raise an exception.
  70. /// </summary>
  71. public override byte PrefixLength
  72. {
  73. get => (byte)(ResolveHost() ? 128 : 32);
  74. // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length,
  75. // which is automatically determined by it's IP type. Anything else is meaningless.
  76. set => throw new NotImplementedException();
  77. }
  78. /// <summary>
  79. /// Gets a value indicating whether the address has a value.
  80. /// </summary>
  81. public bool HasAddress => _addresses.Length != 0;
  82. /// <summary>
  83. /// Gets the host name of this object.
  84. /// </summary>
  85. public string HostName { get; }
  86. /// <summary>
  87. /// Gets a value indicating whether this host has attempted to be resolved.
  88. /// </summary>
  89. public bool Resolved { get; private set; }
  90. /// <summary>
  91. /// Gets or sets the IP Addresses associated with this object.
  92. /// </summary>
  93. /// <param name="index">Index of address.</param>
  94. public IPAddress this[int index]
  95. {
  96. get
  97. {
  98. ResolveHost();
  99. return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None;
  100. }
  101. }
  102. /// <summary>
  103. /// Attempts to parse the host string.
  104. /// </summary>
  105. /// <param name="host">Host name to parse.</param>
  106. /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param>
  107. /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
  108. public static bool TryParse(string host, out IPHost hostObj)
  109. {
  110. if (string.IsNullOrWhiteSpace(host))
  111. {
  112. hostObj = IPHost.None;
  113. return false;
  114. }
  115. // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
  116. int i = host.IndexOf(']', StringComparison.Ordinal);
  117. if (i != -1)
  118. {
  119. return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
  120. }
  121. if (IPNetAddress.TryParse(host, out var netAddress))
  122. {
  123. // Host name is an ip address, so fake resolve.
  124. hostObj = new IPHost(host, netAddress.Address);
  125. return true;
  126. }
  127. // Is it a host, IPv4/6 with/out port?
  128. string[] hosts = host.Split(':');
  129. if (hosts.Length <= 2)
  130. {
  131. // This is either a hostname: port, or an IP4:port.
  132. host = hosts[0];
  133. if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase))
  134. {
  135. hostObj = new IPHost(host);
  136. return true;
  137. }
  138. if (IPAddress.TryParse(host, out var netIP))
  139. {
  140. // Host name is an ip address, so fake resolve.
  141. hostObj = new IPHost(host, netIP);
  142. return true;
  143. }
  144. }
  145. else
  146. {
  147. // Invalid host name, as it cannot contain :
  148. hostObj = new IPHost(string.Empty, IPAddress.None);
  149. return false;
  150. }
  151. // Use regular expression as CheckHostName isn't RFC5892 compliant.
  152. // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
  153. string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$";
  154. if (Regex.IsMatch(host, pattern))
  155. {
  156. hostObj = new IPHost(host);
  157. return true;
  158. }
  159. hostObj = IPHost.None;
  160. return false;
  161. }
  162. /// <summary>
  163. /// Attempts to parse the host string.
  164. /// </summary>
  165. /// <param name="host">Host name to parse.</param>
  166. /// <returns>Object representing the string, if it has successfully been parsed.</returns>
  167. public static IPHost Parse(string host)
  168. {
  169. if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
  170. {
  171. return res;
  172. }
  173. throw new InvalidCastException("Host does not contain a valid value. {host}");
  174. }
  175. /// <summary>
  176. /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
  177. /// </summary>
  178. /// <param name="host">Host name to parse.</param>
  179. /// <param name="family">Addressfamily filter.</param>
  180. /// <returns>Object representing the string, if it has successfully been parsed.</returns>
  181. public static IPHost Parse(string host, AddressFamily family)
  182. {
  183. if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
  184. {
  185. if (family == AddressFamily.InterNetwork)
  186. {
  187. res.Remove(AddressFamily.InterNetworkV6);
  188. }
  189. else
  190. {
  191. res.Remove(AddressFamily.InterNetwork);
  192. }
  193. return res;
  194. }
  195. throw new InvalidCastException("Host does not contain a valid value. {host}");
  196. }
  197. /// <summary>
  198. /// Returns the Addresses that this item resolved to.
  199. /// </summary>
  200. /// <returns>IPAddress Array.</returns>
  201. public IPAddress[] GetAddresses()
  202. {
  203. ResolveHost();
  204. return _addresses;
  205. }
  206. /// <inheritdoc/>
  207. public override bool Contains(IPAddress address)
  208. {
  209. if (address != null && !Address.Equals(IPAddress.None))
  210. {
  211. if (address.IsIPv4MappedToIPv6)
  212. {
  213. address = address.MapToIPv4();
  214. }
  215. foreach (var addr in GetAddresses())
  216. {
  217. if (address.Equals(addr))
  218. {
  219. return true;
  220. }
  221. }
  222. }
  223. return false;
  224. }
  225. /// <inheritdoc/>
  226. public override bool Equals(IPObject? other)
  227. {
  228. if (other is IPHost otherObj)
  229. {
  230. // Do we have the name Hostname?
  231. if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase))
  232. {
  233. return true;
  234. }
  235. if (!ResolveHost() || !otherObj.ResolveHost())
  236. {
  237. return false;
  238. }
  239. // Do any of our IP addresses match?
  240. foreach (IPAddress addr in _addresses)
  241. {
  242. foreach (IPAddress otherAddress in otherObj._addresses)
  243. {
  244. if (addr.Equals(otherAddress))
  245. {
  246. return true;
  247. }
  248. }
  249. }
  250. }
  251. return false;
  252. }
  253. /// <inheritdoc/>
  254. public override bool IsIP6()
  255. {
  256. // Returns true if interfaces are only IP6.
  257. if (ResolveHost())
  258. {
  259. foreach (IPAddress i in _addresses)
  260. {
  261. if (i.AddressFamily != AddressFamily.InterNetworkV6)
  262. {
  263. return false;
  264. }
  265. }
  266. return true;
  267. }
  268. return false;
  269. }
  270. /// <inheritdoc/>
  271. public override string ToString()
  272. {
  273. // StringBuilder not optimum here.
  274. string output = string.Empty;
  275. if (_addresses.Length > 0)
  276. {
  277. bool moreThanOne = _addresses.Length > 1;
  278. if (moreThanOne)
  279. {
  280. output = "[";
  281. }
  282. foreach (var i in _addresses)
  283. {
  284. if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified)
  285. {
  286. output += HostName + ",";
  287. }
  288. else if (i.Equals(IPAddress.Any))
  289. {
  290. output += "Any IP4 Address,";
  291. }
  292. else if (Address.Equals(IPAddress.IPv6Any))
  293. {
  294. output += "Any IP6 Address,";
  295. }
  296. else if (i.Equals(IPAddress.Broadcast))
  297. {
  298. output += "Any Address,";
  299. }
  300. else if (i.AddressFamily == AddressFamily.InterNetwork)
  301. {
  302. output += $"{i}/32,";
  303. }
  304. else
  305. {
  306. output += $"{i}/128,";
  307. }
  308. }
  309. output = output[0..^1];
  310. if (moreThanOne)
  311. {
  312. output += "]";
  313. }
  314. }
  315. else
  316. {
  317. output = HostName;
  318. }
  319. return output;
  320. }
  321. /// <inheritdoc/>
  322. public override void Remove(AddressFamily family)
  323. {
  324. if (ResolveHost())
  325. {
  326. _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray();
  327. }
  328. }
  329. /// <inheritdoc/>
  330. public override bool Contains(IPObject address)
  331. {
  332. // An IPHost cannot contain another IPObject, it can only be equal.
  333. return Equals(address);
  334. }
  335. /// <inheritdoc/>
  336. protected override IPObject CalculateNetworkAddress()
  337. {
  338. var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength);
  339. return new IPNetAddress(address, prefixLength);
  340. }
  341. /// <summary>
  342. /// Attempt to resolve the ip address of a host.
  343. /// </summary>
  344. /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns>
  345. private bool ResolveHost()
  346. {
  347. // When was the last time we resolved?
  348. _lastResolved ??= DateTime.UtcNow;
  349. // If we haven't resolved before, or our timer has run out...
  350. if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout)))
  351. {
  352. _lastResolved = DateTime.UtcNow;
  353. ResolveHostInternal().GetAwaiter().GetResult();
  354. Resolved = true;
  355. }
  356. return _addresses.Length > 0;
  357. }
  358. /// <summary>
  359. /// Task that looks up a Host name and returns its IP addresses.
  360. /// </summary>
  361. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  362. private async Task ResolveHostInternal()
  363. {
  364. if (!string.IsNullOrEmpty(HostName))
  365. {
  366. // Resolves the host name - so save a DNS lookup.
  367. if (string.Equals(HostName, "localhost", StringComparison.OrdinalIgnoreCase))
  368. {
  369. _addresses = new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback };
  370. return;
  371. }
  372. if (Uri.CheckHostName(HostName).Equals(UriHostNameType.Dns))
  373. {
  374. try
  375. {
  376. IPHostEntry ip = await Dns.GetHostEntryAsync(HostName).ConfigureAwait(false);
  377. _addresses = ip.AddressList;
  378. }
  379. catch (SocketException ex)
  380. {
  381. // Log and then ignore socket errors, as the result value will just be an empty array.
  382. Debug.WriteLine("GetHostEntryAsync failed with {Message}.", ex.Message);
  383. }
  384. }
  385. }
  386. }
  387. }
  388. }