From 2253100ac6a5dd58f9413b8e82a474e36e0929f0 Mon Sep 17 00:00:00 2001 From: PandaNinjas Date: Sat, 22 Jul 2023 14:26:49 -0400 Subject: Update libnbtplusplus submodule Signed-off-by: PandaNinjas --- libraries/libnbtplusplus | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'libraries') diff --git a/libraries/libnbtplusplus b/libraries/libnbtplusplus index 2203af7e..a5e8fd52 160000 --- a/libraries/libnbtplusplus +++ b/libraries/libnbtplusplus @@ -1 +1 @@ -Subproject commit 2203af7eeb48c45398139b583615134efd8d407f +Subproject commit a5e8fd52b8bf4ab5d5bcc042b2a247867589985f -- cgit From f7ffbcca6c5490e24ee74486cfc6698a38512561 Mon Sep 17 00:00:00 2001 From: seth Date: Wed, 26 Jul 2023 14:45:30 -0400 Subject: chore(docs): correct markdownlint warnings Signed-off-by: seth --- libraries/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'libraries') diff --git a/libraries/README.md b/libraries/README.md index 4da11314..e75a381e 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -61,7 +61,7 @@ The `standard` and `legacy` launchers are available. Example (some parts have been censored): -``` +```text mod legacyjavafixer-1.0 mainClass net.minecraft.launchwrapper.Launch param --username -- cgit From 1d468ac35ad88d8c77cc83f25e3704d9bd7df01b Mon Sep 17 00:00:00 2001 From: Sefa Eyeoglu Date: Wed, 2 Aug 2023 18:35:35 +0200 Subject: chore: reformat Signed-off-by: Sefa Eyeoglu --- libraries/LocalPeer/include/LocalPeer.h | 44 ++- libraries/LocalPeer/src/LocalPeer.cpp | 65 ++-- libraries/LocalPeer/src/LockedFile.cpp | 6 +- libraries/LocalPeer/src/LockedFile.h | 10 +- libraries/LocalPeer/src/LockedFile_unix.cpp | 6 +- libraries/LocalPeer/src/LockedFile_win.cpp | 40 +-- libraries/gamemode/include/gamemode_client.h | 328 ++++++++++----------- libraries/javacheck/JavaCheck.java | 8 +- libraries/katabasis/include/katabasis/Bits.h | 16 +- libraries/katabasis/include/katabasis/DeviceFlow.h | 64 ++-- libraries/katabasis/include/katabasis/Globals.h | 4 +- libraries/katabasis/include/katabasis/PollServer.h | 25 +- libraries/katabasis/include/katabasis/Reply.h | 38 +-- .../katabasis/include/katabasis/RequestParameter.h | 8 +- libraries/katabasis/src/DeviceFlow.cpp | 178 ++++++----- libraries/katabasis/src/JsonResponse.cpp | 5 +- libraries/katabasis/src/JsonResponse.h | 6 +- libraries/katabasis/src/PollServer.cpp | 37 +-- libraries/katabasis/src/Reply.cpp | 31 +- libraries/launcher/net/minecraft/Launcher.java | 8 +- .../launcher/org/prismlauncher/EntryPoint.java | 20 +- .../exception/ParameterNotFoundException.java | 2 - .../prismlauncher/exception/ParseException.java | 2 - .../org/prismlauncher/launcher/Launcher.java | 2 - .../launcher/impl/AbstractLauncher.java | 8 +- .../launcher/impl/StandardLauncher.java | 6 +- .../launcher/impl/legacy/LegacyFrame.java | 12 +- .../launcher/impl/legacy/LegacyLauncher.java | 15 +- .../org/prismlauncher/utils/Parameters.java | 6 +- .../org/prismlauncher/utils/ReflectionUtils.java | 9 +- .../org/prismlauncher/utils/logging/Level.java | 1 - .../org/prismlauncher/utils/logging/Log.java | 4 +- libraries/murmur2/src/MurmurHash2.h | 4 +- libraries/rainbow/include/rainbow.h | 27 +- libraries/rainbow/src/rainbow.cpp | 187 ++++-------- libraries/systeminfo/include/distroutils.h | 17 +- libraries/systeminfo/include/sys.h | 32 +- libraries/systeminfo/src/distroutils.cpp | 166 ++++------- libraries/systeminfo/src/sys_apple.cpp | 19 +- libraries/systeminfo/src/sys_test.cpp | 24 +- libraries/systeminfo/src/sys_unix.cpp | 56 ++-- libraries/systeminfo/src/sys_win32.cpp | 2 +- 42 files changed, 652 insertions(+), 896 deletions(-) (limited to 'libraries') diff --git a/libraries/LocalPeer/include/LocalPeer.h b/libraries/LocalPeer/include/LocalPeer.h index 3619ed5d..c370102f 100644 --- a/libraries/LocalPeer/include/LocalPeer.h +++ b/libraries/LocalPeer/include/LocalPeer.h @@ -43,56 +43,46 @@ #include #include - class QLocalServer; class LockedFile; -class ApplicationId -{ -public: /* methods */ +class ApplicationId { + public: /* methods */ // traditional app = installed system wide and used in a multi-user environment static ApplicationId fromTraditionalApp(); // ID based on a path with all the application data (no two instances with the same data path should run) - static ApplicationId fromPathAndVersion(const QString & dataPath, const QString & version); + static ApplicationId fromPathAndVersion(const QString& dataPath, const QString& version); // custom ID - static ApplicationId fromCustomId(const QString & id); + static ApplicationId fromCustomId(const QString& id); // custom ID, based on a raw string previously acquired from 'toString' - static ApplicationId fromRawString(const QString & id); - + static ApplicationId fromRawString(const QString& id); - QString toString() - { - return m_id; - } + QString toString() { return m_id; } -private: /* methods */ - ApplicationId(const QString & value) - { - m_id = value; - } + private: /* methods */ + ApplicationId(const QString& value) { m_id = value; } -private: /* data */ + private: /* data */ QString m_id; }; -class LocalPeer : public QObject -{ +class LocalPeer : public QObject { Q_OBJECT -public: - LocalPeer(QObject *parent, const ApplicationId &appId); + public: + LocalPeer(QObject* parent, const ApplicationId& appId); ~LocalPeer(); bool isClient(); - bool sendMessage(const QByteArray &message, int timeout); + bool sendMessage(const QByteArray& message, int timeout); ApplicationId applicationId() const; -Q_SIGNALS: - void messageReceived(const QByteArray &message); + Q_SIGNALS: + void messageReceived(const QByteArray& message); -protected Q_SLOTS: + protected Q_SLOTS: void receiveConnection(); -protected: + protected: ApplicationId id; QString socketName; std::unique_ptr server; diff --git a/libraries/LocalPeer/src/LocalPeer.cpp b/libraries/LocalPeer/src/LocalPeer.cpp index b7149c40..ab528c2a 100644 --- a/libraries/LocalPeer/src/LocalPeer.cpp +++ b/libraries/LocalPeer/src/LocalPeer.cpp @@ -38,21 +38,20 @@ ** ****************************************************************************/ - #include "LocalPeer.h" #include #include -#include +#include #include #include -#include #include +#include #include "LockedFile.h" #if defined(Q_OS_WIN) -#include #include -typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); +#include +typedef BOOL(WINAPI* PProcessIdToSessionId)(DWORD, DWORD*); static PProcessIdToSessionId pProcessIdToSessionId = 0; #endif #if defined(Q_OS_UNIX) @@ -60,9 +59,9 @@ static PProcessIdToSessionId pProcessIdToSessionId = 0; #include #endif +#include #include #include -#include static const char* ack = "ack"; @@ -79,13 +78,11 @@ ApplicationId ApplicationId::fromTraditionalApp() quint16 idNum = qChecksum(idc.constData(), idc.size()); auto socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); #if defined(Q_OS_WIN) - if (!pProcessIdToSessionId) - { + if (!pProcessIdToSessionId) { QLibrary lib("kernel32"); pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); } - if (pProcessIdToSessionId) - { + if (pProcessIdToSessionId) { DWORD sessionId = 0; pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); socketName += QLatin1Char('-') + QString::number(sessionId, 16); @@ -114,8 +111,7 @@ ApplicationId ApplicationId::fromRawString(const QString& id) return ApplicationId(id); } -LocalPeer::LocalPeer(QObject * parent, const ApplicationId &appId) - : QObject(parent), id(appId) +LocalPeer::LocalPeer(QObject* parent, const ApplicationId& appId) : QObject(parent), id(appId) { socketName = id.toString(); server.reset(new QLocalServer()); @@ -124,9 +120,7 @@ LocalPeer::LocalPeer(QObject * parent, const ApplicationId &appId) lockFile->open(QIODevice::ReadWrite); } -LocalPeer::~LocalPeer() -{ -} +LocalPeer::~LocalPeer() {} ApplicationId LocalPeer::applicationId() const { @@ -145,7 +139,7 @@ bool LocalPeer::isClient() #if defined(Q_OS_UNIX) // ### Workaround if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { - QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); + QFile::remove(QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName); res = server->listen(socketName); } #endif @@ -155,8 +149,7 @@ bool LocalPeer::isClient() return false; } - -bool LocalPeer::sendMessage(const QByteArray &message, int timeout) +bool LocalPeer::sendMessage(const QByteArray& message, int timeout) { if (!isClient()) return false; @@ -164,17 +157,15 @@ bool LocalPeer::sendMessage(const QByteArray &message, int timeout) QLocalSocket socket; bool connOk = false; int tries = 2; - for(int i = 0; i < tries; i++) { + for (int i = 0; i < tries; i++) { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); - connOk = socket.waitForConnected(timeout/2); - if (!connOk && i < (tries - 1)) - { + connOk = socket.waitForConnected(timeout / 2); + if (!connOk && i < (tries - 1)) { std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } - if (!connOk) - { + if (!connOk) { return false; } @@ -182,36 +173,30 @@ bool LocalPeer::sendMessage(const QByteArray &message, int timeout) QDataStream ds(&socket); ds.writeBytes(uMsg.constData(), uMsg.size()); - if(!socket.waitForBytesWritten(timeout)) - { + if (!socket.waitForBytesWritten(timeout)) { return false; } // wait for 'ack' - if(!socket.waitForReadyRead(timeout)) - { + if (!socket.waitForReadyRead(timeout)) { return false; } // make sure we got 'ack' - if(!(socket.read(qstrlen(ack)) == ack)) - { + if (!(socket.read(qstrlen(ack)) == ack)) { return false; } return true; } - void LocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); - if (!socket) - { + if (!socket) { return; } - while (socket->bytesAvailable() < static_cast(sizeof(quint32))) - { + while (socket->bytesAvailable() < static_cast(sizeof(quint32))) { socket->waitForReadyRead(); } QDataStream ds(socket); @@ -221,21 +206,19 @@ void LocalPeer::receiveConnection() uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); - do - { + do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); - if (got < 0) - { + if (got < 0) { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); - socket->waitForDisconnected(1000); // make sure client reads ack + socket->waitForDisconnected(1000); // make sure client reads ack delete socket; - emit messageReceived(uMsg); //### (might take a long time to return) + emit messageReceived(uMsg); //### (might take a long time to return) } diff --git a/libraries/LocalPeer/src/LockedFile.cpp b/libraries/LocalPeer/src/LockedFile.cpp index 73294a16..e93eabc9 100644 --- a/libraries/LocalPeer/src/LockedFile.cpp +++ b/libraries/LocalPeer/src/LockedFile.cpp @@ -80,8 +80,7 @@ \sa QFile::QFile() */ -LockedFile::LockedFile() - : QFile() +LockedFile::LockedFile() : QFile() { #ifdef Q_OS_WIN wmutex = 0; @@ -97,8 +96,7 @@ LockedFile::LockedFile() \sa QFile::QFile() */ -LockedFile::LockedFile(const QString &name) - : QFile(name) +LockedFile::LockedFile(const QString& name) : QFile(name) { #ifdef Q_OS_WIN wmutex = 0; diff --git a/libraries/LocalPeer/src/LockedFile.h b/libraries/LocalPeer/src/LockedFile.h index 2f29ee20..e8023251 100644 --- a/libraries/LocalPeer/src/LockedFile.h +++ b/libraries/LocalPeer/src/LockedFile.h @@ -45,13 +45,12 @@ #include #endif -class LockedFile : public QFile -{ -public: +class LockedFile : public QFile { + public: enum LockMode { NoLock = 0, ReadLock, WriteLock }; LockedFile(); - LockedFile(const QString &name); + LockedFile(const QString& name); ~LockedFile(); bool open(OpenMode mode); @@ -61,8 +60,7 @@ public: bool isLocked() const; LockMode lockMode() const; - private: - + private: #ifdef Q_OS_WIN Qt::HANDLE wmutex; Qt::HANDLE rmutex; diff --git a/libraries/LocalPeer/src/LockedFile_unix.cpp b/libraries/LocalPeer/src/LockedFile_unix.cpp index 6becc89e..d17e625e 100644 --- a/libraries/LocalPeer/src/LockedFile_unix.cpp +++ b/libraries/LocalPeer/src/LockedFile_unix.cpp @@ -38,10 +38,10 @@ ** ****************************************************************************/ -#include #include -#include #include +#include +#include #include "LockedFile.h" @@ -75,12 +75,10 @@ bool LockedFile::lock(LockMode mode, bool block) return false; } - m_lock_mode = mode; return true; } - bool LockedFile::unlock() { if (!isOpen()) { diff --git a/libraries/LocalPeer/src/LockedFile_win.cpp b/libraries/LocalPeer/src/LockedFile_win.cpp index 93d2c73b..a8dbead3 100644 --- a/libraries/LocalPeer/src/LockedFile_win.cpp +++ b/libraries/LocalPeer/src/LockedFile_win.cpp @@ -38,9 +38,9 @@ ** ****************************************************************************/ -#include "LockedFile.h" #include #include +#include "LockedFile.h" #define MUTEX_PREFIX "QtLockedFile mutex " // Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS @@ -50,8 +50,7 @@ Qt::HANDLE LockedFile::getMutexHandle(int idx, bool doCreate) { if (mutexname.isEmpty()) { QFileInfo fi(*this); - mutexname = QString::fromLatin1(MUTEX_PREFIX) - + fi.absoluteFilePath().toLower(); + mutexname = QString::fromLatin1(MUTEX_PREFIX) + fi.absoluteFilePath().toLower(); } QString mname(mutexname); if (idx >= 0) @@ -64,8 +63,7 @@ Qt::HANDLE LockedFile::getMutexHandle(int idx, bool doCreate) qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); return 0; } - } - else { + } else { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (LPCWSTR)mname.utf16()); if (!mutex) { if (GetLastError() != ERROR_FILE_NOT_FOUND) @@ -81,20 +79,18 @@ bool LockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock) Q_ASSERT(mutex); DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); switch (res) { - case WAIT_OBJECT_0: - case WAIT_ABANDONED: - return true; - break; - case WAIT_TIMEOUT: - break; - default: - qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); + case WAIT_OBJECT_0: + case WAIT_ABANDONED: + return true; + break; + case WAIT_TIMEOUT: + break; + default: + qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); } return false; } - - bool LockedFile::lock(LockMode mode, bool block) { if (!isOpen()) { @@ -130,8 +126,7 @@ bool LockedFile::lock(LockMode mode, bool block) qWarning("QtLockedFile::lock(): too many readers"); rmutex = 0; ok = false; - } - else if (!rmutex) { + } else if (!rmutex) { rmutex = getMutexHandle(idx, true); if (!rmutex || !waitMutex(rmutex, false)) ok = false; @@ -143,8 +138,7 @@ bool LockedFile::lock(LockMode mode, bool block) ReleaseMutex(wmutex); if (!ok) return false; - } - else { + } else { Q_ASSERT(rmutexes.isEmpty()); for (int i = 0; i < MAX_READERS; i++) { Qt::HANDLE mutex = getMutexHandle(i, false); @@ -152,8 +146,7 @@ bool LockedFile::lock(LockMode mode, bool block) rmutexes.append(mutex); } if (rmutexes.size()) { - DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), - TRUE, block ? INFINITE : 0); + DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), TRUE, block ? INFINITE : 0); if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { if (res != WAIT_TIMEOUT) qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); @@ -182,9 +175,8 @@ bool LockedFile::unlock() ReleaseMutex(rmutex); CloseHandle(rmutex); rmutex = 0; - } - else { - foreach(Qt::HANDLE mutex, rmutexes) { + } else { + foreach (Qt::HANDLE mutex, rmutexes) { ReleaseMutex(mutex); CloseHandle(mutex); } diff --git a/libraries/gamemode/include/gamemode_client.h b/libraries/gamemode/include/gamemode_client.h index b6f7afd4..b186cd48 100644 --- a/libraries/gamemode/include/gamemode_client.h +++ b/libraries/gamemode/include/gamemode_client.h @@ -94,7 +94,7 @@ static volatile int internal_libgamemode_loaded = 1; /* Typedefs for the functions to load */ typedef int (*api_call_return_int)(void); -typedef const char *(*api_call_return_cstring)(void); +typedef const char* (*api_call_return_cstring)(void); typedef int (*api_call_pid_return_int)(pid_t); /* Storage for functors */ @@ -111,26 +111,26 @@ static api_call_pid_return_int REAL_internal_gamemode_query_status_for = NULL; * * Returns 0 on success and -1 on failure */ -__attribute__((always_inline)) static inline int internal_bind_libgamemode_symbol( - void *handle, const char *name, void **out_func, size_t func_size, bool required) +__attribute__((always_inline)) static inline int internal_bind_libgamemode_symbol(void* handle, + const char* name, + void** out_func, + size_t func_size, + bool required) { - void *symbol_lookup = NULL; - char *dl_error = NULL; - - /* Safely look up the symbol */ - symbol_lookup = dlsym(handle, name); - dl_error = dlerror(); - if (required && (dl_error || !symbol_lookup)) { - snprintf(internal_gamemode_client_error_string, - sizeof(internal_gamemode_client_error_string), - "dlsym failed - %s", - dl_error); - return -1; - } - - /* Have the symbol correctly, copy it to make it usable */ - memcpy(out_func, &symbol_lookup, func_size); - return 0; + void* symbol_lookup = NULL; + char* dl_error = NULL; + + /* Safely look up the symbol */ + symbol_lookup = dlsym(handle, name); + dl_error = dlerror(); + if (required && (dl_error || !symbol_lookup)) { + snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "dlsym failed - %s", dl_error); + return -1; + } + + /* Have the symbol correctly, copy it to make it usable */ + memcpy(out_func, &symbol_lookup, func_size); + return 0; } /** @@ -140,98 +140,74 @@ __attribute__((always_inline)) static inline int internal_bind_libgamemode_symbo */ __attribute__((always_inline)) static inline int internal_load_libgamemode(void) { - /* We start at 1, 0 is a success and -1 is a fail */ - if (internal_libgamemode_loaded != 1) { - return internal_libgamemode_loaded; - } - - /* Anonymous struct type to define our bindings */ - struct binding { - const char *name; - void **functor; - size_t func_size; - bool required; - } bindings[] = { - { "real_gamemode_request_start", - (void **)&REAL_internal_gamemode_request_start, - sizeof(REAL_internal_gamemode_request_start), - true }, - { "real_gamemode_request_end", - (void **)&REAL_internal_gamemode_request_end, - sizeof(REAL_internal_gamemode_request_end), - true }, - { "real_gamemode_query_status", - (void **)&REAL_internal_gamemode_query_status, - sizeof(REAL_internal_gamemode_query_status), - false }, - { "real_gamemode_error_string", - (void **)&REAL_internal_gamemode_error_string, - sizeof(REAL_internal_gamemode_error_string), - true }, - { "real_gamemode_request_start_for", - (void **)&REAL_internal_gamemode_request_start_for, - sizeof(REAL_internal_gamemode_request_start_for), - false }, - { "real_gamemode_request_end_for", - (void **)&REAL_internal_gamemode_request_end_for, - sizeof(REAL_internal_gamemode_request_end_for), - false }, - { "real_gamemode_query_status_for", - (void **)&REAL_internal_gamemode_query_status_for, - sizeof(REAL_internal_gamemode_query_status_for), - false }, - }; - - void *libgamemode = NULL; - - /* Try and load libgamemode */ - libgamemode = dlopen("libgamemode.so.0", RTLD_NOW); - if (!libgamemode) { - /* Attempt to load unversioned library for compatibility with older - * versions (as of writing, there are no ABI changes between the two - - * this may need to change if ever ABI-breaking changes are made) */ - libgamemode = dlopen("libgamemode.so", RTLD_NOW); - if (!libgamemode) { - snprintf(internal_gamemode_client_error_string, - sizeof(internal_gamemode_client_error_string), - "dlopen failed - %s", - dlerror()); - internal_libgamemode_loaded = -1; - return -1; - } - } - - /* Attempt to bind all symbols */ - for (size_t i = 0; i < sizeof(bindings) / sizeof(bindings[0]); i++) { - struct binding *binder = &bindings[i]; - - if (internal_bind_libgamemode_symbol(libgamemode, - binder->name, - binder->functor, - binder->func_size, - binder->required)) { - internal_libgamemode_loaded = -1; - return -1; - }; - } - - /* Success */ - internal_libgamemode_loaded = 0; - return 0; + /* We start at 1, 0 is a success and -1 is a fail */ + if (internal_libgamemode_loaded != 1) { + return internal_libgamemode_loaded; + } + + /* Anonymous struct type to define our bindings */ + struct binding { + const char* name; + void** functor; + size_t func_size; + bool required; + } bindings[] = { + { "real_gamemode_request_start", (void**)&REAL_internal_gamemode_request_start, sizeof(REAL_internal_gamemode_request_start), + true }, + { "real_gamemode_request_end", (void**)&REAL_internal_gamemode_request_end, sizeof(REAL_internal_gamemode_request_end), true }, + { "real_gamemode_query_status", (void**)&REAL_internal_gamemode_query_status, sizeof(REAL_internal_gamemode_query_status), false }, + { "real_gamemode_error_string", (void**)&REAL_internal_gamemode_error_string, sizeof(REAL_internal_gamemode_error_string), true }, + { "real_gamemode_request_start_for", (void**)&REAL_internal_gamemode_request_start_for, + sizeof(REAL_internal_gamemode_request_start_for), false }, + { "real_gamemode_request_end_for", (void**)&REAL_internal_gamemode_request_end_for, sizeof(REAL_internal_gamemode_request_end_for), + false }, + { "real_gamemode_query_status_for", (void**)&REAL_internal_gamemode_query_status_for, + sizeof(REAL_internal_gamemode_query_status_for), false }, + }; + + void* libgamemode = NULL; + + /* Try and load libgamemode */ + libgamemode = dlopen("libgamemode.so.0", RTLD_NOW); + if (!libgamemode) { + /* Attempt to load unversioned library for compatibility with older + * versions (as of writing, there are no ABI changes between the two - + * this may need to change if ever ABI-breaking changes are made) */ + libgamemode = dlopen("libgamemode.so", RTLD_NOW); + if (!libgamemode) { + snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "dlopen failed - %s", dlerror()); + internal_libgamemode_loaded = -1; + return -1; + } + } + + /* Attempt to bind all symbols */ + for (size_t i = 0; i < sizeof(bindings) / sizeof(bindings[0]); i++) { + struct binding* binder = &bindings[i]; + + if (internal_bind_libgamemode_symbol(libgamemode, binder->name, binder->functor, binder->func_size, binder->required)) { + internal_libgamemode_loaded = -1; + return -1; + }; + } + + /* Success */ + internal_libgamemode_loaded = 0; + return 0; } /** * Redirect to the real libgamemode */ -__attribute__((always_inline)) static inline const char *gamemode_error_string(void) +__attribute__((always_inline)) static inline const char* gamemode_error_string(void) { - /* If we fail to load the system gamemode, or we have an error string already, return our error - * string instead of diverting to the system version */ - if (internal_load_libgamemode() < 0 || internal_gamemode_client_error_string[0] != '\0') { - return internal_gamemode_client_error_string; - } + /* If we fail to load the system gamemode, or we have an error string already, return our error + * string instead of diverting to the system version */ + if (internal_load_libgamemode() < 0 || internal_gamemode_client_error_string[0] != '\0') { + return internal_gamemode_client_error_string; + } - return REAL_internal_gamemode_error_string(); + return REAL_internal_gamemode_error_string(); } /** @@ -246,22 +222,22 @@ __attribute__((always_inline)) static inline #endif int gamemode_request_start(void) { - /* Need to load gamemode */ - if (internal_load_libgamemode() < 0) { + /* Need to load gamemode */ + if (internal_load_libgamemode() < 0) { #ifdef GAMEMODE_AUTO - fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); + fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif - return -1; - } + return -1; + } - if (REAL_internal_gamemode_request_start() < 0) { + if (REAL_internal_gamemode_request_start() < 0) { #ifdef GAMEMODE_AUTO - fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); + fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif - return -1; - } + return -1; + } - return 0; + return 0; } /* Redirect to the real libgamemode */ @@ -272,94 +248,90 @@ __attribute__((always_inline)) static inline #endif int gamemode_request_end(void) { - /* Need to load gamemode */ - if (internal_load_libgamemode() < 0) { + /* Need to load gamemode */ + if (internal_load_libgamemode() < 0) { #ifdef GAMEMODE_AUTO - fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); + fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif - return -1; - } + return -1; + } - if (REAL_internal_gamemode_request_end() < 0) { + if (REAL_internal_gamemode_request_end() < 0) { #ifdef GAMEMODE_AUTO - fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); + fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif - return -1; - } + return -1; + } - return 0; + return 0; } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_query_status(void) { - /* Need to load gamemode */ - if (internal_load_libgamemode() < 0) { - return -1; - } - - if (REAL_internal_gamemode_query_status == NULL) { - snprintf(internal_gamemode_client_error_string, - sizeof(internal_gamemode_client_error_string), - "gamemode_query_status missing (older host?)"); - return -1; - } - - return REAL_internal_gamemode_query_status(); + /* Need to load gamemode */ + if (internal_load_libgamemode() < 0) { + return -1; + } + + if (REAL_internal_gamemode_query_status == NULL) { + snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), + "gamemode_query_status missing (older host?)"); + return -1; + } + + return REAL_internal_gamemode_query_status(); } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_request_start_for(pid_t pid) { - /* Need to load gamemode */ - if (internal_load_libgamemode() < 0) { - return -1; - } - - if (REAL_internal_gamemode_request_start_for == NULL) { - snprintf(internal_gamemode_client_error_string, - sizeof(internal_gamemode_client_error_string), - "gamemode_request_start_for missing (older host?)"); - return -1; - } - - return REAL_internal_gamemode_request_start_for(pid); + /* Need to load gamemode */ + if (internal_load_libgamemode() < 0) { + return -1; + } + + if (REAL_internal_gamemode_request_start_for == NULL) { + snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), + "gamemode_request_start_for missing (older host?)"); + return -1; + } + + return REAL_internal_gamemode_request_start_for(pid); } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_request_end_for(pid_t pid) { - /* Need to load gamemode */ - if (internal_load_libgamemode() < 0) { - return -1; - } - - if (REAL_internal_gamemode_request_end_for == NULL) { - snprintf(internal_gamemode_client_error_string, - sizeof(internal_gamemode_client_error_string), - "gamemode_request_end_for missing (older host?)"); - return -1; - } - - return REAL_internal_gamemode_request_end_for(pid); + /* Need to load gamemode */ + if (internal_load_libgamemode() < 0) { + return -1; + } + + if (REAL_internal_gamemode_request_end_for == NULL) { + snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), + "gamemode_request_end_for missing (older host?)"); + return -1; + } + + return REAL_internal_gamemode_request_end_for(pid); } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_query_status_for(pid_t pid) { - /* Need to load gamemode */ - if (internal_load_libgamemode() < 0) { - return -1; - } - - if (REAL_internal_gamemode_query_status_for == NULL) { - snprintf(internal_gamemode_client_error_string, - sizeof(internal_gamemode_client_error_string), - "gamemode_query_status_for missing (older host?)"); - return -1; - } - - return REAL_internal_gamemode_query_status_for(pid); + /* Need to load gamemode */ + if (internal_load_libgamemode() < 0) { + return -1; + } + + if (REAL_internal_gamemode_query_status_for == NULL) { + snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), + "gamemode_query_status_for missing (older host?)"); + return -1; + } + + return REAL_internal_gamemode_query_status_for(pid); } -#endif // CLIENT_GAMEMODE_H +#endif // CLIENT_GAMEMODE_H diff --git a/libraries/javacheck/JavaCheck.java b/libraries/javacheck/JavaCheck.java index 4bf43a54..7cde86cf 100644 --- a/libraries/javacheck/JavaCheck.java +++ b/libraries/javacheck/JavaCheck.java @@ -1,10 +1,5 @@ public final class JavaCheck { - - private static final String[] CHECKED_PROPERTIES = new String[] { - "os.arch", - "java.version", - "java.vendor" - }; + private static final String[] CHECKED_PROPERTIES = new String[] {"os.arch", "java.version", "java.vendor"}; public static void main(String[] args) { int returnCode = 0; @@ -21,5 +16,4 @@ public final class JavaCheck { System.exit(returnCode); } - } diff --git a/libraries/katabasis/include/katabasis/Bits.h b/libraries/katabasis/include/katabasis/Bits.h index f11f25d2..15da2a5a 100644 --- a/libraries/katabasis/include/katabasis/Bits.h +++ b/libraries/katabasis/include/katabasis/Bits.h @@ -1,8 +1,8 @@ #pragma once -#include #include #include +#include #include namespace Katabasis { @@ -11,17 +11,13 @@ enum class Activity { LoggingIn, LoggingOut, Refreshing, - FailedSoft, //!< soft failure. this generally means the user auth details haven't been invalidated - FailedHard, //!< hard failure. auth is invalid - FailedGone, //!< hard failure. auth is invalid, and the account no longer exists + FailedSoft, //!< soft failure. this generally means the user auth details haven't been invalidated + FailedHard, //!< hard failure. auth is invalid + FailedGone, //!< hard failure. auth is invalid, and the account no longer exists Succeeded }; -enum class Validity { - None, - Assumed, - Certain -}; +enum class Validity { None, Assumed, Certain }; struct Token { QDateTime issueInstant; @@ -34,4 +30,4 @@ struct Token { bool persistent = true; }; -} +} // namespace Katabasis diff --git a/libraries/katabasis/include/katabasis/DeviceFlow.h b/libraries/katabasis/include/katabasis/DeviceFlow.h index 0401df3c..98724d81 100644 --- a/libraries/katabasis/include/katabasis/DeviceFlow.h +++ b/libraries/katabasis/include/katabasis/DeviceFlow.h @@ -2,13 +2,13 @@ #include #include -#include #include +#include #include +#include "Bits.h" #include "Reply.h" #include "RequestParameter.h" -#include "Bits.h" namespace Katabasis { @@ -16,14 +16,12 @@ class ReplyServer; class PollServer; /// Simple OAuth2 Device Flow authenticator. -class DeviceFlow: public QObject -{ +class DeviceFlow : public QObject { Q_OBJECT -public: + public: Q_ENUMS(GrantFlow) -public: - + public: struct Options { QString userAgent = QStringLiteral("Katabasis/1.0"); QString responseType = QStringLiteral("code"); @@ -34,7 +32,7 @@ public: QUrl accessTokenUrl; }; -public: + public: /// Are we authenticated? bool linked(); @@ -44,21 +42,21 @@ public: /// Provider-specific extra tokens, available after a successful authentication QVariantMap extraTokens(); -public: + public: // TODO: put in `Options` /// User-defined extra parameters to append to request URL QVariantMap extraRequestParams(); - void setExtraRequestParams(const QVariantMap &value); + void setExtraRequestParams(const QVariantMap& value); // TODO: split up the class into multiple, each implementing one OAuth2 flow /// Grant type (if non-standard) QString grantType(); - void setGrantType(const QString &value); + void setGrantType(const QString& value); -public: + public: /// Constructor. /// @param parent Parent object. - explicit DeviceFlow(Options & opts, Token & token, QObject *parent = 0, QNetworkAccessManager *manager = 0); + explicit DeviceFlow(Options& opts, Token& token, QObject* parent = 0, QNetworkAccessManager* manager = 0); /// Get refresh token. QString refreshToken(); @@ -66,7 +64,7 @@ public: /// Get token expiration time QDateTime expires(); -public slots: + public slots: /// Authenticate. void login(); @@ -79,24 +77,24 @@ public slots: /// Handle situation where reply server has opted to close its connection void serverHasClosed(bool paramsfound = false); -signals: + signals: /// Emitted when client needs to open a web browser window, with the given URL. - void openBrowser(const QUrl &url); + void openBrowser(const QUrl& url); /// Emitted when client can close the browser window. void closeBrowser(); /// Emitted when client needs to show a verification uri and user code - void showVerificationUriAndCode(const QUrl &uri, const QString &code, int expiresIn); + void showVerificationUriAndCode(const QUrl& uri, const QString& code, int expiresIn); /// Emitted when the internal state changes void activityChanged(Activity activity); -public slots: + public slots: /// Handle verification response. void onVerificationReceived(QMap); -protected slots: + protected slots: /// Handle completion of a Device Authorization Request void onDeviceAuthReplyFinished(); @@ -104,20 +102,20 @@ protected slots: void onRefreshFinished(); /// Handle failure of a refresh request. - void onRefreshError(QNetworkReply::NetworkError error, QNetworkReply *reply); + void onRefreshError(QNetworkReply::NetworkError error, QNetworkReply* reply); -protected: + protected: /// Set refresh token. - void setRefreshToken(const QString &v); + void setRefreshToken(const QString& v); /// Set token expiration time. void setExpires(QDateTime v); /// Start polling authorization server - void startPollServer(const QVariantMap ¶ms, int expiresIn); + void startPollServer(const QVariantMap& params, int expiresIn); /// Set authentication token. - void setToken(const QString &v); + void setToken(const QString& v); /// Set the linked state void setLinked(bool v); @@ -126,26 +124,26 @@ protected: void setExtraTokens(QVariantMap extraTokens); /// Set local poll server - void setPollServer(PollServer *server); + void setPollServer(PollServer* server); - PollServer * pollServer() const; + PollServer* pollServer() const; void updateActivity(Activity activity); -protected: + protected: Options options_; QVariantMap extraReqParams_; - QNetworkAccessManager *manager_ = nullptr; + QNetworkAccessManager* manager_ = nullptr; ReplyList timedReplies_; QString grantType_; -protected: - Token &token_; + protected: + Token& token_; -private: - PollServer *pollServer_ = nullptr; + private: + PollServer* pollServer_ = nullptr; Activity activity_ = Activity::Idle; }; -} +} // namespace Katabasis diff --git a/libraries/katabasis/include/katabasis/Globals.h b/libraries/katabasis/include/katabasis/Globals.h index 512745d3..02fe1cf4 100644 --- a/libraries/katabasis/include/katabasis/Globals.h +++ b/libraries/katabasis/include/katabasis/Globals.h @@ -45,7 +45,7 @@ const char OAUTH2_EXPIRES_IN[] = "expires_in"; const char OAUTH2_DEVICE_CODE[] = "device_code"; const char OAUTH2_USER_CODE[] = "user_code"; const char OAUTH2_VERIFICATION_URI[] = "verification_uri"; -const char OAUTH2_VERIFICATION_URL[] = "verification_url"; // Google sign-in +const char OAUTH2_VERIFICATION_URL[] = "verification_url"; // Google sign-in const char OAUTH2_VERIFICATION_URI_COMPLETE[] = "verification_uri_complete"; const char OAUTH2_INTERVAL[] = "interval"; @@ -56,4 +56,4 @@ const char AUTHORIZATION_CODE[] = "authorization_code"; const char HTTP_HTTP_HEADER[] = "HTTP"; const char HTTP_AUTHORIZATION_HEADER[] = "Authorization"; -} +} // namespace Katabasis diff --git a/libraries/katabasis/include/katabasis/PollServer.h b/libraries/katabasis/include/katabasis/PollServer.h index 77103867..fd6a5351 100644 --- a/libraries/katabasis/include/katabasis/PollServer.h +++ b/libraries/katabasis/include/katabasis/PollServer.h @@ -12,32 +12,35 @@ class QNetworkAccessManager; namespace Katabasis { /// Poll an authorization server for token -class PollServer : public QObject -{ +class PollServer : public QObject { Q_OBJECT -public: - explicit PollServer(QNetworkAccessManager * manager, const QNetworkRequest &request, const QByteArray & payload, int expiresIn, QObject *parent = 0); + public: + explicit PollServer(QNetworkAccessManager* manager, + const QNetworkRequest& request, + const QByteArray& payload, + int expiresIn, + QObject* parent = 0); /// Seconds to wait between polling requests Q_PROPERTY(int interval READ interval WRITE setInterval) int interval() const; void setInterval(int interval); -signals: + signals: void verificationReceived(QMap); - void serverClosed(bool); // whether it has found parameters + void serverClosed(bool); // whether it has found parameters -public slots: + public slots: void startPolling(); -protected slots: + protected slots: void onPollTimeout(); void onExpiration(); void onReplyFinished(); -protected: - QNetworkAccessManager *manager_; + protected: + QNetworkAccessManager* manager_; const QNetworkRequest request_; const QByteArray payload_; const int expiresIn_; @@ -45,4 +48,4 @@ protected: QTimer pollTimer; }; -} +} // namespace Katabasis diff --git a/libraries/katabasis/include/katabasis/Reply.h b/libraries/katabasis/include/katabasis/Reply.h index 415cf4ec..89ee90e9 100644 --- a/libraries/katabasis/include/katabasis/Reply.h +++ b/libraries/katabasis/include/katabasis/Reply.h @@ -1,38 +1,38 @@ #pragma once +#include #include -#include -#include -#include #include -#include +#include +#include +#include namespace Katabasis { constexpr int defaultTimeout = 30 * 1000; /// A network request/reply pair that can time out. -class Reply: public QTimer { +class Reply : public QTimer { Q_OBJECT -public: - Reply(QNetworkReply *reply, int timeOut = defaultTimeout, QObject *parent = 0); + public: + Reply(QNetworkReply* reply, int timeOut = defaultTimeout, QObject* parent = 0); -signals: + signals: void error(QNetworkReply::NetworkError); -public slots: + public slots: /// When time out occurs, the QNetworkReply's error() signal is triggered. void onTimeOut(); -public: - QNetworkReply *reply; + public: + QNetworkReply* reply; bool timedOut = false; }; /// List of O2Replies. class ReplyList { -public: + public: ReplyList() { ignoreSslErrors_ = false; } /// Destructor. @@ -40,24 +40,24 @@ public: virtual ~ReplyList(); /// Create a new O2Reply from a QNetworkReply, and add it to this list. - void add(QNetworkReply *reply, int timeOut = defaultTimeout); + void add(QNetworkReply* reply, int timeOut = defaultTimeout); /// Add an O2Reply to the list, while taking ownership of it. - void add(Reply *reply); + void add(Reply* reply); /// Remove item from the list that corresponds to a QNetworkReply. - void remove(QNetworkReply *reply); + void remove(QNetworkReply* reply); /// Find an O2Reply in the list, corresponding to a QNetworkReply. /// @return Matching O2Reply or NULL. - Reply *find(QNetworkReply *reply); + Reply* find(QNetworkReply* reply); bool ignoreSslErrors(); void setIgnoreSslErrors(bool ignoreSslErrors); -protected: - QList replies_; + protected: + QList replies_; bool ignoreSslErrors_; }; -} +} // namespace Katabasis diff --git a/libraries/katabasis/include/katabasis/RequestParameter.h b/libraries/katabasis/include/katabasis/RequestParameter.h index ca36934a..1d23cf0e 100644 --- a/libraries/katabasis/include/katabasis/RequestParameter.h +++ b/libraries/katabasis/include/katabasis/RequestParameter.h @@ -4,12 +4,10 @@ namespace Katabasis { /// Request parameter (name-value pair) participating in authentication. struct RequestParameter { - RequestParameter(const QByteArray &n, const QByteArray &v): name(n), value(v) {} - bool operator <(const RequestParameter &other) const { - return (name == other.name)? (value < other.value): (name < other.name); - } + RequestParameter(const QByteArray& n, const QByteArray& v) : name(n), value(v) {} + bool operator<(const RequestParameter& other) const { return (name == other.name) ? (value < other.value) : (name < other.name); } QByteArray name; QByteArray value; }; -} +} // namespace Katabasis diff --git a/libraries/katabasis/src/DeviceFlow.cpp b/libraries/katabasis/src/DeviceFlow.cpp index f49fcb7d..3b9d9c53 100644 --- a/libraries/katabasis/src/DeviceFlow.cpp +++ b/libraries/katabasis/src/DeviceFlow.cpp @@ -1,26 +1,26 @@ -#include -#include +#include +#include +#include #include -#include +#include #include -#include -#include #include -#include -#include +#include +#include +#include +#include #include -#include #include -#include +#include #include #include "katabasis/DeviceFlow.h" -#include "katabasis/PollServer.h" #include "katabasis/Globals.h" +#include "katabasis/PollServer.h" -#include "KatabasisLogging.h" #include "JsonResponse.h" +#include "KatabasisLogging.h" namespace { @@ -43,10 +43,11 @@ bool hasMandatoryDeviceAuthParams(const QVariantMap& params) return true; } -QByteArray createQueryParameters(const QList ¶meters) { +QByteArray createQueryParameters(const QList& parameters) +{ QByteArray ret; bool first = true; - for( auto & h: parameters) { + for (auto& h : parameters) { if (first) { first = false; } else { @@ -56,32 +57,35 @@ QByteArray createQueryParameters(const QList ¶m } return ret; } -} +} // namespace namespace Katabasis { -DeviceFlow::DeviceFlow(Options & opts, Token & token, QObject *parent, QNetworkAccessManager *manager) : QObject(parent), token_(token) { +DeviceFlow::DeviceFlow(Options& opts, Token& token, QObject* parent, QNetworkAccessManager* manager) : QObject(parent), token_(token) +{ manager_ = manager ? manager : new QNetworkAccessManager(this); qRegisterMetaType("QNetworkReply::NetworkError"); options_ = opts; } -bool DeviceFlow::linked() { +bool DeviceFlow::linked() +{ return token_.validity != Validity::None; } -void DeviceFlow::setLinked(bool v) { - qDebug() << "DeviceFlow::setLinked:" << (v? "true": "false"); +void DeviceFlow::setLinked(bool v) +{ + qDebug() << "DeviceFlow::setLinked:" << (v ? "true" : "false"); token_.validity = v ? Validity::Certain : Validity::None; } void DeviceFlow::updateActivity(Activity activity) { - if(activity_ == activity) { + if (activity_ == activity) { return; } activity_ = activity; - switch(activity) { + switch (activity) { case Katabasis::Activity::Idle: case Katabasis::Activity::LoggingIn: case Katabasis::Activity::LoggingOut: @@ -103,22 +107,26 @@ void DeviceFlow::updateActivity(Activity activity) emit activityChanged(activity_); } -QString DeviceFlow::token() { +QString DeviceFlow::token() +{ return token_.token; } -void DeviceFlow::setToken(const QString &v) { +void DeviceFlow::setToken(const QString& v) +{ token_.token = v; } -QVariantMap DeviceFlow::extraTokens() { +QVariantMap DeviceFlow::extraTokens() +{ return token_.extra; } -void DeviceFlow::setExtraTokens(QVariantMap extraTokens) { +void DeviceFlow::setExtraTokens(QVariantMap extraTokens) +{ token_.extra = extraTokens; } -void DeviceFlow::setPollServer(PollServer *server) +void DeviceFlow::setPollServer(PollServer* server) { if (pollServer_) pollServer_->deleteLater(); @@ -126,7 +134,7 @@ void DeviceFlow::setPollServer(PollServer *server) pollServer_ = server; } -PollServer *DeviceFlow::pollServer() const +PollServer* DeviceFlow::pollServer() const { return pollServer_; } @@ -136,7 +144,7 @@ QVariantMap DeviceFlow::extraRequestParams() return extraReqParams_; } -void DeviceFlow::setExtraRequestParams(const QVariantMap &value) +void DeviceFlow::setExtraRequestParams(const QVariantMap& value) { extraReqParams_ = value; } @@ -149,13 +157,14 @@ QString DeviceFlow::grantType() return OAUTH2_GRANT_TYPE_DEVICE; } -void DeviceFlow::setGrantType(const QString &value) +void DeviceFlow::setGrantType(const QString& value) { grantType_ = value; } // First get the URL and token to display to the user -void DeviceFlow::login() { +void DeviceFlow::login() +{ qDebug() << "DeviceFlow::link"; updateActivity(Activity::LoggingIn); @@ -173,7 +182,7 @@ void DeviceFlow::login() { QUrl url(options_.authorizationUrl); QNetworkRequest deviceRequest(url); deviceRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - QNetworkReply *tokenReply = manager_->post(deviceRequest, payload); + QNetworkReply* tokenReply = manager_->post(deviceRequest, payload); connect(tokenReply, &QNetworkReply::finished, this, &DeviceFlow::onDeviceAuthReplyFinished, Qt::QueuedConnection); } @@ -182,19 +191,18 @@ void DeviceFlow::login() { void DeviceFlow::onDeviceAuthReplyFinished() { qDebug() << "DeviceFlow::onDeviceAuthReplyFinished"; - QNetworkReply *tokenReply = qobject_cast(sender()); - if (!tokenReply) - { - qDebug() << "DeviceFlow::onDeviceAuthReplyFinished: reply is null"; - return; + QNetworkReply* tokenReply = qobject_cast(sender()); + if (!tokenReply) { + qDebug() << "DeviceFlow::onDeviceAuthReplyFinished: reply is null"; + return; } if (tokenReply->error() == QNetworkReply::NoError) { QByteArray replyData = tokenReply->readAll(); // Dump replyData // SENSITIVE DATA in RelWithDebInfo or Debug builds - //qDebug() << "DeviceFlow::onDeviceAuthReplyFinished: replyData\n"; - //qDebug() << QString( replyData ); + // qDebug() << "DeviceFlow::onDeviceAuthReplyFinished: replyData\n"; + // qDebug() << QString( replyData ); QVariantMap params = parseJsonResponse(replyData); @@ -202,7 +210,7 @@ void DeviceFlow::onDeviceAuthReplyFinished() qDebug() << "DeviceFlow::onDeviceAuthReplyFinished: Tokens returned:\n"; foreach (QString key, params.keys()) { // SENSITIVE DATA in RelWithDebInfo or Debug builds, so it is truncated first - qDebug() << key << ": "<< params.value( key ).toString(); + qDebug() << key << ": " << params.value(key).toString(); } // Check for mandatory parameters @@ -237,7 +245,7 @@ void DeviceFlow::onDeviceAuthReplyFinished() } // Spin up polling for the user completing the login flow out of band -void DeviceFlow::startPollServer(const QVariantMap ¶ms, int expiresIn) +void DeviceFlow::startPollServer(const QVariantMap& params, int expiresIn) { qDebug() << "DeviceFlow::startPollServer: device_ and user_code expires in" << expiresIn << "seconds"; @@ -250,14 +258,14 @@ void DeviceFlow::startPollServer(const QVariantMap ¶ms, int expiresIn) QList parameters; parameters.append(RequestParameter(OAUTH2_CLIENT_ID, options_.clientIdentifier.toUtf8())); - if ( !options_.clientSecret.isEmpty() ) { + if (!options_.clientSecret.isEmpty()) { parameters.append(RequestParameter(OAUTH2_CLIENT_SECRET, options_.clientSecret.toUtf8())); } parameters.append(RequestParameter(OAUTH2_CODE, deviceCode.toUtf8())); parameters.append(RequestParameter(OAUTH2_GRANT_TYPE, grantType.toUtf8())); QByteArray payload = createQueryParameters(parameters); - PollServer * pollServer = new PollServer(manager_, authRequest, payload, expiresIn, this); + PollServer* pollServer = new PollServer(manager_, authRequest, payload, expiresIn, this); if (params.contains(OAUTH2_INTERVAL)) { bool ok = false; int interval = params[OAUTH2_INTERVAL].toInt(&ok); @@ -272,7 +280,8 @@ void DeviceFlow::startPollServer(const QVariantMap ¶ms, int expiresIn) } // Once the user completes the flow, update the internal state and report it to observers -void DeviceFlow::onVerificationReceived(const QMap response) { +void DeviceFlow::onVerificationReceived(const QMap response) +{ qDebug() << "DeviceFlow::onVerificationReceived: Emitting closeBrowser()"; emit closeBrowser(); @@ -307,7 +316,7 @@ void DeviceFlow::onVerificationReceived(const QMap response) { // Or if the flow fails or the polling times out, update the internal state with error and report it to observers void DeviceFlow::serverHasClosed(bool paramsfound) { - if ( !paramsfound ) { + if (!paramsfound) { // server has probably timed out after receiving first response updateActivity(Activity::FailedHard); } @@ -315,7 +324,8 @@ void DeviceFlow::serverHasClosed(bool paramsfound) setPollServer(NULL); } -void DeviceFlow::logout() { +void DeviceFlow::logout() +{ qDebug() << "DeviceFlow::unlink"; updateActivity(Activity::LoggingOut); // FIXME: implement logout flows... if they exist @@ -323,24 +333,29 @@ void DeviceFlow::logout() { updateActivity(Activity::FailedHard); } -QDateTime DeviceFlow::expires() { +QDateTime DeviceFlow::expires() +{ return token_.notAfter; } -void DeviceFlow::setExpires(QDateTime v) { +void DeviceFlow::setExpires(QDateTime v) +{ token_.notAfter = v; } -QString DeviceFlow::refreshToken() { +QString DeviceFlow::refreshToken() +{ return token_.refresh_token; } -void DeviceFlow::setRefreshToken(const QString &v) { +void DeviceFlow::setRefreshToken(const QString& v) +{ qCDebug(katabasisCredentials) << "new refresh token:" << v; token_.refresh_token = v; } namespace { -QByteArray buildRequestBody(const QMap ¶meters) { +QByteArray buildRequestBody(const QMap& parameters) +{ QByteArray body; bool first = true; foreach (QString key, parameters.keys()) { @@ -354,9 +369,10 @@ QByteArray buildRequestBody(const QMap ¶meters) { } return body; } -} +} // namespace -bool DeviceFlow::refresh() { +bool DeviceFlow::refresh() +{ qDebug() << "DeviceFlow::refresh: Token: ..." << refreshToken().right(7); updateActivity(Activity::Refreshing); @@ -376,21 +392,22 @@ bool DeviceFlow::refresh() { refreshRequest.setHeader(QNetworkRequest::ContentTypeHeader, MIME_TYPE_XFORM); QMap parameters; parameters.insert(OAUTH2_CLIENT_ID, options_.clientIdentifier); - if ( !options_.clientSecret.isEmpty() ) { + if (!options_.clientSecret.isEmpty()) { parameters.insert(OAUTH2_CLIENT_SECRET, options_.clientSecret); } parameters.insert(OAUTH2_REFRESH_TOKEN, refreshToken()); parameters.insert(OAUTH2_GRANT_TYPE, OAUTH2_REFRESH_TOKEN); QByteArray data = buildRequestBody(parameters); - QNetworkReply *refreshReply = manager_->post(refreshRequest, data); + QNetworkReply* refreshReply = manager_->post(refreshRequest, data); timedReplies_.add(refreshReply); connect(refreshReply, &QNetworkReply::finished, this, &DeviceFlow::onRefreshFinished, Qt::QueuedConnection); return true; } -void DeviceFlow::onRefreshFinished() { - QNetworkReply *refreshReply = qobject_cast(sender()); +void DeviceFlow::onRefreshFinished() +{ + QNetworkReply* refreshReply = qobject_cast(sender()); auto networkError = refreshReply->error(); if (networkError == QNetworkReply::NoError) { @@ -399,10 +416,9 @@ void DeviceFlow::onRefreshFinished() { setToken(tokens.value(OAUTH2_ACCESS_TOKEN).toString()); setExpires(QDateTime::currentDateTimeUtc().addSecs(tokens.value(OAUTH2_EXPIRES_IN).toInt())); QString refreshToken = tokens.value(OAUTH2_REFRESH_TOKEN).toString(); - if(!refreshToken.isEmpty()) { + if (!refreshToken.isEmpty()) { setRefreshToken(refreshToken); - } - else { + } else { qDebug() << "No new refresh token. Keep the old one."; } timedReplies_.remove(refreshReply); @@ -415,37 +431,37 @@ void DeviceFlow::onRefreshFinished() { } } -void DeviceFlow::onRefreshError(QNetworkReply::NetworkError error, QNetworkReply *refreshReply) { +void DeviceFlow::onRefreshError(QNetworkReply::NetworkError error, QNetworkReply* refreshReply) +{ QString errorString = "No Reply"; - if(refreshReply) { + if (refreshReply) { timedReplies_.remove(refreshReply); errorString = refreshReply->errorString(); } - switch (error) - { - // used for invalid credentials and similar errors. Fall through. - case QNetworkReply::AuthenticationRequiredError: - case QNetworkReply::ContentAccessDenied: - case QNetworkReply::ContentOperationNotPermittedError: - case QNetworkReply::ProtocolInvalidOperationError: - updateActivity(Activity::FailedHard); - break; - case QNetworkReply::ContentGoneError: { - updateActivity(Activity::FailedGone); - break; - } - case QNetworkReply::TimeoutError: - case QNetworkReply::OperationCanceledError: - case QNetworkReply::SslHandshakeFailedError: - default: - updateActivity(Activity::FailedSoft); - return; + switch (error) { + // used for invalid credentials and similar errors. Fall through. + case QNetworkReply::AuthenticationRequiredError: + case QNetworkReply::ContentAccessDenied: + case QNetworkReply::ContentOperationNotPermittedError: + case QNetworkReply::ProtocolInvalidOperationError: + updateActivity(Activity::FailedHard); + break; + case QNetworkReply::ContentGoneError: { + updateActivity(Activity::FailedGone); + break; + } + case QNetworkReply::TimeoutError: + case QNetworkReply::OperationCanceledError: + case QNetworkReply::SslHandshakeFailedError: + default: + updateActivity(Activity::FailedSoft); + return; } - if(refreshReply) { + if (refreshReply) { refreshReply->deleteLater(); } qDebug() << "DeviceFlow::onRefreshFinished: Error" << static_cast(error) << " - " << errorString; } -} +} // namespace Katabasis diff --git a/libraries/katabasis/src/JsonResponse.cpp b/libraries/katabasis/src/JsonResponse.cpp index 63384d12..6840627a 100644 --- a/libraries/katabasis/src/JsonResponse.cpp +++ b/libraries/katabasis/src/JsonResponse.cpp @@ -7,7 +7,8 @@ namespace Katabasis { -QVariantMap parseJsonResponse(const QByteArray &data) { +QVariantMap parseJsonResponse(const QByteArray& data) +{ QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(data, &err); if (err.error != QJsonParseError::NoError) { @@ -23,4 +24,4 @@ QVariantMap parseJsonResponse(const QByteArray &data) { return doc.object().toVariantMap(); } -} +} // namespace Katabasis diff --git a/libraries/katabasis/src/JsonResponse.h b/libraries/katabasis/src/JsonResponse.h index e7fe7e30..ff347175 100644 --- a/libraries/katabasis/src/JsonResponse.h +++ b/libraries/katabasis/src/JsonResponse.h @@ -6,7 +6,7 @@ class QByteArray; namespace Katabasis { - /// Parse JSON data into a QVariantMap -QVariantMap parseJsonResponse(const QByteArray &data); +/// Parse JSON data into a QVariantMap +QVariantMap parseJsonResponse(const QByteArray& data); -} +} // namespace Katabasis diff --git a/libraries/katabasis/src/PollServer.cpp b/libraries/katabasis/src/PollServer.cpp index 1083c599..c1c316df 100644 --- a/libraries/katabasis/src/PollServer.cpp +++ b/libraries/katabasis/src/PollServer.cpp @@ -1,30 +1,28 @@ #include #include -#include "katabasis/PollServer.h" #include "JsonResponse.h" +#include "katabasis/PollServer.h" namespace { -QMap toVerificationParams(const QVariantMap &map) +QMap toVerificationParams(const QVariantMap& map) { QMap params; - for (QVariantMap::const_iterator i = map.constBegin(); - i != map.constEnd(); ++i) - { + for (QVariantMap::const_iterator i = map.constBegin(); i != map.constEnd(); ++i) { params[i.key()] = i.value().toString(); } return params; } -} +} // namespace namespace Katabasis { -PollServer::PollServer(QNetworkAccessManager *manager, const QNetworkRequest &request, const QByteArray &payload, int expiresIn, QObject *parent) - : QObject(parent) - , manager_(manager) - , request_(request) - , payload_(payload) - , expiresIn_(expiresIn) +PollServer::PollServer(QNetworkAccessManager* manager, + const QNetworkRequest& request, + const QByteArray& payload, + int expiresIn, + QObject* parent) + : QObject(parent), manager_(manager), request_(request), payload_(payload), expiresIn_(expiresIn) { expirationTimer.setTimerType(Qt::VeryCoarseTimer); expirationTimer.setInterval(expiresIn * 1000); @@ -58,7 +56,7 @@ void PollServer::startPolling() void PollServer::onPollTimeout() { qDebug() << "PollServer::onPollTimeout: retrying"; - QNetworkReply * reply = manager_->post(request_, payload_); + QNetworkReply* reply = manager_->post(request_, payload_); connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished())); } @@ -70,7 +68,7 @@ void PollServer::onExpiration() void PollServer::onReplyFinished() { - QNetworkReply *reply = qobject_cast(sender()); + QNetworkReply* reply = qobject_cast(sender()); if (!reply) { qDebug() << "PollServer::onReplyFinished: reply is null"; @@ -93,8 +91,7 @@ void PollServer::onReplyFinished() // polling interval on each such connection timeout, is RECOMMENDED." setInterval(interval() * 2); pollTimer.start(); - } - else { + } else { QString error = params.value("error"); if (error == "slow_down") { // rfc8628#section-3.2 @@ -103,14 +100,12 @@ void PollServer::onReplyFinished() // be increased by 5 seconds for this and all subsequent requests." setInterval(interval() + 5); pollTimer.start(); - } - else if (error == "authorization_pending") { + } else if (error == "authorization_pending") { // keep trying - rfc8628#section-3.2 // "The authorization request is still pending as the end user hasn't // yet completed the user-interaction steps (Section 3.3)." pollTimer.start(); - } - else { + } else { expirationTimer.stop(); emit serverClosed(true); // let O2 handle the other cases @@ -120,4 +115,4 @@ void PollServer::onReplyFinished() reply->deleteLater(); } -} +} // namespace Katabasis diff --git a/libraries/katabasis/src/Reply.cpp b/libraries/katabasis/src/Reply.cpp index c2607900..4a5017e2 100644 --- a/libraries/katabasis/src/Reply.cpp +++ b/libraries/katabasis/src/Reply.cpp @@ -1,42 +1,48 @@ -#include #include