Compare commits

...

11 Commits

Author SHA1 Message Date
Syping d37369ad4f add AutoStart option, Last Start and Last Stop 2024-04-25 23:11:46 +02:00
Syping 95db23458f add KeepAlive, Status and Buffered Reads 2023-08-09 20:58:21 +02:00
Syping 529a4a8be9 improve debugging, fix likely mess 2023-03-20 08:28:37 +01:00
Syping 684e3962de envMode now finally working 2021-07-08 02:57:49 +02:00
Syping 60f3937b7b Quality of Life improvements 2021-07-07 23:47:24 +02:00
Syping d2aed1ef6e more missing errors 2020-10-16 06:32:34 +02:00
Syping 866f0f1874 added custom argument parser 2020-10-16 06:29:55 +02:00
Syping d96bc26b97 add environment value parsing 2020-10-16 05:38:18 +02:00
Syping a9fb05c5a9 Fix Qt 5.15 deprecations 2020-10-14 23:14:33 +02:00
Syping 2cef92e61f improve security 2020-09-19 09:47:02 +02:00
Syping d4a25b8346 add WebSockets support 2020-09-19 09:31:57 +02:00
8 changed files with 1192 additions and 724 deletions

View File

@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.5)
project(smsub LANGUAGES CXX)
project(smsub LANGUAGES CXX VERSION 0.8)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
@ -8,10 +8,16 @@ set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt5 COMPONENTS Network REQUIRED)
set(FORCE_QT_VERSION "" CACHE STRING "Force Qt Version")
if(FORCE_QT_VERSION)
set(QT_VERSION_MAJOR ${FORCE_QT_VERSION})
else()
find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED)
endif()
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Network WebSockets REQUIRED)
set(SMSUB_SOURCES
main.cpp
@ -30,6 +36,6 @@ add_executable(smsub
${SMSUB_SOURCES}
)
target_link_libraries(smsub PRIVATE Qt5::Network)
target_link_libraries(smsub PRIVATE Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::WebSockets)
install(TARGETS smsub DESTINATION bin)

View File

@ -1,106 +1,134 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <QCoreApplication>
#include <QTextStream>
#include "SMSubProcess.h"
#include "smsub.h"
SMSubProcess::SMSubProcess(const QString &executable, const QStringList &arguments, const QString &workingDirectory, const int &termTimeout) :
termTimeout(termTimeout)
{
// Set process executable, arguments and working directory
process.setProgram(executable);
process.setArguments(arguments);
process.setWorkingDirectory(workingDirectory);
// stdout and stderr in same IO stream
process.setProcessChannelMode(QProcess::MergedChannels);
// Connect process signal handlers
QObject::connect(&process, &QProcess::readyRead, this, &SMSubProcess::readyRead);
QObject::connect(&process, &QProcess::errorOccurred, this, &SMSubProcess::processError);
QObject::connect(&process, QOverload<int>::of(&QProcess::finished), this, &SMSubProcess::processExit);
}
void SMSubProcess::start()
{
process.start(QIODevice::ReadWrite);
}
void SMSubProcess::readyRead()
{
// Read process output and emit event
while (process.canReadLine()) {
const QByteArray readData = process.readLine().trimmed();
emit outputWritten(readData + '\n');
}
}
void SMSubProcess::processExit(int exitCode)
{
// Exit with the same exit code as the process
emit processStopped();
QCoreApplication::exit(exitCode);
}
void SMSubProcess::processError(QProcess::ProcessError error)
{
// Handle process errors
if (likely(error == QProcess::FailedToStart)) {
QTextStream(stderr) << "Process failed to start!" << endl;
QCoreApplication::exit(1);
}
else if (error == QProcess::UnknownError) {
QTextStream(stderr) << "Unknown error occurred!" << endl;
QCoreApplication::exit(1);
}
}
void SMSubProcess::aboutToQuit()
{
// Main process terminated, terminate subprocess with set timeout
if (process.state() == QProcess::Running) {
process.terminate();
if (!process.waitForFinished(termTimeout)) {
QTextStream(stderr) << "Failed to terminate process!" << endl;
}
}
}
void SMSubProcess::killProcess()
{
// Kill process as requested
if (process.state() == QProcess::Running) {
process.kill();
}
}
void SMSubProcess::stopProcess()
{
// Terminate process as requested
if (process.state() == QProcess::Running) {
process.terminate();
}
}
void SMSubProcess::writeInput(const QByteArray &input)
{
// Write input from Unix/IPC socket to process
process.write(input);
}
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <QCoreApplication>
#include <QTextStream>
#include <QDateTime>
#include "SMSubProcess.h"
#include "smsub.h"
SMSubProcess::SMSubProcess(const QString &executable, const QStringList &arguments, const QString &workingDirectory, const int &termTimeout, const bool &keepAlive) :
termTimeout(termTimeout), keepAlive(keepAlive)
{
// Set process executable, arguments and working directory
process.setProgram(executable);
process.setArguments(arguments);
process.setWorkingDirectory(workingDirectory);
// manage input channel
process.setInputChannelMode(QProcess::ManagedInputChannel);
// stdout and stderr in same IO stream
process.setProcessChannelMode(QProcess::MergedChannels);
// Connect process signal handlers
QObject::connect(&process, &QProcess::readyRead, this, &SMSubProcess::readyRead);
QObject::connect(&process, &QProcess::errorOccurred, this, &SMSubProcess::processError);
QObject::connect(&process, &QProcess::started, this, [=]() {
QTextStream(stderr) << "Subprocess started!" << smsub_endl;
emit statusUpdated(true, QDateTime::currentDateTimeUtc().toSecsSinceEpoch());
});
QObject::connect(&process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [=](int exitCode) {
QTextStream(stderr) << "Subprocess exited!" << smsub_endl;
// Exit with the same exit code as the process
emit statusUpdated(false, QDateTime::currentDateTimeUtc().toSecsSinceEpoch());
if (!keepAlive)
QCoreApplication::exit(exitCode);
});
}
void SMSubProcess::readyRead()
{
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O RR!" << smsub_endl;
#endif
// Read process output and emit event
#ifdef SMSUB_BUFFERED_READS
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O W!" << smsub_endl;
#endif
const QByteArray readData = process.read(1024);
if (!readData.isEmpty())
emit outputWritten(readData);
#else
while (process.canReadLine()) {
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O WL!" << smsub_endl;
#endif
const QByteArray readData = process.readLine().trimmed();
emit outputWritten(readData + '\n');
}
#endif
}
void SMSubProcess::processError(QProcess::ProcessError error)
{
// Handle process errors
if (Q_LIKELY(error == QProcess::FailedToStart)) {
QTextStream(stderr) << "Process failed to start!" << smsub_endl;
if (!keepAlive)
QCoreApplication::exit(1);
}
else if (error == QProcess::UnknownError) {
QTextStream(stderr) << "Unknown error occurred!" << smsub_endl;
if (!keepAlive)
QCoreApplication::exit(1);
}
}
void SMSubProcess::aboutToQuit()
{
// Main process terminated, terminate subprocess with set timeout
if (process.state() == QProcess::Running) {
process.terminate();
if (!process.waitForFinished(termTimeout)) {
QTextStream(stderr) << "Failed to terminate process!" << smsub_endl;
}
}
}
void SMSubProcess::startProcess()
{
// Start process as requested
if (process.state() == QProcess::NotRunning)
process.start(QIODevice::ReadWrite);
}
void SMSubProcess::stopProcess()
{
// Terminate process as requested
if (process.state() == QProcess::Running)
process.terminate();
}
void SMSubProcess::killProcess()
{
// Kill process as requested
if (process.state() == QProcess::Running)
process.kill();
}
void SMSubProcess::writeInput(const QByteArray &input)
{
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O IN!" << smsub_endl;
#endif
// Write input from Unix/IPC socket to process
if (process.state() == QProcess::Running)
process.write(input);
}

View File

@ -1,53 +1,52 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SMSUBPROCESS_H
#define SMSUBPROCESS_H
#include <QObject>
#include <QProcess>
class SMSubProcess : public QObject
{
Q_OBJECT
public:
SMSubProcess(const QString &executable, const QStringList &arguments, const QString& workingDirectory, const int &termTimeout = 60000);
void start();
private:
QProcess process;
int termTimeout;
public slots:
void aboutToQuit();
void killProcess();
void stopProcess();
void writeInput(const QByteArray &input);
private slots:
void readyRead();
void processExit(int exitCode);
void processError(QProcess::ProcessError error);
signals:
void outputWritten(const QByteArray &output);
void processStopped();
};
#endif // SMSUBPROCESS_H
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SMSUBPROCESS_H
#define SMSUBPROCESS_H
#include <QObject>
#include <QProcess>
class SMSubProcess : public QObject
{
Q_OBJECT
public:
SMSubProcess(const QString &executable, const QStringList &arguments, const QString &workingDirectory, const int &termTimeout = 60000, const bool &keepAlive = false);
private:
QProcess process;
int termTimeout;
bool keepAlive;
public slots:
void aboutToQuit();
void startProcess();
void stopProcess();
void killProcess();
void writeInput(const QByteArray &input);
private slots:
void readyRead();
void processError(QProcess::ProcessError error);
signals:
void outputWritten(const QByteArray &output);
void statusUpdated(const bool status, const qint64 time);
};
#endif // SMSUBPROCESS_H

View File

@ -1,171 +1,284 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <QCoreApplication>
#include <QTimer>
#include <QUuid>
#include "SMSubServer.h"
#include "smsub.h"
SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &socket) : serverSettings(serverSettings)
{
setSocketOptions(QLocalServer::UserAccessOption | QLocalServer::GroupAccessOption);
listen(socket);
}
void SMSubServer::incomingConnection(quintptr socketDescriptor)
{
QLocalSocket *socket = new QLocalSocket();
socket->setSocketDescriptor(socketDescriptor);
QObject::connect(socket, &QLocalSocket::readyRead, this, &SMSubServer::readyRead);
QObject::connect(socket, &QLocalSocket::disconnected, this, &SMSubServer::deleteSocket);
// Set authentication state
if (serverSettings->isLocal) {
socket->setProperty("Authenticated", true);
sockets << socket;
}
else {
socket->setProperty("Authenticated", false);
}
// Initial open writing
socket->write(QString("SMSub Version %1\n").arg(QCoreApplication::applicationVersion()).toUtf8());
}
void SMSubServer::readyRead()
{
// 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
if (likely(isAuthenticated)) {
if (readData.startsWith("+dbg")) {
socket->setProperty("ReceiveDbgMsg", true);
socket->write("Debug messages enabled!\n");
}
else if (readData.startsWith("-dbg")) {
socket->setProperty("ReceiveDbgMsg", false);
socket->write("Debug messages disabled!\n");
}
else if (readData.startsWith("+log")) {
socket->setProperty("ReceiveLog", true);
debugOutput(socket, "Log output enabled!");
}
else if (readData.startsWith("-log")) {
socket->setProperty("ReceiveLog", false);
debugOutput(socket, "Log output disabled!");
}
else if (readData.startsWith("+reg")) {
if (likely(serverSettings->canRegister)) {
QByteArray authUuid = QUuid::createUuid().toByteArray(QUuid::Id128);
authUuid = QByteArray::fromHex(authUuid).toBase64(QByteArray::OmitTrailingEquals);
emit tokenRegistered(QString::fromUtf8(authUuid));
socket->write("Token: " + authUuid + '\n');
}
else {
socket->write("Permission denied!\n");
}
}
else if (readData.startsWith("kill")) {
emit killRequested();
debugOutput(socket, "Killing server!");
}
else if (readData.startsWith("stop")) {
emit stopRequested();
debugOutput(socket, "Stopping server!");
}
else if (readData.startsWith("wl")) {
const QByteArray writeData = readData.mid(3);
emit inputWritten(writeData + '\n');
debugOutput(socket, "Write line \"" + writeData + "\"!");
}
else if (readData.startsWith("w")) {
const QByteArray writeData = readData.mid(2);
emit inputWritten(writeData);
debugOutput(socket, "Write \"" + writeData + "\"!");
}
}
else {
// Authenticate when token is valid, otherwise disconnect
if (unlikely(tokens.contains(QString::fromUtf8(readData)))) {
// Set client as authenticated and add it to vector
socket->setProperty("Authenticated", true);
socket->write("Login successful!\n");
isAuthenticated = true;
sockets << socket;
}
else {
// Stop receiving data and disconnect socket
QObject::disconnect(socket, &QLocalSocket::readyRead, this, &SMSubServer::readyRead);
socket->write("Incorrect token!\n");
socket->disconnectFromServer();
return;
}
}
}
}
void SMSubServer::deleteSocket()
{
// Delete socket and remove from index
QLocalSocket *socket = (QLocalSocket*)sender();
sockets.removeAll(socket);
socket->deleteLater();
}
void SMSubServer::debugOutput(QLocalSocket *socket, const QByteArray &message)
{
// Only send debug messages when the client opted-in
const QVariant variant = socket->property("ReceiveDbgMsg");
if (unlikely(variant.type() == QVariant::Bool)) {
bool receiveDbgMsg = variant.toBool();
if (likely(receiveDbgMsg)) {
socket->write(message + '\n');
}
}
}
void SMSubServer::writeOutput(const QByteArray &output)
{
// Read process output when client opted-in for log
QVector<QLocalSocket*>::const_iterator it = sockets.constBegin();
QVector<QLocalSocket*>::const_iterator end = sockets.constEnd();
while (it != end) {
const QVariant variant = (*it)->property("ReceiveLog");
if (unlikely(variant.type() == QVariant::Bool)) {
bool receiveLog = variant.toBool();
if (likely(receiveLog)) {
(*it)->write(output);
}
}
it++;
}
}
void SMSubServer::registerToken(const QString &token)
{
// Register temporary token for a secure remote connection
tokens << token;
QTimer::singleShot(30000, [this, token]() {
tokens.removeAll(token);
});
}
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <QCoreApplication>
#include <QTimer>
#include <QUuid>
#include "SMSubServer.h"
#include "smsub.h"
SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &socket) : serverSettings(serverSettings)
{
QLocalServer *localServer = new QLocalServer(this);
localServer->setSocketOptions(QLocalServer::UserAccessOption | QLocalServer::GroupAccessOption);
localServer->listen(socket);
QObject::connect(localServer, &QLocalServer::newConnection, this, &SMSubServer::newConnection);
type = ServerType::Local;
server = localServer;
status = false;
startTime = QDateTime::currentDateTimeUtc().toSecsSinceEpoch();
stopTime = startTime;
}
SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &serverName, const quint16 &port) : serverSettings(serverSettings)
{
QWebSocketServer *webSocketServer = new QWebSocketServer(serverName, QWebSocketServer::NonSecureMode, this);
webSocketServer->listen(QHostAddress::LocalHost, port);
QObject::connect(webSocketServer, &QWebSocketServer::newConnection, this, &SMSubServer::newConnection);
type = ServerType::WebSocket;
server = webSocketServer;
status = false;
startTime = QDateTime::currentDateTimeUtc().toSecsSinceEpoch();
stopTime = startTime;
}
bool SMSubServer::isListening()
{
if (Q_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 (Q_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;
QTextStream(stderr) << "LocalSocket connected!" << smsub_endl;
}
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;
QTextStream(stderr) << QString("WebSocket %1:%2 connected!").arg(webSocket->peerName(), QString::number(webSocket->peerPort())) << smsub_endl;
}
else {
// Just for being sure
return;
}
// Set authentication state
if (serverSettings->isLocal) {
socket->setProperty("Authenticated", true);
sockets << socket;
}
else {
socket->setProperty("Authenticated", false);
}
}
bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
{
// Only allow commands being sent if authenticated
const bool isAuthenticated = socket->property("Authenticated").toBool();
if (Q_LIKELY(isAuthenticated)) {
if (message.startsWith("+dbg")) {
socket->setProperty("ReceiveDbgMsg", true);
sendMessage(socket, "Debug messages enabled!\n");
}
else if (message.startsWith("-dbg")) {
socket->setProperty("ReceiveDbgMsg", false);
sendMessage(socket, "Debug messages disabled!\n");
}
else if (message.startsWith("+log")) {
socket->setProperty("ReceiveLog", true);
debugOutput(socket, "Log output enabled!");
}
else if (message.startsWith("-log")) {
socket->setProperty("ReceiveLog", false);
debugOutput(socket, "Log output disabled!");
}
else if (message.startsWith("+reg")) {
if (Q_LIKELY(serverSettings->canRegister)) {
QByteArray authUuid = QUuid::createUuid().toByteArray(QUuid::Id128);
authUuid = QByteArray::fromHex(authUuid).toBase64(QByteArray::OmitTrailingEquals);
emit tokenRegistered(QString::fromUtf8(authUuid));
sendMessage(socket, "Token: " + authUuid + '\n');
}
else {
sendMessage(socket, "Permission denied!\n");
}
}
else if (message.startsWith("status")) {
if (status) {
sendMessage(socket, QString("Status: on\nLast Start: %1\nLast Stop: %2\n").arg(QString::number(startTime), QString::number(stopTime)).toUtf8());
}
else {
sendMessage(socket, QString("Status: off\nLast Start: %1\nLast Stop: %2\n").arg(QString::number(startTime), QString::number(stopTime)).toUtf8());
}
}
else if (message.startsWith("start")) {
emit startRequested();
debugOutput(socket, "Starting server!");
}
else if (message.startsWith("stop")) {
emit stopRequested();
debugOutput(socket, "Stopping server!");
}
else if (message.startsWith("kill")) {
emit killRequested();
debugOutput(socket, "Killing server!");
}
else if (message.startsWith("quit")) {
QTimer::singleShot(0, qApp, &QCoreApplication::quit);
debugOutput(socket, "Qutting smsub!");
}
else if (message.startsWith("wl")) {
const QByteArray writeData = message.mid(3);
emit inputWritten(writeData + '\n');
debugOutput(socket, "Write line \"" + writeData + "\"!");
}
else if (message.startsWith("w")) {
const QByteArray writeData = message.mid(2);
emit inputWritten(writeData);
debugOutput(socket, "Write \"" + writeData + "\"!");
}
}
else {
// Authenticate when token is valid, otherwise disconnect
if (Q_UNLIKELY(tokens.contains(QString::fromUtf8(message)))) {
// Set client as authenticated and add it to vector
socket->setProperty("Authenticated", true);
sendMessage(socket, "Login successful!\n");
sockets << socket;
}
else {
// Stop receiving data and disconnect socket
if (Q_LIKELY(type == ServerType::Local)) {
QLocalSocket *localSocket = static_cast<QLocalSocket*>(socket);
QObject::disconnect(localSocket, &QLocalSocket::readyRead, this, &SMSubServer::lsReadyRead);
localSocket->write("Incorrect token!\n");
localSocket->disconnectFromServer();
return false;
}
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 false;
}
}
}
return true;
}
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());
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "LocalSocket I/O RR!" << smsub_endl;
#endif
while (socket->canReadLine()) {
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "LocalSocket I/O WL!" << smsub_endl;
#endif
const QByteArray message = socket->readLine().trimmed();
if (!messageReceived(socket, message))
return;
}
}
void SMSubServer::deleteSocket()
{
// Delete socket and remove from index
QObject *socket = sender();
sockets.removeAll(socket);
socket->deleteLater();
}
void SMSubServer::debugOutput(QObject *socket, const QByteArray &message)
{
// Only send debug messages when the client opted-in
const QVariant variant = socket->property("ReceiveDbgMsg");
#if QT_VERSION >= 0x060000
if (Q_UNLIKELY(variant.typeId() == QMetaType::Bool)) {
#else
if (Q_UNLIKELY(variant.type() == QVariant::Bool)) {
#endif
bool receiveDbgMsg = variant.toBool();
if (Q_LIKELY(receiveDbgMsg)) {
sendMessage(socket, message + '\n');
}
}
}
void SMSubServer::writeOutput(const QByteArray &output)
{
// Read process output when client opted-in for log
for (auto it = sockets.constBegin(); it != sockets.constEnd(); it++) {
const QVariant variant = (*it)->property("ReceiveLog");
#if QT_VERSION >= 0x060000
if (Q_UNLIKELY(variant.typeId() == QMetaType::Bool)) {
#else
if (Q_UNLIKELY(variant.type() == QVariant::Bool)) {
#endif
bool receiveLog = variant.toBool();
if (Q_LIKELY(receiveLog)) {
sendMessage(*it, output);
}
}
}
}
void SMSubServer::sendMessage(QObject *socket, const QByteArray &message)
{
if (Q_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)
{
// Register temporary token for a secure remote connection
tokens << token;
QTimer::singleShot(30000, this, [=]() {
tokens.removeAll(token);
});
}
void SMSubServer::statusUpdated(const bool status_, const qint64 time)
{
status = status_;
status ? (startTime = time) : (stopTime = time);
}

View File

@ -1,60 +1,77 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SMSUBSERVER_H
#define SMSUBSERVER_H
#include <QLocalServer>
#include <QLocalSocket>
#include <QObject>
struct SMSubServerSettings
{
bool canRegister;
bool isLocal;
};
class SMSubServer : public QLocalServer
{
Q_OBJECT
public:
SMSubServer(SMSubServerSettings *serverSettings, const QString &socket);
public slots:
void writeOutput(const QByteArray &output);
void registerToken(const QString &token);
private slots:
void incomingConnection(quintptr socketDescriptor);
void deleteSocket();
void readyRead();
private:
inline void debugOutput(QLocalSocket *socket, const QByteArray &message);
SMSubServerSettings *serverSettings;
QVector<QLocalSocket*> sockets;
QVector<QString> tokens;
signals:
void tokenRegistered(const QString &password);
void inputWritten(const QByteArray &input);
void killRequested();
void stopRequested();
};
#endif // SMSUBSERVER_H
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SMSUBSERVER_H
#define SMSUBSERVER_H
#include <QWebSocketServer>
#include <QLocalServer>
#include <QLocalSocket>
#include <QWebSocket>
#include <QObject>
struct SMSubServerSettings
{
bool canRegister;
bool isLocal;
};
class SMSubServer : public QObject
{
Q_OBJECT
public:
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:
void writeOutput(const QByteArray &output);
void registerToken(const QString &token);
void statusUpdated(const bool status, const qint64 time);
private slots:
void wsMessageReceived(const QByteArray &message);
void lsReadyRead();
void newConnection();
void deleteSocket();
private:
inline void debugOutput(QObject *socket, const QByteArray &message);
inline void sendMessage(QObject *socket, const QByteArray &message);
bool messageReceived(QObject *socket, const QByteArray &message);
SMSubServerSettings *serverSettings;
QVector<QObject*> sockets;
QVector<QString> tokens;
qint64 startTime;
qint64 stopTime;
ServerType type;
QObject *server;
bool status;
signals:
void tokenRegistered(const QString &password);
void inputWritten(const QByteArray &input);
void startRequested();
void stopRequested();
void killRequested();
};
#endif // SMSUBSERVER_H

876
main.cpp
View File

@ -1,281 +1,595 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextStream>
#include <QJsonValue>
#include <QJsonArray>
#include <QFileInfo>
#include <QFile>
#include "SMSubProcess.h"
#include "SMSubServer.h"
#include "smsub.h"
#ifdef Q_OS_UNIX
#include <initializer_list>
#include "signal.h"
#include "unistd.h"
#endif
#ifdef Q_OS_UNIX
void catchUnixSignals(std::initializer_list<int> quitSignals) {
auto handler = [](int sig) -> void {
QString unixSignal;
switch (sig) {
case SIGINT:
unixSignal = QLatin1String("SIGINT");
break;
case SIGHUP:
unixSignal = QLatin1String("SIGHUP");
break;
case SIGQUIT:
unixSignal = QLatin1String("SIGQUIT");
break;
case SIGTERM:
unixSignal = QLatin1String("SIGTERM");
break;
default:
unixSignal = QString::number(sig);
}
QTextStream(stderr) << "Received Unix signal: " << unixSignal << endl;
QCoreApplication::quit();
};
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (int sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (int sig : quitSignals)
sigaction(sig, &sa, nullptr);
}
#endif
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setApplicationName("Server Manager Subprocess");
a.setApplicationVersion("0.2.1");
#ifdef Q_OS_UNIX
catchUnixSignals({SIGINT, SIGHUP, SIGQUIT, SIGTERM});
#endif
QCommandLineParser commandLineParser;
commandLineParser.addHelpOption();
commandLineParser.addVersionOption();
QCommandLineOption processManifest("json", "JSON process manifest.", "json");
commandLineParser.addOption(processManifest);
QCommandLineOption processExecutable(QStringList() << "exec" << "executable", "Process executable to run.", "exec");
commandLineParser.addOption(processExecutable);
QCommandLineOption processArguments(QStringList() << "args" << "arguments", "Arguments given to process.", "args");
commandLineParser.addOption(processArguments);
#ifdef Q_OS_WIN
QCommandLineOption subprocessSocket(QStringList() << "sock" << "socket", "IPC socket used for local communication.", "sock");
#else
QCommandLineOption subprocessSocket(QStringList() << "sock" << "socket", "Unix socket used for local communication.", "sock");
#endif
commandLineParser.addOption(subprocessSocket);
#ifdef Q_OS_WIN
QCommandLineOption subprocessRemoteSocket(QStringList() << "rsock" << "rsocket", "IPC socket used for remote communication.", "rsock");
#else
QCommandLineOption subprocessRemoteSocket(QStringList() << "rsock" << "rsocket", "Unix socket used for remote communication.", "rsock");
#endif
commandLineParser.addOption(subprocessRemoteSocket);
QCommandLineOption processTimeout("timeout", "SMSub termination timeout.", "timeout");
commandLineParser.addOption(processTimeout);
commandLineParser.process(a);
if (unlikely(commandLineParser.isSet(processManifest) && commandLineParser.isSet(processExecutable))) {
QTextStream(stderr) << "You can't define a Process executable and a JSON process manifest at the same time!" << endl;
return 1;
}
bool timeoutSet = false;
int termTimeout = 60000;
if (unlikely(commandLineParser.isSet(processTimeout))) {
bool ok;
const int _termTimeout = commandLineParser.value(processTimeout).toInt(&ok);
if (ok) {
termTimeout = _termTimeout;
timeoutSet = true;
}
}
QString executable;
QString workingDirectory;
QStringList argumentList;
if (likely(commandLineParser.isSet(processManifest))) {
QFile manifestFile(commandLineParser.value(processManifest));
if (likely(manifestFile.open(QIODevice::ReadOnly))) {
const QByteArray jsonData = manifestFile.readAll();
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
QJsonObject jsonObject = jsonDocument.object();
if (likely(jsonObject.contains("Executable"))) {
const QJsonValue jsonExecutable = jsonObject.value("Executable");
if (unlikely(!jsonExecutable.isString())) {
QTextStream(stderr) << "Executable is not a string in manifest, aborting!" << endl;
manifestFile.close();
return 1;
}
executable = jsonExecutable.toString();
}
else {
QTextStream(stderr) << "Executable is not defined in manifest, aborting!" << endl;
manifestFile.close();
return 1;
}
if (likely(jsonObject.contains("WorkingDirectory"))) {
const QJsonValue jsonWorkingDirectory = jsonObject.value("WorkingDirectory");
if (unlikely(!jsonWorkingDirectory.isString())) {
QTextStream(stderr) << "Working Directory is not a string in manifest, aborting!" << endl;
manifestFile.close();
return 1;
}
workingDirectory = jsonWorkingDirectory.toString();
}
else {
workingDirectory = QFileInfo(executable).absolutePath();
}
if (likely(jsonObject.contains("Arguments"))) {
const QJsonValue jsonArguments = jsonObject.value("Arguments");
if (likely(jsonArguments.isArray())) {
const QJsonArray jsonArray = jsonArguments.toArray();
QJsonArray::const_iterator it = jsonArray.constBegin();
QJsonArray::const_iterator end = jsonArray.constEnd();
while (it != end) {
argumentList << it->toString();
it++;
}
}
else {
QTextStream(stderr) << "Arguments is not a array in manifest, aborting!" << endl;
manifestFile.close();
return 1;
}
}
if (unlikely(!timeoutSet && jsonObject.contains("TerminationTimeout"))) {
const QJsonValue jsonTimeout = jsonObject.value("TerminationTimeout");
if (unlikely(!jsonTimeout.isDouble())) {
termTimeout = qRound(jsonTimeout.toDouble());
}
else {
QTextStream(stderr) << "Termination Timeout is not a number in manifest, aborting!" << endl;
return 1;
}
}
manifestFile.close();
}
}
else if (unlikely(commandLineParser.isSet(processArguments))) {
QTextStream(stderr) << "Arguments over command line are not supported yet!" << endl;
return 1;
}
QString socket;
if (likely(commandLineParser.isSet(subprocessSocket))) {
socket = commandLineParser.value(subprocessSocket);
}
else {
#ifdef Q_OS_WIN
QTextStream(stderr) << "You must define at least a local IPC socket!" << endl;
#else
QTextStream(stderr) << "You must define at least a local Unix socket!" << endl;
#endif
return 1;
}
SMSubServerSettings localSettings;
localSettings.isLocal = true;
SMSubServer subLocal(&localSettings, socket);
if (unlikely(!subLocal.isListening())) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start local IPC socket!" << endl;
#else
QTextStream(stderr) << "Failed to start local Unix socket!" << endl;
#endif
return 1;
}
QString rsocket;
if (unlikely(commandLineParser.isSet(subprocessRemoteSocket))) {
rsocket = commandLineParser.value(subprocessRemoteSocket);
}
SMSubServerSettings remoteSettings;
remoteSettings.canRegister = false;
remoteSettings.isLocal = false;
SMSubServer subRemote(&remoteSettings, rsocket);
if (unlikely(!rsocket.isEmpty())) {
if (unlikely(!subRemote.isListening())) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start remote IPC socket!" << endl;
#else
QTextStream(stderr) << "Failed to start remote Unix socket!" << endl;
#endif
return 1;
}
localSettings.canRegister = true;
}
else {
localSettings.canRegister = false;
}
SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subLocal, &SMSubServer::writeOutput);
QObject::connect(&subLocal, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(&subLocal, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(&subLocal, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
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();
return a.exec();
}
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextStream>
#include <QJsonValue>
#include <QJsonArray>
#include <QFileInfo>
#include <QFile>
#include "SMSubProcess.h"
#include "SMSubServer.h"
#include "smsub.h"
#ifdef Q_OS_UNIX
#include <initializer_list>
#include "signal.h"
#endif
#ifdef Q_OS_UNIX
void catchUnixSignals(std::initializer_list<int> quitSignals) {
auto handler = [](int sig) -> void {
QString unixSignal;
switch (sig) {
case SIGINT:
unixSignal = QLatin1String("SIGINT");
break;
case SIGHUP:
unixSignal = QLatin1String("SIGHUP");
break;
case SIGQUIT:
unixSignal = QLatin1String("SIGQUIT");
break;
case SIGTERM:
unixSignal = QLatin1String("SIGTERM");
break;
default:
unixSignal = QString::number(sig);
}
QTextStream(stderr) << "Received Unix signal: " << unixSignal << smsub_endl;
QCoreApplication::quit();
};
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (int sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (int sig : quitSignals)
sigaction(sig, &sa, nullptr);
}
#endif
QStringList parseStringArguments(const QString &string)
{
QString argument;
bool slashMode = false;
bool dQuoteMode = false;
bool sQuoteMode = false;
QStringList argumentList;
for (const QChar &strChar : string) {
if (!slashMode && !dQuoteMode && !sQuoteMode) {
if (strChar == ' ') {
if (!argument.isEmpty()) {
argumentList << argument;
argument.clear();
}
}
else if (strChar == '\"') {
dQuoteMode = true;
}
else if (strChar == '\'') {
sQuoteMode = true;
}
else if (strChar == '\\') {
slashMode = true;
}
else {
argument += strChar;
}
}
else if (slashMode) {
argument += strChar;
slashMode = false;
}
else if (dQuoteMode) {
if (strChar == '\"') {
dQuoteMode = false;
}
else {
argument += strChar;
}
}
else if (sQuoteMode) {
if (strChar == '\'') {
sQuoteMode = false;
}
else {
argument += strChar;
}
}
}
if (slashMode || dQuoteMode || sQuoteMode)
return QStringList();
if (!argument.isEmpty())
argumentList << argument;
return argumentList;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setApplicationName("Server Manager Subprocess");
a.setApplicationVersion("0.8");
#ifdef Q_OS_UNIX
catchUnixSignals({SIGINT, SIGHUP, SIGQUIT, SIGTERM});
#endif
bool rportSet = false;
bool autoStart = true;
bool keepAlive = false;
bool timeoutSet = false;
int termTimeout = 60000;
quint16 rport;
QString socket;
QString rsocket;
QString executable;
QString workingDirectory;
QStringList argumentList;
const QByteArray envEnvironmentMode = qgetenv("SMSUB_ENVIRONMENT_MODE");
const QByteArray envAutoStart = qgetenv("SMSUB_AUTOSTART");
const QByteArray envKeepAlive = qgetenv("SMSUB_KEEPALIVE");
const QByteArray envManifest = qgetenv("SMSUB_JSON");
const QByteArray envExecutable = qgetenv("SMSUB_EXEC");
const QByteArray envArguments = qgetenv("SMSUB_ARGS");
const QByteArray envSocket = qgetenv("SMSUB_SOCK");
const QByteArray envRemotePort = qgetenv("SMSUB_RPORT");
const QByteArray envRemoteSocket = qgetenv("SMSUB_RSOCK");
const QByteArray envTimeout = qgetenv("SMSUB_TIMEOUT");
const QByteArray envWorkDir = qgetenv("SMSUB_WORKDIR");
if (envEnvironmentMode == "1" || envEnvironmentMode.toLower() == "true" || envEnvironmentMode.toLower() == "yes") {
if (envExecutable.isEmpty() && envArguments.isEmpty()) {
QStringList arguments = a.arguments();
arguments.removeFirst();
executable = arguments.takeFirst();
argumentList = arguments;
}
else {
if (!envExecutable.isEmpty()) {
executable = QString::fromUtf8(envExecutable);
}
else {
QTextStream(stderr) << "Executable is not defined in environment, aborting!" << smsub_endl;
return 1;
}
if (!envArguments.isEmpty()) {
argumentList = parseStringArguments(QString::fromUtf8(envArguments));
if (argumentList.empty()) {
QTextStream(stderr) << "Arguments can't be parsed properly!" << smsub_endl;
return 1;
}
}
else {
QTextStream(stderr) << "Arguments are not defined in environment, aborting!" << smsub_endl;
return 1;
}
}
if (!envTimeout.isEmpty()) {
bool ok;
const int _termTimeout = envTimeout.toInt(&ok);
if (ok) {
termTimeout = _termTimeout;
timeoutSet = true;
}
else {
QTextStream(stderr) << "Termination timeout is not a number in environment, aborting!" << smsub_endl;
return 1;
}
}
if (!envAutoStart.isEmpty()) {
if (envAutoStart == "0" || envAutoStart.toLower() == "false" || envAutoStart.toLower() == "no") {
autoStart = false;
}
}
if (!envKeepAlive.isEmpty()) {
if (envKeepAlive == "1" || envKeepAlive.toLower() == "true" || envKeepAlive.toLower() == "yes") {
keepAlive = true;
}
}
if (!envWorkDir.isEmpty()) {
workingDirectory = QString::fromUtf8(envWorkDir);
}
else {
workingDirectory = QFileInfo(executable).absolutePath();
}
if (!envSocket.isEmpty()) {
socket = QString::fromUtf8(envSocket);
}
else {
#ifdef Q_OS_WIN
QTextStream(stderr) << "You must define at least a local IPC socket!" << smsub_endl;
#else
QTextStream(stderr) << "You must define at least a local Unix socket!" << smsub_endl;
#endif
return 1;
}
if (!envRemoteSocket.isEmpty()) {
rsocket = QString::fromUtf8(envRemoteSocket);
}
if (!envRemotePort.isEmpty()) {
bool ok;
const quint16 _rport = envRemotePort.toUShort(&ok);
if (ok) {
rport = _rport;
rportSet = true;
}
else {
QTextStream(stderr) << "WebSockets port is not valid in environment!" << smsub_endl;
return 1;
}
}
}
else {
QCommandLineParser commandLineParser;
commandLineParser.addHelpOption();
commandLineParser.addVersionOption();
QCommandLineOption processManifest("json", "JSON process manifest.", "json");
commandLineParser.addOption(processManifest);
QCommandLineOption processExecutable(QStringList() << "exec" << "executable", "Process executable to run.", "exec");
commandLineParser.addOption(processExecutable);
QCommandLineOption processArguments(QStringList() << "args" << "arguments", "Arguments given to process.", "args");
commandLineParser.addOption(processArguments);
#ifdef Q_OS_WIN
QCommandLineOption subprocessSocket(QStringList() << "sock" << "socket", "IPC socket used for local communication.", "sock");
#else
QCommandLineOption subprocessSocket(QStringList() << "sock" << "socket", "Unix socket used for local communication.", "sock");
#endif
commandLineParser.addOption(subprocessSocket);
QCommandLineOption subprocessRemotePort("rport", "WebSockets port used for remote communication.", "rport");
commandLineParser.addOption(subprocessRemotePort);
#ifdef Q_OS_WIN
QCommandLineOption subprocessRemoteSocket(QStringList() << "rsock" << "rsocket", "IPC socket used for remote communication.", "rsock");
#else
QCommandLineOption subprocessRemoteSocket(QStringList() << "rsock" << "rsocket", "Unix socket used for remote communication.", "rsock");
#endif
commandLineParser.addOption(subprocessRemoteSocket);
QCommandLineOption processTimeout("timeout", "SMSub termination timeout.", "timeout");
commandLineParser.addOption(processTimeout);
commandLineParser.process(a);
if (commandLineParser.isSet(processManifest) && commandLineParser.isSet(processExecutable) ||
!envManifest.isEmpty() && !envExecutable.isEmpty() ||
commandLineParser.isSet(processManifest) && !envExecutable.isEmpty() ||
!envManifest.isEmpty() && commandLineParser.isSet(processExecutable)) {
QTextStream(stderr) << "You can't define a Process executable and a JSON process manifest at the same time!" << smsub_endl;
return 1;
}
if (commandLineParser.isSet(processManifest) && commandLineParser.isSet(processArguments) ||
!envManifest.isEmpty() && !envArguments.isEmpty() ||
commandLineParser.isSet(processManifest) && !envArguments.isEmpty() ||
!envManifest.isEmpty() && commandLineParser.isSet(processArguments)) {
QTextStream(stderr) << "You can't define a Process arguments and a JSON process manifest at the same time!" << smsub_endl;
return 1;
}
if (commandLineParser.isSet(subprocessRemotePort) && commandLineParser.isSet(subprocessRemoteSocket) ||
!envRemotePort.isEmpty() && !envRemoteSocket.isEmpty() ||
commandLineParser.isSet(subprocessRemotePort) && !envRemoteSocket.isEmpty() ||
!envRemotePort.isEmpty() && commandLineParser.isSet(subprocessRemoteSocket)) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "You can't define a WebSockets port and a IPC socket at same time!" << smsub_endl;
#else
QTextStream(stderr) << "You can't define a WebSockets port and a Unix socket at same time!" << smsub_endl;
#endif
return 1;
}
if (commandLineParser.isSet(processTimeout)) {
bool ok;
const int _termTimeout = commandLineParser.value(processTimeout).toInt(&ok);
if (ok) {
termTimeout = _termTimeout;
timeoutSet = true;
}
else {
QTextStream(stderr) << "Termination timeout is not a number in argument, aborting!" << smsub_endl;
return 1;
}
}
else if (!envTimeout.isEmpty()) {
bool ok;
const int _termTimeout = envTimeout.toInt(&ok);
if (ok) {
termTimeout = _termTimeout;
timeoutSet = true;
}
else {
QTextStream(stderr) << "Termination timeout is not a number in environment, aborting!" << smsub_endl;
return 1;
}
}
if (commandLineParser.isSet(processExecutable)) {
executable = commandLineParser.value(processExecutable);
}
else if (!envExecutable.isEmpty()) {
executable = QString::fromUtf8(envExecutable);
}
if (!envAutoStart.isEmpty()) {
if (envAutoStart == "0" || envAutoStart.toLower() == "false" || envAutoStart.toLower() == "no") {
autoStart = false;
}
}
if (!envKeepAlive.isEmpty()) {
if (envKeepAlive == "1" || envKeepAlive.toLower() == "true" || envKeepAlive.toLower() == "yes") {
keepAlive = true;
}
}
if (!envWorkDir.isEmpty()) {
workingDirectory = QString::fromUtf8(envWorkDir);
}
else {
workingDirectory = QFileInfo(executable).absolutePath();
}
QString manifestPath;
if (commandLineParser.isSet(processManifest)) {
manifestPath = commandLineParser.value(processManifest);
}
else if (!envManifest.isEmpty()) {
manifestPath = QString::fromUtf8(envManifest);
}
if (!manifestPath.isEmpty()) {
QFile manifestFile(manifestPath);
if (manifestFile.open(QIODevice::ReadOnly)) {
const QByteArray jsonData = manifestFile.readAll();
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
QJsonObject jsonObject = jsonDocument.object();
if (jsonObject.contains("Executable")) {
const QJsonValue jsonExecutable = jsonObject.value("Executable");
if (!jsonExecutable.isString()) {
QTextStream(stderr) << "Executable is not a string in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
executable = jsonExecutable.toString();
}
else {
QTextStream(stderr) << "Executable is not defined in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
if (jsonObject.contains("AutoStart")) {
const QJsonValue jsonAutoStart = jsonObject.value("AutoStart");
if (!jsonAutoStart.isBool()) {
QTextStream(stderr) << "AutoStart is not a bool in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
autoStart = jsonAutoStart.toBool();
}
if (jsonObject.contains("KeepAlive")) {
const QJsonValue jsonKeepAlive = jsonObject.value("KeepAlive");
if (!jsonKeepAlive.isBool()) {
QTextStream(stderr) << "KeepAlive is not a bool in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
keepAlive = jsonKeepAlive.toBool();
}
if (jsonObject.contains("WorkingDirectory")) {
const QJsonValue jsonWorkingDirectory = jsonObject.value("WorkingDirectory");
if (!jsonWorkingDirectory.isString()) {
QTextStream(stderr) << "Working Directory is not a string in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
workingDirectory = jsonWorkingDirectory.toString();
}
if (jsonObject.contains("Arguments")) {
const QJsonValue jsonArguments = jsonObject.value("Arguments");
if (jsonArguments.isArray()) {
const QJsonArray jsonArray = jsonArguments.toArray();
for (auto it = jsonArray.constBegin(); it != jsonArray.constEnd(); it++) {
argumentList << it->toString();
}
}
else {
QTextStream(stderr) << "Arguments is not a array in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
}
if (!timeoutSet && jsonObject.contains("TerminationTimeout")) {
const QJsonValue jsonTimeout = jsonObject.value("TerminationTimeout");
if (!jsonTimeout.isDouble()) {
termTimeout = qRound(jsonTimeout.toDouble());
}
else {
QTextStream(stderr) << "Termination timeout is not a number in manifest, aborting!" << smsub_endl;
return 1;
}
}
manifestFile.close();
}
}
else if (commandLineParser.isSet(processArguments)) {
argumentList = parseStringArguments(commandLineParser.value(processArguments));
if (argumentList.empty()) {
QTextStream(stderr) << "Arguments can't be parsed properly!" << smsub_endl;
return 1;
}
}
else if (!envArguments.isEmpty()) {
argumentList = parseStringArguments(QString::fromUtf8(envArguments));
if (argumentList.empty()) {
QTextStream(stderr) << "Arguments can't be parsed properly!" << smsub_endl;
return 1;
}
}
if (commandLineParser.isSet(subprocessSocket)) {
socket = commandLineParser.value(subprocessSocket);
}
else if (!envSocket.isEmpty()) {
socket = QString::fromUtf8(envSocket);
}
else {
#ifdef Q_OS_WIN
QTextStream(stderr) << "You must define at least a local IPC socket!" << smsub_endl;
#else
QTextStream(stderr) << "You must define at least a local Unix socket!" << smsub_endl;
#endif
return 1;
}
if (commandLineParser.isSet(subprocessRemoteSocket)) {
rsocket = commandLineParser.value(subprocessRemoteSocket);
}
else if (!envRemoteSocket.isEmpty()) {
rsocket = QString::fromUtf8(envRemoteSocket);
}
if (commandLineParser.isSet(subprocessRemotePort)) {
bool ok;
const quint16 _rport = commandLineParser.value(subprocessRemotePort).toUShort(&ok);
if (ok) {
rport = _rport;
rportSet = true;
}
else {
QTextStream(stderr) << "WebSockets port is not valid in arguments!" << smsub_endl;
return 1;
}
}
else if (!envRemotePort.isEmpty()) {
bool ok;
const quint16 _rport = envRemotePort.toUShort(&ok);
if (ok) {
rport = _rport;
rportSet = true;
}
else {
QTextStream(stderr) << "WebSockets port is not valid in arguments!" << smsub_endl;
return 1;
}
}
}
SMSubServerSettings localSettings;
localSettings.isLocal = true;
SMSubServer subLocal(&localSettings, socket);
if (!subLocal.isListening()) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start local IPC socket!" << smsub_endl;
#else
QTextStream(stderr) << "Failed to start local Unix socket!" << smsub_endl;
#endif
return 1;
}
SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout, keepAlive);
SMSubServerSettings remoteSettings;
remoteSettings.canRegister = false;
remoteSettings.isLocal = false;
if (!rsocket.isEmpty()) {
SMSubServer *subRemote = new SMSubServer(&remoteSettings, rsocket);
if (!subRemote->isListening()) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start remote IPC socket!" << smsub_endl;
#else
QTextStream(stderr) << "Failed to start remote Unix socket!" << smsub_endl;
#endif
return 1;
}
localSettings.canRegister = true;
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput);
QObject::connect(&subProcess, &SMSubProcess::statusUpdated, subRemote, &SMSubServer::statusUpdated);
QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(subRemote, &SMSubServer::startRequested, &subProcess, &SMSubProcess::startProcess);
QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
}
else if (rportSet) {
SMSubServer *subRemote = new SMSubServer(&remoteSettings, QString(), rport);
if (!subRemote->isListening()) {
QTextStream(stderr) << "Failed to start remote WebSockets server!" << smsub_endl;
return 1;
}
localSettings.canRegister = true;
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput);
QObject::connect(&subProcess, &SMSubProcess::statusUpdated, subRemote, &SMSubServer::statusUpdated);
QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(subRemote, &SMSubServer::startRequested, &subProcess, &SMSubProcess::startProcess);
QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
}
else {
localSettings.canRegister = false;
}
QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subLocal, &SMSubServer::writeOutput);
QObject::connect(&subProcess, &SMSubProcess::statusUpdated, &subLocal, &SMSubServer::statusUpdated);
QObject::connect(&subLocal, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(&subLocal, &SMSubServer::startRequested, &subProcess, &SMSubProcess::startProcess);
QObject::connect(&subLocal, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(&subLocal, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(&a, &QCoreApplication::aboutToQuit, &subProcess, &SMSubProcess::aboutToQuit);
if (autoStart)
subProcess.startProcess();
QTextStream(stderr) << QString("SMSub Version %1 initialized!").arg(QCoreApplication::applicationVersion()) << smsub_endl;
return a.exec();
}

19
smsub.h
View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
* Copyright (C) 2020-2023 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
@ -18,21 +18,12 @@
#ifndef SMSUB_H
#define SMSUB_H
#include <QtGlobal>
#ifndef SMSUB_WITHOUT_EXPECT
#ifndef likely
#define likely(x) __builtin_expect((x),1)
#endif
#ifndef unlikely
#define unlikely(x) __builtin_expect((x),0)
#endif
#if QT_VERSION >= 0x050F00
#define smsub_endl Qt::endl
#else
#ifndef likely
#define likely(x) (x)
#endif
#ifndef unlikely
#define unlikely(x) (x)
#endif
#define smsub_endl endl
#endif
#endif // SMSUB_H

View File

@ -1,35 +1,35 @@
###############################################################################
# smsub Server Manager Subprocess
# Copyright (C) 2020 Syping
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# This software is provided as-is, no warranties are given to you, we are not
# responsible for anything with use of the software, you are self responsible.
###############################################################################
QT -= gui
QT += network
CONFIG += c++11 console
CONFIG -= app_bundle
SOURCES += main.cpp \
SMSubProcess.cpp \
SMSubServer.cpp
HEADERS += smsub.h \
SMSubProcess.h \
SMSubServer.h
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
###############################################################################
# smsub Server Manager Subprocess
# Copyright (C) 2020-2021 Syping
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# This software is provided as-is, no warranties are given to you, we are not
# responsible for anything with use of the software, you are self responsible.
###############################################################################
QT -= gui
QT += network websockets
CONFIG += c++11 console
CONFIG -= app_bundle
SOURCES += main.cpp \
SMSubProcess.cpp \
SMSubServer.cpp
HEADERS += smsub.h \
SMSubProcess.h \
SMSubServer.h
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target