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