handler.cpp 30.9 KB
Newer Older
Jan Grulich's avatar
Jan Grulich committed
1
/*
Jan Grulich's avatar
Cleanup    
Jan Grulich committed
2
    Copyright 2013-2014 Jan Grulich <jgrulich@redhat.com>
Jan Grulich's avatar
Jan Grulich committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

    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 <http://www.gnu.org/licenses/>.
*/

#include "handler.h"
Jan Grulich's avatar
Jan Grulich committed
22
#include "connectioneditordialog.h"
23
#include "uiutils.h"
24
#include "debug.h"
Jan Grulich's avatar
Jan Grulich committed
25

Jan Grulich's avatar
Jan Grulich committed
26
27
28
29
30
#include <NetworkManagerQt/Manager>
#include <NetworkManagerQt/AccessPoint>
#include <NetworkManagerQt/WiredDevice>
#include <NetworkManagerQt/WirelessDevice>
#include <NetworkManagerQt/Settings>
31
#include <NetworkManagerQt/Setting>
32
#include <NetworkManagerQt/Connection>
33
#include <NetworkManagerQt/Utils>
34
#include <NetworkManagerQt/ConnectionSettings>
35
#include <NetworkManagerQt/GsmSetting>
36
37
#include <NetworkManagerQt/WiredSetting>
#include <NetworkManagerQt/WirelessSetting>
Jan Grulich's avatar
Jan Grulich committed
38
#include <NetworkManagerQt/ActiveConnection>
Martin Kacej's avatar
Martin Kacej committed
39
#include <NetworkManagerQt/Ipv4Setting>
Jan Grulich's avatar
Jan Grulich committed
40

41
42
#include <libnm/nm-vpn-plugin-info.h>

43
#if WITH_MODEMMANAGER_SUPPORT
44
45
#include <ModemManagerQt/Manager>
#include <ModemManagerQt/ModemDevice>
46
#endif
47

48
#include <QDBusError>
49
#include <QDBusMetaType>
50
#include <QDBusPendingReply>
51
#include <QIcon>
52

53
#include <KNotification>
Jan Grulich's avatar
Jan Grulich committed
54
#include <KLocalizedString>
55
#include <KUser>
Jan Grulich's avatar
Jan Grulich committed
56
#include <KProcess>
Jan Grulich's avatar
Jan Grulich committed
57
58
#include <KService>
#include <KServiceTypeTrader>
59
#include <KWindowSystem>
60
#include <KWallet>
Jan Grulich's avatar
Jan Grulich committed
61

62
63
64
65
#define AGENT_SERVICE "org.kde.kded5"
#define AGENT_PATH "/modules/networkmanagement"
#define AGENT_IFACE "org.kde.plasmanetworkmanagement"

66
67
// 10 seconds
#define NM_REQUESTSCAN_LIMIT_RATE 10000
68

69
Handler::Handler(QObject *parent)
Jan Grulich's avatar
Jan Grulich committed
70
    : QObject(parent)
Jan Grulich's avatar
Jan Grulich committed
71
72
    , m_tmpWirelessEnabled(NetworkManager::isWirelessEnabled())
    , m_tmpWwanEnabled(NetworkManager::isWwanEnabled())
Jan Grulich's avatar
Jan Grulich committed
73
{
74
    initKdedModule();
75
76
77
78
79
    QDBusConnection::sessionBus().connect(QStringLiteral(AGENT_SERVICE),
                                            QStringLiteral(AGENT_PATH),
                                            QStringLiteral(AGENT_IFACE),
                                            QStringLiteral("registered"),
                                            this, SLOT(initKdedModule()));
80

81
82
83
84
85
    QDBusConnection::sessionBus().connect(QStringLiteral(AGENT_SERVICE),
                                            QStringLiteral(AGENT_PATH),
                                            QStringLiteral(AGENT_IFACE),
                                            QStringLiteral("secretsError"),
                                            this, SLOT(secretAgentError(QString, QString)));
Jan Grulich's avatar
Jan Grulich committed
86
87
88
89
90
91
}

Handler::~Handler()
{
}

92
void Handler::activateConnection(const QString& connection, const QString& device, const QString& specificObject)
Jan Grulich's avatar
Jan Grulich committed
93
{
94
    NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection);
Jan Grulich's avatar
Jan Grulich committed
95

