FreedomBox/actions/dynamicdns
Sunil Mohan Adapa 7e0156adbe
dynamicdns: Rewrite configuration handling and update using URL
- Drop all the bash code.

- Run the update URL code with same logic as before. Don't need to use action
code for it.

- Completely new way to handle configuration: using key/value store. Import old
configuration once and delete it.

- Use a glib scheduler instead of creating a cron job.

- Store and show status from key/value store.

- Handle multiple domains when getting/setting configuration and status. The UI
still shows a single configuration form. To be improved later.

- Catch and report all errors during the update process.

- Drop all NAT detection code.

- Drop selfhost.bz. German only, no free account, no proper TLS on domain, no
easy to test. Existing accounts will continue to work with "other" as the
service type.

- For gnudip update code, add a timeout of 10 seconds, set a buffer size of two
powers and fix handling error messages from server.

Tests:

- GnuDIP:

  - Upon submission of the form, the IP is updated if app is enabled. IP is not
  updated if app is disabled.

  - Every 5 minutes, check is made again and IP is updated.

  - If IP lookup URL is available, update calls are not made if the DNS is
  already up-to-date.

  - If IP lookup URL is not available, update calls are made unconditionally
  every 5 minutes.

- For each of noip.com, freedns.afraid.org and other service:

  - Upon submission of the form, the IP is updated if app is enabled. IP is not
  updated if app is disabled.

  - Every 5 minutes, check is made again and IP is updated.

  - If IP lookup URL is available, update calls are not made if the DNS is
  already up-to-date.

  - If IP lookup URL is not available, update calls are made unconditionally
  every 5 minutes.

- Form validation:

  - Domain field is always mandatory.

  - When type is selected as gnudip, the fields server, username, and password
  are mandatory.

  - When type is selected other than gnudip, the field update URL is mandatory.
  The rest are optional.

  - When the update URL contains a field contains <User>, username is mandatory.
  For <Pass>, password is mandatory. For <Ip>, ip_lookup_url is mandatory.

  - When use HTTP basic auth is checked, the fields username and password are
  mandatory.

  - Password is optional only if a previous password exists. If configuration is
  deleted from kvstore, password is mandatory.

- Configuration import:

  Install dynamicdns without the patch. Add configuration with each of the
  service types. For GnuDIP service type, set two configurations with one with
  and without IP lookup URL. Update to code with the patch. Setup should run.

  - All fields in the configuration should be imported properly.

  - If the previous configuration is disabled, app should be disabled after
  import. Enabled otherwise.

  - Updating the IP address should work immediately after import.

- Enable/Disable: when enabled, IP URL should be enabled every 5 minutes.
When disabled, updates should not happen.

- Status:

  - When status is removed from the DB, it should show that no status is
  available yet.

  - When the form is updated or update happens via the timer, the status is
  shown. It should show success for a proper update. Proper external IP address
  should be shown.

  - Set the server to localhost and submit. Status should show 'Server refused
  connection' message. IP address should be '-'.

  - Set the server to an unknown domain. Status should show 'Could not find
  server' message. IP address should be '-'.

  - Set the server to a known domain. Status should show 'Connection timed out'
  message. IP address should be '-'.

  - Last update time should keep increasing as time passes.

- Backup/restore:

  - Functional tests.

- Javascript:

  - When GnuDIP is selected as the type, the fields server, username, password,
  domain, show password, and IP lookup URL should be shown while other fields
  should be hidden. Same on page load with GnuDIP as pre-selected type.

  - When GnuDIP is not selected as the type, the fields update URL, accept all
  SSL certificates, use basic HTTP auth, domain name, username, password, show
  password, IP lookup URL and use IPv6 fields should be shown and rest of the
  fields should be hidden. Same on page load with non-GnuDIP as pre-selected
  type.

  - When show password is checked, password should be shown and when it is
  unchecked, password is masked.

  - When other service types are selected, the update URL values changes to the
  respective service's URL.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
2022-02-10 20:31:39 -05:00

157 lines
4.9 KiB
Python
Executable File

