summaryrefslogtreecommitdiff
path: root/simpleddns.py
blob: 7c05e1cd038410934c56f97a7aee113f369668af (plain)
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
#!/usr/bin/env python3
'''Simple Dynamic DNS updater'''

import os
import sys
import subprocess
import argparse
import ast
import dataclasses
from time import sleep
from abc import ABC, abstractmethod
from typing import NoReturn, Optional, Any
from pathlib import Path
import dns
import dns.resolver
import requests

VERSION = '0.1.0'

def parse_args() -> argparse.Namespace:
	'''Parse command-line arguments'''
	parser = argparse.ArgumentParser(prog='simpleddns',
		description='Simple dynamic DNS updater',
		formatter_class=argparse.RawDescriptionHelpFormatter,
		epilog='''configuration:
        Configure SimpleDDNS by running with --setup or editing the file
        ~/.config/simpleddns/config (or $SIMPLEDDNS_CONFIG_DIR/config).
        There you should find comments documenting the various options.

environment variables:
        SIMPLEDDNS_CONFIG_DIR - directory where configburation files are stored''')
	parser.add_argument('--setup', help='Set up configuration', action='store_true')
	parser.add_argument('--dry-run',
		help='Print what API calls would be made, without actually making any non-GET calls.',
		action='store_true')
	parser.add_argument('--version', action='version', version=f'%(prog)s {VERSION}')
	return parser.parse_args()

def fatal_error(message: str) -> NoReturn:
	'''Output error message & exit'''
	sys.stderr.write(f'Fatal error: {message}\n')
	sys.exit(1)

def warn(message: str) -> None:
	'''Print warning message'''
	sys.stderr.write(f'WARNING: {message}\n')

def setup_config(config_path: Path) -> None:
	'''Interactively set up configuration file'''
	if config_path.exists():
		should_delete = input('Configuration already exists. Delete it [y/n]? ')
		if not should_delete.strip().lower().startswith('y'):
			print('Aborting.')
			return
		config_path.unlink()
	default_get_ip = 'curl --no-progress-meter ifconfig.co'
	domain_name = input('Domain name? ').strip()
	if not domain_name:
		fatal_error('Domain name must be set')
	get_ip = input(f'Command for getting IP address [default: {default_get_ip}]? ').strip()
	if not get_ip:
		get_ip = default_get_ip
	if any(c.isspace() for c in domain_name):
		fatal_error('Domain name must not contain any whitespace')
	print('1. AWS Route 53')
	print('2. DigitalOcean Domains')
	print('3. Linode Domains')
	domain_type = input('Select a domain type from the list above [1-3]: ').strip()
	if domain_type == '1':
		type_name = 'aws_route53'
		options = ''
		print('(Credentials in ~/.aws/credentials will be used)')
	elif domain_type == '2':
		access_token = input('Enter personal access token (will be echoed): ').strip()
		if not access_token:
			fatal_error('Personal access token is required.')
		options = f'''# Personal access token (secret!!)
    access_token = {repr(access_token)}'''
		type_name = 'digitalocean'
	elif domain_type == '3':
		access_token = input('Enter personal access token (will be echoed): ').strip()
		if not access_token:
			fatal_error('Personal access token is required.')
		options = f'''# Personal access token (secret!!)
    access_token = {repr(access_token)}'''
		type_name = 'linode'
	else:
		fatal_error('Invalid choice')
	fd = os.open(config_path, os.O_CREAT | os.O_WRONLY | os.O_EXCL, 0o600)
	with os.fdopen(fd, 'w') as config:
		config.write(f'''# simpleddns configuration
# Values here are python literals (see ast.literal_eval).
# So quotes are always required around strings.
#
# Using environment variables
#     If a value starts with $, it is interpreted as an environment variable, e.g.
#              access_token = $MY_ACCESS_TOKEN
#     In this case, simpleddns will fail if the variable isn't set, and
#     to avoid ambiguity the variable's value must still be a python literal!
#     So set MY_ACCESS_TOKEN='"foo"', rather than MY_ACCESS_TOKEN=foo
Settings
    # Interval in seconds between checking IP address for changes
    #  (API calls are only made when it changes)
    interval = 15
    # Timeout to wait for API responses
    timeout = 20
    # Time To Live (in seconds) with which to create DNS records
    ttl = 300
    # Delay between API calls (seconds), to avoid being rate limited.
    #  0.4 seconds should be more than enough for both Linode and AWS,
    #  but you may want to set this higher if you have other things
    #  making frequent API calls.
    request_delay = 0.4
    # Allow Dynamic DNS to proceed without a CAA record blocking ACME http challenges.
    # Enabling this is almost definitely a bad idea, since it lets people forge
    # certificates for your domain if they get in the way of the IP address lookup process.
    allow_no_caa = False
Domain {type_name} {domain_name}
    # Command(s) for getting IP address(es)
    getip = [{repr(get_ip)}]
    {options}
''')
	print(f'Configuration created successfully at {config_path}')

