Merge pull request #192 from Gamadril/master

Added very basic WebSocket support to json server

Former-commit-id: e9045e1f32192b4e4e56ffa81d5828030f21a0f0
This commit is contained in:
tvdzwan 2014-11-09 15:52:52 +01:00
commit 1515f8dec3
2 changed files with 195 additions and 13 deletions

View File

@ -10,6 +10,8 @@
// Qt includes // Qt includes
#include <QResource> #include <QResource>
#include <QDateTime> #include <QDateTime>
#include <QCryptographicHash>
#include <QHostInfo>
// hyperion util includes // hyperion util includes
#include <hyperion/ImageProcessorFactory.h> #include <hyperion/ImageProcessorFactory.h>
@ -25,7 +27,8 @@ JsonClientConnection::JsonClientConnection(QTcpSocket *socket, Hyperion * hyperi
_socket(socket), _socket(socket),
_imageProcessor(ImageProcessorFactory::getInstance().newImageProcessor()), _imageProcessor(ImageProcessorFactory::getInstance().newImageProcessor()),
_hyperion(hyperion), _hyperion(hyperion),
_receiveBuffer() _receiveBuffer(),
_webSocketHandshakeDone(false)
{ {
// connect internal signals and slots // connect internal signals and slots
connect(_socket, SIGNAL(disconnected()), this, SLOT(socketClosed())); connect(_socket, SIGNAL(disconnected()), this, SLOT(socketClosed()));
@ -42,6 +45,19 @@ void JsonClientConnection::readData()
{ {
_receiveBuffer += _socket->readAll(); _receiveBuffer += _socket->readAll();
if (_webSocketHandshakeDone)
{
// websocket mode, data frame
handleWebSocketFrame();
} else
{
// might be a handshake request or raw socket data
if(_receiveBuffer.contains("Upgrade: websocket"))
{
doWebSocketHandshake();
} else
{
// raw socket data, handling as usual
int bytes = _receiveBuffer.indexOf('\n') + 1; int bytes = _receiveBuffer.indexOf('\n') + 1;
while(bytes > 0) while(bytes > 0)
{ {
@ -57,10 +73,135 @@ void JsonClientConnection::readData()
// try too look up '\n' again // try too look up '\n' again
bytes = _receiveBuffer.indexOf('\n') + 1; bytes = _receiveBuffer.indexOf('\n') + 1;
} }
}
}
}
void JsonClientConnection::handleWebSocketFrame()
{
if ((_receiveBuffer.at(0) & 0x80) == 0x80)
{
// final bit found, frame complete
quint8 * maskKey = NULL;
quint8 opCode = _receiveBuffer.at(0) & 0x0F;
bool isMasked = (_receiveBuffer.at(1) & 0x80) == 0x80;
quint64 payloadLength = _receiveBuffer.at(1) & 0x7F;
quint32 index = 2;
switch (payloadLength)
{
case 126:
payloadLength = ((_receiveBuffer.at(2) << 8) & 0xFF00) | (_receiveBuffer.at(3) & 0xFF);
index += 2;
break;
case 127:
payloadLength = 0;
for (uint i=0; i < 8; i++) {
payloadLength |= ((quint64)(_receiveBuffer.at(index+i) & 0xFF)) << (8*(7-i));
}
index += 8;
break;
default:
break;
}
if (isMasked)
{
// if the data is masked we need to get the key for unmasking
maskKey = new quint8[4];
for (uint i=0; i < 4; i++)
{
maskKey[i] = _receiveBuffer.at(index + i);
}
index += 4;
}
// check the type of data frame
switch (opCode)
{
case 0x01:
{
// frame contains text, extract it
QByteArray result = _receiveBuffer.mid(index, payloadLength);
_receiveBuffer.clear();
// unmask data if necessary
if (isMasked)
{
for (uint i=0; i < payloadLength; i++)
{
result[i] = (result[i] ^ maskKey[i % 4]);
}
if (maskKey != NULL)
{
delete[] maskKey;
maskKey = NULL;
}
}
handleMessage(QString(result).toStdString());
}
break;
case 0x08:
{
// close request, confirm
quint8 close[] = {0x88, 0};
_socket->write((const char*)close, 2);
_socket->flush();
_socket->close();
}
break;
case 0x09:
{
// ping received, send pong
quint8 pong[] = {0x0A, 0};
_socket->write((const char*)pong, 2);
_socket->flush();
}
break;
}
} else
{
std::cout << "Someone is sending very big messages over several frames... it's not supported yet" << std::endl;
quint8 close[] = {0x88, 0};
_socket->write((const char*)close, 2);
_socket->flush();
_socket->close();
}
}
void JsonClientConnection::doWebSocketHandshake()
{
// http header, might not be a very reliable check...
std::cout << "Websocket handshake" << std::endl;
// get the key to prepare an answer
int start = _receiveBuffer.indexOf("Sec-WebSocket-Key") + 19;
std::string value(_receiveBuffer.mid(start, _receiveBuffer.indexOf("\r\n", start) - start).data());
_receiveBuffer.clear();
// must be always appended
value += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// generate sha1 hash
QByteArray hash = QCryptographicHash::hash(value.c_str(), QCryptographicHash::Sha1);
// prepare an answer
std::ostringstream h;
h << "HTTP/1.1 101 Switching Protocols\r\n" <<
"Upgrade: websocket\r\n" <<
"Connection: Upgrade\r\n" <<
"Sec-WebSocket-Accept: " << QString(hash.toBase64()).toStdString() << "\r\n\r\n";
_socket->write(h.str().c_str());
_socket->flush();
// we are in WebSocket mode, data frames should follow next
_webSocketHandshakeDone = true;
} }
void JsonClientConnection::socketClosed() void JsonClientConnection::socketClosed()
{ {
_webSocketHandshakeDone = false;
emit connectionClosed(this); emit connectionClosed(this);
} }
@ -206,6 +347,9 @@ void JsonClientConnection::handleServerInfoCommand(const Json::Value &)
result["success"] = true; result["success"] = true;
Json::Value & info = result["info"]; Json::Value & info = result["info"];
// add host name for remote clients
info["hostname"] = QHostInfo::localHostName().toStdString();
// collect priority information // collect priority information
Json::Value & priorities = info["priorities"] = Json::Value(Json::arrayValue); Json::Value & priorities = info["priorities"] = Json::Value(Json::arrayValue);
uint64_t now = QDateTime::currentMSecsSinceEpoch(); uint64_t now = QDateTime::currentMSecsSinceEpoch();
@ -362,7 +506,32 @@ void JsonClientConnection::sendMessage(const Json::Value &message)
{ {
Json::FastWriter writer; Json::FastWriter writer;
std::string serializedReply = writer.write(message); std::string serializedReply = writer.write(message);
if (!_webSocketHandshakeDone)
{
// raw tcp socket mode
_socket->write(serializedReply.data(), serializedReply.length()); _socket->write(serializedReply.data(), serializedReply.length());
} else
{
// websocket mode
quint32 size = serializedReply.length();
// prepare data frame
QByteArray response;
response.append(0x81);
if (size > 125)
{
response.append(0x7E);
response.append((size >> 8) & 0xFF);
response.append(size & 0xFF);
} else {
response.append(size);
}
response.append(serializedReply.c_str(), serializedReply.length());
_socket->write(response.data(), response.length());
}
} }
void JsonClientConnection::sendSuccessReply() void JsonClientConnection::sendSuccessReply()

View File

@ -137,6 +137,16 @@ private:
/// ///
void sendErrorReply(const std::string & error); void sendErrorReply(const std::string & error);
///
/// Do handshake for a websocket connection
///
void doWebSocketHandshake();
///
/// Handle incoming websocket data frame
///
void handleWebSocketFrame();
private: private:
/// ///
/// Check if a JSON messag is valid according to a given JSON schema /// Check if a JSON messag is valid according to a given JSON schema
@ -161,4 +171,7 @@ private:
/// The buffer used for reading data from the socket /// The buffer used for reading data from the socket
QByteArray _receiveBuffer; QByteArray _receiveBuffer;
/// used for WebSocket detection and connection handling
bool _webSocketHandshakeDone;
}; };