Skip to content

Add maximum packet size check #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/ws.nim
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type
key*: string
protocol*: string
readyState*: ReadyState
maxPacketSize*: int
masked*: bool # send masked packets

WebSocketError* = object of IOError
Expand All @@ -23,6 +24,7 @@ type
WebSocketProtocolMismatchError* = object of WebSocketError
WebSocketFailedUpgradeError* = object of WebSocketError
WebSocketHandshakeError* = object of WebSocketError
WebSocketOversizedPacketError* = object of WebSocketError

func newWebSocketClosedError(): auto =
newException(WebSocketClosedError, "Socket closed")
Expand Down Expand Up @@ -97,7 +99,8 @@ proc handshake*(ws: WebSocket, headers: HttpHeaders) {.async.} =

proc newWebSocket*(
req: Request,
protocol: string = ""
protocol: string = "",
maxPacketSize: int = 1024*1024
): Future[WebSocket] {.async.} =
## Creates a new socket from a request.
try:
Expand All @@ -108,6 +111,7 @@ proc newWebSocket*(
ws.masked = false
ws.tcpSocket = req.client
ws.protocol = protocol
ws.maxPacketSize = maxPacketSize
await ws.handshake(req.headers)
return ws

Expand All @@ -120,13 +124,15 @@ proc newWebSocket*(

proc newWebSocket*(
url: string,
protocols: seq[string] = @[]
protocols: seq[string] = @[],
maxPacketSize: int = 1024*1024
): Future[WebSocket] {.async.} =
## Creates a new WebSocket connection,
## protocol is optional, "" means no protocol.
var ws = WebSocket()
ws.masked = true
ws.tcpSocket = newAsyncSocket()
ws.maxPacketSize = maxPacketSize

var uri = parseUri(url)
var port = Port(9001)
Expand Down Expand Up @@ -390,6 +396,8 @@ proc recvFrame(ws: WebSocket): Future[Frame] {.async.} =
raise newWebSocketClosedError()

# Read the data.
if int finalLen > ws.maxPacketSize:
raise newException(WebSocketOversizedPacketError, "Socket attempted to receive a packet larger than maxPacketSize, attempted size: " + $finalLen.int)
result.data = await ws.tcpSocket.recv(int finalLen)
if result.data.len != int finalLen:
raise newWebSocketClosedError()
Expand Down