@dataclasses.dataclass
class Settings:
	'''Global (i.e. not per-domain) settings'''
	dry_run: bool = False
	interval: int = 15
	timeout: int = 20
	ttl: int = 300
	request_delay: float = 0.4

class Domain(ABC):
	'''A domain whose DNS will be updated'''
	full_domain: str
	root_domain: str
	subdomain: str
	allow_no_caa: bool
	getip: list[str]
	settings: Settings
	last_ips: list[str]
	_had_error: bool

	def __init__(self, settings: Settings, domain: str):
		self.allow_no_caa = False
		self.settings = settings
		self.full_domain = domain
		last_dot = domain.rfind('.')
		if last_dot == -1:
			raise ValueError(f'Domain {domain} has no . in it')
		second_last_dot = domain.rfind('.', 0, last_dot)
		if second_last_dot == -1:
			self.subdomain = ''
			self.root_domain = domain
		else:
			self.subdomain = domain[:second_last_dot]
			self.root_domain = domain[second_last_dot+1:]
		self.last_ips = []
		self._init()

	def _info(self, message: str) -> None:
		'''Print informational message prefixed with domain name'''
		print(f'{self.full_domain}: {message}')

	def _error(self, message: str) -> None:
		'''Print warning and set _had_error field to True.'''
		self._had_error = True
		warn(f'{self.full_domain}: {message}')

	def _ttl(self) -> int:
		'''Get TTL value to use for records for this domain'''
		return getattr(self, 'ttl', 0) or self.settings.ttl

	def _timeout(self) -> int:
		'''Get API request timeout'''
		return getattr(self, 'timeout', 0) or self.settings.timeout

	def _request_delay(self) -> float:
		'''Get delay between requests (seconds)'''
		return getattr(self, 'request_delay', 0) or self.settings.request_delay

	@abstractmethod
	def _init(self) -> None:
		'''Extra provider-specific initialization'''

	@abstractmethod
	def update(self, ips: list[str]) -> bool:
		'''Make necessary API request to update domain to use new IP addresses.
		   Returns False on failure.'''

	@abstractmethod
	def validate_specifics(self) -> str:
		'''Validate provider-specific settings for domain'''

	def check_caa(self) -> None:
		'''Ensure that a CAA record exists blocking http ACME challenges,
		   Unless allow_no_caa is set.'''
		if self.allow_no_caa:
			return
		dot = -1
		# In a case like foo.bar.example.com, the following domains are checked
		# in order for CAA records:
		#    1. foo.bar.example.com
		#    2. bar.example.com
		#    3. example.com
		# The first one with a CAA record is taken as authoritative.
		ok = False
		while '.' in (subdomain := self.full_domain[dot + 1:]):
			try:
				subdomain_records = list(dns.resolver.resolve(subdomain, 'CAA'))
			except dns.resolver.NoAnswer:
				dot = self.full_domain.find('.', dot + 1)
				continue
			ok = False
			for record in subdomain_records:
				# (We have to use getattr here because mypy doesn't
				#  like dnspython's CAA-specific type.)
				if b'http-' in getattr(record, 'value'):
					ok = False
					break
				if getattr(record, 'tag') != b'issue':
					continue
				ok = True
			if not ok:
				fatal_error(f'CAA records for {subdomain} allow http ACME:\n' + \
					''.join(record.to_text() + '\n' for record in subdomain_records) + \
					'''You should disable HTTP challenges, otherwise anyone who can hijack your
get-IP-address command can forge TLS certificates for your domain.''')
			break
		if not ok:
			fatal_error(f'''No CAA record found for {self.full_domain}.
You should create a CAA record that doesn't allow HTTP challenges;
otherwise anyone who can hijack your get-IP-address command
can forge TLS certificates for your domain.''')

	def validate(self) -> str:
		'''Validate this object (ensure all required settings are set, etc.)'''
		if not getattr(self, 'getip', ''):
			return 'getip not set'
		if not isinstance(self.getip, list):
			return 'getip should be a list.'
		return self.validate_specifics()

	def get_ips(self) -> list[str]:
		'''Get IP addresses using the registered commands.'''
		ips = []
		for cmd in self.getip:
			result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, check=False)
			if result.returncode:
				warn(f'{repr(cmd)} failed (exit code {result.returncode})')
				return []
			ip = result.stdout.decode(errors='replace').strip()
			# this test isn't perfect, but it should catch most cases of weird stuff
			if not ip or '..' in ip or any(c not in '0123456789abcdefABCDEF:.' for c in ip):
				warn(f'IP address {repr(ip)} is invalid (from command {repr(cmd)}')
				return []
			ips.append(ip)
		ips.sort()
		return ips

	def check_for_update(self) -> bool:
		'''Update DNS records if IP has changed. Returns False on error.'''
		ips = self.get_ips()
		if ips == self.last_ips:
			return True
		self._info('Dealing with new IP address(es)... ')
		sys.stdout.flush()
		if self.update(ips):
			self.last_ips = ips
			return True
		return False