96
    if (!con) {
97
        qCWarning(PLASMA_NM) << "Not possible to activate this connection";
98
99
        return;
    }
Jan Grulich's avatar
Jan Grulich committed
100
101
102
103

    if (con->settings()->connectionType() == NetworkManager::ConnectionSettings::Vpn) {
        NetworkManager::VpnSetting::Ptr vpnSetting = con->settings()->setting(NetworkManager::Setting::Vpn).staticCast<NetworkManager::VpnSetting>();
        if (vpnSetting) {
104
            qCDebug(PLASMA_NM) << "Checking VPN" << con->name() << "type:" << vpnSetting->serviceType();
105
106
107
108

            bool pluginMissing = false;

            // Check missing plasma-nm VPN plugin
Jan Grulich's avatar
Jan Grulich committed
109
            const KService::List services = KServiceTypeTrader::self()->query("PlasmaNetworkManagement/VpnUiPlugin",
110
                                                                              QString::fromLatin1("[X-NetworkManager-Services]=='%1'").arg(vpnSetting->serviceType()));
111
112
113
114
115
116
117
118
119
120
121
122
            pluginMissing = services.isEmpty();

            // Check missing NetworkManager VPN plugin
            if (!pluginMissing) {
                GSList *plugins = nullptr;
                plugins = nm_vpn_plugin_info_list_load();

                NMVpnPluginInfo *plugin_info = nm_vpn_plugin_info_list_find_by_service(plugins, vpnSetting->serviceType().toStdString().c_str());
                pluginMissing = !plugin_info;
            }

            if (pluginMissing) {
123
                qCWarning(PLASMA_NM) << "VPN" << vpnSetting->serviceType() << "not found, skipping";
124
                KNotification *notification = new KNotification("MissingVpnPlugin", KNotification::CloseOnTimeout, this);
Jan Grulich's avatar
Jan Grulich committed
125
                notification->setComponentName("networkmanagement");
126
127
                notification->setTitle(con->name());
                notification->setText(i18n("Missing VPN plugin"));
128
                notification->setIconName(QStringLiteral("dialog-warning"));
129
                notification->sendEvent();
Jan Grulich's avatar
Jan Grulich committed
130
131
                return;
            }
132

Jan Grulich's avatar
Jan Grulich committed
133
134
        }
    }
Jan Grulich's avatar
Jan Grulich committed
135

136
#if WITH_MODEMMANAGER_SUPPORT
137
138
139
140
141
142
    if (con->settings()->connectionType() == NetworkManager::ConnectionSettings::Gsm) {
        NetworkManager::ModemDevice::Ptr nmModemDevice = NetworkManager::findNetworkInterface(device).objectCast<NetworkManager::ModemDevice>();
        if (nmModemDevice) {
            ModemManager::ModemDevice::Ptr mmModemDevice = ModemManager::findModemDevice(nmModemDevice->udi());
            if (mmModemDevice) {
                ModemManager::Modem::Ptr modem = mmModemDevice->interface(ModemManager::ModemDevice::ModemInterface).objectCast<ModemManager::Modem>();
143
144
145
                NetworkManager::GsmSetting::Ptr gsmSetting = con->settings()->setting(NetworkManager::Setting::Gsm).staticCast<NetworkManager::GsmSetting>();
                if (gsmSetting && gsmSetting->pinFlags() == NetworkManager::Setting::NotSaved &&
                    modem && modem->unlockRequired() > MM_MODEM_LOCK_NONE) {
146
147
148
149
150
151
152
153
154
155
156
                    QDBusInterface managerIface("org.kde.plasmanetworkmanagement", "/org/kde/plasmanetworkmanagement", "org.kde.plasmanetworkmanagement", QDBusConnection::sessionBus(), this);
                    managerIface.call("unlockModem", mmModemDevice->uni());
                    connect(modem.data(), &ModemManager::Modem::unlockRequiredChanged, this, &Handler::unlockRequiredChanged);
                    m_tmpConnectionPath = connection;
                    m_tmpDevicePath = device;
                    m_tmpSpecificPath = specificObject;
                    return;
                }
            }
        }
    }
157
#endif
158

159
160
161
    QDBusPendingReply<QDBusObjectPath> reply = NetworkManager::activateConnection(connection, device, specificObject);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    watcher->setProperty("action", Handler::ActivateConnection);
