IPHost.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #nullable enable
  2. using System;
  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. /// Represents an IPHost that has no value.
  17. /// </summary>
  18. public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
  19. /// <summary>
  20. /// Time when last resolved.
  21. /// </summary>
  22. private long _lastResolved;
  23. /// <summary>
  24. /// Gets the IP Addresses, attempting to resolve the name, if there are none.
  25. /// </summary>
  26. private IPAddress[] _addresses;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="IPHost"/> class.
  29. /// </summary>
  30. /// <param name="name">Host name to assign.</param>
  31. public IPHost(string name)
  32. {
  33. HostName = name ?? throw new ArgumentNullException(nameof(name));
  34. _addresses = Array.Empty<IPAddress>();
  35. Resolved = false;
  36. }
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="IPHost"/> class.
  39. /// </summary>
  40. /// <param name="name">Host name to assign.</param>
  41. /// <param name="address">Address to assign.</param>
  42. private IPHost(string name, IPAddress address)
  43. {
  44. HostName = name ?? throw new ArgumentNullException(nameof(name));
  45. _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) };
  46. Resolved = !address.Equals(IPAddress.None);
  47. }
  48. /// <summary>
  49. /// Gets or sets the object's first IP address.
  50. /// </summary>
  51. public override IPAddress Address
  52. {
  53. get
  54. {
  55. return ResolveHost() ? this[0] : IPAddress.None;
  56. }
  57. set
  58. {
  59. // Not implemented.
  60. }
  61. }
  62. /// <summary>
  63. /// Gets or sets the object's first IP's subnet prefix.
  64. /// The setter does nothing, but shouldn't raise an exception.
  65. /// </summary>
  66. public override byte PrefixLength
  67. {
  68. get
  69. {
  70. return (byte)(ResolveHost() ? 128 : 0);
  71. }
  72. set
  73. {
  74. // Not implemented.
  75. }
  76. }
  77. /// <summary>
  78. /// Gets or sets timeout value before resolve required, in minutes.
  79. /// </summary>
  80. public byte Timeout { get; set; } = 30;
  81. /// <summary>
  82. /// Gets a value indicating whether the address has a value.
  83. /// </summary>
  84. public bool HasAddress
  85. {
  86. get
  87. {
  88. return _addresses.Length > 0;
  89. }
  90. }
  91. /// <summary>
  92. /// Gets the host name of this object.
  93. /// </summary>
  94. public string HostName { get; }
  95. /// <summary>
  96. /// Gets a value indicating whether this host has attempted to be resolved.
  97. /// </summary>
  98. public bool Resolved { get; private set; }
  99. /// <summary>
  100. /// Gets or sets the IP Addresses associated with this object.
  101. /// </summary>
  102. /// <param name="index">Index of address.</param>
  103. public IPAddress this[int index]
  104. {
  105. get
  106. {
  107. ResolveHost();
  108. return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None;
  109. }
  110. }
  111. /// <summary>
  112. /// Attempts to parse the host string.
  113. /// </summary>
  114. /// <param name="host">Host name to parse.</param>
  115. /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param>
  116. /// <returns>Success result of the parsing.</returns>
  117. public static bool TryParse(string host, out IPHost hostObj)
  118. {
  119. if (!string.IsNullOrEmpty(host))
  120. {
  121. // See if it's an IPv6 with port address e.g. [::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. else
  128. {
  129. // See if it's an IPv6 in [] with no port.
  130. i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase);
  131. if (i != -1)
  132. {
  133. return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
  134. }
  135. // Is it a host or IPv4 with port?
  136. string[] hosts = host.Split(':');
  137. if (hosts.Length > 2)
  138. {
  139. hostObj = new IPHost(string.Empty, IPAddress.None);
  140. return false;
  141. }
  142. // Remove port from IPv4 if it exists.
  143. host = hosts[0];
  144. if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase))
  145. {
  146. hostObj = new IPHost(host, new IPAddress(Ipv4Loopback));
  147. return true;
  148. }
  149. if (IPNetAddress.TryParse(host, out IPNetAddress netIP))
  150. {
  151. // Host name is an ip address, so fake resolve.
  152. hostObj = new IPHost(host, netIP.Address);
  153. return true;
  154. }
  155. }
  156. // Only thing left is to see if it's a host string.
  157. if (!string.IsNullOrEmpty(host))
  158. {
  159. // Use regular expression as CheckHostName isn't RFC5892 compliant.
  160. // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
  161. Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
  162. if (re.Match(host).Success)
  163. {
  164. hostObj = new IPHost(host);
  165. return true;
  166. }
  167. }
  168. }
  169. hostObj = IPHost.None;
  170. return false;
  171. }
  172. /// <summary>
  173. /// Attempts to parse the host string.
  174. /// </summary>
  175. /// <param name="host">Host name to parse.</param>
  176. /// <returns>Object representing the string, if it has successfully been parsed.</returns>
  177. public static IPHost Parse(string host)
  178. {
  179. if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
  180. {
  181. return res;
  182. }
  183. throw new InvalidCastException("Host does not contain a valid value. {host}");
  184. }
  185. /// <summary>
  186. /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
  187. /// </summary>
  188. /// <param name="host">Host name to parse.</param>
  189. /// <param name="family">Addressfamily filter.</param>
  190. /// <returns>Object representing the string, if it has successfully been parsed.</returns>
  191. public static IPHost Parse(string host, AddressFamily family)
  192. {
  193. if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
  194. {
  195. if (family == AddressFamily.InterNetwork)
  196. {
  197. res.Remove(AddressFamily.InterNetworkV6);
  198. }
  199. else
  200. {
  201. res.Remove(AddressFamily.InterNetwork);
  202. }
  203. return res;
  204. }
  205. throw new InvalidCastException("Host does not contain a valid value. {host}");
  206. }
  207. /// <summary>
  208. /// Returns the Addresses that this item resolved to.
  209. /// </summary>
  210. /// <returns>IPAddress Array.</returns>
  211. public IPAddress[] GetAddresses()
  212. {
  213. ResolveHost();
  214. return _addresses;
  215. }
  216. /// <inheritdoc/>
  217. public override bool Contains(IPAddress address)
  218. {
  219. if (address != null && !Address.Equals(IPAddress.None))
  220. {
  221. if (address.IsIPv4MappedToIPv6)
  222. {
  223. address = address.MapToIPv4();
  224. }
  225. foreach (var addr in GetAddresses())
  226. {
  227. if (address.Equals(addr))
  228. {
  229. return true;
  230. }
  231. }
  232. }
  233. return false;
  234. }
  235. /// <inheritdoc/>
  236. public override bool Equals(IPObject? other)
  237. {
  238. if (other is IPHost otherObj)
  239. {
  240. // Do we have the name Hostname?
  241. if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase))
  242. {
  243. return true;
  244. }
  245. if (!ResolveHost() || !otherObj.ResolveHost())
  246. {
  247. return false;
  248. }
  249. // Do any of our IP addresses match?
  250. foreach (IPAddress addr in _addresses)
  251. {
  252. foreach (IPAddress otherAddress in otherObj._addresses)
  253. {
  254. if (addr.Equals(otherAddress))
  255. {
  256. return true;
  257. }
  258. }
  259. }
  260. }
  261. return false;
  262. }
  263. /// <inheritdoc/>
  264. public override bool IsIP6()
  265. {
  266. // Returns true if interfaces are only IP6.
  267. if (ResolveHost())
  268. {
  269. foreach (IPAddress i in _addresses)
  270. {
  271. if (i.AddressFamily != AddressFamily.InterNetworkV6)
  272. {
  273. return false;
  274. }
  275. }
  276. return true;
  277. }
  278. return false;
  279. }
  280. /// <inheritdoc/>
  281. public override string ToString()
  282. {
  283. // StringBuilder not optimum here.
  284. string output = string.Empty;
  285. if (_addresses.Length > 0)
  286. {
  287. bool moreThanOne = _addresses.Length > 1;
  288. if (moreThanOne)
  289. {
  290. output = "[";
  291. }
  292. foreach (var i in _addresses)
  293. {
  294. if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified)
  295. {
  296. output += HostName + ",";
  297. }
  298. else if (i.Equals(IPAddress.Any))
  299. {
  300. output += "Any IP4 Address,";
  301. }
  302. else if (Address.Equals(IPAddress.IPv6Any))
  303. {
  304. output += "Any IP6 Address,";
  305. }
  306. else if (i.Equals(IPAddress.Broadcast))
  307. {
  308. output += "Any Address,";
  309. }
  310. else
  311. {
  312. output += $"{i}/32,";
  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>The result of the comparison function.</returns>
  351. private bool ResolveHost()
  352. {
  353. // When was the last time we resolved?
  354. if (_lastResolved == 0)
  355. {
  356. _lastResolved = DateTime.Now.Ticks;
  357. }
  358. // If we haven't resolved before, or out timer has run out...
  359. if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.Now.Ticks - _lastResolved).TotalMinutes > Timeout))
  360. {
  361. _lastResolved = DateTime.Now.Ticks;
  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>Array of IPAddress objects.</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)
  389. {
  390. // Ignore socket errors, as the result value will just be an empty array.
  391. }
  392. }
  393. }
  394. }
  395. }
  396. }