diff --git a/CMakeLists.txt b/CMakeLists.txt index fd73687..0898546 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,54 +1,55 @@ cmake_minimum_required(VERSION 3.5) set(KF5_VERSION "5.57.0") # handled by release scripts set(KF5_DEP_VERSION "5.56.0") # handled by release scripts project(KWallet VERSION ${KF5_VERSION}) set(CMAKE_EXPORT_COMPILE_COMMANDS 1) include(FeatureSummary) find_package(ECM 5.56.0 NO_MODULE) set_package_properties(ECM PROPERTIES TYPE REQUIRED DESCRIPTION "Extra CMake Modules." URL "https://projects.kde.org/projects/kdesupport/extra-cmake-modules") feature_summary(WHAT REQUIRED_PACKAGES_NOT_FOUND FATAL_ON_MISSING_REQUIRED_PACKAGES) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) set(REQUIRED_QT_VERSION 5.10.0) find_package(Qt5 ${REQUIRED_QT_VERSION} CONFIG REQUIRED Widgets DBus) include(KDEInstallDirs) include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) include(KDECMakeSettings) include(ECMAddQch) include(ECMSetupVersion) include(ECMQtDeclareLoggingCategory) option(BUILD_KWALLETD "Build the kwallet daemon" ON) option(BUILD_KWALLET_QUERY "Build kwallet-query tool" ON) option(BUILD_QCH "Build API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)" OFF) add_feature_info(QCH ${BUILD_QCH} "API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)") find_package(KF5CoreAddons ${KF5_DEP_VERSION} REQUIRED) find_package(KF5Config ${KF5_DEP_VERSION} REQUIRED) find_package(KF5WindowSystem ${KF5_DEP_VERSION} REQUIRED) find_package(KF5I18n ${KF5_DEP_VERSION} REQUIRED) find_package(KF5DocTools ${KF5_DEP_VERSION}) +add_definitions(-DQT_NO_FOREACH) add_definitions(-DTRANSLATION_DOMAIN=\"kwalletd5\") if (IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/po") ki18n_install(po) endif() add_subdirectory(src) if (BUILD_TESTING) add_subdirectory(autotests) add_subdirectory(tests) add_subdirectory(examples) endif() if (KF5DocTools_FOUND) add_subdirectory(docs) endif() # contains list of debug categories, for kdebugsettings install(FILES kwallet.categories DESTINATION ${KDE_INSTALL_CONFDIR}) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/src/api/KWallet/kwallet.cpp b/src/api/KWallet/kwallet.cpp index c6909fe..392b20d 100644 --- a/src/api/KWallet/kwallet.cpp +++ b/src/api/KWallet/kwallet.cpp @@ -1,1672 +1,1674 @@ /* This file is part of the KDE project * * Copyright (C) 2002-2004 George Staikos * Copyright (C) 2008 Michael Leupold * Copyright (C) 2011 Valentin Rusu * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kwallet.h" #include #include "kwallet_api_debug.h" #include #include #include #include #include #include #include #if HAVE_KSECRETSSERVICE #include "ksecretsservice/ksecretsservicecollection.h" #endif #include "kwallet_interface.h" #if HAVE_KSECRETSSERVICE typedef QMap StringToStringStringMapMap; Q_DECLARE_METATYPE(StringToStringStringMapMap) #endif typedef QMap StringByteArrayMap; Q_DECLARE_METATYPE(StringByteArrayMap) namespace KWallet { class KWalletDLauncher { public: KWalletDLauncher(); ~KWalletDLauncher(); KWalletDLauncher(const KWalletDLauncher &) = delete; KWalletDLauncher& operator=(const KWalletDLauncher &) = delete; org::kde::KWallet &getInterface(); // this static variable is used below to switch between old KWallet // infrastructure and the new one which is built on top of the new // KSecretsService infrastructure. It's value can be changed via the // the Wallet configuration module in System Settings bool m_useKSecretsService; org::kde::KWallet *m_wallet_deamon; KConfigGroup m_cgroup; bool m_walletEnabled; }; Q_GLOBAL_STATIC(KWalletDLauncher, walletLauncher) static QString appid() { return qApp->applicationName(); } static void registerTypes() { static bool registered = false; if (!registered) { #if HAVE_KSECRETSSERVICE qDBusRegisterMetaType(); qDBusRegisterMetaType(); #endif qDBusRegisterMetaType(); registered = true; } } bool Wallet::isUsingKSecretsService() { return walletLauncher()->m_useKSecretsService; } const QString Wallet::LocalWallet() { // NOTE: This method stays unchanged for KSecretsService KConfigGroup cfg(KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Wallet")); if (!cfg.readEntry("Use One Wallet", true)) { QString tmp = cfg.readEntry("Local Wallet", "localwallet"); if (tmp.isEmpty()) { return QStringLiteral("localwallet"); } return tmp; } QString tmp = cfg.readEntry("Default Wallet", "kdewallet"); if (tmp.isEmpty()) { return QStringLiteral("kdewallet"); } return tmp; } const QString Wallet::NetworkWallet() { // NOTE: This method stays unchanged for KSecretsService KConfigGroup cfg(KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Wallet")); QString tmp = cfg.readEntry("Default Wallet", "kdewallet"); if (tmp.isEmpty()) { return QStringLiteral("kdewallet"); } return tmp; } const QString Wallet::PasswordFolder() { return QStringLiteral("Passwords"); } const QString Wallet::FormDataFolder() { return QStringLiteral("Form Data"); } class Q_DECL_HIDDEN Wallet::WalletPrivate { public: WalletPrivate(Wallet *wallet, int h, const QString &n) : q(wallet), name(n), handle(h) #if HAVE_KSECRETSSERVICE , secretsCollection(0) #endif {} void walletServiceUnregistered(); #if HAVE_KSECRETSSERVICE template int writeEntry(const QString &key, const T &value, Wallet::EntryType entryType) { int rc = -1; KSecretsService::Secret secret; secret.setValue(QVariant::fromValue(value)); KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = folder; attrs[KSS_ATTR_WALLETTYPE] = QString("%1").arg((int)entryType); KSecretsService::CreateCollectionItemJob *createItemJob = secretsCollection->createItem(key, attrs, secret); if (!createItemJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute CreateCollectionItemJob : " << createItemJob->errorString(); } rc = createItemJob->error(); return rc; } QExplicitlySharedDataPointer findItem(const QString &key) const; template int readEntry(const QString &key, T &value) const; bool readSecret(const QString &key, KSecretsService::Secret &value) const; template int forEachItemThatMatches(const QString &key, V verb) { int rc = -1; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = folder; KSecretsService::SearchCollectionItemsJob *searchItemsJob = secretsCollection->searchItems(attrs); if (searchItemsJob->exec()) { QRegExp re(key, Qt::CaseSensitive, QRegExp::Wildcard); - foreach (KSecretsService::SearchCollectionItemsJob::Item item, searchItemsJob->items()) { + const auto list = searchItemsJob->items(); + for (KSecretsService::SearchCollectionItemsJob::Item item : list) { KSecretsService::ReadItemPropertyJob *readLabelJob = item->label(); if (readLabelJob->exec()) { QString label = readLabelJob->propertyValue().toString(); if (re.exactMatch(label)) { if (verb(this, label, item.data())) { rc = 0; // one successful iteration already produced results, so success return } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute ReadItemPropertyJob " << readLabelJob->errorString(); } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::SearchCollectionItemsJob " << searchItemsJob->errorString(); } return rc; } void createDefaultFolders(); struct InsertIntoEntryList; struct InsertIntoMapList; struct InsertIntoPasswordList; KSecretsService::Collection *secretsCollection; #endif // HAVE_KSECRETSSERVICE Wallet *q; QString name; QString folder; int handle; int transactionId; }; #if HAVE_KSECRETSSERVICE void Wallet::WalletPrivate::createDefaultFolders() { // NOTE: KWalletManager expects newly created wallets to have two default folders // b->createFolder(KWallet::Wallet::PasswordFolder()); // b->createFolder(KWallet::Wallet::FormDataFolder()); QString strDummy(""); folder = PasswordFolder(); writeEntry(PasswordFolder(), strDummy, KWallet::Wallet::Unknown); folder = FormDataFolder(); writeEntry(FormDataFolder(), strDummy, KWallet::Wallet::Unknown); } #endif // HAVE_KSECRETSSERVICE static const char s_kwalletdServiceName[] = "org.kde.kwalletd5"; Wallet::Wallet(int handle, const QString &name) : QObject(nullptr), d(new WalletPrivate(this, handle, name)) { if (walletLauncher()->m_useKSecretsService) { // see openWallet for initialization code; this constructor does not have any code } else { QDBusServiceWatcher *watcher = new QDBusServiceWatcher(QString::fromLatin1(s_kwalletdServiceName), QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this); connect(watcher, SIGNAL(serviceUnregistered(QString)), this, SLOT(walletServiceUnregistered())); connect(&walletLauncher()->getInterface(), SIGNAL(walletClosed(int)), SLOT(slotWalletClosed(int))); connect(&walletLauncher()->getInterface(), SIGNAL(folderListUpdated(QString)), SLOT(slotFolderListUpdated(QString))); connect(&walletLauncher()->getInterface(), SIGNAL(folderUpdated(QString,QString)), SLOT(slotFolderUpdated(QString,QString))); connect(&walletLauncher()->getInterface(), SIGNAL(applicationDisconnected(QString,QString)), SLOT(slotApplicationDisconnected(QString,QString))); // Verify that the wallet is still open if (d->handle != -1) { QDBusReply r = walletLauncher()->getInterface().isOpen(d->handle); if (r.isValid() && !r) { d->handle = -1; d->name.clear(); } } } } Wallet::~Wallet() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { d->folder.clear(); d->name.clear(); delete d->secretsCollection; } else { #endif if (d->handle != -1) { if (!walletLauncher.isDestroyed()) { walletLauncher()->getInterface().close(d->handle, false, appid()); } else { qCDebug(KWALLET_API_LOG) << "Problem with static destruction sequence." "Destroy any static Wallet before the event-loop exits."; } d->handle = -1; d->folder.clear(); d->name.clear(); } #if HAVE_KSECRETSSERVICE } #endif delete d; } QStringList Wallet::walletList() { QStringList result; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::ListCollectionsJob *listJob = KSecretsService::Collection::listCollections(); if (listJob->exec()) { result = listJob->collections(); } else { qCDebug(KWALLET_API_LOG) << "Cannot execute ListCollectionsJob: " << listJob->errorString(); } } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().wallets(); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); } else { result = r; } } #if HAVE_KSECRETSSERVICE } #endif return result; } void Wallet::changePassword(const QString &name, WId w) { if (w == 0) { qCDebug(KWALLET_API_LOG) << "Pass a valid window to KWallet::Wallet::changePassword()."; } // Make sure the password prompt window will be visible and activated KWindowSystem::allowExternalProcessWindowActivation(); #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::Collection *coll = KSecretsService::Collection::findCollection(name); KSecretsService::ChangeCollectionPasswordJob *changePwdJob = coll->changePassword(); if (!changePwdJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute change password job: " << changePwdJob->errorString(); } coll->deleteLater(); } else { #endif if (walletLauncher()->m_walletEnabled) { walletLauncher()->getInterface().changePassword(name, (qlonglong)w, appid()); } #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::isEnabled() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { return walletLauncher()->m_cgroup.readEntry("Enabled", true); } else { #endif return walletLauncher()->m_walletEnabled; #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::isOpen(const QString &name) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::Collection *coll = KSecretsService::Collection::findCollection(name, KSecretsService::Collection::OpenOnly); KSecretsService::ReadCollectionPropertyJob *readLocked = coll->isLocked(); if (readLocked->exec()) { return !readLocked->propertyValue().toBool(); } else { qCDebug(KWALLET_API_LOG) << "ReadLocked job failed"; return false; } } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().isOpen(name); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return false; #if HAVE_KSECRETSSERVICE } #endif } int Wallet::closeWallet(const QString &name, bool force) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "Wallet::closeWallet NOOP"; return 0; } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().close(name, force); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return -1; } else { return r; } } else return -1; #if HAVE_KSECRETSSERVICE } #endif } int Wallet::deleteWallet(const QString &name) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::Collection *coll = KSecretsService::Collection::findCollection(name, KSecretsService::Collection::OpenOnly); KJob *deleteJob = coll->deleteCollection(); if (!deleteJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute delete job " << deleteJob->errorString(); } return deleteJob->error(); } else { #endif if (walletLauncher->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().deleteWallet(name); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return -1; } else { return r; } } else return -1; #if HAVE_KSECRETSSERVICE } #endif } Wallet *Wallet::openWallet(const QString &name, WId w, OpenType ot) { if (w == 0) { qCDebug(KWALLET_API_LOG) << "Pass a valid window to KWallet::Wallet::openWallet()."; } if (!walletLauncher()->m_walletEnabled) { qCDebug(KWALLET_API_LOG) << "User disabled the wallet system so returning 0 here."; return nullptr; } #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { Wallet *wallet = new Wallet(-1, name); // FIXME: should we specify CreateCollection or OpenOnly here? wallet->d->secretsCollection = KSecretsService::Collection::findCollection(name, KSecretsService::Collection::CreateCollection, QVariantMap(), w); connect(wallet->d->secretsCollection, SIGNAL(statusChanged(int)), wallet, SLOT(slotCollectionStatusChanged(int))); connect(wallet->d->secretsCollection, SIGNAL(deleted()), wallet, SLOT(slotCollectionDeleted())); if (ot == Synchronous) { qCDebug(KWALLET_API_LOG) << "WARNING openWallet OpenType=Synchronous requested"; // TODO: not sure what to do with in this case; however, all other KSecretsService API methods are already // async and will perform sync inside this API because of it's design } return wallet; } else { #endif Wallet *wallet = new Wallet(-1, name); // connect the daemon's opened signal to the slot filtering the // signals we need connect(&walletLauncher()->getInterface(), SIGNAL(walletAsyncOpened(int,int)), wallet, SLOT(walletAsyncOpened(int,int))); // Make sure the password prompt window will be visible and activated KWindowSystem::allowExternalProcessWindowActivation(); org::kde::KWallet &interface = walletLauncher->getInterface(); // do the call QDBusReply r; if (ot == Synchronous) { interface.setTimeout(0x7FFFFFFF); // Don't timeout after 25s, but 24 days r = interface.open(name, (qlonglong)w, appid()); interface.setTimeout(-1); // Back to the default 25s // after this call, r would contain a transaction id >0 if OK or -1 if NOK // if OK, the slot walletAsyncOpened should have been received, but the transaction id // will not match. We'll get that handle from the reply - see below } else if (ot == Asynchronous) { r = interface.openAsync(name, (qlonglong)w, appid(), true); } else if (ot == Path) { r = interface.openPathAsync(name, (qlonglong)w, appid(), true); } else { delete wallet; return nullptr; } // error communicating with the daemon (maybe not running) if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); delete wallet; return nullptr; } wallet->d->transactionId = r.value(); if (ot == Synchronous || ot == Path) { // check for an immediate error if (wallet->d->transactionId < 0) { delete wallet; wallet = nullptr; } else { wallet->d->handle = r.value(); } } else if (ot == Asynchronous) { if (wallet->d->transactionId < 0) { QTimer::singleShot(0, wallet, SLOT(emitWalletAsyncOpenError())); // client code is responsible for deleting the wallet } } return wallet; #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotCollectionStatusChanged(int status) { #if HAVE_KSECRETSSERVICE KSecretsService::Collection::Status collStatus = (KSecretsService::Collection::Status)status; switch (collStatus) { case KSecretsService::Collection::NewlyCreated: d->createDefaultFolders(); // fall through case KSecretsService::Collection::FoundExisting: emitWalletOpened(); break; case KSecretsService::Collection::Deleted: case KSecretsService::Collection::Invalid: case KSecretsService::Collection::Pending: // nothing to do break; case KSecretsService::Collection::NotFound: emitWalletAsyncOpenError(); break; } #else Q_UNUSED(status) #endif } void Wallet::slotCollectionDeleted() { d->folder.clear(); d->name.clear(); emit walletClosed(); } bool Wallet::disconnectApplication(const QString &wallet, const QString &app) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "Wallet::disconnectApplication NOOP"; return true; } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().disconnectApplication(wallet, app); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return -1; #if HAVE_KSECRETSSERVICE } #endif } QStringList Wallet::users(const QString &name) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "KSecretsService does not handle users list"; return QStringList(); } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().users(name); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return QStringList(); } else { return r; } } else return QStringList(); #if HAVE_KSECRETSSERVICE } #endif } int Wallet::sync() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // NOOP with KSecretsService } else { #endif if (d->handle == -1) { return -1; } walletLauncher()->getInterface().sync(d->handle, appid()); #if HAVE_KSECRETSSERVICE } #endif return 0; } int Wallet::lockWallet() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::CollectionLockJob *lockJob = d->secretsCollection->lock(); if (lockJob->exec()) { d->folder.clear(); d->name.clear(); } else { qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::CollectionLockJob : " << lockJob->errorString(); return -1; } return lockJob->error(); } else { #endif if (d->handle == -1) { return -1; } QDBusReply r = walletLauncher()->getInterface().close(d->handle, true, appid()); d->handle = -1; d->folder.clear(); d->name.clear(); if (r.isValid()) { return r; } else { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return -1; } #if HAVE_KSECRETSSERVICE } #endif } const QString &Wallet::walletName() const { return d->name; } bool Wallet::isOpen() const { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { return !d->secretsCollection->isLocked(); } else { #endif return d->handle != -1; #if HAVE_KSECRETSSERVICE } #endif } void Wallet::requestChangePassword(WId w) { if (w == 0) { qCDebug(KWALLET_API_LOG) << "Pass a valid window to KWallet::Wallet::requestChangePassword()."; } #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::ChangeCollectionPasswordJob *changePwdJob = d->secretsCollection->changePassword(); if (!changePwdJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute ChangeCollectionPasswordJob : " << changePwdJob->errorString(); } } else { #endif if (d->handle == -1) { return; } // Make sure the password prompt window will be visible and activated KWindowSystem::allowExternalProcessWindowActivation(); walletLauncher()->getInterface().changePassword(d->name, (qlonglong)w, appid()); #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotWalletClosed(int handle) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->handle == handle) { d->handle = -1; d->folder.clear(); d->name.clear(); emit walletClosed(); } #if HAVE_KSECRETSSERVICE } #endif } QStringList Wallet::folderList() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QStringList result; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = ""; // search for items having this attribute no matter what value it has KSecretsService::SearchCollectionItemsJob *searchJob = d->secretsCollection->searchItems(attrs); if (searchJob->exec()) { - KSecretsService::ReadCollectionItemsJob::ItemList itemList = searchJob->items(); - foreach (const KSecretsService::ReadCollectionItemsJob::Item &item, itemList) { + const KSecretsService::ReadCollectionItemsJob::ItemList itemList = searchJob->items(); + for (const KSecretsService::ReadCollectionItemsJob::Item &item : itemList) { KSecretsService::ReadItemPropertyJob *readAttrsJob = item->attributes(); if (readAttrsJob->exec()) { KSecretsService::StringStringMap attrs = readAttrsJob->propertyValue().value(); const QString folder = attrs[KSS_ATTR_ENTRYFOLDER]; if (!folder.isEmpty() && !result.contains(folder)) { result.append(folder); } } else { qCDebug(KWALLET_API_LOG) << "Cannot read item attributes : " << readAttrsJob->errorString(); } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute ReadCollectionItemsJob : " << searchJob->errorString(); } return result; } else { #endif if (d->handle == -1) { return QStringList(); } QDBusReply r = walletLauncher()->getInterface().folderList(d->handle, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return QStringList(); } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } QStringList Wallet::entryList() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QStringList result; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = d->folder; KSecretsService::SearchCollectionItemsJob *readItemsJob = d->secretsCollection->searchItems(attrs); if (readItemsJob->exec()) { - foreach (KSecretsService::SearchCollectionItemsJob::Item item, readItemsJob->items()) { + const auto list = readItemsJob->items(); + for (KSecretsService::SearchCollectionItemsJob::Item item : list) { KSecretsService::ReadItemPropertyJob *readLabelJob = item->label(); if (readLabelJob->exec()) { result.append(readLabelJob->propertyValue().toString()); } else { qCDebug(KWALLET_API_LOG) << "Cannot execute readLabelJob" << readItemsJob->errorString(); } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute readItemsJob" << readItemsJob->errorString(); } return result; } else { #endif if (d->handle == -1) { return QStringList(); } QDBusReply r = walletLauncher()->getInterface().entryList(d->handle, d->folder, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return QStringList(); } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::hasFolder(const QString &f) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // FIXME: well, this is not the best implementation, but it's done quickly :) // the best way would be to searchItems with the attribute label having the value f // doing that would reduce DBus traffic. But KWallet API wille not last. QStringList folders = folderList(); return folders.contains(f); } else { #endif if (d->handle == -1) { return false; } QDBusReply r = walletLauncher()->getInterface().hasFolder(d->handle, f, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::createFolder(const QString &f) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QString strDummy(""); d->folder = f; d->writeEntry(f, strDummy, KWallet::Wallet::Unknown); return true; } else { #endif if (d->handle == -1) { return false; } if (!hasFolder(f)) { QDBusReply r = walletLauncher()->getInterface().createFolder(d->handle, f, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } return true; // folder already exists #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::setFolder(const QString &f) { bool rc = false; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { if (hasFolder(f)) { d->folder = f; rc = true; } } else { #endif if (d->handle == -1) { return rc; } // Don't do this - the folder could have disappeared? #if 0 if (f == d->folder) { return true; } #endif if (hasFolder(f)) { d->folder = f; rc = true; } #if HAVE_KSECRETSSERVICE } #endif return rc; } bool Wallet::removeFolder(const QString &f) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { bool result = false; // search for all items having the folder f then delete them KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = f; KSecretsService::SearchCollectionItemsJob *searchJob = d->secretsCollection->searchItems(attrs); if (searchJob->exec()) { - KSecretsService::SearchCollectionItemsJob::ItemList itemList = searchJob->items(); + const KSecretsService::SearchCollectionItemsJob::ItemList itemList = searchJob->items(); if (!itemList.isEmpty()) { result = true; - foreach (const KSecretsService::SearchCollectionItemsJob::Item &item, itemList) { + for (const KSecretsService::SearchCollectionItemsJob::Item &item : itemList) { KSecretsService::SecretItemDeleteJob *deleteJob = item->deleteItem(); if (!deleteJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot delete item : " << deleteJob->errorString(); result = false; } result &= true; } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::SearchCollectionItemsJob : " << searchJob->errorString(); } return result; } else { #endif if (d->handle == -1) { return false; } QDBusReply r = walletLauncher()->getInterface().removeFolder(d->handle, f, appid()); if (d->folder == f) { setFolder(QString()); } if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } const QString &Wallet::currentFolder() const { return d->folder; } #if HAVE_KSECRETSSERVICE QExplicitlySharedDataPointer Wallet::WalletPrivate::findItem(const QString &key) const { QExplicitlySharedDataPointer result; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = folder; attrs["Label"] = key; KSecretsService::SearchCollectionItemsJob *searchJob = secretsCollection->searchItems(attrs); if (searchJob->exec()) { KSecretsService::SearchCollectionItemsJob::ItemList itemList = searchJob->items(); if (!itemList.isEmpty()) { result = itemList.first(); } else { qCDebug(KWALLET_API_LOG) << "entry named " << key << " not found in folder " << folder; } } else { qCDebug(KWALLET_API_LOG) << "Cannot exec KSecretsService::SearchCollectionItemsJob : " << searchJob->errorString(); } return result; } template int Wallet::WalletPrivate::readEntry(const QString &key, T &value) const { int rc = -1; QExplicitlySharedDataPointer item = findItem(key); if (item) { KSecretsService::GetSecretItemSecretJob *readJob = item->getSecret(); if (readJob->exec()) { KSecretsService::Secret theSecret = readJob->secret(); qCDebug(KWALLET_API_LOG) << "Secret contentType is " << theSecret.contentType(); value = theSecret.value().value(); rc = 0; } else { qCDebug(KWALLET_API_LOG) << "Cannot exec GetSecretItemSecretJob : " << readJob->errorString(); } } return rc; } bool Wallet::WalletPrivate::readSecret(const QString &key, KSecretsService::Secret &value) const { bool result = false; QExplicitlySharedDataPointer item = findItem(key); if (item) { KSecretsService::GetSecretItemSecretJob *readJob = item->getSecret(); if (readJob->exec()) { value = readJob->secret(); result = true; } else { qCDebug(KWALLET_API_LOG) << "Cannot exec GetSecretItemSecretJob : " << readJob->errorString(); } } return result; } #endif int Wallet::readEntry(const QString &key, QByteArray &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { return d->readEntry(key, value); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readEntry(d->handle, d->folder, key, appid()); if (r.isValid()) { value = r; rc = 0; } #if HAVE_KSECRETSSERVICE } #endif return rc; } #if HAVE_KSECRETSSERVICE struct Wallet::WalletPrivate::InsertIntoEntryList { InsertIntoEntryList(QMap< QString, QByteArray> &value) : _value(value) {} bool operator()(Wallet::WalletPrivate *, const QString &label, KSecretsService::SecretItem *item) { bool result = false; KSecretsService::GetSecretItemSecretJob *readSecretJob = item->getSecret(); if (readSecretJob->exec()) { _value.insert(label, readSecretJob->secret().value().toByteArray()); result = true; } else { qCDebug(KWALLET_API_LOG) << "Cannot execute GetSecretItemSecretJob " << readSecretJob->errorString(); } return result; } QMap< QString, QByteArray > _value; }; #endif int Wallet::readEntryList(const QString &key, QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->forEachItemThatMatches(key, WalletPrivate::InsertIntoEntryList(value)); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readEntryList(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; // convert to const QVariantMap val = r.value(); for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { value.insert(it.key(), it.value().toByteArray()); } } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::renameEntry(const QString &oldName, const QString &newName) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(oldName); if (item) { KSecretsService::WriteItemPropertyJob *writeJob = item->setLabel(newName); if (!writeJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot exec WriteItemPropertyJob : " << writeJob->errorString(); } rc = writeJob->error(); } else { qCDebug(KWALLET_API_LOG) << "Cannot locate item " << oldName << " in folder " << d->folder; } } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().renameEntry(d->handle, d->folder, oldName, newName, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::readMap(const QString &key, QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QByteArray ba; rc = d->readEntry< QByteArray >(key, ba); if (rc == 0 && !ba.isEmpty()) { QDataStream ds(&ba, QIODevice::ReadOnly); ds >> value; } } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readMap(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; QByteArray v = r; if (!v.isEmpty()) { QDataStream ds(&v, QIODevice::ReadOnly); ds >> value; } } #if HAVE_KSECRETSSERVICE } #endif return rc; } #if HAVE_KSECRETSSERVICE struct Wallet::WalletPrivate::InsertIntoMapList { InsertIntoMapList(QMap< QString, QMap< QString, QString > > &value) : _value(value) {} bool operator()(Wallet::WalletPrivate *d, const QString &label, KSecretsService::SecretItem *) { bool result = false; QMap map; if (d->readEntry< QMap< QString, QString> >(label, map)) { _value.insert(label, map); result = true; } return result; } QMap< QString, QMap< QString, QString> > &_value; }; #endif int Wallet::readMapList(const QString &key, QMap > &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->forEachItemThatMatches(key, WalletPrivate::InsertIntoMapList(value)); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readMapList(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; const QVariantMap val = r.value(); for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { QByteArray mapData = it.value().toByteArray(); if (!mapData.isEmpty()) { QDataStream ds(&mapData, QIODevice::ReadOnly); QMap v; ds >> v; value.insert(it.key(), v); } } } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::readPassword(const QString &key, QString &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->readEntry(key, value); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readPassword(d->handle, d->folder, key, appid()); if (r.isValid()) { value = r; rc = 0; } #if HAVE_KSECRETSSERVICE } #endif return rc; } #if HAVE_KSECRETSSERVICE struct Wallet::WalletPrivate::InsertIntoPasswordList { InsertIntoPasswordList(QMap< QString, QString> &value) : _value(value) {} bool operator()(Wallet::WalletPrivate *d, const QString &label, KSecretsService::SecretItem *) { bool result = false; QString pwd; if (d->readEntry(label, pwd) == 0) { _value.insert(label, pwd); result = true; } return result; } QMap< QString, QString > &_value; }; #endif int Wallet::readPasswordList(const QString &key, QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->forEachItemThatMatches(key, WalletPrivate::InsertIntoPasswordList(value)); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readPasswordList(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; const QVariantMap val = r.value(); for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { value.insert(it.key(), it.value().toString()); } } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writeEntry(const QString &key, const QByteArray &value, EntryType entryType) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->writeEntry(key, value, entryType); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().writeEntry(d->handle, d->folder, key, value, int(entryType), appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writeEntry(const QString &key, const QByteArray &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = writeEntry(key, value, Stream); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().writeEntry(d->handle, d->folder, key, value, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writeMap(const QString &key, const QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { d->writeEntry(key, value, Map); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QByteArray mapData; QDataStream ds(&mapData, QIODevice::WriteOnly); ds << value; QDBusReply r = walletLauncher()->getInterface().writeMap(d->handle, d->folder, key, mapData, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writePassword(const QString &key, const QString &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->writeEntry(key, value, Password); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().writePassword(d->handle, d->folder, key, value, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } bool Wallet::hasEntry(const QString &key) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(key); return item; } else { #endif if (d->handle == -1) { return false; } QDBusReply r = walletLauncher()->getInterface().hasEntry(d->handle, d->folder, key, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } int Wallet::removeEntry(const QString &key) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(key); if (item) { KSecretsService::SecretItemDeleteJob *deleteJob = item->deleteItem(); if (!deleteJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute SecretItemDeleteJob " << deleteJob->errorString(); } rc = deleteJob->error(); } } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().removeEntry(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } Wallet::EntryType Wallet::entryType(const QString &key) { int rc = 0; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(key); if (item) { KSecretsService::ReadItemPropertyJob *readAttrsJob = item->attributes(); if (readAttrsJob->exec()) { KSecretsService::StringStringMap attrs = readAttrsJob->propertyValue().value(); if (attrs.contains(KSS_ATTR_WALLETTYPE)) { QString entryType = attrs[KSS_ATTR_WALLETTYPE]; bool ok = false; rc = entryType.toInt(&ok); if (!ok) { rc = 0; qCDebug(KWALLET_API_LOG) << KSS_ATTR_WALLETTYPE << " attribute holds non int value " << attrs[KSS_ATTR_WALLETTYPE]; } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute GetSecretItemSecretJob " << readAttrsJob->errorString(); } } } else { #endif if (d->handle == -1) { return Wallet::Unknown; } QDBusReply r = walletLauncher()->getInterface().entryType(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return static_cast(rc); } void Wallet::WalletPrivate::walletServiceUnregistered() { if (handle >= 0) { q->slotWalletClosed(handle); } } void Wallet::slotFolderUpdated(const QString &wallet, const QString &folder) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->name == wallet) { emit folderUpdated(folder); } #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotFolderListUpdated(const QString &wallet) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->name == wallet) { emit folderListUpdated(); } #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotApplicationDisconnected(const QString &wallet, const QString &application) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->handle >= 0 && d->name == wallet && application == appid()) { slotWalletClosed(d->handle); } #if HAVE_KSECRETSSERVICE } #endif } void Wallet::walletAsyncOpened(int tId, int handle) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif // ignore responses to calls other than ours if (d->transactionId != tId || d->handle != -1) { return; } // disconnect the async signal disconnect(this, SLOT(walletAsyncOpened(int,int))); d->handle = handle; emit walletOpened(handle > 0); #if HAVE_KSECRETSSERVICE } #endif } void Wallet::emitWalletAsyncOpenError() { emit walletOpened(false); } void Wallet::emitWalletOpened() { emit walletOpened(true); } bool Wallet::folderDoesNotExist(const QString &wallet, const QString &folder) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "WARNING: changing semantics of folderDoesNotExist with KSS: will prompt for the password"; Wallet *w = openWallet(wallet, 0, Synchronous); if (w) { return !w->hasFolder(folder); } else { return true; } } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().folderDoesNotExist(wallet, folder); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return false; #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::keyDoesNotExist(const QString &wallet, const QString &folder, const QString &key) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "WARNING: changing semantics of keyDoesNotExist with KSS: will prompt for the password"; Wallet *w = openWallet(wallet, 0, Synchronous); if (w) { return !w->hasEntry(key); } return false; } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().keyDoesNotExist(wallet, folder, key); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return false; #if HAVE_KSECRETSSERVICE } #endif } void Wallet::virtual_hook(int, void *) { //BASE::virtual_hook( id, data ); } KWalletDLauncher::KWalletDLauncher() : m_wallet_deamon(nullptr) , m_cgroup(KSharedConfig::openConfig(QStringLiteral("kwalletrc") , KConfig::NoGlobals)->group("Wallet")) , m_walletEnabled(false) { m_useKSecretsService = m_cgroup.readEntry("UseKSecretsService", false); m_walletEnabled = m_cgroup.readEntry("Enabled", true); if (!m_walletEnabled) { qCDebug(KWALLET_API_LOG) << "The wallet service was disabled by the user"; return; } #if HAVE_KSECRETSSERVICE if (m_useKSecretsService) { // NOOP } else { #endif m_wallet_deamon = new org::kde::KWallet(QString::fromLatin1(s_kwalletdServiceName), QStringLiteral("/modules/kwalletd5"), QDBusConnection::sessionBus()); #if HAVE_KSECRETSSERVICE } #endif } KWalletDLauncher::~KWalletDLauncher() { delete m_wallet_deamon; } org::kde::KWallet &KWalletDLauncher::getInterface() { // Q_ASSERT(!m_useKSecretsService); Q_ASSERT(m_wallet_deamon != nullptr); // check if kwalletd is already running QDBusConnectionInterface *bus = QDBusConnection::sessionBus().interface(); if (!bus->isServiceRegistered(QString::fromLatin1(s_kwalletdServiceName))) { // not running! check if it is enabled. if (m_walletEnabled) { // wallet is enabled! try launching it QDBusReply reply = bus->startService(QString::fromLatin1(s_kwalletdServiceName)); if (!reply.isValid()) { qCritical() << "Couldn't start kwalletd: " << reply.error(); } if (!bus->isServiceRegistered(QString::fromLatin1(s_kwalletdServiceName))) { qCDebug(KWALLET_API_LOG) << "The kwalletd service is still not registered"; } else { qCDebug(KWALLET_API_LOG) << "The kwalletd service has been registered"; } } else { qCritical() << "The kwalletd service has been disabled"; } } return *m_wallet_deamon; } } // namespace KWallet #include "moc_kwallet.cpp" diff --git a/src/runtime/kwalletd/ktimeout.cpp b/src/runtime/kwalletd/ktimeout.cpp index cc1e60f..bfdb5fd 100644 --- a/src/runtime/kwalletd/ktimeout.cpp +++ b/src/runtime/kwalletd/ktimeout.cpp @@ -1,80 +1,80 @@ /* This file is part of the KDE libraries Copyright (c) 2003 George Staikos This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ktimeout.h" #include KTimeout::KTimeout(QObject *parent) : QObject(parent) { } KTimeout::~KTimeout() { } void KTimeout::clear() { - foreach (int timerId, _timers) { + for (int timerId : qAsConst(_timers)) { killTimer(timerId); } _timers.clear(); } void KTimeout::removeTimer(int id) { const int timerId = _timers.value(id, 0); if (timerId != 0) { killTimer(timerId); } _timers.remove(id); } void KTimeout::addTimer(int id, int timeout) { if (_timers.contains(id)) { return; } _timers.insert(id, startTimer(timeout)); } void KTimeout::resetTimer(int id, int timeout) { int timerId = _timers.value(id, 0); if (timerId != 0) { killTimer(timerId); _timers.insert(id, startTimer(timeout)); } } void KTimeout::timerEvent(QTimerEvent *ev) { QHash::const_iterator it = _timers.constBegin(); for (; it != _timers.constEnd(); ++it) { if (it.value() == ev->timerId()) { emit timedOut(it.key()); return; } } } diff --git a/src/runtime/kwalletd/kwalletd.cpp b/src/runtime/kwalletd/kwalletd.cpp index a626edb..bac645b 100644 --- a/src/runtime/kwalletd/kwalletd.cpp +++ b/src/runtime/kwalletd/kwalletd.cpp @@ -1,1928 +1,1933 @@ /* This file is part of the KDE libraries Copyright (c) 2002-2004 George Staikos Copyright (c) 2008 Michael Leupold This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kwalletd.h" #include "kwalletd_debug.h" #include "kbetterthankdialog.h" #include "kwalletwizard.h" #ifdef HAVE_GPGMEPP #include "knewwalletdialog.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_GPGMEPP #include #endif #include #include #include #include #include #include #include #include #include "kwalletadaptor.h" class KWalletTransaction { public: explicit KWalletTransaction(QDBusConnection conn) : tType(Unknown) , cancelled(false) , tId(nextTransactionId) , res(-1) , connection(conn) { nextTransactionId++; // make sure the id is never < 0 as that's used for the // error conditions. if (nextTransactionId < 0) { nextTransactionId = 0; } } ~KWalletTransaction() {} enum Type { Unknown, Open, ChangePassword, OpenFail, CloseCancelled }; Type tType; QString appid; qlonglong wId; QString wallet; QString service; bool cancelled; // set true if the client dies before open bool modal; bool isPath; int tId; // transaction id int res; QDBusMessage message; QDBusConnection connection; private: static int nextTransactionId; }; int KWalletTransaction::nextTransactionId = 0; KWalletD::KWalletD() : QObject(nullptr) , _failed(0) , _syncTime(5000) , _curtrans(nullptr) , _useGpg(false) { #ifdef HAVE_GPGMEPP _useGpg = true; #endif srand(time(nullptr)); _showingFailureNotify = false; _closeIdle = false; _idleTime = 0; connect( &_closeTimers, SIGNAL(timedOut(int)), this, SLOT(timedOutClose(int))); connect( &_syncTimers, SIGNAL(timedOut(int)), this, SLOT(timedOutSync(int))); (void)new KWalletAdaptor(this); // register services QDBusConnection::sessionBus().registerService( QStringLiteral("org.kde.kwalletd5")); QDBusConnection::sessionBus().registerObject( QStringLiteral("/modules/kwalletd5"), this); #ifdef Q_WS_X11 screensaver = 0; #endif reconfigure(); // KGlobal::dirs()->addResourceType("kwallet", 0, "share/apps/kwallet"); _dw = new KDirWatch(this); _dw->setObjectName(QStringLiteral("KWallet Directory Watcher")); // _dw->addDir(KGlobal::dirs()->saveLocation("kwallet")); _dw->addDir(KWallet::Backend::getSaveLocation()); _dw->startScan(true); connect(_dw, SIGNAL(dirty(QString)), this, SLOT(emitWalletListDirty())); connect(_dw, &KDirWatch::deleted, this, &KWalletD::emitWalletListDirty); _serviceWatcher.setWatchMode(QDBusServiceWatcher::WatchForOwnerChange); connect(&_serviceWatcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)), this, SLOT(slotServiceOwnerChanged(QString,QString,QString))); } void KWalletD::registerKWalletd4Service() { auto bus = QDBusConnection::sessionBus().interface(); auto reply = bus->registerService(QStringLiteral("org.kde.kwalletd"), QDBusConnectionInterface::QueueService); if (reply.isValid() && (reply.value() == QDBusConnectionInterface::ServiceQueued)) { QDBusInterface _kde_kwalletd4(QStringLiteral("org.kde.kwalletd"), QStringLiteral("/MainApplication"), QStringLiteral("org.kde.KApplication")); if (_kde_kwalletd4.isValid()) { auto qreply = _kde_kwalletd4.call(QStringLiteral("quit")); } } QDBusConnection::sessionBus().registerObject(QStringLiteral("/modules/kwalletd"), this); } KWalletD::~KWalletD() { #ifdef Q_WS_X11 delete screensaver; screensaver = 0; #endif closeAllWallets(); qDeleteAll(_transactions); } #ifdef Q_WS_X11 void KWalletD::connectToScreenSaver() { screensaver = new QDBusInterface("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver"); if (!screensaver->isValid()) { qCDebug(KWALLETD_LOG) << "Service org.freedesktop.ScreenSaver not found. Retrying in 10 seconds..."; // keep attempting every 10 seconds QTimer::singleShot(10000, this, SLOT(connectToScreenSaver())); } else { connect(screensaver, SIGNAL(ActiveChanged(bool)), SLOT(screenSaverChanged(bool))); qCDebug(KWALLETD_LOG) << "connected to screen saver service."; } } #endif int KWalletD::generateHandle() { int rc; // ASSUMPTION: RAND_MAX is fairly large. do { rc = rand(); } while (_wallets.contains(rc) || rc == 0); return rc; } QPair KWalletD::findWallet( const QString& walletName) const { Wallets::const_iterator it = _wallets.constBegin(); const Wallets::const_iterator end = _wallets.constEnd(); for (; it != end; ++it) { if (it.value()->walletName() == walletName) { return qMakePair(it.key(), it.value()); } } return qMakePair(-1, static_cast(nullptr)); } bool KWalletD::_processing = false; void KWalletD::processTransactions() { if (_processing) { return; } _processing = true; // Process remaining transactions while (!_transactions.isEmpty()) { _curtrans = _transactions.takeFirst(); int res; assert(_curtrans->tType != KWalletTransaction::Unknown); switch (_curtrans->tType) { case KWalletTransaction::Open: res = doTransactionOpen(_curtrans->appid, _curtrans->wallet, _curtrans->isPath, _curtrans->wId, _curtrans->modal, _curtrans->service); // multiple requests from the same client // should not produce multiple password // dialogs on a failure if (res < 0) { QList::iterator it; for (it = _transactions.begin(); it != _transactions.end(); ++it) { KWalletTransaction* x = *it; if (_curtrans->appid == x->appid && x->tType == KWalletTransaction::Open && x->wallet == _curtrans->wallet && x->wId == _curtrans->wId) { x->tType = KWalletTransaction::OpenFail; } } } else if (_curtrans->cancelled) { // the wallet opened successfully but the application // opening exited/crashed while the dialog was still shown. KWalletTransaction* _xact = new KWalletTransaction(_curtrans->connection); _xact->tType = KWalletTransaction::CloseCancelled; _xact->appid = _curtrans->appid; _xact->wallet = _curtrans->wallet; _xact->service = _curtrans->service; _transactions.append(_xact); } // emit the AsyncOpened signal as a reply _curtrans->res = res; emit walletAsyncOpened(_curtrans->tId, res); break; case KWalletTransaction::OpenFail: // emit the AsyncOpened signal with an invalid handle _curtrans->res = -1; emit walletAsyncOpened(_curtrans->tId, -1); break; case KWalletTransaction::ChangePassword: doTransactionChangePassword( _curtrans->appid, _curtrans->wallet, _curtrans->wId); break; case KWalletTransaction::CloseCancelled: doTransactionOpenCancelled( _curtrans->appid, _curtrans->wallet, _curtrans->service); break; case KWalletTransaction::Unknown: break; default: break; } // send delayed dbus message reply to the caller if (_curtrans->message.type() != QDBusMessage::InvalidMessage) { if (_curtrans->connection.isConnected()) { QDBusMessage reply = _curtrans->message.createReply(); reply << _curtrans->res; _curtrans->connection.send(reply); } } delete _curtrans; _curtrans = nullptr; } _processing = false; } int KWalletD::openPath( const QString& path, qlonglong wId, const QString& appid) { int tId = openPathAsync(path, wId, appid, false); if (tId < 0) { return tId; } // NOTE the real return value will be sent by the dbusmessage delayed // reply return 0; // wait for the open-transaction to be processed // KWalletOpenLoop loop(this); // return loop.waitForAsyncOpen(tId); } int KWalletD::open(const QString& wallet, qlonglong wId, const QString& appid) { if (!_enabled) { // guard return -1; } if (!QRegExp(QString::fromLatin1("^[\\w\\^\\&\\'\\@\\{\\}\\[\\]\\,\\$\\=\\!\\-\\#\\(\\)\\%\\." "\\+\\_\\s]+$")).exactMatch(wallet)) { return -1; } KWalletTransaction* xact = new KWalletTransaction(connection()); _transactions.append(xact); message().setDelayedReply(true); xact->message = message(); xact->appid = appid; xact->wallet = wallet; xact->wId = wId; xact->modal = true; // mark dialogs as modal, the app has blocking wait xact->tType = KWalletTransaction::Open; xact->isPath = false; QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); // NOTE the real return value will be sent by the dbusmessage delayed // reply return 0; } int KWalletD::openAsync(const QString& wallet, qlonglong wId, const QString& appid, bool handleSession) { if (!_enabled) { // guard return -1; } if (!QRegExp(QString::fromLatin1("^[\\w\\^\\&\\'\\@\\{\\}\\[\\]\\,\\$\\=\\!\\-\\#\\(\\)\\%\\." "\\+\\_\\s]+$")).exactMatch(wallet)) { return -1; } KWalletTransaction* xact = new KWalletTransaction(connection()); _transactions.append(xact); xact->appid = appid; xact->wallet = wallet; xact->wId = wId; xact->modal = true; // mark dialogs as modal, the app has blocking wait xact->tType = KWalletTransaction::Open; xact->isPath = false; if (handleSession) { qCDebug(KWALLETD_LOG) << "openAsync for " << message().service(); _serviceWatcher.setConnection(connection()); _serviceWatcher.addWatchedService(message().service()); xact->service = message().service(); } QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); // opening is in progress. return the transaction number return xact->tId; } int KWalletD::openPathAsync(const QString& path, qlonglong wId, const QString& appid, bool handleSession) { if (!_enabled) { // gaurd return -1; } KWalletTransaction* xact = new KWalletTransaction(connection()); _transactions.append(xact); xact->appid = appid; xact->wallet = path; xact->wId = wId; xact->modal = true; xact->tType = KWalletTransaction::Open; xact->isPath = true; if (handleSession) { qCDebug(KWALLETD_LOG) << "openPathAsync " << message().service(); _serviceWatcher.setConnection(connection()); _serviceWatcher.addWatchedService(message().service()); xact->service = message().service(); } QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); // opening is in progress. return the transaction number return xact->tId; } // Sets up a dialog that will be shown by kwallet. void KWalletD::setupDialog( QWidget* dialog, WId wId, const QString& appid, bool modal) { if (wId != 0) { KWindowSystem::setMainWindow( dialog, wId); // correct, set dialog parent } else { if (appid.isEmpty()) { qWarning() << "Using kwallet without parent window!"; } else { qWarning() << "Application '" << appid << "' using kwallet without parent window!"; } // allow dialog activation even if it interrupts, better than trying // hacks // with keeping the dialog on top or on all desktops // KF5 FIXME what should we use now instead of this: // kapp->updateUserTimestamp(); } if (modal) { KWindowSystem::setState(dialog->winId(), NET::Modal); } else { KWindowSystem::clearState(dialog->winId(), NET::Modal); } activeDialog = dialog; } // If there's a dialog already open and another application tries some // operation that'd lead to // opening a dialog, that application will be blocked by this dialog. A proper // solution would // be to set the second application's window also as a parent for the active // dialog, so that // KWin properly handles focus changes and so on, but there's currently no // support for multiple // dialog parents. In the absence of this support, we use all kinds of bad // hacks to make // sure the user doesn't overlook the active dialog. void KWalletD::checkActiveDialog() { if (!activeDialog) { return; } // KF5 FIXME what should we use now instead of this: // kapp->updateUserTimestamp(); activeDialog->show(); WId window = activeDialog->winId(); KWindowSystem::setState(window, NET::KeepAbove); KWindowSystem::setOnAllDesktops(window, true); KWindowSystem::forceActiveWindow(window); KWindowSystem::raiseWindow(window); } int KWalletD::doTransactionOpen(const QString& appid, const QString& wallet, bool isPath, qlonglong wId, bool modal, const QString& service) { if (_firstUse && !isPath) { // if the user specifies a wallet name, the use it as the default // wallet name if (wallet != KWallet::Wallet::LocalWallet()) { KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Wallet"); cfg.writeEntry("Default Wallet", wallet); } if (wallets().contains(KWallet::Wallet::LocalWallet())) { KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Wallet"); _firstUse = false; cfg.writeEntry("First Use", false); } // else { // // First use wizard // // TODO GPG adjust new smartcard options gathered by // the wizard // QPointer wiz = new KWalletWizard(0); // wiz->setWindowTitle(i18n("KDE Wallet Service")); // setupDialog(wiz, (WId)wId, appid, modal); // int rc = wiz->exec(); // if (rc == QDialog::Accepted && wiz) { // bool useWallet = wiz->field("useWallet").toBool(); // KConfig kwalletrc("kwalletrc"); // KConfigGroup cfg(&kwalletrc, "Wallet"); // cfg.writeEntry("First Use", false); // cfg.writeEntry("Enabled", useWallet); // cfg.writeEntry("Close When Idle", // wiz->field("closeWhenIdle").toBool()); // cfg.writeEntry("Use One Wallet", // !wiz->field("networkWallet").toBool()); // cfg.sync(); // reconfigure(); // // if (!useWallet) { // delete wiz; // return -1; // } // // // Create the wallet // // TODO GPG select the correct wallet type upon // cretion (GPG or blowfish based) // KWallet::Backend *b = new // KWallet::Backend(KWallet::Wallet::LocalWallet()); // #ifdef HAVE_GPGMEPP // if (wiz->field("useBlowfish").toBool()) { // b->setCipherType(KWallet::BACKEND_CIPHER_BLOWFISH); // #endif // QString pass = wiz->field("pass1").toString(); // QByteArray p(pass.toUtf8(), pass.length()); // b->open(p); // p.fill(0); // #ifdef HAVE_GPGMEPP // } else { // assert(wiz->field("useGpg").toBool()); // b->setCipherType(KWallet::BACKEND_CIPHER_GPG); // b->open(wiz->gpgKey()); // } // #endif // b->createFolder(KWallet::Wallet::PasswordFolder()); // b->createFolder(KWallet::Wallet::FormDataFolder()); // b->close(true); // delete b; // delete wiz; // } else { // delete wiz; // return -1; // } // } } int rc = internalOpen(appid, wallet, isPath, WId(wId), modal, service); return rc; } int KWalletD::internalOpen(const QString& appid, const QString& wallet, bool isPath, WId w, bool modal, const QString& service) { bool brandNew = false; QString thisApp; if (appid.isEmpty()) { thisApp = QStringLiteral("KDE System"); } else { thisApp = appid; } if (implicitDeny(wallet, thisApp)) { return -1; } QPair walletInfo = findWallet(wallet); int rc = walletInfo.first; if (rc == -1) { if (_wallets.count() > 20) { qCDebug(KWALLETD_LOG) << "Too many wallets open."; return -1; } KWallet::Backend* b = new KWallet::Backend(wallet, isPath); QString password; bool emptyPass = false; if ((isPath && QFile::exists(wallet)) || (!isPath && KWallet::Backend::exists(wallet))) { // this open attempt will set wallet type from the file header, // even if password is needed int pwless = b->open(QByteArray(), w); #ifdef HAVE_GPGMEPP assert(b->cipherType() != KWallet::BACKEND_CIPHER_UNKNOWN); if (b->cipherType() == KWallet::BACKEND_CIPHER_GPG) { // GPG based wallets do not prompt for password here. Instead, // GPG should already have popped pinentry utility for wallet // decryption if (!b->isOpen()) { // for some reason, GPG operation failed delete b; return -1; } emptyPass = true; } else { #endif if (0 != pwless || !b->isOpen()) { if (pwless == 0) { // release, start anew delete b; b = new KWallet::Backend(wallet, isPath); } KPasswordDialog* kpd = new KPasswordDialog(); if (appid.isEmpty()) { kpd->setPrompt( i18n("KDE has requested to open the wallet " "'%1'. Please enter the password for " "this wallet below.", wallet.toHtmlEscaped())); } else { kpd->setPrompt(i18n( "The application '%1' has requested " "to open the wallet '%2'. Please enter " "the password for this wallet below.", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); } brandNew = false; // don't use KStdGuiItem::open() here which has trailing // ellipsis! // KF5 FIXME what should we use now instead of this: // kpd->setButtonGuiItem(KDialog::Ok,KGuiItem( // i18n( "&Open" ), "wallet-open")); kpd->setWindowTitle(i18n("KDE Wallet Service")); kpd->setPixmap( KIconLoader::global()->loadIcon(QStringLiteral("kwalletmanager"), KIconLoader::Desktop, KIconLoader::SizeHuge)); if (w != KWindowSystem::activeWindow() && w != 0L) { // If the dialog is modal to a minimized window it // might not be visible // (but still blocking the calling application). // Notify the user about // the request to open the wallet. KNotification* notification = new KNotification( QStringLiteral("needsPassword"), kpd, KNotification::Persistent | KNotification::CloseWhenWidgetActivated); QStringList actions; if (appid.isEmpty()) { notification->setText( i18n("An application has requested to open a " "wallet (%1).", wallet.toHtmlEscaped())); actions.append( i18nc("Text of a button for switching to the " "(unnamed) application " "requesting a password", "Switch there")); } else { notification->setText( i18n("%1 has requested to open a " "wallet (%2).", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); actions.append( i18nc("Text of a button for switching to the " "application requesting " "a password", "Switch to %1", appid.toHtmlEscaped())); } notification->setActions(actions); connect(notification, SIGNAL(action1Activated()), this, SLOT(activatePasswordDialog())); notification->sendEvent(); } while (!b->isOpen()) { setupDialog(kpd, w, appid, modal); if (kpd->exec() == QDialog::Accepted) { password = kpd->password(); int rc = b->open(password.toUtf8()); if (!b->isOpen()) { const auto errorStr = KWallet::Backend::openRCToString(rc); qCWarning(KWALLETD_LOG) << "Failed to open wallet" << wallet << errorStr; kpd->setPrompt(i18n( "Error opening the wallet " "'%1'. Please try again.
(Error code %2: %3)
", wallet.toHtmlEscaped(), rc, errorStr)); kpd->setPassword(QLatin1String("")); } } else { break; } } delete kpd; } else { emptyPass = true; } #ifdef HAVE_GPGMEPP } #endif } else { brandNew = true; #ifdef HAVE_GPGMEPP // prompt the user for the new wallet format here KWallet::BackendCipherType newWalletType = KWallet::BACKEND_CIPHER_UNKNOWN; std::shared_ptr newWalletDlg( new KWallet::KNewWalletDialog( appid, wallet, QWidget::find(w))); GpgME::Key gpgKey; setupDialog(newWalletDlg.get(), (WId)w, appid, true); if (newWalletDlg->exec() == QDialog::Accepted) { newWalletType = newWalletDlg->isBlowfish() ? KWallet::BACKEND_CIPHER_BLOWFISH : KWallet::BACKEND_CIPHER_GPG; gpgKey = newWalletDlg->gpgKey(); } else { // user cancelled the dialog box delete b; return -1; } if (newWalletType == KWallet::BACKEND_CIPHER_GPG) { b->setCipherType(newWalletType); b->open(gpgKey); } else if (newWalletType == KWallet::BACKEND_CIPHER_BLOWFISH) { #endif // HAVE_GPGMEPP b->setCipherType(KWallet::BACKEND_CIPHER_BLOWFISH); KNewPasswordDialog* kpd = new KNewPasswordDialog(); KColorScheme colorScheme(QPalette::Active, KColorScheme::View); kpd->setBackgroundWarningColor(colorScheme.background(KColorScheme::NegativeBackground).color()); if (wallet == KWallet::Wallet::LocalWallet() || wallet == KWallet::Wallet::NetworkWallet()) { // Auto create these wallets. if (appid.isEmpty()) { kpd->setPrompt( i18n("KDE has requested to open the wallet. This " "is used to store sensitive data in a " "secure fashion. Please enter a password to " "use with this wallet or click cancel to " "deny the application's request.")); } else { kpd->setPrompt( i18n("The application '%1' has " "requested to open the KDE wallet. This is " "used to store sensitive data in a secure " "fashion. Please enter a password to use " "with this wallet or click cancel to deny " "the application's request.", appid.toHtmlEscaped())); } } else { if (appid.length() == 0) { kpd->setPrompt( i18n("KDE has requested to create a new " "wallet named '%1'. Please choose a " "password for this wallet, or cancel to " "deny the application's request.", wallet.toHtmlEscaped())); } else { kpd->setPrompt(i18n( "The application '%1' has requested " "to create a new wallet named '%2'. " "Please choose a password for this wallet, or " "cancel to deny the application's request.", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); } } kpd->setWindowTitle(i18n("KDE Wallet Service")); // KF5 FIXME what should we use now instead of this: // kpd->setButtonGuiItem(KDialog::Ok,KGuiItem(i18n("C&reate"),"document-new")); kpd->setPixmap( KIconLoader::global()->loadIcon(QStringLiteral("kwalletmanager"), KIconLoader::Desktop, KIconLoader::SizeHuge)); while (!b->isOpen()) { setupDialog(kpd, w, appid, modal); if (kpd->exec() == QDialog::Accepted) { password = kpd->password(); int rc = b->open(password.toUtf8()); if (!b->isOpen()) { kpd->setPrompt( i18n("Error opening the wallet " "'%1'. Please try again.
(Error code %2: %3)
", wallet.toHtmlEscaped(), rc, KWallet::Backend::openRCToString(rc))); } } else { break; } } delete kpd; #ifdef HAVE_GPGMEPP } #endif } if ((b->cipherType() == KWallet::BACKEND_CIPHER_BLOWFISH) && !emptyPass && (password.isNull() || !b->isOpen())) { delete b; return -1; } if (emptyPass && !isAuthorizedApp(appid, wallet, w)) { delete b; return -1; } _wallets.insert(rc = generateHandle(), b); _sessions.addSession(appid, service, rc); _syncTimers.addTimer(rc, _syncTime); if (brandNew) { createFolder(rc, KWallet::Wallet::PasswordFolder(), appid); createFolder(rc, KWallet::Wallet::FormDataFolder(), appid); } b->ref(); if (_closeIdle) { _closeTimers.addTimer(rc, _idleTime); } if (brandNew) { emit walletCreated(wallet); } emit walletOpened(wallet); if (_wallets.count() == 1 && _launchManager) { KToolInvocation::startServiceByDesktopName( QStringLiteral("kwalletmanager-kwalletd")); } } else { // prematurely add a reference so that the wallet does not close while // the // authorization dialog is being shown. walletInfo.second->ref(); bool isAuthorized = _sessions.hasSession(appid, rc) || isAuthorizedApp(appid, wallet, w); // as the wallet might have been forcefully closed, find it again to // make sure it's // still available (isAuthorizedApp might show a dialog). walletInfo = findWallet(wallet); if (!isAuthorized) { if (walletInfo.first != -1) { walletInfo.second->deref(); // check if the wallet should be closed now. internalClose(walletInfo.second, walletInfo.first, false); } return -1; } else { if (walletInfo.first != -1) { _sessions.addSession(appid, service, rc); } else { // wallet was forcefully closed. return -1; } } } return rc; } bool KWalletD::isAuthorizedApp( const QString& appid, const QString& wallet, WId w) { if (!_openPrompt) { return true; } int response = 0; QString thisApp; if (appid.isEmpty()) { thisApp = QStringLiteral("KDE System"); } else { thisApp = appid; } if (!implicitAllow(wallet, thisApp)) { KConfigGroup cfg = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Allow"); if (!cfg.isEntryImmutable(wallet)) { KBetterThanKDialog* dialog = new KBetterThanKDialog; dialog->setWindowTitle(i18n("KDE Wallet Service")); if (appid.isEmpty()) { dialog->setLabel(i18n("KDE has requested access to the " "open wallet '%1'.", wallet.toHtmlEscaped())); } else { dialog->setLabel( i18n("The application '%1' has requested " "access to the open wallet '%2'.", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); } setupDialog(dialog, w, appid, false); response = dialog->exec(); delete dialog; } } if (response == 0 || response == 1) { if (response == 1) { KConfigGroup cfg = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Allow"); QStringList apps = cfg.readEntry(wallet, QStringList()); if (!apps.contains(thisApp)) { if (cfg.isEntryImmutable(wallet)) { return false; } apps += thisApp; _implicitAllowMap[wallet] += thisApp; cfg.writeEntry(wallet, apps); cfg.sync(); } } } else if (response == 3) { KConfigGroup cfg = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Deny"); QStringList apps = cfg.readEntry(wallet, QStringList()); if (!apps.contains(thisApp)) { apps += thisApp; _implicitDenyMap[wallet] += thisApp; cfg.writeEntry(wallet, apps); cfg.sync(); } return false; } else { return false; } return true; } int KWalletD::deleteWallet(const QString& wallet) { int result = -1; QString path = KWallet::Backend::getSaveLocation() + "/" + wallet + ".kwl"; QString pathSalt = KWallet::Backend::getSaveLocation() + "/" + wallet + ".salt"; if (QFile::exists(path)) { const QPair walletInfo = findWallet(wallet); internalClose(walletInfo.second, walletInfo.first, true); QFile::remove(path); emit walletDeleted(wallet); // also delete access control entries KConfigGroup cfgAllow = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Allow"); cfgAllow.deleteEntry(wallet); KConfigGroup cfgDeny = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Deny"); cfgDeny.deleteEntry(wallet); if (QFile::exists(pathSalt)) { QFile::remove(pathSalt); } result = 0; } return result; } void KWalletD::changePassword( const QString& wallet, qlonglong wId, const QString& appid) { KWalletTransaction* xact = new KWalletTransaction(connection()); message().setDelayedReply(true); xact->message = message(); // TODO GPG this shouldn't be allowed on a GPG managed wallet; a warning // should be displayed about this xact->appid = appid; xact->wallet = wallet; xact->wId = wId; xact->modal = false; xact->tType = KWalletTransaction::ChangePassword; _transactions.append(xact); QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); checkActiveDialog(); } void KWalletD::initiateSync(int handle) { // add a timer and reset it right away _syncTimers.addTimer(handle, _syncTime); _syncTimers.resetTimer(handle, _syncTime); } void KWalletD::doTransactionChangePassword( const QString& appid, const QString& wallet, qlonglong wId) { const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* w = walletInfo.second; bool reclose = false; if (!w) { handle = doTransactionOpen(appid, wallet, false, wId, false, QLatin1String("")); if (-1 == handle) { KMessageBox::sorryWId((WId)wId, i18n("Unable to open wallet. The wallet must be opened in " "order to change the password."), i18n("KDE Wallet Service")); return; } w = _wallets.value(handle); reclose = true; } assert(w); #ifdef HAVE_GPGMEPP if (w->cipherType() == KWallet::BACKEND_CIPHER_GPG) { QString keyID = w->gpgKey().shortKeyID(); assert(!keyID.isNull()); KMessageBox::errorWId( (WId)wId, i18n("The %1 wallet is encrypted using GPG " "key %2. Please use GPG tools (such " "as kleopatra) to change the passphrase " "associated to that key.", wallet.toHtmlEscaped(), keyID)); } else { #endif QPointer kpd = new KNewPasswordDialog(); kpd->setPrompt(i18n("Please choose a new password for the wallet " "'%1'.", wallet.toHtmlEscaped())); kpd->setWindowTitle(i18n("KDE Wallet Service")); kpd->setAllowEmptyPasswords(true); KColorScheme colorScheme(QPalette::Active, KColorScheme::View); kpd->setBackgroundWarningColor(colorScheme.background(KColorScheme::NegativeBackground).color()); setupDialog(kpd, (WId)wId, appid, false); if (kpd->exec() == QDialog::Accepted && kpd) { QString p = kpd->password(); if (!p.isNull()) { w->setPassword(p.toUtf8()); int rc = w->close(true); if (rc < 0) { KMessageBox::sorryWId((WId)wId, i18n("Error re-encrypting the wallet. Password was " "not changed."), i18n("KDE Wallet Service")); reclose = true; } else { rc = w->open(p.toUtf8()); if (rc < 0) { KMessageBox::sorryWId((WId)wId, i18n("Error reopening the wallet. Data may be " "lost."), i18n("KDE Wallet Service")); reclose = true; } } } } delete kpd; #ifdef HAVE_GPGMEPP } #endif if (reclose) { internalClose(w, handle, true); } } int KWalletD::close(const QString& wallet, bool force) { const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* w = walletInfo.second; return internalClose(w, handle, force); } int KWalletD::internalClose(KWallet::Backend* const w, const int handle, const bool force, const bool saveBeforeClose) { if (w) { const QString& wallet = w->walletName(); if ((w->refCount() == 0 && !_leaveOpen) || force) { // this is only a safety measure. sessions should be gone already. _sessions.removeAllSessions(handle); if (_closeIdle) { _closeTimers.removeTimer(handle); } _syncTimers.removeTimer(handle); _wallets.remove(handle); w->close(saveBeforeClose); doCloseSignals(handle, wallet); delete w; return 0; } return 1; } return -1; } int KWalletD::close(int handle, bool force, const QString& appid) { KWallet::Backend* w = _wallets.value(handle); if (w) { if (_sessions.hasSession(appid, handle)) { // remove one handle for the application bool removed = _sessions.removeSession(appid, message().service(), handle); // alternatively try sessionless if (removed || _sessions.removeSession(appid, QLatin1String(""), handle)) { w->deref(); } return internalClose(w, handle, force); } return 1; // not closed, handle unknown } return -1; // not open to begin with, or other error } bool KWalletD::isOpen(const QString& wallet) { const QPair walletInfo = findWallet(wallet); return walletInfo.second != nullptr; } bool KWalletD::isOpen(int handle) { if (handle == 0) { return false; } KWallet::Backend* rc = _wallets.value(handle); if (rc == nullptr && ++_failed > 5) { _failed = 0; QTimer::singleShot(0, this, SLOT(notifyFailures())); } else if (rc != nullptr) { _failed = 0; } return rc != nullptr; } QStringList KWalletD::wallets() const { QString path = KWallet::Backend::getSaveLocation(); QDir dir(path, QStringLiteral("*.kwl")); QStringList rc; dir.setFilter(QDir::Files | QDir::Hidden); - foreach (const QFileInfo& fi, dir.entryInfoList()) { + const auto list = dir.entryInfoList(); + for (const QFileInfo& fi : list) { QString fn = fi.fileName(); if (fn.endsWith(QLatin1String(".kwl"))) { fn.truncate(fn.length() - 4); } rc += fn; } return rc; } void KWalletD::sync(int handle, const QString& appid) { KWallet::Backend* b; // get the wallet and check if we have a password for it (safety measure) if ((b = getWallet(appid, handle))) { QString wallet = b->walletName(); b->sync(0); } } void KWalletD::timedOutSync(int handle) { _syncTimers.removeTimer(handle); if (_wallets.contains(handle) && _wallets[handle]) { _wallets[handle]->sync(0); } else { qDebug("wallet not found for sync!"); } } void KWalletD::doTransactionOpenCancelled( const QString& appid, const QString& wallet, const QString& service) { // there will only be one session left to remove - all others // have already been removed in slotServiceOwnerChanged and all // transactions for opening new sessions have been deleted. if (!_sessions.hasSession(appid)) { return; } const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* b = walletInfo.second; if (handle != -1 && b) { b->deref(); internalClose(b, handle, false); } // close the session in case the wallet hasn't been closed yet _sessions.removeSession(appid, service, handle); } QStringList KWalletD::folderList(int handle, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { return b->folderList(); } return QStringList(); } bool KWalletD::hasFolder(int handle, const QString& f, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { return b->hasFolder(f); } return false; } bool KWalletD::removeFolder( int handle, const QString& f, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { bool rc = b->removeFolder(f); initiateSync(handle); emit folderListUpdated(b->walletName()); return rc; } return false; } bool KWalletD::createFolder( int handle, const QString& f, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { bool rc = b->createFolder(f); initiateSync(handle); emit folderListUpdated(b->walletName()); return rc; } return false; } QByteArray KWalletD::readMap(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry* e = b->readEntry(key); if (e && e->type() == KWallet::Wallet::Map) { return e->map(); } } return QByteArray(); } QVariantMap KWalletD::readMapList(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); QVariantMap rc; - foreach (KWallet::Entry* entry, b->readEntryList(key)) { + const auto lst = b->readEntryList(key); + for (KWallet::Entry* entry : lst) { if (entry->type() == KWallet::Wallet::Map) { rc.insert(entry->key(), entry->map()); } } return rc; } return QVariantMap(); } QByteArray KWalletD::readEntry(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry* e = b->readEntry(key); if (e) { return e->value(); } } return QByteArray(); } QVariantMap KWalletD::readEntryList(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); QVariantMap rc; - foreach (KWallet::Entry* entry, b->readEntryList(key)) { + const auto lst = b->readEntryList(key); + for (KWallet::Entry* entry : lst) { rc.insert(entry->key(), entry->value()); } return rc; } return QVariantMap(); } QStringList KWalletD::entryList( int handle, const QString& folder, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); return b->entryList(); } return QStringList(); } QString KWalletD::readPassword(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry* e = b->readEntry(key); if (e && e->type() == KWallet::Wallet::Password) { return e->password(); } } return QString(); } QVariantMap KWalletD::readPasswordList(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); QVariantMap rc; - foreach (KWallet::Entry* entry, b->readEntryList(key)) { + const auto lst = b->readEntryList(key); + for (KWallet::Entry* entry : lst) { if (entry->type() == KWallet::Wallet::Password) { rc.insert(entry->key(), entry->password()); } } return rc; } return QVariantMap(); } int KWalletD::writeMap(int handle, const QString& folder, const QString& key, const QByteArray& value, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::Map); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::writeEntry(int handle, const QString& folder, const QString& key, const QByteArray& value, int entryType, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::EntryType(entryType)); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::writeEntry(int handle, const QString& folder, const QString& key, const QByteArray& value, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::Stream); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::writePassword(int handle, const QString& folder, const QString& key, const QString& value, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::Password); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::entryType(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { if (!b->hasFolder(folder)) { return KWallet::Wallet::Unknown; } b->setFolder(folder); if (b->hasEntry(key)) { return b->readEntry(key)->type(); } } return KWallet::Wallet::Unknown; } bool KWalletD::hasEntry(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { if (!b->hasFolder(folder)) { return false; } b->setFolder(folder); return b->hasEntry(key); } return false; } int KWalletD::removeEntry(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { if (!b->hasFolder(folder)) { return 0; } b->setFolder(folder); bool rc = b->removeEntry(key); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return rc ? 0 : -3; } return -1; } void KWalletD::slotServiceOwnerChanged( const QString& name, const QString& oldOwner, const QString& newOwner) { Q_UNUSED(name); qCDebug(KWALLETD_LOG) << "slotServiceOwnerChanged " << name << ", " << oldOwner << ", " << newOwner; if (!newOwner.isEmpty()) { return; // no application exit, don't care. } // as we don't have the application id we have to cycle // all sessions. As an application can basically open wallets // with several appids, we can't stop if we found one. QString service(oldOwner); - QList sessremove(_sessions.findSessions(service)); + const QList sessremove(_sessions.findSessions(service)); KWallet::Backend* b = nullptr; // check all sessions for wallets to close - Q_FOREACH (const KWalletAppHandlePair& s, sessremove) { + for (const KWalletAppHandlePair& s : sessremove) { b = getWallet(s.first, s.second); if (b) { b->deref(); internalClose(b, s.second, false); } } // remove all the sessions in case they aren't gone yet - Q_FOREACH (const KWalletAppHandlePair& s, sessremove) { + for (const KWalletAppHandlePair& s : sessremove) { _sessions.removeSession(s.first, service, s.second); } // cancel all open-transactions still running for the service QList::iterator tit; for (tit = _transactions.begin(); tit != _transactions.end(); ++tit) { if ((*tit)->tType == KWalletTransaction::Open && (*tit)->service == oldOwner) { delete (*tit); *tit = nullptr; } } _transactions.removeAll(nullptr); // if there's currently an open-transaction being handled, // mark it as cancelled. if (_curtrans && _curtrans->tType == KWalletTransaction::Open && _curtrans->service == oldOwner) { qCDebug(KWALLETD_LOG) << "Cancelling current transaction!"; _curtrans->cancelled = true; } _serviceWatcher.removeWatchedService(oldOwner); } KWallet::Backend* KWalletD::getWallet(const QString& appid, int handle) { if (handle == 0) { return nullptr; } KWallet::Backend* w = _wallets.value(handle); if (w) { // the handle is valid if (_sessions.hasSession(appid, handle)) { // the app owns this handle _failed = 0; if (_closeIdle) { _closeTimers.resetTimer(handle, _idleTime); } return w; } } if (++_failed > 5) { _failed = 0; QTimer::singleShot(0, this, SLOT(notifyFailures())); } return nullptr; } void KWalletD::notifyFailures() { if (!_showingFailureNotify) { _showingFailureNotify = true; KMessageBox::information(nullptr, i18n("There have been repeated failed attempts to gain access to " "a wallet. An application may be misbehaving."), i18n("KDE Wallet Service")); _showingFailureNotify = false; } } void KWalletD::doCloseSignals(int handle, const QString& wallet) { emit walletClosed(handle); emit walletClosed(wallet); if (_wallets.isEmpty()) { emit allWalletsClosed(); } } int KWalletD::renameEntry(int handle, const QString& folder, const QString& oldName, const QString& newName, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); int rc = b->renameEntry(oldName, newName); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return rc; } return -1; } QStringList KWalletD::users(const QString& wallet) const { const QPair walletInfo = findWallet(wallet); return _sessions.getApplications(walletInfo.first); } bool KWalletD::disconnectApplication( const QString& wallet, const QString& application) { const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* backend = walletInfo.second; if (handle != -1 && _sessions.hasSession(application, handle)) { int removed = _sessions.removeAllSessions(application, handle); for (int i = 0; i < removed; ++i) { backend->deref(); } internalClose(backend, handle, false); emit applicationDisconnected(wallet, application); return true; } return false; } void KWalletD::emitFolderUpdated(const QString& wallet, const QString& folder) { emit folderUpdated(wallet, folder); } void KWalletD::emitWalletListDirty() { const QStringList walletsInDisk = wallets(); - foreach (auto i, _wallets.values()) { + const auto lst = _wallets.values(); + for (auto i : lst) { if (!walletsInDisk.contains(i->walletName())) { internalClose(i, _wallets.key(i), true, false); } } emit walletListDirty(); } void KWalletD::reconfigure() { KConfig cfg(QStringLiteral("kwalletrc")); KConfigGroup walletGroup(&cfg, "Wallet"); _firstUse = walletGroup.readEntry("First Use", true); _enabled = walletGroup.readEntry("Enabled", true); _launchManager = walletGroup.readEntry("Launch Manager", false); _leaveOpen = walletGroup.readEntry("Leave Open", true); bool idleSave = _closeIdle; _closeIdle = walletGroup.readEntry("Close When Idle", false); _openPrompt = walletGroup.readEntry("Prompt on Open", false); int timeSave = _idleTime; // in minutes! _idleTime = walletGroup.readEntry("Idle Timeout", 10) * 60 * 1000; #ifdef Q_WS_X11 if (walletGroup.readEntry("Close on Screensaver", false)) { // BUG 254273 : if kwalletd starts before the screen saver, then the // connection fails and kwalletd never receives it's notifications // To fix this, we use a timer and perform periodic connection // attempts until connection succeeds QTimer::singleShot(0, this, SLOT(connectToScreenSaver())); } else { if (screensaver && screensaver->isValid()) { screensaver->disconnect(SIGNAL(ActiveChanged(bool)), this, SLOT(screenSaverChanged(bool))); delete screensaver; screensaver = 0; } } #endif // Handle idle changes if (_closeIdle) { if (_idleTime != timeSave) { // Timer length changed Wallets::const_iterator it = _wallets.constBegin(); const Wallets::const_iterator end = _wallets.constEnd(); for (; it != end; ++it) { _closeTimers.resetTimer(it.key(), _idleTime); } } if (!idleSave) { // add timers for all the wallets Wallets::const_iterator it = _wallets.constBegin(); const Wallets::const_iterator end = _wallets.constEnd(); for (; it != end; ++it) { _closeTimers.addTimer(it.key(), _idleTime); } } } else { _closeTimers.clear(); } // Update the implicit allow stuff _implicitAllowMap.clear(); const KConfigGroup autoAllowGroup(&cfg, "Auto Allow"); QStringList entries = autoAllowGroup.entryMap().keys(); for (QStringList::const_iterator i = entries.constBegin(); i != entries.constEnd(); ++i) { _implicitAllowMap[*i] = autoAllowGroup.readEntry(*i, QStringList()); } // Update the implicit allow stuff _implicitDenyMap.clear(); const KConfigGroup autoDenyGroup(&cfg, "Auto Deny"); entries = autoDenyGroup.entryMap().keys(); for (QStringList::const_iterator i = entries.constBegin(); i != entries.constEnd(); ++i) { _implicitDenyMap[*i] = autoDenyGroup.readEntry(*i, QStringList()); } // Update if wallet was enabled/disabled if (!_enabled) { // close all wallets while (!_wallets.isEmpty()) { Wallets::const_iterator it = _wallets.constBegin(); internalClose(it.value(), it.key(), true); } QApplication::exit(0); } } bool KWalletD::isEnabled() const { return _enabled; } bool KWalletD::folderDoesNotExist( const QString& wallet, const QString& folder) { if (!wallets().contains(wallet)) { return true; } const QPair walletInfo = findWallet(wallet); if (walletInfo.second) { return walletInfo.second->folderDoesNotExist(folder); } KWallet::Backend* b = new KWallet::Backend(wallet); b->open(QByteArray()); bool rc = b->folderDoesNotExist(folder); delete b; return rc; } bool KWalletD::keyDoesNotExist( const QString& wallet, const QString& folder, const QString& key) { if (!wallets().contains(wallet)) { return true; } const QPair walletInfo = findWallet(wallet); if (walletInfo.second) { return walletInfo.second->entryDoesNotExist(folder, key); } KWallet::Backend* b = new KWallet::Backend(wallet); b->open(QByteArray()); bool rc = b->entryDoesNotExist(folder, key); delete b; return rc; } bool KWalletD::implicitAllow(const QString& wallet, const QString& app) { return _implicitAllowMap[wallet].contains(app); } bool KWalletD::implicitDeny(const QString& wallet, const QString& app) { return _implicitDenyMap[wallet].contains(app); } void KWalletD::timedOutClose(int id) { KWallet::Backend* w = _wallets.value(id); if (w) { internalClose(w, id, true); } } void KWalletD::closeAllWallets() { Wallets walletsCopy = _wallets; Wallets::const_iterator it = walletsCopy.constBegin(); const Wallets::const_iterator end = walletsCopy.constEnd(); for (; it != end; ++it) { internalClose(it.value(), it.key(), true); } walletsCopy.clear(); // All of this should be basically noop. Let's just be safe. _wallets.clear(); } QString KWalletD::networkWallet() { return KWallet::Wallet::NetworkWallet(); } QString KWalletD::localWallet() { return KWallet::Wallet::LocalWallet(); } void KWalletD::screenSaverChanged(bool s) { if (s) { closeAllWallets(); } } void KWalletD::activatePasswordDialog() { checkActiveDialog(); } int KWalletD::pamOpen( const QString& wallet, const QByteArray& passwordHash, int sessionTimeout) { if (_processing) { return -1; } if (!QRegExp(QString::fromLatin1("^[\\w\\^\\&\\'\\@\\{\\}\\[\\]\\,\\$\\=\\!\\-\\#\\(\\)\\%\\." "\\+\\_\\s]+$")).exactMatch(wallet)) { return -1; } // check if the wallet is already open QPair walletInfo = findWallet(wallet); int rc = walletInfo.first; if (rc != -1) { return rc; // Wallet already opened, return handle } if (_wallets.count() > 20) { return -1; } KWallet::Backend* b = nullptr; // If the wallet we want to open does not exists. create it and set pam // hash if (!wallets().contains(wallet)) { b = new KWallet::Backend(wallet); b->setCipherType(KWallet::BACKEND_CIPHER_BLOWFISH); } else { b = new KWallet::Backend(wallet); } int openrc = b->openPreHashed(passwordHash); if (openrc != 0 || !b->isOpen()) { delete b; return openrc; } // opening the wallet was successful int handle = generateHandle(); _wallets.insert(handle, b); _syncTimers.addTimer(handle, _syncTime); // don't reference the wallet or add a session so it // can be reclosed easily. if (sessionTimeout > 0) { _closeTimers.addTimer(handle, sessionTimeout); } else if (_closeIdle) { _closeTimers.addTimer(handle, _idleTime); } emit walletOpened(wallet); if (_wallets.count() == 1 && _launchManager) { KToolInvocation::startServiceByDesktopName(QStringLiteral("kwalletmanager-kwalletd")); } return handle; } // vim: tw=220:ts=4 diff --git a/src/runtime/kwalletd/kwalletsessionstore.cpp b/src/runtime/kwalletd/kwalletsessionstore.cpp index 6755892..af4de62 100644 --- a/src/runtime/kwalletd/kwalletsessionstore.cpp +++ b/src/runtime/kwalletd/kwalletsessionstore.cpp @@ -1,173 +1,175 @@ /* This file is part of the KDE Wallet Daemon Copyright (c) 2008 Michael Leupold This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kwalletsessionstore.h" class KWalletSessionStore::Session { public: QString m_service; // client dbus service (or empty) int m_handle; // backend handle }; KWalletSessionStore::KWalletSessionStore() { } KWalletSessionStore::~KWalletSessionStore() { - Q_FOREACH (const QList &l, m_sessions) { + for (const QList &l : qAsConst(m_sessions)) { qDeleteAll(l); } } void KWalletSessionStore::addSession(const QString &appid, const QString &service, int handle) { Session *sess = new Session(); sess->m_service = service; sess->m_handle = handle; m_sessions[appid].append(sess); } bool KWalletSessionStore::hasSession(const QString &appid, int handle) const { if (!m_sessions.contains(appid)) { return false; } else if (handle == -1) { return true; } QList::const_iterator it; QList::const_iterator end = m_sessions[appid].constEnd(); for (it = m_sessions[appid].constBegin(); it != end; ++it) { Q_ASSERT(*it); if ((*it)->m_handle == handle) { return true; } } return false; } QList KWalletSessionStore::findSessions(const QString &service) const { QList rc; - QList sessionKeys(m_sessions.keys()); - Q_FOREACH (const QString &appid, sessionKeys) { - Q_FOREACH (const Session *sess, m_sessions[appid]) { + const QList sessionKeys(m_sessions.keys()); + for (const QString &appid : sessionKeys) { + const auto lst = m_sessions[appid]; + for (const Session *sess : lst) { Q_ASSERT(sess); if (sess->m_service == service) { rc.append(qMakePair(appid, sess->m_handle)); } } } return rc; } bool KWalletSessionStore::removeSession(const QString &appid, const QString &service, int handle) { if (!m_sessions.contains(appid)) { return false; } QList::const_iterator it; QList::const_iterator end = m_sessions[appid].constEnd(); for (it = m_sessions[appid].constBegin(); it != end; ++it) { Q_ASSERT(*it); if ((*it)->m_service == service && (*it)->m_handle == handle) { Session *sess = *it; m_sessions[appid].removeAll(sess); delete sess; if (m_sessions[appid].isEmpty()) { m_sessions.remove(appid); } return true; } } return false; } int KWalletSessionStore::removeAllSessions(const QString &appid, int handle) { if (!m_sessions.contains(appid)) { return false; } QList::iterator it; QList::iterator end = m_sessions[appid].end(); for (it = m_sessions[appid].begin(); it != end; ++it) { Q_ASSERT(*it); if ((*it)->m_handle == handle) { delete *it; *it = nullptr; } } int removed = m_sessions[appid].removeAll(nullptr); if (m_sessions[appid].isEmpty()) { m_sessions.remove(appid); } return removed; } int KWalletSessionStore::removeAllSessions(int handle) { QList appremove; int numrem = 0; - QList sessionKeys(m_sessions.keys()); - Q_FOREACH (const QString &appid, sessionKeys) { + const QList sessionKeys(m_sessions.keys()); + for (const QString &appid : sessionKeys) { QList::iterator it; QList::iterator end = m_sessions[appid].end(); for (it = m_sessions[appid].begin(); it != end; ++it) { Q_ASSERT(*it); if ((*it)->m_handle == handle) { delete *it; *it = nullptr; numrem++; } } // remove all zeroed sessions m_sessions[appid].removeAll(nullptr); if (m_sessions[appid].isEmpty()) { appremove.append(appid); } } // now remove all applications without sessions - Q_FOREACH (const QString &appid, appremove) { + for (const QString &appid : qAsConst(appremove)) { m_sessions.remove(appid); } return numrem; } QStringList KWalletSessionStore::getApplications(int handle) const { QStringList rc; - Q_FOREACH (const QString &appid, m_sessions.uniqueKeys()) { + const auto lst = m_sessions.uniqueKeys(); + for (const QString &appid : lst) { if (hasSession(appid, handle)) { rc.append(appid); } } return rc; } diff --git a/src/runtime/kwalletd/migrationagent.cpp b/src/runtime/kwalletd/migrationagent.cpp index 44f6376..8ad3cf8 100644 --- a/src/runtime/kwalletd/migrationagent.cpp +++ b/src/runtime/kwalletd/migrationagent.cpp @@ -1,265 +1,265 @@ /* This file is part of the KDE Frameworks Copyright (c) 2014 Valentin Rusu This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "migrationagent.h" #include "kwalletd_debug.h" #include "migrationwizard.h" #include "kwalletd.h" #include #include #include #include #include #include #define SERVICE_KWALLETD4 "org.kde.kwalletd" #define ENTRY_ALREADY_MIGRATED "alreadyMigrated" #define ENTRY_SHOW_MIGRATION_WIZARD "showMigrationWizard" MigrationAgent::MigrationAgent(KWalletD* kd, const char *hash) : _kf5_daemon(kd) , _kde4_daemon(nullptr) , _pam_hash(hash) { connect(this, &MigrationAgent::migrationFinished, _kf5_daemon, &KWalletD::registerKWalletd4Service); if (isAlreadyMigrated()) { qCDebug(KWALLETD_LOG) << "old wallets were already migrated"; emit migrationFinished(); } else { QTimer::singleShot(100, this, SLOT(migrateWallets())); } } void MigrationAgent::migrateWallets() { // the migration is done in several steps : // is the setting "alreadyMigrated" present and true ? // if yes, then stop here // if not, then is kwalletd present (the daemon from KDE4) ? // if not, then stop here // if yes, then start the migration wizard // if the migration wizard returns without error // create "alreadyMigrated=true" setting qCDebug(KWALLETD_LOG) << "Migration agent starting..."; if (connectOldDaemon()) { if (!isEmptyOldWallet()) { if (isMigrationWizardOk()) { setAlreadyMigrated(); emit migrationFinished(); } else { qCDebug(KWALLETD_LOG) << "Migration wizard returned an error or has been canceled. The migration agent will resume upon next daemon start"; } } else { qCDebug(KWALLETD_LOG) << "Old wallet is empty. No need to migrate."; setAlreadyMigrated(); emit migrationFinished(); } } else { qCDebug(KWALLETD_LOG) << "KDE4 kwalletd not present, stopping migration agent"; emit migrationFinished(); } qCDebug(KWALLETD_LOG) << "Migration agent stop."; } bool MigrationAgent::isAlreadyMigrated() { KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Migration"); return cfg.readEntry(ENTRY_ALREADY_MIGRATED, false); } void MigrationAgent::setAlreadyMigrated() { KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Migration"); cfg.writeEntry(ENTRY_ALREADY_MIGRATED, true); } bool MigrationAgent::connectOldDaemon() { // the old daemon may not have been started, so attempt start it // NOTE we provide a "fake" org.kde.kwalletd.service file - see the project structure // however, this thing is a HACK as we cannot tell here, in KF5, user's KDE4 install prefix // the provided .service file assumes /usr/bin QDBusConnectionInterface *bus = QDBusConnection::sessionBus().interface(); if (!bus->isServiceRegistered(QStringLiteral(SERVICE_KWALLETD4))) { qCDebug(KWALLETD_LOG) << "kwalletd not started. Attempting start..."; QDBusReply reply = bus->startService(SERVICE_KWALLETD4); if (!reply.isValid()) { qCDebug(KWALLETD_LOG) << "Couldn't start kwalletd: " << reply.error(); return false; } if (!bus->isServiceRegistered(QStringLiteral(SERVICE_KWALLETD4))) { qCDebug(KWALLETD_LOG) << "The kwalletd service is still not registered after start attemtp. Aborting migration"; return false; } else { qCDebug(KWALLETD_LOG) << "The kwalletd service has been registered"; } } _kde4_daemon = new org::kde::KWallet(QStringLiteral(SERVICE_KWALLETD4), QStringLiteral("/modules/kwalletd"), QDBusConnection::sessionBus()); return _kde4_daemon->isValid(); } bool MigrationAgent::isMigrationWizardOk() { bool ok = false; // The migration wizard would no longer been shown by default. // see BUG 351056 // NOTE if user wants to show the migration wizard, then he should add the // following setting to the kwalletrc: // [Migration] // showMigrationWizard=true KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Migration"); bool showMigrationWizard = cfg.readEntry(ENTRY_SHOW_MIGRATION_WIZARD, false); if (showMigrationWizard) { MigrationWizard *wizard = new MigrationWizard(this); int result = wizard->exec(); if (QDialog::Accepted == result) { // the user either migrated the wallets, or choose not to be prompted again ok = true; } } else { if (performMigration(0, true)) { ok = true; } else { qCDebug(KWALLETD_LOG) << "Migration failed."; } } return ok; } void MigrationAgent::emitProgressMessage(const QString &msg) { emit progressMessage(msg); } class MigrationException { public: MigrationException(const QString &msg): _msg(msg) {} QString _msg; }; template R invokeAndCheck(MigrationAgent *migrationAgent, F f, QString errorMsg) { QDBusPendingReply reply = f(); reply.waitForFinished(); QApplication::processEvents(); // keep UI responsive to show progress messages if (!reply.isValid()) { migrationAgent->emitProgressMessage(errorMsg); throw MigrationException(errorMsg); } return reply.value(); } bool MigrationAgent::isEmptyOldWallet() const { QStringList wallets; try { wallets = invokeAndCheck( const_cast(this), [this] { return _kde4_daemon->wallets(); }, i18n("Cannot read old wallet list. Aborting.")); } catch (MigrationException ex) { return true; } return wallets.length() == 0; } bool MigrationAgent::performMigration(WId wid, bool withoutWizard) { auto appId = i18n("KDE Wallet Migration Agent"); try { QStringList wallets = invokeAndCheck( this, [this] { return _kde4_daemon->wallets(); }, i18n("Cannot read old wallet list. Aborting.")); - foreach (const QString &wallet, wallets) { + for (const QString &wallet : qAsConst(wallets)) { emit progressMessage(i18n("Migrating wallet: %1", wallet)); emit progressMessage(i18n("* Creating KF5 wallet: %1", wallet)); int handle5 = -1; if (withoutWizard && (_pam_hash != nullptr)) { // see BUG 351056 for why this hacky code // If the user has several wallets, all the values will be // merged into the single LocalWallet handle5 = _kf5_daemon->pamOpen(KWallet::Wallet::LocalWallet(), _pam_hash, 0); } else { handle5 = _kf5_daemon->internalOpen(appId, wallet, false, 0, true, QString()); } if (handle5 <0) { emit progressMessage(i18n("ERROR when attempting new wallet creation. Aborting.")); return false; } int handle4 = invokeAndCheck( this, [this, wallet, wid, appId] { return _kde4_daemon->open(wallet, wid, appId); }, i18n("Cannot open KDE4 wallet named: %1", wallet)); emit progressMessage(i18n("* Opened KDE4 wallet: %1", wallet)); const QStringList folders = invokeAndCheck( this, [this, handle4, appId] { return _kde4_daemon->folderList(handle4, appId); }, i18n("Cannot retrieve folder list. Aborting.")); - foreach (const QString &folder, folders) { + for (const QString &folder : folders) { emit progressMessage(i18n("* Migrating folder %1", folder)); - QStringList entries = invokeAndCheck( + const QStringList entries = invokeAndCheck( this, [this, handle4, folder, appId] { return _kde4_daemon->entryList(handle4, folder, appId); }, i18n("Cannot retrieve folder %1 entries. Aborting.", folder)); - foreach (const QString &key, entries) { + for (const QString &key : entries) { int entryType = invokeAndCheck( this, [this, handle4, folder, key, appId] { return _kde4_daemon->entryType(handle4, folder, key, appId); }, i18n("Cannot retrieve key %1 info. Aborting.", key)); // handle the case where the entries are already there if (_kf5_daemon->hasEntry(handle5, folder, key, appId)) { emit progressMessage(i18n("* SKIPPING entry %1 in folder %2 as it seems already migrated", key, folder)); } else { QByteArray entry = invokeAndCheck( this, [this, handle4, folder, key, appId] { return _kde4_daemon->readEntry(handle4, folder, key, appId); }, i18n("Cannot retrieve key %1 data. Aborting.", key)); if ( _kf5_daemon->writeEntry(handle5, folder, key, entry, entryType, appId) != 0 ) { auto msg = i18n("Cannot write entry %1 in the new wallet. Aborting.", key); emit progressMessage(msg); throw MigrationException(msg); } } } } //_kde4_daemon->close(handle4, false, appId); //_kf5_daemon->close(handle5, true, appId); _kf5_daemon->sync(handle5, appId); emit progressMessage(i18n("DONE migrating wallet\n")); } } catch (MigrationException ex) { return false; } return true; }