IPHost.cs 15 KB

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