1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39 
40 // see comment in ../platformdefs_win.h.
41 #define WIN32_LEAN_AND_MEAN 1
42 
43 #include "qgenericengine.h"
44 #include "../qnetworksession_impl.h"
45 
46 #include <QtNetwork/private/qnetworkconfiguration_p.h>
47 
48 #include <QtCore/qthread.h>
49 #include <QtCore/qmutex.h>
50 #include <QtCore/qcoreapplication.h>
51 #include <QtCore/qstringlist.h>
52 
53 #include <QtCore/qdebug.h>
54 #include <QtCore/private/qcoreapplication_p.h>
55 
56 #if defined(Q_OS_WIN32)
57 // PMIB_TCPTABLE2 is only available since Vista
58 #if _WIN32_WINNT < 0x0601
59 #  undef _WIN32_WINNT
60 #  define _WIN32_WINNT 0x0601
61 #endif // _WIN32_WINNT < 0x0601
62 #include "../platformdefs_win.h"
63 #include <iphlpapi.h>
64 #endif
65 
66 #ifdef Q_OS_WINRT
67 #include <qfunctions_winrt.h>
68 
69 #include <wrl.h>
70 #include <windows.foundation.h>
71 #include <windows.foundation.collections.h>
72 #include <windows.networking.connectivity.h>
73 
74 using namespace Microsoft::WRL;
75 using namespace Microsoft::WRL::Wrappers;
76 using namespace ABI::Windows::Foundation;
77 using namespace ABI::Windows::Foundation::Collections;
78 using namespace ABI::Windows::Networking;
79 using namespace ABI::Windows::Networking::Connectivity;
80 #endif // Q_OS_WINRT
81 
82 // needed as interface is used as parameter name in qGetInterfaceType
83 #undef interface
84 
85 #ifdef Q_OS_LINUX
86 #include <sys/socket.h>
87 #include <sys/ioctl.h>
88 #include <net/if.h>
89 #include <net/if_arp.h>
90 #include <unistd.h>
91 #endif
92 
93 QT_BEGIN_NAMESPACE
94 
95 #ifndef QT_NO_NETWORKINTERFACE
qGetInterfaceType(const QString & interface)96 static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interface)
97 {
98 #if defined(Q_OS_WIN32)
99     // QNetworkInterface::name returns a more friendly name on Windows. That name is not
100     // accepted as an identifier for CreateFile so we have to obtain the Luid.
101     std::wstring buf = interface.toStdWString();
102     if (buf.size() == 0)
103         return QNetworkConfiguration::BearerUnknown;
104 
105     NET_LUID luid;
106     NETIO_STATUS status = ConvertInterfaceNameToLuidW(buf.c_str(), &luid);
107     if (status != NO_ERROR)
108         return QNetworkConfiguration::BearerUnknown;
109 
110     switch (luid.Info.IfType) {
111     case IF_TYPE_ETHERNET_CSMACD:
112     case IF_TYPE_ISO88025_TOKENRING:
113     case IF_TYPE_PPP:
114     case IF_TYPE_SOFTWARE_LOOPBACK:
115         return QNetworkConfiguration::BearerEthernet;
116     case IF_TYPE_IEEE80211:
117         return QNetworkConfiguration::BearerWLAN;
118     case IF_TYPE_ATM:
119     case IF_TYPE_IEEE1394:
120     case IF_TYPE_OTHER:
121     case IF_TYPE_TUNNEL:
122         return QNetworkConfiguration::BearerUnknown;
123     default:
124 #ifdef BEARER_MANAGEMENT_DEBUG
125         qDebug() << "Interface Type" << luid.Info.IfType;
126 #endif
127         return QNetworkConfiguration::BearerUnknown;
128     }
129     return QNetworkConfiguration::BearerUnknown;
130 
131 #elif defined(Q_OS_LINUX)
132     int sock = socket(AF_INET, SOCK_DGRAM, 0);
133 
134     ifreq request;
135     strncpy(request.ifr_name, interface.toLocal8Bit().data(), sizeof(request.ifr_name) - 1);
136     request.ifr_name[sizeof(request.ifr_name) - 1] = '\0';
137     int result = ioctl(sock, SIOCGIFHWADDR, &request);
138     close(sock);
139 
140     if (result >= 0 && request.ifr_hwaddr.sa_family == ARPHRD_ETHER)
141         return QNetworkConfiguration::BearerEthernet;
142 #elif defined(Q_OS_WINRT)
143     ComPtr<INetworkInformationStatics> networkInfoStatics;
144     HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &networkInfoStatics);
145     Q_ASSERT_SUCCEEDED(hr);
146     ComPtr<IVectorView<ConnectionProfile *>> connectionProfiles;
147     hr = networkInfoStatics->GetConnectionProfiles(&connectionProfiles);
148     Q_ASSERT_SUCCEEDED(hr);
149     if (!connectionProfiles)
150         return QNetworkConfiguration::BearerUnknown;
151 
152     unsigned int size;
153     hr = connectionProfiles->get_Size(&size);
154     Q_ASSERT_SUCCEEDED(hr);
155     for (unsigned int i = 0; i < size; ++i) {
156         ComPtr<IConnectionProfile> profile;
157         hr = connectionProfiles->GetAt(i, &profile);
158         Q_ASSERT_SUCCEEDED(hr);
159 
160         ComPtr<INetworkAdapter> adapter;
161         hr = profile->get_NetworkAdapter(&adapter);
162         // Indicates that no internet connection is available/the device is in airplane mode
163         if (hr == E_INVALIDARG)
164             return QNetworkConfiguration::BearerUnknown;
165         Q_ASSERT_SUCCEEDED(hr);
166         GUID id;
167         hr = adapter->get_NetworkAdapterId(&id);
168         Q_ASSERT_SUCCEEDED(hr);
169         OLECHAR adapterName[39]={0};
170         int length = StringFromGUID2(id, adapterName, 39);
171         // "length - 1" as we have to remove the null terminator from it in order to compare
172         if (!length
173                 || QString::fromRawData(reinterpret_cast<const QChar *>(adapterName), length - 1) != interface)
174             continue;
175 
176         ComPtr<IConnectionProfile2> profile2;
177         hr = profile.As(&profile2);
178         Q_ASSERT_SUCCEEDED(hr);
179         boolean isWLan;
180         hr = profile2->get_IsWlanConnectionProfile(&isWLan);
181         Q_ASSERT_SUCCEEDED(hr);
182         if (isWLan)
183             return QNetworkConfiguration::BearerWLAN;
184 
185         boolean isWWan;
186         hr = profile2->get_IsWwanConnectionProfile(&isWWan);
187         Q_ASSERT_SUCCEEDED(hr);
188         if (isWWan) {
189             ComPtr<IWwanConnectionProfileDetails> details;
190             hr = profile2->get_WwanConnectionProfileDetails(&details);
191             Q_ASSERT_SUCCEEDED(hr);
192             WwanDataClass dataClass;
193             hr = details->GetCurrentDataClass(&dataClass);
194             Q_ASSERT_SUCCEEDED(hr);
195             switch (dataClass) {
196             case WwanDataClass_Edge:
197             case WwanDataClass_Gprs:
198                 return QNetworkConfiguration::Bearer2G;
199             case WwanDataClass_Umts:
200                 return QNetworkConfiguration::BearerWCDMA;
201             case WwanDataClass_LteAdvanced:
202                 return QNetworkConfiguration::BearerLTE;
203             case WwanDataClass_Hsdpa:
204             case WwanDataClass_Hsupa:
205                 return QNetworkConfiguration::BearerHSPA;
206             case WwanDataClass_Cdma1xRtt:
207             case WwanDataClass_Cdma3xRtt:
208             case WwanDataClass_CdmaUmb:
209                 return QNetworkConfiguration::BearerCDMA2000;
210             case WwanDataClass_Cdma1xEvdv:
211             case WwanDataClass_Cdma1xEvdo:
212             case WwanDataClass_Cdma1xEvdoRevA:
213             case WwanDataClass_Cdma1xEvdoRevB:
214                 return QNetworkConfiguration::BearerEVDO;
215             case WwanDataClass_Custom:
216             case WwanDataClass_None:
217             default:
218                 return QNetworkConfiguration::BearerUnknown;
219             }
220         }
221         return QNetworkConfiguration::BearerEthernet;
222     }
223 #else
224     Q_UNUSED(interface);
225 #endif
226 
227     return QNetworkConfiguration::BearerUnknown;
228 }
229 #endif
230 
QGenericEngine(QObject * parent)231 QGenericEngine::QGenericEngine(QObject *parent)
232 :   QBearerEngineImpl(parent)
233 {
234     //workaround for deadlock in __cxa_guard_acquire with webkit on macos x
235     //initialise the Q_GLOBAL_STATIC in same thread as the AtomicallyInitializedStatic
236     (void)QNetworkInterface::interfaceFromIndex(0);
237 }
238 
~QGenericEngine()239 QGenericEngine::~QGenericEngine()
240 {
241 }
242 
getInterfaceFromId(const QString & id)243 QString QGenericEngine::getInterfaceFromId(const QString &id)
244 {
245     QMutexLocker locker(&mutex);
246 
247     return configurationInterface.value(id);
248 }
249 
hasIdentifier(const QString & id)250 bool QGenericEngine::hasIdentifier(const QString &id)
251 {
252     QMutexLocker locker(&mutex);
253 
254     return configurationInterface.contains(id);
255 }
256 
connectToId(const QString & id)257 void QGenericEngine::connectToId(const QString &id)
258 {
259     emit connectionError(id, OperationNotSupported);
260 }
261 
disconnectFromId(const QString & id)262 void QGenericEngine::disconnectFromId(const QString &id)
263 {
264     emit connectionError(id, OperationNotSupported);
265 }
266 
initialize()267 void QGenericEngine::initialize()
268 {
269     doRequestUpdate();
270 }
271 
requestUpdate()272 void QGenericEngine::requestUpdate()
273 {
274     doRequestUpdate();
275 }
276 
doRequestUpdate()277 void QGenericEngine::doRequestUpdate()
278 {
279 #ifndef QT_NO_NETWORKINTERFACE
280     QMutexLocker locker(&mutex);
281 
282     // Immediately after connecting with a wireless access point
283     // QNetworkInterface::allInterfaces() will sometimes return an empty list. Calling it again a
284     // second time results in a non-empty list. If we loose interfaces we will end up removing
285     // network configurations which will break current sessions.
286     QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
287     if (interfaces.isEmpty())
288         interfaces = QNetworkInterface::allInterfaces();
289 
290     QStringList previous = accessPointConfigurations.keys();
291 
292     // create configuration for each interface
293     while (!interfaces.isEmpty()) {
294         QNetworkInterface interface = interfaces.takeFirst();
295 
296         if (!interface.isValid())
297             continue;
298 
299         // ignore loopback interface
300         if (interface.flags() & QNetworkInterface::IsLoopBack)
301             continue;
302 
303 #ifndef Q_OS_WIN
304         // ignore WLAN interface handled in separate engine
305         if (qGetInterfaceType(interface.name()) == QNetworkConfiguration::BearerWLAN)
306             continue;
307 #endif
308 
309         uint identifier;
310         if (interface.index())
311             identifier = qHash(QLatin1String("generic:") + QString::number(interface.index()));
312         else
313             identifier = qHash(QLatin1String("generic:") + interface.hardwareAddress());
314 
315         const QString id = QString::number(identifier);
316 
317         previous.removeAll(id);
318 
319         QString name = interface.humanReadableName();
320         if (name.isEmpty())
321             name = interface.name();
322 
323         QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Defined;
324         if ((interface.flags() & QNetworkInterface::IsRunning) && !interface.addressEntries().isEmpty())
325             state |= QNetworkConfiguration::Active;
326 
327         if (accessPointConfigurations.contains(id)) {
328             QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
329 
330             bool changed = false;
331 
332             ptr->mutex.lock();
333 
334             if (!ptr->isValid) {
335                 ptr->isValid = true;
336                 changed = true;
337             }
338 
339             if (ptr->name != name) {
340                 ptr->name = name;
341                 changed = true;
342             }
343 
344             if (ptr->id != id) {
345                 ptr->id = id;
346                 changed = true;
347             }
348 
349             if (ptr->state != state) {
350                 ptr->state = state;
351                 changed = true;
352             }
353 
354             ptr->mutex.unlock();
355 
356             if (changed) {
357                 locker.unlock();
358                 emit configurationChanged(ptr);
359                 locker.relock();
360             }
361         } else {
362             QNetworkConfigurationPrivatePointer ptr(new QNetworkConfigurationPrivate);
363 
364             ptr->name = name;
365             ptr->isValid = true;
366             ptr->id = id;
367             ptr->state = state;
368             ptr->type = QNetworkConfiguration::InternetAccessPoint;
369             ptr->bearerType = qGetInterfaceType(interface.name());
370 
371             accessPointConfigurations.insert(id, ptr);
372             configurationInterface.insert(id, interface.name());
373 
374             locker.unlock();
375             emit configurationAdded(ptr);
376             locker.relock();
377         }
378     }
379 
380     while (!previous.isEmpty()) {
381         QNetworkConfigurationPrivatePointer ptr =
382             accessPointConfigurations.take(previous.takeFirst());
383 
384         configurationInterface.remove(ptr->id);
385 
386         locker.unlock();
387         emit configurationRemoved(ptr);
388         locker.relock();
389     }
390 
391     locker.unlock();
392 #endif
393 
394     emit updateCompleted();
395 }
396 
sessionStateForId(const QString & id)397 QNetworkSession::State QGenericEngine::sessionStateForId(const QString &id)
398 {
399     QMutexLocker locker(&mutex);
400 
401     QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
402 
403     if (!ptr)
404         return QNetworkSession::Invalid;
405 
406     QMutexLocker configLocker(&ptr->mutex);
407 
408     if (!ptr->isValid) {
409         return QNetworkSession::Invalid;
410     } else if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
411         return QNetworkSession::Connected;
412     } else if ((ptr->state & QNetworkConfiguration::Discovered) ==
413                 QNetworkConfiguration::Discovered) {
414         return QNetworkSession::Disconnected;
415     } else if ((ptr->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
416         return QNetworkSession::NotAvailable;
417     } else if ((ptr->state & QNetworkConfiguration::Undefined) ==
418                 QNetworkConfiguration::Undefined) {
419         return QNetworkSession::NotAvailable;
420     }
421 
422     return QNetworkSession::Invalid;
423 }
424 
capabilities() const425 QNetworkConfigurationManager::Capabilities QGenericEngine::capabilities() const
426 {
427     return QNetworkConfigurationManager::ForcedRoaming;
428 }
429 
createSessionBackend()430 QNetworkSessionPrivate *QGenericEngine::createSessionBackend()
431 {
432     return new QNetworkSessionPrivateImpl;
433 }
434 
defaultConfiguration()435 QNetworkConfigurationPrivatePointer QGenericEngine::defaultConfiguration()
436 {
437     return QNetworkConfigurationPrivatePointer();
438 }
439 
440 
requiresPolling() const441 bool QGenericEngine::requiresPolling() const
442 {
443     return true;
444 }
445 
446 QT_END_NAMESPACE
447