| 1 | #!/usr/bin/env python3 |
| 2 | import hmac |
| 3 | import html |
| 4 | from http import HTTPStatus |
| 5 | import http.server |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import plistlib |
| 9 | import re |
| 10 | import shutil |
| 11 | import tempfile |
| 12 | import zipfile |
| 13 | |
| 14 | ROOT = Path(os.environ["OTA_ROOT"]) |
| 15 | ORIGIN = os.environ["OTA_ORIGIN"] |
| 16 | TOKEN = os.environ["OTA_UPLOAD_TOKEN"].encode() |
| 17 | KEEP = 20 |
| 18 | MAX_IPA = 2 * 1024**3 |
| 19 | BUILD = re.compile(r"/([0-9a-f]{32})(/manifest\.plist|/app\.ipa)?\Z") |
| 20 | APP_PLIST = re.compile(r"Payload/[^/]+\.app/Info\.plist\Z") |
| 21 | |
| 22 | |
| 23 | def app_info(ipa): |
| 24 | with zipfile.ZipFile(ipa) as archive: |
| 25 | return plistlib.loads(archive.read(next(name for name in archive.namelist() if APP_PLIST.fullmatch(name)))) |
| 26 | |
| 27 | |
| 28 | def title(info): |
| 29 | return info.get("CFBundleDisplayName") or info["CFBundleName"] |
| 30 | |
| 31 | |
| 32 | def version(info): |
| 33 | return info["CFBundleShortVersionString"] |
| 34 | |
| 35 | |
| 36 | class Handler(http.server.BaseHTTPRequestHandler): |
| 37 | protocol_version = "HTTP/1.1" |
| 38 | |
| 39 | def send(self, status, content_type, body): |
| 40 | self.send_response(status) |
| 41 | self.send_header("Content-Type", content_type) |
| 42 | self.send_header("Content-Length", str(len(body))) |
| 43 | self.end_headers() |
| 44 | self.wfile.write(body) |
| 45 | |
| 46 | def do_GET(self): |
| 47 | if self.path == "/health": |
| 48 | return self.send(HTTPStatus.OK, "text/plain", b"ok") |
| 49 | match = BUILD.fullmatch(self.path) |
| 50 | ipa = ROOT / match[1] / "app.ipa" if match else None |
| 51 | if not ipa or not ipa.is_file(): |
| 52 | return self.send(HTTPStatus.NOT_FOUND, "text/plain", b"not found") |
| 53 | if match[2] == "/app.ipa": |
| 54 | self.send_response(HTTPStatus.OK) |
| 55 | self.send_header("Content-Type", "application/octet-stream") |
| 56 | self.send_header("Content-Length", str(ipa.stat().st_size)) |
| 57 | self.end_headers() |
| 58 | with ipa.open("rb") as source: |
| 59 | shutil.copyfileobj(source, self.wfile, 1 << 20) |
| 60 | return |
| 61 | info = app_info(ipa) |
| 62 | base = f"{ORIGIN}/{match[1]}" |
| 63 | if match[2]: |
| 64 | return self.send(HTTPStatus.OK, "text/xml", plistlib.dumps({"items": [{ |
| 65 | "assets": [{"kind": "software-package", "url": f"{base}/app.ipa"}], |
| 66 | "metadata": {"bundle-identifier": info["CFBundleIdentifier"], "bundle-version": version(info), "kind": "software", "title": title(info)}, |
| 67 | }]})) |
| 68 | install = html.escape(f"itms-services://?action=download-manifest&url={base}/manifest.plist") |
| 69 | self.send(HTTPStatus.OK, "text/html; charset=utf-8", f"""<!doctype html> |
| 70 | <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> |
| 71 | <title>{html.escape(title(info))}</title> |
| 72 | <style>body{{font:18px system-ui;max-width:24em;margin:20vh auto;padding:0 1em;text-align:center}}a{{display:inline-block;margin-top:1em;padding:.7em 2em;border-radius:2em;background:#07f;color:#fff;text-decoration:none}}</style> |
| 73 | <h1>{html.escape(title(info))}</h1><p>{html.escape(version(info))}</p><a href="{install}">Install</a> |
| 74 | """.encode()) |
| 75 | |
| 76 | def do_PUT(self): |
| 77 | if self.path != "/builds" or not hmac.compare_digest(self.headers.get("Authorization", "").encode(), b"Bearer " + TOKEN): |
| 78 | self.close_connection = True |
| 79 | return self.send(HTTPStatus.UNAUTHORIZED, "text/plain", b"unauthorized") |
| 80 | size = int(self.headers.get("Content-Length", -1)) |
| 81 | if not 0 < size <= MAX_IPA: |
| 82 | self.close_connection = True |
| 83 | return self.send(HTTPStatus.LENGTH_REQUIRED, "text/plain", b"a Content-Length up to 2 GiB is required") |
| 84 | ROOT.mkdir(exist_ok=True) |
| 85 | with tempfile.NamedTemporaryFile(dir=ROOT, prefix=".upload-", delete=False) as upload: |
| 86 | try: |
| 87 | remaining = size |
| 88 | while remaining: |
| 89 | chunk = self.rfile.read(min(1 << 20, remaining)) |
| 90 | if not chunk: |
| 91 | raise ConnectionError("upload ended early") |
| 92 | upload.write(chunk) |
| 93 | remaining -= len(chunk) |
| 94 | upload.flush() |
| 95 | app_info(upload.name) |
| 96 | except (ConnectionError, zipfile.BadZipFile, StopIteration, KeyError, plistlib.InvalidFileException): |
| 97 | os.unlink(upload.name) |
| 98 | self.close_connection = True |
| 99 | return self.send(HTTPStatus.BAD_REQUEST, "text/plain", b"not an IPA with an app Info.plist") |
| 100 | build = os.urandom(16).hex() |
| 101 | (ROOT / build).mkdir() |
| 102 | os.chmod(upload.name, 0o644) |
| 103 | os.replace(upload.name, ROOT / build / "app.ipa") |
| 104 | for old in sorted((path for path in ROOT.glob("*/") if BUILD.fullmatch("/" + path.name)), key=lambda path: path.stat().st_mtime)[:-KEEP]: |
| 105 | shutil.rmtree(old) |
| 106 | self.send(HTTPStatus.CREATED, "text/plain", f"{ORIGIN}/{build}\n".encode()) |
| 107 | |
| 108 | |
| 109 | if __name__ == "__main__": |
| 110 | http.server.ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever() |