summaryrefslogtreecommitdiffstats
path: root/src/network/kernel/qnetconmonitor_win.cpp
blob: 147314dbeb190a3687c4524630e964042a4b002b (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
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qnetconmonitor_p.h"

#include "private/qobject_p.h"

#include <QtCore/quuid.h>
#include <QtCore/qmetaobject.h>

#include <QtNetwork/qnetworkinterface.h>

#include <objbase.h>
#include <netlistmgr.h>
#include <wrl/client.h>
#include <wrl/wrappers/corewrappers.h>
#include <comdef.h>
#include <iphlpapi.h>

#include <algorithm>

using namespace Microsoft::WRL;

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcNetMon, "qt.network.monitor");

namespace {
QString errorStringFromHResult(HRESULT hr)
{
    _com_error error(hr);
    return QString::fromWCharArray(error.ErrorMessage());
}

template<typename T>
bool QueryInterfaceImpl(IUnknown *from, REFIID riid, void **ppvObject)
{
    if (riid == __uuidof(T)) {
        *ppvObject = static_cast<T *>(from);
        from->AddRef();
        return true;
    }
    return false;
}

QNetworkInterface getInterfaceFromHostAddress(const QHostAddress &local)
{
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    auto it = std::find_if(
            interfaces.cbegin(), interfaces.cend(), [&local](const QNetworkInterface &iface) {
                const auto &entries = iface.addressEntries();
                return std::any_of(entries.cbegin(), entries.cend(),
                                   [&local](const QNetworkAddressEntry &entry) {
                                       return entry.ip().isEqual(local,
                                                                 QHostAddress::TolerantConversion);
                                   });
            });
    if (it == interfaces.cend()) {
        qCDebug(lcNetMon, "Could not find the interface for the local address.");
        return {};
    }
    return *it;
}
} // anonymous namespace

class QNetworkConnectionEvents : public INetworkConnectionEvents
{
public:
    QNetworkConnectionEvents(QNetworkConnectionMonitorPrivate *monitor);
    virtual ~QNetworkConnectionEvents();

    HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override;

    ULONG STDMETHODCALLTYPE AddRef() override { return ++ref; }
    ULONG STDMETHODCALLTYPE Release() override
    {
        if (--ref == 0) {
            delete this;
            return 0;
        }
        return ref;
    }

    HRESULT STDMETHODCALLTYPE
    NetworkConnectionConnectivityChanged(GUID connectionId, NLM_CONNECTIVITY connectivity) override;
    HRESULT STDMETHODCALLTYPE NetworkConnectionPropertyChanged(
            GUID connectionId, NLM_CONNECTION_PROPERTY_CHANGE flags) override;

    [[nodiscard]]
    bool setTarget(const QNetworkInterface &iface);
    [[nodiscard]]
    bool startMonitoring();
    [[nodiscard]]
    bool stopMonitoring();

private:
    ComPtr<INetworkConnection> getNetworkConnectionFromAdapterGuid(QUuid guid);

    QUuid currentConnectionId{};

    ComPtr<INetworkListManager> networkListManager;
    ComPtr<IConnectionPoint> connectionPoint;

    QNetworkConnectionMonitorPrivate *monitor = nullptr;

    QAtomicInteger<ULONG> ref = 0;
    DWORD cookie = 0;
};

class QNetworkConnectionMonitorPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QNetworkConnectionMonitor);

public:
    QNetworkConnectionMonitorPrivate();
    ~QNetworkConnectionMonitorPrivate();

    [[nodiscard]]
    bool setTargets(const QHostAddress &local, const QHostAddress &remote);
    [[nodiscard]]
    bool startMonitoring();
    void stopMonitoring();

    void setConnectivity(NLM_CONNECTIVITY newConnectivity);

