Compare commits

...

4 Commits
0.5 ... master

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
7 changed files with 263 additions and 140 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)

View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2021 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,55 +18,76 @@
#include <QCoreApplication>
#include <QTextStream>
#include <QDateTime>
#include "SMSubProcess.h"
#include "smsub.h"
#include <QDebug>
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, QProcess::ExitStatus>::of(&QProcess::finished), this, [=](int exitCode) {
// Exit with the same exit code as the process
emit processStopped();
QCoreApplication::exit(exitCode);
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::start()
{
process.start(QIODevice::ReadWrite);
}
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 (likely(error == QProcess::FailedToStart)) {
if (Q_LIKELY(error == QProcess::FailedToStart)) {
QTextStream(stderr) << "Process failed to start!" << smsub_endl;
QCoreApplication::exit(1);
if (!keepAlive)
QCoreApplication::exit(1);
}
else if (error == QProcess::UnknownError) {
QTextStream(stderr) << "Unknown error occurred!" << smsub_endl;
QCoreApplication::exit(1);
if (!keepAlive)
QCoreApplication::exit(1);
}
}
@ -81,24 +102,33 @@ void SMSubProcess::aboutToQuit()
}
}
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-2021 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,17 +26,18 @@ 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:
@ -45,8 +46,7 @@ private slots:
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-2021 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
@ -92,7 +100,7 @@ bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
{
// Only allow commands being sent if authenticated
const bool isAuthenticated = socket->property("Authenticated").toBool();
if (likely(isAuthenticated)) {
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,7 +165,7 @@ 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");
@ -149,7 +173,7 @@ bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
}
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");
@ -177,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;
@ -196,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');
}
}
@ -209,9 +243,13 @@ 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 (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);
}
}
@ -220,7 +258,7 @@ void SMSubServer::writeOutput(const QByteArray &output)
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,3 +276,9 @@ void SMSubServer::registerToken(const QString &token)
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-2021 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

