## Runtime configuration (DESIGN 11.1). Keys FIXED owner-delegated, #16: ## --public-origin | FFF_VTT_PUBLIC_ORIGIN browser origin, exact match later for Origin checks ## --port | FFF_VTT_PORT listen port, 1..65535 ## --state-dir | FFF_VTT_STATE_DIR directory holding state.db (and tiles later) ## Flags win over env, env wins over defaults. The listen address is NOT a key: the server always ## binds 127.0.0.1 (DESIGN 3.4 T15; nginx is the only public face). import std/[os, strutils] type Config* = object publicOrigin*: string port*: int stateDir*: string help*: bool ConfigError* = object of CatchableError ## Bad flag, bad env value or an incoherent combination; main() prints it and exits 2. EnvLookup* = proc(key: string): string {.closure.} ## Environment reader, injected so tests do not touch the process env. const BindAddress* = "127.0.0.1" DefaultPublicOrigin* = "http://localhost:8080" DefaultPort* = 9000 DefaultStateDir* = "run" proc processEnv(): EnvLookup = result = proc(key: string): string = getEnv(key) proc fail(msg: string) {.noreturn.} = raise newException(ConfigError, msg) proc parsePort(key, value: string): int = if value.len == 0 or value.len > 5 or not value.allCharsInSet(Digits): fail key & ": expected a port number 1..65535, got \"" & value & "\"" let p = parseInt(value) if p < 1 or p > 65535: fail key & ": expected a port number 1..65535, got " & value p proc parseOrigin(key, value: string): string = ## scheme://host[:port], lowercased, no trailing slash: this string is compared byte for byte ## against the browser's Origin header (3.2), so it must be the canonical form. var v = value.strip if v.len == 0: fail key & ": expected http(s)://host[:port]" var scheme = "" for candidate in ["https://", "http://"]: if v.toLowerAscii.startsWith(candidate): scheme = candidate v = v[candidate.len .. ^1] break if scheme.len == 0: fail key & ": expected an http:// or https:// origin, got \"" & value & "\"" if '?' in v or '#' in v or '@' in v or '[' in v or ']' in v: fail key & ": origin must be scheme://host[:port] (no query, fragment, userinfo or IPv6 literal), got \"" & value & "\"" var hostPort = v let slash = v.find('/') if slash >= 0: if v[slash .. ^1].strip(chars = {'/'}).len != 0: fail key & ": origin must have no path, got \"" & value & "\"" hostPort = v[0 ..< slash] if hostPort.len == 0: fail key & ": origin has no host, got \"" & value & "\"" var host = hostPort let colon = hostPort.rfind(':') if colon >= 0: host = hostPort[0 ..< colon] discard parsePort(key, hostPort[colon + 1 .. ^1]) const hostChars = {'a'..'z', 'A'..'Z', '0'..'9', '.', '-', '_'} if host.len == 0 or not host.allCharsInSet(hostChars): fail key & ": origin host must be a DNS name or IPv4 literal, got \"" & value & "\"" scheme & hostPort.toLowerAscii proc parseStateDir(key, value: string): string = var v = value.strip if v.len == 0: fail key & ": expected a directory path" while v.len > 1 and v[^1] == '/': v.setLen(v.len - 1) v proc usage*(): string = """fff-vtt - server-authoritative vision VTT Usage: fff-vtt [options] Options: --public-origin= Browser origin the site is served from (default: http://localhost:8080). Env: FFF_VTT_PUBLIC_ORIGIN --port= Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT --state-dir= Directory holding state.db (default: run). Env: FFF_VTT_STATE_DIR -h, --help Print this help and exit. The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front. """ proc parseConfig*(args: openArray[string], envLookup: EnvLookup = nil): Config = let lookup = if envLookup.isNil: processEnv() else: envLookup result.publicOrigin = DefaultPublicOrigin result.port = DefaultPort result.stateDir = DefaultStateDir # --help wins over everything, including a broken env: the usage text must always be reachable. for arg in args: if arg == "-h" or arg == "--help": result.help = true if result.help: return let envOrigin = lookup("FFF_VTT_PUBLIC_ORIGIN") if envOrigin.strip.len > 0: result.publicOrigin = parseOrigin("FFF_VTT_PUBLIC_ORIGIN", envOrigin) let envPort = lookup("FFF_VTT_PORT") if envPort.strip.len > 0: result.port = parsePort("FFF_VTT_PORT", envPort.strip) let envState = lookup("FFF_VTT_STATE_DIR") if envState.strip.len > 0: result.stateDir = parseStateDir("FFF_VTT_STATE_DIR", envState) var i = 0 while i < args.len: let arg = args[i] inc i if not arg.startsWith("--"): fail "unexpected argument \"" & arg & "\" (see --help)" var key = arg[2 .. ^1] var value = "" var hasValue = false let eq = key.find('=') if eq >= 0: value = key[eq + 1 .. ^1] key = key[0 ..< eq] hasValue = true if key notin ["public-origin", "port", "state-dir"]: fail "unknown flag --" & key & " (see --help)" if not hasValue: if i >= args.len: fail "--" & key & ": missing value" value = args[i] inc i case key of "public-origin": result.publicOrigin = parseOrigin("--public-origin", value) of "port": result.port = parsePort("--port", value.strip) of "state-dir": result.stateDir = parseStateDir("--state-dir", value) else: discard proc dbPath*(c: Config): string = c.stateDir / "state.db"