Feature/web socket (#25)
* Add basic handshake * Basic message exchange * Base for a simple socket server * Web socket events * changelog * Small tweak
This commit is contained in:
1 parent
be4ef44338
commit
ed7c5c618b
18 files changed
+442
-15
No files matched your search
@@ -13,6 +13,7 @@ namespace Http
|
||||
private total_sent = 0
|
||||
private id = "<uninit>"
|
||||
private close = true
|
||||
private ws_upgrade = false
|
||||
private state = Http.HttpConnectionState.INIT
|
||||
|
||||
private server
|
||||
@@ -41,6 +42,7 @@ namespace Http
|
||||
m.header_only = false
|
||||
m.http_code = 0
|
||||
m.close = true
|
||||
m.ws_upgrade = false
|
||||
m.SetState(Http.HttpConnectionState.INIT)
|
||||
end function
|
||||
|
||||
@@ -83,7 +85,7 @@ namespace Http
|
||||
if m.request.state = Http.HttpRequestState.DONE
|
||||
server.num_requests = validint(server.num_requests) + 1
|
||||
m.response = new HttpResponse(m.request, m.server, m.settings)
|
||||
m.response.Process()
|
||||
m.response.Process(m)
|
||||
m.SetState(Http.HttpConnectionState.SEND_HEADER)
|
||||
else
|
||||
m.setState(Http.HttpConnectionState.DONE)
|
||||
|
||||
@@ -44,10 +44,10 @@ namespace Http
|
||||
m.headers = {}
|
||||
end function
|
||||
|
||||
function Process() as boolean
|
||||
function Process(connection as HttpConnection) as boolean
|
||||
routers = m.server.routers
|
||||
for each router in routers
|
||||
if router.OnRequest(m.request, m)
|
||||
if router.OnRequest(m.request, m, connection)
|
||||
return true
|
||||
end if
|
||||
end for
|
||||
|
||||
@@ -32,13 +32,14 @@ namespace Http
|
||||
m.routes.push({ method: "*", path: path, handler: handler })
|
||||
end function
|
||||
|
||||
private function OnRequest(request as object, response as HttpResponse) as boolean
|
||||
private function OnRequest(request as object, response as HttpResponse, connection as HttpConnection) as boolean
|
||||
for each route in m.routes
|
||||
if m.RouteMatchesRequest(route, request)
|
||||
if route.handler({
|
||||
router: m,
|
||||
request: request,
|
||||
response: response,
|
||||
connection: connection,
|
||||
server: response.server
|
||||
}) = true
|
||||
return true
|
||||
|
||||
@@ -3,6 +3,7 @@ import "pkg:/components/WebServer/HttpSettings.bs"
|
||||
import "pkg:/components/WebServer/HttpRouter.bs"
|
||||
import "pkg:/components/WebServer/HttpConnectionState.bs"
|
||||
import "pkg:/components/WebServer/HttpConnection.bs"
|
||||
import "pkg:/components/WebServer/WebSocket/WebSocketServer.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
@@ -28,6 +29,7 @@ namespace Http
|
||||
|
||||
public settings as Http.HttpSettings
|
||||
public task
|
||||
public websocket as Web.WebSocketServer
|
||||
|
||||
function new(settings as HttpSettings, task as object)
|
||||
m.log = new log.Logger("HttpResponse")
|
||||
@@ -130,6 +132,10 @@ namespace Http
|
||||
if conn.close
|
||||
conn.socket.close()
|
||||
connections.delete(id)
|
||||
else if conn.ws_upgrade and m.websocket <> invalid
|
||||
m.log.info("upgrading connection to web socket")
|
||||
m.websocket.AddConnection(conn.socket)
|
||||
connections.delete(id)
|
||||
else
|
||||
conn.Recycle()
|
||||
conn.PollRequest(m)
|
||||
@@ -160,6 +166,9 @@ namespace Http
|
||||
conn = connections[id]
|
||||
conn.socket.close()
|
||||
end for
|
||||
if m.websocket <> invalid
|
||||
m.websocket.Close()
|
||||
end if
|
||||
' final stats
|
||||
m.log.info(UnixNL() + m.stats())
|
||||
end function
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import "pkg:/source/utils/StringUtils.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
class BasicAuthMiddleware extends HttpRouter
|
||||
@@ -33,12 +35,7 @@ namespace Http
|
||||
end if
|
||||
|
||||
encoded = authHeader.Mid(6)
|
||||
|
||||
buffer = createObject("roByteArray")
|
||||
buffer.FromBase64String(encoded)
|
||||
|
||||
decoded = buffer.ToAsciiString()
|
||||
|
||||
decoded = FromBase64(encoded)
|
||||
components = decoded.Tokenize(":")
|
||||
|
||||
if components.Count() = 2
|
||||
|
||||
@@ -9,6 +9,8 @@ import "pkg:/components/WebServer/Middleware/CommandsApiRouter.bs"
|
||||
import "pkg:/components/WebServer/Middleware/CorsMiddleware.bs"
|
||||
import "pkg:/components/WebServer/Middleware/BasicAuthMiddleware.bs"
|
||||
import "pkg:/components/WebServer/Middleware/DashRouter.bs"
|
||||
import "pkg:/components/WebServer/WebSocket/Middleware/WebSocketMiddleware.bs"
|
||||
import "pkg:/components/WebServer/WebSocket/WebSocketServer.bs"
|
||||
|
||||
function Init()
|
||||
m.top.functionName = "WebServerLoop"
|
||||
@@ -20,9 +22,20 @@ function WebServerLoop()
|
||||
m.settings = new Http.HttpSettings(m.webServerPort)
|
||||
' Root at www to get http://IP_ADDRESS:PORT/index.html
|
||||
m.settings.WwwRoot = "pkg:/www"
|
||||
m.settings.Timeout = 2000
|
||||
' Short interval to keep polling on web socket messages
|
||||
m.settings.Timeout = 500
|
||||
m.server = new Http.HttpServer(m.settings, m)
|
||||
|
||||
#if WEB_SOCKETS
|
||||
m.websocket = new Web.WebSocketServer()
|
||||
m.websocket.OnMessage(function(context as object)
|
||||
connection = context.connection
|
||||
message = context.message
|
||||
connection.Send("Echo: " + message)
|
||||
end function)
|
||||
m.server.websocket = m.websocket
|
||||
#end if
|
||||
|
||||
homeRouter = new Http.HttpRouter()
|
||||
homeRouter.Get("/", function(context as object) as boolean
|
||||
response = context.response
|
||||
@@ -36,6 +49,9 @@ function WebServerLoop()
|
||||
allowedOrigin = `http://${GetLocalIpAddress()}:8888`
|
||||
#end if
|
||||
m.server.UseRouter(new Http.CorsMiddleware(allowedOrigin))
|
||||
#if WEB_SOCKETS
|
||||
m.server.UseRouter(new Http.WebSocketMiddleware())
|
||||
#end if
|
||||
m.server.UseRouter(homeRouter)
|
||||
m.server.UseRouter(new Http.DashRouter())
|
||||
m.server.UseRouter(new Http.CommandsApiRouter())
|
||||
@@ -58,9 +74,11 @@ function WebServerLoop()
|
||||
|
||||
while true
|
||||
m.server.PreWait()
|
||||
m.websocket.Poll()
|
||||
msg = wait(timeout, msgPort)
|
||||
tm = type(msg)
|
||||
if tm = "roSocketEvent" or msg = invalid
|
||||
msg = wait(0, m.port)
|
||||
msgType = type(msg)
|
||||
if msgType = "roSocketEvent" or msg = invalid
|
||||
m.server.PostWait()
|
||||
end if
|
||||
end while
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import "pkg:/source/utils/Crypto.bs"
|
||||
|
||||
namespace Http
|
||||
|
||||
const WEB_SOCKET_MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
class WebSocketMiddleware extends HttpRouter
|
||||
|
||||
function new()
|
||||
super()
|
||||
|
||||
m.Get("*", function(context as object) as boolean
|
||||
request = context.request
|
||||
response = context.response
|
||||
connection = context.connection
|
||||
|
||||
if LCase(validStr(request.headers["Connection"])) <> "upgrade"
|
||||
return false
|
||||
end if
|
||||
|
||||
if LCase(validStr(request.headers["Upgrade"])) <> "websocket"
|
||||
return false
|
||||
end if
|
||||
|
||||
webSocketKey = request.headers["Sec-WebSocket-Key"]
|
||||
if webSocketKey = invalid
|
||||
return false
|
||||
end if
|
||||
|
||||
sha1Hash = GetSha1(webSocketKey + Http.WEB_SOCKET_MAGIC_STRING)
|
||||
buffer = CreateObject("roByteArray")
|
||||
buffer.FromHexString(sha1Hash)
|
||||
webSocketAccept = ToBase64(buffer.ToAsciiString())
|
||||
|
||||
response.http_code = 101
|
||||
response.headers["Connection"] = "Upgrade"
|
||||
response.headers["Upgrade"] = "websocket"
|
||||
response.headers["Sec-WebSocket-Accept"] = webSocketAccept
|
||||
response.header_only = true
|
||||
response.source = Http.HttpResponseSource.GENERATED
|
||||
|
||||
connection.ws_upgrade = true
|
||||
|
||||
return true
|
||||
end function)
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,79 @@
|
||||
import "pkg:/components/WebServer/WebSocket/WebSocketFrame.bs"
|
||||
import "pkg:/components/WebServer/WebSocket/WebSocketConnectionState.bs"
|
||||
import "pkg:/source/roku_modules/log/LogMixin.brs"
|
||||
|
||||
namespace Web
|
||||
|
||||
const BUFSIZE = 65536
|
||||
|
||||
class WebSocketConnection
|
||||
private log as log.Logger
|
||||
|
||||
private server
|
||||
private socket
|
||||
private frame
|
||||
public id = invalid
|
||||
public state = invalid
|
||||
|
||||
function new(server as WebSocketServer, socket as object)
|
||||
m.log = new log.Logger("WebSocketConnection")
|
||||
m.server = server
|
||||
m.socket = socket
|
||||
m.socket.SetKeepAlive(true)
|
||||
m.socket.SetNoDelay(true)
|
||||
m.id = Stri(m.socket.getID()).trim()
|
||||
|
||||
m.buffer = CreateObject("roByteArray")
|
||||
m.buffer[Web.BUFSIZE] = 0
|
||||
|
||||
m.frame = new Web.WebSocketFrame()
|
||||
|
||||
m.state = Web.WebSocketConnectionState.OPEN
|
||||
end function
|
||||
|
||||
function Poll() as void
|
||||
if not m.socket.eOK()
|
||||
m.Close()
|
||||
return
|
||||
end if
|
||||
received = m.socket.receive(m.buffer, 0, Web.BUFSIZE)
|
||||
if received = 0
|
||||
m.Close()
|
||||
return
|
||||
else if received > 0
|
||||
if m.frame.ReadFromBuffer(m.buffer, 0, received)
|
||||
message = m.frame.GetPayloadText()
|
||||
m.log.info("received message:", message)
|
||||
|
||||
m.server.TriggerOnMessage(m, message)
|
||||
end if
|
||||
end if
|
||||
end function
|
||||
|
||||
function IsClosed() as boolean
|
||||
return m.state = Web.WebSocketConnectionState.CLOSED
|
||||
end function
|
||||
|
||||
function Close() as void
|
||||
if m.IsClosed()
|
||||
return
|
||||
end if
|
||||
m.socket.Close()
|
||||
m.state = Web.WebSocketConnectionState.CLOSED
|
||||
m.server.TriggerOnDisconnect(m)
|
||||
end function
|
||||
|
||||
function Send(text as string) as void
|
||||
if m.IsClosed()
|
||||
return
|
||||
end if
|
||||
m.frame.SetPayloadText(text)
|
||||
written_bytes = m.frame.WriteToBuffer(m.buffer, 0, Web.BUFSIZE)
|
||||
if written_bytes > 0
|
||||
m.socket.Send(m.buffer, 0, written_bytes)
|
||||
end if
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Web
|
||||
|
||||
enum WebSocketConnectionState
|
||||
CONNECTING = 0 'We probably don't ever see this state, since we upgrade existing connections from web server
|
||||
OPEN = 1
|
||||
CLOSING = 2
|
||||
CLOSED = 3
|
||||
end enum
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,105 @@
|
||||
import "pkg:/components/WebServer/WebSocket/WebSocketOpCode.bs"
|
||||
|
||||
namespace Web
|
||||
|
||||
class WebSocketFrame
|
||||
public fin
|
||||
public opcode
|
||||
public is_masked
|
||||
public payload_size
|
||||
public mask
|
||||
public payload
|
||||
|
||||
private index
|
||||
private length
|
||||
|
||||
function new()
|
||||
m.payload = CreateObject("roByteArray")
|
||||
end function
|
||||
|
||||
function ReadFromBuffer(buffer as object, index as integer, length as integer) as boolean
|
||||
m.buffer = buffer
|
||||
m.index = index
|
||||
m.length = length
|
||||
|
||||
firstByte = m.ReadByte()
|
||||
m.fin = (firstByte and &h80) <> 0
|
||||
m.opcode = firstByte and &hf
|
||||
|
||||
if not m.fin
|
||||
return false
|
||||
end if
|
||||
|
||||
if m.opcode <> Web.WebSocketOpCode.TEXT
|
||||
return false
|
||||
end if
|
||||
|
||||
secondByte = m.ReadByte()
|
||||
m.is_masked = (secondByte and &h80) <> 0
|
||||
m.payload_size = secondByte and &h7F
|
||||
|
||||
if not m.is_masked
|
||||
return false
|
||||
end if
|
||||
|
||||
if m.payload_size >= 126
|
||||
return false
|
||||
end if
|
||||
|
||||
m.mask = [m.ReadByte(), m.ReadByte(), m.ReadByte(), m.ReadByte()]
|
||||
|
||||
m.payload.Clear()
|
||||
for i = 0 to m.payload_size - 1
|
||||
m.payload[i] = m.Xor(m.ReadByte(), m.mask[i mod 4])
|
||||
end for
|
||||
|
||||
return true
|
||||
end function
|
||||
|
||||
function WriteToBuffer(buffer as object, index as integer, length as integer) as integer
|
||||
m.buffer = buffer
|
||||
m.index = index
|
||||
m.length = length
|
||||
|
||||
m.WriteByte(m.fin or m.opcode)
|
||||
m.WriteByte(m.payload_size)
|
||||
|
||||
for i = 0 to m.payload_size - 1
|
||||
m.buffer[m.index] = m.payload[i]
|
||||
m.index++
|
||||
end for
|
||||
|
||||
return m.index - index
|
||||
end function
|
||||
|
||||
function GetPayloadText() as string
|
||||
return m.payload.ToAsciiString()
|
||||
end function
|
||||
|
||||
function SetPayloadText(text as string)
|
||||
m.fin = &h80
|
||||
m.opcode = Web.WebSocketOpCode.TEXT
|
||||
m.is_masked = false
|
||||
m.mask = invalid
|
||||
m.payload.FromAsciiString(text)
|
||||
m.payload_size = m.payload.Count()
|
||||
end function
|
||||
|
||||
function ReadByte() as integer
|
||||
byte = m.buffer[m.index]
|
||||
m.index++
|
||||
return byte
|
||||
end function
|
||||
|
||||
function WriteByte(byte as integer) as integer
|
||||
m.buffer[m.index] = byte
|
||||
m.index++
|
||||
return byte
|
||||
end function
|
||||
|
||||
function Xor(a as integer, b as integer) as integer
|
||||
return (a or b) and not (a and b)
|
||||
end function
|
||||
end class
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Web
|
||||
|
||||
enum WebSocketOpCode
|
||||
CONTINUATION = 0
|
||||
TEXT = 1
|
||||
BINARY = 2
|
||||
CLOSE = 8
|
||||
PING = 9
|
||||
PONG = 10
|
||||
end enum
|
||||
|
||||
end namespace
|
||||
@@ -0,0 +1,100 @@
|
||||
import "pkg:/components/WebServer/WebSocket/WebSocketConnection.bs"
|
||||
|
||||
namespace Web
|
||||
|
||||
class WebSocketServer
|
||||
private log as log.Logger
|
||||
|
||||
private connections = invalid
|
||||
private buffer = invalid
|
||||
private onConnectListeners
|
||||
private onDisconnectListeners
|
||||
private onMessageListeners
|
||||
|
||||
function new()
|
||||
m.log = new log.Logger("WebSocketServer")
|
||||
m.connections = CreateObject("roAssociativeArray")
|
||||
m.onConnectListeners = []
|
||||
m.onDisconnectListeners = []
|
||||
m.onMessageListeners = []
|
||||
end function
|
||||
|
||||
function OnConnect(callback as function)
|
||||
m.onConnectListeners.push(callback)
|
||||
end function
|
||||
|
||||
function OnDisconnect(callback as function)
|
||||
m.onDisconnectListeners.push(callback)
|
||||
end function
|
||||
|
||||
function OnMessage(callback as function)
|
||||
m.onMessageListeners.push(callback)
|
||||
end function
|
||||
|
||||
function AddConnection(socket as object)
|
||||
client = new Web.WebSocketConnection(m, socket)
|
||||
m.connections[client.id] = client
|
||||
m.TriggerOnConnect(client)
|
||||
end function
|
||||
|
||||
function TriggerOnConnect(connection as Web.WebSocketConnection)
|
||||
m.log.info("on connect")
|
||||
for each listener in m.onConnectListeners
|
||||
listener({
|
||||
server: m,
|
||||
connection: connection
|
||||
})
|
||||
end for
|
||||
end function
|
||||
|
||||
function TriggerOnDisconnect(connection as Web.WebSocketConnection)
|
||||
m.log.info("on disconnect")
|
||||
for each listener in m.onDisconnectListeners
|
||||
listener({
|
||||
server: m,
|
||||
connection: connection
|
||||
})
|
||||
end for
|
||||
end function
|
||||
|
||||
function TriggerOnMessage(connection as Web.WebSocketConnection, message as string)
|
||||
for each listener in m.onMessageListeners
|
||||
listener({
|
||||
server: m,
|
||||
connection: connection,
|
||||
message: message
|
||||
})
|
||||
end for
|
||||
end function
|
||||
|
||||
function Poll()
|
||||
connections = m.connections
|
||||
for each id in connections
|
||||
connection = connections[id]
|
||||
if connection.IsClosed()
|
||||
connections.delete(id)
|
||||
else
|
||||
connection.Poll()
|
||||
end if
|
||||
end for
|
||||
end function
|
||||
|
||||
function Close()
|
||||
connections = m.connections
|
||||
for each id in connections
|
||||
conn = connections[id]
|
||||
conn.Close()
|
||||
end for
|
||||
end function
|
||||
|
||||
function Send(text as string) as void
|
||||
connections = m.connections
|
||||
for each id in connections
|
||||
conn = connections[id]
|
||||
conn.Send(text)
|
||||
end for
|
||||
end function
|
||||
|
||||
end class
|
||||
|
||||
end namespace
|
||||
+1
-1
@@ -23,4 +23,4 @@ splash_min_time=0
|
||||
|
||||
supports_input_launch=1
|
||||
|
||||
bs_const=DEBUG=true;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false
|
||||
bs_const=DEBUG=true;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false;WEB_SOCKETS=true
|
||||
@@ -6,3 +6,12 @@ function GetSha256(input as string) as string
|
||||
digest.Setup("sha256")
|
||||
return digest.Process(buffer)
|
||||
end function
|
||||
|
||||
function GetSha1(input as string) as string
|
||||
buffer = CreateObject("roByteArray")
|
||||
buffer.FromAsciiString(input)
|
||||
|
||||
digest = CreateObject("roEVPDigest")
|
||||
digest.Setup("sha1")
|
||||
return digest.Process(buffer)
|
||||
end function
|
||||
@@ -135,3 +135,15 @@ function PathJoin(path1 as string, path2 as string) as string
|
||||
end if
|
||||
return path1 + "/" + path2
|
||||
end function
|
||||
|
||||
function ToBase64(input as string) as string
|
||||
buffer = createObject("roByteArray")
|
||||
buffer.FromAsciiString(input)
|
||||
return buffer.ToBase64String()
|
||||
end function
|
||||
|
||||
function FromBase64(input as string) as string
|
||||
buffer = createObject("roByteArray")
|
||||
buffer.FromBase64String(input)
|
||||
return buffer.ToAsciiString()
|
||||
end function
|
||||
@@ -117,7 +117,8 @@ namespace WebUtils
|
||||
function HttpTitle(code = 0 as integer) as string
|
||||
hcm = m.HttpTitles
|
||||
if hcm = invalid
|
||||
hcm = { n200: "OK", n206: "Partial Content" }
|
||||
hcm = { n101: "Switching Protocols" }
|
||||
hcm.append({ n200: "OK", n206: "Partial Content" })
|
||||
hcm.append({ n301: "Moved Permanently", n304: "Not Modified" })
|
||||
hcm.append({ n400: "Bad Request", n401: "Unauthorized", n403: "Forbidden", n404: "Not Found", n413: "Request Entity Too Large" })
|
||||
hcm.append({ n500: "Internal Server Error", n501: "Not Implemented" })
|
||||
|
||||
Reference in new issue
Block a user