The protocol shell over the socket, in DESIGN 6.5 order: spend a token, parse, then
unknown type / unnamed player / role / fields / lookup / semantics. Every readable
intent gets exactly one ack with a 6.5 code; an unreadable frame gets one error.
- hello {proto, role, me} as the first frame (n = 1); the scene block lands in slice 5
- /ws?proto=N is required: 400 when absent or not an integer, 101 + closing 4003 on
a mismatch (no hello, no state)
- intent bucket 30/s burst 100 and the 10-in-10-s malformed flood (closing 1008);
a rate-limited intent applies nothing and the connection stays open
- mummy maxMessageLen stated explicitly (64 KB) and mummy's own log lines routed
through the event log instead of stdout
- server Ping(seq) right after hello and every 20 s (lag enforcement stays M5);
inbound Pings are answered with a Pong, which mummy does not do itself
- close reasons: every server-initiated close sends closing {reason, code} then the
close frame, and slice 2's eviction/revocation paths do the same (FIXED, #18)
590 lines
22 KiB
Nim
590 lines
22 KiB
Nim
## 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/[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, 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.
|
|
|
|
type
|
|
App = ref object
|
|
cfg: Config
|
|
lg: Logger
|
|
db: DbConn
|
|
dbLock: Lock
|
|
conns: Conns
|
|
instanceLock: InstanceLock
|
|
|
|
var appHandle: pointer
|
|
## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}`
|
|
## (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
|
|
|
|
proc formValue(body, name: string): string =
|
|
## application/x-www-form-urlencoded: first value of `name`, percent-decoded, '+' = space.
|
|
for pair in body.split('&'):
|
|
let eq = pair.find('=')
|
|
let rawName = if eq >= 0: pair[0 ..< eq] else: pair
|
|
if rawName != name: continue
|
|
let raw = if eq >= 0: pair[eq + 1 .. ^1] else: ""
|
|
result = ""
|
|
var i = 0
|
|
while i < raw.len:
|
|
if raw[i] == '+':
|
|
result.add ' '
|
|
inc i
|
|
elif raw[i] == '%' and i + 2 < raw.len:
|
|
let hex = raw[i + 1 .. i + 2]
|
|
try:
|
|
result.add char(parseHexInt(hex))
|
|
except ValueError:
|
|
result.add raw[i]
|
|
inc i
|
|
continue
|
|
i += 3
|
|
else:
|
|
result.add raw[i]
|
|
inc i
|
|
return
|
|
|
|
proc sessionCookie(request: Request): string =
|
|
## First `fff_session` cookie across all Cookie headers (mummy's [] returns only the first header).
|
|
for (name, value) in request.headers:
|
|
if name.toLowerAscii != "cookie": continue
|
|
for part in value.split(';'):
|
|
let p = part.strip
|
|
if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1]
|
|
|
|
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
|
|
|
|
proc healthz(request: Request) {.gcsafe.} =
|
|
## Liveness only in this slice. M5 makes it report the global lock as well (DESIGN 11.3).
|
|
var headers: HttpHeaders
|
|
headers["Content-Type"] = "application/json"
|
|
request.respond(200, headers, """{"status":"ok"}""")
|
|
|
|
proc join(request: Request) {.gcsafe.} =
|
|
## POST /join: the only way to get a session (DESIGN 3.2, 6.6). The key travels in the body only.
|
|
let contentType = request.headers["Content-Type"].toLowerAscii
|
|
if not contentType.startsWith("application/x-www-form-urlencoded"):
|
|
request.respond(400, body = "")
|
|
return
|
|
if request.body.len > MaxJoinBody:
|
|
request.respond(400, body = "")
|
|
return
|
|
let key = formValue(request.body, "key")
|
|
if key.len == 0 or key.len > MaxJoinBody:
|
|
request.respond(400, body = "")
|
|
return
|
|
|
|
var player: Option[Player]
|
|
var token = ""
|
|
withLock app.dbLock:
|
|
player = findPlayerByKey(app.db, key)
|
|
if player.isSome:
|
|
token = randomSessionToken()
|
|
createSession(app.db, player.get.id, sha256Hex(token))
|
|
if player.isNone:
|
|
# No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline).
|
|
app.lg.log(lvInfo, "join_refused")
|
|
request.respond(401, body = "")
|
|
return
|
|
|
|
# The token is deliberately never registered for redaction: sessions never expire, so a value
|
|
# registry would grow without bound. It is only ever written to the Set-Cookie header; if a future
|
|
# call site passes it to the logger, the `cookie`/`session` field-name mask is the net (11.3).
|
|
app.lg.log(lvInfo, "join_ok", [("player", $player.get.id)])
|
|
var headers: HttpHeaders
|
|
headers["Location"] = "/"
|
|
headers["Set-Cookie"] = CookieName & "=" & token &
|
|
"; HttpOnly; Secure; SameSite=Strict; Path=/"
|
|
headers["Referrer-Policy"] = "no-referrer"
|
|
request.respond(303, headers)
|
|
|
|
proc wsUpgrade(request: Request) {.gcsafe.} =
|
|
## 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
|
|
let token = sessionCookie(request)
|
|
if token.len == 0:
|
|
request.respond(401, body = "")
|
|
return
|
|
|
|
var player: Option[Player]
|
|
withLock app.dbLock:
|
|
player = sessionPlayer(app.db, sha256Hex(token))
|
|
if player.isNone:
|
|
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"
|
|
app.lg.log(lvInfo, "conn_refused_total", [("player", $player.get.id)])
|
|
request.respond(503, headers, body = "")
|
|
return
|
|
|
|
var ws: WebSocket
|
|
try:
|
|
ws = request.upgradeToWebSocket()
|
|
except MummyError:
|
|
app.conns.cancelReserve()
|
|
request.respond(400, body = "")
|
|
return
|
|
|
|
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
|
|
withLock app.dbLock:
|
|
stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome
|
|
if not stillValid:
|
|
if app.conns.connById(activated.id).isSome:
|
|
let live = app.conns.connById(activated.id).get
|
|
closeRegistered(live, ReasonRevoked, CloseRevoked)
|
|
return
|
|
if activated.evicted.isSome:
|
|
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)
|
|
|
|
# ---------------------------------------------------------------------------------------------------
|
|
# 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 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
|
|
|
|
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:
|
|
ackErr(conn, env.reqId, CodeCapReached)
|
|
return
|
|
app.lg.addSecret(created.key)
|
|
app.lg.log(lvInfo, "key_created", [("player", $created.id)])
|
|
ackOk(conn, env.reqId, %*{"id": created.id, "key": created.key})
|
|
return
|
|
|
|
of "key.replace":
|
|
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]
|
|
var notFound = false
|
|
var notAllowed = false
|
|
withLock app.dbLock:
|
|
let target = playerById(app.db, id)
|
|
if target.isNone:
|
|
notFound = true
|
|
elif target.get.role == prGm:
|
|
notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2)
|
|
else:
|
|
key = replacePlayerKey(app.db, id)
|
|
if notFound:
|
|
ackErr(conn, env.reqId, CodeNotFound)
|
|
return
|
|
if notAllowed:
|
|
ackErr(conn, env.reqId, CodeNotAllowed)
|
|
return
|
|
if key.isNone:
|
|
ackErr(conn, env.reqId, CodeNotFound)
|
|
return
|
|
let closed = app.conns.revokePlayer(id)
|
|
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, env.reqId, %*{"key": key.get})
|
|
return
|
|
|
|
of "player.remove":
|
|
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
|
|
var notFound = false
|
|
var notAllowed = false
|
|
withLock app.dbLock:
|
|
let target = playerById(app.db, id)
|
|
if target.isNone:
|
|
notFound = true
|
|
elif target.get.role == prGm:
|
|
notAllowed = true
|
|
else:
|
|
removed = removePlayer(app.db, id)
|
|
if notFound:
|
|
ackErr(conn, env.reqId, CodeNotFound)
|
|
return
|
|
if notAllowed:
|
|
ackErr(conn, env.reqId, CodeNotAllowed)
|
|
return
|
|
if not removed:
|
|
ackErr(conn, env.reqId, CodeNotFound)
|
|
return
|
|
let closed = app.conns.revokePlayer(id)
|
|
for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked)
|
|
app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)])
|
|
ackOk(conn, env.reqId)
|
|
return
|
|
|
|
else:
|
|
# 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 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 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
|
|
|
|
proc buildRouter(): Router =
|
|
result.get("/healthz", healthz)
|
|
result.post("/join", join)
|
|
result.get("/ws", wsUpgrade)
|
|
|
|
proc cliUsage(): string =
|
|
"""fff-vtt - server-authoritative vision VTT
|
|
|
|
Usage: fff-vtt [options]
|
|
fff-vtt gm-key [--new] [options]
|
|
|
|
Options:
|
|
--public-origin=<url> Browser origin the site is served from (default: http://localhost:8080).
|
|
Env: FFF_VTT_PUBLIC_ORIGIN
|
|
--port=<n> Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT
|
|
--state-dir=<path> Directory holding state.db (default: run). Env: FFF_VTT_STATE_DIR
|
|
-h, --help Print this help and exit.
|
|
|
|
Commands:
|
|
gm-key Create the single GM if needed and print the GM key (same key on re-run).
|
|
gm-key --new Rotate the GM key and revoke all GM sessions. Refused while the server
|
|
holds the state-dir lock (stop the server first).
|
|
|
|
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]
|
|
for arg in rawArgs:
|
|
if arg == "--new": rotate = true
|
|
else: cfgArgs.add arg
|
|
var cfg: Config
|
|
try:
|
|
cfg = parseConfig(cfgArgs)
|
|
except ConfigError as e:
|
|
stderr.writeLine "fff-vtt gm-key: " & e.msg
|
|
return 2
|
|
if cfg.help:
|
|
stdout.write cliUsage()
|
|
return 0
|
|
try:
|
|
createDir(cfg.stateDir)
|
|
except CatchableError as e:
|
|
stderr.writeLine "fff-vtt gm-key: cannot create " & cfg.stateDir & ": " & e.msg
|
|
return 1
|
|
|
|
var lock: InstanceLock
|
|
if rotate:
|
|
lock = tryAcquire(cfg.stateDir)
|
|
if not lock.held:
|
|
stderr.writeLine "fff-vtt gm-key --new: the server is running on " & cfg.stateDir &
|
|
" (state-dir lock held); stop it first"
|
|
return 3
|
|
|
|
var conn: DbConn
|
|
try:
|
|
conn = openDatabase(cfg.dbPath)
|
|
except CatchableError as e:
|
|
stderr.writeLine "fff-vtt gm-key: cannot open " & cfg.dbPath & ": " & e.msg
|
|
return 1
|
|
defer: close(conn)
|
|
try:
|
|
discard migrate(conn)
|
|
let created = ensureGm(conn, rotate)
|
|
if created.rotated:
|
|
stdout.writeLine "GM key (new): " & created.key
|
|
else:
|
|
stdout.writeLine "GM key: " & created.key
|
|
stdout.flushFile()
|
|
except CatchableError as e:
|
|
stderr.writeLine "fff-vtt gm-key: " & e.msg
|
|
return 1
|
|
0
|
|
|
|
proc readRedactionSecrets(db: DbConn, lg: Logger) =
|
|
## The safety net behind "never log keys": register every stored key for redaction.
|
|
for row in db.getAllRows(sql"SELECT secret FROM player_key"):
|
|
if row.len > 0 and row[0].len >= MinSecretLen:
|
|
try: lg.addSecret(row[0])
|
|
except ValueError: discard
|
|
|
|
proc runServer(cfg: Config): int =
|
|
let lg = newLogger()
|
|
lg.log(lvInfo, "server_start", [("origin", cfg.publicOrigin), ("state_dir", cfg.stateDir),
|
|
("bind", BindAddress)])
|
|
try:
|
|
createDir(cfg.stateDir)
|
|
except CatchableError as e:
|
|
lg.log(lvError, "state_dir_failed", [("path", cfg.stateDir), ("error", e.msg)])
|
|
return 1
|
|
|
|
var instanceLock = tryAcquire(cfg.stateDir)
|
|
if not instanceLock.held:
|
|
lg.log(lvError, "state_dir_locked", [("path", cfg.stateDir)])
|
|
return 1
|
|
|
|
var conn: DbConn
|
|
try:
|
|
conn = openDatabase(cfg.dbPath)
|
|
except CatchableError as e:
|
|
lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)])
|
|
return 1
|
|
let applied = try: migrate(conn)
|
|
except CatchableError as e:
|
|
lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)])
|
|
return 1
|
|
lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)),
|
|
("applied", $applied)])
|
|
|
|
let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock)
|
|
initLock(state.dbLock)
|
|
readRedactionSecrets(conn, lg)
|
|
appHandle = cast[pointer](state)
|
|
|
|
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
|
|
|
|
proc main() =
|
|
let args = commandLineParams()
|
|
if args.len > 0 and args[0] == "gm-key":
|
|
quit runGmKey(if args.len > 1: args[1 .. ^1] else: @[])
|
|
|
|
var cfg: Config
|
|
try:
|
|
cfg = parseConfig(args)
|
|
except ConfigError as e:
|
|
stderr.writeLine "fff-vtt: " & e.msg
|
|
quit 2
|
|
if cfg.help:
|
|
stdout.write cliUsage()
|
|
quit 0
|
|
quit runServer(cfg)
|
|
|
|
when isMainModule:
|
|
main()
|