#!/bin/sh # Download the protected Godmode installer. This public bootstrap contains no keys. set -eu usage() { cat <<'USAGE' Usage: curl -fsSL https://get.godmode.build | bash bash bootstrap.sh [--home DIR] [--version vX.Y.Z] Installs Godmode and godmodeup, and adds their directory to your shell's PATH. Requires Python 3.9+, macOS or Linux, and the private preview password. The password is entered without echoing it; automation can set GODMODE_PREVIEW_PASSWORD. Existing installations are preserved. Run godmodeup to update them. Activate afterwards with: godmode license activate USAGE } # Nothing runs until the complete function definition has arrived through the pipe. main() { if [ "$#" -eq 1 ]; then case "$1" in -h|--help) usage; return 0 ;; esac fi if ! command -v python3 >/dev/null 2>&1; then printf '%s\n' 'godmode bootstrap: Python 3.9 or later is required; nothing installed' >&2 return 1 fi exec python3 -I - "$@" <<'GODMODE_BOOTSTRAP_PY' import sys if sys.version_info < (3, 9): sys.exit("godmode bootstrap: Python 3.9 or later is required; nothing installed") import base64 import getpass import http.client import os from pathlib import Path import re import signal import ssl import subprocess import tempfile import time import urllib.error import urllib.request import warnings ORIGIN = "https://godmode.build" MAX_INSTALLER = 512 * 1024 class BootstrapError(Exception): pass class RefuseRedirects(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def options(arguments): result = [] seen = set() while arguments: flag = arguments.pop(0) if flag not in ("--home", "--version") or flag in seen: raise BootstrapError("unknown or repeated option; use --help") if not arguments or not arguments[0] or arguments[0].startswith("--"): raise BootstrapError("missing option value; use --help") value = arguments.pop(0) if flag == "--version" and (len(value) > 40 or not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", value)): raise BootstrapError("version must be vX.Y.Z") seen.add(flag) result.extend((flag, value)) return result def password(): value = os.environ.pop("GODMODE_PREVIEW_PASSWORD", None) if value is None: try: with open("/dev/tty", "w") as tty: with warnings.catch_warnings(): warnings.simplefilter("error", getpass.GetPassWarning) value = getpass.getpass("Godmode preview password: ", stream=tty) except (OSError, EOFError, getpass.GetPassWarning): raise BootstrapError("preview password required; run in a terminal or set GODMODE_PREVIEW_PASSWORD") from None if not value or len(value) > 4096: raise BootstrapError("preview password is empty or too long") return value def download(secret): opener = urllib.request.build_opener( urllib.request.ProxyHandler({}), RefuseRedirects(), urllib.request.HTTPSHandler(context=ssl.create_default_context())) authorization = base64.b64encode(("godmode:" + secret).encode("utf-8")).decode("ascii") request = urllib.request.Request(ORIGIN + "/install.sh", headers={ "Authorization": "Basic " + authorization, "User-Agent": "godmode-bootstrap/1", "Accept": "text/plain, application/x-sh, application/octet-stream", "Accept-Encoding": "identity", }) try: with opener.open(request, timeout=30) as response: if response.status != 200: raise BootstrapError("installer server returned an unexpected response") if response.headers.get_content_type() == "text/html": raise BootstrapError("installer server returned HTML instead of a script") length = response.headers.get("Content-Length") if length is not None and (not re.fullmatch(r"[0-9]+", length) or int(length) > MAX_INSTALLER): raise BootstrapError("installer download exceeds its size limit") payload = response.read(MAX_INSTALLER + 1) if len(payload) > MAX_INSTALLER: raise BootstrapError("installer download exceeds its size limit") if length is not None and len(payload) != int(length): raise BootstrapError("installer download is incomplete") except urllib.error.HTTPError as error: status = error.code error.close() if status == 401: raise BootstrapError("preview password was not accepted") from None if 300 <= status < 400: raise BootstrapError("installer redirected a request; redirects are refused") from None raise BootstrapError("installer download failed (HTTP " + str(status) + ")") from None except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException): raise BootstrapError("cannot download the installer over verified HTTPS") from None if (not payload.startswith(b"#!/bin/sh\n# godmode-installer-format: 1\n") or b"\0" in payload): raise BootstrapError("download is not a Godmode installer") return payload def interrupted(signum, _frame): raise SystemExit(128 + signum) def stop_installer(child): # The installer owns a separate process group. Stop its shell and helpers, # allow their cleanup traps to run, then kill any remaining descendants. # Repeated cancellation must not interrupt this cleanup. for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(signum, signal.SIG_IGN) try: os.killpg(child.pid, signal.SIGTERM) except ProcessLookupError: pass deadline = time.monotonic() + 2 while time.monotonic() < deadline: child.poll() # Reap the direct child so it does not keep the group alive. try: os.killpg(child.pid, 0) except ProcessLookupError: break time.sleep(0.05) try: os.killpg(child.pid, signal.SIGKILL) except ProcessLookupError: pass child.wait() def main(): arguments = options(sys.argv[1:]) secret = password() payload = download(secret) # A private temporary directory is cleaned on success, error and interruption. with tempfile.TemporaryDirectory(prefix="godmode-bootstrap-") as directory: installer = Path(directory) / "install.sh" descriptor = os.open(installer, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(descriptor, "wb") as stream: stream.write(payload) checked = subprocess.run(["sh", "-n", str(installer)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if checked.returncode: raise BootstrapError("downloaded installer is not valid shell") child_environment = dict(os.environ, GODMODE_PREVIEW_PASSWORD=secret) try: child = None try: # Defer cancellation through fork/exec until the child PID is # owned, so a signal cannot strand a just-started installer. pending = [] handlers = {} try: for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): handlers[signum] = signal.signal(signum, lambda number, _frame: pending.append(number)) child = subprocess.Popen(["sh", str(installer), "--path", "--install-only", *arguments], env=child_environment, stdin=subprocess.DEVNULL, start_new_session=True) finally: for signum, handler in handlers.items(): signal.signal(signum, handler) if pending: raise SystemExit(128 + pending[0]) returncode = child.wait() except BaseException: if child is not None: stop_installer(child) raise finally: child_environment.pop("GODMODE_PREVIEW_PASSWORD", None) secret = None if returncode: return returncode if returncode > 0 else 128 - returncode print(" For later updates, run: godmodeup") return 0 signal.signal(signal.SIGTERM, interrupted) signal.signal(signal.SIGHUP, interrupted) try: sys.exit(main()) except KeyboardInterrupt: print("\ngodmode bootstrap: cancelled", file=sys.stderr) sys.exit(130) except BootstrapError as error: sys.exit("godmode bootstrap: " + str(error)) except (OSError, ValueError, http.client.HTTPException): # Underlying exceptions can contain user inputs, paths or server responses. sys.exit("godmode bootstrap: could not complete installation") GODMODE_BOOTSTRAP_PY } main "$@"