Jan Grulich's avatar
Jan Grulich committed
162
    watcher->setProperty("connection", con->name());
Lukáš Tinkl's avatar
Lukáš Tinkl committed
163
    connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
164
}
165

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
QString Handler::wifiCode(const QString& connectionPath, const QString& ssid, int _securityType) const
{
    NetworkManager::WirelessSecurityType securityType = static_cast<NetworkManager::WirelessSecurityType>(_securityType);

    QString ret = QStringLiteral("WIFI:S:") + ssid + QLatin1Char(';');
    if (securityType != NetworkManager::NoneSecurity) {
        switch (securityType) {
            case NetworkManager::NoneSecurity:
                break;
            case NetworkManager::StaticWep:
                ret += "T:WEP;";
                break;
            case NetworkManager::WpaPsk:
            case NetworkManager::Wpa2Psk:
                ret += "T:WPA;";
                break;
            default:
            case NetworkManager::DynamicWep:
            case NetworkManager::WpaEap:
            case NetworkManager::Wpa2Eap:
            case NetworkManager::Leap:
                return {};
        }
    }

    NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(connectionPath);
    if(!connection)
        return {};

    const auto key = QStringLiteral("802-11-wireless-security");
    auto reply = connection->secrets(key);

    const auto secret = reply.argumentAt<0>()[key];
    QString pass;
    switch (securityType) {
        case NetworkManager::NoneSecurity:
            break;
        case NetworkManager::WpaPsk:
        case NetworkManager::Wpa2Psk:
            pass = secret["psk"].toString();
            break;
        default:
            return {};
    }
    if (!pass.isEmpty())
        ret += QStringLiteral("P:") + pass + QLatin1Char(';');

    return ret + QLatin1Char(';');
}

Jan Grulich's avatar
Jan Grulich committed
216
void Handler::addAndActivateConnection(const QString& device, const QString& specificObject, const QString& password)
217
{
Jan Grulich's avatar
Jan Grulich committed
218
    NetworkManager::AccessPoint::Ptr ap;
219
    NetworkManager::WirelessDevice::Ptr wifiDev;
Jan Grulich's avatar
Jan Grulich committed
220
    for (const NetworkManager::Device::Ptr &dev : NetworkManager::networkInterfaces()) {
221
        if (dev->type() == NetworkManager::Device::Wifi) {
222
            wifiDev = dev.objectCast<NetworkManager::WirelessDevice>();
223
224
225
            ap = wifiDev->findAccessPoint(specificObject);
            if (ap) {
                break;
226
227
228
229
            }
        }
    }

230
231
    if (!ap) {
        return;
232
233
    }

234
    NetworkManager::ConnectionSettings::Ptr settings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wireless));
235
    settings->setId(ap->ssid());
236
    settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid());
Jan Grulich's avatar
Jan Grulich committed
237
    settings->setAutoconnect(true);
238
    settings->addToPermissions(KUser().loginName(), QString());
239

240
241
    NetworkManager::WirelessSetting::Ptr wifiSetting = settings->setting(NetworkManager::Setting::Wireless).dynamicCast<NetworkManager::WirelessSetting>();
    wifiSetting->setInitialized(true);
242
    wifiSetting = settings->setting(NetworkManager::Setting::Wireless).dynamicCast<NetworkManager::WirelessSetting>();
243
    wifiSetting->setSsid(ap->ssid().toUtf8());
244
    if (ap->mode() == NetworkManager::AccessPoint::Adhoc) {
245
246
        wifiSetting->setMode(NetworkManager::WirelessSetting::Adhoc);
    }
247
248
    NetworkManager::WirelessSecuritySetting::Ptr wifiSecurity = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast<NetworkManager::WirelessSecuritySetting>();

Jan Grulich's avatar
Jan Grulich committed
249
    NetworkManager::WirelessSecurityType securityType = NetworkManager::findBestWirelessSecurity(wifiDev->wirelessCapabilities(), true, (ap->mode() == NetworkManager::AccessPoint::Adhoc), ap->capabilities(), ap->wpaFlags(), ap->rsnFlags());
250

Jan Grulich's avatar
Jan Grulich committed
251
    if (securityType != NetworkManager::NoneSecurity) {
252
253
254
255
        wifiSecurity->setInitialized(true);
        wifiSetting->setSecurity("802-11-wireless-security");
    }