#!/usr/bin/python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Configuration helper for Dynamic DNS.
"""
import argparse
import json
import pathlib
import urllib
_conf_dir = pathlib.Path('/etc/ez-ipupdate/')
_active_config = _conf_dir / 'ez-ipupdate.conf'
_inactive_config = _conf_dir / 'ez-ipupdate.inactive'
_helper_config = _conf_dir / 'ez-ipupdate-plinth.cfg'
_cron_job = pathlib.Path('/etc/cron.d/ez-ipupdate')
def parse_arguments():
""" Return parsed command line arguments as dictionary. """
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')
subparsers.add_parser('export-config',
help='Print configuration in JSON format')
subparsers.add_parser('clean', help='Remove all old configuration files')
subparsers.add_parser('update', help='For backwards compatibility')
subparser = subparsers.add_parser('success',
help='For backwards compatibility')
subparser.add_argument('wan_ip_address')
subparsers.required = True
return parser.parse_args()
def _read_configuration(path, separator='='):
"""Read ez-ipupdate configuration."""
config = {}
for line in path.read_text().splitlines():
if line.startswith('#'):
continue
parts = line.partition(separator)
if parts[1]:
config[parts[0].strip()] = parts[2].strip()
else:
config[parts[0].strip()] = True
return config
def subcommand_export_config(_):
"""Print the old ez-ipupdate configuration in JSON format."""
input_config = {}
if _active_config.exists():
input_config = _read_configuration(_active_config)
elif _inactive_config.exists():
input_config = _read_configuration(_inactive_config)
helper = {}
if _helper_config.exists():
helper.update(_read_configuration(_helper_config, separator=' '))
def _clean(value):
value_map = {'enabled': True, 'disabled': False, '': None}
return value_map.get(value, value)
domain = {
'service_type': 'gnudip',
'domain': input_config.get('host'),
'server': input_config.get('server'),
'username': input_config.get('user', '').split(':')[0] or None,
'password': input_config.get('user', '').split(':')[-1] or None,
'ip_lookup_url': helper.get('IPURL'),
'update_url': _clean(helper.get('POSTURL')) or None,
'use_http_basic_auth': _clean(helper.get('POSTAUTH')),
'disable_ssl_cert_check': _clean(helper.get('POSTSSLIGNORE')),
'use_ipv6': _clean(helper.get('POSTUSEIPV6')),
}
if isinstance(domain['update_url'], bool):
# 'POSTURL ' is a line found in the configuration file
domain['update_url'] = None
if not domain['server']:
domain['service_type'] = 'other'
update_url = domain['update_url']
try:
server = urllib.parse.urlparse(update_url).netloc
service_types = {
'dynupdate.noip.com': 'noip.com',
'dynupdate.no-ip.com': 'noip.com',
'freedns.afraid.org': 'freedns.afraid.org'
}
domain['service_type'] = service_types.get(server, 'other')
except ValueError:
pass
# Old logic for 'enabling' the app is as follows: If behind NAT, add
# cronjob. If not behind NAT and type is update URL, add cronjob. If not
# behind NAT and type is GnuDIP, move inactive configuration to active
# configuration and start the ez-ipupdate daemon.
enabled = False
if _cron_job.exists() or (domain['service_type'] == 'gnudip'
and _active_config.exists()):
enabled = True
output_config = {'enabled': enabled, 'domains': {domain['domain']: domain}}
print(json.dumps(output_config))
def subcommand_clean(_):
"""Remove all old configuration files."""
last_update = _conf_dir / 'last-update'
status = _conf_dir / 'ez-ipupdate.status'
current_ip = _conf_dir / 'ez-ipupdate.currentIP'
cleanup_files = [
_active_config, _inactive_config, last_update, _helper_config, status,
current_ip
]
for cleanup_file in cleanup_files:
try:
cleanup_file.rename(cleanup_file.with_suffix('.bak'))
except FileNotFoundError:
pass
_cron_job.unlink(missing_ok=True)
def subcommand_update(_):
"""Empty subcommand kept only for backwards compatibility.
Drop after stable release.
"""
def subcommand_success(_):
"""Empty subcommand kept only for backwards compatibility.
Drop after stable release.
"""
def main():
"""Parse arguments and perform all duties."""
arguments = parse_arguments()
subcommand = arguments.subcommand.replace('-', '_')
subcommand_method = globals()['subcommand_' + subcommand]
subcommand_method(arguments)
if __name__ == '__main__':
main()