class LinodeDomain(Domain):
	'''Domain registered with Linode Domains'''
	access_token: str
	# Domain ID for Linode API
	_id: Optional[int]

	def _init(self) -> None:
		self._id = None

	def __repr__(self) -> str:
		return f'<LinodeDomain domain={self.full_domain} ' \
			'getip={repr(self.getip)} ' \
			'access_token={repr(self.access_token)}>'

	def _headers(self, has_body: bool = False) -> dict[str, str]:
		'''Get HTTP headers for making requests'''
		headers = {'Accept': 'application/json', 'Authorization': f'Bearer {self.access_token}'}
		if has_body:
			headers['Content-Type'] = 'application/json'
		return headers

	def _make_request(self, method: str, url: str, body: Any = None) -> Any:
		sleep(self._request_delay())
		headers = self._headers(has_body = body is not None)
		options: dict[Any, Any] = {
			'headers': headers,
			'timeout': self._timeout(),
			'method': method,
			'url': url
		}
		if body is not None:
			options['json'] = body
		try:
			response = requests.request(**options)
			if not response.ok:
				self._error(f'''Got error response from endpoint {repr(url)} (code {response.status_code}):
{response.text}''')
			response_json = response.json()
			if response_json is None:
				self._error(f'Got null response from endpoint {repr(url)}')
			return response_json
		except requests.JSONDecodeError as e:
			self._error(f'Invalid JSON at endpoint {repr(url)}: {e}')
			return None
		except requests.RequestException as e:
			self._error(f'Error making request to {repr(url)}: {e}')
			return None
	def _paginated_get(self, url: str) -> list[Any]:
		'''Get results for a Linode paginated GET API endpoint.'''
		results = []
		page_size = 500
		for page in range(1, 100):
			page_url = f'{url}{"&" if "?" in url else "?"}page={page}&page_size={page_size}'
			response_json = self._make_request('GET', page_url)
			if response_json is None:
				break
			try:
				response_data = response_json['data']
				if not isinstance(response_data, list):
					raise ValueError('"data" member is not a list')
			except (KeyError, ValueError) as e:
				self._error(f'Bad JSON format at endpoint {repr(page_url)}: {e}')
				break
			results.extend(response_data)
			if len(response_data) < page_size:
				# Reached last page, presumably
				break
			if page == 99:
				self._error(f'Giving up after 99 pages of responses to API endpoint {repr(url)}')
		return results

	def _update_record(self, record_id: int, target: str) -> None:
		'''Update A/AAAA record to point to new IP address.'''
		if self.settings.dry_run:
			self._info(f'Update DNS record {record_id} (ttl = {self._ttl()}, target = {target})')
		else:
			payload = {
				'name': self.subdomain,
				'target': target,
				'ttl_sec': self._ttl()
			}
			url = f'https://api.linode.com/v4/domains/{self._id}/records/{record_id}'
			resp = self._make_request('PUT', url, payload)
			if isinstance(resp, dict):
				self._info(f'Successfully updated record {record_id} ' \
					f'with TTL = {self._ttl()}, target = {target}')

	def _delete_record(self, record_id: int) -> None:
		'''Delete DNS record'''
		if self.settings.dry_run:
			self._info(f'Delete DNS record {record_id}')
		else:
			url = f'https://api.linode.com/v4/domains/{self._id}/records/{record_id}'
			resp = self._make_request('DELETE', url)
			if isinstance(resp, dict):
				self._info(f'Successfully deleted record {record_id}')

	def _create_record(self, target: str) -> None:
		'''Create A/AAAA record for target IP address'''
		kind = 'AAAA' if ':' in target else 'A'
		if self.settings.dry_run:
			self._info(f'Add {kind} DNS record (ttl = {self._ttl()}, target = {target})')
		else:
			payload = {
				'type': kind,
				'name': self.subdomain,
				'target': target,
				'ttl_sec': self._ttl(),
			}
			url = f'https://api.linode.com/v4/domains/{self._id}/records'
			resp = self._make_request('POST', url, payload)
			if isinstance(resp, dict):
				self._info(f'Successfully created {kind} record with TTL = {self._ttl()}, target = {target}')

	def update(self, ips: list[str]) -> bool:
		self._had_error = False
		if self._id is None:
			domains = self._paginated_get('https://api.linode.com/v4/domains')
			if self._had_error:
				return False
			for domain in domains:
				domain_name = domain['domain']
				if self.root_domain == domain_name:
					# this is it!
					self._id = domain['id']
			if self._id is None:
				self._error(f'Domain {self.root_domain} not found in Linode. Are you sure it is set up there?')
				return False
		records = self._paginated_get(f'https://api.linode.com/v4/domains/{self._id}/records')
		remaining_ips = set(ips)
		unused_records: dict[str, list[int]] = {'A': [], 'AAAA': []}
		for record in records:
			if record['type'] not in ['A', 'AAAA']:
				continue
			if record['name'] != self.subdomain:
				continue
			if record['target'] in remaining_ips and record['ttl_sec'] == self._ttl():
				# This record covers an IP address we want.
				remaining_ips.remove(record['target'])
				continue
			unused_records[record['type']].append(record['id'])
		if not remaining_ips and not any(v for v in unused_records.values()):
			self._info('No updates needed.')
			return True
		could_update = set()
		# Update existing records if possible (to save on API calls)
		for ip in remaining_ips:
			kind = 'AAAA' if ':' in ip else 'A'
			if unused_records[kind]:
				record_id = unused_records[kind].pop()
				self._update_record(record_id, ip)
				could_update.add(ip)
		remaining_ips -= could_update
		for record_id in (x for rs in unused_records.values() for x in rs):
			self._delete_record(record_id)
		for ip in remaining_ips:
			self._create_record(ip)
		return not self._had_error

	def validate_specifics(self) -> str:
		if not getattr(self, 'access_token', ''):
			return 'Access token not set'
		# OK
		return ''