Jan Grulich's avatar
Jan Grulich committed
256
257
258
259
260
    if (securityType == NetworkManager::Leap ||
        securityType == NetworkManager::DynamicWep ||
        securityType == NetworkManager::Wpa2Eap ||
        securityType == NetworkManager::WpaEap) {
        if (securityType == NetworkManager::DynamicWep || securityType == NetworkManager::Leap) {
261
            wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::Ieee8021x);
Jan Grulich's avatar
Jan Grulich committed
262
            if (securityType == NetworkManager::Leap) {
263
264
                wifiSecurity->setAuthAlg(NetworkManager::WirelessSecuritySetting::Leap);
            }
265
266
267
        } else {
            wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap);
        }
268
269
270
        m_tmpConnectionUuid = settings->uuid();
        m_tmpDevicePath = device;
        m_tmpSpecificPath = specificObject;
271

Jan Grulich's avatar
Jan Grulich committed
272
        QPointer<ConnectionEditorDialog> editor = new ConnectionEditorDialog(settings);
273
274
275
        editor->show();
        KWindowSystem::setState(editor->winId(), NET::KeepAbove);
        KWindowSystem::forceActiveWindow(editor->winId());
Jan Grulich's avatar
Jan Grulich committed
276
        connect(editor.data(), &ConnectionEditorDialog::accepted,
Jan Grulich's avatar
Jan Grulich committed
277
278
279
                [editor, this] () {
                    addConnection(editor->setting());
                });
Jan Grulich's avatar
Jan Grulich committed
280
        connect(editor.data(), &ConnectionEditorDialog::finished,
Jan Grulich's avatar
Jan Grulich committed
281
282
283
284
285
286
287
                [editor] () {
                    if (editor) {
                        editor->deleteLater();
                    }
                });
        editor->setModal(true);
        editor->show();
288
    } else {
Jan Grulich's avatar
Jan Grulich committed
289
        if (securityType == NetworkManager::StaticWep) {
290
291
            wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::Wep);
            wifiSecurity->setWepKey0(password);
292
293
294
            if (KWallet::Wallet::isEnabled()) {
                wifiSecurity->setWepKeyFlags(NetworkManager::Setting::AgentOwned);
            }
295
        } else {
296
297
298
299
300
            if (ap->mode() == NetworkManager::AccessPoint::Adhoc) {
                wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone);
            } else {
                wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk);
            }
301
            wifiSecurity->setPsk(password);
302
303
304
            if (KWallet::Wallet::isEnabled()) {
                wifiSecurity->setPskFlags(NetworkManager::Setting::AgentOwned);
            }
305
        }
306
307
308
        QDBusPendingReply<QDBusObjectPath> reply = NetworkManager::addAndActivateConnection(settings->toMap(), device, specificObject);
        QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
        watcher->setProperty("action", Handler::AddAndActivateConnection);
Jan Grulich's avatar
Jan Grulich committed
309
        watcher->setProperty("connection", settings->name());
Lukáš Tinkl's avatar
Lukáš Tinkl committed
310
        connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
311
    }
Jan Grulich's avatar
Jan Grulich committed
312

313
    settings.clear();
Jan Grulich's avatar
Jan Grulich committed
314
315
}

316
317
318
319
320
321
322
323
324
void Handler::addConnection(const NMVariantMapMap& map)
{
    QDBusPendingReply<QDBusObjectPath> reply = NetworkManager::addConnection(map);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    watcher->setProperty("action", AddConnection);
    watcher->setProperty("connection", map.value("connection").value("id"));
    connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
}

325
void Handler::deactivateConnection(const QString& connection, const QString& device)
Jan Grulich's avatar
Jan Grulich committed
326
{
327
    NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection);
Jan Grulich's avatar
Jan Grulich committed
328

329
    if (!con) {
330
        qCWarning(PLASMA_NM) << "Not possible to deactivate this connection";
331
332
333
        return;
    }

334
    QDBusPendingReply<> reply;
