Compare commits

..

23 Commits
2.0.2 ... 2.0.4

Author SHA1 Message Date
cdee9fec05 release version 2.0.4 2016-07-11 17:29:29 +02:00
ab0d8ff526 Merge pull request #100 from chrisella/master
fix spellings
2016-06-18 12:39:40 +02:00
b3d4367d10 fix spellings 2016-06-17 15:37:07 +01:00
ab51930730 Merge pull request #93 from jjssoftware/HttpHeaderEvents
custom http header validation implementation
2016-06-13 21:01:14 +02:00
Joe
1ed734ec3f Merge pull request #2 from jlippa/master
pull from master
2016-06-11 13:13:16 +01:00
Joe
b99bae459d Merge pull request #1 from Links2004/master
pull from head
2016-06-11 13:05:44 +01:00
26130dc874 Merge pull request #95 from jlippa/Docs
wss / SSL README.md documentation update
2016-06-11 13:35:28 +02:00
joe
815093a123 wss / SSL README.md documentation update 2016-06-11 10:17:13 +01:00
joe
7e5c64a573 mandatoryHttpHeaderCount fix 2016-06-09 19:48:38 +01:00
joe
97443ae777 custom http header validation implementation; minor comment fixes 2016-06-08 23:11:21 +01:00
joe
e589b40b25 custom http header validation implementation 2016-06-08 23:04:18 +01:00
eb2351a4fd Merge pull request #89 from jlippa/nginx
Added sample ESP8266 nginx SSL reverse proxy configuration file
2016-06-07 18:02:50 +02:00
joe
8190e8121c Added sample ESP8266 nginx SSL reverse proxy configuration file 2016-06-05 16:09:22 +01:00
6a914fc5ea Merge pull request #87 from jlippa/master
RFC 6455 4.2.1.4 case sensitivity fix
2016-06-05 09:58:46 +02:00
48ee5fc6fb Firefox fix
Overlay fix for Firefox and other clients that send additional data in the Connection header e.g. "Connection: Keep-Alive, Upgrade"
2016-06-05 08:27:39 +01:00
b1685962c5 Merge pull request #1 from jlippa/jlippa-patch-1
RFC 6455 4.2.1.4 case sensitivity fix
2016-06-04 21:32:44 +01:00
c4e5f5c7e7 RFC 6455 4.2.1.4 case sensitivity fix
This is a case sensitivity fix for the Connection header Upgrade value to make this part meet the requirement of IETF websocket RFC 6455 4.2.1.4: "A |Connection| header field that includes the token "Upgrade", treated as an ASCII case-insensitive value."
2016-06-04 21:31:42 +01:00
6972f7a84e Merge pull request #74 from wnemay/master
Adjustments to headers during client handshake.
2016-05-10 18:02:09 +02:00
93b0b9eeaf Merge pull request #77 from thorstenfreitag/master
Compatibility for broken servers and additional authentication option instead of just basic
2016-05-10 17:52:30 +02:00
dd14850bb6 Used case insensitive recognition for upgrade header. Should work as before, but also with servers that wrongly use lower case upgrade in the header 2016-05-10 11:56:01 +10:00
d36f7bb100 Changed Header value to lower case upgrade, seems to fix connection issues with SAP HCP IoT services. Changed setAuthorization(const char * auth) to send Auth header as is, without BASIC to enable oAuth tokens in header 2016-05-09 00:11:42 +10:00
10a8d3ca67 Adding Origin, as required by spec. https://tools.ietf.org/html/rfc6455#section-1.6 2016-04-30 20:55:59 -07:00
4f55c36c80 RFC requires a port for Host when it is non default. https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23 2016-04-30 15:46:19 -07:00
10 changed files with 305 additions and 28 deletions

View File

@ -40,6 +40,9 @@ a WebSocket Server and Client for Arduino based on RFC6455.
### wss / SSL ###
supported for:
- wss client on the ESP8266
- wss / SSL is not natively supported in WebSocketsServer however it is possible to achieve secure websockets
by running the device behind an SSL proxy. See [Nginx](examples/Nginx/esp8266.ssl.reverse.proxy.conf) for a
sample Nginx server configuration file to enable this.
### ESP Async TCP ###

View File

