summaryrefslogtreecommitdiffstats
path: root/src/network/kernel/qnetworkinformation.cpp
blob: 355c6ab411949298237599fc259b61f19d054686 (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
/****************************************************************************
**
** 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/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("/networkinformationbackends")))

struct QStaticNetworkInformationDataHolder
{
    QMutex instanceMutex;
    std::unique_ptr<QNetworkInformation, QNetworkInformationDeleter> instanceHolder;
    QList<QNetworkInformationBackendFactory *> factories;
};
Q_GLOBAL_STATIC(QStaticNetworkInformationDataHolder, dataHolder);

class QNetworkInformationPrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QNetworkInformation)
public:
    QNetworkInformationPrivate(QNetworkInformationBackend *backend) : backend(backend) { }

    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({});
    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
    \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 application shutdown.

    \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 be available.
        See also QNetworkInformation::Reachability.
*/

/*!
    \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 features
        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
*/

/*!
    \internal ctor
*/
QNetworkInformation::QNetworkInformation(QNetworkInformationBackend *backend)
    : QObject(*(new QNetworkInformationPrivate(backend)))
{
    connect(backend, &QNetworkInformationBackend::reachabilityChanged, this,
            [this]() { emit reachabilityChanged(d_func()->backend->reachability()); });
}

/*!
    \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();
}

/*!
    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;
}

/*!
    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() == backend;
}

/*!
    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