Jan Grulich's avatar
Jan Grulich committed
335
    for (const NetworkManager::ActiveConnection::Ptr &active : NetworkManager::activeConnections()) {
336
337
        if (active->uuid() == con->uuid() && ((!active->devices().isEmpty() && active->devices().first() == device) ||
                                               active->vpn())) {
338
            if (active->vpn()) {
339
                reply = NetworkManager::deactivateConnection(active->path());
340
            } else {
341
                NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(active->devices().first());
Jan Grulich's avatar
Jan Grulich committed
342
                if (device) {
343
                    reply = device->disconnectInterface();
Jan Grulich's avatar
Jan Grulich committed
344
                }
345
            }
Jan Grulich's avatar
Jan Grulich committed
346
347
        }
    }
348
349
350

    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    watcher->setProperty("action", Handler::DeactivateConnection);
Lukáš Tinkl's avatar
Lukáš Tinkl committed
351
    connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
Jan Grulich's avatar
Jan Grulich committed
352
353
}

354
355
void Handler::disconnectAll()
{
Jan Grulich's avatar
Jan Grulich committed
356
    for (const NetworkManager::Device::Ptr &device : NetworkManager::networkInterfaces()) {
357
358
359
360
        device->disconnectInterface();
    }
}

Jan Grulich's avatar
Jan Grulich committed
361
362
363
364
365
void Handler::enableAirplaneMode(bool enable)
{
    if (enable) {
        m_tmpWirelessEnabled = NetworkManager::isWirelessEnabled();
        m_tmpWwanEnabled = NetworkManager::isWwanEnabled();
366
        enableBluetooth(false);
Jan Grulich's avatar
Jan Grulich committed
367
368
369
        enableWireless(false);
        enableWwan(false);
    } else {
370
        enableBluetooth(true);
Jan Grulich's avatar
Jan Grulich committed
371
372
373
374
375
376
377
378
379
        if (m_tmpWirelessEnabled) {
            enableWireless(true);
        }
        if (m_tmpWwanEnabled) {
            enableWwan(true);
        }
    }
}

380
381
382
383
384
385
386
387
388
389
390
void Handler::enableBluetooth(bool enable)
{
    qDBusRegisterMetaType< QMap<QDBusObjectPath, NMVariantMapMap > >();

    QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
    QDBusPendingReply<QMap<QDBusObjectPath, NMVariantMapMap> > reply = QDBusConnection::systemBus().asyncCall(message);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
        [this, enable] (QDBusPendingCallWatcher *watcher) {
            QDBusPendingReply<QMap<QDBusObjectPath, NMVariantMapMap> > reply = *watcher;
            if (reply.isValid()) {
Jan Grulich's avatar
Jan Grulich committed
391
                for (const QDBusObjectPath &path : reply.value().keys()) {
392
393
394
395
396
397
398
399
400
                    const QString objPath = path.path();
                    qCDebug(PLASMA_NM) << "inspecting path" << objPath;
                    const QStringList interfaces = reply.value().value(path).keys();
                    qCDebug(PLASMA_NM) << "interfaces:" << interfaces;
                    if (interfaces.contains("org.bluez.Adapter1")) {
                        // We need to check previous state first
                        if (!enable) {
                            QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", objPath, "org.freedesktop.DBus.Properties", "Get");
                            QList<QVariant> arguments;
401
402
                            arguments << QLatin1String("org.bluez.Adapter1");
                            arguments << QLatin1String("Powered");
403
404
405
406
407
408
409
410
411
412
                            message.setArguments(arguments);
                            QDBusPendingReply<QVariant> getReply = QDBusConnection::systemBus().asyncCall(message);
                            QDBusPendingCallWatcher *getWatcher = new QDBusPendingCallWatcher(getReply, this);
                                connect(getWatcher, &QDBusPendingCallWatcher::finished,
                                    [this, objPath] (QDBusPendingCallWatcher *watcher) {
                                        QDBusPendingReply<QVariant> reply = *watcher;
                                        if (reply.isValid()) {
                                            m_bluetoothAdapters.insert(objPath, reply.value().toBool());
                                            QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", objPath, "org.freedesktop.DBus.Properties", "Set");
                                            QList<QVariant> arguments;
413
414
                                            arguments << QLatin1String("org.bluez.Adapter1");
                                            arguments << QLatin1String("Powered");
415
416
417
418
                                            arguments << QVariant::fromValue(QDBusVariant(QVariant(false)));
                                            message.setArguments(arguments);
                                            QDBusConnection::systemBus().asyncCall(message);
                                        }
Jan Grulich's avatar
Jan Grulich committed
419
                                        watcher->deleteLater();
420
421
422
423
                                    });
                        } else if (enable && m_bluetoothAdapters.value(objPath)) {
                            QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", objPath, "org.freedesktop.DBus.Properties", "Set");
                            QList<QVariant> arguments;
424
425
                            arguments << QLatin1String("org.bluez.Adapter1");
                            arguments << QLatin1String("Powered");
426
427
428
429
430
431
432
                            arguments << QVariant::fromValue(QDBusVariant(QVariant(enable)));
                            message.setArguments(arguments);
                            QDBusConnection::systemBus().asyncCall(message);
                        }
                    }
                }
            }
Jan Grulich's avatar
Jan Grulich committed
433
            watcher->deleteLater();
434
435
436
        });
}

