diff --git a/kcm/qml/main.qml b/kcm/qml/main.qml index 972418c9..3ada6ac6 100755 --- a/kcm/qml/main.qml +++ b/kcm/qml/main.qml @@ -1,257 +1,268 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ import QtQuick 2.1 import QtQuick.Dialogs 1.1 import QtQuick.Controls 2.5 as QQC2 import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.extras 2.0 as PlasmaExtras import org.kde.plasma.networkmanagement 0.2 as PlasmaNM import org.kde.kirigami 2.9 as Kirigami Item { id: root focus: true signal selectedConnectionChanged(string connection) signal requestCreateConnection(int type, string vpnType, string specificType, bool shared) signal requestExportConnection(string connection) signal requestToChangeConnection(string name, string path) Kirigami.Theme.colorSet: Kirigami.Theme.Window Rectangle { id: background anchors.fill: parent focus: true color: Kirigami.Theme.backgroundColor } PlasmaNM.Handler { id: handler } PlasmaNM.KcmIdentityModel { id: connectionModel } PlasmaNM.EditorProxyModel { id: editorProxyModel sourceModel: connectionModel } PlasmaNM.Configuration { id: configuration } QQC2.TextField { id: searchField anchors { left: parent.left right: parent.right top: parent.top } placeholderText: i18n("Search...") onTextChanged: { editorProxyModel.setFilterRegExp(text) } } QQC2.ScrollView { id: scrollView Component.onCompleted: scrollView.background.visible = true // show frame anchors { bottom: rightButtonRow.top bottomMargin: units.smallSpacing left: parent.left right: parent.right top: searchField.bottom } ListView { id: connectionView property bool currentConnectionExportable: false property string currentConnectionName property string currentConnectionPath clip: true focus: true activeFocusOnTab: true model: editorProxyModel currentIndex: -1 boundsBehavior: Flickable.StopAtBounds section.property: "KcmConnectionType" section.delegate: Header { text: section } delegate: ConnectionItem { onAboutToChangeConnection: { // Shouldn't be problem to set this in advance connectionView.currentConnectionExportable = exportable if (connectionModified) { requestToChangeConnection(name, path) } else { connectionView.currentConnectionName = name connectionView.currentConnectionPath = path } } onAboutToExportConnection: { requestExportConnection(path) } onAboutToRemoveConnection: { deleteConfirmationDialog.connectionName = name deleteConfirmationDialog.connectionPath = path deleteConfirmationDialog.open() } } onCurrentConnectionPathChanged: { root.selectedConnectionChanged(currentConnectionPath) } } } Row { id: rightButtonRow anchors { bottom: parent.bottom right: parent.right margins: units.smallSpacing } spacing: units.smallSpacing QQC2.ToolButton { id: addConnectionButton icon.name: "list-add" QQC2.ToolTip.text: i18n("Add new connection") QQC2.ToolTip.visible: hovered onClicked: { addNewConnectionDialog.open() } } QQC2.ToolButton { id: removeConnectionButton enabled: connectionView.currentConnectionPath && connectionView.currentConnectionPath.length icon.name: "list-remove" QQC2.ToolTip.text: i18n("Remove selected connection") QQC2.ToolTip.visible: hovered onClicked: { deleteConfirmationDialog.connectionName = connectionView.currentConnectionName deleteConfirmationDialog.connectionPath = connectionView.currentConnectionPath deleteConfirmationDialog.open() } } QQC2.ToolButton { id: exportConnectionButton enabled: connectionView.currentConnectionExportable icon.name: "document-export" QQC2.ToolTip.text: i18n("Export selected connection") QQC2.ToolTip.visible: hovered onClicked: { root.requestExportConnection(connectionView.currentConnectionPath) } } } Row { id: leftButtonRow anchors { bottom: parent.bottom left: parent.left margins: units.smallSpacing } spacing: units.smallSpacing QQC2.ToolButton { id: configureButton icon.name: "configure" QQC2.ToolTip.text: i18n("Configuration") QQC2.ToolTip.visible: hovered onClicked: { configurationDialog.open() } } } MessageDialog { id: deleteConfirmationDialog property string connectionName property string connectionPath + /* Like QString::toHtmlEscaped */ + function toHtmlEscaped(s) { + return s.replace(/[&<>]/g, function (tag) { + return { + '&': '&', + '<': '<', + '>': '>' + }[tag] || tag + }); + } + icon: StandardIcon.Question standardButtons: StandardButton.Ok | StandardButton.Cancel title: i18nc("@title:window", "Remove Connection") - text: i18n("Do you want to remove the connection '%1'?", connectionName) + text: i18n("Do you want to remove the connection '%1'?", toHtmlEscaped(connectionName)) onAccepted: { if (connectionPath == connectionView.currentConnectionPath) { // Deselect now non-existing connection deselectConnections() } handler.removeConnection(connectionPath) } } AddConnectionDialog { id: addNewConnectionDialog onRequestCreateConnection: { root.requestCreateConnection(type, vpnType, specificType, shared) } } ConfigurationDialog { id: configurationDialog } function deselectConnections() { connectionView.currentConnectionPath = "" } function selectConnection(connectionName, connectionPath) { connectionView.currentConnectionName = connectionName connectionView.currentConnectionPath = connectionPath } } diff --git a/kded/notification.cpp b/kded/notification.cpp index 9e9f3b36..5d3e1d83 100644 --- a/kded/notification.cpp +++ b/kded/notification.cpp @@ -1,596 +1,596 @@ /* Copyright 2009 Will Stephenson Copyright 2013 by Daniel Nicoletti Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "debug.h" #include "notification.h" #include #include #include #include #include #include #include Notification::Notification(QObject *parent) : QObject(parent) { // devices for (const NetworkManager::Device::Ptr &device : NetworkManager::networkInterfaces()) { addDevice(device); } connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &Notification::deviceAdded); // connections for (const NetworkManager::ActiveConnection::Ptr &ac : NetworkManager::activeConnections()) { addActiveConnection(ac); } connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, QOverload::of(&Notification::addActiveConnection)); QDBusConnection::systemBus().connect(QStringLiteral("org.freedesktop.login1"), QStringLiteral("/org/freedesktop/login1"), QStringLiteral("org.freedesktop.login1.Manager"), QStringLiteral("PrepareForSleep"), this, SLOT(onPrepareForSleep(bool))); } void Notification::deviceAdded(const QString &uni) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(uni); addDevice(device); } void Notification::addDevice(const NetworkManager::Device::Ptr &device) { connect(device.data(), &NetworkManager::Device::stateChanged, this, &Notification::stateChanged); } void Notification::stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) { Q_UNUSED(oldstate) NetworkManager::Device *device = qobject_cast(sender()); if (newstate == NetworkManager::Device::Activated && m_notifications.contains(device->uni())) { KNotification *notify = m_notifications.value(device->uni()); notify->deleteLater(); m_notifications.remove(device->uni()); return; } else if (newstate != NetworkManager::Device::Failed) { return; } const QString identifier = UiUtils::prettyInterfaceName(device->type(), device->interfaceName()); QString text; switch (reason) { case NetworkManager::Device::NoReason: case NetworkManager::Device::UnknownReason: case NetworkManager::Device::NowManagedReason: case NetworkManager::Device::NowUnmanagedReason: return; case NetworkManager::Device::ConfigFailedReason: text = i18nc("@info:status Notification when the device failed due to ConfigFailedReason", "The device could not be configured"); break; case NetworkManager::Device::ConfigUnavailableReason: text = i18nc("@info:status Notification when the device failed due to ConfigUnavailableReason", "IP configuration was unavailable"); break; case NetworkManager::Device::ConfigExpiredReason: text = i18nc("@info:status Notification when the device failed due to ConfigExpiredReason", "IP configuration expired"); break; case NetworkManager::Device::NoSecretsReason: text = i18nc("@info:status Notification when the device failed due to NoSecretsReason", "No secrets were provided"); break; case NetworkManager::Device::AuthSupplicantDisconnectReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantDisconnectReason", "Authorization supplicant disconnected"); break; case NetworkManager::Device::AuthSupplicantConfigFailedReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantConfigFailedReason", "Authorization supplicant's configuration failed"); break; case NetworkManager::Device::AuthSupplicantFailedReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantFailedReason", "Authorization supplicant failed"); break; case NetworkManager::Device::AuthSupplicantTimeoutReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantTimeoutReason", "Authorization supplicant timed out"); break; case NetworkManager::Device::PppStartFailedReason: text = i18nc("@info:status Notification when the device failed due to PppStartFailedReason", "PPP failed to start"); break; case NetworkManager::Device::PppDisconnectReason: text = i18nc("@info:status Notification when the device failed due to PppDisconnectReason", "PPP disconnected"); break; case NetworkManager::Device::PppFailedReason: text = i18nc("@info:status Notification when the device failed due to PppFailedReason", "PPP failed"); break; case NetworkManager::Device::DhcpStartFailedReason: text = i18nc("@info:status Notification when the device failed due to DhcpStartFailedReason", "DHCP failed to start"); break; case NetworkManager::Device::DhcpErrorReason: text = i18nc("@info:status Notification when the device failed due to DhcpErrorReason", "A DHCP error occurred"); break; case NetworkManager::Device::DhcpFailedReason: text = i18nc("@info:status Notification when the device failed due to DhcpFailedReason", "DHCP failed "); break; case NetworkManager::Device::SharedStartFailedReason: text = i18nc("@info:status Notification when the device failed due to SharedStartFailedReason", "The shared service failed to start"); break; case NetworkManager::Device::SharedFailedReason: text = i18nc("@info:status Notification when the device failed due to SharedFailedReason", "The shared service failed"); break; case NetworkManager::Device::AutoIpStartFailedReason: text = i18nc("@info:status Notification when the device failed due to AutoIpStartFailedReason", "The auto IP service failed to start"); break; case NetworkManager::Device::AutoIpErrorReason: text = i18nc("@info:status Notification when the device failed due to AutoIpErrorReason", "The auto IP service reported an error"); break; case NetworkManager::Device::AutoIpFailedReason: text = i18nc("@info:status Notification when the device failed due to AutoIpFailedReason", "The auto IP service failed"); break; case NetworkManager::Device::ModemBusyReason: text = i18nc("@info:status Notification when the device failed due to ModemBusyReason", "The modem is busy"); break; case NetworkManager::Device::ModemNoDialToneReason: text = i18nc("@info:status Notification when the device failed due to ModemNoDialToneReason", "The modem has no dial tone"); break; case NetworkManager::Device::ModemNoCarrierReason: text = i18nc("@info:status Notification when the device failed due to ModemNoCarrierReason", "The modem shows no carrier"); break; case NetworkManager::Device::ModemDialTimeoutReason: text = i18nc("@info:status Notification when the device failed due to ModemDialTimeoutReason", "The modem dial timed out"); break; case NetworkManager::Device::ModemDialFailedReason: text = i18nc("@info:status Notification when the device failed due to ModemDialFailedReason", "The modem dial failed"); break; case NetworkManager::Device::ModemInitFailedReason: text = i18nc("@info:status Notification when the device failed due to ModemInitFailedReason", "The modem could not be initialized"); break; case NetworkManager::Device::GsmApnSelectFailedReason: text = i18nc("@info:status Notification when the device failed due to GsmApnSelectFailedReason", "The GSM APN could not be selected"); break; case NetworkManager::Device::GsmNotSearchingReason: text = i18nc("@info:status Notification when the device failed due to GsmNotSearchingReason", "The GSM modem is not searching"); break; case NetworkManager::Device::GsmRegistrationDeniedReason: text = i18nc("@info:status Notification when the device failed due to GsmRegistrationDeniedReason", "GSM network registration was denied"); break; case NetworkManager::Device::GsmRegistrationTimeoutReason: text = i18nc("@info:status Notification when the device failed due to GsmRegistrationTimeoutReason", "GSM network registration timed out"); break; case NetworkManager::Device::GsmRegistrationFailedReason: text = i18nc("@info:status Notification when the device failed due to GsmRegistrationFailedReason", "GSM registration failed"); break; case NetworkManager::Device::GsmPinCheckFailedReason: text = i18nc("@info:status Notification when the device failed due to GsmPinCheckFailedReason", "The GSM PIN check failed"); break; case NetworkManager::Device::FirmwareMissingReason: text = i18nc("@info:status Notification when the device failed due to FirmwareMissingReason", "Device firmware is missing"); break; case NetworkManager::Device::DeviceRemovedReason: text = i18nc("@info:status Notification when the device failed due to DeviceRemovedReason", "The device was removed"); break; case NetworkManager::Device::SleepingReason: text = i18nc("@info:status Notification when the device failed due to SleepingReason", "The networking system is now sleeping"); break; case NetworkManager::Device::ConnectionRemovedReason: text = i18nc("@info:status Notification when the device failed due to ConnectionRemovedReason", "The connection was removed"); break; case NetworkManager::Device::UserRequestedReason: return; case NetworkManager::Device::CarrierReason: text = i18nc("@info:status Notification when the device failed due to CarrierReason", "The cable was disconnected"); break; case NetworkManager::Device::ConnectionAssumedReason: case NetworkManager::Device::SupplicantAvailableReason: return; case NetworkManager::Device::ModemNotFoundReason: text = i18nc("@info:status Notification when the device failed due to ModemNotFoundReason", "The modem could not be found"); break; case NetworkManager::Device::BluetoothFailedReason: text = i18nc("@info:status Notification when the device failed due to BluetoothFailedReason", "The bluetooth connection failed or timed out"); break; case NetworkManager::Device::GsmSimNotInserted: text = i18nc("@info:status Notification when the device failed due to GsmSimNotInserted", "GSM Modem's SIM Card not inserted"); break; case NetworkManager::Device::GsmSimPinRequired: text = i18nc("@info:status Notification when the device failed due to GsmSimPinRequired", "GSM Modem's SIM Pin required"); break; case NetworkManager::Device::GsmSimPukRequired: text = i18nc("@info:status Notification when the device failed due to GsmSimPukRequired", "GSM Modem's SIM Puk required"); break; case NetworkManager::Device::GsmSimWrong: text = i18nc("@info:status Notification when the device failed due to GsmSimWrong", "GSM Modem's SIM wrong"); break; case NetworkManager::Device::InfiniBandMode: text = i18nc("@info:status Notification when the device failed due to InfiniBandMode", "InfiniBand device does not support connected mode"); break; case NetworkManager::Device::DependencyFailed: text = i18nc("@info:status Notification when the device failed due to DependencyFailed", "A dependency of the connection failed"); break; case NetworkManager::Device::Br2684Failed: text = i18nc("@info:status Notification when the device failed due to Br2684Failed", "Problem with the RFC 2684 Ethernet over ADSL bridge"); break; case NetworkManager::Device::ModemManagerUnavailable: text = i18nc("@info:status Notification when the device failed due to ModemManagerUnavailable", "ModemManager not running"); break; case NetworkManager::Device::SsidNotFound: text = i18nc("@info:status Notification when the device failed due to SsidNotFound", "The WiFi network could not be found"); break; case NetworkManager::Device::SecondaryConnectionFailed: text = i18nc("@info:status Notification when the device failed due to SecondaryConnectionFailed", "A secondary connection of the base connection failed"); break; case NetworkManager::Device::DcbFcoeFailed: text = i18nc("@info:status Notification when the device failed due to DcbFcoeFailed", "DCB or FCoE setup failed"); break; case NetworkManager::Device::TeamdControlFailed: text = i18nc("@info:status Notification when the device failed due to TeamdControlFailed", "teamd control failed"); break; case NetworkManager::Device::ModemFailed: text = i18nc("@info:status Notification when the device failed due to ModemFailed", "Modem failed or no longer available"); break; case NetworkManager::Device::ModemAvailable: text = i18nc("@info:status Notification when the device failed due to ModemAvailable", "Modem now ready and available"); break; case NetworkManager::Device::SimPinIncorrect: text = i18nc("@info:status Notification when the device failed due to SimPinIncorrect", "The SIM PIN was incorrect"); break; case NetworkManager::Device::NewActivation: text = i18nc("@info:status Notification when the device failed due to NewActivation", "A new connection activation was enqueued"); break; case NetworkManager::Device::ParentChanged: text = i18nc("@info:status Notification when the device failed due to ParentChanged", "The device's parent changed"); break; case NetworkManager::Device::ParentManagedChanged: text = i18nc("@info:status Notification when the device failed due to ParentManagedChanged", "The device parent's management changed"); break; case NetworkManager::Device::Reserved: return; } if (m_notifications.contains(device->uni())) { KNotification *notify = m_notifications.value(device->uni()); - notify->setText(text); + notify->setText(text.toHtmlEscaped()); notify->update(); } else { KNotification *notify = new KNotification(QStringLiteral("DeviceFailed"), KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); notify->setProperty("uni", device->uni()); notify->setComponentName(QStringLiteral("networkmanagement")); notify->setIconName(QStringLiteral("dialog-warning")); notify->setTitle(identifier); - notify->setText(text); + notify->setText(text.toHtmlEscaped()); notify->sendEvent(); if (notify->id() != -1) { m_notifications[device->uni()] = notify; } } } void Notification::addActiveConnection(const QString &path) { NetworkManager::ActiveConnection::Ptr ac = NetworkManager::findActiveConnection(path); if (ac && ac->isValid()) { addActiveConnection(ac); } } void Notification::addActiveConnection(const NetworkManager::ActiveConnection::Ptr &ac) { if (ac->vpn()) { NetworkManager::VpnConnection::Ptr vpnConnection = ac.objectCast(); connect(vpnConnection.data(), &NetworkManager::VpnConnection::stateChanged, this, &Notification::onVpnConnectionStateChanged); } else if (ac->type() != NetworkManager::ConnectionSettings::Bond && ac->type() != NetworkManager::ConnectionSettings::Bridge && ac->type() != NetworkManager::ConnectionSettings::Generic && ac->type() != NetworkManager::ConnectionSettings::Infiniband && ac->type() != NetworkManager::ConnectionSettings::Team && ac->type() != NetworkManager::ConnectionSettings::Vlan && ac->type() != NetworkManager::ConnectionSettings::Tun) { connect(ac.data(), &NetworkManager::ActiveConnection::stateChanged, this, &Notification::onActiveConnectionStateChanged); } } void Notification::onActiveConnectionStateChanged(NetworkManager::ActiveConnection::State state) { NetworkManager::ActiveConnection *ac = qobject_cast(sender()); QString eventId, text, iconName; const QString acName = ac->id(); const QString connectionId = ac->path(); if (state == NetworkManager::ActiveConnection::Activated) { auto foundConnection = std::find_if(m_activeConnectionsBeforeSleep.constBegin(), m_activeConnectionsBeforeSleep.constEnd(), [ac](const QString &uuid) { return uuid == ac->uuid(); }); if (foundConnection != m_activeConnectionsBeforeSleep.constEnd()) { qCDebug(PLASMA_NM) << "Not emitting connection activated notification as the connection was active prior to suspend"; return; } eventId = QStringLiteral("ConnectionActivated"); text = i18n("Connection '%1' activated.", acName); switch (ac->type()) { case NetworkManager::ConnectionSettings::Wireless: iconName = QStringLiteral("network-wireless-on"); break; case NetworkManager::ConnectionSettings::Wired: iconName = QStringLiteral("network-wired-activated"); break; case NetworkManager::ConnectionSettings::WireGuard: iconName = QStringLiteral("network-vpn"); break; default: // silence warning break; } } else if (state == NetworkManager::ActiveConnection::Deactivated) { if (m_preparingForSleep) { qCDebug(PLASMA_NM) << "Not emitting connection deactivated notification as we're about to suspend"; return; } eventId = QStringLiteral("ConnectionDeactivated"); text = i18n("Connection '%1' deactivated.", acName); switch (ac->type()) { case NetworkManager::ConnectionSettings::Wireless: iconName = QStringLiteral("network-wireless-disconnected"); break; case NetworkManager::ConnectionSettings::Wired: iconName = QStringLiteral("network-unavailable"); break; default: // silence warning break; } } else { qCWarning(PLASMA_NM) << "Unhandled active connection state change: " << state; return; } KNotification *notify = new KNotification(eventId, KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); notify->setProperty("uni", connectionId); notify->setComponentName(QStringLiteral("networkmanagement")); if (!iconName.isEmpty()) { notify->setIconName(iconName); } else { if (state == NetworkManager::ActiveConnection::Activated) { notify->setIconName(QStringLiteral("dialog-information")); } else { notify->setIconName(QStringLiteral("dialog-warning")); } } notify->setTitle(acName); - notify->setText(text); + notify->setText(text.toHtmlEscaped()); notify->sendEvent(); if (notify->id() != -1) { m_notifications[connectionId] = notify; } } void Notification::onVpnConnectionStateChanged(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason) { NetworkManager::VpnConnection *vpn = qobject_cast(sender()); QString eventId, text; const QString vpnName = vpn->connection()->name(); const QString connectionId = vpn->path(); if (state == NetworkManager::VpnConnection::Activated) { eventId = QStringLiteral("ConnectionActivated"); text = i18n("VPN connection '%1' activated.", vpnName); } else if (state == NetworkManager::VpnConnection::Failed) { eventId = QStringLiteral("FailedToActivateConnection"); text = i18n("VPN connection '%1' failed.", vpnName); } else if (state == NetworkManager::VpnConnection::Disconnected) { eventId = QStringLiteral("ConnectionDeactivated"); text = i18n("VPN connection '%1' disconnected.", vpnName); } else { qCWarning(PLASMA_NM) << "Unhandled VPN connection state change: " << state; return; } switch (reason) { case NetworkManager::VpnConnection::UserDisconnectedReason: text = i18n("The VPN connection changed state because the user disconnected it."); break; case NetworkManager::VpnConnection::DeviceDisconnectedReason: text = i18n("The VPN connection changed state because the device it was using was disconnected."); break; case NetworkManager::VpnConnection::ServiceStoppedReason: text = i18n("The service providing the VPN connection was stopped."); break; case NetworkManager::VpnConnection::IpConfigInvalidReason: text = i18n("The IP config of the VPN connection was invalid."); break; case NetworkManager::VpnConnection::ConnectTimeoutReason: text = i18n("The connection attempt to the VPN service timed out."); break; case NetworkManager::VpnConnection::ServiceStartTimeoutReason: text = i18n("A timeout occurred while starting the service providing the VPN connection."); break; case NetworkManager::VpnConnection::ServiceStartFailedReason: text = i18n("Starting the service providing the VPN connection failed."); break; case NetworkManager::VpnConnection::NoSecretsReason: text = i18n("Necessary secrets for the VPN connection were not provided."); break; case NetworkManager::VpnConnection::LoginFailedReason: text = i18n("Authentication to the VPN server failed."); break; case NetworkManager::VpnConnection::ConnectionRemovedReason: text = i18n("The connection was deleted from settings."); break; default: case NetworkManager::VpnConnection::UnknownReason: case NetworkManager::VpnConnection::NoneReason: break; } KNotification *notify = new KNotification(eventId, KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); notify->setProperty("uni", connectionId); notify->setComponentName("networkmanagement"); if (state == NetworkManager::VpnConnection::Activated) { notify->setIconName(QStringLiteral("dialog-information")); } else { notify->setIconName(QStringLiteral("dialog-warning")); } notify->setTitle(vpnName); - notify->setText(text); + notify->setText(text.toHtmlEscaped()); notify->sendEvent(); if (notify->id() != -1) { m_notifications[connectionId] = notify; } } void Notification::notificationClosed() { KNotification *notify = qobject_cast(sender()); m_notifications.remove(notify->property("uni").toString()); notify->deleteLater(); } void Notification::onPrepareForSleep(bool sleep) { m_preparingForSleep = sleep; if (m_checkActiveConnectionOnResumeTimer) { m_checkActiveConnectionOnResumeTimer->stop(); } if (sleep) { // store all active notifications so we don't show a "is connected" notification // on resume if we were connected previously m_activeConnectionsBeforeSleep.clear(); const auto &connections = NetworkManager::activeConnections(); for (const auto &connection : connections) { if (!connection->vpn() && connection->state() == NetworkManager::ActiveConnection::State::Activated) { m_activeConnectionsBeforeSleep << connection->uuid(); } } } else { if (!m_checkActiveConnectionOnResumeTimer) { m_checkActiveConnectionOnResumeTimer = new QTimer(this); m_checkActiveConnectionOnResumeTimer->setInterval(10000); m_checkActiveConnectionOnResumeTimer->setSingleShot(true); connect(m_checkActiveConnectionOnResumeTimer, &QTimer::timeout, this, &Notification::onCheckActiveConnectionOnResume); } m_checkActiveConnectionOnResumeTimer->start(); } } void Notification::onCheckActiveConnectionOnResume() { if (m_activeConnectionsBeforeSleep.isEmpty()) { // if we weren't connected before, don't bother telling us now :) return; } m_activeConnectionsBeforeSleep.clear(); const auto &connections = NetworkManager::activeConnections(); for (const auto &connection : connections) { if (connection->state() == NetworkManager::ActiveConnection::State::Activated || connection->state() == NetworkManager::ActiveConnection::State::Activating) { // we have an active or activating connection, don't tell the user we're no longer connected return; } } KNotification *notify = new KNotification(QStringLiteral("NoLongerConnected"), KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); const QString uni = QStringLiteral("offlineNotification"); notify->setProperty("uni", uni); notify->setComponentName("networkmanagement"); notify->setIconName(QStringLiteral("dialog-warning")); notify->setTitle(i18n("No Network Connection")); notify->setText(i18n("You are no longer connected to a network.")); notify->sendEvent(); if (notify->id() != -1) { m_notifications[uni] = notify; } } diff --git a/kded/passworddialog.cpp b/kded/passworddialog.cpp index 59992ebc..a0bf100e 100644 --- a/kded/passworddialog.cpp +++ b/kded/passworddialog.cpp @@ -1,197 +1,197 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 by Daniel Nicoletti This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "debug.h" #include "passworddialog.h" #include "ui_passworddialog.h" #include "uiutils.h" #include #include #include #include #include #include #include #include #include using namespace NetworkManager; PasswordDialog::PasswordDialog(const NetworkManager::ConnectionSettings::Ptr &connectionSettings, SecretAgent::GetSecretsFlags flags, const QString &setting_name, QWidget *parent) : QDialog(parent), m_ui(nullptr), m_hasError(false), m_settingName(setting_name), m_connectionSettings(connectionSettings), m_error(SecretAgent::NoSecrets), m_flags(flags), m_vpnWidget(nullptr) { setWindowIcon(QIcon::fromTheme(QStringLiteral("dialog-password"))); initializeUi(); } PasswordDialog::~PasswordDialog() { delete m_ui; } void PasswordDialog::initializeUi() { m_ui = new Ui::PasswordDialog; m_ui->setupUi(this); // TODO fix this for high DPI m_ui->labelIcon->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-password")).pixmap(KIconLoader::SizeHuge)); m_ui->labelHeadline->setText(i18n("Authenticate %1", m_connectionSettings->id())); connect(m_ui->buttonBox, &QDialogButtonBox::accepted, this, &PasswordDialog::accept); connect(m_ui->buttonBox, &QDialogButtonBox::rejected, this, &PasswordDialog::reject); connect(m_ui->password, &PasswordField::textChanged, [this](const QString &text){ if (m_connectionSettings->connectionType() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = m_connectionSettings->setting(NetworkManager::Setting::WirelessSecurity).staticCast(); bool valid = true; if (wirelessSecuritySetting) { switch (wirelessSecuritySetting->keyMgmt()) { case NetworkManager::WirelessSecuritySetting::WpaPsk: valid = wpaPskIsValid(text); break; case NetworkManager::WirelessSecuritySetting::Wep: valid = wepKeyIsValid(text, wirelessSecuritySetting->wepKeyType()); break; default: break; } } // disable button if key is not valid m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDisabled(!valid); } }); if (m_connectionSettings->connectionType() != NetworkManager::ConnectionSettings::Vpn) { NetworkManager::Setting::Ptr setting = m_connectionSettings->setting(m_settingName); m_neededSecrets = setting->needSecrets(m_flags & SecretAgent::RequestNew); if (m_neededSecrets.isEmpty()) { qCWarning(PLASMA_NM) << "list of secrets is empty!!!"; m_hasError = true; m_error = SecretAgent::InternalError; m_errorMessage = QLatin1String("No secrets were requested"); return; } WirelessSetting::Ptr wifi = m_connectionSettings->setting(Setting::Wireless).dynamicCast(); Setting::SettingType connectionType = setting->type(); if (wifi && (connectionType == Setting::WirelessSecurity || connectionType == Setting::Security8021x)) { const QString ssid = QString::fromUtf8(wifi->ssid()); - m_ui->labelText->setText(i18n("For accessing the wireless network %1 you need to provide a password below:", ssid)); + m_ui->labelText->setText(i18n("For accessing the wireless network %1 you need to provide a password below:", ssid)); } else { - m_ui->labelText->setText(i18n("Please provide the password for activating connection %1:", m_connectionSettings->id())); + m_ui->labelText->setText(i18n("Please provide the password for activating connection %1:", m_connectionSettings->id())); } QString connectionLabel; UiUtils::iconAndTitleForConnectionSettingsType(m_connectionSettings->connectionType(), connectionLabel); setFocusProxy(m_ui->password); setWindowTitle(i18n("%1 password dialog", connectionLabel)); } else { NetworkManager::VpnSetting::Ptr vpnSetting = m_connectionSettings->setting(Setting::Vpn).dynamicCast(); qWarning() << "VPN Setting " << *vpnSetting; if (!vpnSetting) { qCWarning(PLASMA_NM) << "Missing VPN setting!"; m_hasError = true; m_error = SecretAgent::InternalError; m_errorMessage = QLatin1String("VPN settings are missing"); } else { VpnUiPlugin *vpnUiPlugin; QString error; const QString serviceType = vpnSetting->serviceType(); vpnUiPlugin = KServiceTypeTrader::createInstanceFromQuery(QLatin1String("PlasmaNetworkManagement/VpnUiPlugin"), QString::fromLatin1("[X-NetworkManager-Services]=='%1'").arg(serviceType), this, QVariantList(), &error); if (vpnUiPlugin && error.isEmpty()) { const QString shortName = serviceType.section('.', -1); m_vpnWidget = vpnUiPlugin->askUser(vpnSetting, this); QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(m_vpnWidget); m_ui->vpnWidget->setLayout(layout); - m_ui->labelText->setText(i18n("For accessing the vpn connection %1 you need to provide secrets below:", m_connectionSettings->id())); + m_ui->labelText->setText(i18n("For accessing the vpn connection %1 you need to provide secrets below:", m_connectionSettings->id())); setWindowTitle(i18n("VPN secrets (%1) dialog", shortName)); // Hide generic password field and OK button in case of openconnect dialog m_ui->labelPass->setVisible(false); m_ui->password->setVisible(false); if (shortName == QLatin1String("openconnect")) { QAbstractButton *button = m_ui->buttonBox->button(QDialogButtonBox::Ok); m_ui->buttonBox->removeButton(button); } setFocusProxy(m_vpnWidget); m_vpnWidget->setFocus(Qt::OtherFocusReason); } else { qCWarning(PLASMA_NM) << error << ", serviceType == " << serviceType; m_hasError = true; m_error = SecretAgent::InternalError; m_errorMessage = error; } } } // Workaround to force m_ui->password to get focus. focusNextChild(); } bool PasswordDialog::hasError() const { return m_hasError; } SecretAgent::Error PasswordDialog::error() const { return m_error; } QString PasswordDialog::errorMessage() const { return m_errorMessage; } NMVariantMapMap PasswordDialog::secrets() const { NMVariantMapMap ret = m_connectionSettings->toMap(); QVariantMap result; if (m_vpnWidget) { result = m_vpnWidget->setting(); } else if (!m_ui->password->text().isEmpty() && !m_neededSecrets.isEmpty()) { result.insert(m_neededSecrets.first(), m_ui->password->text()); } ret.insert(m_settingName, result); return ret; } diff --git a/kded/passworddialog.ui b/kded/passworddialog.ui index 7008cbb3..3efa85e8 100644 --- a/kded/passworddialog.ui +++ b/kded/passworddialog.ui @@ -1,139 +1,145 @@ PasswordDialog 0 0 480 147 0 0 640 16777215 Password dialog 1 IconLabel 8 -1 font-weight: bold TextLabel + + Qt::PlainText + 0 0 16777215 16777215 TextLabel + + Qt::PlainText + true Password: 64 true Qt::Vertical QSizePolicy::Preferred 20 40 QDialogButtonBox::Cancel|QDialogButtonBox::Ok PasswordField QLineEdit
passwordfield.h
diff --git a/kded/secretagent.cpp b/kded/secretagent.cpp index a49e3a54..9389f5f6 100644 --- a/kded/secretagent.cpp +++ b/kded/secretagent.cpp @@ -1,672 +1,673 @@ /* Copyright 2013 Jan Grulich Copyright 2013 Lukas Tinkl Copyright 2013 by Daniel Nicoletti This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "passworddialog.h" #include "secretagent.h" #include "debug.h" #include "configuration.h" #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include #include #include #include SecretAgent::SecretAgent(QObject* parent) : NetworkManager::SecretAgent("org.kde.plasma.networkmanagement", parent) , m_openWalletFailed(false) , m_wallet(nullptr) , m_dialog(nullptr) { connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, this, &SecretAgent::killDialogs); // We have to import secrets previously stored in plaintext files importSecretsFromPlainTextFiles(); } SecretAgent::~SecretAgent() { } NMVariantMapMap SecretAgent::GetSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path, const QString &setting_name, const QStringList &hints, uint flags) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); qCDebug(PLASMA_NM) << "Setting name:" << setting_name; qCDebug(PLASMA_NM) << "Hints:" << hints; qCDebug(PLASMA_NM) << "Flags:" << flags; const QString callId = connection_path.path() % setting_name; for (const SecretsRequest &request : m_calls) { if (request == callId) { qCWarning(PLASMA_NM) << "GetSecrets was called again! This should not happen, cancelling first call" << connection_path.path() << setting_name; CancelGetSecrets(connection_path, setting_name); break; } } setDelayedReply(true); SecretsRequest request(SecretsRequest::GetSecrets); request.callId = callId; request.connection = connection; request.connection_path = connection_path; request.flags = static_cast(flags); request.hints = hints; request.setting_name = setting_name; request.message = message(); m_calls << request; processNext(); return NMVariantMapMap(); } void SecretAgent::SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); // qCDebug(PLASMA_NM) << "Setting:" << connection; setDelayedReply(true); SecretsRequest::Type type; if (hasSecrets(connection)) { type = SecretsRequest::SaveSecrets; } else { type = SecretsRequest::DeleteSecrets; } SecretsRequest request(type); request.connection = connection; request.connection_path = connection_path; request.message = message(); m_calls << request; processNext(); } void SecretAgent::DeleteSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); // qCDebug(PLASMA_NM) << "Setting:" << connection; setDelayedReply(true); SecretsRequest request(SecretsRequest::DeleteSecrets); request.connection = connection; request.connection_path = connection_path; request.message = message(); m_calls << request; processNext(); } void SecretAgent::CancelGetSecrets(const QDBusObjectPath &connection_path, const QString &setting_name) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); qCDebug(PLASMA_NM) << "Setting name:" << setting_name; QString callId = connection_path.path() % setting_name; for (int i = 0; i < m_calls.size(); ++i) { SecretsRequest request = m_calls.at(i); if (request.type == SecretsRequest::GetSecrets && callId == request.callId) { if (m_dialog == request.dialog) { m_dialog = nullptr; } delete request.dialog; sendError(SecretAgent::AgentCanceled, QLatin1String("Agent canceled the password dialog"), request.message); m_calls.removeAt(i); break; } } processNext(); } void SecretAgent::dialogAccepted() { for (int i = 0; i < m_calls.size(); ++i) { SecretsRequest request = m_calls[i]; if (request.type == SecretsRequest::GetSecrets && request.dialog == m_dialog) { NMStringMap tmpOpenconnectSecrets; NMVariantMapMap connection = request.dialog->secrets(); if (connection.contains(QLatin1String("vpn"))) { if (connection.value(QStringLiteral("vpn")).contains(QLatin1String("tmp-secrets"))) { QVariantMap vpnSetting = connection.value(QLatin1String("vpn")); tmpOpenconnectSecrets = qdbus_cast(vpnSetting.take(QLatin1String("tmp-secrets"))); connection.insert(QLatin1String("vpn"), vpnSetting); } } sendSecrets(connection, request.message); NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(connection)); NetworkManager::ConnectionSettings::Ptr completeConnectionSettings; NetworkManager::Connection::Ptr con = NetworkManager::findConnectionByUuid(connectionSettings->uuid()); if (con) { completeConnectionSettings = con->settings(); } else { completeConnectionSettings = connectionSettings; } if (request.saveSecretsWithoutReply && completeConnectionSettings->connectionType() != NetworkManager::ConnectionSettings::Vpn) { bool requestOffline = true; if (completeConnectionSettings->connectionType() == NetworkManager::ConnectionSettings::Gsm) { NetworkManager::GsmSetting::Ptr gsmSetting = completeConnectionSettings->setting(NetworkManager::Setting::Gsm).staticCast(); if (gsmSetting) { if (gsmSetting->passwordFlags().testFlag(NetworkManager::Setting::NotSaved) || gsmSetting->passwordFlags().testFlag(NetworkManager::Setting::NotRequired)) { requestOffline = false; } else if (gsmSetting->pinFlags().testFlag(NetworkManager::Setting::NotSaved) || gsmSetting->pinFlags().testFlag(NetworkManager::Setting::NotRequired)) { requestOffline = false; } } } else if (completeConnectionSettings->connectionType() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = completeConnectionSettings->setting(NetworkManager::Setting::WirelessSecurity).staticCast(); if (wirelessSecuritySetting && wirelessSecuritySetting->keyMgmt() == NetworkManager::WirelessSecuritySetting::WpaEap) { NetworkManager::Security8021xSetting::Ptr security8021xSetting = completeConnectionSettings->setting(NetworkManager::Setting::Security8021x).staticCast(); if (security8021xSetting) { if (security8021xSetting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethodFast) || security8021xSetting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethodTtls) || security8021xSetting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethodPeap)) { if (security8021xSetting->passwordFlags().testFlag(NetworkManager::Setting::NotSaved) || security8021xSetting->passwordFlags().testFlag(NetworkManager::Setting::NotRequired)) { requestOffline = false; } } } } } if (requestOffline) { SecretsRequest requestOffline(SecretsRequest::SaveSecrets); requestOffline.connection = connection; requestOffline.connection_path = request.connection_path; requestOffline.saveSecretsWithoutReply = true; m_calls << requestOffline; } } else if (request.saveSecretsWithoutReply && completeConnectionSettings->connectionType() == NetworkManager::ConnectionSettings::Vpn && !tmpOpenconnectSecrets.isEmpty()) { NetworkManager::VpnSetting::Ptr vpnSetting = completeConnectionSettings->setting(NetworkManager::Setting::Vpn).staticCast(); if (vpnSetting) { NMStringMap data = vpnSetting->data(); NMStringMap secrets = vpnSetting->secrets(); // Load secrets from auth dialog which are returned back to NM if (connection.value(QLatin1String("vpn")).contains(QLatin1String("secrets"))) { secrets.unite(qdbus_cast(connection.value(QLatin1String("vpn")).value(QLatin1String("secrets")))); } // Load temporary secrets from auth dialog which are not returned to NM for (const QString &key : tmpOpenconnectSecrets.keys()) { if (secrets.contains(QLatin1String("save_passwords")) && secrets.value(QLatin1String("save_passwords")) == QLatin1String("yes")) { data.insert(key + QLatin1String("-flags"), QString::number(NetworkManager::Setting::AgentOwned)); } else { data.insert(key + QLatin1String("-flags"), QString::number(NetworkManager::Setting::NotSaved)); } secrets.insert(key, tmpOpenconnectSecrets.value(key)); } vpnSetting->setData(data); vpnSetting->setSecrets(secrets); if (!con) { con = NetworkManager::findConnection(request.connection_path.path()); } if (con) { con->update(completeConnectionSettings->toMap()); } } } m_calls.removeAt(i); break; } } m_dialog->deleteLater(); m_dialog = nullptr; processNext(); } void SecretAgent::dialogRejected() { for (int i = 0; i < m_calls.size(); ++i) { SecretsRequest request = m_calls[i]; if (request.type == SecretsRequest::GetSecrets && request.dialog == m_dialog) { sendError(SecretAgent::UserCanceled, QLatin1String("User canceled the password dialog"), request.message); m_calls.removeAt(i); break; } } m_dialog->deleteLater(); m_dialog = nullptr; processNext(); } void SecretAgent::killDialogs() { int i = 0; while (i < m_calls.size()) { SecretsRequest request = m_calls[i]; if (request.type == SecretsRequest::GetSecrets) { delete request.dialog; m_calls.removeAt(i); } ++i; } } void SecretAgent::walletOpened(bool success) { if (!success) { m_openWalletFailed = true; m_wallet->deleteLater(); m_wallet = nullptr; } else { m_openWalletFailed = false; } processNext(); } void SecretAgent::walletClosed() { if (m_wallet) { m_wallet->deleteLater(); } m_wallet = nullptr; } void SecretAgent::processNext() { int i = 0; while (i < m_calls.size()) { SecretsRequest &request = m_calls[i]; switch (request.type) { case SecretsRequest::GetSecrets: if (processGetSecrets(request)) { m_calls.removeAt(i); continue; } break; case SecretsRequest::SaveSecrets: if (processSaveSecrets(request)) { m_calls.removeAt(i); continue; } break; case SecretsRequest::DeleteSecrets: if (processDeleteSecrets(request)) { m_calls.removeAt(i); continue; } break; } ++i; } } bool SecretAgent::processGetSecrets(SecretsRequest &request) const { if (m_dialog) { return false; } NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(request.connection)); NetworkManager::Setting::Ptr setting = connectionSettings->setting(request.setting_name); const bool requestNew = request.flags & RequestNew; const bool userRequested = request.flags & UserRequested; const bool allowInteraction = request.flags & AllowInteraction; const bool isVpn = (setting->type() == NetworkManager::Setting::Vpn); const bool isWireGuard = (setting->type() == NetworkManager::Setting::WireGuard); if (isVpn) { NetworkManager::VpnSetting::Ptr vpnSetting = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); if (vpnSetting->serviceType() == QLatin1String("org.freedesktop.NetworkManager.ssh") && vpnSetting->data()["auth-type"] == QLatin1String("ssh-agent")) { QString authSock = qgetenv("SSH_AUTH_SOCK"); qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Sending SSH auth socket" << authSock; if (authSock.isEmpty()) { sendError(SecretAgent::NoSecrets, QLatin1String("SSH_AUTH_SOCK not present"), request.message); } else { NMStringMap secrets; secrets.insert(QLatin1String("ssh-auth-sock"), authSock); QVariantMap secretData; secretData.insert(QLatin1String("secrets"), QVariant::fromValue(secrets)); request.connection[request.setting_name] = secretData; sendSecrets(request.connection, request.message); } return true; } } NMStringMap secretsMap; if (!requestNew && useWallet()) { if (m_wallet->isOpen()) { if (m_wallet->hasFolder("Network Management") && m_wallet->setFolder("Network Management")) { QString key = QLatin1Char('{') % connectionSettings->uuid() % QLatin1Char('}') % QLatin1Char(';') % request.setting_name; m_wallet->readMap(key, secretsMap); } } else { qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Waiting for the wallet to open"; return false; } } if (!secretsMap.isEmpty()) { setting->secretsFromStringMap(secretsMap); if (!(isVpn || isWireGuard) && setting->needSecrets(requestNew).isEmpty()) { // Enough secrets were retrieved from storage request.connection[request.setting_name] = setting->secretsToMap(); sendSecrets(request.connection, request.message); return true; } } if (!Configuration::showPasswordDialog()) { sendError(SecretAgent::NoSecrets, "Cannot authenticate", request.message); emit secretsError(request.connection_path.path(), i18n("Authentication to %1 failed. Wrong password?", request.connection.value("connection").value("id").toString())); return true; } else if (isWireGuard && userRequested) { // Just return what we have NMVariantMapMap result; NetworkManager::WireGuardSetting::Ptr wireGuardSetting; wireGuardSetting = connectionSettings->setting(NetworkManager::Setting::WireGuard).dynamicCast(); //FIXME workaround when NM is asking for secrets which should be system-stored, if we send an empty map it // won't ask for additional secrets with AllowInteraction flag which would display the authentication dialog if (wireGuardSetting->secretsToMap().isEmpty()) { // Insert an empty secrets map as it was before I fixed it in NetworkManagerQt to make sure NM will ask again // with flags we need QVariantMap secretsMap; secretsMap.insert(QLatin1String("secrets"), QVariant::fromValue(NMStringMap())); result.insert("wireguard", secretsMap); } else { result.insert("wireguard", wireGuardSetting->secretsToMap()); } sendSecrets(result, request.message); return true; } else if (requestNew || (allowInteraction && !setting->needSecrets(requestNew).isEmpty()) || (allowInteraction && userRequested) || (isVpn && allowInteraction)) { m_dialog = new PasswordDialog(connectionSettings, request.flags, request.setting_name); connect(m_dialog, &PasswordDialog::accepted, this, &SecretAgent::dialogAccepted); connect(m_dialog, &PasswordDialog::rejected, this, &SecretAgent::dialogRejected); if (m_dialog->hasError()) { sendError(m_dialog->error(), m_dialog->errorMessage(), request.message); delete m_dialog; m_dialog = nullptr; return true; } else { request.dialog = m_dialog; request.saveSecretsWithoutReply = !connectionSettings->permissions().isEmpty(); m_dialog->show(); KWindowSystem::setState(m_dialog->winId(), NET::KeepAbove); KWindowSystem::forceActiveWindow(m_dialog->winId()); return false; } } else if (isVpn && userRequested) { // just return what we have NMVariantMapMap result; NetworkManager::VpnSetting::Ptr vpnSetting; vpnSetting = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); //FIXME workaround when NM is asking for secrets which should be system-stored, if we send an empty map it // won't ask for additional secrets with AllowInteraction flag which would display the authentication dialog if (vpnSetting->secretsToMap().isEmpty()) { // Insert an empty secrets map as it was before I fixed it in NetworkManagerQt to make sure NM will ask again // with flags we need QVariantMap secretsMap; secretsMap.insert(QLatin1String("secrets"), QVariant::fromValue(NMStringMap())); result.insert("vpn", secretsMap); } else { result.insert("vpn", vpnSetting->secretsToMap()); } sendSecrets(result, request.message); return true; } else if (setting->needSecrets().isEmpty()) { NMVariantMapMap result; result.insert(setting->name(), setting->secretsToMap()); sendSecrets(result, request.message); return true; } else { sendError(SecretAgent::InternalError, QLatin1String("Plasma-nm did not know how to handle the request"), request.message); return true; } } bool SecretAgent::processSaveSecrets(SecretsRequest &request) const { if (useWallet()) { if (m_wallet->isOpen()) { NetworkManager::ConnectionSettings connectionSettings(request.connection); if (!m_wallet->hasFolder("Network Management")) { m_wallet->createFolder("Network Management"); } if (m_wallet->setFolder("Network Management")) { for (const NetworkManager::Setting::Ptr &setting : connectionSettings.settings()) { NMStringMap secretsMap = setting->secretsToStringMap(); if (!secretsMap.isEmpty()) { QString entryName = QLatin1Char('{') % connectionSettings.uuid() % QLatin1Char('}') % QLatin1Char(';') % setting->name(); m_wallet->writeMap(entryName, secretsMap); } } } else if (!request.saveSecretsWithoutReply) { sendError(SecretAgent::InternalError, QLatin1String("Could not store secrets in the wallet."), request.message); return true; } } else { qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Waiting for the wallet to open"; return false; } } if (!request.saveSecretsWithoutReply) { QDBusMessage reply = request.message.createReply(); if (!QDBusConnection::systemBus().send(reply)) { qCWarning(PLASMA_NM) << "Failed put save secrets reply into the queue"; } } return true; } bool SecretAgent::processDeleteSecrets(SecretsRequest &request) const { if (useWallet()) { if (m_wallet->isOpen()) { if (m_wallet->hasFolder("Network Management") && m_wallet->setFolder("Network Management")) { NetworkManager::ConnectionSettings connectionSettings(request.connection); for (const NetworkManager::Setting::Ptr &setting : connectionSettings.settings()) { QString entryName = QLatin1Char('{') % connectionSettings.uuid() % QLatin1Char('}') % QLatin1Char(';') % setting->name(); for (const QString &entry : m_wallet->entryList()) { if (entry.startsWith(entryName)) { m_wallet->removeEntry(entryName); } } } } } else { qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Waiting for the wallet to open"; return false; } } QDBusMessage reply = request.message.createReply(); if (!QDBusConnection::systemBus().send(reply)) { qCWarning(PLASMA_NM) << "Failed put delete secrets reply into the queue"; } return true; } bool SecretAgent::useWallet() const { if (m_wallet) { return true; } /* If opening of KWallet failed before, we should not try to open it again and * we should return false instead */ if (m_openWalletFailed) { m_openWalletFailed = false; return false; } if (KWallet::Wallet::isEnabled()) { m_wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), 0, KWallet::Wallet::Asynchronous); if (m_wallet) { connect(m_wallet, &KWallet::Wallet::walletOpened, this, &SecretAgent::walletOpened); connect(m_wallet, &KWallet::Wallet::walletClosed, this, &SecretAgent::walletClosed); return true; } else { qCWarning(PLASMA_NM) << "Error opening kwallet."; } } else if (m_wallet) { m_wallet->deleteLater(); m_wallet = nullptr; } return false; } bool SecretAgent::hasSecrets(const NMVariantMapMap &connection) const { NetworkManager::ConnectionSettings connectionSettings(connection); for (const NetworkManager::Setting::Ptr &setting : connectionSettings.settings()) { if (!setting->secretsToMap().isEmpty()) { return true; } } return false; } void SecretAgent::sendSecrets(const NMVariantMapMap &secrets, const QDBusMessage &message) const { QDBusMessage reply; reply = message.createReply(QVariant::fromValue(secrets)); if (!QDBusConnection::systemBus().send(reply)) { qCWarning(PLASMA_NM) << "Failed put the secret into the queue"; } } void SecretAgent::importSecretsFromPlainTextFiles() { KConfig config(QLatin1String("plasma-networkmanagement"), KConfig::SimpleConfig); // No action is required when the list of secrets is empty if (!config.groupList().isEmpty()) { for (const QString &groupName : config.groupList()) { QString loadedUuid = groupName.split(';').first().remove('{').remove('}'); QString loadedSettingType = groupName.split(';').last(); NetworkManager::Connection::Ptr connection = NetworkManager::findConnectionByUuid(loadedUuid); if (connection) { NetworkManager::Setting::SecretFlags secretFlags = KWallet::Wallet::isEnabled() ? NetworkManager::Setting::AgentOwned : NetworkManager::Setting::None; QMap secrets = config.entryMap(groupName); NMVariantMapMap settings = connection->settings()->toMap(); for (const QString &setting : settings.keys()) { if (setting == QLatin1String("vpn")) { NetworkManager::VpnSetting::Ptr vpnSetting = connection->settings()->setting(NetworkManager::Setting::Vpn).staticCast(); if (vpnSetting) { // Add loaded secrets from the config file vpnSetting->secretsFromStringMap(secrets); NMStringMap vpnData = vpnSetting->data(); // Reset flags, we can't save secrets to our secret agent when KWallet is not enabled, because // we dropped support for plaintext files, therefore they need to be stored to NetworkManager for (const QString &key : vpnData.keys()) { if (key.endsWith(QLatin1String("-flags"))) { vpnData.insert(key, QString::number((int)secretFlags)); } } vpnSetting->setData(vpnData); settings.insert(setting, vpnSetting->toMap()); connection->update(settings); } } else { if (setting == loadedSettingType) { QVariantMap tmpSetting = settings.value(setting); // Reset flags, we can't save secrets to our secret agent when KWallet is not enabled, because // we dropped support for plaintext files, therefore they need to be stored to NetworkManager for (const QString &key : tmpSetting.keys()) { if (key.endsWith(QLatin1String("-flags"))) { tmpSetting.insert(key, (int)secretFlags); } } // Add loaded secrets from the config file QMap::const_iterator it = secrets.constBegin(); QMap::const_iterator end = secrets.constEnd(); for (; it != end; ++it) { tmpSetting.insert(it.key(), it.value()); } // Replace the old setting with the new one settings.insert(setting, tmpSetting); // Update the connection which re-saves secrets connection->update(settings); } } } } // Remove the group KConfigGroup group(&config, groupName); group.deleteGroup(); } } }