@ -0,0 +1,83 @@
# ESP8266 nginx SSL reverse proxy configuration file (tested and working on nginx v1.10.0)
# proxy cache location
proxy_cache_path /opt/etc/nginx/cache levels=1:2 keys_zone=ESP8266_cache:10m max_size=10g inactive=5m use_temp_path=off;
# webserver proxy
server {
# general server parameters
listen 50080;
server_name myDomain.net;
access_log /opt/var/log/nginx/myDomain.net.access.log;
# SSL configuration
ssl on;
ssl_certificate /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/fullchain.pem;
ssl_certificate_key /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/privkey.pem;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
location / {
# proxy caching configuration
proxy_cache ESP8266_cache;
proxy_cache_revalidate on;
proxy_cache_min_uses 1;
proxy_cache_use_stale off;
proxy_cache_lock on;
# proxy_cache_bypass $http_cache_control;
# include the sessionId cookie value as part of the cache key - keeps the cache per user
# proxy_cache_key $proxy_host$request_uri$cookie_sessionId;
# header pass through configuration
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# ESP8266 custom headers which identify to the device that it's running through an SSL proxy
proxy_set_header X-SSL On;
proxy_set_header X-SSL-WebserverPort 50080;
proxy_set_header X-SSL-WebsocketPort 50081;
# extra debug headers
add_header X-Proxy-Cache $upstream_cache_status;
add_header X-Forwarded-For $proxy_add_x_forwarded_for;
# actual proxying configuration
proxy_ssl_session_reuse on;
# target the IP address of the device with proxy_pass
proxy_pass http://192.168.0.20;
proxy_read_timeout 90;
}
}
# websocket proxy
server {
# general server parameters
listen 50081;
server_name myDomain.net;
access_log /opt/var/log/nginx/myDomain.net.wss.access.log;
# SSL configuration
ssl on;
ssl_certificate /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/fullchain.pem;
ssl_certificate_key /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/privkey.pem;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
location / {
# websocket upgrade tunnel configuration
proxy_pass http://192.168.0.20:81;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_read_timeout 86400;
}
}

View File

@ -0,0 +1,86 @@
/*
* WebSocketServerHttpHeaderValidation.ino
*
* Created on: 08.06.2016
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsServer webSocket = WebSocketsServer(81);
#define USE_SERIAL Serial1
const unsigned long int validSessionId = 12345; //some arbitrary value to act as a valid sessionId
/*
* Returns a bool value as an indicator to describe whether a user is allowed to initiate a websocket upgrade
* based on the value of a cookie. This function expects the rawCookieHeaderValue to look like this "sessionId=<someSessionIdNumberValue>|"
*/
bool isCookieValid(String rawCookieHeaderValue) {
if (rawCookieHeaderValue.indexOf("sessionId") != -1) {
String sessionIdStr = rawCookieHeaderValue.substring(rawCookieHeaderValue.indexOf("sessionId=") + 10, rawCookieHeaderValue.indexOf("|"));
unsigned long int sessionId = strtoul(sessionIdStr.c_str(), NULL, 10);
return sessionId == validSessionId;
}
return false;
}
/*
* The WebSocketServerHttpHeaderValFunc delegate passed to webSocket.onValidateHttpHeader
*/
bool validateHttpHeader(String headerName, String headerValue) {
//assume a true response for any headers not handled by this validator
bool valid = true;
if(headerName.equalsIgnoreCase("Cookie")) {
//if the header passed is the Cookie header, validate it according to the rules in 'isCookieValid' function
valid = isCookieValid(headerValue);
}
return valid;
}
void setup() {
// USE_SERIAL.begin(921600);
USE_SERIAL.begin(115200);
//Serial.setDebugOutput(true);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFiMulti.addAP("SSID", "passpasspass");
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
//connecting clients must supply a valid session cookie at websocket upgrade handshake negotiation time
const char * headerkeys[] = { "Cookie" };
size_t headerKeyCount = sizeof(headerkeys) / sizeof(char*);
webSocket.onValidateHttpHeader(validateHttpHeader, headerkeys, headerKeyCount);
webSocket.begin();
}
void loop() {
webSocket.loop();
}

View File

@ -1,5 +1,5 @@
name=WebSockets
version=2.0.2
version=2.0.4
author=Markus Sattler
maintainer=Markus Sattler
sentence=WebSockets for Arduino (Server + Client)

View File

@ -426,7 +426,7 @@ void WebSockets::handleWebsocketPayloadCb(WSclient_t * client, bool ok, uint8_t
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] text: %s\n", client->num, payload);
// no break here!
case WSop_binary:
messageRecived(client, header->opCode, payload, header->payloadLen);
messageReceived(client, header->opCode, payload, header->payloadLen);
break;
case WSop_ping:
// send pong back

View File

