2021-06-27 06:35:36 +00:00
|
|
|
## nim-websock
|
2022-07-21 15:38:13 +00:00
|
|
|
## Copyright (c) 2021-2022 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.
|
|
|
|
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
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]
|
2021-06-11 20:04:09 +00:00
|
|
|
import ./types, ./frame, ./utils, ./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
|
|
|
|
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
|
|
|
|
|
2021-06-12 00:40:56 +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
|
|
|
|
while ws.readyState notin {ReadyState.Closing}:
|
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
|
|
|
|
|
2021-06-12 00:40:56 +00:00
|
|
|
proc writeControl*(
|
|
|
|
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"
|
|
|
|
|
2021-06-11 20:04:09 +00:00
|
|
|
proc send*(
|
|
|
|
ws: WSSession,
|
|
|
|
data: seq[byte] = @[],
|
2021-06-12 00:40:56 +00:00
|
|
|
opcode: Opcode): Future[void]
|
2021-06-12 02:53:34 +00:00
|
|
|
{.async, raises: [Defect, WSClosedError].} =
|
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"
|
|
|
|
|
|
|
|
let maskKey = if ws.masked:
|
|
|
|
genMaskKey(ws.rng)
|
|
|
|
else:
|
|
|
|
default(MaskKey)
|
|
|
|
|
|
|
|
if opcode in {Opcode.Text, Opcode.Cont, Opcode.Binary}:
|
2021-06-12 02:53:34 +00:00
|
|
|
await ws.writeMessage(
|
|
|
|
data, opcode, maskKey, ws.extensions)
|
|
|
|
|
|
|
|
return
|
2021-06-11 20:04:09 +00:00
|
|
|
|
2021-06-12 02:53:34 +00:00
|
|
|
await ws.writeControl(data, opcode, maskKey)
|
2021-06-12 00:40:56 +00:00
|
|
|
|
|
|
|
proc send*(
|
|
|
|
ws: WSSession,
|
|
|
|
data: string): Future[void]
|
|
|
|
{.raises: [Defect, WSClosedError].} =
|
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]))
|
2021-05-25 22:39:10 +00:00
|
|
|
except RangeError:
|
|
|
|
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:
|
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
|
2021-06-11 20:04:09 +00:00
|
|
|
await ws.send(prepareCloseBody(code, reason), Opcode.Close)
|
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:
|
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:
|
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
|
|
|
|
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
|
|
|
|
2021-06-12 00:40:56 +00:00
|
|
|
proc ping*(
|
|
|
|
ws: WSSession,
|
|
|
|
data: seq[byte] = @[]): Future[void]
|
|
|
|
{.raises: [Defect, WSClosedError].} =
|
2021-05-25 22:39:10 +00:00
|
|
|
ws.send(data, opcode = Opcode.Ping)
|
|
|
|
|
|
|
|
proc recv*(
|
|
|
|
ws: WSSession,
|
|
|
|
data: pointer,
|
|
|
|
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
|
|
|
|
var pbuffer = cast[ptr UncheckedArray[byte]](data)
|
|
|
|
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
|
2021-06-14 19:41:31 +00:00
|
|
|
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:
|
|
|
|
var buf = newSeq[byte](min(size, ws.frameSize))
|
|
|
|
let read = await ws.recv(addr buf[0], buf.len)
|
2021-05-25 22:39:10 +00:00
|
|
|
|
2021-08-04 16:23:56 +00:00
|
|
|
buf.setLen(read)
|
|
|
|
if res.len + buf.len > size:
|
|
|
|
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
|
|
|
|
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
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
try:
|
|
|
|
ws.readyState = ReadyState.Closing
|
|
|
|
await ws.send(
|
|
|
|
prepareCloseBody(code, reason),
|
|
|
|
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()
|
|
|
|
except CatchableError as exc:
|
|
|
|
ws.readyState = ReadyState.Closed
|
|
|
|
await ws.stream.closeWait()
|
2021-05-25 22:39:10 +00:00
|
|
|
except CatchableError as exc:
|
2021-06-11 20:04:09 +00:00
|
|
|
trace "Exception closing", exc = exc.msg
|