1#!/usr/bin/env python3
2import json
3import os
4from pathlib import Path
5import signal
6import socket
7import sqlite3
8import subprocess
9import sys
10import time
11
12
13os.umask(0o077)
14network = json.loads(Path("/etc/xmpp-network.json").read_text())
15host = os.environ["XMPP_HOST"]
16certificate = Path("/tls/live/server/fullchain.pem")
17key = certificate.with_name("privkey.pem")
18mode = sys.argv[1]
19
20if mode == "certificates":
21 domain = os.environ["XMPP_DOMAIN"]
22 names = list(dict.fromkeys([domain, host, "groups." + domain]))
23 if host.endswith(".test"):
24 certificate.parent.mkdir(parents=True, exist_ok=True)
25 if not certificate.exists():
26 subprocess.run([
27 "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "30",
28 "-subj", "/CN=" + domain, "-addext", "subjectAltName=" + ",".join("DNS:" + name for name in names),
29 "-keyout", str(key), "-out", str(certificate),
30 ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
31 while True:
32 time.sleep(3600)
33 credentials = Path("/tmp/cloudflare.ini")
34 credentials.write_text("dns_cloudflare_api_token = " + os.environ.pop("DNS_TOKEN") + "\n")
35 command = [
36 "certbot", "certonly", "--non-interactive", "--agree-tos", "--email", os.environ["OWNER_EMAIL"],
37 "--dns-cloudflare", "--dns-cloudflare-credentials", str(credentials),
38 "--dns-cloudflare-propagation-seconds", "30", "--cert-name", "server",
39 "--config-dir", "/tls", "--work-dir", "/tmp/certbot-work", "--logs-dir", "/tmp/certbot-logs",
40 "--keep-until-expiring", *[arg for name in names for arg in ("-d", name)],
41 ]
42 while True:
43 subprocess.run(command, check=not certificate.exists())
44 time.sleep(12 * 60 * 60)
45
46while not certificate.exists() or not key.exists():
47 time.sleep(1)
48
49if mode == "prosody":
50 command = ["prosody", "-F", "--config", "/etc/prosody/prosody.cfg.lua"]
51elif mode == "turn":
52 address = "1.1.1.1" if host.endswith(".test") else socket.gethostbyname(host)
53 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as route:
54 route.connect((address, network["turn"]))
55 local_ip = route.getsockname()[0]
56 with sqlite3.connect("/tmp/turn.sqlite") as database:
57 database.executescript(Path("/usr/share/coturn/schema.sql").read_text())
58 # A public/private external-ip mapping whitelists the private address as a relay peer.
59 config = Path("/tmp/turnserver.conf")
60 config.write_text("\n".join([
61 "listening-port=" + str(network["turn"]), "tls-listening-port=" + str(network["turn_tls"]),
62 "min-port=" + str(network["relay_first"]), "max-port=" + str(network["relay_last"]),
63 "listening-ip=0.0.0.0", "relay-ip=" + local_ip,
64 "external-ip=" + (local_ip if host.endswith(".test") else address),
65 "realm=" + host, "server-name=" + host, "fingerprint", "use-auth-secret",
66 "static-auth-secret=" + os.environ.pop("TURN_SECRET"),
67 "cert=" + str(certificate), "pkey=" + str(key),
68 "no-cli", "no-multicast-peers", "no-tcp-relay", "no-rfc5780", "no-software-attribute",
69 "user-quota=12", "total-quota=128", "log-file=stdout", "simple-log",
70 "pidfile=/tmp/turnserver.pid", "userdb=/tmp/turn.sqlite", "relay-threads=2",
71 *["denied-peer-ip=" + cidr for cidr in (
72 "0.0.0.0-0.255.255.255", "10.0.0.0-10.255.255.255", "100.64.0.0-100.127.255.255",
73 "127.0.0.0-127.255.255.255", "169.254.0.0-169.254.255.255",
74 "172.16.0.0-172.31.255.255", "192.168.0.0-192.168.255.255", "224.0.0.0-255.255.255.255",
75 "::", "::1", "fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
76 )],
77 ]) + "\n")
78 command = ["turnserver", "-c", str(config)]
79else:
80 raise ValueError("unknown XMPP task")
81
82process = subprocess.Popen(command)
83
84
85def stop(signum, frame):
86 process.send_signal(signum)
87
88
89signal.signal(signal.SIGTERM, stop)
90signal.signal(signal.SIGINT, stop)
91previous = (certificate.read_bytes(), key.read_bytes())
92while process.poll() is None:
93 time.sleep(2)
94 current = (certificate.read_bytes(), key.read_bytes())
95 if current != previous:
96 previous = current
97 if mode == "prosody":
98 process.send_signal(signal.SIGHUP)
99 else:
100 process.terminate()
101 process.wait(timeout=20)
102 process = subprocess.Popen(command)
103sys.exit(process.returncode)