@ -181,6 +181,10 @@ typedef struct {
WSMessageHeader_t cWsHeaderDecode;
String base64Authorization; ///< Base64 encoded Auth request
String plainAuthorization; ///< Base64 encoded Auth request
bool cHttpHeadersValid; ///< non-websocket http header validity indicator
size_t cMandatoryHeadersCount; ///< non-websocket mandatory http headers present count
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
String cHttpLine; ///< HTTP header lines
@ -201,7 +205,7 @@ class WebSockets {
virtual void clientDisconnect(WSclient_t * client);
virtual bool clientIsConnected(WSclient_t * client);
virtual void messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
virtual void messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
void clientDisconnect(WSclient_t * client, uint16_t code, char * reason = NULL, size_t reasonLen = 0);
bool sendFrame(WSclient_t * client, WSopcode_t opcode, uint8_t * payload = NULL, size_t length = 0, bool mask = false, bool fin = true, bool headerToPayload = false);

View File

@ -62,6 +62,7 @@ void WebSocketsClient::begin(const char *host, uint16_t port, const char * url,
_client.cExtensions = "";
_client.cVersion = 0;
_client.base64Authorization = "";
_client.plainAuthorization = "";
#ifdef ESP8266
randomSeed(RANDOM_REG32);
@ -228,7 +229,8 @@ void WebSocketsClient::setAuthorization(const char * user, const char * password
*/
void WebSocketsClient::setAuthorization(const char * auth) {
if(auth) {
_client.base64Authorization = auth;
//_client.base64Authorization = auth;
_client.plainAuthorization = auth;
}
}
@ -243,7 +245,7 @@ void WebSocketsClient::setAuthorization(const char * auth) {
* @param payload uint8_t *
* @param lenght size_t
*/
void WebSocketsClient::messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t lenght) {
void WebSocketsClient::messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t lenght) {
WStype_t type = WStype_ERROR;
switch(opcode) {
@ -392,15 +394,16 @@ void WebSocketsClient::sendHeader(WSclient_t * client) {
#endif
String handshake = "GET " + client->cUrl + " HTTP/1.1\r\n"
"Host: " + _host + "\r\n"
"Upgrade: websocket\r\n"
"Host: " + _host + ":" + _port + "\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n"
"Origin: file://\r\n"
"User-Agent: arduino-WebSocket-Client\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: " + client->cKey + "\r\n";
if(client->cProtocol.length() > 0) {
handshake += "Sec-WebSocket-Protocol: " + client->cProtocol + "\r\n";
handshake += "Sec-WebSocket-Protocol: " + client->cProtocol + "\r\n";
}
if(client->cExtensions.length() > 0) {
@ -411,6 +414,10 @@ void WebSocketsClient::sendHeader(WSclient_t * client) {
handshake += "Authorization: Basic " + client->base64Authorization + "\r\n";
}
if(client->plainAuthorization.length() > 0) {
handshake += "Authorization: " + client->plainAuthorization + "\r\n";
}
handshake += "\r\n";
client->tcp->write(handshake.c_str(), handshake.length());
@ -442,7 +449,7 @@ void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {
String headerValue = headerLine->substring(headerLine->indexOf(':') + 2);
if(headerName.equalsIgnoreCase("Connection")) {
if(headerValue.indexOf("Upgrade") >= 0) {
if(headerValue.equalsIgnoreCase("upgrade")) {
client->cIsUpgrade = true;
}
} else if(headerName.equalsIgnoreCase("Upgrade")) {
@ -620,6 +627,3 @@ void WebSocketsClient::asyncConnect() {
}
#endif

View File

@ -82,7 +82,7 @@ class WebSocketsClient: private WebSockets {
WebSocketClientEvent _cbEvent;
void messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
void messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
void clientDisconnect(WSclient_t * client);
bool clientIsConnected(WSclient_t * client);

View File

@ -40,6 +40,9 @@ WebSocketsServer::WebSocketsServer(uint16_t port, String origin, String protocol
_cbEvent = NULL;
_httpHeaderValidationFunc = NULL;
_mandatoryHttpHeaders = NULL;
_mandatoryHttpHeaderCount = 0;
}
@ -53,10 +56,14 @@ WebSocketsServer::~WebSocketsServer() {
// TODO how to close server?
#endif
if (_mandatoryHttpHeaders)
delete[] _mandatoryHttpHeaders;
_mandatoryHttpHeaderCount = 0;
}
/**
* calles to init the Websockets server
* called to initialize the Websocket server
*/
void WebSocketsServer::begin(void) {
WSclient_t * client;
@ -83,6 +90,7 @@ void WebSocketsServer::begin(void) {
client->base64Authorization = "";
client->cWsRXsize = 0;
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
client->cHttpLine = "";
#endif
@ -118,7 +126,31 @@ void WebSocketsServer::onEvent(WebSocketServerEvent cbEvent) {
_cbEvent = cbEvent;
}
/**
/*
* Sets the custom http header validator function
* @param httpHeaderValidationFunc WebSocketServerHttpHeaderValFunc ///< pointer to the custom http header validation function
* @param mandatoryHttpHeaders[] const char* ///< the array of named http headers considered to be mandatory / must be present in order for websocket upgrade to succeed
* @param mandatoryHttpHeaderCount size_t ///< the number of items in the mandatoryHttpHeaders array
*/
void WebSocketsServer::onValidateHttpHeader(
WebSocketServerHttpHeaderValFunc validationFunc,
const char* mandatoryHttpHeaders[],
size_t mandatoryHttpHeaderCount)
{
_httpHeaderValidationFunc = validationFunc;
if (_mandatoryHttpHeaders)
delete[] _mandatoryHttpHeaders;
_mandatoryHttpHeaderCount = mandatoryHttpHeaderCount;
_mandatoryHttpHeaders = new String[_mandatoryHttpHeaderCount];
for (size_t i = 0; i < _mandatoryHttpHeaderCount; i++) {
_mandatoryHttpHeaders[i] = mandatoryHttpHeaders[i];
}
}
/*
* send text data to client
* @param num uint8_t client id
* @param payload uint8_t *
@ -279,9 +311,8 @@ void WebSocketsServer::disconnect(uint8_t num) {
}
/**
* set the Authorizatio for the http request
/*
* set the Authorization for the http request
* @param user const char *
* @param password const char *
*/
@ -388,7 +419,7 @@ bool WebSocketsServer::newClient(WEBSOCKETS_NETWORK_CLASS * TCPclient) {
* @param payload uint8_t *
* @param lenght size_t
*/
void WebSocketsServer::messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t lenght) {
void WebSocketsServer::messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t lenght) {
WStype_t type = WStype_ERROR;
switch(opcode) {
@ -446,6 +477,7 @@ void WebSocketsServer::clientDisconnect(WSclient_t * client) {
client->cIsWebsocket = false;
client->cWsRXsize = 0;
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
client->cHttpLine = "";
#endif
@ -461,7 +493,7 @@ void WebSocketsServer::clientDisconnect(WSclient_t * client) {
/**
* get client state
* @param client WSclient_t * ptr to the client struct
* @return true = conneted
* @return true = connected
*/
bool WebSocketsServer::clientIsConnected(WSclient_t * client) {
@ -492,7 +524,7 @@ bool WebSocketsServer::clientIsConnected(WSclient_t * client) {
}
#if (WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP8266_ASYNC)
/**
* Handle incomming Connection Request
* Handle incoming Connection Request
*/
void WebSocketsServer::handleNewClients(void) {
@ -569,10 +601,22 @@ void WebSocketsServer::handleClientData(void) {
}
#endif
/*
* returns an indicator whether the given named header exists in the configured _mandatoryHttpHeaders collection
* @param headerName String ///< the name of the header being checked
*/
bool WebSocketsServer::hasMandatoryHeader(String headerName) {
for (size_t i = 0; i < _mandatoryHttpHeaderCount; i++) {
if (_mandatoryHttpHeaders[i].equalsIgnoreCase(headerName))
return true;
}
return false;
}
/**
* handle the WebSocket header reading
* @param client WSclient_t * ptr to the client struct
* handles http header reading for WebSocket upgrade
* @param client WSclient_t * ///< pointer to the client struct
* @param headerLine String ///< the header being read / processed
*/
void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
@ -581,16 +625,23 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
if(headerLine->length() > 0) {
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] RX: %s\n", client->num, headerLine->c_str());
// websocket request starts allways with GET see rfc6455
// websocket requests always start with GET see rfc6455
if(headerLine->startsWith("GET ")) {
// cut URL out
client->cUrl = headerLine->substring(4, headerLine->indexOf(' ', 4));
//reset non-websocket http header validation state for this client
client->cHttpHeadersValid = true;
client->cMandatoryHeadersCount = 0;
} else if(headerLine->indexOf(':')) {
String headerName = headerLine->substring(0, headerLine->indexOf(':'));
String headerValue = headerLine->substring(headerLine->indexOf(':') + 2);
if(headerName.equalsIgnoreCase("Connection")) {
if(headerValue.indexOf("Upgrade") >= 0) {
headerValue.toLowerCase();
if(headerValue.indexOf("upgrade") >= 0) {
client->cIsUpgrade = true;
}
} else if(headerName.equalsIgnoreCase("Upgrade")) {
@ -608,7 +659,13 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
client->cExtensions = headerValue;
} else if(headerName.equalsIgnoreCase("Authorization")) {
client->base64Authorization = headerValue;
} else {
client->cHttpHeadersValid &= execHttpHeaderValidation(headerName, headerValue);
if (_mandatoryHttpHeaderCount > 0 && hasMandatoryHeader(headerName)) {
client->cMandatoryHeadersCount++;
}
}
} else {
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header error (%s)\n", headerLine->c_str());
}
@ -618,8 +675,8 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
client->tcp->readStringUntil('\n', &(client->cHttpLine), std::bind(&WebSocketsServer::handleHeader, this, client, &(client->cHttpLine)));
#endif
} else {
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] Header read fin.\n", client->num);
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] Header read fin.\n", client->num);
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cURL: %s\n", client->num, client->cUrl.c_str());
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cIsUpgrade: %d\n", client->num, client->cIsUpgrade);
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cIsWebsocket: %d\n", client->num, client->cIsWebsocket);
@ -628,6 +685,8 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cExtensions: %s\n", client->num, client->cExtensions.c_str());
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cVersion: %d\n", client->num, client->cVersion);
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - base64Authorization: %s\n", client->num, client->base64Authorization.c_str());
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cHttpHeadersValid: %d\n", client->num, client->cHttpHeadersValid);
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cMandatoryHeadersCount: %d\n", client->num, client->cMandatoryHeadersCount);
bool ok = (client->cIsUpgrade && client->cIsWebsocket);
@ -641,6 +700,12 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
if(client->cVersion != 13) {
ok = false;
}
if(!client->cHttpHeadersValid) {
ok = false;
}
if (client->cMandatoryHeadersCount != _mandatoryHttpHeaderCount) {
ok = false;
}
}
if(_base64Authorization.length() > 0) {

View File

@ -38,8 +38,10 @@ public:
#ifdef __AVR__
typedef void (*WebSocketServerEvent)(uint8_t num, WStype_t type, uint8_t * payload, size_t length);
typedef bool (*WebSocketServerHttpHeaderValFunc)(String headerName, String headerValue);
#else
typedef std::function<void (uint8_t num, WStype_t type, uint8_t * payload, size_t length)> WebSocketServerEvent;
typedef std::function<bool (String headerName, String headerValue)> WebSocketServerHttpHeaderValFunc;
#endif
WebSocketsServer(uint16_t port, String origin = "", String protocol = "arduino");
@ -55,6 +57,10 @@ public:
#endif
void onEvent(WebSocketServerEvent cbEvent);
void onValidateHttpHeader(
WebSocketServerHttpHeaderValFunc validationFunc,
const char* mandatoryHttpHeaders[],
size_t mandatoryHttpHeaderCount);
bool sendTXT(uint8_t num, uint8_t * payload, size_t length = 0, bool headerToPayload = false);
@ -90,16 +96,19 @@ protected:
String _origin;
String _protocol;
String _base64Authorization; ///< Base64 encoded Auth request
String * _mandatoryHttpHeaders;
size_t _mandatoryHttpHeaderCount;
WEBSOCKETS_NETWORK_SERVER_CLASS * _server;
WSclient_t _clients[WEBSOCKETS_SERVER_CLIENT_MAX];
WebSocketServerEvent _cbEvent;
WebSocketServerHttpHeaderValFunc _httpHeaderValidationFunc;
bool newClient(WEBSOCKETS_NETWORK_CLASS * TCPclient);
void messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
void messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
void clientDisconnect(WSclient_t * client);
bool clientIsConnected(WSclient_t * client);
@ -111,7 +120,6 @@ protected:
void handleHeader(WSclient_t * client, String * headerLine);
/**
* called if a non Websocket connection is coming in.
* Note: can be override
@ -162,6 +170,30 @@ protected:
}
}
/*
* Called at client socket connect handshake negotiation time for each http header that is not
* a websocket specific http header (not Connection, Upgrade, Sec-WebSocket-*)
* If the custom httpHeaderValidationFunc returns false for any headerName / headerValue passed, the
* socket negotiation is considered invalid and the upgrade to websockets request is denied / rejected
* This mechanism can be used to enable custom authentication schemes e.g. test the value
* of a session cookie to determine if a user is logged on / authenticated
*/
virtual bool execHttpHeaderValidation(String headerName, String headerValue) {
if(_httpHeaderValidationFunc) {
//return the value of the custom http header validation function
return _httpHeaderValidationFunc(headerName, headerValue);
}
//no custom http header validation so just assume all is good
return true;
}
private:
/*
* returns an indicator whether the given named header exists in the configured _mandatoryHttpHeaders collection
* @param headerName String ///< the name of the header being checked
*/
bool hasMandatoryHeader(String headerName);
};