summaryrefslogtreecommitdiff
path: root/ui/qt5/netsimplewifipage.cc
blob: 6d0a1bd403b9fba6bcc39547b73fa4dc09e381a2 (plain) (blame)
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
/*
 * netsimplewifipage.cc - Implementation of the UI.Network.Wireless page
 * horizon-qt5, the Qt 5 user interface for
 * Project Horizon
 *
 * Copyright (c) 2019-2020 Adélie Linux and contributors.  All rights reserved.
 * This code is licensed under the AGPL 3.0 license, as noted in the
 * LICENSE-code file in the root directory of this repository.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

#include "netsimplewifipage.hh"
#include "customwifidialog.hh"
#include "netdhcppage.hh"

#include <assert.h>
#include <sstream>
#include <QHBoxLayout>
#include <QVBoxLayout>

#ifdef HAS_INSTALL_ENV
#   include <QApplication>
#   include <QMessageBox>
#   include <QProgressBar>
int scanResults(wpactrl_t *control, char const *s, size_t len, void *page, tain_t *) {
    NetworkSimpleWirelessPage *our_page = reinterpret_cast<NetworkSimpleWirelessPage *>(page);
    return our_page->processScan(control, s, len);
}
#endif  /* HAS_INSTALL_ENV */

NetworkSimpleWirelessPage::NetworkSimpleWirelessPage(QWidget *parent)
    : HorizonWizardPage(parent)
#ifdef HAS_INSTALL_ENV
    , control(WPACTRL_ZERO), associated(false)
#endif  /* HAS_INSTALL_ENV */
    {
    QVBoxLayout *layout = new QVBoxLayout;
    QHBoxLayout *buttonLayout = new QHBoxLayout;

    loadWatermark("network");
    setTitle(tr("Select Your Network"));

    statusLabel = new QLabel(tr("Scanning for networks..."));
    statusLabel->setWordWrap(true);

    addNetButton = new QPushButton(tr("&Add Network..."));
    addNetButton->setIcon(QIcon::fromTheme("list-add"));
    connect(addNetButton, &QPushButton::clicked, [=] {
        CustomWiFiDialog d;
        if(d.exec() == QDialog::Accepted) {
            QListWidgetItem *netitem = new QListWidgetItem;
            netitem->setText(d.networkName());
            netitem->setIcon(QIcon::fromTheme("network-wireless-signal-none"));
            netitem->setToolTip(tr("Frequency: Unknown"));
            netitem->setData(Qt::UserRole, d.flags());
            netitem->setData(Qt::UserRole + 1, 2);

            ssidListView->insertItem(0, netitem);
        }
    });

    buttonLayout->addSpacing(10);
    buttonLayout->addWidget(addNetButton, 0, Qt::AlignCenter);

    ssidListView = new QListWidget;
    connect(ssidListView, &QListWidget::currentItemChanged,
            this, &NetworkSimpleWirelessPage::networkChosen);

#ifdef HAS_INSTALL_ENV
    rescanButton = new QPushButton(tr("&Rescan Networks"));
    connect(rescanButton, &QPushButton::clicked, [=](void) { doScan(); });

    buttonLayout->addWidget(rescanButton, 0, Qt::AlignCenter);

    exchange_item.filter = "CTRL-EVENT-SCAN-RESULTS";
    exchange_item.cb = &scanResults;
    notify = nullptr;
    connNotify = nullptr;
    dialog = nullptr;
#endif  /* HAS_INSTALL_ENV */

    buttonLayout->addSpacing(10);
    passphrase = new QLineEdit(this);
    connect(passphrase, &QLineEdit::textChanged,
            this, &NetworkSimpleWirelessPage::completeChanged);
    passphrase->setEchoMode(QLineEdit::Password);
    passphrase->setMinimumWidth(255);
    passphrase->hide();

    layout->addWidget(statusLabel, 0, Qt::AlignCenter);
    layout->addSpacing(10);
    layout->addWidget(ssidListView, 0, Qt::AlignCenter);
    layout->addLayout(buttonLayout);
    layout->addSpacing(10);
    layout->addWidget(passphrase, 0, Qt::AlignCenter);
    setLayout(layout);
}

