add WebSockets support

This commit is contained in:
Syping 2020-09-19 09:31:57 +02:00
parent 2af86f0524
commit d4a25b8346
5 changed files with 223 additions and 104 deletions

View file

@ -12,6 +12,7 @@ set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt5 COMPONENTS Network REQUIRED) find_package(Qt5 COMPONENTS Network REQUIRED)
find_package(Qt5 COMPONENTS WebSockets QUIET)
set(SMSUB_SOURCES set(SMSUB_SOURCES
main.cpp main.cpp
@ -30,6 +31,6 @@ add_executable(smsub
${SMSUB_SOURCES} ${SMSUB_SOURCES}
) )
target_link_libraries(smsub PRIVATE Qt5::Network) target_link_libraries(smsub PRIVATE Qt5::Network Qt5::WebSockets)
install(TARGETS smsub DESTINATION bin) install(TARGETS smsub DESTINATION bin)

View file

@ -24,16 +24,59 @@
SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &socket) : serverSettings(serverSettings) SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &socket) : serverSettings(serverSettings)
{ {
setSocketOptions(QLocalServer::UserAccessOption | QLocalServer::GroupAccessOption); QLocalServer *localServer = new QLocalServer(this);
listen(socket); localServer->setSocketOptions(QLocalServer::UserAccessOption | QLocalServer::GroupAccessOption);
localServer->listen(socket);
QObject::connect(localServer, &QLocalServer::newConnection, this, &SMSubServer::newConnection);
type = ServerType::Local;
server = localServer;
} }
void SMSubServer::incomingConnection(quintptr socketDescriptor) SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &serverName, const quint16 &port) : serverSettings(serverSettings)
{ {
QLocalSocket *socket = new QLocalSocket(); QWebSocketServer *webSocketServer = new QWebSocketServer(serverName, QWebSocketServer::NonSecureMode, this);
socket->setSocketDescriptor(socketDescriptor); webSocketServer->listen(QHostAddress::LocalHost, port);
QObject::connect(socket, &QLocalSocket::readyRead, this, &SMSubServer::readyRead);
QObject::connect(socket, &QLocalSocket::disconnected, this, &SMSubServer::deleteSocket); QObject::connect(webSocketServer, &QWebSocketServer::newConnection, this, &SMSubServer::newConnection);
type = ServerType::WebSocket;
server = webSocketServer;
}
bool SMSubServer::isListening()
{
if (likely(type == ServerType::Local)) {
return static_cast<QLocalServer*>(server)->isListening();
}
else if (type == ServerType::WebSocket) {
return static_cast<QWebSocketServer*>(server)->isListening();
}
return false;
}
void SMSubServer::newConnection()
{
QObject *socket;
if (likely(type == ServerType::Local)) {
QLocalSocket *localSocket = static_cast<QLocalServer*>(server)->nextPendingConnection();
QObject::connect(localSocket, &QLocalSocket::readyRead, this, &SMSubServer::lsReadyRead);
QObject::connect(localSocket, &QLocalSocket::disconnected, this, &SMSubServer::deleteSocket);
localSocket->write(QString("SMSub Version %1\n").arg(QCoreApplication::applicationVersion()).toUtf8());
socket = localSocket;
}
else if (type == ServerType::WebSocket) {
QWebSocket *webSocket = static_cast<QWebSocketServer*>(server)->nextPendingConnection();
QObject::connect(webSocket, &QWebSocket::binaryMessageReceived, this, &SMSubServer::wsMessageReceived);
QObject::connect(webSocket, &QWebSocket::disconnected, this, &SMSubServer::deleteSocket);
webSocket->sendBinaryMessage(QString("SMSub Version %1\n").arg(QCoreApplication::applicationVersion()).toUtf8());
socket = webSocket;
}
else {
// Just for being sure
return;
}
// Set authentication state // Set authentication state
if (serverSettings->isLocal) { if (serverSettings->isLocal) {
@ -43,103 +86,118 @@ void SMSubServer::incomingConnection(quintptr socketDescriptor)
else { else {
socket->setProperty("Authenticated", false); socket->setProperty("Authenticated", false);
} }
// Initial open writing
socket->write(QString("SMSub Version %1\n").arg(QCoreApplication::applicationVersion()).toUtf8());
} }
void SMSubServer::readyRead() void SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
{ {
// Manage client input
QLocalSocket *socket = (QLocalSocket*)sender();
bool isAuthenticated = socket->property("Authenticated").toBool();
while (socket->canReadLine()) {
const QByteArray readData = socket->readLine().trimmed();
// Only allow commands being sent if authenticated // Only allow commands being sent if authenticated
bool isAuthenticated = socket->property("Authenticated").toBool();
if (likely(isAuthenticated)) { if (likely(isAuthenticated)) {
if (readData.startsWith("+dbg")) { if (message.startsWith("+dbg")) {
socket->setProperty("ReceiveDbgMsg", true); socket->setProperty("ReceiveDbgMsg", true);
socket->write("Debug messages enabled!\n"); sendMessage(socket, "Debug messages enabled!\n");
} }
else if (readData.startsWith("-dbg")) { else if (message.startsWith("-dbg")) {
socket->setProperty("ReceiveDbgMsg", false); socket->setProperty("ReceiveDbgMsg", false);
socket->write("Debug messages disabled!\n"); sendMessage(socket, "Debug messages disabled!\n");
} }
else if (readData.startsWith("+log")) { else if (message.startsWith("+log")) {
socket->setProperty("ReceiveLog", true); socket->setProperty("ReceiveLog", true);
debugOutput(socket, "Log output enabled!"); debugOutput(socket, "Log output enabled!");
} }
else if (readData.startsWith("-log")) { else if (message.startsWith("-log")) {
socket->setProperty("ReceiveLog", false); socket->setProperty("ReceiveLog", false);
debugOutput(socket, "Log output disabled!"); debugOutput(socket, "Log output disabled!");
} }
else if (readData.startsWith("+reg")) { else if (message.startsWith("+reg")) {
if (likely(serverSettings->canRegister)) { if (likely(serverSettings->canRegister)) {
QByteArray authUuid = QUuid::createUuid().toByteArray(QUuid::Id128); QByteArray authUuid = QUuid::createUuid().toByteArray(QUuid::Id128);
authUuid = QByteArray::fromHex(authUuid).toBase64(QByteArray::OmitTrailingEquals); authUuid = QByteArray::fromHex(authUuid).toBase64(QByteArray::OmitTrailingEquals);
emit tokenRegistered(QString::fromUtf8(authUuid)); emit tokenRegistered(QString::fromUtf8(authUuid));
socket->write("Token: " + authUuid + '\n'); sendMessage(socket, "Token: " + authUuid + '\n');
} }
else { else {
socket->write("Permission denied!\n"); sendMessage(socket, "Permission denied!\n");
} }
} }
else if (readData.startsWith("kill")) { else if (message.startsWith("kill")) {
emit killRequested(); emit killRequested();
debugOutput(socket, "Killing server!"); debugOutput(socket, "Killing server!");
} }
else if (readData.startsWith("stop")) { else if (message.startsWith("stop")) {
emit stopRequested(); emit stopRequested();
debugOutput(socket, "Stopping server!"); debugOutput(socket, "Stopping server!");
} }
else if (readData.startsWith("wl")) { else if (message.startsWith("wl")) {
const QByteArray writeData = readData.mid(3); const QByteArray writeData = message.mid(3);
emit inputWritten(writeData + '\n'); emit inputWritten(writeData + '\n');
debugOutput(socket, "Write line \"" + writeData + "\"!"); debugOutput(socket, "Write line \"" + writeData + "\"!");
} }
else if (readData.startsWith("w")) { else if (message.startsWith("w")) {
const QByteArray writeData = readData.mid(2); const QByteArray writeData = message.mid(2);
emit inputWritten(writeData); emit inputWritten(writeData);
debugOutput(socket, "Write \"" + writeData + "\"!"); debugOutput(socket, "Write \"" + writeData + "\"!");
} }
} }
else { else {
// Authenticate when token is valid, otherwise disconnect // Authenticate when token is valid, otherwise disconnect
if (unlikely(tokens.contains(QString::fromUtf8(readData)))) { if (unlikely(tokens.contains(QString::fromUtf8(message)))) {
// Set client as authenticated and add it to vector // Set client as authenticated and add it to vector
socket->setProperty("Authenticated", true); socket->setProperty("Authenticated", true);
socket->write("Login successful!\n"); sendMessage(socket, "Login successful!\n");
isAuthenticated = true; isAuthenticated = true;
sockets << socket; sockets << socket;
} }
else { else {
// Stop receiving data and disconnect socket // Stop receiving data and disconnect socket
QObject::disconnect(socket, &QLocalSocket::readyRead, this, &SMSubServer::readyRead); if (likely(type == ServerType::Local)) {
socket->write("Incorrect token!\n"); QLocalSocket *localSocket = static_cast<QLocalSocket*>(socket);
socket->disconnectFromServer(); QObject::disconnect(localSocket, &QLocalSocket::readyRead, this, &SMSubServer::lsReadyRead);
localSocket->write("Incorrect token!\n");
localSocket->disconnectFromServer();
}
else if (type == ServerType::WebSocket) {
QWebSocket *webSocket = static_cast<QWebSocket*>(socket);
QObject::disconnect(webSocket, &QWebSocket::binaryMessageReceived, this, &SMSubServer::wsMessageReceived);
webSocket->sendBinaryMessage("Incorrect token!\n");
webSocket->close(QWebSocketProtocol::CloseCodeNormal);
}
return; return;
} }
} }
}
void SMSubServer::wsMessageReceived(const QByteArray &message)
{
QWebSocket *socket = static_cast<QWebSocket*>(sender());
messageReceived(socket, message.trimmed());
}
void SMSubServer::lsReadyRead()
{
QLocalSocket *socket = static_cast<QLocalSocket*>(sender());
while (socket->canReadLine()) {
const QByteArray message = socket->readLine().trimmed();
messageReceived(socket, message);
} }
} }
void SMSubServer::deleteSocket() void SMSubServer::deleteSocket()
{ {
// Delete socket and remove from index // Delete socket and remove from index
QLocalSocket *socket = (QLocalSocket*)sender(); QObject *socket = sender();
sockets.removeAll(socket); sockets.removeAll(socket);
socket->deleteLater(); socket->deleteLater();
} }
void SMSubServer::debugOutput(QLocalSocket *socket, const QByteArray &message) void SMSubServer::debugOutput(QObject *socket, const QByteArray &message)
{ {
// Only send debug messages when the client opted-in // Only send debug messages when the client opted-in
const QVariant variant = socket->property("ReceiveDbgMsg"); const QVariant variant = socket->property("ReceiveDbgMsg");
if (unlikely(variant.type() == QVariant::Bool)) { if (unlikely(variant.type() == QVariant::Bool)) {
bool receiveDbgMsg = variant.toBool(); bool receiveDbgMsg = variant.toBool();
if (likely(receiveDbgMsg)) { if (likely(receiveDbgMsg)) {
socket->write(message + '\n'); sendMessage(socket, message + '\n');
} }
} }
} }
@ -147,20 +205,32 @@ void SMSubServer::debugOutput(QLocalSocket *socket, const QByteArray &message)
void SMSubServer::writeOutput(const QByteArray &output) void SMSubServer::writeOutput(const QByteArray &output)
{ {
// Read process output when client opted-in for log // Read process output when client opted-in for log
QVector<QLocalSocket*>::const_iterator it = sockets.constBegin(); QVector<QObject*>::const_iterator it = sockets.constBegin();
QVector<QLocalSocket*>::const_iterator end = sockets.constEnd(); QVector<QObject*>::const_iterator end = sockets.constEnd();
while (it != end) { while (it != end) {
const QVariant variant = (*it)->property("ReceiveLog"); const QVariant variant = (*it)->property("ReceiveLog");
if (unlikely(variant.type() == QVariant::Bool)) { if (unlikely(variant.type() == QVariant::Bool)) {
bool receiveLog = variant.toBool(); bool receiveLog = variant.toBool();
if (likely(receiveLog)) { if (likely(receiveLog)) {
(*it)->write(output); sendMessage(*it, output);
} }
} }
it++; it++;
} }
} }
void SMSubServer::sendMessage(QObject *socket, const QByteArray &message)
{
if (likely(type == ServerType::Local)) {
QLocalSocket *localSocket = static_cast<QLocalSocket*>(socket);
localSocket->write(message);
}
else if (type == ServerType::WebSocket) {
QWebSocket *webSocket = static_cast<QWebSocket*>(socket);
webSocket->sendBinaryMessage(message);
}
}
void SMSubServer::registerToken(const QString &token) void SMSubServer::registerToken(const QString &token)
{ {
// Register temporary token for a secure remote connection // Register temporary token for a secure remote connection

View file

@ -19,8 +19,10 @@
#ifndef SMSUBSERVER_H #ifndef SMSUBSERVER_H
#define SMSUBSERVER_H #define SMSUBSERVER_H
#include <QWebSocketServer>
#include <QLocalServer> #include <QLocalServer>
#include <QLocalSocket> #include <QLocalSocket>
#include <QWebSocket>
#include <QObject> #include <QObject>
struct SMSubServerSettings struct SMSubServerSettings
@ -29,26 +31,36 @@ struct SMSubServerSettings
bool isLocal; bool isLocal;
}; };
class SMSubServer : public QLocalServer class SMSubServer : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
SMSubServer(SMSubServerSettings *serverSettings, const QString &socket); SMSubServer(SMSubServerSettings *serverSettings, const QString &socket);
SMSubServer(SMSubServerSettings *serverSettings, const QString &serverName, const quint16 &port);
bool isListening();
enum ServerType { Local, WebSocket };
Q_ENUM(ServerType)
public slots: public slots:
void writeOutput(const QByteArray &output); void writeOutput(const QByteArray &output);
void registerToken(const QString &token); void registerToken(const QString &token);
private slots: private slots:
void incomingConnection(quintptr socketDescriptor); void wsMessageReceived(const QByteArray &message);
void lsReadyRead();
void newConnection();
void deleteSocket(); void deleteSocket();
void readyRead();
private: private:
inline void debugOutput(QLocalSocket *socket, const QByteArray &message); inline void debugOutput(QObject *socket, const QByteArray &message);
inline void sendMessage(QObject *socket, const QByteArray &message);
void messageReceived(QObject *socket, const QByteArray &message);
SMSubServerSettings *serverSettings; SMSubServerSettings *serverSettings;
QVector<QLocalSocket*> sockets; QVector<QObject*> sockets;
QVector<QString> tokens; QVector<QString> tokens;
ServerType type;
QObject *server;
signals: signals:
void tokenRegistered(const QString &password); void tokenRegistered(const QString &password);

View file

@ -79,7 +79,7 @@ int main(int argc, char *argv[])
{ {
QCoreApplication a(argc, argv); QCoreApplication a(argc, argv);
a.setApplicationName("Server Manager Subprocess"); a.setApplicationName("Server Manager Subprocess");
a.setApplicationVersion("0.2.1"); a.setApplicationVersion("0.3");
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
catchUnixSignals({SIGINT, SIGHUP, SIGQUIT, SIGTERM}); catchUnixSignals({SIGINT, SIGHUP, SIGQUIT, SIGTERM});
@ -105,6 +105,9 @@ int main(int argc, char *argv[])
#endif #endif
commandLineParser.addOption(subprocessSocket); commandLineParser.addOption(subprocessSocket);
QCommandLineOption subprocessRemotePort("rport", "WebSockets port used for remote communication.", "rport");
commandLineParser.addOption(subprocessRemotePort);
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
QCommandLineOption subprocessRemoteSocket(QStringList() << "rsock" << "rsocket", "IPC socket used for remote communication.", "rsock"); QCommandLineOption subprocessRemoteSocket(QStringList() << "rsock" << "rsocket", "IPC socket used for remote communication.", "rsock");
#else #else
@ -122,6 +125,15 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
if (unlikely(commandLineParser.isSet(subprocessRemotePort) && commandLineParser.isSet(subprocessRemoteSocket))) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "You can't define a WebSockets port and a IPC socket at same time!" << endl;
#else
QTextStream(stderr) << "You can't define a WebSockets port and a Unix socket at same time!" << endl;
#endif
return 1;
}
bool timeoutSet = false; bool timeoutSet = false;
int termTimeout = 60000; int termTimeout = 60000;
if (unlikely(commandLineParser.isSet(processTimeout))) { if (unlikely(commandLineParser.isSet(processTimeout))) {
@ -239,13 +251,29 @@ int main(int argc, char *argv[])
rsocket = commandLineParser.value(subprocessRemoteSocket); rsocket = commandLineParser.value(subprocessRemoteSocket);
} }
bool rportSet = false;
quint16 rport;
if (unlikely(commandLineParser.isSet(subprocessRemotePort))) {
bool ok;
rport = commandLineParser.value(subprocessRemotePort).toUShort(&ok);
if (!ok) {
QTextStream(stderr) << "WebSockets port is not valid!" << endl;
return 1;
}
else {
rportSet = true;
}
}
SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout);
SMSubServerSettings remoteSettings; SMSubServerSettings remoteSettings;
remoteSettings.canRegister = false; remoteSettings.canRegister = false;
remoteSettings.isLocal = false; remoteSettings.isLocal = false;
SMSubServer subRemote(&remoteSettings, rsocket);
if (unlikely(!rsocket.isEmpty())) { if (unlikely(!rsocket.isEmpty())) {
if (unlikely(!subRemote.isListening())) { SMSubServer *subRemote = new SMSubServer(&remoteSettings, rsocket);
if (unlikely(!subRemote->isListening())) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start remote IPC socket!" << endl; QTextStream(stderr) << "Failed to start remote IPC socket!" << endl;
#else #else
@ -254,27 +282,35 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
localSettings.canRegister = true; localSettings.canRegister = true;
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput);
QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
}
else if (unlikely(rportSet)) {
SMSubServer *subRemote = new SMSubServer(&remoteSettings, QString(), rport);
if (unlikely(!subRemote->isListening())) {
QTextStream(stderr) << "Failed to start remote WebSockets server!" << endl;
return 1;
}
localSettings.canRegister = true;
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput);
QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
} }
else { else {
localSettings.canRegister = false; localSettings.canRegister = false;
} }
SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subLocal, &SMSubServer::writeOutput); QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subLocal, &SMSubServer::writeOutput);
QObject::connect(&subLocal, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput); QObject::connect(&subLocal, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(&subLocal, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess); QObject::connect(&subLocal, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(&subLocal, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess); QObject::connect(&subLocal, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(&a, &QCoreApplication::aboutToQuit, &subProcess, &SMSubProcess::aboutToQuit); QObject::connect(&a, &QCoreApplication::aboutToQuit, &subProcess, &SMSubProcess::aboutToQuit);
if (unlikely(!rsocket.isEmpty())) {
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, &subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subRemote, &SMSubServer::writeOutput);
QObject::connect(&subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(&subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(&subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
}
subProcess.start(); subProcess.start();
return a.exec(); return a.exec();

View file

@ -17,7 +17,7 @@
############################################################################### ###############################################################################
QT -= gui QT -= gui
QT += network QT += network websockets
CONFIG += c++11 console CONFIG += c++11 console
CONFIG -= app_bundle CONFIG -= app_bundle