IPHost.cs 15 KB

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