2014-06-30 20:41:29 +00:00
|
|
|
import os.path
|
2015-08-30 17:50:34 +00:00
|
|
|
|
|
|
|
# DO NOT import non-standard modules. This module is imported by
|
|
|
|
# migrate.py which runs on fresh machines before anything is installed
|
|
|
|
# besides Python.
|
2014-06-30 20:41:29 +00:00
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
# THE ENVIRONMENT FILE AT /etc/mailinabox.conf
|
2014-06-30 20:41:29 +00:00
|
|
|
|
2014-06-03 20:21:17 +00:00
|
|
|
def load_environment():
|
|
|
|
# Load settings from /etc/mailinabox.conf.
|
2014-06-30 20:41:29 +00:00
|
|
|
return load_env_vars_from_file("/etc/mailinabox.conf")
|
2014-06-17 22:21:12 +00:00
|
|
|
|
|
|
|
def load_env_vars_from_file(fn):
|
|
|
|
# Load settings from a KEY=VALUE file.
|
2014-06-30 20:41:29 +00:00
|
|
|
import collections
|
|
|
|
env = collections.OrderedDict()
|
2023-12-23 13:07:25 +00:00
|
|
|
with open(fn, encoding="utf-8") as f:
|
2023-01-15 13:28:43 +00:00
|
|
|
for line in f:
|
|
|
|
env.setdefault(*line.strip().split("=", 1))
|
2014-06-17 22:21:12 +00:00
|
|
|
return env
|
2014-06-03 20:21:17 +00:00
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
def save_environment(env):
|
2023-12-23 13:07:25 +00:00
|
|
|
with open("/etc/mailinabox.conf", "w", encoding="utf-8") as f:
|
2015-08-28 12:29:55 +00:00
|
|
|
for k, v in env.items():
|
2023-12-22 15:41:21 +00:00
|
|
|
f.write(f"{k}={v}\n")
|
2015-07-25 11:47:10 +00:00
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
# THE SETTINGS FILE AT STORAGE_ROOT/settings.yaml.
|
2015-07-25 11:47:10 +00:00
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
def write_settings(config, env):
|
2015-08-30 17:50:34 +00:00
|
|
|
import rtyaml
|
2015-08-28 12:29:55 +00:00
|
|
|
fn = os.path.join(env['STORAGE_ROOT'], 'settings.yaml')
|
2023-12-23 13:07:25 +00:00
|
|
|
with open(fn, "w", encoding="utf-8") as f:
|
2015-08-28 12:29:55 +00:00
|
|
|
f.write(rtyaml.dump(config))
|
|
|
|
|
|
|
|
def load_settings(env):
|
2015-08-30 17:50:34 +00:00
|
|
|
import rtyaml
|
2015-08-28 12:29:55 +00:00
|
|
|
fn = os.path.join(env['STORAGE_ROOT'], 'settings.yaml')
|
2015-07-25 11:47:10 +00:00
|
|
|
try:
|
2023-12-23 13:07:25 +00:00
|
|
|
with open(fn, encoding="utf-8") as f:
|
2023-01-15 13:28:43 +00:00
|
|
|
config = rtyaml.load(f)
|
2023-12-22 15:16:15 +00:00
|
|
|
if not isinstance(config, dict): raise ValueError # caught below
|
2015-07-25 11:47:10 +00:00
|
|
|
return config
|
2015-08-28 12:29:55 +00:00
|
|
|
except:
|
|
|
|
return { }
|
2015-07-25 11:47:10 +00:00
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
# UTILITIES
|
2014-06-30 20:41:29 +00:00
|
|
|
|
2014-06-20 01:16:38 +00:00
|
|
|
def safe_domain_name(name):
|
|
|
|
# Sanitize a domain name so it is safe to use as a file name on disk.
|
|
|
|
import urllib.parse
|
|
|
|
return urllib.parse.quote(name, safe='')
|
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
def sort_domains(domain_names, env):
|
2015-07-21 11:25:11 +00:00
|
|
|
# Put domain names in a nice sorted order.
|
|
|
|
|
|
|
|
# The nice order will group domain names by DNS zone, i.e. the top-most
|
|
|
|
# domain name that we serve that ecompasses a set of subdomains. Map
|
|
|
|
# each of the domain names to the zone that contains them. Walk the domains
|
|
|
|
# from shortest to longest since zones are always shorter than their
|
|
|
|
# subdomains.
|
|
|
|
zones = { }
|
2023-12-22 15:19:47 +00:00
|
|
|
for domain in sorted(domain_names, key=len):
|
2015-07-21 11:25:11 +00:00
|
|
|
for z in zones.values():
|
|
|
|
if domain.endswith("." + z):
|
|
|
|
# We found a parent domain already in the list.
|
|
|
|
zones[domain] = z
|
|
|
|
break
|
2014-06-22 15:34:36 +00:00
|
|
|
else:
|
2015-07-21 11:25:11 +00:00
|
|
|
# 'break' did not occur: there is no parent domain, so it is its
|
|
|
|
# own zone.
|
|
|
|
zones[domain] = domain
|
|
|
|
|
|
|
|
# Sort the zones.
|
|
|
|
zone_domains = sorted(zones.values(),
|
|
|
|
key = lambda d : (
|
|
|
|
# PRIMARY_HOSTNAME or the zone that contains it is always first.
|
|
|
|
not (d == env['PRIMARY_HOSTNAME'] or env['PRIMARY_HOSTNAME'].endswith("." + d)),
|
|
|
|
|
|
|
|
# Then just dumb lexicographically.
|
|
|
|
d,
|
|
|
|
))
|
|
|
|
|
|
|
|
# Now sort the domain names that fall within each zone.
|
2023-12-22 15:13:36 +00:00
|
|
|
return sorted(domain_names,
|
2015-07-21 11:25:11 +00:00
|
|
|
key = lambda d : (
|
|
|
|
# First by zone.
|
|
|
|
zone_domains.index(zones[d]),
|
|
|
|
|
|
|
|
# PRIMARY_HOSTNAME is always first within the zone that contains it.
|
|
|
|
d != env['PRIMARY_HOSTNAME'],
|
|
|
|
|
|
|
|
# Followed by any of its subdomains.
|
|
|
|
not d.endswith("." + env['PRIMARY_HOSTNAME']),
|
|
|
|
|
|
|
|
# Then in right-to-left lexicographic order of the .-separated parts of the name.
|
|
|
|
list(reversed(d.split("."))),
|
|
|
|
))
|
2023-12-22 15:12:50 +00:00
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
def sort_email_addresses(email_addresses, env):
|
|
|
|
email_addresses = set(email_addresses)
|
2023-12-22 15:21:04 +00:00
|
|
|
domains = {email.split("@", 1)[1] for email in email_addresses if "@" in email}
|
2014-08-17 22:43:57 +00:00
|
|
|
ret = []
|
|
|
|
for domain in sort_domains(domains, env):
|
2023-12-22 15:21:04 +00:00
|
|
|
domain_emails = {email for email in email_addresses if email.endswith("@" + domain)}
|
2014-08-17 22:43:57 +00:00
|
|
|
ret.extend(sorted(domain_emails))
|
|
|
|
email_addresses -= domain_emails
|
|
|
|
ret.extend(sorted(email_addresses)) # whatever is left
|
|
|
|
return ret
|
|
|
|
|
2023-12-22 15:25:13 +00:00
|
|
|
def shell(method, cmd_args, env=None, capture_stderr=False, return_bytes=False, trap=False, input=None):
|
2014-06-09 12:09:45 +00:00
|
|
|
# A safe way to execute processes.
|
|
|
|
# Some processes like apt-get require being given a sane PATH.
|
|
|
|
import subprocess
|
2014-06-22 15:34:36 +00:00
|
|
|
|
2023-12-22 15:25:13 +00:00
|
|
|
if env is None:
|
|
|
|
env = {}
|
2014-06-09 12:09:45 +00:00
|
|
|
env.update({ "PATH": "/sbin:/bin:/usr/sbin:/usr/bin" })
|
2014-06-22 15:34:36 +00:00
|
|
|
kwargs = {
|
|
|
|
'env': env,
|
|
|
|
'stderr': None if not capture_stderr else subprocess.STDOUT,
|
|
|
|
}
|
|
|
|
if method == "check_output" and input is not None:
|
|
|
|
kwargs['input'] = input
|
|
|
|
|
2023-01-28 16:08:20 +00:00
|
|
|
if not trap:
|
2014-06-22 15:34:36 +00:00
|
|
|
ret = getattr(subprocess, method)(cmd_args, **kwargs)
|
2023-01-28 16:08:20 +00:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
ret = getattr(subprocess, method)(cmd_args, **kwargs)
|
|
|
|
code = 0
|
|
|
|
except subprocess.CalledProcessError as e:
|
2014-06-22 15:34:36 +00:00
|
|
|
ret = e.output
|
|
|
|
code = e.returncode
|
2014-06-19 01:39:27 +00:00
|
|
|
if not return_bytes and isinstance(ret, bytes): ret = ret.decode("utf8")
|
2014-06-22 15:34:36 +00:00
|
|
|
if not trap:
|
|
|
|
return ret
|
|
|
|
else:
|
|
|
|
return code, ret
|
2014-06-21 23:25:35 +00:00
|
|
|
|
|
|
|
def create_syslog_handler():
|
|
|
|
import logging.handlers
|
|
|
|
handler = logging.handlers.SysLogHandler(address='/dev/log')
|
|
|
|
handler.setLevel(logging.WARNING)
|
|
|
|
return handler
|
2014-10-07 20:24:11 +00:00
|
|
|
|
|
|
|
def du(path):
|
|
|
|
# Computes the size of all files in the path, like the `du` command.
|
|
|
|
# Based on http://stackoverflow.com/a/17936789. Takes into account
|
|
|
|
# soft and hard links.
|
|
|
|
total_size = 0
|
|
|
|
seen = set()
|
2023-12-22 15:21:10 +00:00
|
|
|
for dirpath, _dirnames, filenames in os.walk(path):
|
2014-10-07 20:24:11 +00:00
|
|
|
for f in filenames:
|
|
|
|
fp = os.path.join(dirpath, f)
|
|
|
|
try:
|
|
|
|
stat = os.lstat(fp)
|
|
|
|
except OSError:
|
|
|
|
continue
|
|
|
|
if stat.st_ino in seen:
|
|
|
|
continue
|
|
|
|
seen.add(stat.st_ino)
|
|
|
|
total_size += stat.st_size
|
|
|
|
return total_size
|
2015-04-29 21:06:38 +00:00
|
|
|
|
|
|
|
def wait_for_service(port, public, env, timeout):
|
|
|
|
# Block until a service on a given port (bound privately or publicly)
|
|
|
|
# is taking connections, with a maximum timeout.
|
|
|
|
import socket, time
|
|
|
|
start = time.perf_counter()
|
|
|
|
while True:
|
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
s.settimeout(timeout/3)
|
|
|
|
try:
|
|
|
|
s.connect(("127.0.0.1" if not public else env['PUBLIC_IP'], port))
|
|
|
|
return True
|
|
|
|
except OSError:
|
|
|
|
if time.perf_counter() > start+timeout:
|
|
|
|
return False
|
|
|
|
time.sleep(min(timeout/4, 1))
|
2015-07-21 11:25:11 +00:00
|
|
|
|
2024-03-23 15:16:40 +00:00
|
|
|
def get_ssh_port():
|
|
|
|
port_value = get_ssh_config_value("port")
|
|
|
|
|
|
|
|
if port_value:
|
|
|
|
return int(port_value)
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
def get_ssh_config_value(parameter_name):
|
|
|
|
# Returns ssh configuration value for the provided parameter
|
2024-11-27 13:22:45 +00:00
|
|
|
import subprocess
|
2024-03-23 15:16:40 +00:00
|
|
|
try:
|
|
|
|
output = shell('check_output', ['sshd', '-T'])
|
|
|
|
except FileNotFoundError:
|
|
|
|
# sshd is not installed. That's ok.
|
|
|
|
return None
|
|
|
|
except subprocess.CalledProcessError:
|
|
|
|
# error while calling shell command
|
|
|
|
return None
|
|
|
|
|
|
|
|
for line in output.split("\n"):
|
|
|
|
if " " not in line: continue # there's a blank line at the end
|
|
|
|
key, values = line.split(" ", 1)
|
|
|
|
if key == parameter_name:
|
|
|
|
return values # space-delimited if there are multiple values
|
|
|
|
|
|
|
|
# Did not find the parameter!
|
|
|
|
return None
|
|
|
|
|
2015-07-21 11:25:11 +00:00
|
|
|
if __name__ == "__main__":
|
2015-11-29 14:43:12 +00:00
|
|
|
from web_update import get_web_domains
|
2015-07-21 11:25:11 +00:00
|
|
|
env = load_environment()
|
2015-11-29 14:43:12 +00:00
|
|
|
domains = get_web_domains(env)
|
2015-07-21 11:25:11 +00:00
|
|
|
for domain in domains:
|
|
|
|
print(domain)
|