Jan Grulich's avatar
Jan Grulich committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
void Handler::enableNetworking(bool enable)
{
    NetworkManager::setNetworkingEnabled(enable);
}

void Handler::enableWireless(bool enable)
{
    NetworkManager::setWirelessEnabled(enable);
}

void Handler::enableWwan(bool enable)
{
    NetworkManager::setWwanEnabled(enable);
}

452
453
void Handler::removeConnection(const QString& connection)
{
454
    NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection);
455

Jan Grulich's avatar
Jan Grulich committed
456
    if (!con || con->uuid().isEmpty()) {
457
        qCWarning(PLASMA_NM) << "Not possible to remove connection " << connection;
458
459
460
        return;
    }

461
    // Remove slave connections
Jan Grulich's avatar
Jan Grulich committed
462
    for (const NetworkManager::Connection::Ptr &connection : NetworkManager::listConnections()) {
463
        NetworkManager::ConnectionSettings::Ptr settings = connection->settings();
464
        if (settings->master() == con->uuid()) {
465
            connection->remove();
466
467
468
        }
    }

469
470
471
    QDBusPendingReply<> reply = con->remove();
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    watcher->setProperty("action", Handler::RemoveConnection);
472
    watcher->setProperty("connection", con->name());
Lukáš Tinkl's avatar
Lukáš Tinkl committed
473
    connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
474
}
Jan Grulich's avatar
Jan Grulich committed
475

476
477
478
479
480
481
482
483
484
void Handler::updateConnection(const NetworkManager::Connection::Ptr& connection, const NMVariantMapMap& map)
{
    QDBusPendingReply<> reply = connection->update(map);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
    watcher->setProperty("action", UpdateConnection);
    watcher->setProperty("connection", connection->name());
    connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
}

485
void Handler::requestScan(const QString &interface)
Jan Grulich's avatar
Jan Grulich committed
486
{
Jan Grulich's avatar
Jan Grulich committed
487
    for (NetworkManager::Device::Ptr device : NetworkManager::networkInterfaces()) {
Jan Grulich's avatar
Jan Grulich committed
488
489
        if (device->type() == NetworkManager::Device::Wifi) {
            NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast<NetworkManager::WirelessDevice>();
490
491

            if (wifiDevice && wifiDevice->state() != NetworkManager::WirelessDevice::Unavailable) {
492
493
494
                if (!interface.isEmpty() && interface != wifiDevice->interfaceName()) {
                    continue;
                }
495

496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
                if (!checkRequestScanRateLimit(wifiDevice)) {
                    QDateTime now = QDateTime::currentDateTime();
                    // for NM < 1.12, lastScan is not available
                    QDateTime lastScan = wifiDevice->lastScan();
                    QDateTime lastRequestScan = wifiDevice->lastRequestScan();
                    // Compute the next time we can run a scan
                    int timeout = NM_REQUESTSCAN_LIMIT_RATE;
                    if (lastScan.isValid() && lastScan.msecsTo(now) < NM_REQUESTSCAN_LIMIT_RATE) {
                        timeout = NM_REQUESTSCAN_LIMIT_RATE - lastScan.msecsTo(now);
                    } else if (lastRequestScan.isValid() && lastRequestScan.msecsTo(now) < NM_REQUESTSCAN_LIMIT_RATE) {
                        timeout = NM_REQUESTSCAN_LIMIT_RATE - lastRequestScan.msecsTo(now);
                    }
                    qCDebug(PLASMA_NM) << "Rescheduling a request scan for" << wifiDevice->interfaceName() << "in" << timeout;
                    scheduleRequestScan(wifiDevice->interfaceName(), timeout);

                    if (!interface.isEmpty()) {
                        return;
                    }
                    continue;
                } else if (m_wirelessScanRetryTimer.contains(interface)){
                    m_wirelessScanRetryTimer.value(interface)->stop();
                    delete m_wirelessScanRetryTimer.take(interface);
                }

520
                qCDebug(PLASMA_NM) << "Requesting wifi scan on device" << wifiDevice->interfaceName();
521
522
523
                QDBusPendingReply<> reply = wifiDevice->requestScan();
                QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
                watcher->setProperty("action", Handler::RequestScan);
524
                watcher->setProperty("interface", wifiDevice->interfaceName());
525
                connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished);
Jan Grulich's avatar
Jan Grulich committed
526
527
528
529
            }
        }
    }
}
530

