diff --git a/server/main.nim b/server/main.nim index 03509f1..6803628 100644 --- a/server/main.nim +++ b/server/main.nim @@ -1,21 +1,24 @@ -## fff-vtt entrypoint. M3 slice 2 (#17): getting in. Config, state dir + data-dir lock, SQLite -## migrations, `fff-vtt gm-key`, `POST /join`, session cookies, and the authenticated `/ws` upgrade -## with connection caps and key/player revocation. Nothing game-specific yet. -## Wire codes/close codes and the rest of the envelope land in slice 3 (#18); this slice carries the -## minimum ack shape (DESIGN 6.1) for the three intents auth needs: key.create, key.replace, -## player.remove. +## fff-vtt entrypoint. M3 slice 2 (#17): getting in - config, state dir + data-dir lock, SQLite +## migrations, `fff-vtt gm-key`, `POST /join`, session cookies, the authenticated `/ws` upgrade +## with connection caps and key/player revocation. +## M3 slice 3 (#18): the WS protocol shell - `hello`, the per-connection `n` counter, exactly one +## `ack` per intent, `error` frames, the intent rate limit, the malformed-flood close, the proto +## version check, the oversize frame limit (mummy's 64 KB) and the server Ping heartbeat. +## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so +## every server-initiated close is preceded by a `closing {reason, code}` message and the client +## reads 1005 + that message (DESIGN 6.5). ## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face. -import std/[json, locks, options, os, strutils] +import std/[atomics, json, locks, options, os, strutils] +import std/typedthreads import db_connector/db_sqlite import mummy, mummy/routers -import config, db, eventlog, crypto, auth, conns, instancelock +import config, db, eventlog, crypto, auth, conns, instancelock, protocol const CookieName* = "fff_session" ## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED. MaxJoinBody* = 1024 ## DESIGN 6.6: the sign-in body is at most 1 KB. - ProtoAck* = "ack" type App = ref object @@ -31,6 +34,51 @@ var appHandle: pointer ## (mummy's handler types are non-closure procs, so the state cannot be captured). template app(): App = cast[App](appHandle) +var heartbeatThread: Thread[void] + ## The ping thread's handle must outlive the process (a global, not a stack local). +var pingCounter: Atomic[int64] + ## Payload of the last server Ping; the client echoes it in its Pong (4.3). Atomic because the + ## heartbeat thread and the upgrade handler (a worker thread) both send pings. + +proc nextPingSeq(): int64 = + pingCounter.fetchAdd(1) + 1 + +# --------------------------------------------------------------------------------------------------- +# Frame senders. `n` is the per-connection counter (DESIGN 6): it is allocated under the registry +# lock, so two threads sending to one connection never collide, and a frame is dropped for a +# connection that is gone (nextFrameNo answers 0). + +proc nextN(conn: Conn): int = + ## 0 = the connection is gone: the frame is dropped. + app.conns.nextFrameNo(conn.id) + +proc ackOk(conn: Conn, reqId: int, extra: JsonNode = nil) = + let n = nextN(conn) + if n > 0: conn.ws.send($ackFrame(reqId, n, extra)) + +proc ackErr(conn: Conn, reqId: int, code: string) = + let n = nextN(conn) + if n > 0: conn.ws.send($nackFrame(reqId, n, code)) + +proc sendError(conn: Conn, code: string) = + ## Only for frames that cannot be acked (DESIGN 6.5). + let n = nextN(conn) + if n > 0: conn.ws.send($errorFrame(code, n)) + +proc closeRegistered(conn: Conn, reason: string, code: int) = + ## A server-initiated close of a live connection: `closing` first (FIXED #18), then the close + ## frame. The registry entry goes first so nothing else can be enqueued behind the reason. + let n = nextN(conn) + app.conns.remove(conn.id) + if n > 0: conn.ws.send($closingFrame(reason, code, n)) + conn.ws.close() + +proc closeGone(conn: Conn, reason: string, code: int) = + ## Same, for a connection the registry already dropped (eviction, revocation). The snapshot's + ## frame number still closes the sequence correctly. + conn.ws.send($closingFrame(reason, code, conn.frameNo)) + conn.ws.close() + # --------------------------------------------------------------------------------------------------- # HTTP helpers @@ -69,16 +117,14 @@ proc sessionCookie(request: Request): string = let p = part.strip if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1] -proc ackError(ws: WebSocket, reqId: int, code: string) = - ws.send($(%*{"t": ProtoAck, "reqId": reqId, "ok": false, "code": code})) - -proc ackOk(ws: WebSocket, reqId: int, extra: JsonNode = newJObject()) = - var ack = newJObject() - ack["t"] = %ProtoAck - ack["reqId"] = %reqId - ack["ok"] = %true - for key, value in extra: ack[key] = value - ws.send($ack) +proc protoQuery(request: Request): int = + ## `/ws?proto=N` (DESIGN 6.2). -1 = absent or not a plain integer: HTTP 400, no upgrade (6.5 row 3). + let raw = request.queryParams["proto"] + if raw.len == 0 or raw.len > 9 or not raw.allCharsInSet(Digits): return -1 + try: + result = parseInt(raw) + except ValueError: + return -1 # --------------------------------------------------------------------------------------------------- # HTTP handlers @@ -128,7 +174,7 @@ proc join(request: Request) {.gcsafe.} = request.respond(303, headers) proc wsUpgrade(request: Request) {.gcsafe.} = - ## GET /ws: Origin, then session, then the total cap, then the upgrade (DESIGN 6.5 rows 1-4). + ## GET /ws: Origin, session, proto, total cap, then the upgrade (DESIGN 6.5 rows 1-5). if request.headers["Origin"] != app.cfg.publicOrigin: request.respond(403, body = "") return @@ -144,6 +190,11 @@ proc wsUpgrade(request: Request) {.gcsafe.} = request.respond(401, body = "") return + let proto = protoQuery(request) + if proto < 0: + request.respond(400, body = "") + return + if not app.conns.reserve(): var headers: HttpHeaders headers["Retry-After"] = "5" @@ -159,7 +210,19 @@ proc wsUpgrade(request: Request) {.gcsafe.} = request.respond(400, body = "") return - let activated = app.conns.activate(player.get.id, player.get.role, ws) + if proto != ProtoVersion: + # Row 5: a browser cannot read an HTTP status from a WebSocket, so the upgrade completes and + # the reason arrives as a `closing` message; no `hello`, no state (FIXED #18). + app.conns.cancelReserve() + ws.send($closingFrame(ReasonProtoMismatch, CloseProtoMismatch, 1)) + ws.close() + app.lg.log(lvInfo, "conn_refused_proto", [("player", $player.get.id), ("proto", $proto)]) + return + + let pid = player.get.id + let role = player.get.role + let named = player.get.name.isSome + let activated = app.conns.activate(pid, role, ws, named) # Close the replacement race: a key.replace between the lookup and the activation must not leave # a live connection on a revoked session. var stillValid = false @@ -167,56 +230,77 @@ proc wsUpgrade(request: Request) {.gcsafe.} = stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome if not stillValid: if app.conns.connById(activated.id).isSome: - app.conns.remove(activated.id) - ws.close() + let live = app.conns.connById(activated.id).get + closeRegistered(live, ReasonRevoked, CloseRevoked) return if activated.evicted.isSome: - activated.evicted.get.close() - app.lg.log(lvInfo, "conn_evicted", [("player", $player.get.id), - ("evicted_conn", $activated.evictedId.get)]) - app.lg.log(lvInfo, "conn_open", [("player", $player.get.id), ("role", $player.get.role), + let doomed = activated.evicted.get + closeGone(doomed, ReasonEvicted, CloseEvicted) + app.lg.log(lvInfo, "conn_evicted", [("player", $pid), ("evicted_conn", $doomed.id)]) + app.lg.log(lvInfo, "conn_open", [("player", $pid), ("role", $role), ("conn", $activated.id), ("total", $app.conns.activeCount)]) + # `hello` is the first frame on the connection (n = 1). The scene block and the resync sequence + # arrive with slice 5; this slice sends proto, role and me (DESIGN 6.1, 6.3). It is queued here, + # before the handler returns, and a browser cannot send anything before it has seen the 101, so + # in practice nothing can overtake it. + let me = if player.get.name.isSome: %player.get.name.get else: newJNull() + let helloN = app.conns.nextFrameNo(activated.id) + ws.send($helloFrame(ProtoVersion, helloN, $role, pid, me)) + # One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3). + ws.send($nextPingSeq(), Ping) + # --------------------------------------------------------------------------------------------------- -# WebSocket intents needed by this slice. Slice 3 adds the full envelope, error frames, rate limits -# and unknown-type handling; anything else here is ignored on purpose. +# Intent pipeline (DESIGN 6.5). Order: parse, rate limit, unknown type, unnamed player, role, +# fields, lookup, semantics. Every readable intent gets exactly one `ack`; an unreadable frame gets +# exactly one `error`. -proc handleIntent(conn: Conn, text: string) {.gcsafe.} = - var node: JsonNode - try: - node = parseJson(text) - except CatchableError: +proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = + if not isCatalogueIntent(env.t): + ackErr(conn, env.reqId, CodeUnknownType) + return + if not conn.named and conn.role != prGm and env.t notin ["conn.ping", "player.setname"]: + # An unnamed player may only ping and set their name (DESIGN 6.1 Roles). + ackErr(conn, env.reqId, CodeNotAllowed) + return + if conn.role != prGm and isGmOnlyIntent(env.t): + ackErr(conn, env.reqId, CodeNotAllowed) return - if node.kind != JObject: return - let t = node{"t"} - let reqIdNode = node{"reqId"} - if t.kind != JString or reqIdNode.kind != JInt: return - let reqId = reqIdNode.getInt - case t.getStr - of "key.create": - if conn.role != prGm: - ackError(conn.ws, reqId, "not-allowed") + case env.t + of "conn.ping": + let ts = env.node{"ts"} + if ts.isNil or ts.kind != JInt: + ackErr(conn, env.reqId, CodeInvalid) return + ackOk(conn, env.reqId, %*{"ts": ts.getInt}) + return + + of "act.do": + # Reserved for the FFF hook (DESIGN 9): always refused, never ok. Its fields are not validated + # in M3 because the answer is the same for every readable envelope; the hook's field schema is + # part of the FFF work (9). + ackErr(conn, env.reqId, CodeNoRules) + return + + of "key.create": var created: tuple[id: int, key: string] var capped = false withLock app.dbLock: capped = playerCount(app.db) >= MaxPlayers if not capped: created = createPlayerWithKey(app.db) if capped: - ackError(conn.ws, reqId, "cap-reached") + ackErr(conn, env.reqId, CodeCapReached) return app.lg.addSecret(created.key) app.lg.log(lvInfo, "key_created", [("player", $created.id)]) - ackOk(conn.ws, reqId, %*{"id": created.id, "key": created.key}) + ackOk(conn, env.reqId, %*{"id": created.id, "key": created.key}) + return of "key.replace": - if conn.role != prGm: - ackError(conn.ws, reqId, "not-allowed") - return - let idNode = node{"id"} - if idNode.kind != JInt: - ackError(conn.ws, reqId, "invalid") + let idNode = env.node{"id"} + if idNode.isNil or idNode.kind != JInt: + ackErr(conn, env.reqId, CodeInvalid) return let id = idNode.getInt var key: Option[string] @@ -231,27 +315,25 @@ proc handleIntent(conn: Conn, text: string) {.gcsafe.} = else: key = replacePlayerKey(app.db, id) if notFound: - ackError(conn.ws, reqId, "not-found") + ackErr(conn, env.reqId, CodeNotFound) return if notAllowed: - ackError(conn.ws, reqId, "not-allowed") + ackErr(conn, env.reqId, CodeNotAllowed) return if key.isNone: - ackError(conn.ws, reqId, "not-found") + ackErr(conn, env.reqId, CodeNotFound) return let closed = app.conns.revokePlayer(id) - for ws in closed: ws.close() + for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked) app.lg.addSecret(key.get) app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)]) - ackOk(conn.ws, reqId, %*{"key": key.get}) + ackOk(conn, env.reqId, %*{"key": key.get}) + return of "player.remove": - if conn.role != prGm: - ackError(conn.ws, reqId, "not-allowed") - return - let idNode = node{"id"} - if idNode.kind != JInt: - ackError(conn.ws, reqId, "invalid") + let idNode = env.node{"id"} + if idNode.isNil or idNode.kind != JInt: + ackErr(conn, env.reqId, CodeInvalid) return let id = idNode.getInt var removed = false @@ -266,38 +348,91 @@ proc handleIntent(conn: Conn, text: string) {.gcsafe.} = else: removed = removePlayer(app.db, id) if notFound: - ackError(conn.ws, reqId, "not-found") + ackErr(conn, env.reqId, CodeNotFound) return if notAllowed: - ackError(conn.ws, reqId, "not-allowed") + ackErr(conn, env.reqId, CodeNotAllowed) return if not removed: - ackError(conn.ws, reqId, "not-found") + ackErr(conn, env.reqId, CodeNotFound) return let closed = app.conns.revokePlayer(id) - for ws in closed: ws.close() + for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked) app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)]) - ackOk(conn.ws, reqId) + ackOk(conn, env.reqId) + return else: - discard # slice 3 answers unknown-type; this slice only carries the auth intents + # A catalogue intent whose slice has not landed yet (#19-#25). It still gets its one ack, with + # a static code and no state; `unknown-type` is the honest answer until the handler exists + # (DESIGN 6.1, slice-3 note). + ackErr(conn, env.reqId, CodeUnknownType) + +proc malformedFrame(conn: Conn, nowMs: int64) {.gcsafe.} = + ## DESIGN 6.5 step 2 / row 8: one `error malformed`, and the tenth inside 10 s closes with 1008. + if app.conns.recordMalformed(conn.id, nowMs): + closeRegistered(conn, ReasonMalformedFlood, CloseMalformedFlood) + app.lg.log(lvWarn, "conn_malformed_flood", [("player", $conn.playerId), ("conn", $conn.id)]) + else: + sendError(conn, CodeMalformed) + +proc handleText(conn: Conn, text: string) {.gcsafe.} = + ## DESIGN 6.5 steps 2 and 3: the bucket is spent by every inbound frame, readable or not. + let nowMs = monotonicMs() + let allowed = app.conns.takeIntentToken(conn.id, nowMs) + let env = parseEnvelope(text) + if not allowed: + if env.ok: ackErr(conn, env.reqId, CodeRateLimited) + else: sendError(conn, CodeRateLimited) + return + if not env.ok: + malformedFrame(conn, nowMs) + return + dispatch(conn, env) proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} = case event of MessageEvent: - let conn = app.conns.connForWs(ws) - if conn.isNone: return - if message.kind == TextMessage: - handleIntent(conn.get, message.data) + let found = app.conns.connForWs(ws) + if found.isNone: return + let conn = found.get + case message.kind + of TextMessage: + handleText(conn, message.data) + of BinaryMessage: + # DESIGN 6: a binary frame counts as malformed. + malformedFrame(conn, monotonicMs()) + of Ping: + # mummy does not answer client Pings itself; RFC 6455 requires a Pong with the same payload. + ws.send(message.data, Pong) + of Pong: + var seqNo: int64 + try: + seqNo = int64(parseInt(message.data)) + except ValueError: + seqNo = -1 + app.conns.notePong(conn.id, seqNo, monotonicMs()) of CloseEvent, ErrorEvent: - let conn = app.conns.connForWs(ws) - if conn.isSome: - app.conns.remove(conn.get.id) - app.lg.log(lvDebug, "conn_close", [("player", $conn.get.playerId), - ("conn", $conn.get.id)]) + let found = app.conns.connForWs(ws) + if found.isSome: + app.conns.remove(found.get.id) + app.lg.log(lvDebug, "conn_close", [("player", $found.get.playerId), + ("conn", $found.get.id)]) else: discard +# --------------------------------------------------------------------------------------------------- +# Heartbeat: a Ping every PingIntervalMs on every connection. Lag measurement and the stop-feeding +# rule are M5 (4.3); here the seq is only recorded when the Pong comes back. + +proc heartbeat() {.thread.} = + while true: + sleep(PingIntervalMs) + if appHandle == nil: continue # no App yet: nothing to ping + let payload = $nextPingSeq() + for conn in app().conns.snapshot(): + conn.ws.send(payload, Ping) + # --------------------------------------------------------------------------------------------------- # Startup and CLI @@ -327,6 +462,14 @@ Commands: The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front. """ +proc mummyLog(level: LogLevel, args: varargs[string]) {.gcsafe.} = + ## mummy's own lines (dropped oversize frame, bad frame) go through the event log, so nothing + ## writes to stdout behind the logger's back (DESIGN 11.3). Details ride at debug level. + if appHandle == nil: return + var text = "" + for arg in args: text.add arg + app().lg.log(if level == ErrorLevel: lvWarn else: lvDebug, "mummy", [("msg", text)]) + proc runGmKey(rawArgs: seq[string]): int = var rotate = false var cfgArgs: seq[string] @@ -416,7 +559,12 @@ proc runServer(cfg: Config): int = readRedactionSecrets(conn, lg) appHandle = cast[pointer](state) - let server = newServer(buildRouter().toHandler(), websocketEvent) + createThread(heartbeatThread, heartbeat) + lg.log(lvInfo, "heartbeat", [("interval_ms", $PingIntervalMs), ("proto", $ProtoVersion)]) + + # maxMessageLen is DESIGN 6.4's 64 KB, stated explicitly rather than inherited from mummy. + let server = newServer(buildRouter().toHandler(), websocketEvent, mummyLog, + maxMessageLen = MaxInboundBytes) lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)]) server.serve(Port(cfg.port), BindAddress) 0