2021-06-27 06:35:36 +00:00
|
|
|
## nim-websock
|
2023-07-24 20:38:21 +00:00
|
|
|
## Copyright (c) 2021-2023 Status Research & Development GmbH
|
2021-05-25 22:39:10 +00:00
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2024-01-22 12:08:17 +00:00
|
|
|
{.push gcsafe, raises: [].}
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
import std/strformat
|
2021-05-25 22:39:10 +00:00
|
|
|
import pkg/[chronos, chronicles, stew/byteutils, stew/endians2]
|
2023-07-24 20:38:21 +00:00
|
|
|
import ./types, ./frame, ./utf8dfa, ./http
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
import pkg/chronos/streams/asyncstream
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
logScope:
|
2021-07-14 17:26:46 +00:00
|
|
|
topics = "websock ws-session"
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2024-01-22 12:08:17 +00:00
|
|
|
template used(x: typed) =
|
|
|
|
# silence unused warning
|
|
|
|
discard
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
proc prepareCloseBody(code: StatusCodes, reason: string): seq[byte] =
|
2021-05-25 22:39:10 +00:00
|
|
|
result = reason.toBytes
|
|
|
|
if ord(code) > 999:
|
|
|
|
result = @(ord(code).uint16.toBytesBE()) & result
|
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
proc writeMessage(ws: WSSession,
|
2021-05-25 22:39:10 +00:00
|
|
|
data: seq[byte] = @[],
|
2021-06-11 20:04:09 +00:00
|
|
|
opcode: Opcode,
|
2021-06-12 00:40:56 +00:00
|
|
|
maskKey: MaskKey,
|
2021-06-11 20:04:09 +00:00
|
|
|
extensions: seq[Ext]) {.async.} =
|
2021-05-25 22:39:10 +00:00
|
|
|
|
|
|
|
if opcode notin {Opcode.Text, Opcode.Cont, Opcode.Binary}:
|
2021-06-12 00:40:56 +00:00
|
|
|
warn "Attempting to send a data frame with an invalid opcode!"
|
|
|
|
raise newException(WSInvalidOpcodeError,
|
|
|
|
&"Attempting to send a data frame with an invalid opcode {opcode}!")
|
2021-05-25 22:39:10 +00:00
|
|
|
|
|
|
|
let maxSize = ws.frameSize
|
|
|
|
var i = 0
|
2022-09-06 09:09:21 +00:00
|
|
|
while ws.readyState notin {ReadyState.Closing, ReadyState.Closed}:
|
2022-06-30 15:14:07 +00:00
|
|
|
let canSend = min(data.len - i, maxSize)
|
2021-06-11 20:04:09 +00:00
|
|
|
let frame = Frame(
|
2022-06-30 15:14:07 +00:00
|
|
|
fin: if (canSend + i >= data.len): true else: false,
|
2021-05-25 22:39:10 +00:00
|
|
|
rsv1: false,
|
|
|
|
rsv2: false,
|
|
|
|
rsv3: false,
|
|
|
|
opcode: if i > 0: Opcode.Cont else: opcode, # fragments have to be `Continuation` frames
|
|
|
|
mask: ws.masked,
|
2022-06-30 15:14:07 +00:00
|
|
|
data: data[i ..< canSend + i],
|
2021-05-25 22:39:10 +00:00
|
|
|
maskKey: maskKey)
|
2021-06-11 20:04:09 +00:00
|
|
|
|
|
|
|
let encoded = await frame.encode(extensions)
|
|
|
|
await ws.stream.writer.write(encoded)
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2022-06-30 15:14:07 +00:00
|
|
|
i += canSend
|
2021-05-25 22:39:10 +00:00
|
|
|
if i >= data.len:
|
|
|
|
break
|
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
proc writeControl(
|
2021-06-12 00:40:56 +00:00
|
|
|
ws: WSSession,
|
|
|
|
data: seq[byte] = @[],
|
|
|
|
opcode: Opcode,
|
|
|
|
maskKey: MaskKey) {.async.} =
|
|
|
|
## Send a frame applying the supplied
|
|
|
|
## extensions
|
|
|
|
##
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
opcode = opcode
|
|
|
|
dataSize = data.len
|
|
|
|
masked = ws.masked
|
|
|
|
|
|
|
|
if opcode in {Opcode.Text, Opcode.Cont, Opcode.Binary}:
|
|
|
|
warn "Attempting to send a control frame with an invalid opcode!"
|
|
|
|
raise newException(WSInvalidOpcodeError,
|
|
|
|
&"Attempting to send a control frame with an invalid opcode {opcode}!")
|
|
|
|
|
|
|
|
let frame = Frame(
|
|
|
|
fin: true,
|
|
|
|
rsv1: false,
|
|
|
|
rsv2: false,
|
|
|
|
rsv3: false,
|
|
|
|
opcode: opcode,
|
|
|
|
mask: ws.masked,
|
|
|
|
data: data,
|
|
|
|
maskKey: maskKey)
|
|
|
|
|
|
|
|
let encoded = await frame.encode()
|
|
|
|
await ws.stream.writer.write(encoded)
|
|
|
|
|
|
|
|
trace "Wrote control frame"
|
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
func isControl(opcode: Opcode): bool =
|
|
|
|
opcode notin {Opcode.Text, Opcode.Cont, Opcode.Binary}
|
|
|
|
|
|
|
|
proc nonCancellableSend(
|
2021-06-11 20:04:09 +00:00
|
|
|
ws: WSSession,
|
|
|
|
data: seq[byte] = @[],
|
2021-06-12 00:40:56 +00:00
|
|
|
opcode: Opcode): Future[void]
|
2022-09-06 09:09:21 +00:00
|
|
|
{.async.} =
|
2021-06-11 20:04:09 +00:00
|
|
|
## Send a frame
|
|
|
|
##
|
|
|
|
|
2021-06-12 00:40:56 +00:00
|
|
|
if ws.readyState == ReadyState.Closed:
|
|
|
|
raise newException(WSClosedError, "WebSocket is closed!")
|
|
|
|
|
|
|
|
if ws.readyState in {ReadyState.Closing} and opcode notin {Opcode.Close}:
|
|
|
|
trace "Can only respond with Close opcode to a closing connection"
|
|
|
|
return
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
opcode = opcode
|
|
|
|
dataSize = data.len
|
|
|
|
masked = ws.masked
|
|
|
|
|
|
|
|
trace "Sending data to remote"
|
|
|
|
|
2023-07-24 20:38:21 +00:00
|
|
|
let maskKey =
|
|
|
|
if ws.masked:
|
|
|
|
MaskKey.random(ws.rng[])
|
2021-06-12 00:40:56 +00:00
|
|
|
else:
|
|
|
|
default(MaskKey)
|
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
if opcode.isControl:
|
|
|
|
await ws.writeControl(data, opcode, maskKey)
|
|
|
|
else:
|
|
|
|
await ws.writeMessage(data, opcode, maskKey, ws.extensions)
|
2021-06-12 02:53:34 +00:00
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
proc doSend(
|
|
|
|
ws: WSSession,
|
|
|
|
data: seq[byte] = @[],
|
|
|
|
opcode: Opcode
|
|
|
|
): Future[void] =
|
|
|
|
let
|
|
|
|
retFut = newFuture[void]("doSend")
|
|
|
|
sendFut = ws.nonCancellableSend(data, opcode)
|
|
|
|
|
|
|
|
proc handleSend {.async.} =
|
|
|
|
try:
|
|
|
|
await sendFut
|
|
|
|
retFut.complete()
|
|
|
|
except CatchableError as exc:
|
|
|
|
retFut.fail(exc)
|
|
|
|
|
|
|
|
asyncSpawn handleSend()
|
|
|
|
retFut
|
|
|
|
|
|
|
|
proc sendLoop(ws: WSSession) {.gcsafe, async.} =
|
|
|
|
while ws.sendQueue.len > 0:
|
|
|
|
let task = ws.sendQueue.popFirst()
|
|
|
|
if task.fut.cancelled:
|
|
|
|
continue
|
|
|
|
|
|
|
|
try:
|
|
|
|
await ws.doSend(task.data, task.opcode)
|
|
|
|
task.fut.complete()
|
|
|
|
except CatchableError as exc:
|
|
|
|
task.fut.fail(exc)
|
|
|
|
|
|
|
|
proc send*(
|
|
|
|
ws: WSSession,
|
|
|
|
data: seq[byte] = @[],
|
|
|
|
opcode: Opcode): Future[void] =
|
|
|
|
if opcode.isControl:
|
|
|
|
# Control frames (see Section 5.5) MAY be injected in the middle of
|
|
|
|
# a fragmented message. Control frames themselves MUST NOT be
|
|
|
|
# fragmented.
|
|
|
|
# See RFC 6455 Section 5.4 Fragmentation
|
|
|
|
return ws.doSend(data, opcode)
|
|
|
|
|
|
|
|
let fut = newFuture[void]("send")
|
2021-06-11 20:04:09 +00:00
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
ws.sendQueue.addLast (data: data, opcode: opcode, fut: fut)
|
|
|
|
|
|
|
|
if isNil(ws.sendLoop) or ws.sendLoop.finished:
|
|
|
|
ws.sendLoop = sendLoop(ws)
|
|
|
|
|
|
|
|
fut
|
2021-06-12 00:40:56 +00:00
|
|
|
|
|
|
|
proc send*(
|
|
|
|
ws: WSSession,
|
2024-01-22 12:08:17 +00:00
|
|
|
data: string): Future[void] =
|
2021-05-25 22:39:10 +00:00
|
|
|
send(ws, data.toBytes(), Opcode.Text)
|
|
|
|
|
|
|
|
proc handleClose*(
|
|
|
|
ws: WSSession,
|
|
|
|
frame: Frame,
|
2021-12-27 10:27:21 +00:00
|
|
|
payload: seq[byte] = @[]) {.async.} =
|
2021-05-25 22:39:10 +00:00
|
|
|
## Handle close sequence
|
|
|
|
##
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
fin = frame.fin
|
|
|
|
masked = frame.mask
|
|
|
|
opcode = frame.opcode
|
|
|
|
readyState = ws.readyState
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Handling close"
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-28 12:52:18 +00:00
|
|
|
if ws.readyState != ReadyState.Open and ws.readyState != ReadyState.Closing:
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Connection isn't open, aborting close sequence!"
|
2021-05-25 22:39:10 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
var
|
2021-06-11 20:04:09 +00:00
|
|
|
code = StatusFulfilled
|
2021-05-25 22:39:10 +00:00
|
|
|
reason = ""
|
|
|
|
|
2022-07-05 17:02:05 +00:00
|
|
|
case payload.len:
|
2021-06-11 20:04:09 +00:00
|
|
|
of 0:
|
|
|
|
code = StatusNoStatus
|
|
|
|
of 1:
|
2021-05-25 22:39:10 +00:00
|
|
|
raise newException(WSPayloadLengthError,
|
|
|
|
"Invalid close frame with payload length 1!")
|
2021-06-11 20:04:09 +00:00
|
|
|
else:
|
2021-05-25 22:39:10 +00:00
|
|
|
try:
|
2021-12-27 10:27:21 +00:00
|
|
|
code = StatusCodes(uint16.fromBytesBE(payload[0..<2]))
|
2024-01-22 12:08:17 +00:00
|
|
|
except RangeDefect:
|
2021-05-25 22:39:10 +00:00
|
|
|
raise newException(WSInvalidCloseCodeError,
|
|
|
|
"Status code out of range!")
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
if code in StatusNotUsed or
|
|
|
|
code in StatusReservedProtocol:
|
|
|
|
raise newException(WSInvalidCloseCodeError,
|
|
|
|
&"Can't use reserved status code: {code}")
|
|
|
|
|
|
|
|
if code == StatusReserved or
|
|
|
|
code == StatusNoStatus or
|
|
|
|
code == StatusClosedAbnormally:
|
|
|
|
raise newException(WSInvalidCloseCodeError,
|
|
|
|
&"Can't use reserved status code: {code}")
|
|
|
|
|
|
|
|
# remaining payload bytes are reason for closing
|
2021-12-27 10:27:21 +00:00
|
|
|
reason = string.fromBytes(payload[2..payload.high])
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-05-28 16:47:24 +00:00
|
|
|
if not ws.binary and validateUTF8(reason) == false:
|
2021-06-01 02:39:14 +00:00
|
|
|
raise newException(WSInvalidUTF8,
|
|
|
|
"Invalid UTF8 sequence detected in close reason")
|
2021-05-28 16:47:24 +00:00
|
|
|
|
2021-06-25 09:22:10 +00:00
|
|
|
trace "Handling close message", code = ord(code), reason
|
2021-05-25 22:39:10 +00:00
|
|
|
if not isNil(ws.onClose):
|
|
|
|
try:
|
2021-06-11 20:04:09 +00:00
|
|
|
(code, reason) = ws.onClose(code, reason)
|
2021-05-25 22:39:10 +00:00
|
|
|
except CatchableError as exc:
|
2024-01-22 12:08:17 +00:00
|
|
|
used(exc)
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Exception in Close callback, this is most likely a bug", exc = exc.msg
|
|
|
|
else:
|
|
|
|
code = StatusFulfilled
|
|
|
|
reason = ""
|
2021-05-25 22:39:10 +00:00
|
|
|
|
|
|
|
# don't respond to a terminated connection
|
|
|
|
if ws.readyState != ReadyState.Closing:
|
|
|
|
ws.readyState = ReadyState.Closing
|
2021-06-25 09:22:10 +00:00
|
|
|
trace "Sending close", code = ord(code), reason
|
2022-11-22 09:45:38 +00:00
|
|
|
try:
|
|
|
|
await ws.send(prepareCloseBody(code, reason), Opcode.Close).wait(5.seconds)
|
|
|
|
except CatchableError as exc:
|
2024-01-22 12:08:17 +00:00
|
|
|
used(exc)
|
2022-11-22 09:45:38 +00:00
|
|
|
trace "Failed to send Close opcode", err=exc.msg
|
2021-05-25 22:39:10 +00:00
|
|
|
|
|
|
|
ws.readyState = ReadyState.Closed
|
2021-06-12 00:40:56 +00:00
|
|
|
|
|
|
|
# TODO: Under TLS, the response takes longer
|
|
|
|
# to depart and fails to write the resp code
|
|
|
|
# and cleanly close the connection. Definitely
|
|
|
|
# looks like a bug, but not sure if it's chronos
|
|
|
|
# or us?
|
|
|
|
await sleepAsync(10.millis)
|
|
|
|
await ws.stream.closeWait()
|
2021-05-25 22:39:10 +00:00
|
|
|
|
|
|
|
proc handleControl*(ws: WSSession, frame: Frame) {.async.} =
|
|
|
|
## Handle control frames
|
|
|
|
##
|
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
logScope:
|
|
|
|
fin = frame.fin
|
|
|
|
masked = frame.mask
|
|
|
|
opcode = frame.opcode
|
|
|
|
readyState = ws.readyState
|
|
|
|
len = frame.length
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Handling control frame"
|
2021-06-01 02:39:14 +00:00
|
|
|
|
2021-05-25 22:39:10 +00:00
|
|
|
if not frame.fin:
|
|
|
|
raise newException(WSFragmentedControlFrameError,
|
|
|
|
"Control frame cannot be fragmented!")
|
|
|
|
|
|
|
|
if frame.length > 125:
|
|
|
|
raise newException(WSPayloadTooLarge,
|
|
|
|
"Control message payload is greater than 125 bytes!")
|
|
|
|
|
2021-12-27 10:27:21 +00:00
|
|
|
var payload = newSeq[byte](frame.length.int)
|
2021-06-01 02:39:14 +00:00
|
|
|
if frame.length > 0:
|
2021-12-27 10:27:21 +00:00
|
|
|
payload.setLen(frame.length.int)
|
2021-06-01 02:39:14 +00:00
|
|
|
# Read control frame payload.
|
2021-12-27 10:27:21 +00:00
|
|
|
await ws.stream.reader.readExactly(addr payload[0], frame.length.int)
|
2021-06-01 02:39:14 +00:00
|
|
|
if frame.mask:
|
|
|
|
mask(
|
2021-12-27 10:27:21 +00:00
|
|
|
payload.toOpenArray(0, payload.high),
|
2021-06-01 02:39:14 +00:00
|
|
|
frame.maskKey)
|
|
|
|
|
|
|
|
# Process control frame payload.
|
|
|
|
case frame.opcode:
|
|
|
|
of Opcode.Ping:
|
|
|
|
if not isNil(ws.onPing):
|
|
|
|
try:
|
2021-12-27 10:27:21 +00:00
|
|
|
ws.onPing(payload)
|
2021-06-01 02:39:14 +00:00
|
|
|
except CatchableError as exc:
|
2024-01-22 12:08:17 +00:00
|
|
|
used(exc)
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Exception in Ping callback, this is most likely a bug", exc = exc.msg
|
2021-06-01 02:39:14 +00:00
|
|
|
|
|
|
|
# send pong to remote
|
2021-12-27 10:27:21 +00:00
|
|
|
await ws.send(payload, Opcode.Pong)
|
2021-06-01 02:39:14 +00:00
|
|
|
of Opcode.Pong:
|
|
|
|
if not isNil(ws.onPong):
|
|
|
|
try:
|
2021-12-27 10:27:21 +00:00
|
|
|
ws.onPong(payload)
|
2021-06-01 02:39:14 +00:00
|
|
|
except CatchableError as exc:
|
2024-01-22 12:08:17 +00:00
|
|
|
used(exc)
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Exception in Pong callback, this is most likely a bug", exc = exc.msg
|
2021-06-01 02:39:14 +00:00
|
|
|
of Opcode.Close:
|
2021-12-27 10:27:21 +00:00
|
|
|
await ws.handleClose(frame, payload)
|
2021-06-01 02:39:14 +00:00
|
|
|
else:
|
|
|
|
raise newException(WSInvalidOpcodeError, "Invalid control opcode!")
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2024-01-22 12:08:17 +00:00
|
|
|
{.warning[HoleEnumConv]:off.}
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
proc readFrame*(ws: WSSession, extensions: seq[Ext] = @[]): Future[Frame] {.async.} =
|
2021-05-25 22:39:10 +00:00
|
|
|
## Gets a frame from the WebSocket.
|
|
|
|
## See https://tools.ietf.org/html/rfc6455#section-5.2
|
|
|
|
##
|
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
while ws.readyState != ReadyState.Closed:
|
2021-06-01 20:24:00 +00:00
|
|
|
let frame = await Frame.decode(
|
2021-06-11 20:04:09 +00:00
|
|
|
ws.stream.reader, ws.masked, extensions)
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
opcode = frame.opcode
|
|
|
|
len = frame.length
|
|
|
|
mask = frame.mask
|
|
|
|
fin = frame.fin
|
|
|
|
|
|
|
|
trace "Decoded new frame"
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
# return the current frame if it's not one of the control frames
|
|
|
|
if frame.opcode notin {Opcode.Text, Opcode.Cont, Opcode.Binary}:
|
|
|
|
await ws.handleControl(frame) # process control frames# process control frames
|
|
|
|
continue
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
return frame
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2024-01-22 12:08:17 +00:00
|
|
|
{.warning[HoleEnumConv]:on.}
|
|
|
|
|
2021-06-12 00:40:56 +00:00
|
|
|
proc ping*(
|
|
|
|
ws: WSSession,
|
2024-01-22 12:08:17 +00:00
|
|
|
data: seq[byte] = @[]): Future[void] =
|
2021-05-25 22:39:10 +00:00
|
|
|
ws.send(data, opcode = Opcode.Ping)
|
|
|
|
|
|
|
|
proc recv*(
|
|
|
|
ws: WSSession,
|
2023-01-25 16:56:42 +00:00
|
|
|
data: pointer | ptr byte | ref seq[byte], # nim bug: pointer doesn't match ptr byte?
|
2021-05-25 22:39:10 +00:00
|
|
|
size: int): Future[int] {.async.} =
|
2021-06-11 20:04:09 +00:00
|
|
|
## Attempts to read up to ``size`` bytes
|
|
|
|
##
|
|
|
|
## If ``size`` is less than the data in
|
|
|
|
## the frame, allow reading partial frames
|
2021-05-25 22:39:10 +00:00
|
|
|
##
|
2021-06-11 20:04:09 +00:00
|
|
|
## If no data is left in the pipe await
|
|
|
|
## until at least one byte is available
|
|
|
|
##
|
|
|
|
## Otherwise, read as many frames as needed
|
|
|
|
## up to ``size`` bytes, note that we do break
|
|
|
|
## at message boundaries (``fin`` flag set).
|
|
|
|
##
|
|
|
|
## Use this to stream data from frames
|
2021-05-25 22:39:10 +00:00
|
|
|
##
|
|
|
|
|
2022-05-18 12:37:53 +00:00
|
|
|
doAssert ws.reading == false, "Only one concurrent read allowed"
|
|
|
|
ws.reading = true
|
|
|
|
defer: ws.reading = false
|
|
|
|
|
2021-05-25 22:39:10 +00:00
|
|
|
var consumed = 0
|
2023-01-25 16:56:42 +00:00
|
|
|
when data is pointer or data is ptr byte:
|
|
|
|
let pbuffer = cast[ptr UncheckedArray[byte]](data)
|
2021-05-25 22:39:10 +00:00
|
|
|
try:
|
2021-06-11 20:04:09 +00:00
|
|
|
if isNil(ws.frame):
|
|
|
|
ws.frame = await ws.readFrame(ws.extensions)
|
2021-08-04 16:23:56 +00:00
|
|
|
ws.first = true
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
while consumed < size:
|
|
|
|
if isNil(ws.frame):
|
2022-05-18 12:37:53 +00:00
|
|
|
assert ws.readyState == ReadyState.Closed
|
|
|
|
trace "Closed connection, breaking"
|
2021-05-25 22:39:10 +00:00
|
|
|
break
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
logScope:
|
2021-08-04 16:23:56 +00:00
|
|
|
first = ws.first
|
2021-06-11 20:04:09 +00:00
|
|
|
fin = ws.frame.fin
|
|
|
|
len = ws.frame.length
|
|
|
|
consumed = ws.frame.consumed
|
|
|
|
remainder = ws.frame.remainder
|
|
|
|
opcode = ws.frame.opcode
|
|
|
|
masked = ws.frame.mask
|
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
if ws.first == (ws.frame.opcode == Opcode.Cont):
|
2021-06-11 20:04:09 +00:00
|
|
|
error "Opcode mismatch!"
|
|
|
|
raise newException(WSOpcodeMismatchError,
|
2021-08-04 16:23:56 +00:00
|
|
|
&"Opcode mismatch: first: {ws.first}, opcode: {ws.frame.opcode}")
|
2021-06-11 20:04:09 +00:00
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
if ws.first:
|
2021-06-11 20:04:09 +00:00
|
|
|
ws.binary = ws.frame.opcode == Opcode.Binary # set binary flag
|
|
|
|
trace "Setting binary flag"
|
|
|
|
|
|
|
|
let len = min(ws.frame.remainder.int, size - consumed)
|
2021-06-12 02:14:53 +00:00
|
|
|
if len > 0:
|
|
|
|
trace "Reading bytes from frame stream", len
|
2023-01-25 16:56:42 +00:00
|
|
|
when data is ref seq[byte]:
|
|
|
|
data[].setLen(consumed + len)
|
|
|
|
let read = await ws.frame.read(ws.stream.reader, addr data[][consumed], len)
|
|
|
|
else:
|
|
|
|
let read = await ws.frame.read(ws.stream.reader, addr pbuffer[consumed], len)
|
2021-06-12 02:14:53 +00:00
|
|
|
if read <= 0:
|
2022-05-18 12:37:53 +00:00
|
|
|
trace "Didn't read any bytes, stopping"
|
|
|
|
raise newException(WSClosedError, "WebSocket is closed!")
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-12 02:14:53 +00:00
|
|
|
trace "Read data from frame", read
|
|
|
|
consumed += read
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
# all has been consumed from the frame
|
|
|
|
# read the next frame
|
|
|
|
if ws.frame.remainder <= 0:
|
2021-08-04 16:23:56 +00:00
|
|
|
ws.first = false
|
2021-06-11 20:04:09 +00:00
|
|
|
|
|
|
|
if ws.frame.fin: # we're at the end of the message, break
|
|
|
|
trace "Read all frames, breaking"
|
|
|
|
ws.frame = nil
|
|
|
|
break
|
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
# read next frame
|
2021-06-11 20:04:09 +00:00
|
|
|
ws.frame = await ws.readFrame(ws.extensions)
|
2021-06-01 02:39:14 +00:00
|
|
|
except CatchableError as exc:
|
2021-06-12 00:40:56 +00:00
|
|
|
trace "Exception reading frames", exc = exc.msg
|
2021-05-25 22:39:10 +00:00
|
|
|
ws.readyState = ReadyState.Closed
|
|
|
|
await ws.stream.closeWait()
|
2021-06-12 01:05:06 +00:00
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
raise exc
|
2021-06-11 20:04:09 +00:00
|
|
|
finally:
|
2021-06-12 01:05:06 +00:00
|
|
|
if not isNil(ws.frame) and
|
|
|
|
(ws.frame.fin and ws.frame.remainder <= 0):
|
|
|
|
trace "Last frame in message and no more bytes left to read, reseting current frame"
|
2021-06-11 20:04:09 +00:00
|
|
|
ws.frame = nil
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-06-12 02:53:34 +00:00
|
|
|
return consumed
|
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
proc recvMsg*(
|
2021-05-25 22:39:10 +00:00
|
|
|
ws: WSSession,
|
|
|
|
size = WSMaxMessageSize): Future[seq[byte]] {.async.} =
|
|
|
|
## Attempt to read a full message up to max `size`
|
|
|
|
## bytes in `frameSize` chunks.
|
|
|
|
##
|
2021-08-04 16:23:56 +00:00
|
|
|
## If no `fin` flag arrives await until cancelled or
|
|
|
|
## closed.
|
2021-05-25 22:39:10 +00:00
|
|
|
##
|
|
|
|
## If message is larger than `size` a `WSMaxMessageSizeError`
|
|
|
|
## exception is thrown.
|
|
|
|
##
|
|
|
|
## In all other cases it awaits a full message.
|
|
|
|
##
|
2021-08-04 16:23:56 +00:00
|
|
|
try:
|
|
|
|
var res: seq[byte]
|
|
|
|
while ws.readyState != ReadyState.Closed:
|
2023-01-25 16:56:42 +00:00
|
|
|
var buf = new(seq[byte])
|
2024-01-22 12:08:17 +00:00
|
|
|
let read {.used.} = await ws.recv(buf, min(size, ws.frameSize))
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2023-01-25 16:56:42 +00:00
|
|
|
if res.len + buf[].len > size:
|
2021-08-04 16:23:56 +00:00
|
|
|
raise newException(WSMaxMessageSizeError, "Max message size exceeded")
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
trace "Read message", size = read
|
2023-01-25 16:56:42 +00:00
|
|
|
res.add(buf[])
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
# no more frames
|
|
|
|
if isNil(ws.frame):
|
|
|
|
break
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
# read the entire message, exit
|
|
|
|
if ws.frame.fin and ws.frame.remainder <= 0:
|
|
|
|
trace "Read full message, breaking!"
|
|
|
|
break
|
|
|
|
|
2022-09-06 09:09:21 +00:00
|
|
|
if ws.readyState == ReadyState.Closed:
|
|
|
|
# avoid reporting incomplete message
|
|
|
|
raise newException(WSClosedError, "WebSocket is closed!")
|
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
if not ws.binary and validateUTF8(res.toOpenArray(0, res.high)) == false:
|
|
|
|
raise newException(WSInvalidUTF8, "Invalid UTF8 sequence detected")
|
|
|
|
|
|
|
|
return res
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Exception reading message", exc = exc.msg
|
|
|
|
ws.readyState = ReadyState.Closed
|
|
|
|
await ws.stream.closeWait()
|
|
|
|
|
|
|
|
raise exc
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
proc recv*(
|
|
|
|
ws: WSSession,
|
|
|
|
size = WSMaxMessageSize): Future[seq[byte]]
|
|
|
|
{.deprecated: "deprecated in favor of recvMsg()".} =
|
|
|
|
ws.recvMsg(size)
|
2021-05-25 22:39:10 +00:00
|
|
|
|
|
|
|
proc close*(
|
|
|
|
ws: WSSession,
|
2021-06-11 20:04:09 +00:00
|
|
|
code = StatusFulfilled,
|
2021-05-25 22:39:10 +00:00
|
|
|
reason: string = "") {.async.} =
|
|
|
|
## Close the Socket, sends close packet.
|
|
|
|
##
|
|
|
|
|
|
|
|
if ws.readyState != ReadyState.Open:
|
|
|
|
return
|
|
|
|
|
2022-11-22 09:45:38 +00:00
|
|
|
proc gentleCloser(ws: WSSession, closeBody: seq[byte]) {.async.} =
|
2021-05-25 22:39:10 +00:00
|
|
|
await ws.send(
|
2022-11-22 09:45:38 +00:00
|
|
|
closeBody,
|
2021-05-25 22:39:10 +00:00
|
|
|
opcode = Opcode.Close)
|
|
|
|
|
|
|
|
# read frames until closed
|
2022-05-25 14:02:46 +00:00
|
|
|
try:
|
|
|
|
while ws.readyState != ReadyState.Closed:
|
|
|
|
discard await ws.readFrame()
|
2023-06-06 20:57:40 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2022-05-25 14:02:46 +00:00
|
|
|
except CatchableError as exc:
|
2024-01-22 12:08:17 +00:00
|
|
|
discard exc # most likely EOF
|
2022-11-22 09:45:38 +00:00
|
|
|
try:
|
|
|
|
ws.readyState = ReadyState.Closing
|
|
|
|
await gentleCloser(ws, prepareCloseBody(code, reason)).wait(10.seconds)
|
2023-06-06 20:57:40 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
trace "Cancellation when closing!", exc = exc.msg
|
|
|
|
raise exc
|
2021-05-25 22:39:10 +00:00
|
|
|
except CatchableError as exc:
|
2024-01-22 12:08:17 +00:00
|
|
|
used(exc)
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Exception closing", exc = exc.msg
|
2022-11-22 09:45:38 +00:00
|
|
|
finally:
|
|
|
|
await ws.stream.closeWait()
|
|
|
|
ws.readyState = ReadyState.Closed
|