class DigitalOceanDomain(Domain):
	'''Domain registered with DigitalOcean Domains'''
	access_token: str
	_client: Any

	def _init(self) -> None:
		pass

	def update(self, ips: list[str]) -> bool:
		client = self._client
		a_records = client.domains.list_records(
			domain_name=self.root_domain,
			name=self.full_domain,
			type='A',
			per_page=200
		)
		sleep(self._request_delay())
		aaaa_records = client.domains.list_records(
			domain_name=self.root_domain,
			name=self.full_domain,
			type='AAAA',
			per_page=200
		)
		sleep(self._request_delay())
		print(a_records,aaaa_records)
		return True

	def validate_specifics(self) -> str:
		if not getattr(self, 'access_token', ''):
			return 'Access token not set'
		import pydo # pylint: disable=import-error
		self._client = pydo.Client(token=self.access_token)
		# OK
		return ''

def _parse_config_value(value: str) -> Any:
	value = value.strip()
	if value.startswith('$'):
		env_var = os.getenv(value[1:])
		if env_var is None:
			fatal_error(f'Environment variable not set (but used in config): {value}')
		value = env_var
	try:
		return ast.literal_eval(value)
	except ValueError:
		fatal_error(f'Invalid option value: {value} (try adding quotes around it?)')

def parse_config(config_path: Path) -> tuple[Settings, list[Domain]]:
	'''Parse configuration file'''
	curr_section: Settings | Domain | None = None
	settings = Settings()
	domains: list[Domain] = []
	with open(config_path, encoding='utf-8') as config:
		for line in config:
			line = line.strip()
			if not line or line[0] == '#':
				# blank line/comment
				continue
			if line.startswith('Settings'):
				if isinstance(curr_section, Domain):
					domains.append(curr_section)
				curr_section = settings
			elif line.startswith('Domain '):
				if isinstance(curr_section, Domain):
					domains.append(curr_section)
				parts = line.split()
				if len(parts) != 3:
					fatal_error('Domain declaration should have exactly ' \
						'two space-separated arguments (type and name)')
				kind = parts[1]
				domain_name = parts[2].rstrip('.')
				domain_class: Optional[type] = {
					'linode': LinodeDomain,
					'aws_route53': Route53Domain,
					'digitalocean': DigitalOceanDomain,
				}.get(kind)
				if domain_class is None:
					fatal_error(f'No such domain type: {kind}')
				curr_section = domain_class(settings, domain_name)
			else:
				if not curr_section:
					fatal_error('First non-empty line of configuration must be a Domain declaration or Settings')
				parts = [part.strip() for part in line.split('=', maxsplit=1)]
				if len(parts) != 2:
					fatal_error(f'Invalid syntax (want key = value): {line}')
				[key, value] = parts
				setattr(curr_section, key, _parse_config_value(value))
	if isinstance(curr_section, Domain):
		domains.append(curr_section)
	for domain in domains:
		err = domain.validate()
		if err:
			fatal_error(f'In domain {domain.full_domain}: {err}')
	return (settings, domains)