NetworkSimpleWirelessPage::~NetworkSimpleWirelessPage() {
#ifdef HAS_INSTALL_ENV
    wpactrl_end(&control);
#endif  /* HAS_INSTALL_ENV */
}

#ifdef HAS_INSTALL_ENV
void NetworkSimpleWirelessPage::scanDone(QString message) {
    rescanButton->setEnabled(true);
    statusLabel->setText(message);
}
#endif  /* HAS_INSTALL_ENV */

void NetworkSimpleWirelessPage::networkChosen(QListWidgetItem *current,
                                              QListWidgetItem *) {
    passphrase->clear();
    passphrase->hide();

    if(current == nullptr) {
        emit completeChanged();
        return;
    }

    QStringList flags = current->data(Qt::UserRole).toStringList();
    if(flags.length() == 0) {
        goto done;
    }

    for(auto &flag : flags) {
        if(flag.startsWith("WPA-EAP") || flag.startsWith("WPA2-EAP")) {
            passphrase->setEnabled(false);
            passphrase->setPlaceholderText(tr("WPA Enterprise networks are not supported in this release of Horizon."));
            passphrase->show();
            goto done;
        }

        if(flag.startsWith("WPA-PSK") || flag.startsWith("WPA2-PSK")) {
            passphrase->setEnabled(true);
            passphrase->setPlaceholderText(tr("WPA Passphrase"));
            passphrase->show();
            goto done;
        }

        if(flag.startsWith("WEP")) {
            passphrase->setEnabled(true);
            passphrase->setPlaceholderText(tr("WEP Passphrase"));
            passphrase->show();
            goto done;
        }
    }

done:
    emit completeChanged();
    return;
}

#ifdef HAS_INSTALL_ENV
void NetworkSimpleWirelessPage::doScan() {
    ssidListView->clear();
    rescanButton->setEnabled(false);
    statusLabel->setText(tr("Scanning for networks..."));

    tain_t deadline;
    wparesponse_t response;
    std::string suppsock = "/var/run/wpa_supplicant/" +
            horizonWizard()->chosen_auto_iface;

    tain_now_g();
    wpactrl_end(&control);
    if(!wpactrl_start_g(&control, suppsock.c_str(), 2000)) {
        rescanButton->setEnabled(false);
        statusLabel->setText(tr("Couldn't communicate with wireless subsystem (Code %1)").arg(errno));
        return;
    }

    response = wpactrl_command_g(&control, "SCAN");
    if(response != WPA_OK && response != WPA_FAILBUSY) {
        scanDone(tr("Couldn't scan for wireless networks (Code %1)").arg(response));
        return;
    }

    tain_from_millisecs(&deadline, 15000);
    tain_add_g(&deadline, &deadline);
    wpactrl_xchg_init(&exchange, &exchange_item, 1, &deadline, this);
    if(!wpactrl_xchg_start(&control, &exchange)) {
        scanDone(tr("Failed to scan for wireless networks."));
        return;
    }

    if(notify != nullptr) {
        notify->setEnabled(false);
        notify->deleteLater();
        notify = nullptr;
    }

    notify = new QSocketNotifier(wpactrl_fd(&control), QSocketNotifier::Read, this);
    connect(notify, &QSocketNotifier::activated, [=](int) {
        QString status;

        tain_now_g();
        if(wpactrl_xchg_timeout_g(&control, &exchange)) {
            status = tr("Network scan timed out.");
        } else {
            if(wpactrl_update(&control) < 0) {
                status = tr("Issue communicating with wireless subsystem.");
            } else {
                int code = wpactrl_xchg_event_g(&control, &exchange);
                if(code == -2) {
                    /* if the callback is what failed, we already set status */
                    status = statusLabel->text();
                } else if(code < 0) {
                    /* non-callback failure */
                    status = tr("Issue processing scanned networks (Code %1)")
                            .arg(code);
                } else if(code == 0) {
                    /* Not finished yet, so don't do anything. */
                    return;
                } else {
                    status = tr("Select your wireless network.");
                }
            }
        }
        notify->setEnabled(false);
        notify->deleteLater();
        notify = nullptr;
        statusLabel->setText(status);
        rescanButton->setEnabled(true);
        return;
    });
    notify->setEnabled(true);
}
#endif  /* HAS_INSTALL_ENV */

