aboutsummaryrefslogtreecommitdiff
path: root/src/dns_updater.rs
blob: de9a8740e811337e75fda1a36ea5fe873c39ec61 (plain) (blame)
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use std::collections::HashSet;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{anyhow, bail, Result};
use tokio::select;
use tokio::sync::watch;
use tracing::*;

use crate::dns_config::*;
use crate::DomainProvider;

const RETRY_DELAY: Duration = Duration::from_secs(600); // 10 minutes

pub async fn dns_updater_task(
    mut rx_dns_config: watch::Receiver<Arc<DnsConfig>>,
    providers: Vec<DomainProvider>,
    allowed_domains: Vec<String>,
    mut must_exit: watch::Receiver<bool>,
) {
    for dom in allowed_domains.iter() {
        info!(domain = dom, "allowing subdomains of domain");
    }
    for prov in providers.iter() {
        info!(
            domain = prov.domain,
            provider = prov.provider.provider(),
            "got provider for domain"
        );
    }

    info!("DNS updater starting");

    let mut config = Arc::new(DnsConfig::new());
    let mut failures = HashSet::new();

    while !*must_exit.borrow() {
        select!(
            c = rx_dns_config.changed() => {
                if c.is_err() {
                    break;
                }
            }
            _ = tokio::time::sleep(RETRY_DELAY) => {
                if failures.is_empty() {
                    continue;
                }
            }
            _ = must_exit.changed() => continue,
        );

        // Always lag 15 seconds behind actual updates,
        // to avoid sending too many at once and hitting rate limits
        tokio::time::sleep(Duration::from_secs(15)).await;

        let new_config: Arc<DnsConfig> = rx_dns_config.borrow_and_update().clone();
        let mut new_failures = HashSet::new();

        for (key, value) in new_config.entries.iter() {
            if failures.contains(key) {
                info!(
                    record = key.to_string(),
                    target = value.to_string(),
                    "retrying after failure"
                );
            } else if config.entries.get(key) == Some(value) {
                // Skip entries that haven't changed, and that were
                // successfully updated on the previous iteration
                continue;
            }

            // Skip entries for unallowed domains
            if !allowed_domains
                .iter()
                .any(|d| key.dns_path == *d || key.dns_path.ends_with(&format!(".{}", d)))
            {
                error!(
                    domain = key.dns_path,
                    "domain/subdomain/hostname not in allowed list",
                );
                continue;
            }

            let provider = providers.iter().find(|p| {
                key.dns_path == p.domain || key.dns_path.ends_with(&format!(".{}", p.domain))
            });

            if let Some(provider) = provider {
                if let Err(e) = update_dns_entry(key, value, provider).await {
                    error!(
                        record = key.to_string(),
                        target = value.to_string(),
                        error = e.to_string(),
                        "unable to update record, will retry later"
                    );
                    new_failures.insert(key.clone());
                }
            } else {
                error!(
                    domain = key.dns_path,
                    "no provider matches this domain/subdomain/hostname"
                );
            }
        }

        config = new_config;
        failures = new_failures;
    }
}

async fn update_dns_entry(
    key: &DnsEntryKey,
    value: &DnsEntryValue,
    provider: &DomainProvider,
) -> Result<()> {
    let subdomain = if key.dns_path == provider.domain {
        None
    } else {
        Some(
            key.dns_path
                .strip_suffix(&format!(".{}", provider.domain))
                .unwrap(),
        )
    };
    info!(
        record = key.to_string(),
        target = value.to_string(),
        domain = provider.domain,
        subdomain = &subdomain,
        provider = provider.provider.provider(),
        "updating record"
    );

    if value.targets.is_empty() {
        bail!("zero targets (internal error)");
    }

    match key.record_type {
        DnsRecordType::A => {
            let mut targets = vec![];
            for tgt in value.targets.iter() {
                targets.push(
                    tgt.parse::<Ipv4Addr>()
                        .map_err(|_| anyhow!("Invalid ipv4 address: {}", tgt))?,
                );
            }
            provider
                .provider
                .update_a(&provider.domain, subdomain, &targets)
                .await?;
        }
        DnsRecordType::AAAA => {
            let mut targets = vec![];
            for tgt in value.targets.iter() {
                targets.push(
                    tgt.parse::<Ipv6Addr>()
                        .map_err(|_| anyhow!("Invalid ipv6 address: {}", tgt))?,
                );
            }
            provider
                .provider
                .update_aaaa(&provider.domain, subdomain, &targets)
                .await?;
        }
        DnsRecordType::CNAME => {
            let mut targets = value.targets.iter().cloned().collect::<Vec<_>>();
            if targets.len() > 1 {
                targets.sort();
                warn!(
					record = key.to_string(),
					all_targets = value.to_string(),
					selected_target = targets[0],
					"Several CNAME targets, taking first one in alphabetical order. Consider switching to a single global target instead."
				);
            }
            provider
                .provider
                .update_cname(&provider.domain, subdomain, &targets[0])
                .await?;
        }
    }
    Ok(())
}