Compare commits

...

9 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
8 changed files with 580 additions and 234 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,11 +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)
find_package(Qt5 COMPONENTS WebSockets QUIET)
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
@ -31,6 +36,6 @@ add_executable(smsub
${SMSUB_SOURCES}
)
target_link_libraries(smsub PRIVATE Qt5::Network Qt5::WebSockets)
target_link_libraries(smsub PRIVATE Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::WebSockets)
install(TARGETS smsub DESTINATION bin)

View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
* 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:
@ -18,57 +18,76 @@
#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) :
termTimeout(termTimeout)
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, QOverload<int>::of(&QProcess::finished), this, &SMSubProcess::processExit);
}
void SMSubProcess::start()
{
process.start(QIODevice::ReadWrite);
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');
}
}
void SMSubProcess::processExit(int exitCode)
{
// Exit with the same exit code as the process
emit processStopped();
QCoreApplication::exit(exitCode);
#endif
}
void SMSubProcess::processError(QProcess::ProcessError error)
{
// Handle process errors
if (likely(error == QProcess::FailedToStart)) {
QTextStream(stderr) << "Process failed to start!" << endl;
QCoreApplication::exit(1);
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!" << endl;
QCoreApplication::exit(1);
QTextStream(stderr) << "Unknown error occurred!" << smsub_endl;
if (!keepAlive)
QCoreApplication::exit(1);
}
}
@ -78,29 +97,38 @@ void SMSubProcess::aboutToQuit()
if (process.state() == QProcess::Running) {
process.terminate();
if (!process.waitForFinished(termTimeout)) {
QTextStream(stderr) << "Failed to terminate process!" << endl;
QTextStream(stderr) << "Failed to terminate process!" << smsub_endl;
}
}
}
void SMSubProcess::killProcess()
void SMSubProcess::startProcess()
{
// Kill process as requested
if (process.state() == QProcess::Running) {
process.kill();
}
// 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) {
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
process.write(input);
if (process.state() == QProcess::Running)
process.write(input);
}

View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
* 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:
@ -26,28 +26,27 @@ class SMSubProcess : public QObject
{
Q_OBJECT
public:
SMSubProcess(const QString &executable, const QStringList &arguments, const QString& workingDirectory, const int &termTimeout = 60000);
void start();
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 killProcess();
void startProcess();
void stopProcess();
void killProcess();
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();
void statusUpdated(const bool status, const qint64 time);
};
#endif // SMSUBPROCESS_H

