2021-05-24 18:47:27 -06:00
|
|
|
## Nim-Libp2p
|
|
|
|
## Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
## 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.
|
|
|
|
|
|
|
|
|
2021-04-14 03:35:58 +05:30
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
import std/[tables,
|
|
|
|
strutils,
|
|
|
|
uri,
|
|
|
|
parseutils]
|
|
|
|
|
|
|
|
import pkg/[chronos,
|
2021-04-06 02:31:10 +05:30
|
|
|
chronos/apps/http/httptable,
|
|
|
|
chronos/apps/http/httpserver,
|
|
|
|
chronos/streams/asyncstream,
|
2021-04-14 03:35:58 +05:30
|
|
|
chronos/streams/tlsstream,
|
2021-03-18 09:30:21 -06:00
|
|
|
chronicles,
|
|
|
|
httputils,
|
|
|
|
stew/byteutils,
|
|
|
|
stew/endians2,
|
|
|
|
stew/base64,
|
2021-04-06 02:31:10 +05:30
|
|
|
stew/base10,
|
|
|
|
nimcrypto/sha]
|
2021-03-18 09:30:21 -06:00
|
|
|
|
2021-05-24 18:47:27 -06:00
|
|
|
import ./utils, ./stream, ./frame, ./errors
|
2021-03-11 09:04:14 +05:30
|
|
|
|
|
|
|
const
|
2021-03-18 09:30:21 -06:00
|
|
|
SHA1DigestSize* = 20
|
|
|
|
WSHeaderSize* = 12
|
|
|
|
WSDefaultVersion* = 13
|
|
|
|
WSDefaultFrameSize* = 1 shl 20 # 1mb
|
2021-04-14 16:37:38 +05:30
|
|
|
WSMaxMessageSize* = 20 shl 20 # 20mb
|
2021-03-18 09:30:21 -06:00
|
|
|
WSGuid* = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
2021-04-06 02:31:10 +05:30
|
|
|
CRLF* = "\r\n"
|
2021-03-11 09:04:14 +05:30
|
|
|
|
|
|
|
type
|
2021-03-18 09:30:21 -06:00
|
|
|
ReadyState* {.pure.} = enum
|
2021-03-11 09:04:14 +05:30
|
|
|
Connecting = 0 # The connection is not yet open.
|
|
|
|
Open = 1 # The connection is open and ready to communicate.
|
|
|
|
Closing = 2 # The connection is in the process of closing.
|
|
|
|
Closed = 3 # The connection is closed or couldn't be opened.
|
|
|
|
|
|
|
|
HttpCode* = enum
|
|
|
|
Http101 = 101 # Switching Protocols
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
Status* {.pure.} = enum
|
|
|
|
# 0-999 not used
|
|
|
|
Fulfilled = 1000
|
|
|
|
GoingAway = 1001
|
|
|
|
ProtocolError = 1002
|
|
|
|
CannotAccept = 1003
|
|
|
|
# 1004 reserved
|
|
|
|
NoStatus = 1005 # use by clients
|
|
|
|
ClosedAbnormally = 1006 # use by clients
|
|
|
|
Inconsistent = 1007
|
|
|
|
PolicyError = 1008
|
|
|
|
TooLarge = 1009
|
|
|
|
NoExtensions = 1010
|
|
|
|
UnexpectedError = 1011
|
2021-04-14 16:37:38 +05:30
|
|
|
ReservedCode = 3999 # use by clients
|
|
|
|
# 3000-3999 reserved for libs
|
|
|
|
# 4000-4999 reserved for applications
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-05-24 18:47:27 -06:00
|
|
|
ControlCb* = proc(data: openArray[byte] = [])
|
|
|
|
{.gcsafe, raises: [Defect].}
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
CloseResult* = tuple
|
|
|
|
code: Status
|
|
|
|
reason: string
|
|
|
|
|
|
|
|
CloseCb* = proc(code: Status, reason: string):
|
2021-04-14 03:35:58 +05:30
|
|
|
CloseResult {.gcsafe, raises: [Defect].}
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
WebSocket* = ref object
|
2021-04-06 02:31:10 +05:30
|
|
|
stream*: AsyncStream
|
|
|
|
version*: uint
|
2021-03-18 09:30:21 -06:00
|
|
|
key*: string
|
|
|
|
protocol*: string
|
|
|
|
readyState*: ReadyState
|
|
|
|
masked*: bool # send masked packets
|
2021-05-22 03:04:40 -06:00
|
|
|
binary*: bool # is payload binary?
|
2021-03-18 09:30:21 -06:00
|
|
|
rng*: ref BrHmacDrbgContext
|
|
|
|
frameSize: int
|
|
|
|
frame: Frame
|
|
|
|
onPing: ControlCb
|
|
|
|
onPong: ControlCb
|
|
|
|
onClose: CloseCb
|
|
|
|
|
|
|
|
template remainder*(frame: Frame): uint64 =
|
|
|
|
frame.length - frame.consumed
|
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
proc `$`(ht: HttpTables): string =
|
|
|
|
## Returns string representation of HttpTable/Ref.
|
|
|
|
var res = ""
|
2021-04-14 16:37:38 +05:30
|
|
|
for key, value in ht.stringItems(true):
|
|
|
|
res.add(key.normalizeHeaderName())
|
|
|
|
res.add(": ")
|
|
|
|
res.add(value)
|
|
|
|
res.add(CRLF)
|
2021-04-06 02:31:10 +05:30
|
|
|
|
|
|
|
## add for end of header mark
|
|
|
|
res.add(CRLF)
|
|
|
|
res
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
proc prepareCloseBody(code: Status, reason: string): seq[byte] =
|
|
|
|
result = reason.toBytes
|
|
|
|
if ord(code) > 999:
|
|
|
|
result = @(ord(code).uint16.toBytesBE()) & result
|
|
|
|
|
|
|
|
proc handshake*(
|
|
|
|
ws: WebSocket,
|
2021-04-06 02:31:10 +05:30
|
|
|
request: HttpRequestRef,
|
|
|
|
version: uint = WSDefaultVersion) {.async.} =
|
2021-03-11 09:04:14 +05:30
|
|
|
## Handles the websocket handshake.
|
2021-03-18 09:30:21 -06:00
|
|
|
##
|
2021-04-06 02:31:10 +05:30
|
|
|
let
|
|
|
|
reqHeaders = request.headers
|
|
|
|
|
|
|
|
ws.version = Base10.decode(
|
|
|
|
uint,
|
|
|
|
reqHeaders.getString("Sec-WebSocket-Version"))
|
|
|
|
.tryGet() # this method throws
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
if ws.version != version:
|
|
|
|
raise newException(WSVersionError,
|
|
|
|
"Websocket version not supported, Version: " &
|
2021-04-06 02:31:10 +05:30
|
|
|
reqHeaders.getString("Sec-WebSocket-Version"))
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
ws.key = reqHeaders.getString("Sec-WebSocket-Key").strip()
|
|
|
|
if reqHeaders.contains("Sec-WebSocket-Protocol"):
|
|
|
|
let wantProtocol = reqHeaders.getString("Sec-WebSocket-Protocol").strip()
|
2021-03-11 09:04:14 +05:30
|
|
|
if ws.protocol != wantProtocol:
|
2021-03-18 09:30:21 -06:00
|
|
|
raise newException(WSProtoMismatchError,
|
2021-03-11 09:04:14 +05:30
|
|
|
"Protocol mismatch (expected: " & ws.protocol & ", got: " &
|
|
|
|
wantProtocol & ")")
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
let cKey = ws.key & WSGuid
|
2021-05-22 02:26:45 -06:00
|
|
|
let acceptKey = Base64Pad.encode(
|
|
|
|
sha1.digest(cKey.toOpenArray(0, cKey.high)).data)
|
|
|
|
|
2021-04-14 03:35:58 +05:30
|
|
|
var headerData = [
|
|
|
|
("Connection", "Upgrade"),
|
2021-04-14 16:37:38 +05:30
|
|
|
("Upgrade", "webSocket"),
|
2021-04-14 03:35:58 +05:30
|
|
|
("Sec-WebSocket-Accept", acceptKey)]
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
var headers = HttpTable.init(headerData)
|
2021-03-11 09:04:14 +05:30
|
|
|
if ws.protocol != "":
|
2021-04-06 02:31:10 +05:30
|
|
|
headers.add("Sec-WebSocket-Protocol", ws.protocol)
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
try:
|
|
|
|
discard await request.respond(httputils.Http101, "", headers)
|
|
|
|
except CatchableError as exc:
|
2021-04-14 16:37:38 +05:30
|
|
|
raise newException(WSHandshakeError,
|
|
|
|
"Failed to sent handshake response. Error: " & exc.msg)
|
2021-05-22 02:26:45 -06:00
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
ws.readyState = ReadyState.Open
|
|
|
|
|
|
|
|
proc createServer*(
|
2021-05-24 18:47:27 -06:00
|
|
|
_: typedesc[WebSocket],
|
2021-04-06 02:31:10 +05:30
|
|
|
request: HttpRequestRef,
|
2021-03-18 09:30:21 -06:00
|
|
|
protocol: string = "",
|
|
|
|
frameSize = WSDefaultFrameSize,
|
|
|
|
onPing: ControlCb = nil,
|
|
|
|
onPong: ControlCb = nil,
|
|
|
|
onClose: CloseCb = nil): Future[WebSocket] {.async.} =
|
2021-03-11 09:04:14 +05:30
|
|
|
## Creates a new socket from a request.
|
2021-03-18 09:30:21 -06:00
|
|
|
##
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
if not request.headers.contains("Sec-WebSocket-Version"):
|
2021-03-18 09:30:21 -06:00
|
|
|
raise newException(WSHandshakeError, "Missing version header")
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
let wsStream = AsyncStream(
|
|
|
|
reader: request.connection.reader,
|
|
|
|
writer: request.connection.writer)
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
var ws = WebSocket(
|
2021-04-06 02:31:10 +05:30
|
|
|
stream: wsStream,
|
2021-03-18 09:30:21 -06:00
|
|
|
protocol: protocol,
|
|
|
|
masked: false,
|
|
|
|
rng: newRng(),
|
|
|
|
frameSize: frameSize,
|
|
|
|
onPing: onPing,
|
|
|
|
onPong: onPong,
|
|
|
|
onClose: onClose)
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
await ws.handshake(request)
|
2021-03-18 09:30:21 -06:00
|
|
|
return ws
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
proc send*(
|
|
|
|
ws: WebSocket,
|
|
|
|
data: seq[byte] = @[],
|
2021-05-22 02:26:45 -06:00
|
|
|
opcode: Opcode) {.async.} =
|
2021-03-18 09:30:21 -06:00
|
|
|
## Send a frame
|
|
|
|
##
|
|
|
|
|
|
|
|
if ws.readyState == ReadyState.Closed:
|
|
|
|
raise newException(WSClosedError, "Socket is closed!")
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
opcode = opcode
|
|
|
|
dataSize = data.len
|
2021-05-22 02:26:45 -06:00
|
|
|
masked = ws.masked
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
debug "Sending data to remote"
|
|
|
|
|
|
|
|
var maskKey: array[4, char]
|
|
|
|
if ws.masked:
|
|
|
|
maskKey = genMaskKey(ws.rng)
|
|
|
|
|
|
|
|
if opcode notin {Opcode.Text, Opcode.Cont, Opcode.Binary}:
|
2021-05-24 18:47:27 -06:00
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
if ws.readyState in {ReadyState.Closing} and opcode notin {Opcode.Close}:
|
|
|
|
return
|
2021-05-22 02:26:45 -06:00
|
|
|
|
|
|
|
await ws.stream.writer.write(
|
2021-05-24 18:47:27 -06:00
|
|
|
Frame(
|
|
|
|
fin: true,
|
|
|
|
rsv1: false,
|
|
|
|
rsv2: false,
|
|
|
|
rsv3: false,
|
|
|
|
opcode: opcode,
|
|
|
|
mask: ws.masked,
|
|
|
|
data: data, # allow sending data with close messages
|
|
|
|
maskKey: maskKey)
|
|
|
|
.encode())
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
return
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
let maxSize = ws.frameSize
|
|
|
|
var i = 0
|
2021-04-14 16:37:38 +05:30
|
|
|
while ws.readyState notin {ReadyState.Closing}:
|
2021-03-18 09:30:21 -06:00
|
|
|
let len = min(data.len, (maxSize + i))
|
2021-05-22 02:26:45 -06:00
|
|
|
await ws.stream.writer.write(
|
2021-05-24 18:47:27 -06:00
|
|
|
Frame(
|
2021-05-22 02:26:45 -06:00
|
|
|
fin: if (i + len >= data.len): true else: false,
|
|
|
|
rsv1: false,
|
|
|
|
rsv2: false,
|
|
|
|
rsv3: false,
|
|
|
|
opcode: if i > 0: Opcode.Cont else: opcode, # fragments have to be `Continuation` frames
|
|
|
|
mask: ws.masked,
|
|
|
|
data: data[i ..< len],
|
2021-05-24 18:47:27 -06:00
|
|
|
maskKey: maskKey)
|
|
|
|
.encode())
|
2021-04-14 16:37:38 +05:30
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
i += len
|
2021-04-14 16:37:38 +05:30
|
|
|
if i >= data.len:
|
|
|
|
break
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
proc send*(ws: WebSocket, data: string): Future[void] =
|
|
|
|
send(ws, toBytes(data), Opcode.Text)
|
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
proc handleClose*(ws: WebSocket, frame: Frame, payLoad: seq[byte] = @[]) {.async.} =
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
logScope:
|
|
|
|
fin = frame.fin
|
|
|
|
masked = frame.mask
|
|
|
|
opcode = frame.opcode
|
|
|
|
serverState = ws.readyState
|
|
|
|
|
|
|
|
debug "Handling close sequence"
|
2021-05-22 02:26:45 -06:00
|
|
|
|
|
|
|
if ws.readyState notin {ReadyState.Open}:
|
|
|
|
return
|
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
var
|
|
|
|
code = Status.Fulfilled
|
|
|
|
reason = ""
|
|
|
|
|
|
|
|
if payLoad.len == 1:
|
2021-05-22 02:26:45 -06:00
|
|
|
raise newException(WSPayloadLengthError,
|
|
|
|
"Invalid close frame with payload length 1!")
|
2021-04-14 16:37:38 +05:30
|
|
|
|
2021-05-22 02:26:45 -06:00
|
|
|
if payLoad.len > 1:
|
2021-04-14 16:37:38 +05:30
|
|
|
# first two bytes are the status
|
|
|
|
let ccode = uint16.fromBytesBE(payLoad[0..<2])
|
|
|
|
if ccode <= 999 or ccode > 1015:
|
2021-05-22 02:26:45 -06:00
|
|
|
raise newException(WSInvalidCloseCodeError,
|
|
|
|
"Invalid code in close message!")
|
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
try:
|
2021-03-18 09:30:21 -06:00
|
|
|
code = Status(ccode)
|
2021-04-14 16:37:38 +05:30
|
|
|
except RangeError:
|
2021-05-22 02:26:45 -06:00
|
|
|
raise newException(WSInvalidCloseCodeError,
|
|
|
|
"Status code out of range!")
|
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
# remining payload bytes are reason for closing
|
|
|
|
reason = string.fromBytes(payLoad[2..payLoad.high])
|
|
|
|
|
|
|
|
var rcode: Status
|
|
|
|
if code in {Status.Fulfilled}:
|
|
|
|
rcode = Status.Fulfilled
|
|
|
|
|
|
|
|
if not isNil(ws.onClose):
|
|
|
|
try:
|
|
|
|
(rcode, reason) = ws.onClose(code, reason)
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception in Close callback, this is most likely a bug", exc = exc.msg
|
|
|
|
|
|
|
|
# don't respond to a terminated connection
|
|
|
|
if ws.readyState != ReadyState.Closing:
|
|
|
|
ws.readyState = ReadyState.Closing
|
|
|
|
await ws.send(prepareCloseBody(rcode, reason), Opcode.Close)
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
ws.readyState = ReadyState.Closed
|
2021-04-14 16:37:38 +05:30
|
|
|
await ws.stream.closeWait()
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-05-22 02:26:45 -06:00
|
|
|
proc handleControl*(ws: WebSocket, frame: Frame) {.async.} =
|
2021-03-18 09:30:21 -06:00
|
|
|
## handle control frames
|
|
|
|
##
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-05-22 02:26:45 -06: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-03-18 09:30:21 -06:00
|
|
|
try:
|
2021-05-22 02:26:45 -06:00
|
|
|
var payLoad = newSeq[byte](frame.length.int)
|
|
|
|
if frame.length > 0:
|
|
|
|
payLoad.setLen(frame.length.int)
|
|
|
|
# Read control frame payload.
|
|
|
|
await ws.stream.reader.readExactly(addr payLoad[0], frame.length.int)
|
|
|
|
if frame.mask:
|
|
|
|
mask(
|
|
|
|
payLoad.toOpenArray(0, payLoad.high),
|
|
|
|
frame.maskKey)
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
# Process control frame payload.
|
|
|
|
case frame.opcode:
|
|
|
|
of Opcode.Ping:
|
|
|
|
if not isNil(ws.onPing):
|
|
|
|
try:
|
2021-05-22 02:26:45 -06:00
|
|
|
ws.onPing(payLoad)
|
2021-03-18 09:30:21 -06:00
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception in Ping callback, this is most likelly a bug", exc = exc.msg
|
|
|
|
|
|
|
|
# send pong to remote
|
2021-04-14 16:37:38 +05:30
|
|
|
await ws.send(payLoad, Opcode.Pong)
|
2021-03-18 09:30:21 -06:00
|
|
|
of Opcode.Pong:
|
|
|
|
if not isNil(ws.onPong):
|
|
|
|
try:
|
2021-05-22 02:26:45 -06:00
|
|
|
ws.onPong(payLoad)
|
2021-03-18 09:30:21 -06:00
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception in Pong callback, this is most likelly a bug", exc = exc.msg
|
|
|
|
of Opcode.Close:
|
2021-04-14 16:37:38 +05:30
|
|
|
await ws.handleClose(frame, payLoad)
|
2021-03-18 09:30:21 -06:00
|
|
|
else:
|
2021-04-14 16:37:38 +05:30
|
|
|
raise newException(WSInvalidOpcodeError, "Invalid control opcode!")
|
|
|
|
except WebSocketError as exc:
|
|
|
|
debug "Handled websocket exception", exc = exc.msg
|
|
|
|
raise exc
|
2021-03-18 09:30:21 -06:00
|
|
|
except CatchableError as exc:
|
2021-04-06 02:31:10 +05:30
|
|
|
trace "Exception handling control messages", exc = exc.msg
|
2021-03-18 09:30:21 -06:00
|
|
|
ws.readyState = ReadyState.Closed
|
2021-04-06 02:31:10 +05:30
|
|
|
await ws.stream.closeWait()
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
proc readFrame*(ws: WebSocket): Future[Frame] {.async.} =
|
|
|
|
## Gets a frame from the WebSocket.
|
|
|
|
## See https://tools.ietf.org/html/rfc6455#section-5.2
|
|
|
|
##
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
try:
|
2021-04-14 03:35:58 +05:30
|
|
|
while ws.readyState != ReadyState.Closed:
|
2021-05-24 18:47:27 -06:00
|
|
|
let frame = await Frame.decode(ws.stream.reader, ws.masked)
|
2021-05-22 02:26:45 -06:00
|
|
|
debug "Decoded new frame", opcode = frame.opcode, len = frame.length, mask = frame.mask
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
# return the current frame if it's not one of the control frames
|
|
|
|
if frame.opcode notin {Opcode.Text, Opcode.Cont, Opcode.Binary}:
|
2021-05-22 02:26:45 -06:00
|
|
|
await ws.handleControl(frame) # process control frames# process control frames
|
2021-03-18 09:30:21 -06:00
|
|
|
continue
|
|
|
|
|
|
|
|
return frame
|
2021-04-14 16:37:38 +05:30
|
|
|
except WebSocketError as exc:
|
2021-05-22 02:26:45 -06:00
|
|
|
trace "Websocket error", exc = exc.msg
|
2021-04-14 16:37:38 +05:30
|
|
|
raise exc
|
2021-03-18 09:30:21 -06:00
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception reading frame, dropping socket", exc = exc.msg
|
|
|
|
ws.readyState = ReadyState.Closed
|
2021-04-06 02:31:10 +05:30
|
|
|
await ws.stream.closeWait()
|
2021-03-18 09:30:21 -06:00
|
|
|
raise exc
|
|
|
|
|
2021-05-22 02:26:45 -06:00
|
|
|
proc ping*(ws: WebSocket, data: seq[byte] = @[]): Future[void] =
|
|
|
|
ws.send(data, opcode = Opcode.Ping)
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
proc recv*(
|
|
|
|
ws: WebSocket,
|
|
|
|
data: pointer,
|
2021-05-22 03:04:40 -06:00
|
|
|
size: int): Future[int] {.async.} =
|
2021-03-18 09:30:21 -06:00
|
|
|
## Attempts to read up to `size` bytes
|
|
|
|
##
|
2021-04-14 03:35:58 +05:30
|
|
|
## Will read as many frames as necessary
|
2021-03-18 09:30:21 -06:00
|
|
|
## to fill the buffer until either
|
|
|
|
## the message ends (frame.fin) or
|
|
|
|
## the buffer is full. If no data is on
|
|
|
|
## the pipe will await until at least
|
|
|
|
## one byte is available
|
|
|
|
##
|
|
|
|
|
2021-05-22 03:04:40 -06:00
|
|
|
var consumed = 0
|
|
|
|
var pbuffer = cast[ptr UncheckedArray[byte]](data)
|
2021-03-18 09:30:21 -06:00
|
|
|
try:
|
|
|
|
while consumed < size:
|
|
|
|
# we might have to read more than
|
|
|
|
# one frame to fill the buffer
|
|
|
|
|
2021-05-24 18:47:27 -06:00
|
|
|
# TODO: Figure out a cleaner way to handle
|
|
|
|
# retrieving new frames
|
|
|
|
if isNil(ws.frame):
|
|
|
|
ws.frame = await ws.readFrame()
|
|
|
|
|
|
|
|
if isNil(ws.frame):
|
|
|
|
return consumed
|
|
|
|
|
|
|
|
if ws.frame.opcode == Opcode.Cont:
|
|
|
|
raise newException(WSOpcodeMismatchError,
|
|
|
|
"Expected Text or Binary frame")
|
|
|
|
elif (not ws.frame.fin and ws.frame.remainder() <= 0):
|
2021-03-18 09:30:21 -06:00
|
|
|
ws.frame = await ws.readFrame()
|
2021-04-14 16:37:38 +05:30
|
|
|
# This could happen if the connection is closed.
|
2021-05-24 18:47:27 -06:00
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
if isNil(ws.frame):
|
2021-05-22 02:26:45 -06:00
|
|
|
return consumed
|
2021-04-14 16:37:38 +05:30
|
|
|
|
|
|
|
if ws.frame.opcode != Opcode.Cont:
|
2021-05-22 02:26:45 -06:00
|
|
|
raise newException(WSOpcodeMismatchError,
|
2021-05-24 18:47:27 -06:00
|
|
|
"Expected Continuation frame")
|
2021-05-22 02:26:45 -06:00
|
|
|
|
2021-05-24 18:47:27 -06:00
|
|
|
ws.binary = ws.frame.opcode == Opcode.Binary # set binary flag
|
|
|
|
if ws.frame.fin and ws.frame.remainder() <= 0:
|
2021-04-14 16:37:38 +05:30
|
|
|
ws.frame = nil
|
|
|
|
break
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
let len = min(ws.frame.remainder().int, size - consumed)
|
2021-04-14 16:37:38 +05:30
|
|
|
if len == 0:
|
|
|
|
continue
|
2021-05-22 02:26:45 -06:00
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
let read = await ws.stream.reader.readOnce(addr pbuffer[consumed], len)
|
2021-03-18 09:30:21 -06:00
|
|
|
if read <= 0:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if ws.frame.mask:
|
|
|
|
# unmask data using offset
|
2021-05-22 02:26:45 -06:00
|
|
|
mask(
|
2021-03-18 09:30:21 -06:00
|
|
|
pbuffer.toOpenArray(consumed, (consumed + read) - 1),
|
|
|
|
ws.frame.maskKey,
|
2021-04-14 16:37:38 +05:30
|
|
|
ws.frame.consumed.int)
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
consumed += read
|
|
|
|
ws.frame.consumed += read.uint64
|
|
|
|
|
2021-05-22 03:04:40 -06:00
|
|
|
return consumed.int
|
2021-04-14 16:37:38 +05:30
|
|
|
|
|
|
|
except WebSocketError as exc:
|
|
|
|
debug "Websocket error", exc = exc.msg
|
|
|
|
ws.readyState = ReadyState.Closed
|
|
|
|
await ws.stream.closeWait()
|
|
|
|
raise exc
|
2021-03-18 09:30:21 -06:00
|
|
|
except CancelledError as exc:
|
|
|
|
debug "Cancelling reading", exc = exc.msg
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception reading frames", exc = exc.msg
|
|
|
|
|
|
|
|
proc recv*(
|
|
|
|
ws: WebSocket,
|
2021-05-22 03:04:40 -06:00
|
|
|
size = WSMaxMessageSize): Future[seq[byte]] {.async.} =
|
2021-03-18 09:30:21 -06:00
|
|
|
## Attempt to read a full message up to max `size`
|
|
|
|
## bytes in `frameSize` chunks.
|
|
|
|
##
|
2021-04-06 02:31:10 +05:30
|
|
|
## If no `fin` flag arrives await until either
|
|
|
|
## cancelled or the `fin` flag arrives.
|
2021-03-18 09:30:21 -06:00
|
|
|
##
|
|
|
|
## If message is larger than `size` a `WSMaxMessageSizeError`
|
|
|
|
## exception is thrown.
|
|
|
|
##
|
|
|
|
## In all other cases it awaits a full message.
|
|
|
|
##
|
2021-05-22 03:04:40 -06:00
|
|
|
var res: seq[byte]
|
2021-03-18 09:30:21 -06:00
|
|
|
try:
|
|
|
|
while ws.readyState != ReadyState.Closed:
|
2021-05-22 03:04:40 -06:00
|
|
|
var buf = newSeq[byte](ws.frameSize)
|
|
|
|
let read = await ws.recv(addr buf[0], buf.len)
|
2021-03-18 09:30:21 -06:00
|
|
|
if read <= 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
buf.setLen(read)
|
|
|
|
if res.len + buf.len > size:
|
|
|
|
raise newException(WSMaxMessageSizeError, "Max message size exceeded")
|
|
|
|
|
|
|
|
res.add(buf)
|
|
|
|
|
|
|
|
# no more frames
|
|
|
|
if isNil(ws.frame):
|
|
|
|
break
|
|
|
|
|
|
|
|
# read the entire message, exit
|
|
|
|
if ws.frame.fin and ws.frame.remainder().int <= 0:
|
|
|
|
break
|
2021-04-14 16:37:38 +05:30
|
|
|
except WebSocketError as exc:
|
|
|
|
debug "Websocket error", exc = exc.msg
|
2021-03-18 09:30:21 -06:00
|
|
|
raise exc
|
|
|
|
except CancelledError as exc:
|
|
|
|
debug "Cancelling reading", exc = exc.msg
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception reading frames", exc = exc.msg
|
|
|
|
|
2021-05-22 03:04:40 -06:00
|
|
|
return res
|
2021-03-18 09:30:21 -06:00
|
|
|
|
|
|
|
proc close*(
|
|
|
|
ws: WebSocket,
|
|
|
|
code: Status = Status.Fulfilled,
|
|
|
|
reason: string = "") {.async.} =
|
2021-03-11 09:04:14 +05:30
|
|
|
## Close the Socket, sends close packet.
|
2021-03-18 09:30:21 -06:00
|
|
|
##
|
|
|
|
|
|
|
|
if ws.readyState != ReadyState.Open:
|
2021-03-11 09:04:14 +05:30
|
|
|
return
|
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
try:
|
|
|
|
ws.readyState = ReadyState.Closing
|
|
|
|
await ws.send(
|
|
|
|
prepareCloseBody(code, reason),
|
|
|
|
opcode = Opcode.Close)
|
|
|
|
|
|
|
|
# read frames until closed
|
|
|
|
while ws.readyState != ReadyState.Closed:
|
|
|
|
discard await ws.recv()
|
|
|
|
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception closing", exc = exc.msg
|
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
proc initiateHandshake(
|
|
|
|
uri: Uri,
|
|
|
|
address: TransportAddress,
|
2021-04-14 03:35:58 +05:30
|
|
|
headers: HttpTable,
|
|
|
|
flags: set[TLSFlags] = {}): Future[AsyncStream] {.async.} =
|
2021-04-06 02:31:10 +05:30
|
|
|
## Initiate handshake with server
|
|
|
|
|
|
|
|
var transp: StreamTransport
|
|
|
|
try:
|
|
|
|
transp = await connect(address)
|
|
|
|
except CatchableError as exc:
|
|
|
|
raise newException(
|
|
|
|
TransportError,
|
|
|
|
"Cannot connect to " & $transp.remoteAddress() & " Error: " & exc.msg)
|
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
let
|
|
|
|
requestHeader = "GET " & uri.path & " HTTP/1.1" & CRLF & $headers
|
|
|
|
reader = newAsyncStreamReader(transp)
|
|
|
|
writer = newAsyncStreamWriter(transp)
|
|
|
|
|
2021-04-14 03:35:58 +05:30
|
|
|
var stream: AsyncStream
|
|
|
|
|
2021-04-14 16:37:38 +05:30
|
|
|
try:
|
|
|
|
var res: seq[byte]
|
|
|
|
if uri.scheme == "https":
|
|
|
|
let tlsstream = newTLSClientAsyncStream(reader, writer, "", flags = flags)
|
|
|
|
stream = AsyncStream(
|
|
|
|
reader: tlsstream.reader,
|
|
|
|
writer: tlsstream.writer)
|
|
|
|
|
|
|
|
await tlsstream.writer.write(requestHeader)
|
|
|
|
res = await tlsstream.reader.readHeaders()
|
|
|
|
else:
|
|
|
|
stream = AsyncStream(
|
|
|
|
reader: reader,
|
|
|
|
writer: writer)
|
|
|
|
await stream.writer.write(requestHeader)
|
|
|
|
res = await stream.reader.readHeaders()
|
|
|
|
|
|
|
|
if res.len == 0:
|
|
|
|
raise newException(ValueError, "Empty response from server")
|
|
|
|
|
|
|
|
let resHeader = res.parseResponse()
|
|
|
|
if resHeader.failed():
|
|
|
|
# Header could not be parsed
|
|
|
|
raise newException(WSMalformedHeaderError, "Malformed header received.")
|
|
|
|
|
|
|
|
if resHeader.code != ord(Http101):
|
|
|
|
raise newException(WSFailedUpgradeError,
|
|
|
|
"Server did not reply with a websocket upgrade:" &
|
|
|
|
" Header code: " & $resHeader.code &
|
|
|
|
" Header reason: " & resHeader.reason() &
|
|
|
|
" Address: " & $transp.remoteAddress())
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Websocket failed during handshake", exc = exc.msg
|
|
|
|
await stream.closeWait()
|
|
|
|
raise exc
|
2021-04-06 02:31:10 +05:30
|
|
|
|
2021-04-14 03:35:58 +05:30
|
|
|
return stream
|
2021-04-06 02:31:10 +05:30
|
|
|
|
2021-03-18 09:30:21 -06:00
|
|
|
proc connect*(
|
2021-04-06 02:31:10 +05:30
|
|
|
_: type WebSocket,
|
2021-03-18 09:30:21 -06:00
|
|
|
uri: Uri,
|
|
|
|
protocols: seq[string] = @[],
|
2021-04-14 03:35:58 +05:30
|
|
|
flags: set[TLSFlags] = {},
|
2021-03-18 09:30:21 -06:00
|
|
|
version = WSDefaultVersion,
|
|
|
|
frameSize = WSDefaultFrameSize,
|
|
|
|
onPing: ControlCb = nil,
|
|
|
|
onPong: ControlCb = nil,
|
|
|
|
onClose: CloseCb = nil): Future[WebSocket] {.async.} =
|
|
|
|
## create a new websockets client
|
|
|
|
##
|
|
|
|
|
|
|
|
var key = Base64.encode(genWebSecKey(newRng()))
|
2021-03-11 09:04:14 +05:30
|
|
|
var uri = uri
|
|
|
|
case uri.scheme
|
|
|
|
of "ws":
|
|
|
|
uri.scheme = "http"
|
2021-04-14 03:35:58 +05:30
|
|
|
of "wss":
|
|
|
|
uri.scheme = "https"
|
2021-03-11 09:04:14 +05:30
|
|
|
else:
|
2021-04-14 03:35:58 +05:30
|
|
|
raise newException(WSWrongUriSchemeError, "uri scheme has to be 'ws' or 'wss'")
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
var headerData = [
|
|
|
|
("Connection", "Upgrade"),
|
|
|
|
("Upgrade", "websocket"),
|
|
|
|
("Cache-Control", "no-cache"),
|
|
|
|
("Sec-WebSocket-Version", $version),
|
|
|
|
("Sec-WebSocket-Key", key)]
|
2021-03-18 09:30:21 -06:00
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
var headers = HttpTable.init(headerData)
|
2021-03-11 09:04:14 +05:30
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
if protocols.len != 0:
|
|
|
|
headers.add("Sec-WebSocket-Protocol", protocols.join(", "))
|
2021-03-18 09:30:21 -06:00
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
let address = initTAddress(uri.hostname & ":" & uri.port)
|
2021-04-14 03:35:58 +05:30
|
|
|
let stream = await initiateHandshake(uri, address, headers, flags)
|
2021-03-11 09:04:14 +05:30
|
|
|
|
|
|
|
# Client data should be masked.
|
2021-03-18 09:30:21 -06:00
|
|
|
return WebSocket(
|
2021-04-06 02:31:10 +05:30
|
|
|
stream: stream,
|
2021-04-14 16:37:38 +05:30
|
|
|
readyState: ReadyState.Open,
|
2021-03-18 09:30:21 -06:00
|
|
|
masked: true,
|
|
|
|
rng: newRng(),
|
|
|
|
frameSize: frameSize,
|
|
|
|
onPing: onPing,
|
|
|
|
onPong: onPong,
|
|
|
|
onClose: onClose)
|
|
|
|
|
|
|
|
proc connect*(
|
2021-04-06 02:31:10 +05:30
|
|
|
_: type WebSocket,
|
2021-03-18 09:30:21 -06:00
|
|
|
host: string,
|
|
|
|
port: Port,
|
|
|
|
path: string,
|
|
|
|
protocols: seq[string] = @[],
|
|
|
|
version = WSDefaultVersion,
|
|
|
|
frameSize = WSDefaultFrameSize,
|
|
|
|
onPing: ControlCb = nil,
|
|
|
|
onPong: ControlCb = nil,
|
|
|
|
onClose: CloseCb = nil): Future[WebSocket] {.async.} =
|
|
|
|
## Create a new websockets client
|
|
|
|
## using a string path
|
|
|
|
##
|
2021-03-11 09:04:14 +05:30
|
|
|
|
|
|
|
var uri = "ws://" & host & ":" & $port
|
|
|
|
if path.startsWith("/"):
|
|
|
|
uri.add path
|
|
|
|
else:
|
|
|
|
uri.add "/" & path
|
2021-03-18 09:30:21 -06:00
|
|
|
|
2021-04-06 02:31:10 +05:30
|
|
|
return await WebSocket.connect(
|
2021-03-18 09:30:21 -06:00
|
|
|
parseUri(uri),
|
|
|
|
protocols,
|
2021-04-14 03:35:58 +05:30
|
|
|
{},
|
|
|
|
version,
|
|
|
|
frameSize,
|
|
|
|
onPing,
|
|
|
|
onPong,
|
|
|
|
onClose)
|
|
|
|
|
|
|
|
proc tlsConnect*(
|
|
|
|
_: type WebSocket,
|
|
|
|
host: string,
|
|
|
|
port: Port,
|
|
|
|
path: string,
|
|
|
|
protocols: seq[string] = @[],
|
|
|
|
flags: set[TLSFlags] = {},
|
|
|
|
version = WSDefaultVersion,
|
|
|
|
frameSize = WSDefaultFrameSize,
|
|
|
|
onPing: ControlCb = nil,
|
|
|
|
onPong: ControlCb = nil,
|
|
|
|
onClose: CloseCb = nil): Future[WebSocket] {.async.} =
|
|
|
|
|
|
|
|
var uri = "wss://" & host & ":" & $port
|
|
|
|
if path.startsWith("/"):
|
|
|
|
uri.add path
|
|
|
|
else:
|
|
|
|
uri.add "/" & path
|
|
|
|
|
|
|
|
return await WebSocket.connect(
|
|
|
|
parseUri(uri),
|
|
|
|
protocols,
|
|
|
|
flags,
|
2021-03-18 09:30:21 -06:00
|
|
|
version,
|
|
|
|
frameSize,
|
|
|
|
onPing,
|
|
|
|
onPong,
|
|
|
|
onClose)
|