void NetworkSimpleWirelessPage::initializePage() {
#ifdef HAS_INSTALL_ENV
    doScan();
#endif  /* HAS_INSTALL_ENV */
}

bool NetworkSimpleWirelessPage::isComplete() const {
    if(ssidListView->currentRow() == -1) {
        return false;
    }

    return (passphrase->isHidden() || passphrase->text().size() > 0);
}

int NetworkSimpleWirelessPage::nextId() const {
    return HorizonWizard::Page_Network_DHCP;
}

#ifdef HAS_INSTALL_ENV
void NetworkSimpleWirelessPage::associate() {
    QList<QListWidgetItem *> items = ssidListView->selectedItems();
    if(items.size() == 0) {
        return;
    }

    if(dialog != nullptr) dialog->deleteLater();
    dialog = new QProgressDialog(this);
    dialog->setCancelButton(nullptr);

    QProgressBar *bar = new QProgressBar;
    bar->setRange(0, 0);
    bar->setFixedSize(QSize(150, 24));
    dialog->setBar(bar);
    dialog->setLabelText(tr("Connecting..."));
    dialog->setMinimumDuration(1);

    dialog->show();
    QApplication::processEvents(QEventLoop::AllEvents, 1000);

    if(connNotify != nullptr) {
        connNotify->setEnabled(false);
        connNotify->deleteLater();
        connNotify = nullptr;
    }

    wpactrl_filter_add(&control, "CTRL-EVENT-ASSOC-REJECT");
    wpactrl_filter_add(&control, "CTRL-EVENT-AUTH-REJECT");
    wpactrl_filter_add(&control, "CTRL-EVENT-CONNECTED");

    connNotify = new QSocketNotifier(wpactrl_fd(&control), QSocketNotifier::Read, this);
    connect(connNotify, &QSocketNotifier::activated,
            this, &NetworkSimpleWirelessPage::processAssociateMessage);

    const char *ssid, *pass;
    std::string password, network;

    if(passphrase->isHidden()) {
        pass = nullptr;
    } else {
        password = ("\"" + passphrase->text().toStdString() + "\"");
        pass = password.c_str();
    }
    network = ("\"" + items[0]->text().toStdString() + "\"");
    ssid = network.c_str();

    tain_now_g();
    if(wpactrl_associate_g(&control, ssid, pass) == 0) {
        dialog->hide();
        QMessageBox::critical(this, tr("Could Not Connect"),
                              tr("An issue occurred connecting to the specified wireless network.  "
                                 "Ensure your passphrase is correct and try again."));
    } else {
        dialog->setLabelText(tr("Associating..."));
    }

    return;
}

void NetworkSimpleWirelessPage::processAssociateMessage(int) {
    QString error;

    if(wpactrl_update(&control) < 0) {
        dialog->setLabelText(tr("Issue communicating with wireless subsystem."));
    } else {
        char *raw_msg = wpactrl_msg(&control);
        if(raw_msg == nullptr) {
            return;
        }
        QString msg(raw_msg);
        msg = msg.remove(0, 3);

        wpactrl_ackmsg(&control);

        if(msg.startsWith("CTRL-EVENT-CONNECTED")) {
            /* Happy day! */
            dialog->setRange(0, 1);
            dialog->setValue(1);
            dialog->setLabelText(tr("Connected."));
            associated = true;
            horizonWizard()->next();
        } else if(msg.startsWith("CTRL-EVENT-ASSOC-REJECT")) {
            error = tr("There was an issue connecting to your wireless network.  "
                       "You may need to move closer to your wireless gateway, or reset your hardware and try again.\n\n"
                       "Technical details: %1").arg(msg);
        } else if(msg.startsWith("CTRL-EVENT-AUTH-REJECT")) {
            error = tr("There was an issue connecting to your wireless network.  "
                       "Ensure your passphrase is correct and try again.\n\n"
                       "Technical details: %1").arg(msg);
        } else {
            /* unknown message. */
            return;
        }
    }

    connNotify->setEnabled(false);
    connNotify->deleteLater();
    connNotify = nullptr;

    if(!associated) {
        dialog->hide();
        QMessageBox::critical(this, tr("Could Not Connect"), error);
    }

    return;
}