private:
    ComPtr<QNetworkConnectionEvents> connectionEvents;
    // We can assume we have access to internet/subnet when this class is created because
    // connection has already been established to the peer:
    NLM_CONNECTIVITY connectivity = NLM_CONNECTIVITY(
            NLM_CONNECTIVITY_IPV4_INTERNET | NLM_CONNECTIVITY_IPV6_INTERNET
            | NLM_CONNECTIVITY_IPV4_SUBNET | NLM_CONNECTIVITY_IPV6_SUBNET
            | NLM_CONNECTIVITY_IPV4_LOCALNETWORK | NLM_CONNECTIVITY_IPV6_LOCALNETWORK
            | NLM_CONNECTIVITY_IPV4_NOTRAFFIC | NLM_CONNECTIVITY_IPV6_NOTRAFFIC);

    bool sameSubnet = false;
    bool isLinkLocal = false;
    bool monitoring = false;
    bool comInitFailed = false;
    bool remoteIsIPv6 = false;
};

QNetworkConnectionEvents::QNetworkConnectionEvents(QNetworkConnectionMonitorPrivate *monitor)
    : monitor(monitor)
{
    auto hr = CoCreateInstance(CLSID_NetworkListManager, nullptr, CLSCTX_INPROC_SERVER,
                               IID_INetworkListManager, &networkListManager);
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Could not get a NetworkListManager instance:"
                            << errorStringFromHResult(hr);
        return;
    }

    ComPtr<IConnectionPointContainer> connectionPointContainer;
    hr = networkListManager.As(&connectionPointContainer);
    if (SUCCEEDED(hr)) {
        hr = connectionPointContainer->FindConnectionPoint(IID_INetworkConnectionEvents,
                                                           &connectionPoint);
    }
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Failed to get connection point for network events:"
                            << errorStringFromHResult(hr);
    }
}

QNetworkConnectionEvents::~QNetworkConnectionEvents()
{
    Q_ASSERT(ref == 0);
}

ComPtr<INetworkConnection> QNetworkConnectionEvents::getNetworkConnectionFromAdapterGuid(QUuid guid)
{
    ComPtr<IEnumNetworkConnections> connections;
    auto hr = networkListManager->GetNetworkConnections(connections.GetAddressOf());
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Failed to enumerate network connections:"
                            << errorStringFromHResult(hr);
        return nullptr;
    }
    ComPtr<INetworkConnection> connection = nullptr;
    do {
        hr = connections->Next(1, connection.GetAddressOf(), nullptr);
        if (FAILED(hr)) {
            qCDebug(lcNetMon) << "Failed to get next network connection in enumeration:"
                                << errorStringFromHResult(hr);
            break;
        }
        if (connection) {
            GUID adapterId;
            hr = connection->GetAdapterId(&adapterId);
            if (FAILED(hr)) {
                qCDebug(lcNetMon) << "Failed to get adapter ID from network connection:"
                                    << errorStringFromHResult(hr);
                continue;
            }
            if (guid == adapterId)
                return connection;
        }
    } while (connection);
    return nullptr;
}

HRESULT STDMETHODCALLTYPE QNetworkConnectionEvents::QueryInterface(REFIID riid, void **ppvObject)
{
    if (!ppvObject)
        return E_INVALIDARG;

    return QueryInterfaceImpl<IUnknown>(this, riid, ppvObject)
                    || QueryInterfaceImpl<INetworkConnectionEvents>(this, riid, ppvObject)
            ? S_OK
            : E_NOINTERFACE;
}

HRESULT STDMETHODCALLTYPE QNetworkConnectionEvents::NetworkConnectionConnectivityChanged(
        GUID connectionId, NLM_CONNECTIVITY newConnectivity)
{
    // This function is run on a different thread than 'monitor' is created on, so we need to run
    // it on that thread
    QMetaObject::invokeMethod(monitor->q_ptr,
                              [this, connectionId, newConnectivity, monitor = this->monitor]() {
                                  if (connectionId == currentConnectionId)
                                      monitor->setConnectivity(newConnectivity);
                              },
                              Qt::QueuedConnection);
    return S_OK;
}

HRESULT STDMETHODCALLTYPE QNetworkConnectionEvents::NetworkConnectionPropertyChanged(
        GUID connectionId, NLM_CONNECTION_PROPERTY_CHANGE flags)
{
    Q_UNUSED(connectionId);
    Q_UNUSED(flags);
    return E_NOTIMPL;
}