View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
* 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:
@ -32,6 +32,9 @@ SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &soc
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)
@ -43,11 +46,14 @@ SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &ser
type = ServerType::WebSocket;
server = webSocketServer;
status = false;
startTime = QDateTime::currentDateTimeUtc().toSecsSinceEpoch();
stopTime = startTime;
}
bool SMSubServer::isListening()
{
if (likely(type == ServerType::Local)) {
if (Q_LIKELY(type == ServerType::Local)) {
return static_cast<QLocalServer*>(server)->isListening();
}
else if (type == ServerType::WebSocket) {
@ -59,12 +65,13 @@ bool SMSubServer::isListening()
void SMSubServer::newConnection()
{
QObject *socket;
if (likely(type == ServerType::Local)) {
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();
@ -72,6 +79,7 @@ void SMSubServer::newConnection()
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
@ -91,8 +99,8 @@ void SMSubServer::newConnection()
bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
{
// Only allow commands being sent if authenticated
bool isAuthenticated = socket->property("Authenticated").toBool();
if (likely(isAuthenticated)) {
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");
@ -110,7 +118,7 @@ bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
debugOutput(socket, "Log output disabled!");
}
else if (message.startsWith("+reg")) {
if (likely(serverSettings->canRegister)) {
if (Q_LIKELY(serverSettings->canRegister)) {
QByteArray authUuid = QUuid::createUuid().toByteArray(QUuid::Id128);
authUuid = QByteArray::fromHex(authUuid).toBase64(QByteArray::OmitTrailingEquals);
emit tokenRegistered(QString::fromUtf8(authUuid));
@ -120,14 +128,30 @@ bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
sendMessage(socket, "Permission denied!\n");
}
}
else if (message.startsWith("kill")) {
emit killRequested();
debugOutput(socket, "Killing server!");
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');
@ -141,16 +165,15 @@ bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
}
else {
// Authenticate when token is valid, otherwise disconnect
if (unlikely(tokens.contains(QString::fromUtf8(message)))) {
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");
isAuthenticated = true;
sockets << socket;
}
else {
// Stop receiving data and disconnect socket
if (likely(type == ServerType::Local)) {
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");
@ -178,7 +201,13 @@ void SMSubServer::wsMessageReceived(const QByteArray &message)
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;
@ -197,9 +226,13 @@ void SMSubServer::debugOutput(QObject *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)) {
#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 (likely(receiveDbgMsg)) {
if (Q_LIKELY(receiveDbgMsg)) {
sendMessage(socket, message + '\n');
}
}
@ -208,23 +241,24 @@ void SMSubServer::debugOutput(QObject *socket, const QByteArray &message)
void SMSubServer::writeOutput(const QByteArray &output)
{
// Read process output when client opted-in for log
QVector<QObject*>::const_iterator it = sockets.constBegin();
QVector<QObject*>::const_iterator end = sockets.constEnd();
while (it != end) {
for (auto it = sockets.constBegin(); it != sockets.constEnd(); it++) {
const QVariant variant = (*it)->property("ReceiveLog");
if (unlikely(variant.type() == QVariant::Bool)) {
#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 (likely(receiveLog)) {
if (Q_LIKELY(receiveLog)) {
sendMessage(*it, output);
}
}
it++;
}
}
void SMSubServer::sendMessage(QObject *socket, const QByteArray &message)
{
if (likely(type == ServerType::Local)) {
if (Q_LIKELY(type == ServerType::Local)) {
QLocalSocket *localSocket = static_cast<QLocalSocket*>(socket);
localSocket->write(message);
}
@ -238,7 +272,13 @@ void SMSubServer::registerToken(const QString &token)
{
// Register temporary token for a secure remote connection
tokens << token;
QTimer::singleShot(30000, [this, 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,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
* 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:
@ -45,6 +45,7 @@ public:
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);
@ -59,14 +60,18 @@ private:
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 killRequested();
void startRequested();
void stopRequested();
void killRequested();
};
#endif // SMSUBSERVER_H

584
main.cpp
View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
* 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:
@ -33,7 +33,6 @@
#ifdef Q_OS_UNIX
#include <initializer_list>
#include "signal.h"
#include "unistd.h"
#endif
#ifdef Q_OS_UNIX
@ -56,7 +55,7 @@ void catchUnixSignals(std::initializer_list<int> quitSignals) {
default:
unixSignal = QString::number(sig);
}
QTextStream(stderr) << "Received Unix signal: " << unixSignal << endl;
QTextStream(stderr) << "Received Unix signal: " << unixSignal << smsub_endl;
QCoreApplication::quit();
};
@ -75,243 +74,522 @@ void catchUnixSignals(std::initializer_list<int> quitSignals) {
}
#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.3.1");
a.setApplicationVersion("0.8");
#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);
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 (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;
}
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 rportSet = false;
bool autoStart = true;
bool keepAlive = false;
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;
}
}
quint16 rport;
QString socket;
QString rsocket;
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();
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 manifest, aborting!" << endl;
manifestFile.close();
QTextStream(stderr) << "Executable is not defined in environment, aborting!" << smsub_endl;
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();
if (!envArguments.isEmpty()) {
argumentList = parseStringArguments(QString::fromUtf8(envArguments));
if (argumentList.empty()) {
QTextStream(stderr) << "Arguments can't be parsed properly!" << smsub_endl;
return 1;
}
workingDirectory = jsonWorkingDirectory.toString();
}
else {
workingDirectory = QFileInfo(executable).absolutePath();
QTextStream(stderr) << "Arguments are not defined in environment, aborting!" << smsub_endl;
return 1;
}
}
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++;
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) << "Arguments is not a array in manifest, aborting!" << endl;
QTextStream(stderr) << "Executable is not defined in manifest, aborting!" << smsub_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());
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();
}
else {
QTextStream(stderr) << "Termination Timeout is not a number in manifest, aborting!" << endl;
return 1;
}
}
manifestFile.close();
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;
}
}
}
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 {
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!" << endl;
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!" << endl;
QTextStream(stderr) << "You must define at least a local Unix socket!" << smsub_endl;
#endif
return 1;
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 (unlikely(!subLocal.isListening())) {
if (!subLocal.isListening()) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start local IPC socket!" << endl;
QTextStream(stderr) << "Failed to start local IPC socket!" << smsub_endl;
#else
QTextStream(stderr) << "Failed to start local Unix socket!" << endl;
QTextStream(stderr) << "Failed to start local Unix socket!" << smsub_endl;
#endif
return 1;
}
QString rsocket;
if (unlikely(commandLineParser.isSet(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);
SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout, keepAlive);
SMSubServerSettings remoteSettings;
remoteSettings.canRegister = false;
remoteSettings.isLocal = false;
if (unlikely(!rsocket.isEmpty())) {
if (!rsocket.isEmpty()) {
SMSubServer *subRemote = new SMSubServer(&remoteSettings, rsocket);
if (unlikely(!subRemote->isListening())) {
if (!subRemote->isListening()) {
#ifdef Q_OS_WIN
QTextStream(stderr) << "Failed to start remote IPC socket!" << endl;
QTextStream(stderr) << "Failed to start remote IPC socket!" << smsub_endl;
#else
QTextStream(stderr) << "Failed to start remote Unix socket!" << endl;
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::killRequested, &subProcess, &SMSubProcess::killProcess);
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 (unlikely(rportSet)) {
else if (rportSet) {
SMSubServer *subRemote = new SMSubServer(&remoteSettings, QString(), rport);
if (unlikely(!subRemote->isListening())) {
QTextStream(stderr) << "Failed to start remote WebSockets server!" << endl;
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::killRequested, &subProcess, &SMSubProcess::killProcess);
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::killRequested, &subProcess, &SMSubProcess::killProcess);
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);
subProcess.start();
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,6 +1,6 @@
###############################################################################
# smsub Server Manager Subprocess
# Copyright (C) 2020 Syping
# 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: