summaryrefslogtreecommitdiffstats
path: root/src/qconnectivity/main.cpp
blob: e9ded93c1100d1b2941c21c907f3e8bdd5923978 (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
/****************************************************************************
**
** 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 <QtCore>
#include <QtNetwork/QLocalSocket>
#include <QtNetwork/QLocalServer>

#include <unistd.h>
#include <cutils/properties.h>
#include <cutils/sockets.h>
#include <netutils/dhcp.h>
#include <netutils/ifc.h>

// Code values come from android/system/netd/ResponseCode.h
static const int InterfaceChange = 600;

static const char UNIQUE_HOSTNAME[] = "net.hostname";

static bool QT_CONNECTIVITY_DEBUG = !qgetenv("QT_CONNECTIVITY_DEBUG").isEmpty();
static bool QT_USE_EXPIRED_LEASE = !qgetenv("QT_USE_EXPIRED_LEASE").isEmpty();

// sanity check a renewal time, lower value than
// this might indicate a badly configured DHCP server
static int MIN_RENEWAL_TIME_SECS = 300; // 5 min

#define ETH_INTERFACE_HW "eth0"
#define ETH_INTERFACE_EMULATOR "eth1"

#if Q_ANDROID_VERSION_MAJOR == 4 && Q_ANDROID_VERSION_MINOR < 3
// this function is defined in android/system/core/libnetutils/dhcp_utils.c
extern "C" {
int dhcp_do_request_renew(const char *ifname,
                          char *ipaddr,
                          char *gateway,
                          uint32_t *prefixLength,
                          char *dns1,
                          char *dns2,
                          char *server,
                          uint32_t *lease,
                          char *vendorInfo);
}
#endif

static int q_dhcp_do_request(bool renew,
                             const char *ifname,
                             char *ipaddr,
                             char *gateway,
                             uint32_t *prefixLength,
                             char *dns1,
                             char *dns2,
                             char *server,
                             uint32_t *lease,
                             char *vendorInfo,
                             char *domain)
{
#if Q_ANDROID_VERSION_MAJOR == 4 && Q_ANDROID_VERSION_MINOR < 3
    if (!renew)
        return dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns1, dns2, server, lease, vendorInfo);
    return dhcp_do_request_renew(ifname, ipaddr, gateway, prefixLength, dns1, dns2, server, lease, vendorInfo);
#else
    char *dns[3] = {dns1, dns2, 0};
    char mtu[PROPERTY_VALUE_MAX];
#if Q_ANDROID_VERSION_MAJOR == 4 && Q_ANDROID_VERSION_MINOR < 4
    if (!renew)
        return dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns, server, lease, vendorInfo);
    return dhcp_do_request_renew(ifname, ipaddr, gateway, prefixLength, dns, server, lease, vendorInfo);
#else
    if (!renew)
        return dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns, server, lease, vendorInfo, domain, mtu);
    return dhcp_do_request_renew(ifname, ipaddr, gateway, prefixLength, dns, server, lease, vendorInfo, domain, mtu);
#endif
#endif
}


class LeaseTimer;
class QConnectivityDaemon : public QObject
{
    Q_OBJECT
public:
    QConnectivityDaemon();

protected:
    void setHostnamePropery(const char *interface) const;
    void sendCommand(const char *command) const;
    void handleInterfaceChange(const QList<QByteArray> &message);
    bool startDhcp(bool renew, const char *interface);
    void stopDhcp(const char *interface);
    bool ethernetSupported() const;
    bool isEmulator() const;

protected slots:
    void initNetdConnection();
    void handleNetdEvent();
    void handleRequest();
    void handleNewConnection();
    void sendReply(QLocalSocket *requester, const QByteArray &reply) const;
    void updateLease();
    void handleError(QLocalSocket::LocalSocketError /*socketError*/) const;

private:
    friend class LeaseTimer;
    QLocalSocket *m_netdSocket;
    // currently used to listen for requests from Qt Wifi library,
    // in future can be used also for Bluetooth and etc.
    QLocalServer *m_serverSocket;
    bool m_linkUp;
    LeaseTimer *m_leaseTimer;
    bool m_isEmulator;
    QByteArray m_ethInterface;
    // android initializes services in a separate threads, therefore it is
    // not guaranteed that the netd socket will be ready at the time when qconnectivity
    // is starting up - we try to reconnect again after 2 second intervals. This
    // variable holds the maximum attempt count (chosen arbitrarily).
    int m_attemptCount;
};

class LeaseTimer : public QTimer
{
    Q_OBJECT
public:
    LeaseTimer(QConnectivityDaemon *daemon) : m_daemon(daemon) {}

    void setInterface(const QByteArray &interface)
    {
        if (m_ifc.isEmpty()) {
            m_ifc = interface;
        } else {
            // for example when user switches from eth0 to wlan0, we
            // stop DHCP on the previous interface
            if (m_ifc != interface) {
                m_daemon->stopDhcp(m_ifc.constData());
                m_ifc = interface;
            }
        }
    }

    QByteArray interface() const { return m_ifc; }

private:
    QConnectivityDaemon *m_daemon;
    QByteArray m_ifc;
};

QConnectivityDaemon::QConnectivityDaemon()
    : m_netdSocket(0),
      m_serverSocket(0),
      m_linkUp(false),
      m_leaseTimer(0),
      m_isEmulator(isEmulator()),
      m_attemptCount(50)
{
    qDebug() << "starting QConnectivityDaemon...";
    if (!m_isEmulator) {
        m_ethInterface = ETH_INTERFACE_HW;
        m_leaseTimer = new LeaseTimer(this);
        m_leaseTimer->setSingleShot(true);
        connect(m_leaseTimer, SIGNAL(timeout()), this, SLOT(updateLease()));

        int serverFd = socket_local_server("qconnectivity", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
        if (serverFd != -1) {
            m_serverSocket = new QLocalServer(this);
            if (m_serverSocket->listen(serverFd))
                connect(m_serverSocket, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
            else
                qWarning() << "QConnectivityDaemon: not able to listen on the server socket...";
        } else {
            qWarning() << "QConnectivityDaemon: failed to open qconnectivity server socket";
        }
    } else {
        m_ethInterface = ETH_INTERFACE_EMULATOR;
    }
    initNetdConnection();
}

bool QConnectivityDaemon::isEmulator() const
{
    bool isEmulator = false;
    QFile conf("/system/bin/appcontroller.conf");
    if (conf.open(QIODevice::ReadOnly)) {
        QByteArray content = conf.readAll();
        isEmulator = content.contains("platform=emulator");
        conf.close();
    } else {
        qWarning() << "Failed to read appcontroller.conf";
    }
    return isEmulator;
}

void QConnectivityDaemon::initNetdConnection()
{
    int netdFd = socket_local_client("netd", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
    if (netdFd != -1) {
        qDebug() << "QConnectivityDaemon: connected to netd socket";
        m_netdSocket = new QLocalSocket(this);
        m_netdSocket->setSocketDescriptor(netdFd);
        connect(m_netdSocket, SIGNAL(readyRead()), this, SLOT(handleNetdEvent()));
        connect(m_netdSocket, SIGNAL(error(QLocalSocket::LocalSocketError)),
                this, SLOT(handleError(QLocalSocket::LocalSocketError)));
    } else {
        qWarning() << "QConnectivityDaemon: failed to connect to netd socket, reattempting...";
        if (--m_attemptCount != 0)
            QTimer::singleShot(200, this, SLOT(initNetdConnection()));
        return;
    }
    if (ethernetSupported()) {
        // down-up sequence generates "linkstate" events, which we can use to setup
        // our daemon on initial startup (device boot) or on daemon restarts
        sendCommand(QByteArray("0 interface setcfg ").append(m_ethInterface).append(" down").constData());
        sendCommand(QByteArray("0 interface setcfg ").append(m_ethInterface).append(" up").constData());
    }
    // disable firewall - this setting seems to be enabled only when using "Always-on VPN"
    // mode on Android phones, see setLockdownTracker() in ConnectivityService.java
    sendCommand("0 firewall disable");
}

void QConnectivityDaemon::setHostnamePropery(const char *interface) const
{
    // Setup our unique device name (used as a host name argument for dhcpcd call in
    // dhcp_do_request). On Android device name is set in ConnectivityService.java and
    // the id is generated with the help of SecureRandom.java class. We will use Mac
    // address as a unique hostname.
    char prop_value[PROPERTY_VALUE_MAX];
    property_get(UNIQUE_HOSTNAME, prop_value, NULL);
    if ((prop_value[0] == '\0')) {
        char hwaddr[6];
        memset(hwaddr, 0, sizeof(hwaddr));
        ifc_init();
        if (ifc_get_hwaddr(interface, (void *)hwaddr) == 0) {
            QByteArray macAddress(hwaddr, sizeof(hwaddr));
            property_set(UNIQUE_HOSTNAME, macAddress.toHex().prepend("b2qt-").constData());
        } else {
            qWarning() << "QConnectivityDaemon: failed to get MAC address";
        }
        ifc_close();
    }
}

void QConnectivityDaemon::sendCommand(const char *command) const
{
    if (!m_netdSocket) {
        qDebug() << "QConnectivityDaemon: netd socket is not ready!";
        return;
    }
    qDebug() << "QConnectivityDaemon: sending command - " << command;
    // netd expects "\0" terminated commands...
    m_netdSocket->write(command, qstrlen(command) + 1);
    m_netdSocket->flush();
}

void QConnectivityDaemon::handleInterfaceChange(const QList<QByteArray> &message)
{
    // Format: "Code Iface linkstate <name> <up/down>"
    if (message.size() < 5)
        return;

    if (message.at(2) == "linkstate" && message.at(3) == m_ethInterface) {
        if (message.at(4) == "up") {
            // ethernet cable has been plugged in
            if (!m_linkUp) {
                m_linkUp = true;
                startDhcp(false, m_ethInterface);
            }
        } else {
            // .. plugged out
            if (m_linkUp) {
                m_linkUp = false;
                stopDhcp(m_ethInterface);
            }
        }
    }
}

bool QConnectivityDaemon::startDhcp(bool renew, const char *interface)
{
    qDebug() << "QConnectivityDaemon: startDhcp [ renew" << renew << "] "
             << "interface: " << interface;
    setHostnamePropery(interface);

    int result = 0;
    char  ipaddr[PROPERTY_VALUE_MAX];
    quint32 prefixLength = 0;
    char gateway[PROPERTY_VALUE_MAX];
    char    dns1[PROPERTY_VALUE_MAX];
    char    dns2[PROPERTY_VALUE_MAX];
    char  server[PROPERTY_VALUE_MAX];
    quint32 lease = 0;
    char vendorInfo[PROPERTY_VALUE_MAX];
    char domain[PROPERTY_VALUE_MAX] = {0};

    if (renew) {
        result = q_dhcp_do_request(true, interface, ipaddr, gateway, &prefixLength,
                                   dns1, dns2, server, &lease, vendorInfo, domain);
    } else {
        // stop any existing DHCP daemon before starting new
        dhcp_stop(interface);
        // this uses "ctl.start.*" mechanism to start "dhcpcd" daemon as defined by
        // the device init.rc. Android starts dhcpcd with argument -B which means that
        // we are responsible for renewing a lease before it expires
        ifc_clear_addresses(interface);
        result = q_dhcp_do_request(false, interface, ipaddr, gateway, &prefixLength,
                                   dns1, dns2, server, &lease, vendorInfo, domain);
    }

    bool success = (result == 0) ? true : false;
    if (success) {
        qDebug() << "\nipaddr: " << ipaddr << "\nprefixLength: " << prefixLength
                 << "\ngateway: " << gateway << "\ndns1: " << dns1 << "\ndns2: " << dns2;

        if (!renew) {
            in_addr _ipaddr, _gateway, _dns1, _dns2;
            inet_aton(ipaddr, &_ipaddr);
            inet_aton(gateway, &_gateway);
            inet_aton(dns1, &_dns1);
            inet_aton(dns2, &_dns2);

            ifc_configure(interface, _ipaddr.s_addr, prefixLength,
                          _gateway.s_addr, _dns1.s_addr, _dns2.s_addr);

            // set DNS servers for interface - see NetworkManagementService.java
            if (domain[0]) {
                QByteArray dnsForInterface("0 resolver setifdns ");
                dnsForInterface.append(interface).append(" ").append(domain).append(" ");
                dnsForInterface.append(dns1).append(" ").append(dns2);
                sendCommand(dnsForInterface.constData());
            }
            // set default interface for DNS - see NetworkManagementService.java
            sendCommand(QByteArray("0 resolver setdefaultif ").append(interface).constData());

            property_set("net.dns1", dns1);
            property_set("net.dns2", dns2);
        }

        if (!m_isEmulator && lease >= 0) {
            if (lease < MIN_RENEWAL_TIME_SECS) {
                qWarning() << "QConnectivityDaemon: DHCP server proposes lease time " << lease
                           << "seconds. We will use" << MIN_RENEWAL_TIME_SECS << " seconds instead.";
                lease = MIN_RENEWAL_TIME_SECS;
            }
            // update lease when 48% of lease time has elapsed
            if (m_leaseTimer->isActive())
                m_leaseTimer->stop();
            m_leaseTimer->setInterface(interface);
            m_leaseTimer->start(lease * 480);
        }
    } else {
        qWarning("QConnectivityDaemon: DHCP request failed - %s", dhcp_get_errmsg());
        if (renew) {
            // If it fails to renew a lease (faulty server, proxy?) we re-connect.
            // Some users might prefer to use expired lease over having interrupt
            // in network connection
            if (QT_USE_EXPIRED_LEASE)
                return true;
            qDebug() << "QConnectivityDaemon: attempting to re-connect...";
            stopDhcp(interface);
            startDhcp(false, interface);
        }
    }
    return success;
}

void QConnectivityDaemon::stopDhcp(const char *interface)
{
    qDebug() << "QConnectivityDaemon: stopDhcp: " << interface;
    ifc_clear_addresses(interface);
    dhcp_stop(interface);
    if (!m_isEmulator && m_leaseTimer->isActive())
        m_leaseTimer->stop();
}

bool QConnectivityDaemon::ethernetSupported() const
{
    // standard linux kernel path
    return QDir().exists(QString("/sys/class/net/").append(m_ethInterface));
}

void QConnectivityDaemon::handleNetdEvent()
{
    QByteArray data = m_netdSocket->readAll();
    if (QT_CONNECTIVITY_DEBUG)
        qDebug() << "QConnectivityDaemon: netd event: " << data;
    if (data.endsWith('\0'))
        data.chop(1);

    QList<QByteArray> message = data.split(' ');
    int code = message.at(0).toInt();
    switch (code) {
    case InterfaceChange:
        handleInterfaceChange(message);
        break;
    default:
        break;
    }
}

void QConnectivityDaemon::handleRequest()
{
    // Format: "interface <connect/disconnect>"
    QLocalSocket *requester = qobject_cast<QLocalSocket *>(QObject::sender());
    if (requester->canReadLine()) {
        QByteArray request = requester->readLine(requester->bytesAvailable());

        qDebug() << "QConnectivityDaemon: received a request: " << request;
        QList<QByteArray> cmd = request.split(' ');
        if (cmd.size() < 2)
            return;

        QByteArray interface = cmd.at(0);
        if (cmd.at(1) == "connect") {
            QByteArray reply;
            if (startDhcp(false, interface.constData()))
                reply = "success";
            else
                reply = "failed";
            sendReply(requester, reply);
        } else {
            stopDhcp(interface.constData());
        }
    }
}

void QConnectivityDaemon::handleNewConnection()
{
    QLocalSocket *requester = m_serverSocket->nextPendingConnection();
    connect(requester, SIGNAL(readyRead()), this, SLOT(handleRequest()));
    connect(requester, SIGNAL(disconnected()), requester, SLOT(deleteLater()));
}

void QConnectivityDaemon::sendReply(QLocalSocket *requester, const QByteArray &reply) const
{
    QByteArray r = reply;
    r.append("\n");
    requester->write(r.constData(), r.length());
    requester->flush();
    requester->disconnectFromServer();
}

void QConnectivityDaemon::updateLease()
{
    qDebug() << "QConnectivityDaemon: updating lease";
    startDhcp(true, m_leaseTimer->interface().constData());
}

void QConnectivityDaemon::handleError(QLocalSocket::LocalSocketError /*socketError*/) const
{
    qWarning() << "QConnectivityDaemon: QLocalSocket::LocalSocketError";
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QConnectivityDaemon connectivityDaemon;

    return a.exec();
}

#include "main.moc"