From 594e1d9812a4be879742719cd06a72ae659a7cea Mon Sep 17 00:00:00 2001 From: Maurice O'Neal Date: Thu, 12 Sep 2019 01:29:46 -0400 Subject: [PATCH] Major bug fixes and a few minor changes Fixed a bug that caused the host to not respond to any commands when a module is present. CmdExecutor::loadMods() had a malformed 'for' loop that caused the command executor to infinite loop. Also re-formed the way the external command loaders (modules) are constructed. Instead, the modules are also intialized at the same time as the internal command loader. The CmdExecutor::loadModFile() and CmdExecutor::unloadModFile() functions now load and unload modules via the module name instead of the path to the module main file. The documentation for ASYNC_ENABLE_MOD and ASYNC_DISABLE_MOD updated to reflect this change. Also part of the module contruction re-form, it fixed a bug that caused the command loaders to operate in a thread different from the command executor. CmdExecutor::loadMods() was refactored into cmdExecutor::buildCmdLoaders(), added the internal command loader to it and have it so this function gets called only when the command executor successfully moves to it's own thread. Fixed a bug that caused the session to crash only when a module is present. It turns out the qobject_cast() function used in CmdExecutor::loadModFile() only pulled the surface class ModCommandLoader so any attempt to access the base class functions from CommandLoader caused the session to crash so to fix this, ModCommandLoader was merged into CommandLoader. The Command loader documentation and test module were updated to reflect this change. Fixed a bug that auto removed any modules that were installed when the host is restarted. The issue was in TCPServer::syncModPath() that used the modules's main file without a suffix when the file did indeed have a suffix, causing the function to think the module no longer exists and remove all of it's files from the host file system. The original intent for this function was to keep the module database table in sync with what was actually in the host file system. It was decided that this is not necessary so the function was removed altogether. Also changed up the way the module files are deleted. The TCPSever class will now use the module name instead of the path to the module's main library file and will use a single use ModDeleteTimer for each module that was requested to be deleted instead of a single continuous timer constantly checking for modules to delete. The ls_cmds command will now list the commands in alphabetical order of the command names and fixed a bug with the -find option that would display nothing if an exact match to any text in the table could not be found. Fixed a bug found in the deployed application that would segmentation fault on startup due to certain library files being included in the deployed installation directory. Updated the linux_build.sh script to include only libsqlite, libQT5, libssl and libicu files. It will no longer blindly copy all library files from the dev machine and then remove files the setup script thinks the application might or might not need. Any module built on import rev1 will simply not work and no attempt will be made to make it work so the host new minimum import rev is now rev2. this update is mustly just bug fixes; nothing that would require any client behaviour changes so just the host patch is bumped. 1.0.0 --> 1.0.1 --- docs/Async.md | 4 +- docs/Command_Loaders.md | 48 +++--- linux_build.sh | 7 +- modules/Tester/command.h | 32 ++-- modules/Tester/main.cpp | 2 +- modules/Tester/main.h | 8 +- modules/Tester/tester.pro | 34 ---- src/cmd_executor.cpp | 350 ++++++++++++++++++-------------------- src/cmd_executor.h | 44 ++--- src/commands/command.h | 32 ++-- src/commands/info.cpp | 33 +++- src/commands/info.h | 4 + src/commands/mods.cpp | 12 +- src/common.h | 4 +- src/db.h | 2 +- src/session.cpp | 4 +- src/session.h | 6 +- src/tcp_server.cpp | 115 ++++++------- src/tcp_server.h | 51 +++--- 19 files changed, 363 insertions(+), 429 deletions(-) delete mode 100644 modules/Tester/tester.pro diff --git a/docs/Async.md b/docs/Async.md index 03f6dce..714e059 100644 --- a/docs/Async.md +++ b/docs/Async.md @@ -97,10 +97,10 @@ This internal only async commmand doesn't carry any data. Instead, it notifies a This internal only async commmand doesn't carry any data. It is used to send a ```resServer()``` signal to the ```TCPServer``` object in the main process. This will cause it stop listing for clients, close all sessions, reload the host settings and start listening for clients again. ```ASYNC_ENABLE_MOD (15)``` -This internal only async commmand carry ```TEXT``` path to the main library file of a module. All ```Session``` objects will then load the module. +This internal only async commmand carry ```TEXT``` of a module name. All ```Session``` objects that receive this will then load the requested module. ```ASYNC_DISABLE_MOD (16)``` -This internal only async commmand carry ```TEXT``` path to the main library file of a module. All ```Session``` objects will then delete all commands associated with the with this module and then unload it. +This internal only async commmand carry ```TEXT``` of a module name. All ```Session``` objects that receive this will delete all commands associated with the with this module and then unload it. ```ASYNC_GROUP_UPDATED (17)``` This is an internal only command that carry ```TEXT``` command line arguments to notify all ```Session``` objects that a group's host rank has changed. Example: ```-name "group_name" -rank 2```. All ```Session``` object that have matching group names to ```group_name``` will need to update the host rank to ```2```. When the session's host rank to adjusted this way, the session will need to re-check the currently loaded commands and determine if it needs to remove any commands that the user no longer have access to and add any commands that the user may have gained access to. diff --git a/docs/Command_Loaders.md b/docs/Command_Loaders.md index 50413cf..021ca57 100644 --- a/docs/Command_Loaders.md +++ b/docs/Command_Loaders.md @@ -1,8 +1,8 @@ ### 2.1 Command Loaders ### -Every command object ([Command_Objects](Command_Objects.md)) defined in the host must internally define a unique command name. Command loaders have the very simple job of creating these objects via the requested command name. The host use command names to determine if the current session is allowed to load them or not and command loaders are used to relate those command names with the command objects themselves. +Every command object ([Command_Objects](Command_Objects.md)) defined in the host must have a unique command name atteched to it. Command loaders have the very simple job of creating these objects via the requested command name. The host use command names to determine if the current session is allowed to load them or not and command loaders are used to relate those command names with the command objects themselves. -When the host ```CmdExecutor``` determines that it can indeed load the commands based on the command names, it will then assign command ids to all command objects that were successfully built from the command loader. Each command loader can have a total of 256 command objects and internally defined commands start at command id: 256 - 512 and module defined commands start at command id: 513 and up. +When the host ```CmdExecutor``` determines that it can indeed load the commands based on the command names, it will then assign command ids to all command objects that were successfully built from the command loader. Each command loader can have a total of 256 command objects. Internally defined commands start at command id: 256 - 512 and module defined commands start at command id: 513 and up. ### 2.2 CommandLoader Class ### @@ -15,32 +15,11 @@ This function is used to create the ```ExternCommand``` object associated with t This function needs to return a ```QStringList``` of all of command names that this loader can actually load when the ```cmdObj()``` function is called. the host uses this list to enforce user access filtering of the command objects using the built in permission id system. ```QStringList pubCmdList()``` -This funtion needs to work the same way as ```cmdList()``` except the loader will use this function to name any commands that can be accessed by un-logged in clients. aka, public commands. Note: the commands listed here must also be listed in ```cmdList()``` or else the commands will not get loaded at all. +This funtion needs to work the same way as ```cmdList()``` except the loader can this function to name any commands that can be accessed by un-logged in clients. aka, public commands. Note: the commands listed here must also be listed in ```cmdList()``` or else the commands will not get loaded at all. ```QStringList rankExemptList()``` The loader can use this function to return a ```QStringList``` of all of command names that need to be exempt from host ranking system (section [5.2](Host_Features.md)). Commands listed here will be allowed to load/run regardless of what host rank the current user is. -Here's a few notes to consider when using this class: - -* Never self delete or explicitly delete the command loader or any of the command objects it sucessfully creates at any time. The host ```CmdExecutor``` object will handle the life cycle of these objects externally. -* Command ids are assigned in alphabetical order of the command names returned by ```cmdList()```. The command ids will remain constant as long as the command names also remain constant. All clients are recommended to rely on the ASYNC_ADD_CMD and ASYNC_RM_CMD async commands to keep track of the command ids and names (section [6.2](Async.md)). - -### 2.3 Modules ### - -External commands are added to the host through modules based on low level [QT plugins](https://doc.qt.io/qt-5/plugins-howto.html). Each module must define a ```ModCommandLoader``` class in it's main library file and the file itself must be named 'main' with a library file extension that the host platform supports (main.so, main.dll, etc..). Modules are installed using the *add_mod* internal command that supports extracting the module's library files from an archive file (.zip, .tar, etc...) or just a single library file (.so, .dll, .a, etc...). - -In the case of an archive file, it extracts all of the files from the the archive file while preserving the directory tree so you can bundle additional files that your module depends on but as mentioned before, a library file named 'main' must be present on the base directory. - -A template and an example of a module can be found in the 'modules/Tester' directory of the source code of this project. It provides the command.cpp and command.h files that contain the ```ModCommandLoader```, ```CommandLoader``` and ```ExternCommand``` classes that are needed to create a module. Also feel free to copy the command.cpp and command.h files from 'src/commands' if you prefer. - -### 2.4 The Import Rev ### - -The import rev is a single digit versioning system for external modules that help the host determine if it is compatible with the module it is attempting to load or not. Bumps to this rev is usually triggered by significant changes to the ```CommandLoader``` or ```ModCommandLoader``` classes. Compatibility negotiation is a two way communication between the host ```CmdExecutor``` and the module itself using the virtual functions described in section 2.5. - -### 2.5 ModCommandLoader Class ### - -This class uses ```CommandLoader``` as a base and adds more virtual functions more suitable for loading command objects from an external library file: - ```bool hostRevOk(quint64 rev)``` When the host calls this function, it will pass the import rev that it supports in the ```quint64``` parameter. Use this function to return if this rev is acceptable or not. The host will give up loading the module if the rev is not acceptable. @@ -51,7 +30,24 @@ Use this function to return the import rev that this module supports. The host w The host will call this function if a command object fails to load or if ```hostRevOk()``` returns false so it can log the error message returned by it to the host database. ```void modPath(QString path)``` -The host will call this function after successfully negotiating the import rev. The ```QString``` parameter passed into this will have the absolute path to the module's install directory. You can use this path to load additional files that came bundled in the archive file. +The host will call this function after successfully negotiating the import rev. The ```QString``` parameter passed into this will have the absolute path to the module's install directory. You can use this path to load additional files that came bundled the module. ```void aboutToDelete()``` -The host will call this function before calling ```deleteLater()```. All command objects at this point should already be deleted, use this opportunity to free any resources related to the loader itself. Unload any additional lib files that the loader may have used. \ No newline at end of file +The host will call this function before calling ```deleteLater()```. All command objects at this point should already be deleted, use this opportunity to free any resources related to the loader itself. Unload any additional lib files that the loader may have used. + +Here's a few notes to consider when using this class: + +* Never self delete or explicitly delete the command loader or any of the command objects it sucessfully creates at any time. The host ```CmdExecutor``` object will handle the life cycle of these objects externally. +* Command ids are assigned in alphabetical order of the command names returned by ```cmdList()```. The command ids will remain constant as long as the command names also remain constant. All clients are recommended to rely on the ASYNC_ADD_CMD and ASYNC_RM_CMD async commands to keep track of the command ids and names (section [6.2](Async.md)). + +### 2.3 Modules ### + +External commands are added to the host through modules based on low level [QT plugins](https://doc.qt.io/qt-5/plugins-howto.html). Each module must define a ```CommandLoader``` class in it's main library file and the file itself must be named 'main' with a library file extension that the host platform supports (main.so, main.dll, etc..). Modules are installed using the *add_mod* internal command that supports extracting the module's library files from an archive file (.zip, .tar, etc...) or just a single library file (.so, .dll, .a, etc...). + +In the case of an archive file, it extracts all of the files from the the archive file while preserving the directory tree so you can bundle additional files that your module depends on but as mentioned before, a library file named 'main' must be present on the base directory. + +A template and an example of a module can be found in the 'modules/Tester' directory of the source code of this project. It provides the command.cpp and command.h files that contain the ```CommandLoader``` and ```ExternCommand``` classes that are needed to create a module. Also feel free to copy the command.cpp and command.h files from 'src/commands' if you prefer. + +### 2.4 The Import Rev ### + +The import rev is a single digit versioning system for external modules that help the host determine if it is compatible with the module it is attempting to load or not. Bumps to this rev is usually triggered by significant changes to the ```CommandLoader``` class. Compatibility negotiation is a two way communication between the host ```CmdExecutor``` and the module itself using the virtual functions described in section 2.2. \ No newline at end of file diff --git a/linux_build.sh b/linux_build.sh index 573de8c..166434b 100644 --- a/linux_build.sh +++ b/linux_build.sh @@ -48,7 +48,10 @@ if [ $? -eq 0 ]; then mkdir -v ./build/ mkdir -v ./build/sqldrivers mkdir -v ./build/lib - ldd ./$bin_name | grep "=> /" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libQt" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libicu" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libssl" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib + ldd ./$bin_name | grep "libcrypto" | awk '{print $3}' | xargs -I '{}' cp -v '{}' ./build/lib mv -v ./$bin_name ./build/$bin_name cp -v $qt_dir/../plugins/sqldrivers/libqsqlite.so ./build/sqldrivers @@ -82,8 +85,6 @@ if [ $? -eq 0 ]; then echo "sudo chmod -R 755 $install_dir/sqldrivers" >> $setup_script echo "sudo chmod 755 /etc/systemd/system/$bin_name@$USER.service" >> $setup_script echo "sudo ln -sf $install_dir/$bin_name.sh $bin_dir/$bin_name" >> $setup_script - echo "cd $install_dir/lib" >> $setup_script - echo "ldd $install_dir/$bin_name | grep \"=> /\" | awk '{if (\$3 != \"not found\") print \$1}' | xargs -I '{}' sudo rm -f '{}'" >> $setup_script echo "sudo systemctl start $bin_name@$USER" >> $setup_script echo "sudo systemctl enable $bin_name@$USER" >> $setup_script echo "echo \"\nInstallation finished. If you ever need to uninstall this application, run this command:\n\"" >> $setup_script diff --git a/modules/Tester/command.h b/modules/Tester/command.h index b8a93ca..a696815 100644 --- a/modules/Tester/command.h +++ b/modules/Tester/command.h @@ -152,31 +152,19 @@ public: virtual ~CommandLoader() {} - virtual QStringList pubCmdList() {return QStringList();} - virtual QStringList cmdList() {return QStringList();} - virtual QStringList rankExemptList() {return QStringList();} - virtual ExternCommand *cmdObj(const QString &) {return nullptr;} -}; - -class ModCommandLoader : public CommandLoader -{ - Q_OBJECT - -public: - - explicit ModCommandLoader(QObject *parent = nullptr) : CommandLoader(parent) {} - - virtual ~ModCommandLoader() {} - - virtual void modPath(const QString &) {} - virtual void aboutToDelete() {} - virtual bool hostRevOk(quint64) {return false;} - virtual QString lastError() {return "";} - virtual quint64 rev() {return 0;} + virtual void modPath(const QString &) {} + virtual void aboutToDelete() {} + virtual bool hostRevOk(quint64) {return false;} + virtual QString lastError() {return "";} + virtual quint64 rev() {return 0;} + virtual QStringList pubCmdList() {return QStringList();} + virtual QStringList cmdList() {return QStringList();} + virtual QStringList rankExemptList() {return QStringList();} + virtual ExternCommand *cmdObj(const QString &) {return nullptr;} }; QT_BEGIN_NAMESPACE -Q_DECLARE_INTERFACE(ModCommandLoader, MOD_LOADER_IID) +Q_DECLARE_INTERFACE(CommandLoader, MOD_LOADER_IID) QT_END_NAMESPACE #endif // EXTERN_COMMAND_H diff --git a/modules/Tester/main.cpp b/modules/Tester/main.cpp index 5a91ca7..a0d1c58 100644 --- a/modules/Tester/main.cpp +++ b/modules/Tester/main.cpp @@ -21,7 +21,7 @@ QString libName() return QString(LIB_NAME) + "_" + QString(LIB_VERSION); } -Loader::Loader(QObject *parent) : ModCommandLoader(parent) +Loader::Loader(QObject *parent) : CommandLoader(parent) { } diff --git a/modules/Tester/main.h b/modules/Tester/main.h index 962631b..99ddfc6 100644 --- a/modules/Tester/main.h +++ b/modules/Tester/main.h @@ -23,14 +23,14 @@ #include "command.h" -#define IMPORT_REV 1 +#define IMPORT_REV 2 // the import revision is a module compatibility version number // used by the host to determine if it can successfully load and // run this library or not. as of right now, the host supports rev1 // and up. -#define LIB_VERSION "1.0.0" +#define LIB_VERSION "1.0.1" #define LIB_NAME "MRCITestMod" // the versioning system for the library itself can be completely @@ -38,11 +38,11 @@ QString libName(); -class Loader : public ModCommandLoader +class Loader : public CommandLoader { Q_OBJECT Q_PLUGIN_METADATA(IID "MRCI.host.module") - Q_INTERFACES(ModCommandLoader) + Q_INTERFACES(CommandLoader) public: diff --git a/modules/Tester/tester.pro b/modules/Tester/tester.pro deleted file mode 100644 index cdcfa17..0000000 --- a/modules/Tester/tester.pro +++ /dev/null @@ -1,34 +0,0 @@ -#------------------------------------------------- -# -# Project created by QtCreator 2017-06-26T15:36:12 -# -# This file is part of MCI_Host. -# -# MCI_Host is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# MCI_Host is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with MCI_Host under the GPL.txt file. If not, see -# . -# -#------------------------------------------------- - -QT -= gui - -TARGET = ModTester -TEMPLATE = lib - -SOURCES += \ - command.cpp \ - main.cpp - -HEADERS += \ - command.h \ - main.h diff --git a/src/cmd_executor.cpp b/src/cmd_executor.cpp index a69c04a..c14bb35 100644 --- a/src/cmd_executor.cpp +++ b/src/cmd_executor.cpp @@ -33,11 +33,30 @@ CmdExecutor::CmdExecutor(RWSharedObjs *rwShare, SharedObjs *rdOnlyShare, QShared exeDebugInfo = debugInfo; rdSharedObjs = rdOnlyShare; rwSharedObjs = rwShare; - internalCmds = new InternalCommandLoader(rwShare, this); + internalCmds = nullptr; connect(this, &CmdExecutor::loop, this, &CmdExecutor::exeCmd); } +void CmdExecutor::buildCmdLoaders() +{ + internalCmds = new InternalCommandLoader(rwSharedObjs, this); + + cmdLoaders.insert(INTERN_MOD_NAME, internalCmds); + + Query db(this); + + db.setType(Query::PULL, TABLE_MODULES); + db.addColumn(COLUMN_MOD_NAME); + db.addCondition(COLUMN_LOCKED, false); + db.exec(); + + for (int i = 0; i < db.rows(); ++i) + { + loadModFile(db.getData(COLUMN_MOD_NAME, i).toString()); + } +} + void CmdExecutor::wrCrashDebugInfo(const QString &msg) { if (exeDebugInfo->isAttached()) @@ -75,8 +94,6 @@ void CmdExecutor::connectInternCmd(InternCommand *cmd, quint16 cmdId, const QStr connect(cmd, &InternCommand::authOk, this, &CmdExecutor::authOk); connect(cmd, &InternCommand::termAllCommands, this, &CmdExecutor::termAllCommands); connect(cmd, &InternCommand::termCommandId, this, &CmdExecutor::termCommandId); - connect(cmd, &InternCommand::loadMod, this, &CmdExecutor::loadModFile); - connect(cmd, &InternCommand::unloadMod, this, &CmdExecutor::unloadModFile); connect(cmd, &InternCommand::reloadCommands, this, &CmdExecutor::buildCommands); connectCommon(cmd, cmdOutput, cmdId, cmdName); @@ -108,7 +125,10 @@ void CmdExecutor::connectCommon(ExternCommand *cmd, CommandOutput *cmdOutput, qu connect(cmd, &ExternCommand::closeSession, this, &CmdExecutor::endSession); connect(cmd, &ExternCommand::logout, this, &CmdExecutor::logout); - cmd->cmdId = cmdId; + cmd->cmdId = cmdId; + cmd->inMoreInputMode = false; + cmd->inLoopMode = false; + cmd->errSent = false; cmd->setObjectName(cmdName); cmdOutput->setCmdId(cmdId); @@ -225,7 +245,7 @@ void CmdExecutor::termCommandObj(quint16 cmdId, ExternCommand *cmd, bool del) if (del) { - wrCrashDebugInfo(" exe func: termCommandObj()\n cmd id: " + QString::number(cmdId) + "\n note: calling the command object's aboutToDelete()"); + wrCrashDebugInfo(" exe func: termCommandObj()\n cmd id: " + QString::number(cmdId) + "\n note: deleting intern commands"); for (auto internObj : cmd->internCommands.values()) { @@ -233,12 +253,24 @@ void CmdExecutor::termCommandObj(quint16 cmdId, ExternCommand *cmd, bool del) internObj->deleteLater(); } + wrCrashDebugInfo(" exe func: termCommandObj()\n cmd id: " + QString::number(cmdId) + "\n note: calling the command object's aboutToDelete()"); + cmd->aboutToDelete(); cmd->deleteLater(); commands.remove(cmdId); cmdNames.remove(cmdId); + for (auto&& list : cmdIdsByModName.values()) + { + if (list.contains(cmdId)) + { + list.removeAll(cmdId); + + break; + } + } + emit dataToSession(ASYNC_RM_CMD, wrInt(cmdId, 16), CMD_ID); } } @@ -268,36 +300,24 @@ void CmdExecutor::termAllCommands() void CmdExecutor::close() { - clearCommands(); + termCommandsInList(commands.keys(), true); + + for (auto cmdLoader : cmdLoaders.values()) + { + cmdLoader->aboutToDelete(); + } + + for (auto plugin : plugins.values()) + { + plugin->unload(); + plugin->deleteLater(); + } + cleanupDbConnection(); emit okToDelete(); } -void CmdExecutor::clearCommands() -{ - termCommandsInList(commands.keys(), true); - - QList loaders = mods.keys(); - - for (auto* loader : loaders) - { - ModCommandLoader *cmdLoader = qobject_cast(loader->instance()); - - if (cmdLoader) - { - wrCrashDebugInfo(" exe func: clearCommands()\n mod file: " + loader->fileName() + "\n note: calling the modules's aboutToDelete()"); - - cmdLoader->aboutToDelete(); - } - - loader->unload(); - loader->deleteLater(); - } - - mods.clear(); -} - void CmdExecutor::commandFinished(quint16 cmdId) { emit dataToSession(cmdId, QByteArray(), IDLE); @@ -343,143 +363,122 @@ void CmdExecutor::procInternRequest(ExternCommand *cmd, quint16 cmdId, const QSt } } -quint16 CmdExecutor::getModIdOffs(const QString &path) +quint16 CmdExecutor::getModIdOffs(const QString &name) { - Query db(this); - - db.setType(Query::PULL, TABLE_MODULES); - db.addColumn(COLUMN_CMD_ID_OFFS); - db.addCondition(COLUMN_MOD_MAIN, path); - db.exec(); - - return static_cast(db.getData(COLUMN_CMD_ID_OFFS).toUInt()); -} - -void CmdExecutor::loadModFile(const QString &path) -{ - loadModLib(path, getModIdOffs(path)); -} - -void CmdExecutor::loadModLib(const QString &path, quint16 idOffs) -{ - if (!isModFileLoaded(path) && QFile::exists(path)) + if (name == INTERN_MOD_NAME) { - bool modOk = false; - auto *pluginLoader = new QPluginLoader(path); - QObject *cmdLoaderObj = pluginLoader->instance(); - ModCommandLoader *cmdLoader = qobject_cast(cmdLoaderObj); - QString modPath = QFileInfo(path).path(); + return MAX_CMDS_PER_MOD; + } + else + { + Query db(this); - if (idOffs == 0) - { - qDebug() << "CmdExecutor::loadModLib() err: failed to get a valid command id offset for the module."; - } - else if (!pluginLoader->isLoaded()) - { - qDebug() << "CmdExecutor::loadModLib() err: failed to load mod lib file: " << path << " reason: " << pluginLoader->errorString(); - } - else if (!cmdLoaderObj) - { - qDebug() << "CmdExecutor::loadModLib() err: failed to load mod lib file: " << path << " reason: the root component object could not be instantiated."; - } - else if (!cmdLoader) - { - qDebug() << "CmdExecutor::loadModLib() err: failed to load mod lib file: " << path << " reason: the ModCommandLoader object could not be instantiated."; - } - else if (cmdLoader->rev() < IMPORT_REV) - { - qDebug() << "CmdExecutor::loadModLib() err: failed to load mod lib file: " << path << " reason: module import rev " << cmdLoader->rev() << " not compatible with host rev " << IMPORT_REV << "."; - } - else if (!cmdLoader->hostRevOk(IMPORT_REV)) - { - qDebug() << "CmdExecutor::loadModLib() err: failed to load mod lib file: " << path << " the module rejected the host import rev. reason: " << cmdLoader->lastError() << "."; - } - else - { - wrCrashDebugInfo(" exe func: loadModLib()\n path: " + path); + db.setType(Query::PULL, TABLE_MODULES); + db.addColumn(COLUMN_CMD_ID_OFFS); + db.addCondition(COLUMN_MOD_NAME, name); + db.exec(); - modOk = true; - - cmdLoader->modPath(modPath); - - loadCmds(cmdLoader, idOffs, pluginLoader, QFileInfo(modPath).fileName()); - } - - if (!modOk) - { - pluginLoader->unload(); - pluginLoader->deleteLater(); - } + return static_cast(db.getData(COLUMN_CMD_ID_OFFS).toUInt()); } } -void CmdExecutor::unloadModFile(const QString &path) -{ - if (isModFileLoaded(path)) - { - QList modLoaders = mods.keys(); - - for (auto* loader : modLoaders) - { - if (rmFileSuffix(loader->fileName()) == path) - { - QList cmdList = mods.value(loader); - - termCommandsInList(cmdList, true); - - ModCommandLoader *cmdLoader = qobject_cast(loader->instance()); - - if (cmdLoader != nullptr) - { - wrCrashDebugInfo(" exe func: unloadModFile()\n mod file: " + loader->fileName() + "\n note: calling the modules's aboutToDelete()"); - - cmdLoader->aboutToDelete(); - } - - loader->unload(); - loader->deleteLater(); - - mods.remove(loader); - - break; - } - } - } -} - -bool CmdExecutor::isModFileLoaded(const QString &path) -{ - bool ret = false; - - QList loaders = mods.keys(); - - for (auto* loader : loaders) - { - if (rmFileSuffix(loader->fileName()) == path) - { - ret = true; - - break; - } - } - - return ret; -} - -void CmdExecutor::loadMods() +QString CmdExecutor::getModFile(const QString &modName) { Query db(this); db.setType(Query::PULL, TABLE_MODULES); db.addColumn(COLUMN_MOD_MAIN); - db.addColumn(COLUMN_CMD_ID_OFFS); - db.addCondition(COLUMN_LOCKED, false); + db.addCondition(COLUMN_MOD_NAME, modName); db.exec(); - for (int i = 0; db.rows(); ++i) + return db.getData(COLUMN_MOD_MAIN).toString(); +} + +void CmdExecutor::loadModFile(const QString &modName) +{ + bool modOk = false; + QString path = getModFile(modName); + auto *pluginLoader = new QPluginLoader(path); + QObject *cmdLoaderObj = pluginLoader->instance(); + CommandLoader *cmdLoader = qobject_cast(cmdLoaderObj); + + if (!pluginLoader->isLoaded()) { - loadModLib(db.getData(COLUMN_MOD_MAIN, i).toString(), static_cast(db.getData(COLUMN_CMD_ID_OFFS).toUInt())); + qDebug() << "CmdExecutor::loadModFile() err: failed to load mod lib file: " << path << " reason: " << pluginLoader->errorString(); } + else if (!cmdLoaderObj) + { + qDebug() << "CmdExecutor::loadModFile() err: failed to load mod lib file: " << path << " reason: the root component object could not be instantiated."; + } + else if (!cmdLoader) + { + qDebug() << "CmdExecutor::loadModFile() err: failed to load mod lib file: " << path << " reason: the ModCommandLoader object could not be instantiated."; + } + else if (cmdLoader->rev() < IMPORT_REV) + { + qDebug() << "CmdExecutor::loadModFile() err: failed to load mod lib file: " << path << " reason: module import rev " << cmdLoader->rev() << " not compatible with host rev " << IMPORT_REV << "."; + } + else if (!cmdLoader->hostRevOk(IMPORT_REV)) + { + qDebug() << "CmdExecutor::loadModFile() err: failed to load mod lib file: " << path << " the module rejected the host import rev. reason: " << cmdLoader->lastError() << "."; + } + else + { + modOk = true; + + wrCrashDebugInfo(" exe func: loadModFile()\n path: " + path + " \nmod name: " + modName + " \nnote: calling the module's modPath() function."); + + cmdLoader->modPath(QFileInfo(path).path()); + + cmdLoaders.insert(modName, cmdLoader); + plugins.insert(modName, pluginLoader); + } + + if (!modOk) + { + pluginLoader->unload(); + pluginLoader->deleteLater(); + } +} + +void CmdExecutor::unloadModFile(const QString &modName) +{ + if (cmdIdsByModName.contains(modName)) + { + termCommandsInList(cmdIdsByModName[modName], true); + + wrCrashDebugInfo(" exe func: unloadModFile()\n mod name: " + modName + "\n note: calling the modules's aboutToDelete()"); + + cmdLoaders[modName]->aboutToDelete(); + plugins[modName]->unload(); + plugins[modName]->deleteLater(); + + cmdIdsByModName.remove(modName); + cmdLoaders.remove(modName); + plugins.remove(modName); + } +} + +void CmdExecutor::addCommandToList(quint16 cmdId, const QString &cmdName, const QString &modName, ExternCommand *cmdObj) +{ + procInternRequest(cmdObj, cmdId, cmdName); + + commands.insert(cmdId, cmdObj); + cmdNames.insert(cmdId, cmdName); + + if (cmdIdsByModName.contains(modName)) + { + cmdIdsByModName[modName].append(cmdId); + } + else + { + QList list; + + list.append(cmdId); + cmdIdsByModName.insert(modName, list); + } + + emit dataToSession(ASYNC_ADD_CMD, toNEW_CMD(cmdId, cmdName, cmdObj), NEW_CMD); } bool CmdExecutor::allowCmdLoad(const QString &cmdName, const QString &modName, const QStringList &exemptList) @@ -525,60 +524,39 @@ void CmdExecutor::loadInternCmd(CommandLoader *loader, const QString &cmdName, c if (cmdObj != nullptr) { connectInternCmd(cmdObj, id, uniqueName); - procInternRequest(cmdObj, id, uniqueName); - - commands.insert(id, cmdObj); - cmdNames.insert(id, uniqueName); - - emit dataToSession(ASYNC_ADD_CMD, toNEW_CMD(id, uniqueName, cmdObj), NEW_CMD); + addCommandToList(id, uniqueName, INTERN_MOD_NAME, cmdObj); } } -void CmdExecutor::loadExternCmd(CommandLoader *loader, const QString &cmdName, const QString &uniqueName, quint16 id) +void CmdExecutor::loadExternCmd(CommandLoader *loader, const QString &modName, const QString &cmdName, const QString &uniqueName, quint16 id) { ExternCommand *cmdObj = loader->cmdObj(cmdName); if (cmdObj != nullptr) { connectExternCmd(cmdObj, id, uniqueName); - procInternRequest(cmdObj, id, uniqueName); - - commands.insert(id, cmdObj); - cmdNames.insert(id, uniqueName); - - emit dataToSession(ASYNC_ADD_CMD, toNEW_CMD(id, uniqueName, cmdObj), NEW_CMD); + addCommandToList(id, uniqueName, modName, cmdObj); } } -void CmdExecutor::addToModList(quint16 cmdId, QPluginLoader *pluginLoader) -{ - if (mods.contains(pluginLoader)) - { - mods[pluginLoader].append(cmdId); - } - else - { - mods.insert(pluginLoader, QList() << cmdId); - } -} - -void CmdExecutor::loadCmd(CommandLoader *loader, quint16 cmdId, QPluginLoader *pluginLoader, const QString &cmdName, const QString &uniqueCmdName) +void CmdExecutor::loadCmd(CommandLoader *loader, quint16 cmdId, const QString &modName, const QString &cmdName, const QString &uniqueCmdName) { wrCrashDebugInfo(" exe func: loadCmd()\n cmd id: " + QString::number(cmdId) + "\n cmd name: " + cmdName); - if (pluginLoader == nullptr) + if (modName == INTERN_MOD_NAME) { loadInternCmd(loader, cmdName, uniqueCmdName, cmdId); } else { - loadExternCmd(loader, cmdName, uniqueCmdName, cmdId); - addToModList(cmdId, pluginLoader); + loadExternCmd(loader, modName, cmdName, uniqueCmdName, cmdId); } } -void CmdExecutor::loadCmds(CommandLoader *loader, quint16 idOffs, QPluginLoader *pluginLoader, const QString &modName) +void CmdExecutor::loadCmds(CommandLoader *loader, quint16 idOffs, const QString &modName) { + wrCrashDebugInfo(" exe func: loadCmds()\n mod name: " + modName + "\n id offs: " + QString::number(idOffs)); + QStringList list = loader->cmdList(); QStringList pub = loader->pubCmdList(); QStringList exempt = loader->rankExemptList(); @@ -605,12 +583,12 @@ void CmdExecutor::loadCmds(CommandLoader *loader, quint16 idOffs, QPluginLoader { if (pub.contains(list[id], Qt::CaseInsensitive)) { - loadCmd(loader, cmdId, pluginLoader, list[id], unique); + loadCmd(loader, cmdId, modName, list[id], unique); } } else if (allowCmdLoad(list[id], modName, exempt)) { - loadCmd(loader, cmdId, pluginLoader, list[id], unique); + loadCmd(loader, cmdId, modName, list[id], unique); } } } @@ -623,8 +601,10 @@ void CmdExecutor::loadCmds(CommandLoader *loader, quint16 idOffs, QPluginLoader void CmdExecutor::buildCommands() { - loadCmds(internalCmds, MAX_CMDS_PER_MOD, nullptr, INTERN_MOD_NAME); - loadMods(); + for (auto&& loaderName : cmdLoaders.keys()) + { + loadCmds(cmdLoaders[loaderName], getModIdOffs(loaderName), loaderName); + } } bool CmdExecutor::externBlockedTypeId(uchar typeId) diff --git a/src/cmd_executor.h b/src/cmd_executor.h index fc4eb7f..4a72e25 100644 --- a/src/cmd_executor.h +++ b/src/cmd_executor.h @@ -26,20 +26,20 @@ class CmdExecutor : public QObject private: - SharedObjs *rdSharedObjs; - RWSharedObjs *rwSharedObjs; - InternalCommandLoader *internalCmds; - QSharedMemory *exeDebugInfo; - QList moreInputCmds; - QList activeLoopCmds; - QList pausedCmds; - QHash cmdNames; - QHash commands; - QHash > mods; - int loopIndex; + SharedObjs *rdSharedObjs; + RWSharedObjs *rwSharedObjs; + InternalCommandLoader *internalCmds; + QSharedMemory *exeDebugInfo; + QHash cmdLoaders; + QHash plugins; + QHash > cmdIdsByModName; + QList moreInputCmds; + QList activeLoopCmds; + QList pausedCmds; + QHash cmdNames; + QHash commands; + int loopIndex; - void clearCommands(); - void loadMods(); void nextLoopCmd(); void preExe(ExternCommand *cmdObj, quint16 cmdId); void preExe(const QList &cmdObjs, quint16 cmdId); @@ -48,17 +48,17 @@ private: void connectInternCmd(InternCommand *cmd, quint16 cmdId, const QString &cmdName); void connectExternCmd(ExternCommand *cmd, quint16 cmdId, const QString &cmdName); void openOrCloseChByName(quint16 cmdId, const QString &ch, const QString &sub, bool open); - void loadCmd(CommandLoader *loader, quint16 cmdId, QPluginLoader *pluginLoader, const QString &cmdName, const QString &uniqueCmdName); - void loadCmds(CommandLoader *loader, quint16 idOffs, QPluginLoader *pluginLoader, const QString &modName); + void loadCmd(CommandLoader *loader, quint16 cmdId, const QString &modName, const QString &cmdName, const QString &uniqueCmdName); + void loadCmds(CommandLoader *loader, quint16 idOffs, const QString &modName); void loadInternCmd(CommandLoader *loader, const QString &cmdName, const QString &uniqueName, quint16 id); - void loadExternCmd(CommandLoader *loader, const QString &cmdName, const QString &uniqueName, quint16 id); - void addToModList(quint16 cmdId, QPluginLoader *pluginLoader); - bool isModFileLoaded(const QString &path); + void loadExternCmd(CommandLoader *loader, const QString &modName, const QString &cmdName, const QString &uniqueName, quint16 id); + void addCommandToList(quint16 cmdId, const QString &cmdName, const QString &modName, ExternCommand *cmdObj); bool externBlockedTypeId(uchar typeId); bool p2pBlockedTypeId(uchar typeId); bool allowCmdLoad(const QString &cmdName, const QString &modName, const QStringList &exemptList); QString makeCmdUnique(const QString &name); - quint16 getModIdOffs(const QString &path); + QString getModFile(const QString &modName); + quint16 getModIdOffs(const QString &name); private slots: @@ -82,10 +82,10 @@ public slots: void close(); void buildCommands(); + void buildCmdLoaders(); void wrCrashDebugInfo(const QString &msg); - void unloadModFile(const QString &path); - void loadModFile(const QString &path); - void loadModLib(const QString &path, quint16 idOffs); + void unloadModFile(const QString &modName); + void loadModFile(const QString &modName); void exeCmd(quint16 cmdId, const QByteArray &data, uchar typeId); void backendFromCmd(quint16 cmdId, const QByteArray &data, uchar typeId); diff --git a/src/commands/command.h b/src/commands/command.h index b8a93ca..a696815 100644 --- a/src/commands/command.h +++ b/src/commands/command.h @@ -152,31 +152,19 @@ public: virtual ~CommandLoader() {} - virtual QStringList pubCmdList() {return QStringList();} - virtual QStringList cmdList() {return QStringList();} - virtual QStringList rankExemptList() {return QStringList();} - virtual ExternCommand *cmdObj(const QString &) {return nullptr;} -}; - -class ModCommandLoader : public CommandLoader -{ - Q_OBJECT - -public: - - explicit ModCommandLoader(QObject *parent = nullptr) : CommandLoader(parent) {} - - virtual ~ModCommandLoader() {} - - virtual void modPath(const QString &) {} - virtual void aboutToDelete() {} - virtual bool hostRevOk(quint64) {return false;} - virtual QString lastError() {return "";} - virtual quint64 rev() {return 0;} + virtual void modPath(const QString &) {} + virtual void aboutToDelete() {} + virtual bool hostRevOk(quint64) {return false;} + virtual QString lastError() {return "";} + virtual quint64 rev() {return 0;} + virtual QStringList pubCmdList() {return QStringList();} + virtual QStringList cmdList() {return QStringList();} + virtual QStringList rankExemptList() {return QStringList();} + virtual ExternCommand *cmdObj(const QString &) {return nullptr;} }; QT_BEGIN_NAMESPACE -Q_DECLARE_INTERFACE(ModCommandLoader, MOD_LOADER_IID) +Q_DECLARE_INTERFACE(CommandLoader, MOD_LOADER_IID) QT_END_NAMESPACE #endif // EXTERN_COMMAND_H diff --git a/src/commands/info.cpp b/src/commands/info.cpp index 71001af..4d129c9 100644 --- a/src/commands/info.cpp +++ b/src/commands/info.cpp @@ -38,14 +38,31 @@ QString ListDBG::cmdName() {return "ls_dbg";} QString MyInfo::cmdName() {return "my_info";} QString CmdInfo::cmdName() {return "cmd_info";} +bool ListCommands::strInRowTxt(const QString &str, const QStringList &rowTxt) +{ + bool ret = false; + + for (auto&& strInList : rowTxt) + { + if (strInList.contains(str, Qt::CaseInsensitive)) + { + ret = true; + + break; + } + } + + return ret; +} + void ListCommands::procBin(const SharedObjs *sharedObjs, const QByteArray &data, uchar dType) { Q_UNUSED(sharedObjs); if (dType == TEXT) { - QString find = getParam("-find", parseArgs(data, 2)); - QList cmdIds = sharedObjs->cmdNames->keys(); + QString find = getParam("-find", parseArgs(data, 2)); + QStringList cmdNames = sharedObjs->cmdNames->values(); QList tableData; QStringList separators; QList justLens; @@ -56,18 +73,20 @@ void ListCommands::procBin(const SharedObjs *sharedObjs, const QByteArray &data, separators.append("-------"); } + cmdNames.sort(Qt::CaseInsensitive); tableData.append(QStringList() << "command_id" << "command_name" << "summary"); tableData.append(separators); - for (auto&& cmdId: cmdIds) + for (auto&& cmdName: cmdNames) { QStringList rowData; + quint16 id = sharedObjs->cmdNames->key(cmdName); - rowData.append(QString::number(cmdId)); - rowData.append(sharedObjs->cmdNames->value(cmdId)); - rowData.append(rwSharedObjs->commands->value(cmdId)->shortText()); + rowData.append(QString::number(id)); + rowData.append(cmdName); + rowData.append(rwSharedObjs->commands->value(id)->shortText()); - if (find.isEmpty() || rowData.contains(find, Qt::CaseInsensitive)) + if (find.isEmpty() || strInRowTxt(find, rowData)) { for (int k = 0; k < justLens.size(); ++k) { diff --git a/src/commands/info.h b/src/commands/info.h index 16d9a1d..8cb3d50 100644 --- a/src/commands/info.h +++ b/src/commands/info.h @@ -24,6 +24,10 @@ class ListCommands : public InternCommand { Q_OBJECT +private: + + bool strInRowTxt(const QString &str, const QStringList &rowTxt); + public: static QString cmdName(); diff --git a/src/commands/mods.cpp b/src/commands/mods.cpp index c2f463f..b0dbbb2 100644 --- a/src/commands/mods.cpp +++ b/src/commands/mods.cpp @@ -139,7 +139,7 @@ void UploadMod::procFinished(int exStatus) db.addCondition(COLUMN_MOD_NAME, modName); db.exec(); - emit backendDataOut(ASYNC_ENABLE_MOD, toTEXT(modPath), PUB_IPC_WITH_FEEDBACK); + emit backendDataOut(ASYNC_ENABLE_MOD, toTEXT(modName), PUB_IPC_WITH_FEEDBACK); mainTxt("\nFinished..."); } @@ -187,12 +187,14 @@ void UploadMod::procStartError(QProcess::ProcessError err) void UploadMod::setup() { + mkPath(modPath); + if (QLibrary::isLibrary(clientFile)) { QString suffix = QFileInfo(clientFile).completeSuffix(); QString dst = modPath + "/main." + suffix; - mainTxt("copy file: " + fileBuff->fileName() + " --> " + dst + "/n"); + mainTxt("copy file: " + fileBuff->fileName() + " --> " + dst + "\n"); if (QFile::copy(fileBuff->fileName(), dst)) { @@ -348,10 +350,8 @@ void DelMod::procBin(const SharedObjs *sharedObjs, const QByteArray &binIn, ucha db.addCondition(COLUMN_MOD_NAME, name); db.exec(); - QByteArray modPath = toTEXT(modDataPath() + "/" + name + "/main"); - - emit backendDataOut(ASYNC_DISABLE_MOD, modPath, PRIV_IPC); - emit backendDataOut(ASYNC_DISABLE_MOD, modPath, PUB_IPC_WITH_FEEDBACK); + emit backendDataOut(ASYNC_DISABLE_MOD, toTEXT(name), PRIV_IPC); + emit backendDataOut(ASYNC_DISABLE_MOD, toTEXT(name), PUB_IPC_WITH_FEEDBACK); } } } diff --git a/src/common.h b/src/common.h index 363f68e..0a38490 100644 --- a/src/common.h +++ b/src/common.h @@ -74,7 +74,7 @@ #define FRAME_HEADER_SIZE 6 #define MAX_FRAME_BITS 24 -#define IMPORT_REV 1 +#define IMPORT_REV 2 #define LOCAL_BUFFSIZE 16777215 #define CLIENT_INIT_TIME 5000 #define IPC_PREP_TIME 1000 @@ -353,8 +353,6 @@ signals: void termAllCommands(); void castPeerInfo(); void reloadCommands(); - void loadMod(const QString &path); - void unloadMod(const QString &path); void termCommandId(quint16 cmdId); void backendDataOut(quint16 cmdId, const QByteArray &data, uchar typeId); }; diff --git a/src/db.h b/src/db.h index 9850eeb..135e3da 100644 --- a/src/db.h +++ b/src/db.h @@ -37,7 +37,7 @@ #include "shell.h" #define APP_NAME "MRCI" -#define APP_VER "1.0.0" +#define APP_VER "1.0.1" #define APP_TARGET "mrci" #ifdef Q_OS_WIN diff --git a/src/session.cpp b/src/session.cpp index 477959a..498f95a 100644 --- a/src/session.cpp +++ b/src/session.cpp @@ -148,6 +148,7 @@ void Session::startAsSlave(const QStringList &args) connect(exeThr, &QThread::finished, executor, &CmdExecutor::deleteLater); connect(exeThr, &QThread::finished, exeThr, &QThread::deleteLater); + connect(exeThr, &QThread::started, executor, &CmdExecutor::buildCmdLoaders); connect(executor, &CmdExecutor::okToDelete, this, &Session::closeInstance); connect(executor, &CmdExecutor::okToDelete, exeThr, &QThread::quit); @@ -921,7 +922,7 @@ void Session::backendDataIn(quint16 cmdId, const QByteArray &data) } else if (cmdId == ASYNC_DISABLE_MOD) { - emit delayedDirDel(QFileInfo(fromTEXT(data)).absolutePath()); + emit delayedModDel(fromTEXT(data)); } } else @@ -1169,6 +1170,7 @@ void Session::backendDataIn(quint16 cmdId, const QByteArray &data) else if (cmdId == ASYNC_ENABLE_MOD) { emit loadModFile(fromTEXT(data)); + emit loadCommands(); } else if (cmdId == ASYNC_DISABLE_MOD) { diff --git a/src/session.h b/src/session.h index 41f3f96..f308501 100644 --- a/src/session.h +++ b/src/session.h @@ -116,9 +116,9 @@ signals: void backendToPeers(quint16 cmdId, const QByteArray data); void connectPeers(QSharedPointer peer); void setMaxSessions(uint value); - void unloadModFile(const QString &path); - void loadModFile(const QString &path); - void delayedDirDel(const QString &path); + void unloadModFile(const QString &modName); + void loadModFile(const QString &modName); + void delayedModDel(const QString &modName); void ended(); void closeExe(); void closeServer(); diff --git a/src/tcp_server.cpp b/src/tcp_server.cpp index 25ec37b..0901211 100644 --- a/src/tcp_server.cpp +++ b/src/tcp_server.cpp @@ -16,11 +16,55 @@ // along with MRCI under the LICENSE.md file. If not, see // . +ModDeleteTimer::ModDeleteTimer(const QString &mod, QStringList *queue, QObject *parent) : QTimer (parent) +{ + delQueue = queue; + modName = mod; + + setInterval(5000); // 5 seconds + + queue->append(mod); + + connect(this, &ModDeleteTimer::timeout, this, &ModDeleteTimer::delMod); +} + +void ModDeleteTimer::resetTimer(const QString &mod) +{ + if (modName == mod) + { + start(); + } +} + +void ModDeleteTimer::delMod() +{ + Query db(this); + + db.setType(Query::PULL, TABLE_MODULES); + db.addColumn(COLUMN_MOD_MAIN); + db.addCondition(COLUMN_MOD_NAME, modName); + db.exec(); + + if (db.rows()) + { + QString file = db.getData(COLUMN_MOD_MAIN).toString(); + + QDir(QFileInfo(file).path()).removeRecursively(); + + db.setType(Query::DEL, TABLE_MODULES); + db.addCondition(COLUMN_MOD_NAME, modName); + db.exec(); + } + + delQueue->removeAll(modName); + + deleteLater(); +} + TCPServer::TCPServer(QObject *parent) : QTcpServer(parent) { sessionCounter = new QSharedMemory(sessionCountShareKey(), this); controlPipe = new QLocalServer(this); - dirDelTimer = new QTimer(this); controlSocket = nullptr; flags = 0; @@ -28,7 +72,6 @@ TCPServer::TCPServer(QObject *parent) : QTcpServer(parent) sessionCounter->attach(); connect(controlPipe, &QLocalServer::newConnection, this, &TCPServer::newPipeConnection); - connect(dirDelTimer, &QTimer::timeout, this, &TCPServer::delDir); } void TCPServer::newPipeConnection() @@ -91,8 +134,6 @@ bool TCPServer::start() ret = true; flags |= ACCEPTING; - - syncModPath(); } else { @@ -104,42 +145,6 @@ bool TCPServer::start() return ret; } -void TCPServer::syncModPath() -{ - QDir dir(modDataPath()); - - dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); - - QStringList modNames = dir.entryList(); - - for (auto&& modName : modNames) - { - QString modPath = dir.absolutePath() + "/" + modName; - - if (!QFile::exists(modPath + "/main")) - { - QDir(modPath).removeRecursively(); - } - else if (!modExists(modName)) - { - Query db(this); - - db.setType(Query::PULL, TABLE_MODULES); - db.addColumn(COLUMN_MOD_NAME); - db.exec(); - - quint16 idOffs = static_cast((db.rows() + 2) * MAX_CMDS_PER_MOD); - - db.setType(Query::PUSH, TABLE_MODULES); - db.addColumn(COLUMN_MOD_NAME, modName); - db.addColumn(COLUMN_MOD_MAIN, modPath + "/main"); - db.addColumn(COLUMN_LOCKED, false); - db.addColumn(COLUMN_CMD_ID_OFFS, idOffs); - db.exec(); - } - } -} - void TCPServer::sessionEnded() { uint count = rdSessionLoad() - 1; @@ -258,32 +263,16 @@ bool TCPServer::inBanList(const QString &ip) return db.rows(); } -void TCPServer::delDir() +void TCPServer::delayedModDel(const QString &modName) { - if (dirsToDel.isEmpty()) + if (!modDelQueue.contains(modName)) { - dirDelTimer->stop(); + auto *timer = new ModDeleteTimer(modName, &modDelQueue, this); + + connect(this, &TCPServer::resetModDelTimer, timer, &ModDeleteTimer::resetTimer); } - else - { - QString path = dirsToDel.takeFirst(); - Query db(this); - - db.setType(Query::DEL, TABLE_MODULES); - db.addCondition(COLUMN_MOD_MAIN, path, Query::LIKE); - db.exec(); - - QDir(path).removeRecursively(); - } -} - -void TCPServer::delayedDirDel(const QString &path) -{ - dirDelTimer->setSingleShot(false); - dirDelTimer->start(5000); - - dirsToDel.append(path); + emit resetModDelTimer(modName); } void TCPServer::incomingConnection(qintptr socketDescriptor) @@ -318,7 +307,7 @@ void TCPServer::incomingConnection(qintptr socketDescriptor) connect(ses, &Session::ended, this, &TCPServer::sessionEnded); connect(ses, &Session::ended, thr, &QThread::quit); connect(ses, &Session::connectPeers, this, &TCPServer::connectPeers); - connect(ses, &Session::delayedDirDel, this, &TCPServer::delayedDirDel); + connect(ses, &Session::delayedModDel, this, &TCPServer::delayedModDel); connect(ses, &Session::closeServer, this, &TCPServer::closeServer); connect(ses, &Session::resServer, this, &TCPServer::resServer); diff --git a/src/tcp_server.h b/src/tcp_server.h index e95b9f7..f6925f3 100644 --- a/src/tcp_server.h +++ b/src/tcp_server.h @@ -23,6 +23,30 @@ #include "make_cert.h" #include "openssl/ssl.h" +class ModDeleteTimer : public QTimer +{ + Q_OBJECT + +private: + + QString modName; + QStringList *delQueue; + +private slots: + + void delMod(); + +public slots: + + void resetTimer(const QString &mod); + +public: + + explicit ModDeleteTimer(const QString &mod, QStringList *queue, QObject *parent = nullptr); +}; + +//-------------------------- + class TCPServer: public QTcpServer { Q_OBJECT @@ -32,23 +56,20 @@ private: QSharedMemory *sessionCounter; QLocalServer *controlPipe; QLocalSocket *controlSocket; - QTimer *dirDelTimer; - QStringList dirsToDel; + QStringList modDelQueue; uint flags; bool servOverloaded(); bool inBanList(const QString &ip); - void syncModPath(); void incomingConnection(qintptr socketDescriptor); private slots: - void delDir(); void procPipeIn(); void newPipeConnection(); void closedPipeConnection(); void sessionEnded(); - void delayedDirDel(const QString &path); + void delayedModDel(const QString &modName); public slots: @@ -64,26 +85,8 @@ public: signals: void connectPeers(QSharedPointer peer); + void resetModDelTimer(const QString &modName); void endAllSessions(); }; -//-------------------------------- - -class IPCServer: public QLocalServer -{ - Q_OBJECT - -private: - - uint flags; - - void incomingConnection(qintptr socketDescriptor); - -public: - - explicit IPCServer(QObject *parent = nullptr); - - bool start(); -}; - #endif // TCP_SERVER_H