bool QNetworkConnectionEvents::setTarget(const QNetworkInterface &iface)
{
    // Unset this in case it's already set to something
    currentConnectionId = QUuid{};

    NET_LUID luid;
    if (ConvertInterfaceIndexToLuid(iface.index(), &luid) != NO_ERROR) {
        qCDebug(lcNetMon, "Could not get the LUID for the interface.");
        return false;
    }
    GUID guid;
    if (ConvertInterfaceLuidToGuid(&luid, &guid) != NO_ERROR) {
        qCDebug(lcNetMon, "Could not get the GUID for the interface.");
        return false;
    }
    ComPtr<INetworkConnection> connection = getNetworkConnectionFromAdapterGuid(guid);
    if (!connection) {
        qCDebug(lcNetMon, "Could not get the INetworkConnection instance for the adapter GUID.");
        return false;
    }
    auto hr = connection->GetConnectionId(&guid);
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Failed to get the connection's GUID:" << errorStringFromHResult(hr);
        return false;
    }
    currentConnectionId = guid;

    return true;
}

bool QNetworkConnectionEvents::startMonitoring()
{
    if (currentConnectionId.isNull()) {
        qCDebug(lcNetMon, "Can not start monitoring, set targets first");
        return false;
    }
    if (!connectionPoint) {
        qCDebug(lcNetMon,
                  "We don't have the connection point, cannot start listening to events!");
        return false;
    }

    auto hr = connectionPoint->Advise(this, &cookie);
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Failed to subscribe to network connectivity events:"
                            << errorStringFromHResult(hr);
        return false;
    }
    return true;
}

bool QNetworkConnectionEvents::stopMonitoring()
{
    auto hr = connectionPoint->Unadvise(cookie);
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Failed to unsubscribe from network connection events:"
                            << errorStringFromHResult(hr);
        return false;
    }
    cookie = 0;
    currentConnectionId = QUuid{};
    return true;
}

QNetworkConnectionMonitorPrivate::QNetworkConnectionMonitorPrivate()
{
    auto hr = CoInitialize(nullptr);
    if (FAILED(hr)) {
        qCDebug(lcNetMon) << "Failed to initialize COM:" << errorStringFromHResult(hr);
        comInitFailed = true;
        return;
    }

    connectionEvents = new QNetworkConnectionEvents(this);
}

QNetworkConnectionMonitorPrivate::~QNetworkConnectionMonitorPrivate()
{
    if (comInitFailed)
        return;
    if (monitoring)
        stopMonitoring();
    connectionEvents.Reset();
    CoUninitialize();
}

bool QNetworkConnectionMonitorPrivate::setTargets(const QHostAddress &local,
                                                  const QHostAddress &remote)
{
    if (comInitFailed)
        return false;

    QNetworkInterface iface = getInterfaceFromHostAddress(local);
    if (!iface.isValid())
        return false;
    const auto &addressEntries = iface.addressEntries();
    auto it = std::find_if(
            addressEntries.cbegin(), addressEntries.cend(),
            [&local](const QNetworkAddressEntry &entry) { return entry.ip() == local; });
    if (Q_UNLIKELY(it == addressEntries.cend())) {
        qCDebug(lcNetMon, "The address entry we were working with disappeared");
        return false;
    }
    sameSubnet = remote.isInSubnet(local, it->prefixLength());
    isLinkLocal = remote.isLinkLocal() && local.isLinkLocal();
    remoteIsIPv6 = remote.protocol() == QAbstractSocket::IPv6Protocol;

    return connectionEvents->setTarget(iface);
}

void QNetworkConnectionMonitorPrivate::setConnectivity(NLM_CONNECTIVITY newConnectivity)
{
    Q_Q(QNetworkConnectionMonitor);
    const bool reachable = q->isReachable();
    connectivity = newConnectivity;
    const bool newReachable = q->isReachable();
    if (reachable != newReachable)
        emit q->reachabilityChanged(newReachable);
}

