IPHost.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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.IsNullOrEmpty(host))
  117. {
  118. // See if it's an IPv6 with port address e.g. [::1]:120.
  119. int i = host.IndexOf("]:", StringComparison.OrdinalIgnoreCase);
  120. if (i != -1)
  121. {
  122. return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
  123. }
  124. else
  125. {
  126. // See if it's an IPv6 in [] with no port.
  127. i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase);
  128. if (i != -1)
  129. {
  130. return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
  131. }
  132. // Is it a host or IPv4 with port?
  133. string[] hosts = host.Split(':');
  134. if (hosts.Length > 2)
  135. {
  136. hostObj = new IPHost(string.Empty, IPAddress.None);
  137. return false;
  138. }
  139. // Remove port from IPv4 if it exists.
  140. host = hosts[0];
  141. if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase))
  142. {
  143. hostObj = new IPHost(host, new IPAddress(Ipv4Loopback));
  144. return true;
  145. }
  146. if (IPNetAddress.TryParse(host, out IPNetAddress netIP))
  147. {
  148. // Host name is an ip address, so fake resolve.
  149. hostObj = new IPHost(host, netIP.Address);
  150. return true;
  151. }
  152. }
  153. // Only thing left is to see if it's a host string.
  154. if (!string.IsNullOrEmpty(host))
  155. {
  156. // Use regular expression as CheckHostName isn't RFC5892 compliant.
  157. // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
  158. Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
  159. if (re.Match(host).Success)
  160. {
  161. hostObj = new IPHost(host);
  162. return true;
  163. }
  164. }
  165. }
  166. hostObj = IPHost.None;
  167. return false;
  168. }
  169. /// <summary>
  170. /// Attempts to parse the host string.
  171. /// </summary>
  172. /// <param name="host">Host name to parse.</param>
  173. /// <returns>Object representing the string, if it has successfully been parsed.</returns>
  174. public static IPHost Parse(string host)
  175. {
  176. if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
  177. {
  178. return res;
  179. }
  180. throw new InvalidCastException("Host does not contain a valid value. {host}");
  181. }
  182. /// <summary>
  183. /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
  184. /// </summary>
  185. /// <param name="host">Host name to parse.</param>
  186. /// <param name="family">Addressfamily filter.</param>
  187. /// <returns>Object representing the string, if it has successfully been parsed.</returns>
  188. public static IPHost Parse(string host, AddressFamily family)
  189. {
  190. if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
  191. {
  192. if (family == AddressFamily.InterNetwork)
  193. {
  194. res.Remove(AddressFamily.InterNetworkV6);
  195. }
  196. else
  197. {
  198. res.Remove(AddressFamily.InterNetwork);
  199. }
  200. return res;
  201. }
  202. throw new InvalidCastException("Host does not contain a valid value. {host}");
  203. }
  204. /// <summary>
  205. /// Returns the Addresses that this item resolved to.
  206. /// </summary>
  207. /// <returns>IPAddress Array.</returns>
  208. public IPAddress[] GetAddresses()
  209. {
  210. ResolveHost();
  211. return _addresses;
  212. }
  213. /// <inheritdoc/>
  214. public override bool Contains(IPAddress address)
  215. {
  216. if (address != null && !Address.Equals(IPAddress.None))
  217. {
  218. if (address.IsIPv4MappedToIPv6)
  219. {
  220. address = address.MapToIPv4();
  221. }
  222. foreach (var addr in GetAddresses())
  223. {
  224. if (address.Equals(addr))
  225. {
  226. return true;
  227. }
  228. }
  229. }
  230. return false;
  231. }
  232. /// <inheritdoc/>
  233. public override bool Equals(IPObject? other)
  234. {
  235. if (other is IPHost otherObj)
  236. {
  237. // Do we have the name Hostname?
  238. if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase))
  239. {
  240. return true;
  241. }
  242. if (!ResolveHost() || !otherObj.ResolveHost())
  243. {
  244. return false;
  245. }
  246. // Do any of our IP addresses match?
  247. foreach (IPAddress addr in _addresses)
  248. {
  249. foreach (IPAddress otherAddress in otherObj._addresses)
  250. {
  251. if (addr.Equals(otherAddress))
  252. {
  253. return true;
  254. }
  255. }
  256. }
  257. }
  258. return false;
  259. }
  260. /// <inheritdoc/>
  261. public override bool IsIP6()
  262. {
  263. // Returns true if interfaces are only IP6.
  264. if (ResolveHost())
  265. {
  266. foreach (IPAddress i in _addresses)
  267. {
  268. if (i.AddressFamily != AddressFamily.InterNetworkV6)
  269. {
  270. return false;
  271. }
  272. }
  273. return true;
  274. }
  275. return false;
  276. }
  277. /// <inheritdoc/>
  278. public override string ToString()
  279. {
  280. // StringBuilder not optimum here.
  281. string output = string.Empty;
  282. if (_addresses.Length > 0)
  283. {
  284. bool moreThanOne = _addresses.Length > 1;
  285. if (moreThanOne)
  286. {
  287. output = "[";
  288. }
  289. foreach (var i in _addresses)
  290. {
  291. if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified)
  292. {
  293. output += HostName + ",";
  294. }
  295. else if (i.Equals(IPAddress.Any))
  296. {
  297. output += "Any IP4 Address,";
  298. }
  299. else if (Address.Equals(IPAddress.IPv6Any))
  300. {
  301. output += "Any IP6 Address,";
  302. }
  303. else if (i.Equals(IPAddress.Broadcast))
  304. {
  305. output += "Any Address,";
  306. }
  307. else
  308. {
  309. output += $"{i}/32,";
  310. }
  311. }
  312. output = output[0..^1];
  313. if (moreThanOne)
  314. {
  315. output += "]";
  316. }
  317. }
  318. else
  319. {
  320. output = HostName;
  321. }
  322. return output;
  323. }
  324. /// <inheritdoc/>
  325. public override void Remove(AddressFamily family)
  326. {
  327. if (ResolveHost())
  328. {
  329. _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray();
  330. }
  331. }
  332. /// <inheritdoc/>
  333. public override bool Contains(IPObject address)
  334. {
  335. // An IPHost cannot contain another IPObject, it can only be equal.
  336. return Equals(address);
  337. }
  338. /// <inheritdoc/>
  339. protected override IPObject CalculateNetworkAddress()
  340. {
  341. var netAddr = NetworkAddressOf(this[0], PrefixLength);
  342. return new IPNetAddress(netAddr.Address, netAddr.PrefixLength);
  343. }
  344. /// <summary>
  345. /// Attempt to resolve the ip address of a host.
  346. /// </summary>
  347. /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns>
  348. private bool ResolveHost()
  349. {
  350. // When was the last time we resolved?
  351. if (_lastResolved == null)
  352. {
  353. _lastResolved = DateTime.UtcNow;
  354. }
  355. // If we haven't resolved before, or our timer has run out...
  356. if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved?.AddMinutes(Timeout)))
  357. {
  358. _lastResolved = DateTime.UtcNow;
  359. ResolveHostInternal().GetAwaiter().GetResult();
  360. Resolved = true;
  361. }
  362. return _addresses.Length > 0;
  363. }
  364. /// <summary>
  365. /// Task that looks up a Host name and returns its IP addresses.
  366. /// </summary>
  367. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  368. private async Task ResolveHostInternal()
  369. {
  370. if (!string.IsNullOrEmpty(HostName))
  371. {
  372. // Resolves the host name - so save a DNS lookup.
  373. if (string.Equals(HostName, "localhost", StringComparison.OrdinalIgnoreCase))
  374. {
  375. _addresses = new IPAddress[] { new IPAddress(Ipv4Loopback), new IPAddress(Ipv6Loopback) };
  376. return;
  377. }
  378. if (Uri.CheckHostName(HostName).Equals(UriHostNameType.Dns))
  379. {
  380. try
  381. {
  382. IPHostEntry ip = await Dns.GetHostEntryAsync(HostName).ConfigureAwait(false);
  383. _addresses = ip.AddressList;
  384. }
  385. catch (SocketException ex)
  386. {
  387. // Log and then ignore socket errors, as the result value will just be an empty array.
  388. Debug.WriteLine("GetHostEntryAsync failed with {Message}.", ex.Message);
  389. }
  390. }
  391. }
  392. }
  393. }
  394. }