serve.py (11.5 KB)
1 #!/usr/bin/env python3 2 """ 3 Serve soundstone over HTTPS so that devices on your local network can install 4 it as a PWA without a public web host. 5 6 This script uses mkcert to make a certificate for this computer's address on 7 the local network. A device does not trust that certificate until it trusts 8 mkcert's root certificate authority (CA), so this script prints two QR codes: 9 10 1. an HTTP link that gives the device the mkcert root CA certificate. 11 This is the public certificate, not the private key. 12 2. an HTTPS link to soundstone itself. 13 14 Both servers stop together on Ctrl+C. 15 16 Without mkcert or a network connection, it serves plain HTTP on this computer 17 only. That is enough to use soundstone here, but not to install it elsewhere. 18 19 After scanning the first QR code, install and trust the CA on the device: 20 iOS: Settings → General → VPN & Device Management → install the profile, 21 then Settings → General → About → Certificate Trust Settings → 22 enable full trust 23 Android: open the downloaded file and follow the prompt to install it as a 24 CA certificate 25 """ 26 27 import http.server 28 import socket 29 import socketserver 30 import ssl 31 import subprocess 32 import sys 33 import threading 34 from pathlib import Path 35 from shutil import which 36 37 HTTP_PORT = 8000 # preferred; falls back to the next free port 38 CERT_HTTP_PORT = 8001 # preferred; falls back to the next free port 39 HTTPS_PORT = 8443 # preferred; falls back to the next free port 40 SCRIPT_DIR = Path(__file__).parent.absolute() 41 DATA_DIR = Path.home() / ".soundstone" 42 VENV_DIR = DATA_DIR / "venv" 43 CERT_FILE = DATA_DIR / "https_certs" / "cert.pem" 44 KEY_FILE = DATA_DIR / "https_certs" / "key.pem" 45 46 # The HTTPS server mounts the app here, so that it does not share an install 47 # with another app served from the same address and port. 48 BASE_PATH = "/soundstone/" 49 50 # Path the device fetches the root CA from. Anything else over HTTP is a 404. 51 CA_DOWNLOAD_PATH = "/rootCA.pem" 52 53 54 def run_in_venv(): 55 """Re-run this script in a private venv that has the qrcode package. 56 If the venv or the package cannot be set up, the script still runs and 57 prints URLs without QR codes.""" 58 python_path = VENV_DIR / ("Scripts" if sys.platform == "win32" else "bin") / "python" 59 if not python_path.exists(): 60 print("Creating a Python environment for QR codes...") 61 subprocess.call([sys.executable, "-m", "venv", str(VENV_DIR)]) 62 if python_path.exists(): 63 has_qrcode = subprocess.run([str(python_path), "-c", "import qrcode"], capture_output=True) 64 if has_qrcode.returncode != 0: 65 subprocess.call([str(python_path), "-m", "pip", "install", "-q", "qrcode"]) 66 else: 67 python_path = Path(sys.executable) 68 try: 69 subprocess.check_call([str(python_path), __file__, "--in-venv"]) 70 except (KeyboardInterrupt, subprocess.CalledProcessError): 71 pass 72 sys.exit(0) 73 74 75 def get_local_ip(): 76 """Return the address other devices on the network can reach this 77 computer at, or None if there is no network.""" 78 try: 79 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 80 # Asks which local address would route to a reserved documentation 81 # address (RFC 5737). 82 s.connect(("192.0.2.1", 80)) 83 local_ip = s.getsockname()[0] 84 s.close() 85 return local_ip 86 except OSError: 87 return None 88 89 90 def find_available_port(start_port, max_attempts=20): 91 """Return the first port at or after start_port that can be bound. 92 SO_REUSEADDR stops a socket left in TIME_WAIT by an earlier run from 93 blocking the port.""" 94 for port in range(start_port, start_port + max_attempts): 95 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 96 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 97 try: 98 s.bind(("", port)) 99 return port 100 except OSError: 101 continue 102 finally: 103 s.close() 104 sys.exit(f"Error: no free port near {start_port}.") 105 106 107 def print_qr_code(url, caption): 108 """Print a QR code made of block characters, two rows of the code per line.""" 109 try: 110 import qrcode 111 except ImportError: 112 print(f"\n{caption}\n (QR code unavailable; open this URL by hand)") 113 return 114 qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=1, border=1) 115 qr.add_data(url) 116 qr.make(fit=True) 117 matrix = qr.get_matrix() 118 119 print(f"\n{caption}\n") 120 for y in range(0, len(matrix), 2): 121 line = " " 122 for x in range(len(matrix[y])): 123 top = matrix[y][x] 124 bottom = matrix[y + 1][x] if y + 1 < len(matrix) else False 125 line += "█" if top and bottom else "▀" if top else "▄" if bottom else " " 126 print(line) 127 128 129 def ca_root_file(): 130 """Path to mkcert's root CA certificate.""" 131 caroot = subprocess.run(["mkcert", "-CAROOT"], capture_output=True, text=True).stdout.strip() 132 return Path(caroot) / "rootCA.pem" 133 134 135 def ensure_ca_installed(): 136 """Make sure mkcert's local CA exists and this computer trusts it. 137 mkcert may ask for your password to write to the system trust store.""" 138 if not ca_root_file().exists(): 139 print("Setting up the mkcert local CA (you may be asked for your password)...") 140 subprocess.check_call(["mkcert", "-install"]) 141 142 143 def ensure_leaf_cert(local_ip): 144 """Make a certificate and key for this computer's network address and for 145 localhost, unless there is already one for the same address.""" 146 CERT_FILE.parent.mkdir(parents=True, exist_ok=True) 147 if CERT_FILE.exists() and KEY_FILE.exists(): 148 try: 149 names = ssl._ssl._test_decode_cert(str(CERT_FILE)).get("subjectAltName", ()) 150 except (AttributeError, OSError): 151 names = () 152 if ("IP Address", local_ip) in names: 153 return 154 print(f"Making a certificate for {local_ip}...") 155 subprocess.check_call([ 156 "mkcert", 157 "-cert-file", str(CERT_FILE), 158 "-key-file", str(KEY_FILE), 159 local_ip, "localhost", "127.0.0.1", 160 ]) 161 162 163 def start_ca_server(local_ip): 164 """Start a plain HTTP server that hands out the mkcert root CA certificate, 165 and return it running. The certificate is public, so it is served to any 166 device for as long as the script runs. The caller shuts the server down.""" 167 ca_bytes = ca_root_file().read_bytes() 168 169 class CAHandler(http.server.BaseHTTPRequestHandler): 170 def log_message(self, *args): 171 pass 172 173 def do_GET(self): 174 if self.path in ("/", "/index.html"): 175 self.send_response(302) 176 self.send_header("Location", CA_DOWNLOAD_PATH) 177 self.end_headers() 178 return 179 if self.path != CA_DOWNLOAD_PATH: 180 self.send_error(404) 181 return 182 # This content type makes iOS offer to install the file as a CA profile. 183 self.send_response(200) 184 self.send_header("Content-Type", "application/x-x509-ca-cert") 185 self.send_header("Content-Length", str(len(ca_bytes))) 186 self.send_header("Content-Disposition", 'attachment; filename="rootCA.pem"') 187 self.end_headers() 188 try: 189 self.wfile.write(ca_bytes) 190 except (BrokenPipeError, ConnectionResetError): 191 return 192 193 port = find_available_port(CERT_HTTP_PORT) 194 http.server.HTTPServer.allow_reuse_address = True 195 httpd = http.server.HTTPServer(("", port), CAHandler) 196 threading.Thread(target=httpd.serve_forever, daemon=True).start() 197 198 cert_url = f"http://{local_ip}:{port}{CA_DOWNLOAD_PATH}" 199 print("=" * 69) 200 print("STEP 1: install + trust the local CA on each device (first time only)") 201 print("=" * 69) 202 print_qr_code(cert_url, "Scan to download the root certificate:") 203 print(f" {cert_url}") 204 print("\nOn iOS, after downloading:") 205 print(" • Settings → General → VPN & Device Management → install the profile") 206 print(" • Settings → General → About → Certificate Trust Settings →") 207 print(" toggle ON full trust for the mkcert CA") 208 print("\nOn Android, after downloading:") 209 print(" • open the downloaded file, or Settings → Security → Encryption &") 210 print(" credentials → Install a certificate → CA certificate, then confirm") 211 print("\n(skip this step on a device that already trusts the CA from an earlier run)") 212 return httpd 213 214 215 class ThreadingServer(socketserver.ThreadingTCPServer): 216 daemon_threads = True 217 allow_reuse_address = True 218 219 220 class TLSThreadingServer(ThreadingServer): 221 """Threading server that does the TLS handshake in the worker thread, so 222 that one slow or abandoned handshake does not block other connections.""" 223 224 def __init__(self, server_address, handler_cls, ssl_context): 225 self.ssl_context = ssl_context 226 super().__init__(server_address, handler_cls) 227 228 def process_request_thread(self, request, client_address): 229 try: 230 request.settimeout(20) 231 request = self.ssl_context.wrap_socket(request, server_side=True) 232 request.settimeout(None) 233 except (ssl.SSLError, OSError): 234 # A device that does not trust the CA, a probe, or a client that left. 235 self.shutdown_request(request) 236 return 237 super().process_request_thread(request, client_address) 238 239 240 def make_handler(base_path): 241 """Return a handler that serves SCRIPT_DIR mounted under base_path.""" 242 class Handler(http.server.SimpleHTTPRequestHandler): 243 def __init__(self, *args, **kwargs): 244 super().__init__(*args, directory=str(SCRIPT_DIR), **kwargs) 245 246 def end_headers(self): 247 # Makes browsers check for a newer file on every load. 248 self.send_header("Cache-Control", "no-cache") 249 super().end_headers() 250 251 def log_message(self, *args): 252 pass 253 254 def handle(self): 255 try: 256 super().handle() 257 except (BrokenPipeError, ConnectionResetError, ssl.SSLError): 258 pass 259 260 def translate_path(self, path): 261 if base_path != "/" and path.startswith(base_path): 262 path = "/" + path[len(base_path):] 263 return super().translate_path(path) 264 265 def do_GET(self): 266 # Sends a visit to the bare address into the app. 267 if base_path != "/" and self.path in ("/", "/index.html"): 268 self.send_response(302) 269 self.send_header("Location", base_path) 270 self.send_header("Content-Length", "0") 271 self.end_headers() 272 return 273 return super().do_GET() 274 275 return Handler 276 277 278 def serve_http(): 279 """Serve over plain HTTP to this computer only. Runs until Ctrl+C.""" 280 port = find_available_port(HTTP_PORT) 281 with ThreadingServer(("127.0.0.1", port), make_handler("/")) as httpd: 282 print(f"\nServing over plain HTTP at http://localhost:{port}") 283 print("Other devices can't install soundstone from here, because that needs HTTPS.") 284 print("\nPress Ctrl+C to stop the server") 285 try: 286 httpd.serve_forever() 287 except KeyboardInterrupt: 288 print("\n\nShutting down...") 289 290 291 def serve_https(local_ip, ca_httpd): 292 """Serve over HTTPS under BASE_PATH. Runs until Ctrl+C, then also shuts 293 down the CA server.""" 294 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) 295 ctx.load_cert_chain(certfile=str(CERT_FILE), keyfile=str(KEY_FILE)) 296 port = find_available_port(HTTPS_PORT) 297 298 with TLSThreadingServer(("", port), make_handler(BASE_PATH), ctx) as httpd: 299 https_url = f"https://{local_ip}:{port}{BASE_PATH}" 300 print("\n" + "=" * 60) 301 print("STEP 2: install soundstone (once the device trusts the CA)") 302 print("=" * 60) 303 print_qr_code(https_url, "Scan to open soundstone over HTTPS:") 304 print(f" {https_url}") 305 print("\nThen install it: Share → Add to Home Screen on iOS, or the") 306 print("browser menu → Install app on Android.") 307 print(f"\nOn this computer, open https://localhost:{port}{BASE_PATH}") 308 print("\nPress Ctrl+C to stop the servers") 309 try: 310 httpd.serve_forever() 311 except KeyboardInterrupt: 312 print("\n\nShutting down...") 313 finally: 314 ca_httpd.shutdown() 315 ca_httpd.server_close() 316 317 318 def start(): 319 local_ip = get_local_ip() 320 if not local_ip: 321 print("Couldn't find this computer's address on a local network.") 322 serve_http() 323 return 324 if which("mkcert") is None: 325 print("mkcert isn't installed, so HTTPS isn't available.") 326 print("Install it from https://github.com/FiloSottile/mkcert and run serve.py again.") 327 serve_http() 328 return 329 330 ensure_ca_installed() 331 ensure_leaf_cert(local_ip) 332 serve_https(local_ip, start_ca_server(local_ip)) 333 334 335 if __name__ == "__main__": 336 if "--in-venv" in sys.argv: 337 start() 338 else: 339 run_in_venv()