class Route53Domain(Domain):
	'''Domain registered with AWS Route 53'''
	_id: str
	_client: Any

	def _init(self) -> None:
		self._id = ''
		self._client = None

	def _get_client(self) -> Any:
		import boto3
		if not self._client:
			self._client = boto3.client('route53')
		return self._client

	def _get_hosted_zones(self) -> Optional[list[dict[str, Any]]]:
		'''Get list of hosted zones from AWS. Returns None on failure.'''
		import botocore
		try:
			route53 = self._get_client()
			results = route53.list_hosted_zones(MaxItems='100')
			sleep(self._request_delay())
			zones = []
			while results['IsTruncated']:
				zones.extend(results['HostedZones'])
				results = route53.list_hosted_zones(Marker=results['NextMarker'], MaxItems='100')
				sleep(self._request_delay())
			zones.extend(results['HostedZones'])
			return zones
		except botocore.exceptions.BotoCoreError as e:
			warn(f'Error listing AWS hosted zones: {e}')
			return None

	def _list_record_sets(self) -> Optional[list[dict[str, Any]]]:
		'''Get A and AAAA record sets for this domain. Returns None on failure.'''
		import botocore
		route53 = self._get_client()
		record_sets: list[dict[str, Any]] = []
		start_record_name = self.full_domain + '.'
		start_record_type = 'A'
		start_record_identifier = None
		while start_record_name == self.full_domain + '.' and start_record_type in ['A', 'AAAA']:
			options = {
				'HostedZoneId': self._id,
				'StartRecordName': start_record_name,
				'StartRecordType': start_record_type,
				'MaxItems': '300',
			}
			if start_record_identifier is not None:
				options['StartRecordIdentifier'] = start_record_identifier
			try:
				results = route53.list_resource_record_sets(**options)
			except botocore.exceptions.BotoCoreError as e:
				self._error(f'Error listing record sets: {e}')
				return None
			record_sets.extend(filter(
				lambda record: record['Name'] == self.full_domain + '.' and \
					record['Type'] in ['A', 'AAAA'],
				results['ResourceRecordSets']
			))
			if results['IsTruncated']:
				start_record_name = results['NextRecordName']
				start_record_type = results['NextRecordType']
				start_record_identifier = results['NextRecordIdentifier']
			else:
				start_record_name = ''
			sleep(self._request_delay())
		return record_sets

	def _print_record_set_changes(self, changes: list[dict[str, Any]]) -> None:
		for change in changes:
			action = change['Action']
			record_set = change['ResourceRecordSet']
			domain = record_set['Name'].rstrip('.')
			kind = record_set['Type']
			values = [record['Value'] for record in record_set['ResourceRecords']]
			self._info(f'{action} {kind} record for {domain}: {values}')

	def update(self, ips: list[str]) -> bool:
		import botocore
		self._had_error = False
		if not self._id:
			zones = self._get_hosted_zones()
			if zones is None:
				return False
			for zone in zones:
				if zone['Name'].rstrip('.') == self.root_domain:
					self._id = zone['Id']
					break
		if not self._id:
			self._error(f'Domain {self.root_domain} not found in Route 53. Are you sure it is set up there?')
			return False
		record_sets = self._list_record_sets()
		if record_sets is None:
			return False
		changes = []
		ips_remaining = set(ips)
		for record_set in record_sets:
			values = {record['Value'] for record in record_set['ResourceRecords']}
			if record_set['TTL'] == self._ttl() and values.issubset(ips_remaining):
				ips_remaining -= values
			else:
				# remove this record set
				changes.append({'Action': 'DELETE', 'ResourceRecordSet': record_set})
		ipv4s = [ip for ip in ips_remaining if ':' not in ip]
		ipv6s = [ip for ip in ips_remaining if ':' in ip]
		# See https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html
		if len(ipv4s) > 100 or len(ipv6s) > 100:
			fatal_error(f'Too many IP addresses for domain {self.full_domain} ({len(ipv4s) + len(ipv6s)})')
		if ipv4s:
			# Create A record set
			changes.append({
				'Action': 'CREATE',
				'ResourceRecordSet': {
					'Name': self.full_domain + '.',
					'Type': 'A',
					'TTL': self._ttl(),
					'ResourceRecords': [{'Value': ip} for ip in ipv4s],
				}
			})
		if ipv6s:
			# Create AAAA record set
			changes.append({
				'Action': 'CREATE',
				'ResourceRecordSet': {
					'Name': self.full_domain + '.',
					'Type': 'AAAA',
					'TTL': self._ttl(),
					'ResourceRecords': [{'Value': ip} for ip in ipv6s],
				}
			})
		if self.settings.dry_run:
			self._info('Would make the following changes to DNS record sets:')
			self._print_record_set_changes(changes)
		else:
			# Actually perform the changes
			route53 = self._get_client()
			try:
				response = route53.change_resource_record_sets(
					HostedZoneId=self._id,
					ChangeBatch={
						'Comment': 'simpleddns update',
						'Changes': changes
					}
				)
			except botocore.exceptions.BotoCoreError as e:
				self._error(f'Error making changes to DNS record sets: {e}')
				response = None
			if isinstance(response, dict):
				self._info('Made the following changes to DNS record sets:')
				self._print_record_set_changes(changes)
		return not self._had_error

	def validate_specifics(self) -> str:
		# no provided-specific options for Route 53
		return ''

