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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
|
/****************************************************************************
**
** Copyright (C) 2021 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$
**
****************************************************************************/
// #define DEBUG_LOADING
#include "qnetworkinformation.h"
#include <QtNetwork/private/qnetworkinformation_p.h>
#include <QtNetwork/qnetworkinformation.h>
#include <QtCore/private/qobject_p.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qmutex.h>
#include <QtCore/qthread.h>
#include <QtCore/private/qfactoryloader_p.h>
#include <algorithm>
#include <memory>
#include <mutex>
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcNetInfo)
Q_LOGGING_CATEGORY(lcNetInfo, "qt.network.info");
struct QNetworkInformationDeleter
{
void operator()(QNetworkInformation *information) { delete information; }
};
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
(QNetworkInformationBackendFactory_iid,
QStringLiteral("/networkinformation")))
struct QStaticNetworkInformationDataHolder
{
QMutex instanceMutex;
std::unique_ptr<QNetworkInformation, QNetworkInformationDeleter> instanceHolder;
QList<QNetworkInformationBackendFactory *> factories;
};
Q_GLOBAL_STATIC(QStaticNetworkInformationDataHolder, dataHolder);
static void networkInfoCleanup()
{
if (!dataHolder.exists())
return;
QMutexLocker locker(&dataHolder->instanceMutex);
QNetworkInformation *instance = dataHolder->instanceHolder.get();
if (!instance)
return;
auto needsReinvoke = instance->thread() && instance->thread() != QThread::currentThread();
if (needsReinvoke) {
QMetaObject::invokeMethod(dataHolder->instanceHolder.get(), []() { networkInfoCleanup(); });
return;
}
dataHolder->instanceHolder.reset();
}
class QNetworkInformationPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QNetworkInformation)
public:
QNetworkInformationPrivate(QNetworkInformationBackend *backend) : backend(backend) {
qAddPostRoutine(&networkInfoCleanup);
}
static QNetworkInformation *create(QNetworkInformation::Features features);
static QNetworkInformation *create(QStringView name);
static QNetworkInformation *instance()
{
if (!dataHolder())
return nullptr;
QMutexLocker locker(&dataHolder->instanceMutex);
return dataHolder->instanceHolder.get();
}
static QStringList backendNames();
static void addToList(QNetworkInformationBackendFactory *factory);
static void removeFromList(QNetworkInformationBackendFactory *factory);
private:
static bool initializeList();
std::unique_ptr<QNetworkInformationBackend> backend;
};
bool QNetworkInformationPrivate::initializeList()
{
if (!loader())
return false;
if (!dataHolder())
return false;
static QBasicMutex mutex;
QMutexLocker initLocker(&mutex);
#if QT_CONFIG(library)
loader->update();
#endif
// Instantiates the plugins (and registers the factories)
int index = 0;
while (loader->instance(index))
++index;
initLocker.unlock();
// Now sort the list on number of features available (then name)
const auto featuresNameOrder = [](QNetworkInformationBackendFactory *a,
QNetworkInformationBackendFactory *b) {
if (!a || !b)
return a && !b;
auto aFeaturesSupported = qPopulationCount(unsigned(a->featuresSupported()));
auto bFeaturesSupported = qPopulationCount(unsigned(b->featuresSupported()));
return aFeaturesSupported > bFeaturesSupported
|| (aFeaturesSupported == bFeaturesSupported
&& a->name().compare(b->name(), Qt::CaseInsensitive) < 0);
};
QMutexLocker instanceLocker(&dataHolder->instanceMutex);
std::sort(dataHolder->factories.begin(), dataHolder->factories.end(), featuresNameOrder);
return !dataHolder->factories.isEmpty();
}
void QNetworkInformationPrivate::addToList(QNetworkInformationBackendFactory *factory)
{
// @note: factory is in the base class ctor
if (!dataHolder())
return;
QMutexLocker locker(&dataHolder->instanceMutex);
dataHolder->factories.append(factory);
}
void QNetworkInformationPrivate::removeFromList(QNetworkInformationBackendFactory *factory)
{
// @note: factory is in the base class dtor
if (!dataHolder.exists())
return;
QMutexLocker locker(&dataHolder->instanceMutex);
dataHolder->factories.removeAll(factory);
}
QStringList QNetworkInformationPrivate::backendNames()
{
if (!dataHolder())
return {};
if (!initializeList())
return {};
QMutexLocker locker(&dataHolder->instanceMutex);
const QList copy = dataHolder->factories;
locker.unlock();
QStringList result;
result.reserve(copy.size());
for (const auto *factory : copy)
result << factory->name();
return result;
}
QNetworkInformation *QNetworkInformationPrivate::create(QStringView name)
{
if (name.isEmpty())
return nullptr;
if (!dataHolder())
return nullptr;
#ifdef DEBUG_LOADING
qDebug().nospace() << "create() called with name=\"" << name
<< "\". instanceHolder initialized? " << !!dataHolder->instanceHolder;
#endif
if (!initializeList()) {
#ifdef DEBUG_LOADING
qDebug("Failed to initialize list, returning.");
#endif
return nullptr;
}
QMutexLocker locker(&dataHolder->instanceMutex);
if (dataHolder->instanceHolder)
return dataHolder->instanceHolder.get();
const auto nameMatches = [name](QNetworkInformationBackendFactory *factory) {
return factory->name().compare(name, Qt::CaseInsensitive) == 0;
};
auto it = std::find_if(dataHolder->factories.cbegin(), dataHolder->factories.cend(),
nameMatches);
if (it == dataHolder->factories.cend()) {
#ifdef DEBUG_LOADING
if (dataHolder->factories.isEmpty()) {
qDebug("No plugins available");
} else {
QString listNames;
listNames.reserve(8 * dataHolder->factories.count());
for (const auto *factory : qAsConst(dataHolder->factories))
listNames += factory->name() + QStringLiteral(", ");
listNames.chop(2);
qDebug().nospace() << "Couldn't find " << name << " in list with names: { "
<< listNames << " }";
}
#endif
return nullptr;
}
#ifdef DEBUG_LOADING
qDebug() << "Creating instance using loader named " << (*it)->name();
#endif
QNetworkInformationBackend *backend = (*it)->create((*it)->featuresSupported());
if (!backend)
return nullptr;
dataHolder->instanceHolder.reset(new QNetworkInformation(backend));
Q_ASSERT(name.isEmpty()
|| dataHolder->instanceHolder->backendName().compare(name, Qt::CaseInsensitive) == 0);
return dataHolder->instanceHolder.get();
}
QNetworkInformation *QNetworkInformationPrivate::create(QNetworkInformation::Features features)
{
if (!dataHolder())
return nullptr;
#ifdef DEBUG_LOADING
qDebug().nospace() << "create() called with features=\"" << features
<< "\". instanceHolder initialized? " << !!dataHolder->instanceHolder;
#endif
if (features == 0)
return nullptr;
if (!initializeList()) {
#ifdef DEBUG_LOADING
qDebug("Failed to initialize list, returning.");
#endif
return nullptr;
}
QMutexLocker locker(&dataHolder->instanceMutex);
if (dataHolder->instanceHolder)
return dataHolder->instanceHolder.get();
const auto supportsRequestedFeatures = [features](QNetworkInformationBackendFactory *factory) {
return factory && (factory->featuresSupported() & features) == features;
};
for (auto it = dataHolder->factories.cbegin(), end = dataHolder->factories.cend(); it != end;
++it) {
it = std::find_if(it, end, supportsRequestedFeatures);
if (it == end) {
#ifdef DEBUG_LOADING
if (dataHolder->factories.isEmpty()) {
qDebug("No plugins available");
} else {
QStringList names;
names.reserve(dataHolder->factories.count());
for (const auto *factory : qAsConst(dataHolder->factories))
names += factory->name();
qDebug() << "None of the following backends has all the requested features:"
<< names << features;
}
#endif
break;
}
#ifdef DEBUG_LOADING
qDebug() << "Creating instance using loader named" << (*it)->name();
#endif
if (QNetworkInformationBackend *backend = (*it)->create(features)) {
dataHolder->instanceHolder.reset(new QNetworkInformation(backend));
Q_ASSERT(dataHolder->instanceHolder->supports(features));
return dataHolder->instanceHolder.get();
}
#ifdef DEBUG_LOADING
else {
qDebug() << "The factory returned a nullptr";
}
#endif
}
#ifdef DEBUG_LOADING
qDebug() << "Couldn't find/create an appropriate backend.";
#endif
return nullptr;
}
/*!
\class QNetworkInformationBackend
\internal (Semi-private)
\brief QNetworkInformationBackend provides the interface with
which QNetworkInformation does all of its actual work.
Deriving from and implementing this class makes it a candidate
for use with QNetworkInformation. The derived class must, on
updates, call setters in the QNetworkInformationBackend which
will update the values and emit signals if the value has changed.
\sa QNetworkInformationBackendFactory
*/
/*!
\internal
Destroys base backend class.
*/
QNetworkInformationBackend::~QNetworkInformationBackend() = default;
/*!
\fn QNetworkInformationBackend::name()
Backend name, return the same in
QNetworkInformationBackendFactory::name().
*/
/*!
\fn QNetworkInformation::Features QNetworkInformationBackend::featuresSupported()
Features supported, return the same in
QNetworkInformationBackendFactory::featuresSupported().
*/
/*!
\fn void QNetworkInformationBackend::reachabilityChanged()
You should not emit this signal manually, call setReachability()
instead which will emit this signal when the value changes.
\sa setReachability
*/
/*!
\fn void QNetworkInformationBackend::setReachability(QNetworkInformation::Reachability reachability)
Call this when reachability has changed. It will automatically
emit reachabilityChanged().
\sa setReachability
*/
/*!
\class QNetworkInformationBackendFactory
\internal (Semi-private)
\brief QNetworkInformationBackendFactory provides the interface
for creating instances of QNetworkInformationBackend.
Deriving from and implementing this class will let you register
your plugin with QNetworkInformation. It must provide some basic
information for querying information about the backend, and must
also create the backend if requested. If some pre-conditions for
the backend is not met it must return \nullptr.
*/
/*!
\internal
Adds the factory to an internal list.
*/
QNetworkInformationBackendFactory::QNetworkInformationBackendFactory()
{
QNetworkInformationPrivate::addToList(this);
}
/*!
\internal
Removes the factory from an internal list.
*/
QNetworkInformationBackendFactory::~QNetworkInformationBackendFactory()
{
QNetworkInformationPrivate::removeFromList(this);
}
/*!
\fn QString QNetworkInformationBackendFactory::name()
Backend name, return the same in
QNetworkInformationBackend::name().
*/
/*!
\fn QNetworkInformation::Features QNetworkInformationBackendFactory::featuresSupported()
Features supported, return the same in
QNetworkInformationBackend::featuresSupported().
The factory should not promise support for features that wouldn't
be available after creating the backend.
*/
/*!
\fn QNetworkInformationBackend *QNetworkInformationBackendFactory::create()
Create and return an instance of QNetworkInformationBackend. It
will be deallocated by QNetworkInformation on shutdown. If some
precondition is not met, meaning the backend would not function
correctly, then you must return \nullptr.
*/
/*!
\class QNetworkInformation
\inmodule QtNetwork
\since 6.1
\brief QNetworkInformation exposes various network information
through native backends.
QNetworkInformation provides a cross-platform interface to
network-related information through plugins.
Various plugins can have various functionality supported, and so
you can load() plugins based on which features are needed.
QNetworkInformation is a singleton and stays alive from the first
successful load() until destruction of the QCoreApplication object.
If you destroy and re-create the QCoreApplication object you must call
load() again.
\sa QNetworkInformation::Feature
*/
/*!
\enum QNetworkInformation::Feature
Lists all of the features that a plugin may currently support.
This can be used in QNetworkInformation::load().
\value Reachability
If the plugin supports this feature then the \c reachability property
will provide useful results. Otherwise it will always return
\c{Reachability::Unknown}.
See also QNetworkInformation::Reachability.
\value CaptivePortal
If the plugin supports this feature then the \c isBehindCaptivePortal
property will provide useful results. Otherwise it will always return
\c{false}.
\value TransportMedium
If the plugin supports this feature then the \c transportMedium
property will provide useful results. Otherwise it will always return
\c{TransportMedium::Unknown}.
See also QNetworkInformation::TransportMedium.
\value Metered
If the plugin supports this feature then the \c isMetered
property will provide useful results. Otherwise it will always return
\c{false}.
*/
/*!
\enum QNetworkInformation::Reachability
\value Unknown
If this value is returned then we may be connected but the OS
has still not confirmed full connectivity, or this feature
is not supported.
\value Disconnected
Indicates that the system may have no connectivity at all.
\value Local
Indicates that the system is connected to a network, but it
might only be able to access devices on the local network.
\value Site
Indicates that the system is connected to a network, but it
might only be able to access devices on the local subnet or an
intranet.
\value Online
Indicates that the system is connected to a network and
able to access the Internet.
\sa QNetworkInformation::reachability
*/
/*!
\enum QNetworkInformation::TransportMedium
\since 6.3
Lists the currently recognized media with which one can connect to the
internet.
\value Unknown
Returned if either the OS reports no active medium, the active medium is
not recognized by Qt, or the TransportMedium feature is not supported.
\value Ethernet
Indicates that the currently active connection is using ethernet.
Note: This value may also be returned when Windows is connected to a
Bluetooth personal area network.
\value Cellular
Indicates that the currently active connection is using a cellular
network.
\value WiFi
Indicates that the currently active connection is using Wi-Fi.
\value Bluetooth
Indicates that the currently active connection is connected using
Bluetooth.
\sa QNetworkInformation::transportMedium
*/
/*!
\internal ctor
*/
QNetworkInformation::QNetworkInformation(QNetworkInformationBackend *backend)
: QObject(*(new QNetworkInformationPrivate(backend)))
{
connect(backend, &QNetworkInformationBackend::reachabilityChanged, this,
&QNetworkInformation::reachabilityChanged);
connect(backend, &QNetworkInformationBackend::behindCaptivePortalChanged, this,
&QNetworkInformation::isBehindCaptivePortalChanged);
connect(backend, &QNetworkInformationBackend::transportMediumChanged, this,
&QNetworkInformation::transportMediumChanged);
connect(backend, &QNetworkInformationBackend::isMeteredChanged, this,
&QNetworkInformation::isMeteredChanged);
}
/*!
\internal dtor
*/
QNetworkInformation::~QNetworkInformation() = default;
/*!
\property QNetworkInformation::reachability
\brief The current state of the system's network connectivity.
Indicates the level of connectivity that can be expected. Do note
that this is only based on what the plugin/operating system
reports. In certain scenarios this is known to be wrong. For
example, on Windows the 'Online' check, by default, is performed
by Windows connecting to a Microsoft-owned server. If this server
is for any reason blocked then it will assume it does not have
Online reachability. Because of this you should not use this as a
pre-check before attempting to make a connection.
*/
QNetworkInformation::Reachability QNetworkInformation::reachability() const
{
return d_func()->backend->reachability();
}
/*!
\property QNetworkInformation::isBehindCaptivePortal
\brief Lets you know if the user's device is behind a captive portal.
\since 6.2
This property indicates if the user's device is currently known to be
behind a captive portal. This functionality relies on the operating system's
detection of captive portals and is not supported on systems that don't
report this. On systems where this is not supported this will always return
\c{false}.
*/
bool QNetworkInformation::isBehindCaptivePortal() const
{
return d_func()->backend->behindCaptivePortal();
}
/*!
\property QNetworkInformation::transportMedium
\brief The currently active transport medium for the application
\since 6.3
This property returns the currently active transport medium for the
application, on operating systems where such information is available.
When the current transport medium changes a signal is emitted, this can,
for instance, occur when a user leaves the range of a WiFi network, unplugs
their ethernet cable or enables Airplane mode.
*/
QNetworkInformation::TransportMedium QNetworkInformation::transportMedium() const
{
return d_func()->backend->transportMedium();
}
/*!
\property QNetworkInformation::isMetered
\brief Check if the current connection is metered
\since 6.3
This property returns whether the current connection is (known to be)
metered or not. You can use this as a guiding factor to decide whether your
application should perform certain network requests or uploads.
For instance, you may not want to upload logs or diagnostics while this
property is \c true.
*/
bool QNetworkInformation::isMetered() const
{
return d_func()->backend->isMetered();
}
/*!
Returns the name of the currently loaded backend.
*/
QString QNetworkInformation::backendName() const
{
return d_func()->backend->name();
}
/*!
Returns \c true if the currently loaded backend supports
\a features.
*/
bool QNetworkInformation::supports(Features features) const
{
return (d_func()->backend->featuresSupported() & features) == features;
}
/*!
\since 6.3
Returns all the supported features of the current backend.
*/
QNetworkInformation::Features QNetworkInformation::supportedFeatures() const
{
return d_func()->backend->featuresSupported();
}
/*!
\since 6.3
Attempts to load the platform-default backend.
This platform-to-plugin mapping is as follows:
\table
\header
\li Platform
\li Plugin-name
\row
\li Windows
\li networklistmanager
\row
\li Apple (macOS/iOS)
\li scnetworkreachability
\row
\li Android
\li android
\row
\li Linux
\li networkmanager
\endtable
This function is provided for convenience where the default for a given
platform is good enough. If you are not using the default plugins you must
use one of the other load() overloads.
Returns \c true if it managed to load the backend or if it was already
loaded. Returns \c false otherwise.
\sa instance
*/
bool QNetworkInformation::load()
{
int index = -1;
#ifdef Q_OS_WIN
index = QNetworkInformationBackend::PluginNamesWindowsIndex;
#elif defined(Q_OS_DARWIN)
index = QNetworkInformationBackend::PluginNamesAppleIndex;
#elif defined(Q_OS_ANDROID)
index = QNetworkInformationBackend::PluginNamesAndroidIndex;
#elif defined(Q_OS_LINUX)
index = QNetworkInformationBackend::PluginNamesLinuxIndex;
#endif
if (index == -1)
return false;
return load(QNetworkInformationBackend::PluginNames[index]);
}
/*!
Attempts to load a backend whose name matches \a backend
(case insensitively).
Returns \c true if it managed to load the requested backend or
if it was already loaded. Returns \c false otherwise.
\sa instance
*/
bool QNetworkInformation::load(QStringView backend)
{
auto loadedBackend = QNetworkInformationPrivate::create(backend);
return loadedBackend && loadedBackend->backendName().compare(backend, Qt::CaseInsensitive) == 0;
}
/*!
Load a backend which supports \a features.
Returns \c true if it managed to load the requested backend or
if it was already loaded. Returns \c false otherwise.
\sa instance
*/
bool QNetworkInformation::load(Features features)
{
auto loadedBackend = QNetworkInformationPrivate::create(features);
return loadedBackend && loadedBackend->supports(features);
}
/*!
Returns a list of the names of all currently available backends.
*/
QStringList QNetworkInformation::availableBackends()
{
return QNetworkInformationPrivate::backendNames();
}
/*!
Returns a pointer to the instance of the QNetworkInformation,
if any.
\sa load()
*/
QNetworkInformation *QNetworkInformation::instance()
{
return QNetworkInformationPrivate::instance();
}
QT_END_NAMESPACE
#include "moc_qnetworkinformation.cpp"
#include "moc_qnetworkinformation_p.cpp"
|