531
bool Handler::checkRequestScanRateLimit(const NetworkManager::WirelessDevice::Ptr &wifiDevice)
532
{
533
534
535
536
537
538
539
540
541
542
543
544
545
    QDateTime now = QDateTime::currentDateTime();
    QDateTime lastScan = wifiDevice->lastScan();
    QDateTime lastRequestScan = wifiDevice->lastRequestScan();

    // if the last scan finished within the last 10 seconds
    bool ret = lastScan.isValid() && lastScan.msecsTo(now) < NM_REQUESTSCAN_LIMIT_RATE;
    // or if the last Request was sent within the last 10 seconds
    ret |= lastRequestScan.isValid() && lastRequestScan.msecsTo(now) < NM_REQUESTSCAN_LIMIT_RATE;
    // skip the request scan
    if (ret) {
        qCDebug(PLASMA_NM) << "Last scan finished " << lastScan.msecsTo(now) << "ms ago and last request scan was sent "
                           << lastRequestScan.msecsTo(now) << "ms ago, Skipping scanning interface:" << wifiDevice->interfaceName();
        return false;
546
    }
547
548
    return true;
}
549

550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
void Handler::scheduleRequestScan(const QString &interface, int timeout)
{
    QTimer *timer;
    if (!m_wirelessScanRetryTimer.contains(interface)) {
        // create a timer for the interface
        timer = new QTimer();
        timer->setSingleShot(true);
        m_wirelessScanRetryTimer.insert(interface, timer);
        auto retryAction = [this, interface]() {
            requestScan(interface);
        };
        connect(timer, &QTimer::timeout, this, retryAction);
    } else {
        // set the new value for an existing timer
        timer = m_wirelessScanRetryTimer.value(interface);
        if (timer->isActive()) {
            timer->stop();
        }
    }
569

570
571
572
573
574
575
576
577
578
    // +1 ms is added to avoid having the scan being rejetted by nm
    // because it is run at the exact last millisecond of the requestScan threshold
    timer->setInterval(timeout + 1);
    timer->start();
}

void Handler::scanRequestFailed(const QString &interface)
{
    scheduleRequestScan(interface, 2000);
579
580
}

581
582
void Handler::initKdedModule()
{
583
584
585
586
587
    QDBusMessage initMsg = QDBusMessage::createMethodCall(QStringLiteral(AGENT_SERVICE),
                                                          QStringLiteral(AGENT_PATH),
                                                          QStringLiteral(AGENT_IFACE),
                                                          QStringLiteral("init"));
    QDBusConnection::sessionBus().send(initMsg);
588
589
}

590
591
592
593
594
595
596
void Handler::secretAgentError(const QString &connectionPath, const QString &message)
{
    // If the password was wrong, forget it
    removeConnection(connectionPath);
    emit connectionActivationFailed(connectionPath, message);
}

