summaryrefslogtreecommitdiff
path: root/raveos-calamares-module/wifi/NetworkManager.cpp
blob: cb8869825743c1f7c12954b7dff476181881f242 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#include "NetworkManager.h"

#include <QDBusInterface>
#include <QDBusReply>
#include <QDBusObjectPath>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QDBusMessage>
#include <QVariantMap>
#include <QTimer>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QDateTime>

typedef QMap<QString, QVariantMap> NMConnectionSettings;

static const QString LOG_FILE = "/tmp/calamares-wifi.log";

static void wifiLog(const QString& message)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString logLine = QString("[%1] %2\n").arg(timestamp, message);

    QFile file(LOG_FILE);
    if (file.open(QIODevice::Append | QIODevice::Text))
    {
        QTextStream stream(&file);
        stream << logLine;
        file.close();
    }

    qDebug().noquote() << "[WiFi Module]" << message;
}

NetworkManager::NetworkManager(QObject* parent)
    : QObject(parent)
{
    qDBusRegisterMetaType<NMConnectionSettings>();

    QFile file(LOG_FILE);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream stream(&file);
        stream << "=== Calamares WiFi Module Log ===\n";
        file.close();
    }

    wifiLog("NetworkManager initialized");
    scan();
    updateConnectionState();

    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &NetworkManager::updateConnectionState);
    timer->start(3000);
}

QStringList NetworkManager::networks() const
{
    return m_networks;
}

bool NetworkManager::isConnected() const
{
    return m_connected;
}

void NetworkManager::updateConnectionState()
{
    QDBusInterface nm(
        "org.freedesktop.NetworkManager",
        "/org/freedesktop/NetworkManager",
        "org.freedesktop.NetworkManager",
        QDBusConnection::systemBus()
    );

    if (!nm.isValid())
    {
        return;
    }

    bool newState = false;

    QDBusObjectPath primary =
        nm.property("PrimaryConnection").value<QDBusObjectPath>();

    if (primary.path() != "/" && !primary.path().isEmpty())
    {
        newState = true;
    }

    if (!newState)
    {
        QDBusReply<QList<QDBusObjectPath>> devices = nm.call("GetDevices");
        if (devices.isValid())
        {
            for (const auto& dev : devices.value())
            {
                QDBusInterface devProps(
                    "org.freedesktop.NetworkManager",
                    dev.path(),
                    "org.freedesktop.DBus.Properties",
                    QDBusConnection::systemBus()
                );

                QDBusReply<QVariant> typeReply = devProps.call(
                    "Get",
                    "org.freedesktop.NetworkManager.Device",
                    "DeviceType"
                );

                if (typeReply.isValid() && typeReply.value().toUInt() == 2)
                {
                    QDBusReply<QVariant> stateReply = devProps.call(
                        "Get",
                        "org.freedesktop.NetworkManager.Device",
                        "State"
                    );

                    if (stateReply.isValid())
                    {
                        uint state = stateReply.value().toUInt();
                        wifiLog(QString("WiFi device state: %1").arg(state));
                        if (state == 100)
                        {
                            newState = true;
                            break;
                        }
                    }
                }
            }
        }
    }

    if (newState != m_connected)
    {
        m_connected = newState;
        wifiLog(QString("Connection state changed to: %1").arg(newState ? "connected" : "disconnected"));
        emit connectionChanged();
    }
}