int NetworkSimpleWirelessPage::processScan(wpactrl_t *c, const char *, size_t) {
    assert(c == &control);
    std::vector<QListWidgetItem *> netitems;

    stralloc buf = STRALLOC_ZERO;

    errno = 0;
    if(!wpactrl_querysa_g(&control, "SCAN_RESULTS", &buf)) {
        if(errno == EMSGSIZE) {
            statusLabel->setText(tr("Scan failed: Out of memory"));
            return 0;
        } else {
            statusLabel->setText(tr("Scan failed (Code %1)").arg(errno));
            return 0;
        }
    }

    genalloc nets = GENALLOC_ZERO;
    stralloc netstr = STRALLOC_ZERO;
    errno = 0;

    if(wpactrl_scan_parse(buf.s, buf.len, &nets, &netstr) != 1) {
        statusLabel->setText(tr("Network listing failed (Code %1)").arg(errno));
        return 0;
    }

    wpactrl_scanres_t *netarray = genalloc_s(wpactrl_scanres_t, &nets);
    for(size_t net = 0; net < genalloc_len(wpactrl_scanres_t, &nets); net++) {
        wpactrl_scanres_t network = netarray[net];
        std::string ssid(netstr.s + network.ssid_start, network.ssid_len);
        std::string flags(netstr.s + network.flags_start, network.flags_len);

        /* Don't bother with empty SSIDs. */
        if(ssid.empty()) continue;
        /* since this *is* destructive, we don't run it on our actual SSID */
        if(QString::fromStdString(ssid)
                .remove("\\x00", Qt::CaseSensitive).size() == 0) continue;

        QIcon icon;
        if(network.signal_level < -90) {
            icon = QIcon::fromTheme("network-wireless-signal-none");
        } else if(network.signal_level < -80) {
            icon = QIcon::fromTheme("network-wireless-signal-weak");
        } else if(network.signal_level < -67) {
            icon = QIcon::fromTheme("network-wireless-signal-ok");
        } else if(network.signal_level < -50) {
            icon = QIcon::fromTheme("network-wireless-signal-good");
        } else {
            icon = QIcon::fromTheme("network-wireless-signal-excellent");
        }

        QListWidgetItem *netitem = new QListWidgetItem;
        netitem->setText(QString::fromStdString(ssid));
        netitem->setIcon(icon);
        netitem->setToolTip(tr("Frequency: %1 MHz\nBSSID: %2\nRSSI: %3")
                            .arg(network.frequency)
                            .arg(fromMacAddress(network.bssid))
                            .arg(network.signal_level));
        QString zero(QString::fromStdString(std::string("\0", 1)));
        netitem->setData(Qt::UserRole, QString::fromStdString(flags)
                                       .split(zero));
        netitem->setData(Qt::UserRole + 1, network.signal_level);
        netitems.push_back(netitem);
    }

    std::sort(netitems.begin(), netitems.end(),
              [](QListWidgetItem *left, QListWidgetItem *right) {
        return left->data(Qt::UserRole + 1).toInt() >
               right->data(Qt::UserRole + 1).toInt();
    });

    for(auto &item : netitems) {
        ssidListView->addItem(item);
    }

    stralloc_free(&netstr);
    genalloc_free(wpactrl_scanres_t, &nets);
    stralloc_free(&buf);

    return 1;
}
#endif  /* HAS_INSTALL_ENV */

bool NetworkSimpleWirelessPage::validatePage() {
    /* What a hack!
     *
     * Independent Pages means the DHCP page is never cleaned, even when Back
     * is chosen.  So, we have to do it from here. */
    horizonWizard()->removePage(HorizonWizard::Page_Network_DHCP);
    horizonWizard()->setPage(HorizonWizard::Page_Network_DHCP, new NetDHCPPage);

#ifdef HAS_INSTALL_ENV
    if(associated) return true;

    associate();
    return false;
#else  /* !HAS_INSTALL_ENV */
    return true;
#endif  /* HAS_INSTALL_ENV */
}