597
598
void Handler::replyFinished(QDBusPendingCallWatcher * watcher)
{
599
    QDBusPendingReply<> reply = *watcher;
600
    if (reply.isError() || !reply.isValid()) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
601
        KNotification *notification = nullptr;
602
        QString error = reply.error().message();
Jan Grulich's avatar
Jan Grulich committed
603
        Handler::HandlerAction action = (Handler::HandlerAction)watcher->property("action").toUInt();
604
605
        switch (action) {
            case Handler::ActivateConnection:
Jan Grulich's avatar
Jan Grulich committed
606
607
                notification = new KNotification("FailedToActivateConnection", KNotification::CloseOnTimeout, this);
                notification->setTitle(i18n("Failed to activate %1", watcher->property("connection").toString()));
608
609
                break;
            case Handler::AddAndActivateConnection:
Jan Grulich's avatar
Jan Grulich committed
610
611
                notification = new KNotification("FailedToAddConnection", KNotification::CloseOnTimeout, this);
                notification->setTitle(i18n("Failed to add %1", watcher->property("connection").toString()));
612
                break;
613
614
615
616
            case Handler::AddConnection:
                notification = new KNotification("FailedToAddConnection", KNotification::CloseOnTimeout, this);
                notification->setTitle(i18n("Failed to add connection %1", watcher->property("connection").toString()));
                break;
617
618
619
620
621
622
623
624
            case Handler::DeactivateConnection:
                notification = new KNotification("FailedToDeactivateConnection", KNotification::CloseOnTimeout, this);
                notification->setTitle(i18n("Failed to deactivate %1", watcher->property("connection").toString()));
                break;
            case Handler::RemoveConnection:
                notification = new KNotification("FailedToRemoveConnection", KNotification::CloseOnTimeout, this);
                notification->setTitle(i18n("Failed to remove %1", watcher->property("connection").toString()));
                break;
625
626
627
            case Handler::UpdateConnection:
                notification = new KNotification("FailedToUpdateConnection", KNotification::CloseOnTimeout, this);
                notification->setTitle(i18n("Failed to update connection %1", watcher->property("connection").toString()));
Jan Grulich's avatar
Jan Grulich committed
628
                break;
629
630
631
            case Handler::RequestScan:
            {
                const QString interface = watcher->property("interface").toString();
632
                qCWarning(PLASMA_NM) << "Wireless scan on" << interface << "failed:" << error;
633
634
635
                scanRequestFailed(interface);
                break;
            }
636
637
638
            default:
                break;
        }
Jan Grulich's avatar
Jan Grulich committed
639
640

        if (notification) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
641
            notification->setComponentName("networkmanagement");
Jan Grulich's avatar
Jan Grulich committed
642
            notification->setText(error);
643
            notification->setIconName(QStringLiteral("dialog-warning"));
Jan Grulich's avatar
Jan Grulich committed
644
645
            notification->sendEvent();
        }
646
    } else {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
647
        KNotification *notification = nullptr;
648
649
650
        Handler::HandlerAction action = (Handler::HandlerAction)watcher->property("action").toUInt();

        switch (action) {
651
652
653
654
            case Handler::AddConnection:
                notification = new KNotification("ConnectionAdded", KNotification::CloseOnTimeout, this);
                notification->setText(i18n("Connection %1 has been added", watcher->property("connection").toString()));
                break;
655
656
657
658
            case Handler::RemoveConnection:
                notification = new KNotification("ConnectionRemoved", KNotification::CloseOnTimeout, this);
                notification->setText(i18n("Connection %1 has been removed", watcher->property("connection").toString()));
                break;
659
660
661
            case Handler::UpdateConnection:
                notification = new KNotification("ConnectionUpdated", KNotification::CloseOnTimeout, this);
                notification->setText(i18n("Connection %1 has been updated", watcher->property("connection").toString()));
Jan Grulich's avatar
Jan Grulich committed
662
                break;
663
664
665
            case Handler::RequestScan:
                qCDebug(PLASMA_NM) << "Wireless scan on" << watcher->property("interface").toString() << "succeeded";
                break;
666
667
668
669
670
            default:
                break;
        }

        if (notification) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
671
672
            notification->setComponentName("networkmanagement");
            notification->setTitle(watcher->property("connection").toString());
673
            notification->setIconName(QStringLiteral("dialog-information"));
674
675
            notification->sendEvent();
        }
676
    }
Lamarque Souza's avatar
Lamarque Souza committed
677
678

    watcher->deleteLater();
679
}
680

681
#if WITH_MODEMMANAGER_SUPPORT
682
683
684
685
686
687
void Handler::unlockRequiredChanged(MMModemLock modemLock)
{
    if (modemLock == MM_MODEM_LOCK_NONE) {
        activateConnection(m_tmpConnectionPath, m_tmpDevicePath, m_tmpSpecificPath);
    }
}
688
#endif
689