From f794e49bb6eadd70c52683e60a700a1d7e9cd17b Mon Sep 17 00:00:00 2001 From: Rachel Powers <508861+Ryex@users.noreply.github.com> Date: Mon, 6 Feb 2023 23:05:06 -0800 Subject: we want to make links! Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com> --- launcher/filelink/FileLink.cpp | 119 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 launcher/filelink/FileLink.cpp (limited to 'launcher/filelink/FileLink.cpp') diff --git a/launcher/filelink/FileLink.cpp b/launcher/filelink/FileLink.cpp new file mode 100644 index 00000000..9b5589ab --- /dev/null +++ b/launcher/filelink/FileLink.cpp @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> +// +// SPDX-License-Identifier: GPL-3.0-only + +/* + * Prism Launcher - Minecraft Launcher + * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> + * + * This program 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, version 3. + * + * This program 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 this program. If not, see . + * + */ + +#include "FileLink.h" +#include "BuildConfig.h" + + +#include + +#include +#include + +#include + + +#include +#include + +#include + +#if defined Q_OS_WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#endif + + + + +FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv) +{ +#if defined Q_OS_WIN32 + // attach the parent console + if(AttachConsole(ATTACH_PARENT_PROCESS)) + { + // if attach succeeds, reopen and sync all the i/o + if(freopen("CON", "w", stdout)) + { + std::cout.sync_with_stdio(); + } + if(freopen("CON", "w", stderr)) + { + std::cerr.sync_with_stdio(); + } + if(freopen("CON", "r", stdin)) + { + std::cin.sync_with_stdio(); + } + auto out = GetStdHandle (STD_OUTPUT_HANDLE); + DWORD written; + const char * endline = "\n"; + WriteConsole(out, endline, strlen(endline), &written, NULL); + consoleAttached = true; + } +#endif + setOrganizationName(BuildConfig.LAUNCHER_NAME); + setOrganizationDomain(BuildConfig.LAUNCHER_DOMAIN); + setApplicationName(BuildConfig.LAUNCHER_NAME + "FileLink"); + setApplicationVersion(BuildConfig.printableVersionString() + "\n" + BuildConfig.GIT_COMMIT); + + // Commandline parsing + QCommandLineParser parser; + parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be useed with prismlauncher")); + + parser.addOptions({ + + }); + parser.addHelpOption(); + parser.addVersionOption(); + + parser.process(arguments()); + + qDebug() << "link program launched"; + +} + + +FileLinkApp::~FileLinkApp() +{ + qDebug() << "link program shutting down"; + // Shut down logger by setting the logger function to nothing + qInstallMessageHandler(nullptr); + +#if defined Q_OS_WIN32 + // Detach from Windows console + if(consoleAttached) + { + fclose(stdout); + fclose(stdin); + fclose(stderr); + FreeConsole(); + } +#endif +} + + + + -- cgit From 6d160a7b7e31034c7a657f30003562c20f9b9c21 Mon Sep 17 00:00:00 2001 From: Rachel Powers <508861+Ryex@users.noreply.github.com> Date: Wed, 8 Feb 2023 00:35:03 -0800 Subject: feat: successful process elevation and comunication! Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com> --- launcher/CMakeLists.txt | 9 +- launcher/DesktopServices.cpp | 2 +- launcher/FileSystem.cpp | 140 +++++++++++++++++++++++++++---- launcher/FileSystem.h | 57 +++++++++++-- launcher/StringUtils.cpp | 15 ++++ launcher/StringUtils.h | 2 + launcher/filelink/FileLink.cpp | 106 ++++++++++++++++++++++-- launcher/filelink/FileLink.h | 15 ++++ tests/FileSystem_test.cpp | 181 +++++++++++++++++++++++++++-------------- 9 files changed, 437 insertions(+), 90 deletions(-) (limited to 'launcher/filelink/FileLink.cpp') diff --git a/launcher/CMakeLists.txt b/launcher/CMakeLists.txt index 18d4ce0b..dd62893c 100644 --- a/launcher/CMakeLists.txt +++ b/launcher/CMakeLists.txt @@ -562,6 +562,13 @@ set(ATLAUNCHER_SOURCES set(LINKEXE_SOURCES filelink/FileLink.h filelink/FileLink.cpp + FileSystem.h + FileSystem.cpp + Exception.h + StringUtils.h + StringUtils.cpp + DesktopServices.h + DesktopServices.cpp ) ######## Logging categories ######## @@ -1126,8 +1133,6 @@ if(WIN32) Qt${QT_VERSION_MAJOR}::Xml Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::Concurrent - Qt${QT_VERSION_MAJOR}::Gui - Qt${QT_VERSION_MAJOR}::Widgets ${Launcher_QT_LIBS} ) diff --git a/launcher/DesktopServices.cpp b/launcher/DesktopServices.cpp index 302eaf96..69770e99 100644 --- a/launcher/DesktopServices.cpp +++ b/launcher/DesktopServices.cpp @@ -37,7 +37,7 @@ #include #include #include -#include "Application.h" +//#include "Application.h" /** * This shouldn't exist, but until QTBUG-9328 and other unreported bugs are fixed, it needs to be a thing. diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index ec4af98c..9e51f932 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -36,6 +36,8 @@ #include "FileSystem.h" +#include "BuildConfig.h" + #include #include #include @@ -45,6 +47,7 @@ #include #include #include +#include #include "DesktopServices.h" #include "StringUtils.h" @@ -61,6 +64,11 @@ #include #include #include +//for ShellExecute +#include +//#include +#include +#include #else #include #endif @@ -218,19 +226,29 @@ bool copy::operator()(const QString& offset, bool dryRun) } +bool create_link::operator()(const QString& offset, bool dryRun) +{ + + for (auto pair : m_path_pairs) { + if (!make_link(pair.src, pair.dst, offset, dryRun)) { + return false; + } + } + return true; +} + + /** * @brief links a directory and it's contents from src to dest * @param offset subdirectory form src to link to dest * @return if there was an error during the attempt to link */ -bool create_link::operator()(const QString& offset, bool dryRun) +bool create_link::make_link(const QString& srcPath, const QString& dstPath, const QString& offset, bool dryRun) { m_linked = 0; // reset counter - auto src = PathCombine(m_src.absolutePath(), offset); - auto dst = PathCombine(m_dst.absolutePath(), offset); - - std::error_code err; + auto src = PathCombine(QDir(srcPath).absolutePath(), offset); + auto dst = PathCombine(QDir(dstPath).absolutePath(), offset); // you can't hard link a directory so make sure if we deal with a directory we do so recursively if (m_useHardLinks) @@ -248,26 +266,25 @@ bool create_link::operator()(const QString& offset, bool dryRun) if (m_useHardLinks) { if (m_debug) qDebug() << "making hard link:" << src_path << "to" << dst_path; - fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), err); + fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); } else if (fs::is_directory(StringUtils::toStdString(src_path))) { if (m_debug) qDebug() << "making directory_symlink:" << src_path << "to" << dst_path; - fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), err); + fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); } else { if (m_debug) qDebug() << "making symlink:" << src_path << "to" << dst_path; - fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), err); + fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); } } - if (err) { - qWarning() << "Failed to link files:" << QString::fromStdString(err.message()); + if (m_os_err) { + qWarning() << "Failed to link files:" << QString::fromStdString(m_os_err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; - qDebug() << "Error catagory:" << err.category().name(); - qDebug() << "Error code:" << err.value(); - m_last_os_err = err.value(); - emit linkFailed(src_path, dst_path, err); + qDebug() << "Error catagory:" << m_os_err.category().name(); + qDebug() << "Error code:" << m_os_err.value(); + emit linkFailed(src_path, dst_path, m_os_err); } else { m_linked++; emit fileLinked(relative_dst_path); @@ -290,10 +307,103 @@ bool create_link::operator()(const QString& offset, bool dryRun) auto relative_path = src_dir.relativeFilePath(src_path); link_file(src_path, relative_path); + if (m_os_err) return false; } } - return err.value() == 0; + return m_os_err.value() == 0; +} + +bool create_link::runPrivlaged(const QString& offset) +{ + + QString serverName = BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink_server" + StringUtils::getRandomAlphaNumeric(8); + + connect(&m_linkServer, &QLocalServer::newConnection, this, [&](){ + + qDebug() << "Client connected, sending out pairs"; + // construct block of data to send + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_5_15); // choose correct version better? + + qint32 blocksize = quint32(sizeof(quint32)); + for (auto pair : m_path_pairs) { + blocksize += quint32(pair.src.size()); + blocksize += quint32(pair.dst.size()); + } + qDebug() << "About to write block of size:" << blocksize; + out << blocksize; + + out << quint32(m_path_pairs.length()); + for (auto pair : m_path_pairs) { + out << pair.src; + out << pair.dst; + } + + QLocalSocket *clientConnection = m_linkServer.nextPendingConnection(); + connect(clientConnection, &QLocalSocket::disconnected, + clientConnection, &QLocalSocket::deleteLater); + + qint64 byteswritten = clientConnection->write(block); + bool bytesflushed = clientConnection->flush(); + qDebug() << "block flushed" << byteswritten << bytesflushed; + //clientConnection->disconnectFromServer(); + }); + + qDebug() << "Listening on pipe" << serverName; + if (!m_linkServer.listen(serverName)) { + qDebug() << "Unable to start local pipe server on" << serverName << ":" << m_linkServer.errorString(); + return false; + } + + ExternalLinkFileProcess *linkFileProcess = new ExternalLinkFileProcess(serverName, this); + connect(linkFileProcess, &ExternalLinkFileProcess::processExited, this, [&](){ + emit finishedPrivlaged(); + }); + connect(linkFileProcess, &ExternalLinkFileProcess::finished, linkFileProcess, &QObject::deleteLater); + + linkFileProcess->start(); + + // linkFileProcess->wait(); + + return true; +} + + +void ExternalLinkFileProcess::runLinkFile() { + QString fileLinkExe = PathCombine(QCoreApplication::instance()->applicationDirPath(), BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink"); + QString params = "-s " + m_server; + +#if defined Q_OS_WIN32 + SHELLEXECUTEINFO ShExecInfo; + HRESULT hr; + + fileLinkExe = fileLinkExe + ".exe"; + + qDebug() << "Running: runas" << fileLinkExe << params; + + LPCWSTR programNameWin = (const wchar_t*) fileLinkExe.utf16(); + LPCWSTR paramsWin = (const wchar_t*) params.utf16(); + + // https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfoa + ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); + ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; + ShExecInfo.hwnd = NULL; // Optional. A handle to the owner window, used to display and position any UI that the system might produce while executing this function. + ShExecInfo.lpVerb = L"runas"; // elevate to admin, show UAC + ShExecInfo.lpFile = programNameWin; + ShExecInfo.lpParameters = paramsWin; + ShExecInfo.lpDirectory = NULL; + ShExecInfo.nShow = SW_NORMAL; + ShExecInfo.hInstApp = NULL; + + ShellExecuteEx(&ShExecInfo); + + WaitForSingleObject(ShExecInfo.hProcess, INFINITE); + CloseHandle(ShExecInfo.hProcess); +#endif + + qDebug() << "Process exited"; } bool move(const QString& source, const QString& dest) diff --git a/launcher/FileSystem.h b/launcher/FileSystem.h index 98f55f96..b15d1685 100644 --- a/launcher/FileSystem.h +++ b/launcher/FileSystem.h @@ -39,9 +39,13 @@ #include "Exception.h" #include "pathmatcher/IPathMatcher.h" +#include + #include #include #include +#include +#include namespace FS { @@ -124,16 +128,45 @@ class copy : public QObject { int m_copied; }; +struct LinkPair { + QString src; + QString dst; +}; + +class ExternalLinkFileProcess : public QThread +{ + Q_OBJECT + public: + ExternalLinkFileProcess(QString server, QObject* parent = nullptr) : QThread(parent), m_server(server) {} + + void run() override { + runLinkFile(); + emit processExited(); + } + + signals: + void processExited(); + + private: + void runLinkFile(); + + QString m_server; +}; + /** - * @brief Copies a directory and it's contents from src to dest + * @brief links (a file / a directory and it's contents) from src to dest */ class create_link : public QObject { Q_OBJECT public: + create_link(const QList path_pairs, QObject* parent = nullptr) : QObject(parent) + { + m_path_pairs.append(path_pairs); + } create_link(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent) { - m_src.setPath(src); - m_dst.setPath(dst); + LinkPair pair = {src, dst}; + m_path_pairs.append(pair); } create_link& useHardLinks(const bool useHard) { @@ -161,31 +194,39 @@ class create_link : public QObject { return *this; } - int getLastOSError() { - return m_last_os_err; + std::error_code getOSError() { + return m_os_err; } bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); } + bool runPrivlaged() { return runPrivlaged(QString()); } + bool runPrivlaged(const QString& offset); + int totalLinked() { return m_linked; } signals: void fileLinked(const QString& relativeName); void linkFailed(const QString& srcName, const QString& dstName, std::error_code err); + void finishedPrivlaged(); private: bool operator()(const QString& offset, bool dryRun = false); + bool make_link(const QString& src_path, const QString& dst_path, const QString& offset, bool dryRun); private: bool m_useHardLinks = false; const IPathMatcher* m_matcher = nullptr; bool m_whitelist = false; bool m_recursive = true; - QDir m_src; - QDir m_dst; + + QList m_path_pairs; + int m_linked; bool m_debug = false; - int m_last_os_err = 0; + std::error_code m_os_err; + + QLocalServer m_linkServer; }; /** diff --git a/launcher/StringUtils.cpp b/launcher/StringUtils.cpp index 0f3c3669..93a44d4c 100644 --- a/launcher/StringUtils.cpp +++ b/launcher/StringUtils.cpp @@ -1,5 +1,7 @@ #include "StringUtils.h" +#include + /// If you're wondering where these came from exactly, then know you're not the only one =D /// TAKEN FROM Qt, because it doesn't expose it intelligently @@ -74,3 +76,16 @@ int StringUtils::naturalCompare(const QString& s1, const QString& s2, Qt::CaseSe // The two strings are the same (02 == 2) so fall back to the normal sort return QString::compare(s1, s2, cs); } + +QString StringUtils::getRandomAlphaNumeric(const int length) +{ + const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); + QString randomString; + for(int i=0; i < length; ++i) + { + int index = QRandomGenerator::global()->bounded(0, possibleCharacters.length()); + QChar nextChar = possibleCharacters.at(index); + randomString.append(nextChar); + } + return randomString; +} diff --git a/launcher/StringUtils.h b/launcher/StringUtils.h index 1799605b..1ba19555 100644 --- a/launcher/StringUtils.h +++ b/launcher/StringUtils.h @@ -29,4 +29,6 @@ inline QString fromStdString(string s) #endif int naturalCompare(const QString& s1, const QString& s2, Qt::CaseSensitivity cs); + +QString getRandomAlphaNumeric(const int length); } // namespace StringUtils diff --git a/launcher/filelink/FileLink.cpp b/launcher/filelink/FileLink.cpp index 9b5589ab..78486507 100644 --- a/launcher/filelink/FileLink.cpp +++ b/launcher/filelink/FileLink.cpp @@ -31,8 +31,6 @@ #include - -#include #include #include @@ -48,7 +46,7 @@ -FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv) +FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv), socket(new QLocalSocket(this)) { #if defined Q_OS_WIN32 // attach the parent console @@ -81,18 +79,116 @@ FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv) // Commandline parsing QCommandLineParser parser; - parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be useed with prismlauncher")); + parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be used with prismlauncher")); parser.addOptions({ - + {{"s", "server"}, "Join the specified server on launch", "pipe name"} }); parser.addHelpOption(); parser.addVersionOption(); parser.process(arguments()); + QString serverToJoin = parser.value("server"); + qDebug() << "link program launched"; + if (!serverToJoin.isEmpty()) { + qDebug() << "joining server" << serverToJoin; + joinServer(serverToJoin); + } else { + qDebug() << "no server to join"; + exit(); + } + +} + +void FileLinkApp::joinServer(QString server) +{ + + blockSize = 0; + + in.setDevice(&socket); + in.setVersion(QDataStream::Qt_5_15); + + connect(&socket, &QLocalSocket::connected, this, [&](){ + qDebug() << "connected to server"; + }); + + connect(&socket, &QLocalSocket::readyRead, this, &FileLinkApp::readPathPairs); + + connect(&socket, &QLocalSocket::errorOccurred, this, [&](QLocalSocket::LocalSocketError socketError){ + switch (socketError) { + case QLocalSocket::ServerNotFoundError: + qDebug() << tr("The host was not found. Please make sure " + "that the server is running and that the " + "server name is correct."); + break; + case QLocalSocket::ConnectionRefusedError: + qDebug() << tr("The connection was refused by the peer. " + "Make sure the server is running, " + "and check that the server name " + "is correct."); + break; + case QLocalSocket::PeerClosedError: + break; + default: + qDebug() << tr("The following error occurred: %1.").arg(socket.errorString()); + } + }); + + connect(&socket, &QLocalSocket::disconnected, this, [&](){ + qDebug() << "dissconnected from server"; + }); + + socket.connectToServer(server); + + +} + +void FileLinkApp::runLink() +{ + qDebug() << "creating link"; + FS::create_link lnk(m_path_pairs); + lnk.debug(true); + if (!lnk()) { + qDebug() << "Link Failed!" << lnk.getOSError().value() << lnk.getOSError().message().c_str(); + } + //exit(); + qDebug() << "done, should exit"; +} + +void FileLinkApp::readPathPairs() +{ + m_path_pairs.clear(); + qDebug() << "Reading path pairs from server"; + qDebug() << "bytes avalible" << socket.bytesAvailable(); + if (blockSize == 0) { + // Relies on the fact that QDataStream serializes a quint32 into + // sizeof(quint32) bytes + if (socket.bytesAvailable() < (int)sizeof(quint32)) + return; + qDebug() << "reading block size"; + in >> blockSize; + } + qDebug() << "blocksize is" << blockSize; + qDebug() << "bytes avalible" << socket.bytesAvailable(); + if (socket.bytesAvailable() < blockSize || in.atEnd()) + return; + + quint32 numPairs; + in >> numPairs; + qDebug() << "numPairs" << numPairs; + + for(int i = 0; i < numPairs; i++) { + FS::LinkPair pair; + in >> pair.src; + in >> pair.dst; + qDebug() << "link" << pair.src << "to" << pair.dst; + m_path_pairs.append(pair); + } + + runLink(); } diff --git a/launcher/filelink/FileLink.h b/launcher/filelink/FileLink.h index 253d1394..5d0ba123 100644 --- a/launcher/filelink/FileLink.h +++ b/launcher/filelink/FileLink.h @@ -32,6 +32,11 @@ #include #include #include +#include +#include + +#define PRISM_EXTERNAL_EXE +#include "FileSystem.h" class FileLinkApp : public QCoreApplication { @@ -43,7 +48,17 @@ public: virtual ~FileLinkApp(); private: + + void joinServer(QString server); + void readPathPairs(); + void runLink(); + QDateTime m_startTime; + QLocalSocket socket; + QDataStream in; + quint32 blockSize; + + QList m_path_pairs; #if defined Q_OS_WIN32 // used on Windows to attach the standard IO streams diff --git a/tests/FileSystem_test.cpp b/tests/FileSystem_test.cpp index 395ca5c0..be0a4be0 100644 --- a/tests/FileSystem_test.cpp +++ b/tests/FileSystem_test.cpp @@ -2,6 +2,8 @@ #include #include +#include + #include #include @@ -26,6 +28,66 @@ namespace fs = ghc::filesystem; #include + + +class LinkTask : public Task { + Q_OBJECT + + friend class FileSystemTest; + + LinkTask(QString src, QString dst) + { + m_lnk = new FS::create_link(src, dst, this); + m_lnk->debug(true); + } + + void matcher(const IPathMatcher *filter) + { + m_lnk->matcher(filter); + } + + void linkRecursively(bool recursive) + { + m_lnk->linkRecursively(recursive); + m_linkRecursive = recursive; + } + + void whitelist(bool b) + { + m_lnk->whitelist(b); + } + + private: + void executeTask() override + { + if(!(*m_lnk)()){ +#if defined Q_OS_WIN32 + if (!m_useHard) { + qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; + + qDebug() << "atempting to run with privelage"; + connect(m_lnk, &FS::create_link::finishedPrivlaged, this, [&](){ + emitSucceeded(); + }); + m_lnk->runPrivlaged(); + } else { + qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str(); + } +#else + qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str(); +#endif + } else { + emitSucceeded(); + } + + }; + + FS::create_link *m_lnk; + bool m_useHard = false; + bool m_linkRecursive = true; +}; + + class FileSystemTest : public QObject { Q_OBJECT @@ -273,7 +335,7 @@ slots: void test_link() { QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder"); - auto f = [&folder]() + auto f = [&folder, this]() { QTemporaryDir tempDir; tempDir.setAutoRemove(true); @@ -282,17 +344,17 @@ slots: QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder")); qDebug() << tempDir.path(); qDebug() << target_dir.path(); - FS::create_link lnk(folder, target_dir.path()); - lnk.linkRecursively(false); - lnk.debug(true); - if(!lnk()){ -#if defined Q_OS_WIN32 - qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; - QVERIFY(lnk.getLastOSError() == 1314); - return; -#endif - qDebug() << "Link Failed!" << lnk.getLastOSError(); - } + + LinkTask lnk_tsk(folder, target_dir.path()); + lnk_tsk.linkRecursively(false); + QObject::connect(&lnk_tsk, &Task::finished, [&]{ + QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been."); + }); + lnk_tsk.start(); + + QVERIFY2(QTest::qWaitFor([&]() { + return lnk_tsk.isFinished(); + }, 100000), "Task didn't finish as it should."); for(auto entry: target_dir.entryList()) { @@ -337,7 +399,7 @@ slots: lnk.useHardLinks(true); lnk.debug(true); if(!lnk()){ - qDebug() << "Link Failed!" << lnk.getLastOSError(); + qDebug() << "Link Failed!" << lnk.getOSError().value() << lnk.getOSError().message().c_str(); } for(auto entry: target_dir.entryList()) @@ -385,18 +447,19 @@ slots: QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder")); qDebug() << tempDir.path(); qDebug() << target_dir.path(); - FS::create_link lnk(folder, target_dir.path()); - lnk.matcher(new RegexpMatcher("[.]?mcmeta")); - lnk.linkRecursively(true); - lnk.debug(true); - if(!lnk()){ -#if defined Q_OS_WIN32 - qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; - QVERIFY(lnk.getLastOSError() == 1314); - return; -#endif - qDebug() << "Link Failed!" << lnk.getLastOSError(); - } + + LinkTask lnk_tsk(folder, target_dir.path()); + lnk_tsk.matcher(new RegexpMatcher("[.]?mcmeta")); + lnk_tsk.linkRecursively(true); + QObject::connect(&lnk_tsk, &Task::finished, [&]{ + QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been."); + }); + lnk_tsk.start(); + + QVERIFY2(QTest::qWaitFor([&]() { + return lnk_tsk.isFinished(); + }, 100000), "Task didn't finish as it should."); + for(auto entry: target_dir.entryList()) { @@ -435,19 +498,19 @@ slots: QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder")); qDebug() << tempDir.path(); qDebug() << target_dir.path(); - FS::create_link lnk(folder, target_dir.path()); - lnk.matcher(new RegexpMatcher("[.]?mcmeta")); - lnk.whitelist(true); - lnk.linkRecursively(true); - lnk.debug(true); - if(!lnk()){ -#if defined Q_OS_WIN32 - qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; - QVERIFY(lnk.getLastOSError() == 1314); - return; -#endif - qDebug() << "Link Failed!" << lnk.getLastOSError(); - } + + LinkTask lnk_tsk(folder, target_dir.path()); + lnk_tsk.matcher(new RegexpMatcher("[.]?mcmeta")); + lnk_tsk.linkRecursively(true); + lnk_tsk.whitelist(true); + QObject::connect(&lnk_tsk, &Task::finished, [&]{ + QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been."); + }); + lnk_tsk.start(); + + QVERIFY2(QTest::qWaitFor([&]() { + return lnk_tsk.isFinished(); + }, 100000), "Task didn't finish as it should."); for(auto entry: target_dir.entryList()) { @@ -486,17 +549,17 @@ slots: QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder")); qDebug() << tempDir.path(); qDebug() << target_dir.path(); - FS::create_link lnk(folder, target_dir.path()); - lnk.linkRecursively(true); - lnk.debug(true); - if(!lnk()){ -#if defined Q_OS_WIN32 - qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; - QVERIFY(lnk.getLastOSError() == 1314); - return; -#endif - qDebug() << "Link Failed!" << lnk.getLastOSError(); - } + + LinkTask lnk_tsk(folder, target_dir.path()); + lnk_tsk.linkRecursively(true); + QObject::connect(&lnk_tsk, &Task::finished, [&]{ + QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been."); + }); + lnk_tsk.start(); + + QVERIFY2(QTest::qWaitFor([&]() { + return lnk_tsk.isFinished(); + }, 100000), "Task didn't finish as it should."); auto filter = QDir::Filter::Files | QDir::Filter::Dirs | QDir::Filter::Hidden; @@ -538,16 +601,16 @@ slots: QDir target_dir(FS::PathCombine(tempDir.path(), "pack.mcmeta")); qDebug() << tempDir.path(); qDebug() << target_dir.path(); - FS::create_link lnk(file, target_dir.filePath("pack.mcmeta")); - lnk.debug(true); - if(!lnk()){ -#if defined Q_OS_WIN32 - qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; - QVERIFY(lnk.getLastOSError() == 1314); - return; -#endif - qDebug() << "Link Failed!" << lnk.getLastOSError(); - } + + LinkTask lnk_tsk(file, target_dir.filePath("pack.mcmeta")); + QObject::connect(&lnk_tsk, &Task::finished, [&]{ + QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been."); + }); + lnk_tsk.start(); + + QVERIFY2(QTest::qWaitFor([&]() { + return lnk_tsk.isFinished(); + }, 100000), "Task didn't finish as it should."); auto filter = QDir::Filter::Files; -- cgit From 8ba51c790098ec9ebe3d2ef686f823b61c8a3645 Mon Sep 17 00:00:00 2001 From: Rachel Powers <508861+Ryex@users.noreply.github.com> Date: Wed, 8 Feb 2023 12:36:15 -0800 Subject: refactor: make complete list of links to make and send that. Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com> --- launcher/FileSystem.cpp | 221 +++++++++++++++++++++++++++-------------- launcher/FileSystem.h | 35 +++++-- launcher/filelink/FileLink.cpp | 134 ++++++++++++++++++++----- launcher/filelink/FileLink.h | 6 +- tests/FileSystem_test.cpp | 11 +- 5 files changed, 293 insertions(+), 114 deletions(-) (limited to 'launcher/filelink/FileLink.cpp') diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index 9e51f932..c48a3bba 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -66,7 +66,6 @@ #include //for ShellExecute #include -//#include #include #include #else @@ -228,94 +227,120 @@ bool copy::operator()(const QString& offset, bool dryRun) bool create_link::operator()(const QString& offset, bool dryRun) { + m_linked = 0; // reset counter + m_path_results.clear(); + m_links_to_make.clear(); + + m_path_results.clear(); + + make_link_list(offset); + + if (!dryRun) + return make_links(); - for (auto pair : m_path_pairs) { - if (!make_link(pair.src, pair.dst, offset, dryRun)) { - return false; - } - } return true; } /** - * @brief links a directory and it's contents from src to dest + * @brief make a list off all the links ot make * @param offset subdirectory form src to link to dest * @return if there was an error during the attempt to link */ -bool create_link::make_link(const QString& srcPath, const QString& dstPath, const QString& offset, bool dryRun) +void create_link::make_link_list( const QString& offset) { - m_linked = 0; // reset counter + for (auto pair : m_path_pairs) { + const QString& srcPath = pair.src; + const QString& dstPath = pair.dst; - auto src = PathCombine(QDir(srcPath).absolutePath(), offset); - auto dst = PathCombine(QDir(dstPath).absolutePath(), offset); + auto src = PathCombine(QDir(srcPath).absolutePath(), offset); + auto dst = PathCombine(QDir(dstPath).absolutePath(), offset); - // you can't hard link a directory so make sure if we deal with a directory we do so recursively - if (m_useHardLinks) - m_recursive = true; + // you can't hard link a directory so make sure if we deal with a directory we do so recursively + if (m_useHardLinks) + m_recursive = true; - // Function that'll do the actual linking - auto link_file = [&](QString src_path, QString relative_dst_path) { - if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist)) - return; + // Function that'll do the actual linking + auto link_file = [&](QString src_path, QString relative_dst_path) { + if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist)) { + qDebug() << "path" << relative_dst_path << "in black list or not in whitelist"; + return; + } + - auto dst_path = PathCombine(dst, relative_dst_path); - if (!dryRun) { - - ensureFilePathExists(dst_path); - if (m_useHardLinks) { - if (m_debug) - qDebug() << "making hard link:" << src_path << "to" << dst_path; - fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); - } else if (fs::is_directory(StringUtils::toStdString(src_path))) { - if (m_debug) - qDebug() << "making directory_symlink:" << src_path << "to" << dst_path; - fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); - } else { - if (m_debug) - qDebug() << "making symlink:" << src_path << "to" << dst_path; - fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); + auto dst_path = PathCombine(dst, relative_dst_path); + LinkPair link = {src_path, dst_path}; + m_links_to_make.append(link); + }; + + if ((!m_recursive) || !fs::is_directory(StringUtils::toStdString(src))) { + if (m_debug) + qDebug() << "linking single file or dir:" << src << "to" << dst; + link_file(src, ""); + } else { + if (m_debug) + qDebug() << "linking recursivly:" << src << "to" << dst; + QDir src_dir(src); + QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); + + while (source_it.hasNext()) { + auto src_path = source_it.next(); + auto relative_path = src_dir.relativeFilePath(src_path); + + link_file(src_path, relative_path); } - } + } +} + +bool create_link::make_links() +{ + for (auto link : m_links_to_make) { + + QString src_path = link.src; + QString dst_path = link.dst; + + ensureFilePathExists(dst_path); + if (m_useHardLinks) { + if (m_debug) + qDebug() << "making hard link:" << src_path << "to" << dst_path; + fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); + } else if (fs::is_directory(StringUtils::toStdString(src_path))) { + if (m_debug) + qDebug() << "making directory_symlink:" << src_path << "to" << dst_path; + fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); + } else { + if (m_debug) + qDebug() << "making symlink:" << src_path << "to" << dst_path; + fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), m_os_err); + } + + if (m_os_err) { qWarning() << "Failed to link files:" << QString::fromStdString(m_os_err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; qDebug() << "Error catagory:" << m_os_err.category().name(); qDebug() << "Error code:" << m_os_err.value(); - emit linkFailed(src_path, dst_path, m_os_err); + emit linkFailed(src_path, dst_path, QString::fromStdString(m_os_err.message()), m_os_err.value()); } else { m_linked++; - emit fileLinked(relative_dst_path); - } - - }; - - if ((!m_recursive) || !fs::is_directory(StringUtils::toStdString(src))) { - if (m_debug) - qDebug() << "linking single file or dir:" << src << "to" << dst; - link_file(src, ""); - } else { - if (m_debug) - qDebug() << "linking recursivly:" << src << "to" << dst; - QDir src_dir(src); - QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); - - while (source_it.hasNext()) { - auto src_path = source_it.next(); - auto relative_path = src_dir.relativeFilePath(src_path); - - link_file(src_path, relative_path); - if (m_os_err) return false; + emit fileLinked(src_path, dst_path); } + if (m_os_err) return false; } - - return m_os_err.value() == 0; + return true; } -bool create_link::runPrivlaged(const QString& offset) +void create_link::runPrivlaged(const QString& offset) { + m_linked = 0; // reset counter + m_path_results.clear(); + m_links_to_make.clear(); + + bool gotResults = false; + + make_link_list(offset); QString serverName = BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink_server" + StringUtils::getRandomAlphaNumeric(8); @@ -325,25 +350,72 @@ bool create_link::runPrivlaged(const QString& offset) // construct block of data to send QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); - out.setVersion(QDataStream::Qt_5_15); // choose correct version better? + out.setVersion(QDataStream::Qt_5_0); // choose correct version better? qint32 blocksize = quint32(sizeof(quint32)); - for (auto pair : m_path_pairs) { - blocksize += quint32(pair.src.size()); - blocksize += quint32(pair.dst.size()); + for (auto link : m_links_to_make) { + blocksize += quint32(link.src.size()); + blocksize += quint32(link.dst.size()); } qDebug() << "About to write block of size:" << blocksize; out << blocksize; - out << quint32(m_path_pairs.length()); - for (auto pair : m_path_pairs) { - out << pair.src; - out << pair.dst; + out << quint32(m_links_to_make.length()); + for (auto link : m_links_to_make) { + out << link.src; + out << link.dst; } QLocalSocket *clientConnection = m_linkServer.nextPendingConnection(); connect(clientConnection, &QLocalSocket::disconnected, clientConnection, &QLocalSocket::deleteLater); + + connect(clientConnection, &QLocalSocket::readyRead, this, [&, clientConnection](){ + QDataStream in; + quint32 blockSize = 0; + in.setDevice(clientConnection); + in.setVersion(QDataStream::Qt_5_0); + qDebug() << "Reading path results from client"; + qDebug() << "bytes avalible" << clientConnection->bytesAvailable(); + + // Relies on the fact that QDataStream serializes a quint32 into + // sizeof(quint32) bytes + if (clientConnection->bytesAvailable() < (int)sizeof(quint32)) + return; + qDebug() << "reading block size"; + in >> blockSize; + + qDebug() << "blocksize is" << blockSize; + qDebug() << "bytes avalible" << clientConnection->bytesAvailable(); + if (clientConnection->bytesAvailable() < blockSize || in.atEnd()) + return; + + quint32 numResults; + in >> numResults; + qDebug() << "numResults" << numResults; + + for(int i = 0; i < numResults; i++) { + FS::LinkResult result; + in >> result.src; + in >> result.dst; + in >> result.err_msg; + qint32 err_value; + in >> err_value; + result.err_value = err_value; + if (result.err_value) { + qDebug() << "privlaged link fail" << result.src << "to" << result.dst << "code" << result.err_value << result.err_msg; + emit linkFailed(result.src, result.dst, result.err_msg, result.err_value); + } else { + qDebug() << "privlaged link success" << result.src << "to" << result.dst; + m_linked++; + emit fileLinked(result.src, result.dst); + } + m_path_results.append(result); + } + gotResults = true; + qDebug() << "results recieved, closing connection"; + clientConnection->close(); + }); qint64 byteswritten = clientConnection->write(block); bool bytesflushed = clientConnection->flush(); @@ -354,20 +426,15 @@ bool create_link::runPrivlaged(const QString& offset) qDebug() << "Listening on pipe" << serverName; if (!m_linkServer.listen(serverName)) { qDebug() << "Unable to start local pipe server on" << serverName << ":" << m_linkServer.errorString(); - return false; + return; } - ExternalLinkFileProcess *linkFileProcess = new ExternalLinkFileProcess(serverName, this); - connect(linkFileProcess, &ExternalLinkFileProcess::processExited, this, [&](){ - emit finishedPrivlaged(); - }); + ExternalLinkFileProcess* linkFileProcess = new ExternalLinkFileProcess(serverName, m_useHardLinks, this); + connect(linkFileProcess, &ExternalLinkFileProcess::processExited, this, [&]() { emit finishedPrivlaged(gotResults); }); connect(linkFileProcess, &ExternalLinkFileProcess::finished, linkFileProcess, &QObject::deleteLater); linkFileProcess->start(); - // linkFileProcess->wait(); - - return true; } @@ -375,6 +442,8 @@ void ExternalLinkFileProcess::runLinkFile() { QString fileLinkExe = PathCombine(QCoreApplication::instance()->applicationDirPath(), BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink"); QString params = "-s " + m_server; + params += " -H " + QVariant(m_useHardLinks).toString(); + #if defined Q_OS_WIN32 SHELLEXECUTEINFO ShExecInfo; HRESULT hr; diff --git a/launcher/FileSystem.h b/launcher/FileSystem.h index b15d1685..2e739298 100644 --- a/launcher/FileSystem.h +++ b/launcher/FileSystem.h @@ -133,13 +133,22 @@ struct LinkPair { QString dst; }; -class ExternalLinkFileProcess : public QThread -{ +struct LinkResult { + QString src; + QString dst; + QString err_msg; + int err_value; +}; + +class ExternalLinkFileProcess : public QThread { Q_OBJECT public: - ExternalLinkFileProcess(QString server, QObject* parent = nullptr) : QThread(parent), m_server(server) {} + ExternalLinkFileProcess(QString server, bool useHardLinks, QObject* parent = nullptr) + : QThread(parent), m_server(server), m_useHardLinks(useHardLinks) + {} - void run() override { + void run() override + { runLinkFile(); emit processExited(); } @@ -150,6 +159,8 @@ class ExternalLinkFileProcess : public QThread private: void runLinkFile(); + bool m_useHardLinks = false; + QString m_server; }; @@ -200,19 +211,21 @@ class create_link : public QObject { bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); } - bool runPrivlaged() { return runPrivlaged(QString()); } - bool runPrivlaged(const QString& offset); + void runPrivlaged() { runPrivlaged(QString()); } + void runPrivlaged(const QString& offset); int totalLinked() { return m_linked; } signals: - void fileLinked(const QString& relativeName); - void linkFailed(const QString& srcName, const QString& dstName, std::error_code err); - void finishedPrivlaged(); + void fileLinked(const QString& srcName, const QString& dstName); + void linkFailed(const QString& srcName, const QString& dstName, const QString& err_msg, int err_value); + void finishedPrivlaged(bool gotResults); + void finished(); private: bool operator()(const QString& offset, bool dryRun = false); - bool make_link(const QString& src_path, const QString& dst_path, const QString& offset, bool dryRun); + void make_link_list(const QString& offset); + bool make_links(); private: bool m_useHardLinks = false; @@ -221,6 +234,8 @@ class create_link : public QObject { bool m_recursive = true; QList m_path_pairs; + QList m_path_results; + QList m_links_to_make; int m_linked; bool m_debug = false; diff --git a/launcher/filelink/FileLink.cpp b/launcher/filelink/FileLink.cpp index 78486507..a731ecdb 100644 --- a/launcher/filelink/FileLink.cpp +++ b/launcher/filelink/FileLink.cpp @@ -23,6 +23,8 @@ #include "FileLink.h" #include "BuildConfig.h" +#include "StringUtils.h" + #include @@ -43,6 +45,24 @@ #include #endif +// Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header + +#ifdef __APPLE__ +#include // for deployment target to support pre-catalina targets without std::fs +#endif // __APPLE__ + +#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include) +#if __has_include() && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500) +#define GHC_USE_STD_FS +#include +namespace fs = std::filesystem; +#endif // MacOS min version check +#endif // Other OSes version check + +#ifndef GHC_USE_STD_FS +#include +namespace fs = ghc::filesystem; +#endif @@ -82,7 +102,8 @@ FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv), parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be used with prismlauncher")); parser.addOptions({ - {{"s", "server"}, "Join the specified server on launch", "pipe name"} + {{"s", "server"}, "Join the specified server on launch", "pipe name"}, + {{"H", "hard"}, "use hard links insted of symbolic", "true/false"} }); parser.addHelpOption(); parser.addVersionOption(); @@ -90,6 +111,7 @@ FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv), parser.process(arguments()); QString serverToJoin = parser.value("server"); + m_useHardLinks = QVariant(parser.value("hard")).toBool(); qDebug() << "link program launched"; @@ -109,7 +131,7 @@ void FileLinkApp::joinServer(QString server) blockSize = 0; in.setDevice(&socket); - in.setVersion(QDataStream::Qt_5_15); + in.setVersion(QDataStream::Qt_5_0); connect(&socket, &QLocalSocket::connected, this, [&](){ qDebug() << "connected to server"; @@ -120,25 +142,27 @@ void FileLinkApp::joinServer(QString server) connect(&socket, &QLocalSocket::errorOccurred, this, [&](QLocalSocket::LocalSocketError socketError){ switch (socketError) { case QLocalSocket::ServerNotFoundError: - qDebug() << tr("The host was not found. Please make sure " - "that the server is running and that the " - "server name is correct."); + qDebug() << ("The host was not found. Please make sure " + "that the server is running and that the " + "server name is correct."); break; case QLocalSocket::ConnectionRefusedError: - qDebug() << tr("The connection was refused by the peer. " - "Make sure the server is running, " - "and check that the server name " - "is correct."); + qDebug() << ("The connection was refused by the peer. " + "Make sure the server is running, " + "and check that the server name " + "is correct."); break; case QLocalSocket::PeerClosedError: + qDebug() << ("The connection was closed by the peer. "); break; default: - qDebug() << tr("The following error occurred: %1.").arg(socket.errorString()); + qDebug() << "The following error occurred: " << socket.errorString(); } }); connect(&socket, &QLocalSocket::disconnected, this, [&](){ - qDebug() << "dissconnected from server"; + qDebug() << "dissconnected from server, should exit"; + exit(); }); socket.connectToServer(server); @@ -147,20 +171,82 @@ void FileLinkApp::joinServer(QString server) } void FileLinkApp::runLink() +{ + + std::error_code os_err; + + qDebug() << "creating links"; + + for (auto link : m_links_to_make) { + + QString src_path = link.src; + QString dst_path = link.dst; + + FS::ensureFilePathExists(dst_path); + if (m_useHardLinks) { + qDebug() << "making hard link:" << src_path << "to" << dst_path; + fs::create_hard_link(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); + } else if (fs::is_directory(StringUtils::toStdString(src_path))) { + qDebug() << "making directory_symlink:" << src_path << "to" << dst_path; + fs::create_directory_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); + } else { + qDebug() << "making symlink:" << src_path << "to" << dst_path; + fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); + } + + if (os_err) { + qWarning() << "Failed to link files:" << QString::fromStdString(os_err.message()); + qDebug() << "Source file:" << src_path; + qDebug() << "Destination file:" << dst_path; + qDebug() << "Error catagory:" << os_err.category().name(); + qDebug() << "Error code:" << os_err.value(); + + FS::LinkResult result = {src_path, dst_path, QString::fromStdString(os_err.message()), os_err.value()}; + m_path_results.append(result); + } else { + FS::LinkResult result = {src_path, dst_path}; + m_path_results.append(result); + } + } + + sendResults(); + qDebug() << "done, should exit soon"; + +} + +void FileLinkApp::sendResults() { - qDebug() << "creating link"; - FS::create_link lnk(m_path_pairs); - lnk.debug(true); - if (!lnk()) { - qDebug() << "Link Failed!" << lnk.getOSError().value() << lnk.getOSError().message().c_str(); + // construct block of data to send + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_5_0); + + qint32 blocksize = quint32(sizeof(quint32)); + for (auto result : m_path_results) { + blocksize += quint32(result.src.size()); + blocksize += quint32(result.dst.size()); + blocksize += quint32(result.err_msg.size()); + blocksize += quint32(sizeof(quint32)); } - //exit(); - qDebug() << "done, should exit"; + qDebug() << "About to write block of size:" << blocksize; + out << blocksize; + + out << quint32(m_path_results.length()); + for (auto result : m_path_results) { + out << result.src; + out << result.dst; + out << result.err_msg; + out << quint32(result.err_value); + } + + qint64 byteswritten = socket.write(block); + bool bytesflushed = socket.flush(); + qDebug() << "block flushed" << byteswritten << bytesflushed; } void FileLinkApp::readPathPairs() { - m_path_pairs.clear(); + m_links_to_make.clear(); qDebug() << "Reading path pairs from server"; qDebug() << "bytes avalible" << socket.bytesAvailable(); if (blockSize == 0) { @@ -176,16 +262,16 @@ void FileLinkApp::readPathPairs() if (socket.bytesAvailable() < blockSize || in.atEnd()) return; - quint32 numPairs; - in >> numPairs; - qDebug() << "numPairs" << numPairs; + quint32 numLinks; + in >> numLinks; + qDebug() << "numLinks" << numLinks; - for(int i = 0; i < numPairs; i++) { + for(int i = 0; i < numLinks; i++) { FS::LinkPair pair; in >> pair.src; in >> pair.dst; qDebug() << "link" << pair.src << "to" << pair.dst; - m_path_pairs.append(pair); + m_links_to_make.append(pair); } runLink(); diff --git a/launcher/filelink/FileLink.h b/launcher/filelink/FileLink.h index 5d0ba123..d146b8d9 100644 --- a/launcher/filelink/FileLink.h +++ b/launcher/filelink/FileLink.h @@ -52,13 +52,17 @@ private: void joinServer(QString server); void readPathPairs(); void runLink(); + void sendResults(); + + bool m_useHardLinks = false; QDateTime m_startTime; QLocalSocket socket; QDataStream in; quint32 blockSize; - QList m_path_pairs; + QList m_links_to_make; + QList m_path_results; #if defined Q_OS_WIN32 // used on Windows to attach the standard IO streams diff --git a/tests/FileSystem_test.cpp b/tests/FileSystem_test.cpp index be0a4be0..4ccc4003 100644 --- a/tests/FileSystem_test.cpp +++ b/tests/FileSystem_test.cpp @@ -66,12 +66,17 @@ class LinkTask : public Task { qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; qDebug() << "atempting to run with privelage"; - connect(m_lnk, &FS::create_link::finishedPrivlaged, this, [&](){ - emitSucceeded(); + connect(m_lnk, &FS::create_link::finishedPrivlaged, this, [&](bool gotResults){ + if (gotResults) { + emitSucceeded(); + } else { + qDebug() << "Privlaged run exited without results!"; + emitFailed(); + } }); m_lnk->runPrivlaged(); } else { - qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str(); + qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str(); } #else qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str(); -- cgit From 0c986ba4d006740947603afb2e18dd9d2ffdfd2f Mon Sep 17 00:00:00 2001 From: Rachel Powers <508861+Ryex@users.noreply.github.com> Date: Mon, 20 Mar 2023 16:38:40 -0700 Subject: spelling and formatting Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com> --- launcher/FileSystem.cpp | 14 +-- launcher/FileSystem.h | 185 +++++++++++++---------------- launcher/InstanceCopyTask.cpp | 45 ++++--- launcher/filelink/FileLink.cpp | 110 +++++++---------- launcher/filelink/FileLink.h | 20 ++-- launcher/filelink/main.cpp | 5 +- launcher/ui/dialogs/CopyInstanceDialog.cpp | 40 +++---- launcher/ui/dialogs/CopyInstanceDialog.h | 21 ++-- 8 files changed, 192 insertions(+), 248 deletions(-) (limited to 'launcher/filelink/FileLink.cpp') diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index c913b43e..640cf9be 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -328,7 +328,7 @@ bool create_link::operator()(const QString& offset, bool dryRun) } /** - * @brief make a list off all the links ot make + * @brief make a list off all the links to * @param offset subdirectory form src to link to dest * @return if there was an error during the attempt to link */ @@ -363,7 +363,7 @@ void create_link::make_link_list(const QString& offset) link_file(src, ""); } else { if (m_debug) - qDebug() << "linking recursivly:" << src << "to" << dst << "max_depth:" << m_max_depth; + qDebug() << "linking recursively:" << src << "to" << dst << "max_depth:" << m_max_depth; QDir src_dir(src); QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); @@ -414,7 +414,7 @@ bool create_link::make_links() qWarning() << "Failed to link files:" << QString::fromStdString(m_os_err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; - qDebug() << "Error catagory:" << m_os_err.category().name(); + qDebug() << "Error category:" << m_os_err.category().name(); qDebug() << "Error code:" << m_os_err.value(); emit linkFailed(src_path, dst_path, QString::fromStdString(m_os_err.message()), m_os_err.value()); } else { @@ -469,7 +469,7 @@ void create_link::runPrivileged(const QString& offset) in.setDevice(clientConnection); in.setVersion(QDataStream::Qt_5_0); qDebug() << "Reading path results from client"; - qDebug() << "bytes avalible" << clientConnection->bytesAvailable(); + qDebug() << "bytes available" << clientConnection->bytesAvailable(); // Relies on the fact that QDataStream serializes a quint32 into // sizeof(quint32) bytes @@ -479,7 +479,7 @@ void create_link::runPrivileged(const QString& offset) in >> blockSize; qDebug() << "blocksize is" << blockSize; - qDebug() << "bytes avalible" << clientConnection->bytesAvailable(); + qDebug() << "bytes available" << clientConnection->bytesAvailable(); if (clientConnection->bytesAvailable() < blockSize || in.atEnd()) return; @@ -506,7 +506,7 @@ void create_link::runPrivileged(const QString& offset) m_path_results.append(result); } gotResults = true; - qDebug() << "results recieved, closing connection"; + qDebug() << "results received, closing connection"; clientConnection->close(); }); @@ -981,7 +981,7 @@ FilesystemType getFilesystemType(const QString& name) } /** - * @brief path to the near ancestor that exsists + * @brief path to the near ancestor that exists * */ QString NearestExistentAncestor(const QString& path) diff --git a/launcher/FileSystem.h b/launcher/FileSystem.h index 71175bb4..673c3563 100644 --- a/launcher/FileSystem.h +++ b/launcher/FileSystem.h @@ -44,9 +44,9 @@ #include #include +#include #include #include -#include namespace FS { @@ -84,7 +84,7 @@ bool ensureFolderPathExists(QString filenamepath); /** * @brief Copies a directory and it's contents from src to dest - */ + */ class copy : public QObject { Q_OBJECT public: @@ -167,17 +167,14 @@ class ExternalLinkFileProcess : public QThread { /** * @brief links (a file / a directory and it's contents) from src to dest - */ + */ class create_link : public QObject { Q_OBJECT public: - create_link(const QList path_pairs, QObject* parent = nullptr) : QObject(parent) - { - m_path_pairs.append(path_pairs); - } + create_link(const QList path_pairs, QObject* parent = nullptr) : QObject(parent) { m_path_pairs.append(path_pairs); } create_link(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent) { - LinkPair pair = {src, dst}; + LinkPair pair = { src, dst }; m_path_pairs.append(pair); } create_link& useHardLinks(const bool useHard) @@ -211,28 +208,23 @@ class create_link : public QObject { return *this; } - std::error_code getOSError() { - return m_os_err; - } + std::error_code getOSError() { return m_os_err; } bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); } int totalLinked() { return m_linked; } - void runPrivileged() { runPrivileged(QString()); } void runPrivileged(const QString& offset); QList getResults() { return m_path_results; } - signals: void fileLinked(const QString& srcName, const QString& dstName); void linkFailed(const QString& srcName, const QString& dstName, const QString& err_msg, int err_value); void finished(); void finishedPrivileged(bool gotResults); - private: bool operator()(const QString& offset, bool dryRun = false); void make_link_list(const QString& offset); @@ -262,9 +254,9 @@ class create_link : public QObject { * @brief moves a file by renaming it * @param source source file path * @param dest destination filepath - * + * */ -bool move(const QString& source, const QString& dest); +bool move(const QString& source, const QString& dest); /** * Delete a folder recursively @@ -274,7 +266,7 @@ bool deletePath(QString path); /** * Trash a folder / file */ -bool trash(QString path, QString *pathInTrash = nullptr); +bool trash(QString path, QString* pathInTrash = nullptr); QString PathCombine(const QString& path1, const QString& path2); QString PathCombine(const QString& path1, const QString& path2, const QString& path3); @@ -284,16 +276,15 @@ QString AbsolutePath(const QString& path); /** * @brief depth of path. "foo.txt" -> 0 , "bar/foo.txt" -> 1, /baz/bar/foo.txt -> 2, etc. - * + * * @param path path to measure - * @return int number of componants before base path + * @return int number of components before base path */ int PathDepth(const QString& path); - /** - * @brief cut off segments of path untill it is a max of length depth - * + * @brief cut off segments of path until it is a max of length depth + * * @param path path to truncate * @param depth max depth of new path * @return QString truncated path @@ -363,124 +354,118 @@ enum class FilesystemType { /** * @brief Ordered Mapping of enum types to reported filesystem names - * this maping is non exsaustive, it just attempts to capture the filesystems which could be reasonalbly be in use . + * this mapping is non exsaustive, it just attempts to capture the filesystems which could be reasonalbly be in use . * all string values are in uppercase, use `QString.toUpper()` or equivalent during lookup. - * + * * QMap is ordered - * + * */ -static const QMap s_filesystem_type_names = { - {FilesystemType::FAT, QString("FAT")}, - {FilesystemType::NTFS, QString("NTFS")}, - {FilesystemType::REFS, QString("REFS")}, - {FilesystemType::EXT, QString("EXT")}, - {FilesystemType::EXT_2_OLD, QString("EXT_2_OLD")}, - {FilesystemType::EXT_2_3_4, QString("EXT2/3/4")}, - {FilesystemType::XFS, QString("XFS")}, - {FilesystemType::BTRFS, QString("BTRFS")}, - {FilesystemType::NFS, QString("NFS")}, - {FilesystemType::ZFS, QString("ZFS")}, - {FilesystemType::APFS, QString("APFS")}, - {FilesystemType::HFS, QString("HFS")}, - {FilesystemType::HFSPLUS, QString("HFSPLUS")}, - {FilesystemType::HFSX, QString("HFSX")}, - {FilesystemType::FUSEBLK, QString("FUSEBLK")}, - {FilesystemType::F2FS, QString("F2FS")}, - {FilesystemType::UNKNOWN, QString("UNKNOWN")} -}; - +static const QMap s_filesystem_type_names = { { FilesystemType::FAT, QString("FAT") }, + { FilesystemType::NTFS, QString("NTFS") }, + { FilesystemType::REFS, QString("REFS") }, + { FilesystemType::EXT, QString("EXT") }, + { FilesystemType::EXT_2_OLD, QString("EXT_2_OLD") }, + { FilesystemType::EXT_2_3_4, QString("EXT2/3/4") }, + { FilesystemType::XFS, QString("XFS") }, + { FilesystemType::BTRFS, QString("BTRFS") }, + { FilesystemType::NFS, QString("NFS") }, + { FilesystemType::ZFS, QString("ZFS") }, + { FilesystemType::APFS, QString("APFS") }, + { FilesystemType::HFS, QString("HFS") }, + { FilesystemType::HFSPLUS, QString("HFSPLUS") }, + { FilesystemType::HFSX, QString("HFSX") }, + { FilesystemType::FUSEBLK, QString("FUSEBLK") }, + { FilesystemType::F2FS, QString("F2FS") }, + { FilesystemType::UNKNOWN, QString("UNKNOWN") } }; /** * @brief Ordered Mapping of reported filesystem names to enum types - * this maping is non exsaustive, it just attempts to capture the many way these filesystems could be reported. + * this mapping is non exsaustive, it just attempts to capture the many way these filesystems could be reported. * all keys are in uppercase, use `QString.toUpper()` or equivalent during lookup. - * + * * QMap is ordered - * + * */ static const QMap s_filesystem_type_names_inverse = { - {QString("FAT"), FilesystemType::FAT}, - {QString("NTFS"), FilesystemType::NTFS}, - {QString("REFS"), FilesystemType::REFS}, - {QString("EXT2_OLD"), FilesystemType::EXT_2_OLD}, - {QString("EXT_2_OLD"), FilesystemType::EXT_2_OLD}, - {QString("EXT2"), FilesystemType::EXT_2_3_4}, - {QString("EXT3"), FilesystemType::EXT_2_3_4}, - {QString("EXT4"), FilesystemType::EXT_2_3_4}, - {QString("EXT2/3/4"), FilesystemType::EXT_2_3_4}, - {QString("EXT_2_3_4"), FilesystemType::EXT_2_3_4}, - {QString("EXT"), FilesystemType::EXT}, // must come after all other EXT variants to prevent greedy detection - {QString("XFS"), FilesystemType::XFS}, - {QString("BTRFS"), FilesystemType::BTRFS}, - {QString("NFS"), FilesystemType::NFS}, - {QString("ZFS"), FilesystemType::ZFS}, - {QString("APFS"), FilesystemType::APFS}, - {QString("HFSPLUS"), FilesystemType::HFSPLUS}, - {QString("HFSX"), FilesystemType::HFSX}, - {QString("HFS"), FilesystemType::HFS}, - {QString("FUSEBLK"), FilesystemType::FUSEBLK}, - {QString("F2FS"), FilesystemType::F2FS}, - {QString("UNKNOWN"), FilesystemType::UNKNOWN} + { QString("FAT"), FilesystemType::FAT }, + { QString("NTFS"), FilesystemType::NTFS }, + { QString("REFS"), FilesystemType::REFS }, + { QString("EXT2_OLD"), FilesystemType::EXT_2_OLD }, + { QString("EXT_2_OLD"), FilesystemType::EXT_2_OLD }, + { QString("EXT2"), FilesystemType::EXT_2_3_4 }, + { QString("EXT3"), FilesystemType::EXT_2_3_4 }, + { QString("EXT4"), FilesystemType::EXT_2_3_4 }, + { QString("EXT2/3/4"), FilesystemType::EXT_2_3_4 }, + { QString("EXT_2_3_4"), FilesystemType::EXT_2_3_4 }, + { QString("EXT"), FilesystemType::EXT }, // must come after all other EXT variants to prevent greedy detection + { QString("XFS"), FilesystemType::XFS }, + { QString("BTRFS"), FilesystemType::BTRFS }, + { QString("NFS"), FilesystemType::NFS }, + { QString("ZFS"), FilesystemType::ZFS }, + { QString("APFS"), FilesystemType::APFS }, + { QString("HFSPLUS"), FilesystemType::HFSPLUS }, + { QString("HFSX"), FilesystemType::HFSX }, + { QString("HFS"), FilesystemType::HFS }, + { QString("FUSEBLK"), FilesystemType::FUSEBLK }, + { QString("F2FS"), FilesystemType::F2FS }, + { QString("UNKNOWN"), FilesystemType::UNKNOWN } }; /** * @brief Get the string name of Filesystem enum object - * - * @param type - * @return QString + * + * @param type + * @return QString */ QString getFilesystemTypeName(FilesystemType type); /** * @brief Get the Filesystem enum object from a name - * Does a lookup of the type name and returns an exact match + * Does a lookup of the type name and returns an exact match * - * @param name - * @return FilesystemType + * @param name + * @return FilesystemType */ FilesystemType getFilesystemType(const QString& name); /** * @brief Get the Filesystem enum object from a name * Does a fuzzy lookup of the type name and returns an apropreate match - * - * @param name - * @return FilesystemType + * + * @param name + * @return FilesystemType */ FilesystemType getFilesystemTypeFuzzy(const QString& name); - struct FilesystemInfo { FilesystemType fsType = FilesystemType::UNKNOWN; QString fsTypeName; - int blockSize; - qint64 bytesAvailable; - qint64 bytesFree; - qint64 bytesTotal; + int blockSize; + qint64 bytesAvailable; + qint64 bytesFree; + qint64 bytesTotal; QString name; QString rootPath; }; /** - * @brief path to the near ancestor that exsists - * + * @brief path to the near ancestor that exists + * */ QString NearestExistentAncestor(const QString& path); /** * @brief colect information about the filesystem under a file - * + * */ FilesystemInfo statFS(const QString& path); -static const QList s_clone_filesystems = { - FilesystemType::BTRFS, FilesystemType::APFS, FilesystemType::ZFS, - FilesystemType::XFS, FilesystemType::REFS -}; +static const QList s_clone_filesystems = { FilesystemType::BTRFS, FilesystemType::APFS, FilesystemType::ZFS, + FilesystemType::XFS, FilesystemType::REFS }; /** - * @brief if the Filesystem is reflink/clone capable - * + * @brief if the Filesystem is reflink/clone capable + * */ bool canCloneOnFS(const QString& path); bool canCloneOnFS(const FilesystemInfo& info); @@ -488,13 +473,13 @@ bool canCloneOnFS(FilesystemType type); /** * @brief if the Filesystems are reflink/clone capable and both are on the same device - * + * */ bool canClone(const QString& src, const QString& dst); /** * @brief Copies a directory and it's contents from src to dest - */ + */ class clone : public QObject { Q_OBJECT public: @@ -535,7 +520,7 @@ class clone : public QObject { /** * @brief clone/reflink file from src to dst - * + * */ bool clone_file(const QString& src, const QString& dst, std::error_code& ec); @@ -552,8 +537,8 @@ static const QList s_non_link_filesystems = { }; /** - * @brief if the Filesystem is symlink capable - * + * @brief if the Filesystem is symlink capable + * */ bool canLinkOnFS(const QString& path); bool canLinkOnFS(const FilesystemInfo& info); @@ -561,10 +546,10 @@ bool canLinkOnFS(FilesystemType type); /** * @brief if the Filesystem is symlink capable on both ends - * + * */ bool canLink(const QString& src, const QString& dst); uintmax_t hardLinkCount(const QString& path); -} +} // namespace FS diff --git a/launcher/InstanceCopyTask.cpp b/launcher/InstanceCopyTask.cpp index 6bd56de3..4ac3b51a 100644 --- a/launcher/InstanceCopyTask.cpp +++ b/launcher/InstanceCopyTask.cpp @@ -1,10 +1,10 @@ #include "InstanceCopyTask.h" -#include "settings/INISettingsObject.h" +#include +#include #include "FileSystem.h" #include "NullInstance.h" #include "pathmatcher/RegexpMatcher.h" -#include -#include +#include "settings/INISettingsObject.h" InstanceCopyTask::InstanceCopyTask(InstancePtr origInstance, const InstanceCopyPrefs& prefs) { @@ -15,17 +15,17 @@ InstanceCopyTask::InstanceCopyTask(InstancePtr origInstance, const InstanceCopyP m_useHardLinks = prefs.isLinkRecursivelyEnabled() && prefs.isUseHardLinksEnabled(); m_copySaves = prefs.isLinkRecursivelyEnabled() && prefs.isDontLinkSavesEnabled() && prefs.isCopySavesEnabled(); m_useClone = prefs.isUseCloneEnabled(); - + QString filters = prefs.getSelectedFiltersAsRegex(); if (m_useLinks || m_useHardLinks) { - if (!filters.isEmpty()) filters += "|"; + if (!filters.isEmpty()) + filters += "|"; filters += "instance.cfg"; - } + } qDebug() << "CopyFilters:" << filters; - if (!filters.isEmpty()) - { + if (!filters.isEmpty()) { // Set regex filter: // FIXME: get this from the original instance type... auto matcherReal = new RegexpMatcher(filters); @@ -38,14 +38,14 @@ void InstanceCopyTask::executeTask() { setStatus(tr("Copying instance %1").arg(m_origInstance->name())); - auto copySaves = [&](){ - FS::copy savesCopy(FS::PathCombine(m_origInstance->instanceRoot(), "saves") , FS::PathCombine(m_stagingPath, "saves")); + auto copySaves = [&]() { + FS::copy savesCopy(FS::PathCombine(m_origInstance->instanceRoot(), "saves"), FS::PathCombine(m_stagingPath, "saves")); savesCopy.followSymlinks(true); return savesCopy(); }; - m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this, copySaves]{ + m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this, copySaves] { if (m_useClone) { FS::clone folderClone(m_origInstance->instanceRoot(), m_stagingPath); folderClone.matcher(m_matcher.get()); @@ -53,22 +53,22 @@ void InstanceCopyTask::executeTask() return folderClone(); } else if (m_useLinks || m_useHardLinks) { FS::create_link folderLink(m_origInstance->instanceRoot(), m_stagingPath); - int depth = m_linkRecursively ? -1 : 0; // we need to at least link the top level instead of the instance folder + int depth = m_linkRecursively ? -1 : 0; // we need to at least link the top level instead of the instance folder folderLink.linkRecursively(true).setMaxDepth(depth).useHardLinks(m_useHardLinks).matcher(m_matcher.get()); bool there_were_errors = false; - if(!folderLink()){ + if (!folderLink()) { #if defined Q_OS_WIN32 if (!m_useHardLinks) { qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; - qDebug() << "atempting to run with privelage"; + qDebug() << "attempting to run with privelage"; QEventLoop loop; bool got_priv_results = false; - connect(&folderLink, &FS::create_link::finishedPrivileged, this, [&](bool gotResults){ + connect(&folderLink, &FS::create_link::finishedPrivileged, this, [&](bool gotResults) { if (!gotResults) { qDebug() << "Privileged run exited without results!"; } @@ -77,7 +77,7 @@ void InstanceCopyTask::executeTask() }); folderLink.runPrivileged(); - loop.exec(); // wait for the finished signal + loop.exec(); // wait for the finished signal for (auto result : folderLink.getResults()) { if (result.err_value != 0) { @@ -88,17 +88,17 @@ void InstanceCopyTask::executeTask() if (m_copySaves) { there_were_errors |= !copySaves(); } - + return got_priv_results && !there_were_errors; } else { qDebug() << "Link Failed!" << folderLink.getOSError().value() << folderLink.getOSError().message().c_str(); - } + } #else qDebug() << "Link Failed!" << folderLink.getOSError().value() << folderLink.getOSError().message().c_str(); -#endif +#endif return false; } - + if (m_copySaves) { there_were_errors |= !copySaves(); } @@ -119,8 +119,7 @@ void InstanceCopyTask::executeTask() void InstanceCopyTask::copyFinished() { auto successful = m_copyFuture.result(); - if(!successful) - { + if (!successful) { emitFailed(tr("Instance folder copy failed.")); return; } @@ -130,7 +129,7 @@ void InstanceCopyTask::copyFinished() InstancePtr inst(new NullInstance(m_globalSettings, instanceSettings, m_stagingPath)); inst->setName(name()); inst->setIconKey(m_instIcon); - if(!m_keepPlaytime) { + if (!m_keepPlaytime) { inst->resetTimePlayed(); } if (m_useLinks) diff --git a/launcher/filelink/FileLink.cpp b/launcher/filelink/FileLink.cpp index a731ecdb..ded46061 100644 --- a/launcher/filelink/FileLink.cpp +++ b/launcher/filelink/FileLink.cpp @@ -25,7 +25,6 @@ #include "StringUtils.h" - #include #include @@ -41,53 +40,47 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif -#include #include +#include #endif // Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header #ifdef __APPLE__ -#include // for deployment target to support pre-catalina targets without std::fs -#endif // __APPLE__ +#include // for deployment target to support pre-catalina targets without std::fs +#endif // __APPLE__ #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include) #if __has_include() && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500) #define GHC_USE_STD_FS #include namespace fs = std::filesystem; -#endif // MacOS min version check -#endif // Other OSes version check +#endif // MacOS min version check +#endif // Other OSes version check #ifndef GHC_USE_STD_FS #include namespace fs = ghc::filesystem; #endif - - -FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv), socket(new QLocalSocket(this)) +FileLinkApp::FileLinkApp(int& argc, char** argv) : QCoreApplication(argc, argv), socket(new QLocalSocket(this)) { #if defined Q_OS_WIN32 // attach the parent console - if(AttachConsole(ATTACH_PARENT_PROCESS)) - { + if (AttachConsole(ATTACH_PARENT_PROCESS)) { // if attach succeeds, reopen and sync all the i/o - if(freopen("CON", "w", stdout)) - { + if (freopen("CON", "w", stdout)) { std::cout.sync_with_stdio(); } - if(freopen("CON", "w", stderr)) - { + if (freopen("CON", "w", stderr)) { std::cerr.sync_with_stdio(); } - if(freopen("CON", "r", stdin)) - { + if (freopen("CON", "r", stdin)) { std::cin.sync_with_stdio(); } - auto out = GetStdHandle (STD_OUTPUT_HANDLE); + auto out = GetStdHandle(STD_OUTPUT_HANDLE); DWORD written; - const char * endline = "\n"; + const char* endline = "\n"; WriteConsole(out, endline, strlen(endline), &written, NULL); consoleAttached = true; } @@ -101,10 +94,8 @@ FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv), QCommandLineParser parser; parser.setApplicationDescription(QObject::tr("a batch MKLINK program for windows to be used with prismlauncher")); - parser.addOptions({ - {{"s", "server"}, "Join the specified server on launch", "pipe name"}, - {{"H", "hard"}, "use hard links insted of symbolic", "true/false"} - }); + parser.addOptions({ { { "s", "server" }, "Join the specified server on launch", "pipe name" }, + { { "H", "hard" }, "use hard links instead of symbolic", "true/false" } }); parser.addHelpOption(); parser.addVersionOption(); @@ -122,63 +113,57 @@ FileLinkApp::FileLinkApp(int &argc, char **argv) : QCoreApplication(argc, argv), qDebug() << "no server to join"; exit(); } - } void FileLinkApp::joinServer(QString server) { - - blockSize = 0; + blockSize = 0; in.setDevice(&socket); in.setVersion(QDataStream::Qt_5_0); - connect(&socket, &QLocalSocket::connected, this, [&](){ - qDebug() << "connected to server"; - }); + connect(&socket, &QLocalSocket::connected, this, [&]() { qDebug() << "connected to server"; }); connect(&socket, &QLocalSocket::readyRead, this, &FileLinkApp::readPathPairs); - connect(&socket, &QLocalSocket::errorOccurred, this, [&](QLocalSocket::LocalSocketError socketError){ + connect(&socket, &QLocalSocket::errorOccurred, this, [&](QLocalSocket::LocalSocketError socketError) { switch (socketError) { - case QLocalSocket::ServerNotFoundError: - qDebug() << ("The host was not found. Please make sure " + case QLocalSocket::ServerNotFoundError: + qDebug() + << ("The host was not found. Please make sure " "that the server is running and that the " "server name is correct."); - break; - case QLocalSocket::ConnectionRefusedError: - qDebug() << ("The connection was refused by the peer. " + break; + case QLocalSocket::ConnectionRefusedError: + qDebug() + << ("The connection was refused by the peer. " "Make sure the server is running, " "and check that the server name " "is correct."); - break; - case QLocalSocket::PeerClosedError: - qDebug() << ("The connection was closed by the peer. "); - break; - default: - qDebug() << "The following error occurred: " << socket.errorString(); + break; + case QLocalSocket::PeerClosedError: + qDebug() << ("The connection was closed by the peer. "); + break; + default: + qDebug() << "The following error occurred: " << socket.errorString(); } }); - connect(&socket, &QLocalSocket::disconnected, this, [&](){ - qDebug() << "dissconnected from server, should exit"; + connect(&socket, &QLocalSocket::disconnected, this, [&]() { + qDebug() << "disconnected from server, should exit"; exit(); }); socket.connectToServer(server); - - } void FileLinkApp::runLink() -{ - +{ std::error_code os_err; qDebug() << "creating links"; for (auto link : m_links_to_make) { - QString src_path = link.src; QString dst_path = link.dst; @@ -192,26 +177,25 @@ void FileLinkApp::runLink() } else { qDebug() << "making symlink:" << src_path << "to" << dst_path; fs::create_symlink(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), os_err); - } + } if (os_err) { qWarning() << "Failed to link files:" << QString::fromStdString(os_err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; - qDebug() << "Error catagory:" << os_err.category().name(); + qDebug() << "Error category:" << os_err.category().name(); qDebug() << "Error code:" << os_err.value(); - FS::LinkResult result = {src_path, dst_path, QString::fromStdString(os_err.message()), os_err.value()}; + FS::LinkResult result = { src_path, dst_path, QString::fromStdString(os_err.message()), os_err.value() }; m_path_results.append(result); } else { - FS::LinkResult result = {src_path, dst_path}; + FS::LinkResult result = { src_path, dst_path }; m_path_results.append(result); } } sendResults(); qDebug() << "done, should exit soon"; - } void FileLinkApp::sendResults() @@ -245,10 +229,10 @@ void FileLinkApp::sendResults() } void FileLinkApp::readPathPairs() -{ +{ m_links_to_make.clear(); qDebug() << "Reading path pairs from server"; - qDebug() << "bytes avalible" << socket.bytesAvailable(); + qDebug() << "bytes available" << socket.bytesAvailable(); if (blockSize == 0) { // Relies on the fact that QDataStream serializes a quint32 into // sizeof(quint32) bytes @@ -258,15 +242,15 @@ void FileLinkApp::readPathPairs() in >> blockSize; } qDebug() << "blocksize is" << blockSize; - qDebug() << "bytes avalible" << socket.bytesAvailable(); + qDebug() << "bytes available" << socket.bytesAvailable(); if (socket.bytesAvailable() < blockSize || in.atEnd()) return; - + quint32 numLinks; in >> numLinks; qDebug() << "numLinks" << numLinks; - for(int i = 0; i < numLinks; i++) { + for (int i = 0; i < numLinks; i++) { FS::LinkPair pair; in >> pair.src; in >> pair.dst; @@ -277,17 +261,15 @@ void FileLinkApp::readPathPairs() runLink(); } - FileLinkApp::~FileLinkApp() -{ +{ qDebug() << "link program shutting down"; // Shut down logger by setting the logger function to nothing qInstallMessageHandler(nullptr); #if defined Q_OS_WIN32 // Detach from Windows console - if(consoleAttached) - { + if (consoleAttached) { fclose(stdout); fclose(stdin); fclose(stderr); @@ -295,7 +277,3 @@ FileLinkApp::~FileLinkApp() } #endif } - - - - diff --git a/launcher/filelink/FileLink.h b/launcher/filelink/FileLink.h index d146b8d9..4c47d9bb 100644 --- a/launcher/filelink/FileLink.h +++ b/launcher/filelink/FileLink.h @@ -25,30 +25,26 @@ #include #include -#include +#include +#include #include #include #include -#include -#include -#include -#include #include +#include +#include #define PRISM_EXTERNAL_EXE #include "FileSystem.h" -class FileLinkApp : public QCoreApplication -{ +class FileLinkApp : public QCoreApplication { // friends for the purpose of limiting access to deprecated stuff Q_OBJECT -public: - - FileLinkApp(int &argc, char **argv); + public: + FileLinkApp(int& argc, char** argv); virtual ~FileLinkApp(); -private: - + private: void joinServer(QString server); void readPathPairs(); void runLink(); diff --git a/launcher/filelink/main.cpp b/launcher/filelink/main.cpp index 4a22ff18..83566a3c 100644 --- a/launcher/filelink/main.cpp +++ b/launcher/filelink/main.cpp @@ -22,10 +22,9 @@ #include "FileLink.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - FileLinkApp ldh(argc, argv); - + return ldh.exec(); } diff --git a/launcher/ui/dialogs/CopyInstanceDialog.cpp b/launcher/ui/dialogs/CopyInstanceDialog.cpp index ced57ae0..347bd39f 100644 --- a/launcher/ui/dialogs/CopyInstanceDialog.cpp +++ b/launcher/ui/dialogs/CopyInstanceDialog.cpp @@ -43,15 +43,15 @@ #include "ui/dialogs/IconPickerDialog.h" -#include "BaseVersion.h" -#include "icons/IconList.h" #include "BaseInstance.h" -#include "InstanceList.h" -#include "FileSystem.h" +#include "BaseVersion.h" #include "DesktopServices.h" +#include "FileSystem.h" +#include "InstanceList.h" +#include "icons/IconList.h" -CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent) - :QDialog(parent), ui(new Ui::CopyInstanceDialog), m_original(original) +CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget* parent) + : QDialog(parent), ui(new Ui::CopyInstanceDialog), m_original(original) { ui->setupUi(this); resize(minimumSizeHint()); @@ -74,8 +74,7 @@ CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent) groupList.push_front(""); ui->groupBox->addItems(groupList); int index = groupList.indexOf(APPLICATION->instances()->getInstanceGroup(m_original->id())); - if(index == -1) - { + if (index == -1) { index = 0; } ui->groupBox->setCurrentIndex(index); @@ -108,10 +107,8 @@ CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent) #if defined(Q_OS_WIN) ui->symbolicLinksCheckbox->setIcon(style()->standardIcon(QStyle::SP_VistaShield)); - ui->symbolicLinksCheckbox->setToolTip( - tr("Use symbolic links instead of copying files.") + - tr("\nOn windows symbolic links may require admin permision to create.") - ); + ui->symbolicLinksCheckbox->setToolTip(tr("Use symbolic links instead of copying files.") + + tr("\nOn windows symbolic links may require admin permission to create.")); #endif updateLinkOptions(); @@ -119,7 +116,6 @@ CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent) auto HelpButton = ui->buttonBox->button(QDialogButtonBox::Help); connect(HelpButton, &QPushButton::clicked, this, &CopyInstanceDialog::help); - } CopyInstanceDialog::~CopyInstanceDialog() @@ -131,8 +127,7 @@ void CopyInstanceDialog::updateDialogState() { auto allowOK = !instName().isEmpty(); auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok); - if(OkButton->isEnabled() != allowOK) - { + if (OkButton->isEnabled() != allowOK) { OkButton->setEnabled(allowOK); } } @@ -140,8 +135,7 @@ void CopyInstanceDialog::updateDialogState() QString CopyInstanceDialog::instName() const { auto result = ui->instNameTextBox->text().trimmed(); - if(result.size()) - { + if (result.size()) { return result; } return QString(); @@ -162,7 +156,6 @@ const InstanceCopyPrefs& CopyInstanceDialog::getChosenOptions() const return m_selectedOptions; } - void CopyInstanceDialog::help() { DesktopServices::openUrl(QUrl(BuildConfig.HELP_URL.arg("instance-copy"))); @@ -200,7 +193,8 @@ void CopyInstanceDialog::updateLinkOptions() ui->symbolicLinksCheckbox->setEnabled(m_linkSupported && !ui->hardLinksCheckbox->isChecked() && !ui->useCloneCheckbox->isChecked()); ui->hardLinksCheckbox->setEnabled(m_linkSupported && !ui->symbolicLinksCheckbox->isChecked() && !ui->useCloneCheckbox->isChecked()); - ui->symbolicLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseSymLinksEnabled() && !ui->useCloneCheckbox->isChecked()); + ui->symbolicLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseSymLinksEnabled() && + !ui->useCloneCheckbox->isChecked()); ui->hardLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseHardLinksEnabled() && !ui->useCloneCheckbox->isChecked()); bool linksInUse = (ui->symbolicLinksCheckbox->isChecked() || ui->hardLinksCheckbox->isChecked()); @@ -220,15 +214,13 @@ void CopyInstanceDialog::on_iconButton_clicked() IconPickerDialog dlg(this); dlg.execWithSelection(InstIconKey); - if (dlg.result() == QDialog::Accepted) - { + if (dlg.result() == QDialog::Accepted) { InstIconKey = dlg.selectedIconKey; ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); } } - -void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1) +void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString& arg1) { updateDialogState(); } @@ -247,7 +239,6 @@ void CopyInstanceDialog::on_copySavesCheckbox_stateChanged(int state) updateSelectAllCheckbox(); } - void CopyInstanceDialog::on_keepPlaytimeCheckbox_stateChanged(int state) { m_selectedOptions.enableKeepPlaytime(state == Qt::Checked); @@ -311,7 +302,6 @@ void CopyInstanceDialog::on_recursiveLinkCheckbox_stateChanged(int state) { m_selectedOptions.enableLinkRecursively(state == Qt::Checked); updateLinkOptions(); - } void CopyInstanceDialog::on_dontLinkSavesCheckbox_stateChanged(int state) diff --git a/launcher/ui/dialogs/CopyInstanceDialog.h b/launcher/ui/dialogs/CopyInstanceDialog.h index c447bee9..698c6e93 100644 --- a/launcher/ui/dialogs/CopyInstanceDialog.h +++ b/launcher/ui/dialogs/CopyInstanceDialog.h @@ -22,17 +22,15 @@ class BaseInstance; -namespace Ui -{ +namespace Ui { class CopyInstanceDialog; } -class CopyInstanceDialog : public QDialog -{ +class CopyInstanceDialog : public QDialog { Q_OBJECT -public: - explicit CopyInstanceDialog(InstancePtr original, QWidget *parent = 0); + public: + explicit CopyInstanceDialog(InstancePtr original, QWidget* parent = 0); ~CopyInstanceDialog(); void updateDialogState(); @@ -42,13 +40,12 @@ public: QString iconKey() const; const InstanceCopyPrefs& getChosenOptions() const; -public slots: + public slots: void help(); -private -slots: + private slots: void on_iconButton_clicked(); - void on_instNameTextBox_textChanged(const QString &arg1); + void on_instNameTextBox_textChanged(const QString& arg1); // Checkboxes void on_selectAllCheckbox_stateChanged(int state); void on_copySavesCheckbox_stateChanged(int state); @@ -65,14 +62,14 @@ slots: void on_dontLinkSavesCheckbox_stateChanged(int state); void on_useCloneCheckbox_stateChanged(int state); -private: + private: void checkAllCheckboxes(const bool& b); void updateSelectAllCheckbox(); void updateUseCloneCheckbox(); void updateLinkOptions(); /* data */ - Ui::CopyInstanceDialog *ui; + Ui::CopyInstanceDialog* ui; QString InstIconKey; InstancePtr m_original; InstanceCopyPrefs m_selectedOptions; -- cgit From 197be9cfd0299edba57fe6fe1d7a7841ed0bb771 Mon Sep 17 00:00:00 2001 From: Rachel Powers <508861+Ryex@users.noreply.github.com> Date: Mon, 3 Apr 2023 18:00:56 -0700 Subject: fix: remove fixed datastream version Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com> --- launcher/FileSystem.cpp | 3 +-- launcher/filelink/FileLink.cpp | 2 -- 2 files changed, 1 insertion(+), 4 deletions(-) (limited to 'launcher/filelink/FileLink.cpp') diff --git a/launcher/FileSystem.cpp b/launcher/FileSystem.cpp index 869fbe36..bd985c5b 100644 --- a/launcher/FileSystem.cpp +++ b/launcher/FileSystem.cpp @@ -446,7 +446,6 @@ void create_link::runPrivileged(const QString& offset) // construct block of data to send QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); - out.setVersion(QDataStream::Qt_5_0); // choose correct version better? qint32 blocksize = quint32(sizeof(quint32)); for (auto link : m_links_to_make) { @@ -469,7 +468,7 @@ void create_link::runPrivileged(const QString& offset) QDataStream in; quint32 blockSize = 0; in.setDevice(clientConnection); - in.setVersion(QDataStream::Qt_5_0); + qDebug() << "Reading path results from client"; qDebug() << "bytes available" << clientConnection->bytesAvailable(); diff --git a/launcher/filelink/FileLink.cpp b/launcher/filelink/FileLink.cpp index ded46061..c9599b82 100644 --- a/launcher/filelink/FileLink.cpp +++ b/launcher/filelink/FileLink.cpp @@ -120,7 +120,6 @@ void FileLinkApp::joinServer(QString server) blockSize = 0; in.setDevice(&socket); - in.setVersion(QDataStream::Qt_5_0); connect(&socket, &QLocalSocket::connected, this, [&]() { qDebug() << "connected to server"; }); @@ -203,7 +202,6 @@ void FileLinkApp::sendResults() // construct block of data to send QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); - out.setVersion(QDataStream::Qt_5_0); qint32 blocksize = quint32(sizeof(quint32)); for (auto result : m_path_results) { -- cgit