summaryrefslogtreecommitdiffstats
path: root/src/imports/wifi/qwifimanager.cpp
blob: 04faa93253c7f13f0434f1d1929365414299f37b (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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc
** All rights reserved.
** For any questions to Digia, please use the contact form at
** http://qt.digia.com/
**
** This file is part of Qt Enterprise Embedded.
**
** Licensees holding valid Qt Enterprise licenses may use this file in
** accordance with the Qt Enterprise License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.
**
** If you have questions regarding the use of this file, please use
** the contact form at http://qt.digia.com/
**
****************************************************************************/
#include "qwifimanager.h"

#include <QtCore>

#include <hardware_legacy/wifi.h>
#include <cutils/sockets.h>
#include <unistd.h>

static const char SUPPLICANT_SVC[]  = "init.svc.wpa_supplicant";
static const char WIFI_INTERFACE[]  = "wifi.interface";
static const char QT_WIFI_BACKEND[] = "qt.wifi";

static bool QT_WIFI_DEBUG = !qgetenv("QT_WIFI_DEBUG").isEmpty();

const QEvent::Type WIFI_SCAN_RESULTS = (QEvent::Type) (QEvent::User + 2001);
const QEvent::Type WIFI_CONNECTED = (QEvent::Type) (QEvent::User + 2002);

/*
 * This function is borrowed from /system/core/libnetutils/dhcp_utils.c
 *
 * Wait for a system property to be assigned a specified value.
 * If desired_value is NULL, then just wait for the property to
 * be created with any value. maxwait is the maximum amount of
 * time in seconds to wait before giving up.
 */
static const int NAP_TIME = 200; // wait for 200ms at a time when polling for property values
static int wait_for_property(const char *name, const char *desired_value, int maxwait)
{
    char value[PROPERTY_VALUE_MAX] = {'\0'};
    int maxnaps = (maxwait * 1000) / NAP_TIME;

    if (maxnaps < 1) {
        maxnaps = 1;
    }

    while (maxnaps-- > 0) {
        usleep(NAP_TIME * 1000);
        if (property_get(name, value, NULL)) {
            if (desired_value == NULL ||
                    strcmp(value, desired_value) == 0) {
                return 0;
            }
        }
    }
    return -1; /* failure */
}

class QWifiManagerEvent : public QEvent
{
public:
    QWifiManagerEvent(QEvent::Type type, const QByteArray &data = QByteArray())
        : QEvent(type)
        , m_data(data)
    {
    }

    QByteArray data() const { return m_data; }

private:
    QByteArray m_data;
};

class QWifiManagerEventThread : public QThread
{
public:
    QWifiManagerEventThread(QWifiManager *manager, const QByteArray &interface)
        : m_manager(manager)
        , m_if(interface)
    {

    }

    void run() {
        if (QT_WIFI_DEBUG) qDebug("EventReceiver thread is running");
        char buffer[2048];
        while (1) {
            int size = wifi_wait_for_event(m_if.constData(), buffer, sizeof(buffer) - 1);
            if (size > 0) {
                buffer[size] = 0;

                if (QT_WIFI_DEBUG) qDebug("EVENT: %s", buffer);

                char *event = &buffer[11];
                if (strstr(event, "SCAN-RESULTS")) {
                    if (m_manager->exitingEventThread())
                        return;
                    QWifiManagerEvent *e = new QWifiManagerEvent(WIFI_SCAN_RESULTS);
                    QCoreApplication::postEvent(m_manager, e);
                } else if (strstr(event, "CONNECTED")) {
                    QWifiManagerEvent *e = new QWifiManagerEvent(WIFI_CONNECTED);
                    QCoreApplication::postEvent(m_manager, e);
                } else if (strstr(event, "TERMINATING")) {
                    // stop monitoring for events when supplicant is terminating
                    return;
                }
            }
        }
    }

    QWifiManager *m_manager;
    QByteArray m_if;
};

/*!
    \qmlmodule Qt.labs.wifi 0.1
    \title WiFi Module
    \ingroup b2qt-qmlmodules

    Provides QML types for controlling and accessing information about wireless network interfaces.

    The import command for adding these QML types is:

    \code
    import Qt.labs.wifi 0.1
    \endcode

    If the module is imported into a namespace, some additional methods become available through the
    \l Interface element.

    \code
    import Qt.labs.wifi 0.1 as Wifi
    \endcode

*/

/*!

    \qmltype WifiManager
    \inqmlmodule Qt.labs.wifi
    \brief WifiManager provides information about the wifi backend and available networks.

    This element is the main interface to the WiFi functionality.

 */

/*!
    \qmlproperty enumeration WifiManager::networkState

    This property holds the current state of the network connection.

    \list
    \li \e WifiManager.Disconnected - Not connected to any network
    \li \e WifiManager.ObtainingIPAddress - Requesting IP address from DHCP server
    \li \e WifiManager.DhcpRequestFailed - Could not retrieve IP address
    \li \e WifiManager.Connected - Ready to process network requests
    \endlist
*/

/*!
    \qmlproperty bool WifiManager::backendReady

    This property holds whether or not the backend has been successfully initialized.

    \code
    WifiManager {
        id: wifiManager
        scanning: backendReady
    }

    Button {
        id: wifiOnOffButton
        text: (wifiManager.backendReady) ? "Switch Off" : "Switch On"
        onClicked: {
            if (wifiManager.backendReady) {
                wifiManager.stop()
            } else {
                wifiManager.start()
            }
        }
    }
    \endcode
*/

/*!
    \qmlproperty bool WifiManager::scanning

    This property holds whether or not the backend is scanning for WiFi networks. To
    preserve battery energy, stop scanning for networks once you are done with configuring a network.

    Before starting to scan for networks, you need to initialize the WiFi backend.

    \sa start
*/

/*!
    \qmlproperty string WifiManager::connectedSSID

    This property holds the network name.
*/

/*!
    \qmlproperty WifiNetworkListModel WifiManager::networks

    This property holds a list of networks that can be sensed by a device and should be used as a
    data model in ListView. List is updated every 5 seconds.

    WifiNetworkListModel is a simple data model consisting of WifiNetwork objects, accessed with
    the "network" data role. Instances of WifiNetwork cannot be created directly from the QML system.

    \code
    WifiManager {
        id: wifiManager
        scanning: backendReady
        Component.onCompleted: start()
    }

    Component {
        id: listDelegate
        Rectangle {
            id: delegateBackground
            height: 60
            width: parent.width
            color: "#5C5C5C"
            border.color: "black"
            border.width: 1

            Text {
                id: ssidLabel
                anchors.top: parent.top
                anchors.left: parent.left
                anchors.margins: 10
                font.pixelSize: 20
                font.bold: true
                color: "#E6E6E6"
                text: network.ssid
            }

            Rectangle {
                width: Math.max(100 + network.signalStrength, 0) / 100 * parent.width;
                height: 20
                radius: 10
                antialiasing: true
                anchors.margins: 20
                anchors.right: parent.right
                anchors.top: parent.top
                color: "#BF8888"
                border.color: "#212126"
            }
        }
    }


    ListView {
        id: networkView
        anchors.fill: parent
        model: wifiManager.networks
        delegate: listDelegate
    }
    \endcode

*/

/*!
    \qmlmethod void WifiManager::start()

    Start an initialization of the WiFi backend.

    \sa stop
 */

/*!
    \qmlmethod void WifiManager::stop()

    Stop the WiFi backend and shut down all network functionality.

    \sa start
 */

/*!
    \qmlmethod void WifiManager::connect(WifiNetwork network, const string passphrase)

    Connect to network \a network and use passphrase \a passphrase for authentication.

    \sa disconnect, networkState
 */

/*!
    \qmlmethod void WifiManager::disconnect()

    Disconnect from currently connected network connection.

    \sa connect, networkState
 */

/*!
    \qmlsignal void WifiManager::scanningChanged(bool scanning)

    This signal is emitted when device starts or stops to scan for available wifi networks.

    \sa scanning

*/

/*!
    \qmlsignal void WifiManager::networkStateChanged()

    This signal is emitted whenever changes in a network state occur.

    \sa networkState
*/

/*!
    \qmlsignal void WifiManager::backendReadyChanged()

    This signal is emitted when backend has been successfully initialized or shut down.

    \sa start, stop
*/

/*!
    \qmlsignal void WifiManager::connectedSSIDChanged(string ssid)

    This signal is emitted when the device has connected to or disconnected from a network.
    \a ssid contains the name of the connected network, or an empty string if the network was disconnected.

    \sa connect, disconnect
*/

QWifiManager::QWifiManager()
    : m_networks(this)
    , m_eventThread(0)
    , m_scanTimer(0)
    , m_scanning(false)
    , m_daemonClientSocket(0)
    , m_exitingEventThread(false)
{
    char interface[PROPERTY_VALUE_MAX];
    property_get(WIFI_INTERFACE, interface, NULL);
    m_interface = interface;
    if (QT_WIFI_DEBUG) qDebug("QWifiManager: using wifi interface: %s", m_interface.constData());
    m_eventThread = new QWifiManagerEventThread(this, m_interface);

    m_daemonClientSocket = new QLocalSocket;
    int qconnFd = socket_local_client("qconnectivity", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
    if (qconnFd != -1) {
        m_daemonClientSocket->setSocketDescriptor(qconnFd);
        QObject::connect(m_daemonClientSocket, SIGNAL(readyRead()), this, SLOT(handleDhcpReply()));
        QObject::connect(m_daemonClientSocket, SIGNAL(connected()), this, SLOT(connectedToDaemon()));
    } else {
        qWarning() << "QWifiManager: failed to connect to qconnectivity socket";
    }
    // check if backend has already been initialized
    char backend_status[PROPERTY_VALUE_MAX];
    if (property_get(QT_WIFI_BACKEND, backend_status, NULL)) {
        if (strcmp(backend_status, "running") == 0) {
            // let it re-connect, in most cases this will see that everything is working properly
            // and will do nothing. Special case is when process has crashed or was killed by a system
            // signal in previous execution, which results in broken connection to a supplicant,
            // connectToBackend will fix it..
            connectToBackend();
        } else if (strcmp(backend_status, "stopped") == 0) {
            // same here, cleans up the state
            disconnectFromBackend();
        }
    }
}

QWifiManager::~QWifiManager()
{
    // exit event thread if it is running
    if (m_eventThread->isRunning()) {
        m_exitingEventThread = true;
        call("SCAN");
        m_eventThread->wait();
    }
    delete m_eventThread;
    delete m_daemonClientSocket;
}

void QWifiManager::handleDhcpReply()
{
    if (m_daemonClientSocket->canReadLine()) {
        QByteArray receivedMessage;
        receivedMessage = m_daemonClientSocket->readLine(m_daemonClientSocket->bytesAvailable());
        if (QT_WIFI_DEBUG) qDebug() << "QWifiManager: reply from qconnectivity: " << receivedMessage;
        if (receivedMessage == "success") {
            m_state = Connected;
            emit networkStateChanged();
            emit connectedSSIDChanged(m_connectedSSID);
            // Store settings of a working wifi connection
            call("SAVE_CONFIG");
        } else if (receivedMessage == "failed") {
            m_state = DhcpRequestFailed;
            emit networkStateChanged();
        } else {
            qWarning() << "QWifiManager: unknown message: " << receivedMessage;
        }
    }
}

void QWifiManager::sendDhcpRequest(const QByteArray &request)
{
    if (QT_WIFI_DEBUG) qDebug() << "QWifiManager: sending request - " << request;
    m_request = request;
    m_request.append("\n");
    m_daemonClientSocket->abort();
    // path where android stores "reserved" sockets
    m_daemonClientSocket->connectToServer(ANDROID_SOCKET_DIR "/qconnectivity");
}

void QWifiManager::connectedToDaemon()
{
    m_daemonClientSocket->write(m_request.constData(), m_request.length());
    m_daemonClientSocket->flush();
}

void QWifiManager::start()
{
    if (QT_WIFI_DEBUG) qDebug("QWifiManager: connecting to the backend");
    connectToBackend();
}

void QWifiManager::stop()
{
    if (QT_WIFI_DEBUG) qDebug("QWifiManager: shutting down");
    disconnectFromBackend();
}

void QWifiManager::connectToBackend()
{
    if (!(is_wifi_driver_loaded() || wifi_load_driver() == 0)) {
        qWarning("QWifiManager: failed to load a driver");
        return;
    }
    if (wifi_start_supplicant(0) != 0) {
        qWarning("QWifiManager: failed to start a supplicant");
        return;
    }
    if (wait_for_property(SUPPLICANT_SVC, "running", 5) < 0) {
        qWarning("QWifiManager: Timed out waiting for supplicant to start");
        return;
    }
    if (wifi_connect_to_supplicant(m_interface.constData()) == 0) {
        m_backendReady = true;
        emit backendReadyChanged();
        property_set(QT_WIFI_BACKEND, "running");
    } else {
        qWarning("QWifiManager: failed to connect to a supplicant");
        return;
    }
    if (QT_WIFI_DEBUG) qDebug("QWifiManager: started successfully");
    m_exitingEventThread = false;
    m_eventThread->start();
    handleConnected();
}

void QWifiManager::disconnectFromBackend()
{
    m_exitingEventThread = true;
    call("SCAN");
    m_eventThread->wait();

    if (wifi_stop_supplicant(0) < 0)
        qWarning("QWifiManager: failed to stop supplicant");
    wifi_close_supplicant_connection(m_interface.constData());
    property_set(QT_WIFI_BACKEND, "stopped");
    m_backendReady = false;
    emit backendReadyChanged();
}

void QWifiManager::setScanning(bool scanning)
{
    if (m_scanning == scanning)
        return;

    m_scanning = scanning;
    emit scanningChanged(m_scanning);

    if (m_scanning) {
        if (QT_WIFI_DEBUG) qDebug("QWifiManager: scanning");
        call("SCAN");
        m_scanTimer = startTimer(5000); // ### todo - this could be a qml property
    } else {
        if (QT_WIFI_DEBUG) qDebug("QWifiManager: stop scanning");
        killTimer(m_scanTimer);
    }
}

QByteArray QWifiManager::call(const char *command) const
{
    char data[2048];
    size_t len = sizeof(data) - 1;  // -1: room to add a 0-terminator
    if (wifi_command(m_interface.constData(), command, data, &len) < 0) {
        qWarning("QWifiManager: call failed: %s", command);
        return QByteArray();
    }
    if (len < sizeof(data))
        data[len] = 0;
    QByteArray result = QByteArray::fromRawData(data, len);
    if (QT_WIFI_DEBUG) qDebug("QWifiManager::call: %s ==>\n%s", command, result.constData());
    return result;
}

bool QWifiManager::checkedCall(const char *command) const
{
    return call(command).trimmed().toUpper() == "OK";
}

bool QWifiManager::event(QEvent *e)
{
    switch ((int) e->type()) {
    case WIFI_SCAN_RESULTS:
        m_networks.parseScanResults(call("SCAN_RESULTS"));
        return true;
    case WIFI_CONNECTED:
        handleConnected();
        break;
    case QEvent::Timer: {
        int tid = static_cast<QTimerEvent *>(e)->timerId();
        if (tid == m_scanTimer) {
            call("SCAN");
            return true;
        }
        break;
    }
    }

    return QObject::event(e);
}

void QWifiManager::connect(QWifiNetwork *network, const QString &passphrase)
{
    if (network->ssid() == m_connectedSSID) {
        if (QT_WIFI_DEBUG) qDebug("QWifiManager::connect(), already connected to %s", network->ssid().constData());
        return;
    }

    call("DISABLE_NETWORK all");
    if (!m_connectedSSID.isEmpty()) {
        m_connectedSSID.clear();
        emit connectedSSIDChanged(m_connectedSSID);
    }

    m_state = ObtainingIPAddress;
    emit networkStateChanged();
    bool networkKnown = false;
    QByteArray id;
    QByteArray listResult = call("LIST_NETWORKS");
    QList<QByteArray> lines = listResult.split('\n');
    foreach (const QByteArray &line, lines) {
        if (line.contains(network->ssid())) {
            int networkId = line.toInt();
            id = QByteArray::number(networkId);
            networkKnown = true;
            break;
        }
    }

    if (!networkKnown) {
        bool ok;
        QByteArray id = call("ADD_NETWORK").trimmed();
        id.toInt(&ok);
        if (!ok) {
            qWarning("QWifiManager::connect(), failed to add network");
            return;
        }
    }
    QByteArray setNetworkCommand = QByteArray("SET_NETWORK ") + id;

    bool ok = true;
    if (!networkKnown)
        ok = ok && checkedCall(setNetworkCommand + QByteArray(" ssid ") + '"' + network->ssid() + '"');

    QByteArray key_mgmt;
    if (network->supportsWPA() || network->supportsWPA2()) {
        ok = ok && checkedCall(setNetworkCommand + QByteArray(" psk ") + '"' + passphrase.toLatin1() + '"');
        key_mgmt = "WPA-PSK";
    } else if (network->supportsWEP()) {
        ok = ok && checkedCall(setNetworkCommand + QByteArray(" wep_key0 ") + '"' + passphrase.toLatin1() + '"');
        ok = ok && checkedCall(setNetworkCommand + QByteArray(" auth_alg OPEN SHARED"));
        key_mgmt = "NONE";
    } else if (!network->supportsWPS() && passphrase.length() == 0) {
        // open network
        key_mgmt = "NONE";
    }
    ok = ok && checkedCall(setNetworkCommand + QByteArray(" key_mgmt ") + key_mgmt);

    if (!ok) {
        if (!networkKnown)
            call("REMOVE_NETWORK " + id);
        qWarning("QWifiManager::connect(), failed to set properties on network '%s'", id.constData());
        return;
    }

    call(QByteArray("SELECT_NETWORK ") + id);
    call("RECONNECT");
}

void QWifiManager::disconnect()
{
    call("DISCONNECT");
    QByteArray req = m_interface;
    sendDhcpRequest(req.append(" disconnect"));
    m_state = Disconnected;
    m_connectedSSID.clear();
    emit networkStateChanged();
    emit connectedSSIDChanged(m_connectedSSID);
}

void QWifiManager::handleConnected()
{
    QList<QByteArray> lists = call("LIST_NETWORKS").split('\n');
    QByteArray connectedNetwork;
    for (int i=1; i<lists.size(); ++i) {
        if (lists.at(i).toUpper().contains("[CURRENT]")) {
            connectedNetwork = lists.at(i);
            break;
        }
    }

    if (connectedNetwork.isEmpty()) {
        if (QT_WIFI_DEBUG) qDebug("QWifiManager::handleConnected: not connected to a network...");
        m_state = Disconnected;
        emit networkStateChanged();
        return;
    }

    if (QT_WIFI_DEBUG) qDebug("QWifiManager::handleConnected: current is %s", connectedNetwork.constData());

    QList<QByteArray> info = connectedNetwork.split('\t');
    m_connectedSSID = info.at(1);

    QByteArray req = m_interface;
    sendDhcpRequest(req.append(" connect"));
}