-
Notifications
You must be signed in to change notification settings - Fork 826
Expand file tree
/
Copy pathCloudFlareAPI.Zones.cs
More file actions
69 lines (61 loc) · 2.93 KB
/
CloudFlareAPI.Zones.cs
File metadata and controls
69 lines (61 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
namespace Opserver.Data.Cloudflare
{
public partial class CloudflareAPI
{
private Cache<List<CloudflareZone>> _zones;
public Cache<List<CloudflareZone>> Zones =>
_zones ??= GetCloudflareCache(5.Minutes(), () => Get<List<CloudflareZone>>("zones"));
private static readonly NameValueCollection _dnsRecordFetchParams = new()
{
["per_page"] = "100"
};
private Cache<List<CloudflareDNSRecord>> _dnsRecords;
public Cache<List<CloudflareDNSRecord>> DNSRecords =>
_dnsRecords ??= GetCloudflareCache(5.Minutes(), async () =>
{
var records = new List<CloudflareDNSRecord>();
var data = await Zones.GetData(); // wait on zones to load first...
if (data == null) return records;
foreach (var z in data)
{
var zoneRecords =
await Get<List<CloudflareDNSRecord>>($"zones/{z.Id}/dns_records", _dnsRecordFetchParams);
records.AddRange(zoneRecords);
}
return records;
});
public CloudflareZone GetZoneFromHost(string host) =>
Zones.Data?.FirstOrDefault(z => host.EndsWith(z.Name));
public CloudflareZone GetZoneFromUrl(string url) =>
!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out var uri) ? null : GetZoneFromHost(uri.Host);
/// <summary>
/// Get the IP Addresses for a given DNS record reponse.
/// </summary>
/// <param name="record">The DNS record to get an IP for</param>
/// <returns>Root IP Addresses for this record.</returns>
public List<IPAddress> GetIPs(CloudflareDNSRecord record) => record.Type switch
{
DNSRecordType.A or DNSRecordType.AAAA => new List<IPAddress> { record.IPAddress },
DNSRecordType.CNAME => GetIPs(record.Content),
_ => null,
};
/// <summary>
/// Get the IP Addresses for a given fully qualified host (star records not supported), even through CNAME chains.
/// </summary>
/// <param name="host">The host to get an IP for.</param>
/// <returns>Root IP Addresses for this host.</returns>
public List<IPAddress> GetIPs(string host)
{
if (DNSRecords.Data == null)
return null;
var records = DNSRecords.Data.Where(r => string.Equals(host, r.Name, StringComparison.InvariantCultureIgnoreCase) && (r.Type == DNSRecordType.A || r.Type == DNSRecordType.AAAA || r.Type == DNSRecordType.CNAME)).ToList();
var cNameRecord = records.Find(r => r.Type == DNSRecordType.CNAME);
return cNameRecord != null ? GetIPs(cNameRecord.Content) : records.Select(r => r.IPAddress).ToList();
}
}
}