-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
238 lines (200 loc) · 6.75 KB
/
main.rs
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#![warn(clippy::all, clippy::pedantic)]
use std::net::IpAddr;
use anyhow::{Context, Result};
use clap::Parser;
use cloudflare::endpoints::dns;
use cloudflare::endpoints::dns::{DnsContent, DnsRecord};
use cloudflare::framework::{
async_api::Client, auth::Credentials, response::ApiSuccess, Environment, HttpApiClientConfig,
};
use local_ip_address::local_ip;
use serde::Deserialize;
use tracing::{debug, info};
use tracing_subscriber::{filter::filter_fn, prelude::*};
const V6_URL: &str = "https://v6.ipinfo.io/json";
#[derive(Deserialize)]
pub struct Config {
pub token: String,
pub zoneid: String,
pub hostname: String,
pub ssid: Option<String>,
}
fn config_file() -> Result<Config> {
let xdg_dir =
xdg::BaseDirectories::with_prefix("zoned").context("Failed get config directory")?;
let filename = xdg_dir.place_config_file("config.toml")?;
let builder = config::Config::builder()
.add_source(config::File::from(filename))
.build()
.context("Unable to load config file!")?;
builder
.try_deserialize()
.context("Unable to parse config file!")
}
fn local_ip_address() -> Result<IpAddr> {
let ip = local_ip()?.to_string();
debug!("Found Local IP: {ip}");
ip.parse().context("failed to parse IPv4 address")
}
async fn remote_ip_address(url: &str) -> Result<IpAddr> {
debug!("Fetching IPv6 Address from {url}");
let response = reqwest::get(url).await?;
let parsed: serde_json::Value = response.json().await?;
let ip = parsed["ip"]
.as_str()
.context("Failed to get IPv6 Address from API!")?;
debug!("Found IPv6 Address: {ip}");
ip.parse().context("failed to parse IPv6 address")
}
fn ip_from_record(record: &DnsRecord) -> IpAddr {
match record.content {
DnsContent::A { content } => IpAddr::V4(content),
DnsContent::AAAA { content } => IpAddr::V6(content),
_ => panic!("Unsupported record type: {record:?}"),
}
}
mod wifi {
pub fn ssid() -> Option<String> {
default_interface().and_then(|i| {
std::process::Command::new("networksetup")
.args(["-getairportnetwork", &i])
.output()
.ok()
.and_then(|output| {
if output.status.success() {
String::from_utf8_lossy(&output.stdout)
.split(": ")
.nth(1)
.map(|s| s.trim().to_string())
} else {
None
}
})
})
}
pub fn default_interface() -> Option<String> {
netdev::get_default_interface().ok().map(|i| i.name)
}
}
async fn update_zone(
zoneid: &String,
hostname: &String,
client: &Client,
detected_ip_addr: IpAddr,
) -> Result<()> {
let detected_dns_content = match detected_ip_addr {
IpAddr::V4(ip) => DnsContent::A { content: ip },
IpAddr::V6(ip) => DnsContent::AAAA { content: ip },
};
// Fetch the current DNS record matching the record type and given name.
let current_dns_record = client
.request(&dns::ListDnsRecords {
zone_identifier: zoneid,
params: dns::ListDnsRecordsParams {
name: Some(hostname.to_string()),
record_type: Some(detected_dns_content.clone()),
..Default::default()
},
})
.await
.map(|response: ApiSuccess<Vec<DnsRecord>>| {
response.result.into_iter().find(|record| {
matches!(
record.content,
DnsContent::A { .. } | DnsContent::AAAA { .. }
)
})
})?;
// If the record exists
if let Some(current_dns_record) = current_dns_record {
debug!("Current DNS Record {current_dns_record:#?}");
let current_ip_addr = ip_from_record(¤t_dns_record);
if detected_ip_addr == current_ip_addr {
info!("No change required. {hostname} is already set to {current_ip_addr}");
} else {
info!("Updating {hostname} from {current_ip_addr} to {detected_ip_addr}");
// Update the DNS record
client
.request(&dns::UpdateDnsRecord {
zone_identifier: zoneid,
identifier: ¤t_dns_record.id,
params: dns::UpdateDnsRecordParams {
name: hostname,
content: detected_dns_content,
proxied: Some(current_dns_record.proxied),
ttl: Some(current_dns_record.ttl),
},
})
.await
.context("Unable to update the DNS record!")?;
}
} else {
info!("No record for {hostname} exists. Creating as {detected_ip_addr}");
// Create the DNS record
client
.request(&dns::CreateDnsRecord {
zone_identifier: zoneid,
params: dns::CreateDnsRecordParams {
name: hostname,
content: detected_dns_content,
proxied: Some(false),
ttl: None,
priority: None,
},
})
.await
.context("Unable to create a DNS record!")?;
}
Ok(())
}
#[derive(Debug, Parser)]
struct Cli {
#[command(flatten)]
verbose: clap_verbosity_flag::Verbosity,
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
// Log from this crate only.
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
cli.verbose.log_level_filter().to_string(),
))
.with(
tracing_subscriber::fmt::layer().with_filter(filter_fn(|metadata| {
metadata.target().starts_with(env!("CARGO_PKG_NAME"))
})),
)
.init();
let config: Config = config_file()?;
if config.ssid.is_some() && config.ssid != wifi::ssid() {
info!("SSID does not match. Exiting.");
std::process::exit(1);
}
let credentials = Credentials::UserAuthToken {
token: config.token.clone(),
};
let client = Client::new(
credentials,
HttpApiClientConfig::default(),
Environment::Production,
)
.context("Unable to initialize client")?;
update_zone(
&config.zoneid,
&config.hostname,
&client,
local_ip_address()?,
)
.await
.context("Failed to update IPv4 Record")?;
update_zone(
&config.zoneid,
&config.hostname,
&client,
remote_ip_address(V6_URL).await?,
)
.await
.context("Failed to update IPv6 Record")?;
Ok(())
}