Add websocket connection limit, defaults to 1 and can be modified via config

Add WebsocketAllowInsecureOrigin config setting, default to false
This commit is contained in:
Adrian Gallagher
2017-09-12 14:29:33 +10:00
parent 6e9bda83a1
commit bc85f11c85
2 changed files with 30 additions and 5 deletions

View File

@@ -52,10 +52,12 @@ var (
// WebserverConfig struct holds the prestart variables for the webserver.
type WebserverConfig struct {
Enabled bool
AdminUsername string
AdminPassword string
ListenAddress string
Enabled bool
AdminUsername string
AdminPassword string
ListenAddress string
WebsocketConnectionLimit int
WebsocketAllowInsecureOrigin bool
}
// SMSGlobalConfig structure holds all the variables you need for instant
@@ -239,6 +241,11 @@ func (c *Config) CheckWebserverConfigValues() error {
if port < 1 || port > 65355 {
return errors.New(WarningWebserverListenAddressInvalid)
}
if c.Webserver.WebsocketConnectionLimit <= 0 {
c.Webserver.WebsocketConnectionLimit = 1
}
return nil
}

View File

@@ -54,11 +54,27 @@ var WebsocketClientHub []WebsocketClient
// WebsocketClientHandler upgrades the HTTP connection to a websocket
// compatible one
func WebsocketClientHandler(w http.ResponseWriter, r *http.Request) {
connectionLimit := bot.config.Webserver.WebsocketConnectionLimit
numClients := len(WebsocketClientHub)
if numClients >= connectionLimit {
log.Printf("Websocket client rejected due to websocket client limit reached. Number of clients %d. Limit %d.",
numClients, connectionLimit)
w.WriteHeader(http.StatusForbidden)
return
}
upgrader := websocket.Upgrader{
WriteBufferSize: 1024,
ReadBufferSize: 1024,
}
// Allow insecure origin if the Origin request header is present and not
// equal to the Host request header. Default to false
if bot.config.Webserver.WebsocketAllowInsecureOrigin {
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
}
newClient := WebsocketClient{
ID: len(WebsocketClientHub),
}
@@ -71,7 +87,9 @@ func WebsocketClientHandler(w http.ResponseWriter, r *http.Request) {
newClient.Conn = conn
WebsocketClientHub = append(WebsocketClientHub, newClient)
log.Println("New websocket client connected.")
numClients++
log.Printf("New websocket client connected. Connected clients: %d. Limit %d.",
numClients, connectionLimit)
}
// DisconnectWebsocketClient disconnects a websocket client