| 1 | #!/usr/bin/env python3 |
| 2 | import json |
| 3 | import os |
| 4 | from pathlib import Path |
| 5 | import subprocess |
| 6 | import sys |
| 7 | import time |
| 8 | |
| 9 | |
| 10 | os.umask(0o077) |
| 11 | mode = sys.argv[1] |
| 12 | tls = Path(os.environ.get("CREDENTIALS_DIRECTORY", "/tls/live/server")) |
| 13 | |
| 14 | if mode == "certificates": |
| 15 | credentials = Path("/tmp/cloudflare.ini") |
| 16 | credentials.write_text("dns_cloudflare_api_token = " + os.environ.pop("DNS_TOKEN") + "\n") |
| 17 | command = [ |
| 18 | "certbot", "certonly", "--non-interactive", "--agree-tos", |
| 19 | "--email", os.environ["OWNER_EMAIL"], "--dns-cloudflare", |
| 20 | "--dns-cloudflare-credentials", str(credentials), |
| 21 | "--dns-cloudflare-propagation-seconds", "30", "--cert-name", "server", |
| 22 | "--config-dir", "/tls", "--work-dir", "/tmp/certbot-work", "--logs-dir", "/tmp/certbot-logs", |
| 23 | "--keep-until-expiring", "-d", os.environ["RELAY_HOST"], |
| 24 | ] |
| 25 | while True: |
| 26 | subprocess.run(command, check=not (tls / "fullchain.pem").exists(), timeout=300) |
| 27 | time.sleep(12 * 60 * 60) |
| 28 | |
| 29 | config = Path("/tmp/iroh-relay.toml") |
| 30 | if mode == "relay": |
| 31 | for _ in range(180): |
| 32 | if (tls / "fullchain.pem").exists() and (tls / "privkey.pem").exists(): |
| 33 | break |
| 34 | time.sleep(1) |
| 35 | else: |
| 36 | raise RuntimeError("Relay certificate was not issued within three minutes") |
| 37 | quic_port = int(os.environ["QUIC_PORT"]) if "QUIC_PORT" in os.environ else json.loads( |
| 38 | Path(__file__).with_name("network.json").read_text())["quic"] |
| 39 | metrics = os.environ.get("METRICS_ADDR") |
| 40 | config.write_text( |
| 41 | f'enable_metrics = {json.dumps(bool(metrics))}\nenable_quic_addr_discovery = true\n' |
| 42 | + (f'metrics_bind_addr = {json.dumps(metrics)}\n' if metrics else '') + |
| 43 | f'http_bind_addr = "127.0.0.1:{int(os.environ["HTTP_PORT"])}"\n' |
| 44 | '[tls]\ncert_mode = "Reloading"\n' |
| 45 | f'quic_bind_addr = "0.0.0.0:{quic_port}"\n' |
| 46 | f'manual_cert_path = {json.dumps(str(tls / "fullchain.pem"))}\n' |
| 47 | f'manual_key_path = {json.dumps(str(tls / "privkey.pem"))}\n' |
| 48 | ) |
| 49 | else: |
| 50 | raise ValueError("Unknown relay task") |
| 51 | # --dev leaves HTTPS to Caddy while retaining certificate-backed QUIC discovery. |
| 52 | os.execv("/usr/local/bin/iroh-relay", ["iroh-relay", "--dev", "--config-path", str(config)]) |