208
main.cpp
View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2021 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
@ -135,13 +134,15 @@ int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setApplicationName("Server Manager Subprocess");
a.setApplicationVersion("0.5");
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;
@ -151,24 +152,27 @@ int main(int argc, char *argv[])
QString workingDirectory;
QStringList argumentList;
QByteArray envEnvironmentMode = qgetenv("SMSUB_ENVIRONMENT_MODE");
QByteArray envManifest = qgetenv("SMSUB_JSON");
QByteArray envExecutable = qgetenv("SMSUB_EXEC");
QByteArray envArguments = qgetenv("SMSUB_ARGS");
QByteArray envSocket = qgetenv("SMSUB_SOCK");
QByteArray envRemotePort = qgetenv("SMSUB_RPORT");
QByteArray envRemoteSocket = qgetenv("SMSUB_RSOCK");
QByteArray envTimeout = qgetenv("SMSUB_TIMEOUT");
QByteArray envWorkDir = qgetenv("SMSUB_WORKDIR");
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 (unlikely(envEnvironmentMode == "1" || envEnvironmentMode.toLower() == "true")) {
if (likely(envExecutable.isEmpty() && envArguments.isEmpty())) {
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 (likely(!envExecutable.isEmpty())) {
if (!envExecutable.isEmpty()) {
executable = QString::fromUtf8(envExecutable);
}
else {
@ -176,7 +180,7 @@ int main(int argc, char *argv[])
return 1;
}
if (likely(!envArguments.isEmpty())) {
if (!envArguments.isEmpty()) {
argumentList = parseStringArguments(QString::fromUtf8(envArguments));
if (argumentList.empty()) {
QTextStream(stderr) << "Arguments can't be parsed properly!" << smsub_endl;
@ -189,7 +193,7 @@ int main(int argc, char *argv[])
}
}
if (unlikely(!envTimeout.isEmpty())) {
if (!envTimeout.isEmpty()) {
bool ok;
const int _termTimeout = envTimeout.toInt(&ok);
if (ok) {
@ -202,14 +206,26 @@ int main(int argc, char *argv[])
}
}
if (unlikely(!envWorkDir.isEmpty())) {
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 (likely(!envSocket.isEmpty())) {
if (!envSocket.isEmpty()) {
socket = QString::fromUtf8(envSocket);
}
else {
@ -221,19 +237,20 @@ int main(int argc, char *argv[])
return 1;
}
if (unlikely(!envRemoteSocket.isEmpty())) {
if (!envRemoteSocket.isEmpty()) {
rsocket = QString::fromUtf8(envRemoteSocket);
}
if (unlikely(!envRemotePort.isEmpty())) {
if (!envRemotePort.isEmpty()) {
bool ok;
rport = envRemotePort.toUShort(&ok);
if (!ok) {
QTextStream(stderr) << "WebSockets port is not valid in environment!" << smsub_endl;
return 1;
const quint16 _rport = envRemotePort.toUShort(&ok);
if (ok) {
rport = _rport;
rportSet = true;
}
else {
rportSet = true;
QTextStream(stderr) << "WebSockets port is not valid in environment!" << smsub_endl;
return 1;
}
}
}
@ -273,26 +290,26 @@ int main(int argc, char *argv[])
commandLineParser.process(a);
if (unlikely(commandLineParser.isSet(processManifest) && commandLineParser.isSet(processExecutable) ||
if (commandLineParser.isSet(processManifest) && commandLineParser.isSet(processExecutable) ||
!envManifest.isEmpty() && !envExecutable.isEmpty() ||
commandLineParser.isSet(processManifest) && !envExecutable.isEmpty() ||
!envManifest.isEmpty() && commandLineParser.isSet(processExecutable))) {
!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 (unlikely(commandLineParser.isSet(processManifest) && commandLineParser.isSet(processArguments) ||
if (commandLineParser.isSet(processManifest) && commandLineParser.isSet(processArguments) ||
!envManifest.isEmpty() && !envArguments.isEmpty() ||
commandLineParser.isSet(processManifest) && !envArguments.isEmpty() ||
!envManifest.isEmpty() && commandLineParser.isSet(processArguments))) {
!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 (unlikely(commandLineParser.isSet(subprocessRemotePort) && commandLineParser.isSet(subprocessRemoteSocket) ||
if (commandLineParser.isSet(subprocessRemotePort) && commandLineParser.isSet(subprocessRemoteSocket) ||
!envRemotePort.isEmpty() && !envRemoteSocket.isEmpty() ||
commandLineParser.isSet(subprocessRemotePort) && !envRemoteSocket.isEmpty() ||
!envRemotePort.isEmpty() && commandLineParser.isSet(subprocessRemoteSocket))) {
!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
@ -301,7 +318,7 @@ int main(int argc, char *argv[])
return 1;
}
if (unlikely(commandLineParser.isSet(processTimeout))) {
if (commandLineParser.isSet(processTimeout)) {
bool ok;
const int _termTimeout = commandLineParser.value(processTimeout).toInt(&ok);
if (ok) {
@ -313,7 +330,7 @@ int main(int argc, char *argv[])
return 1;
}
}
else if (unlikely(!envTimeout.isEmpty())) {
else if (!envTimeout.isEmpty()) {
bool ok;
const int _termTimeout = envTimeout.toInt(&ok);
if (ok) {
@ -326,14 +343,26 @@ int main(int argc, char *argv[])
}
}
if (unlikely(commandLineParser.isSet(processExecutable))) {
if (commandLineParser.isSet(processExecutable)) {
executable = commandLineParser.value(processExecutable);
}
else if (unlikely(!envExecutable.isEmpty())) {
else if (!envExecutable.isEmpty()) {
executable = QString::fromUtf8(envExecutable);
}
if (unlikely(!envWorkDir.isEmpty())) {
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 {
@ -341,23 +370,23 @@ int main(int argc, char *argv[])
}
QString manifestPath;
if (likely(commandLineParser.isSet(processManifest))) {
if (commandLineParser.isSet(processManifest)) {
manifestPath = commandLineParser.value(processManifest);
}
else if (!envManifest.isEmpty()) {
manifestPath = QString::fromUtf8(envManifest);
}
if (likely(!manifestPath.isEmpty())) {
if (!manifestPath.isEmpty()) {
QFile manifestFile(manifestPath);
if (likely(manifestFile.open(QIODevice::ReadOnly))) {
if (manifestFile.open(QIODevice::ReadOnly)) {
const QByteArray jsonData = manifestFile.readAll();
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
QJsonObject jsonObject = jsonDocument.object();
if (likely(jsonObject.contains("Executable"))) {
if (jsonObject.contains("Executable")) {
const QJsonValue jsonExecutable = jsonObject.value("Executable");
if (unlikely(!jsonExecutable.isString())) {
if (!jsonExecutable.isString()) {
QTextStream(stderr) << "Executable is not a string in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
@ -370,9 +399,29 @@ int main(int argc, char *argv[])
return 1;
}
if (likely(jsonObject.contains("WorkingDirectory"))) {
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 (unlikely(!jsonWorkingDirectory.isString())) {
if (!jsonWorkingDirectory.isString()) {
QTextStream(stderr) << "Working Directory is not a string in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
@ -380,9 +429,9 @@ int main(int argc, char *argv[])
workingDirectory = jsonWorkingDirectory.toString();
}
if (likely(jsonObject.contains("Arguments"))) {
if (jsonObject.contains("Arguments")) {
const QJsonValue jsonArguments = jsonObject.value("Arguments");
if (likely(jsonArguments.isArray())) {
if (jsonArguments.isArray()) {
const QJsonArray jsonArray = jsonArguments.toArray();
for (auto it = jsonArray.constBegin(); it != jsonArray.constEnd(); it++) {
argumentList << it->toString();
@ -395,9 +444,9 @@ int main(int argc, char *argv[])
}
}
if (unlikely(!timeoutSet && jsonObject.contains("TerminationTimeout"))) {
if (!timeoutSet && jsonObject.contains("TerminationTimeout")) {
const QJsonValue jsonTimeout = jsonObject.value("TerminationTimeout");
if (unlikely(!jsonTimeout.isDouble())) {
if (!jsonTimeout.isDouble()) {
termTimeout = qRound(jsonTimeout.toDouble());
}
else {
@ -409,14 +458,14 @@ int main(int argc, char *argv[])
manifestFile.close();
}
}
else if (unlikely(commandLineParser.isSet(processArguments))) {
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 (unlikely(!envArguments.isEmpty())) {
else if (!envArguments.isEmpty()) {
argumentList = parseStringArguments(QString::fromUtf8(envArguments));
if (argumentList.empty()) {
QTextStream(stderr) << "Arguments can't be parsed properly!" << smsub_endl;
@ -424,7 +473,7 @@ int main(int argc, char *argv[])
}
}
if (likely(commandLineParser.isSet(subprocessSocket))) {
if (commandLineParser.isSet(subprocessSocket)) {
socket = commandLineParser.value(subprocessSocket);
}
else if (!envSocket.isEmpty()) {
@ -439,33 +488,35 @@ int main(int argc, char *argv[])
return 1;
}
if (unlikely(commandLineParser.isSet(subprocessRemoteSocket))) {
if (commandLineParser.isSet(subprocessRemoteSocket)) {
rsocket = commandLineParser.value(subprocessRemoteSocket);
}
else if (unlikely(!envRemoteSocket.isEmpty())) {
else if (!envRemoteSocket.isEmpty()) {
rsocket = QString::fromUtf8(envRemoteSocket);
}
if (unlikely(commandLineParser.isSet(subprocessRemotePort))) {
if (commandLineParser.isSet(subprocessRemotePort)) {
bool ok;
rport = commandLineParser.value(subprocessRemotePort).toUShort(&ok);
if (!ok) {
QTextStream(stderr) << "WebSockets port is not valid in arguments!" << smsub_endl;
return 1;
const quint16 _rport = commandLineParser.value(subprocessRemotePort).toUShort(&ok);
if (ok) {
rport = _rport;
rportSet = true;
}
else {
rportSet = true;
QTextStream(stderr) << "WebSockets port is not valid in arguments!" << smsub_endl;
return 1;
}
}
else if (!envRemotePort.isEmpty()) {
bool ok;
rport = envRemotePort.toUShort(&ok);
if (!ok) {
QTextStream(stderr) << "WebSockets port is not valid in environment!" << smsub_endl;
return 1;
const quint16 _rport = envRemotePort.toUShort(&ok);
if (ok) {
rport = _rport;
rportSet = true;
}
else {
rportSet = true;
QTextStream(stderr) << "WebSockets port is not valid in arguments!" << smsub_endl;
return 1;
}
}
}
@ -474,7 +525,7 @@ int main(int argc, char *argv[])
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!" << smsub_endl;
#else
@ -483,15 +534,15 @@ int main(int argc, char *argv[])
return 1;
}
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!" << smsub_endl;
#else
@ -502,34 +553,43 @@ int main(int argc, char *argv[])
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())) {
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();
}

20
smsub.h
View File

@ -1,6 +1,6 @@
/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020-2021 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:
@ -20,23 +20,7 @@
#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
#else
#ifndef likely
#define likely(x) (x)
#endif
#ifndef unlikely
#define unlikely(x) (x)
#endif
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#if QT_VERSION >= 0x050F00
#define smsub_endl Qt::endl
#else
#define smsub_endl endl