bool QNetworkConnectionMonitorPrivate::startMonitoring()
{
    Q_ASSERT(connectionEvents);
    Q_ASSERT(!monitoring);
    if (connectionEvents->startMonitoring())
        monitoring = true;
    return monitoring;
}

void QNetworkConnectionMonitorPrivate::stopMonitoring()
{
    Q_ASSERT(connectionEvents);
    Q_ASSERT(monitoring);
    if (connectionEvents->stopMonitoring())
        monitoring = false;
}

QNetworkConnectionMonitor::QNetworkConnectionMonitor()
    : QObject(*new QNetworkConnectionMonitorPrivate)
{
}

QNetworkConnectionMonitor::QNetworkConnectionMonitor(const QHostAddress &local,
                                                     const QHostAddress &remote)
    : QObject(*new QNetworkConnectionMonitorPrivate)
{
    setTargets(local, remote);
}

QNetworkConnectionMonitor::~QNetworkConnectionMonitor() = default;

bool QNetworkConnectionMonitor::setTargets(const QHostAddress &local, const QHostAddress &remote)
{
    if (isMonitoring()) {
        qCDebug(lcNetMon, "Monitor is already active, call stopMonitoring() first");
        return false;
    }
    if (local.isNull()) {
        qCDebug(lcNetMon, "Invalid (null) local address, cannot create a reachability target");
        return false;
    }
    // Silently return false for loopback addresses instead of printing warnings later
    if (remote.isLoopback())
        return false;

    return d_func()->setTargets(local, remote);
}

bool QNetworkConnectionMonitor::startMonitoring()
{
    Q_D(QNetworkConnectionMonitor);
    if (isMonitoring()) {
        qCDebug(lcNetMon, "Monitor is already active, call stopMonitoring() first");
        return false;
    }
    return d->startMonitoring();
}

bool QNetworkConnectionMonitor::isMonitoring() const
{
    return d_func()->monitoring;
}

void QNetworkConnectionMonitor::stopMonitoring()
{
    Q_D(QNetworkConnectionMonitor);
    if (!isMonitoring()) {
        qCDebug(lcNetMon, "stopMonitoring was called when not monitoring!");
        return;
    }
    d->stopMonitoring();
}

bool QNetworkConnectionMonitor::isReachable()
{
    Q_D(QNetworkConnectionMonitor);

    const NLM_CONNECTIVITY RequiredSameSubnetIPv6 =
            NLM_CONNECTIVITY(NLM_CONNECTIVITY_IPV6_SUBNET | NLM_CONNECTIVITY_IPV6_LOCALNETWORK
                             | NLM_CONNECTIVITY_IPV6_INTERNET);
    const NLM_CONNECTIVITY RequiredSameSubnetIPv4 =
            NLM_CONNECTIVITY(NLM_CONNECTIVITY_IPV4_SUBNET | NLM_CONNECTIVITY_IPV4_LOCALNETWORK
                             | NLM_CONNECTIVITY_IPV4_INTERNET);

    NLM_CONNECTIVITY required;
    if (d->isLinkLocal) {
        required = NLM_CONNECTIVITY(
                d->remoteIsIPv6 ? NLM_CONNECTIVITY_IPV6_NOTRAFFIC | RequiredSameSubnetIPv6
                                : NLM_CONNECTIVITY_IPV4_NOTRAFFIC | RequiredSameSubnetIPv4);
    } else if (d->sameSubnet) {
        required =
                NLM_CONNECTIVITY(d->remoteIsIPv6 ? RequiredSameSubnetIPv6 : RequiredSameSubnetIPv4);

    } else {
        required = NLM_CONNECTIVITY(d->remoteIsIPv6 ? NLM_CONNECTIVITY_IPV6_INTERNET
                                                    : NLM_CONNECTIVITY_IPV4_INTERNET);
    }

    return d_func()->connectivity & required;
}

bool QNetworkConnectionMonitor::isEnabled()
{
    return true;
}

QT_END_NAMESPACE