void NetworkManager::scan()
{
    m_networks.clear();
    wifiLog("Starting scan...");

    QDBusInterface nm(
        "org.freedesktop.NetworkManager",
        "/org/freedesktop/NetworkManager",
        "org.freedesktop.NetworkManager",
        QDBusConnection::systemBus()
    );

    if (!nm.isValid())
    {
        wifiLog("NetworkManager DBus interface not valid!");
        emit networksChanged();
        return;
    }

    QDBusReply<QList<QDBusObjectPath>> devices = nm.call("GetDevices");

    if (!devices.isValid())
    {
        wifiLog(QString("GetDevices failed: %1").arg(devices.error().message()));
        emit networksChanged();
        return;
    }

    wifiLog(QString("Found %1 devices").arg(devices.value().size()));

    bool foundWireless = false;
    for (const auto& dev : devices.value())
    {
        QDBusInterface devProps(
            "org.freedesktop.NetworkManager",
            dev.path(),
            "org.freedesktop.DBus.Properties",
            QDBusConnection::systemBus()
        );

        QDBusReply<QVariant> typeReply = devProps.call(
            "Get",
            "org.freedesktop.NetworkManager.Device",
            "DeviceType"
        );

        uint deviceType = typeReply.isValid() ? typeReply.value().toUInt() : 0;
        wifiLog(QString("Device %1 type: %2").arg(dev.path()).arg(deviceType));

        if (deviceType != 2)  // Not WiFi
            continue;

        foundWireless = true;
        wifiLog(QString("Found wireless device: %1").arg(dev.path()));

        QDBusInterface wirelessIf(
            "org.freedesktop.NetworkManager",
            dev.path(),
            "org.freedesktop.NetworkManager.Device.Wireless",
            QDBusConnection::systemBus()
        );

        QDBusMessage reply = wirelessIf.call("RequestScan", QVariantMap());
        if (reply.type() == QDBusMessage::ErrorMessage) {
            wifiLog(QString("Scan request failed: %1").arg(reply.errorMessage()));
        } else {
            wifiLog("Scan request sent successfully");
        }
    }

    if (!foundWireless) {
        wifiLog("No wireless devices found!");
    }

    QTimer::singleShot(2000, this, &NetworkManager::fetchAccessPoints);
}

void NetworkManager::fetchAccessPoints()
{
    m_networks.clear();
    wifiLog("Fetching access points...");

    QDBusInterface nm(
        "org.freedesktop.NetworkManager",
        "/org/freedesktop/NetworkManager",
        "org.freedesktop.NetworkManager",
        QDBusConnection::systemBus()
    );

    if (!nm.isValid())
    {
        wifiLog("NM interface not valid in fetchAccessPoints");
        emit networksChanged();
        return;
    }

    QDBusReply<QList<QDBusObjectPath>> devices = nm.call("GetDevices");

    if (!devices.isValid())
    {
        wifiLog("GetDevices failed in fetchAccessPoints");
        emit networksChanged();
        return;
    }

    for (const auto& dev : devices.value())
    {
        QDBusInterface devProps(
            "org.freedesktop.NetworkManager",
            dev.path(),
            "org.freedesktop.DBus.Properties",
            QDBusConnection::systemBus()
        );

        QDBusReply<QVariant> typeReply = devProps.call(
            "Get",
            "org.freedesktop.NetworkManager.Device",
            "DeviceType"
        );

        if (!typeReply.isValid() || typeReply.value().toUInt() != 2)
            continue;  // Not WiFi

        QDBusInterface wirelessIf(
            "org.freedesktop.NetworkManager",
            dev.path(),
            "org.freedesktop.NetworkManager.Device.Wireless",
            QDBusConnection::systemBus()
        );

        QDBusReply<QList<QDBusObjectPath>> aps =
            wirelessIf.call("GetAccessPoints");

        if (!aps.isValid()) {
            wifiLog(QString("GetAccessPoints failed: %1").arg(aps.error().message()));
            continue;
        }

        wifiLog(QString("Found %1 access points on device %2").arg(aps.value().size()).arg(dev.path()));

        for (const auto& ap : aps.value())
        {
            QDBusInterface apIf(
                "org.freedesktop.NetworkManager",
                ap.path(),
                "org.freedesktop.NetworkManager.AccessPoint",
                QDBusConnection::systemBus()
            );

            QByteArray ssidRaw = apIf.property("Ssid").toByteArray();
            QString ssid = QString::fromUtf8(ssidRaw);

            uint frequency = apIf.property("Frequency").toUInt();
            QString band = (frequency > 4000) ? "5GHz" : "2.4GHz";

            wifiLog(QString("Found SSID: %1 (%2, %3 MHz)").arg(ssid, band).arg(frequency));

            if (!ssid.isEmpty() && !m_networks.contains(ssid))
                m_networks << ssid;
        }
    }

    m_networks.sort(Qt::CaseInsensitive);

    wifiLog(QString("Total networks found: %1").arg(m_networks.size()));
    emit networksChanged();
}