def main() -> None:
	'''Run simpleddns'''
	args = parse_args()
	simpleddns_config_dir = os.getenv('SIMPLEDDNS_CONFIG_DIR')
	xdg_config_dir = os.getenv('XDG_CONFIG_DIR')
	if simpleddns_config_dir:
		config_dir = Path(simpleddns_config_dir)
	elif xdg_config_dir:
		config_dir = Path(xdg_config_dir, 'simpleddns')
	else:
		config_dir = Path('~/.config/simpleddns').expanduser()
	os.makedirs(config_dir, exist_ok = True)
	config_path = Path(config_dir, 'config')
	if args.setup:
		setup_config(config_path)
		sys.exit(0)
	if not config_path.exists():
		fatal_error("Configuration doesn't exist. Try running with --setup first.")
	if os.name == 'posix':
		config_mode = config_path.stat().st_mode
		if config_mode & 0o4:
			fatal_error(f'''DANGER: configuration file {config_path} allows
	reading by other users (mode {config_mode & 0o777:o}).
	If there are API tokens in there, revoke them immediately!!''')

	settings, domains = parse_config(config_path)
	settings.dry_run = args.dry_run
	if not domains:
		fatal_error('No domains defined. Try running with --setup?')
	for domain in domains:
		domain.check_caa()

	print('simpleddns started.')
	while True:
		for domain in domains:
			domain.check_for_update()
		sleep(settings.interval)

if __name__ == '__main__':
	main()