-
Notifications
You must be signed in to change notification settings - Fork 0
/
DDNSService.cs
106 lines (96 loc) · 3.29 KB
/
DDNSService.cs
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
namespace CherryDDNS;
public sealed class DDNSService : BackgroundService
{
private static readonly string BASE_ADDRESS = "https://api.godaddy.com";
private static readonly MediaTypeWithQualityHeaderValue CONTENT_TYPE = new MediaTypeWithQualityHeaderValue("application/json");
private static readonly HttpClient client = new HttpClient() { };
private string _ip;
private static DDNSService _instance;
public static DDNSService Instance
{
get
{
if (_instance == null)
{
_instance = new DDNSService();
}
return _instance;
}
}
public DDNSService()
{
VerifyConfig();
_ip = "localhost";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("sso-key", Config.Instance.AuthHeader);
//client.DefaultRequestHeaders.Add("Authorization", );
client.DefaultRequestHeaders.Accept.Add(CONTENT_TYPE);
}
public async void Update()
{
try
{
_ip = client.GetStringAsync("https://api.ipify.org").Result;
foreach (Record record in Config.Instance.Records)
{
string ip = await GetRecord(record);
if (ip != _ip)
{
StringContent content = new StringContent($"[{new DNSRecord(_ip)}]");
content.Headers.ContentType = CONTENT_TYPE;
Uri apiAddress = new Uri($"{BASE_ADDRESS}/v1/domains/{record.DomainName}/records/A/{record.HostName}");
HttpResponseMessage response = client.PutAsync(apiAddress, content).Result;
if (response != null)
{
string data = response.Content.ReadAsStringAsync().Result;
LogManager.ARecordUpdated(record);
}
}
}
}
catch (Exception ex)
{
LogManager.Error(ex);
}
}
private void VerifyConfig()
{
if (string.IsNullOrEmpty(Config.Instance.Key) ||
string.IsNullOrEmpty(Config.Instance.Secret) ||
Config.Instance.Records.Count == 0 ||
string.IsNullOrEmpty(Config.Instance.Records[0].DomainName) ||
string.IsNullOrEmpty(Config.Instance.Records[0].HostName))
{
LogManager.InvalidConfig();
Environment.Exit(1);
}
}
private async Task<string> GetRecord(Record record)
{
try
{
IPAddress[] ips = Dns.GetHostAddresses($"{record.HostName}.{record.DomainName}");
if (ips.Length > 0)
{
return ips[0].ToString();
}
throw new Exception("No IP Address was returned by GetHostAddresses");
}
catch (Exception ex)
{
if (ex.Source == "System.Net.NameResolution" || ex.Message == "No such host is known")
{
return "NO RECORD";
}
LogManager.Error(ex);
return "ERROR";
}
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
Instance.Update();
return Task.CompletedTask;
}
}