void NetworkManager::connectTo(const QString& ssid, const QString& password)
{
    wifiLog(QString("Connecting to: %1").arg(ssid));

    QDBusInterface nm(
        "org.freedesktop.NetworkManager",
        "/org/freedesktop/NetworkManager",
        "org.freedesktop.NetworkManager",
        QDBusConnection::systemBus()
    );

    if (!nm.isValid())
    {
        wifiLog("NM interface not valid for connection");
        return;
    }

    QDBusReply<QList<QDBusObjectPath>> devices = nm.call("GetDevices");
    if (!devices.isValid())
    {
        wifiLog(QString("GetDevices failed: %1").arg(devices.error().message()));
        return;
    }

    QDBusObjectPath wirelessDevice("/");
    QDBusObjectPath accessPoint("/");
    uint apFlags = 0;
    uint apWpaFlags = 0;
    uint apRsnFlags = 0;

    for (const auto& dev : devices.value())
    {
        QDBusInterface devProps(
            "org.freedesktop.NetworkManager",
            dev.path(),
            "org.freedesktop.DBus.Properties",
            QDBusConnection::systemBus()
        );

        QDBusReply<QVariant> typeReply = devProps.call(
            "Get",
            "org.freedesktop.NetworkManager.Device",
            "DeviceType"
        );

        if (typeReply.isValid() && typeReply.value().toUInt() == 2)
        {
            wirelessDevice = dev;
            wifiLog(QString("Using wireless device: %1").arg(dev.path()));

            QDBusInterface wirelessIf(
                "org.freedesktop.NetworkManager",
                dev.path(),
                "org.freedesktop.NetworkManager.Device.Wireless",
                QDBusConnection::systemBus()
            );

            QDBusReply<QList<QDBusObjectPath>> aps = wirelessIf.call("GetAccessPoints");
            if (aps.isValid())
            {
                for (const auto& ap : aps.value())
                {
                    QDBusInterface apIf(
                        "org.freedesktop.NetworkManager",
                        ap.path(),
                        "org.freedesktop.NetworkManager.AccessPoint",
                        QDBusConnection::systemBus()
                    );

                    QByteArray apSsid = apIf.property("Ssid").toByteArray();
                    if (QString::fromUtf8(apSsid) == ssid)
                    {
                        accessPoint = ap;
                        apFlags = apIf.property("Flags").toUInt();
                        apWpaFlags = apIf.property("WpaFlags").toUInt();
                        apRsnFlags = apIf.property("RsnFlags").toUInt();
                        wifiLog(QString("Found access point: %1").arg(ap.path()));
                        wifiLog(QString("AP Flags: 0x%1, WpaFlags: 0x%2, RsnFlags: 0x%3")
                            .arg(apFlags, 0, 16).arg(apWpaFlags, 0, 16).arg(apRsnFlags, 0, 16));
                        break;
                    }
                }
            }
            break;
        }
    }

    if (wirelessDevice.path() == "/" || wirelessDevice.path().isEmpty())
    {
        wifiLog("No wireless device found!");
        return;
    }


    bool apSupportsPsk = ((apWpaFlags & 0x100) != 0) || ((apRsnFlags & 0x100) != 0);
    bool apSupportsSae = (apRsnFlags & 0x400) != 0;  // WPA3
    bool apSupportsEnterprise = ((apWpaFlags & 0x200) != 0) || ((apRsnFlags & 0x200) != 0);
    bool apIsOpen = (apFlags == 0) && (apWpaFlags == 0) && (apRsnFlags == 0);

    bool apHasPrivacy = (apFlags & 0x1) != 0;

    wifiLog(QString("Security detection: PSK=%1, SAE=%2, Enterprise=%3, Open=%4, Privacy=%5")
        .arg(apSupportsPsk).arg(apSupportsSae).arg(apSupportsEnterprise).arg(apIsOpen).arg(apHasPrivacy));

    QVariantMap connection;
    connection["type"] = QString("802-11-wireless");
    connection["id"] = ssid;
    connection["autoconnect"] = true;

    QVariantMap wifi;
    wifi["ssid"] = ssid.toUtf8();
    wifi["mode"] = QString("infrastructure");

    bool isHiddenNetwork = (accessPoint.path() == "/" || accessPoint.path().isEmpty());
    if (isHiddenNetwork)
    {
        wifi["hidden"] = true;
        wifiLog("Treating as hidden network");
    }

    NMConnectionSettings settings;
    settings["connection"] = connection;

    QVariantMap ipv4;
    ipv4["method"] = QString("auto");
    settings["ipv4"] = ipv4;

    QVariantMap ipv6;
    ipv6["method"] = QString("auto");
    settings["ipv6"] = ipv6;

    if (!password.isEmpty() && (apSupportsPsk || apSupportsSae || isHiddenNetwork))
    {
        QVariantMap wifiSecurity;

        if (apSupportsSae && !apSupportsPsk)
        {
            wifiLog("Using WPA3-SAE security");
            wifiSecurity["key-mgmt"] = QString("sae");
            wifiSecurity["psk"] = password;
            wifiSecurity["pmf"] = 3;
        }
        else if (apSupportsPsk)
        {
            if (apSupportsSae)
            {
                wifiLog("Using WPA3-SAE (transition mode - both PSK and SAE available)");
                wifiSecurity["key-mgmt"] = QString("sae");
                wifiSecurity["psk"] = password;
                wifiSecurity["pmf"] = 3;  // Required for SAE
            }
            else
            {
                wifiLog("Using WPA-PSK security");
                wifiSecurity["key-mgmt"] = QString("wpa-psk");
                wifiSecurity["psk"] = password;
            }
        }
        else if (isHiddenNetwork)
        {
            wifiLog("Hidden network with password, assuming WPA-PSK");
            wifiSecurity["key-mgmt"] = QString("wpa-psk");
            wifiSecurity["psk"] = password;
        }

        wifi["security"] = QString("802-11-wireless-security");
        settings["802-11-wireless"] = wifi;
        settings["802-11-wireless-security"] = wifiSecurity;
    }
    else if (apSupportsEnterprise)
    {
        wifiLog("WARNING: Enterprise (802.1X) networks are not supported by this simple connector");
        return;
    }
    else if (apIsOpen || (!apHasPrivacy && !apSupportsPsk && !apSupportsSae))
    {
        wifiLog("Connecting to open network (no security)");
        settings["802-11-wireless"] = wifi;
    }
    else if (!password.isEmpty() && !apSupportsPsk && !apSupportsSae)
    {
        wifiLog("WARNING: Password provided but AP does not support PSK/SAE authentication!");
        wifiLog("Attempting to connect as open network...");
        settings["802-11-wireless"] = wifi;
    }
    else
    {
        wifiLog("No password provided, treating as open network");
        settings["802-11-wireless"] = wifi;
    }

    wifiLog("Calling AddAndActivateConnection...");

    QDBusMessage msg = QDBusMessage::createMethodCall(
        "org.freedesktop.NetworkManager",
        "/org/freedesktop/NetworkManager",
        "org.freedesktop.NetworkManager",
        "AddAndActivateConnection"
    );

    QDBusArgument settingsArg;
    settingsArg.beginMap(QMetaType::fromType<QString>(), QMetaType::fromType<QVariantMap>());
    for (auto it = settings.constBegin(); it != settings.constEnd(); ++it)
    {
        settingsArg.beginMapEntry();
        settingsArg << it.key() << it.value();
        settingsArg.endMapEntry();
    }
    settingsArg.endMap();

    msg << QVariant::fromValue(settingsArg);
    msg << QVariant::fromValue(wirelessDevice);
    msg << QVariant::fromValue(accessPoint);

    QDBusMessage reply = QDBusConnection::systemBus().call(msg);

    if (reply.type() == QDBusMessage::ErrorMessage)
    {
        wifiLog(QString("Connection failed: %1 - %2").arg(reply.errorName(), reply.errorMessage()));
        emit connectionFailed(reply.errorMessage());
    }
    else
    {
        wifiLog("Connection initiated successfully");
        m_lastConnectedSsid = ssid;
        m_lastConnectedPassword = password;
        wifiLog(QString("Stored credentials - SSID: '%1', Password length: %2").arg(m_lastConnectedSsid).arg(m_lastConnectedPassword.length()));

        if (apSupportsSae && !apSupportsPsk)
        {
            m_lastSecurityType = "sae";
        }
        else if (apSupportsPsk && apSupportsSae)
        {
            m_lastSecurityType = "sae";  // Transition mode, we used SAE
        }
        else if (apSupportsPsk)
        {
            m_lastSecurityType = "wpa-psk";
        }
        else
        {
            m_lastSecurityType = "";  // Open network
        }
        wifiLog(QString("Stored security type: '%1'").arg(m_lastSecurityType));


        m_connectionCheckCount = 0;
        startConnectionCheck();
    }
}

void NetworkManager::startConnectionCheck()
{
    m_connectionCheckCount++;
    wifiLog(QString("Connection check attempt %1/10").arg(m_connectionCheckCount));

    updateConnectionState();

    if (m_connected)
    {
        wifiLog("Connection confirmed!");
        return;
    }

    if (m_connectionCheckCount < 10)
    {
        QTimer::singleShot(1000, this, &NetworkManager::startConnectionCheck);
    }
    else
    {
        wifiLog("Connection check timeout - connection may have failed");
        emit connectionFailed("Connection timeout");
    }
}