From 8eed261877ec5ca041ce5b5113bbc4b5c56996a1 Mon Sep 17 00:00:00 2001 From: Shane Kearns Date: Tue, 2 Aug 2011 14:17:39 +0100 Subject: [PATCH] Replace QtBearer implementation with a shim over QtNetwork The bearer management API was integrated into QtNetwork 4.7 This change removes the parallel implementation from QtBearer and inserts a shim for binary compatibility. Applications which linked against QtBearer will now be using the implementation from QtNetwork transparently. QNetworkSession had a private 'd' pointer, the private class is changed to contain a ::QNetworkSession, and API calls are redirected. Signals are connected to the signals of the outer class, or through translation slots of the inner class where casting is required. QNetworkConfigurationManager had no 'd' pointer, but a global static private implementation. This is similarly changed to contain a ::QNetworkConfigurationManager which is used to redirect API calls. Qt's meta object system can't distinguish between QNetworkConfiguration and QtMobility::QNetworkConfiguration. This is because the signals in QtBearer were declared without including the namespace in the parameters. MOC doesn't understand c++ namespaces properly. As QVariants can be cast to the wrong type, a different approach is taken for QNetworkConfiguration to avoid crashes when using QSignalSpy or queued connections. QNetworkConfiguration now derives from ::QNetworkConfiguration. The QNetworkConfiguration 'd' pointer is removed (the Qt class has a 'd' pointer) This makes the two classes bitwise identical except for the vtable for the virtual destructor. QtMobility::QNetworkConfiguration APIs just base-call the Qt class. There is a new private constructor to allow a QtMobility::QNetworkConfiguration to be constructed from a Qt one. The two virtual adaptor classes exist to avoid namespace conflicts QtBearer no longer exports any header files. This version of QtBearer has a dependency on Qt 4.7 or higher, and the Qt headers include the QtMobility version of the API already. Exporting the QtBearer headers causes compile errors in case an application picked up the wrong header files. Testing: Ran qt bearer autotests on symbian3, compiled and run against qt 4.8 and this version of qt mobility. Ran qt bearer autotests on symbian3, compiled against qt 4.6.3 and qt mobility 1.0.2; run against qt 4.8 and this version of qt mobility. --- src/bearer/bearer.pri | 118 +-- src/bearer/bearer.pro | 6 - src/bearer/bearer_old/bearer_old.pro | 34 - src/bearer/qcorewlanengine_mac.mm | 832 ------------ src/bearer/qcorewlanengine_mac_p.h | 150 -- src/bearer/qgenericengine.cpp | 257 ---- src/bearer/qgenericengine_p.h | 94 -- src/bearer/qnativewifiengine_win.cpp | 730 ---------- src/bearer/qnativewifiengine_win_p.h | 95 -- src/bearer/qnetworkconfigmanager.cpp | 97 +- src/bearer/qnetworkconfigmanager.h | 6 +- src/bearer/qnetworkconfigmanager_maemo.cpp | 910 ------------- src/bearer/qnetworkconfigmanager_maemo_p.h | 166 --- src/bearer/qnetworkconfigmanager_p.cpp | 453 ------- src/bearer/qnetworkconfigmanager_p.h | 120 +-- src/bearer/qnetworkconfigmanager_s60_p.cpp | 1273 ----------------- src/bearer/qnetworkconfigmanager_s60_p.h | 209 --- src/bearer/qnetworkconfigmanageradaptor_p.h | 70 + src/bearer/qnetworkconfiguration.cpp | 71 +- src/bearer/qnetworkconfiguration.h | 14 +- src/bearer/qnetworkconfiguration_maemo_p.h | 125 -- src/bearer/qnetworkconfiguration_p.h | 110 -- src/bearer/qnetworkconfiguration_s60_p.cpp | 76 - src/bearer/qnetworkconfiguration_s60_p.h | 120 -- src/bearer/qnetworkmanagerservice_p.cpp | 916 ------------- src/bearer/qnetworkmanagerservice_p.h | 440 ------ src/bearer/qnetworksession.cpp | 143 +-- src/bearer/qnetworksession.h | 6 +- src/bearer/qnetworksession_maemo.cpp | 1038 -------------- src/bearer/qnetworksession_maemo_p.h | 228 ---- src/bearer/qnetworksession_p.cpp | 534 -------- src/bearer/qnetworksession_p.h | 108 +-- src/bearer/qnetworksession_s60_p.cpp | 1428 -------------------- src/bearer/qnetworksession_s60_p.h | 223 --- src/bearer/qnetworksessionadaptor_p.h | 72 + src/bearer/qnetworksessionengine.cpp | 57 - src/bearer/qnetworksessionengine_p.h | 98 -- src/bearer/qnetworksessionengine_win_p.h | 145 -- src/bearer/qnlaengine_win.cpp | 600 -------- src/bearer/qnlaengine_win_p.h | 104 -- src/bearer/qnmdbushelper.cpp | 127 -- src/bearer/qnmdbushelper_p.h | 92 -- src/bearer/qnmwifiengine_unix.cpp | 838 ------------ src/bearer/qnmwifiengine_unix_p.h | 159 --- .../qnetworkconfigmanager.pro | 2 - .../tst_qnetworkconfigmanager.cpp | 4 +- .../qnetworkconfiguration.pro | 2 - .../tst_qnetworkconfiguration.cpp | 4 +- tests/auto/qnetworksession/lackey/main.cpp | 6 +- .../tst_qnetworksession/tst_qnetworksession.cpp | 4 +- .../tst_qnetworksession/tst_qnetworksession.pro | 2 - 51 files changed, 325 insertions(+), 13191 deletions(-) delete mode 100644 src/bearer/bearer_old/bearer_old.pro delete mode 100644 src/bearer/qcorewlanengine_mac.mm delete mode 100644 src/bearer/qcorewlanengine_mac_p.h delete mode 100644 src/bearer/qgenericengine.cpp delete mode 100644 src/bearer/qgenericengine_p.h delete mode 100644 src/bearer/qnativewifiengine_win.cpp delete mode 100644 src/bearer/qnativewifiengine_win_p.h delete mode 100644 src/bearer/qnetworkconfigmanager_maemo.cpp delete mode 100644 src/bearer/qnetworkconfigmanager_maemo_p.h delete mode 100644 src/bearer/qnetworkconfigmanager_p.cpp delete mode 100644 src/bearer/qnetworkconfigmanager_s60_p.cpp delete mode 100644 src/bearer/qnetworkconfigmanager_s60_p.h create mode 100644 src/bearer/qnetworkconfigmanageradaptor_p.h delete mode 100644 src/bearer/qnetworkconfiguration_maemo_p.h delete mode 100644 src/bearer/qnetworkconfiguration_p.h delete mode 100644 src/bearer/qnetworkconfiguration_s60_p.cpp delete mode 100644 src/bearer/qnetworkconfiguration_s60_p.h delete mode 100644 src/bearer/qnetworkmanagerservice_p.cpp delete mode 100644 src/bearer/qnetworkmanagerservice_p.h delete mode 100644 src/bearer/qnetworksession_maemo.cpp delete mode 100644 src/bearer/qnetworksession_maemo_p.h delete mode 100644 src/bearer/qnetworksession_p.cpp delete mode 100644 src/bearer/qnetworksession_s60_p.cpp delete mode 100644 src/bearer/qnetworksession_s60_p.h create mode 100644 src/bearer/qnetworksessionadaptor_p.h delete mode 100644 src/bearer/qnetworksessionengine.cpp delete mode 100644 src/bearer/qnetworksessionengine_p.h delete mode 100644 src/bearer/qnetworksessionengine_win_p.h delete mode 100644 src/bearer/qnlaengine_win.cpp delete mode 100644 src/bearer/qnlaengine_win_p.h delete mode 100644 src/bearer/qnmdbushelper.cpp delete mode 100644 src/bearer/qnmdbushelper_p.h delete mode 100644 src/bearer/qnmwifiengine_unix.cpp delete mode 100644 src/bearer/qnmwifiengine_unix_p.h diff --git a/src/bearer/bearer.pri b/src/bearer/bearer.pri index 0b8d2dd..88dca8d 100644 --- a/src/bearer/bearer.pri +++ b/src/bearer/bearer.pri @@ -6,46 +6,22 @@ SOURCES += qnetworksession.cpp \ qnetworkconfigmanager.cpp \ qnetworkconfiguration.cpp +HEADERS += qnetworksession.h \ + qnetworkconfiguration.h \ + qnetworkconfigmanager.h \ + qnetworksession_p.h \ + qnetworksessionadaptor_p.h \ + qnetworkconfigmanager_p.h \ + qnetworkconfigmanageradaptor_p.h + symbian: { - contains (occ_enabled, yes) { - message("Building with OCC enabled") - DEFINES += OCC_FUNCTIONALITY_AVAILABLE=1 - LIBS += -lextendedconnpref - } else { - message("Building without OCC support") - } - contains(snap_enabled, yes) { - message("Building with SNAP support") - DEFINES += SNAP_FUNCTIONALITY_AVAILABLE=1 - LIBS += -lcmmanager - } else { - message("Building without SNAP support") - LIBS += -lapengine - } - INCLUDEPATH += $$APP_LAYER_SYSTEMINCLUDE - - HEADERS += qnetworkconfigmanager_s60_p.h \ - qnetworkconfiguration_s60_p.h \ - qnetworksession_s60_p.h - SOURCES += qnetworkconfigmanager_s60_p.cpp \ - qnetworkconfiguration_s60_p.cpp \ - qnetworksession_s60_p.cpp - - LIBS += -lcommdb \ - -lconnmon \ - -lcentralrepository \ - -lesock \ - -linsock \ - -lecom \ - -lefsrv \ - -lnetmeta - TARGET.CAPABILITY = ALL -TCB TARGET.UID3 = 0x2002AC81 - + QtBearerManagement.sources = QtBearer.dll QtBearerManagement.path = /sys/bin + QtBearerManagement.pkg_prerules += $${LITERAL_HASH}{\"QtBearer\"},(0x2002AC81),1,2,1,TYPE=SA,RU DEPLOYMENT += QtBearerManagement } else { maemo6|maemo5 { @@ -57,13 +33,6 @@ symbian: { DEFINES += BEARER_MANAGEMENT_DEBUG } - HEADERS += qnetworksession_maemo_p.h \ - qnetworkconfigmanager_maemo_p.h \ - qnetworkconfiguration_maemo_p.h - - SOURCES += qnetworkconfigmanager_maemo.cpp \ - qnetworksession_maemo.cpp - documentation.path = $$QT_MOBILITY_PREFIX/doc documentation.files = doc/html @@ -73,73 +42,6 @@ symbian: { INSTALLS += documentation - } else { - - DEFINES += BEARER_ENGINE - - HEADERS += qnetworkconfigmanager_p.h \ - qnetworkconfiguration_p.h \ - qnetworksession_p.h \ - qnetworksessionengine_p.h \ - qgenericengine_p.h - - SOURCES += qnetworkconfigmanager_p.cpp \ - qnetworksession_p.cpp \ - qnetworksessionengine.cpp \ - qgenericengine.cpp - - unix:!mac:contains(networkmanager_enabled, yes) { - contains(QT_CONFIG,dbus) { - DEFINES += BACKEND_NM - QT += dbus - - HEADERS += qnmdbushelper_p.h \ - qnetworkmanagerservice_p.h \ - qnmwifiengine_unix_p.h - - SOURCES += qnmdbushelper.cpp \ - qnetworkmanagerservice_p.cpp \ - qnmwifiengine_unix.cpp - } else { - message("NetworkManager backend requires Qt DBus support") - } - } - - win32: { - HEADERS += qnlaengine_win_p.h \ - qnetworksessionengine_win_p.h - - !wince*:HEADERS += qnativewifiengine_win_p.h - - SOURCES += qnlaengine_win.cpp - - !wince*:SOURCES += qnativewifiengine_win.cpp - - !wince*:LIBS += -lWs2_32 - wince*:LIBS += -lWs2 - } - } - macx: { - HEADERS += qcorewlanengine_mac_p.h - SOURCES+= qcorewlanengine_mac.mm - LIBS += -framework Foundation -framework SystemConfiguration - - contains(corewlan_enabled, yes) { - isEmpty(QMAKE_MAC_SDK) { - SDK6="yes" - } else { - contains(QMAKE_MAC_SDK, "/Developer/SDKs/MacOSX10.6.sdk") { - SDK6="yes" - } - } - - !isEmpty(SDK6) { - LIBS += -framework CoreWLAN -framework Security - DEFINES += MAC_SDK_10_6 - } - } - - } } diff --git a/src/bearer/bearer.pro b/src/bearer/bearer.pro index adaceb2..1604182 100644 --- a/src/bearer/bearer.pro +++ b/src/bearer/bearer.pro @@ -5,10 +5,4 @@ TARGET = QtBearer QT += network include (../../common.pri) -PUBLIC_HEADERS += qnetworkconfiguration.h \ - qnetworksession.h \ - qnetworkconfigmanager.h - -HEADERS += $$PUBLIC_HEADERS - include(bearer.pri) diff --git a/src/bearer/bearer_old/bearer_old.pro b/src/bearer/bearer_old/bearer_old.pro deleted file mode 100644 index ac988c7..0000000 --- a/src/bearer/bearer_old/bearer_old.pro +++ /dev/null @@ -1,34 +0,0 @@ -# Qt bearer management library -TEMPLATE = lib -TARGET = QtBearer{000a0000} - -QT += network -message("Building QtBearer 10.0 to support version conflict in Symbian") - -VPATH += .. - -HEADERS += qnetworkconfiguration.h \ - qnetworksession.h \ - qnetworkconfigmanager.h - -include (../../../common.pri) -include (../bearer.pri) - -symbian { - - # there are same name public headers from Qt - # and this needs to be added to ensure QtBearer - # uses its own when the 10.0 version is compiled - MMP_RULES += "USERINCLUDE .." - - CONFIG += def_files_disabled - MMP_RULES += defBlock - defBlock = \ - "$${LITERAL_HASH}ifdef WINSCW" \ - "DEFFILE ../../s60installs/bwins/QtBearer.def" \ - "$${LITERAL_HASH}elif defined EABI" \ - "DEFFILE ../../s60installs/eabi/QtBearer.def" \ - "$${LITERAL_HASH}endif" -} - -VERSION=10.0 diff --git a/src/bearer/qcorewlanengine_mac.mm b/src/bearer/qcorewlanengine_mac.mm deleted file mode 100644 index 3e4f909..0000000 --- a/src/bearer/qcorewlanengine_mac.mm +++ /dev/null @@ -1,832 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcorewlanengine_mac_p.h" -#include "qnetworkconfiguration_p.h" - -#include -#include -#include -#include -#include - -#include - -#include -#if defined(MAC_SDK_10_6) //not much functionality without this -#include -#include -#include -#include -#include - -#endif - -#include -#include -#include - -#include -QMap networkInterfaces; - -#ifdef MAC_SDK_10_6 -@interface QNSListener : NSObject -{ - NSNotificationCenter *center; - CWInterface * currentInterface; -} -- (void)notificationHandler;//:(NSNotification *)notification; -- (void)remove; -@end - -@implementation QNSListener -- (id) init -{ - [super init]; - center = [NSNotificationCenter defaultCenter]; - currentInterface = [CWInterface interfaceWithName:nil]; - [center addObserver:self selector:@selector(notificationHandler:) name:kCWLinkDidChangeNotification object:nil]; - [center addObserver:self selector:@selector(notificationHandler:) name:kCWPowerDidChangeNotification object:nil]; - - return self; -} - --(void)dealloc -{ - [center release]; - [currentInterface release]; - [super dealloc]; -} - --(void)remove -{ - [center removeObserver:self]; -} - -- (void)notificationHandler;//:(NSNotification *)notification -{ - QTM_NAMESPACE::QCoreWlanEngine::instance()->requestUpdate(); -} -@end - -QNSListener *listener = 0; -#endif - -QTM_BEGIN_NAMESPACE - -Q_GLOBAL_STATIC(QCoreWlanEngine, coreWlanEngine) - -inline QString cfstringRefToQstring(CFStringRef cfStringRef) { - QString retVal; - CFIndex maxLength = 2 * CFStringGetLength(cfStringRef) + 1/*zero term*/; // max UTF8 - char *cstring = new char[maxLength]; - if (CFStringGetCString(CFStringRef(cfStringRef), cstring, maxLength, kCFStringEncodingUTF8)) { - retVal = QString::fromUtf8(cstring); - } - delete[] cstring; - return retVal; -} - -inline CFStringRef qstringToCFStringRef(const QString &string) -{ - return CFStringCreateWithCharacters(0, reinterpret_cast(string.unicode()), - string.length()); -} - -inline NSString *qstringToNSString(const QString &qstr) -{ return [reinterpret_cast(qstringToCFStringRef(qstr)) autorelease]; } - -inline QString nsstringToQString(const NSString *nsstr) -{ return cfstringRefToQstring(reinterpret_cast(nsstr)); } - -inline QStringList nsarrayToQStringList(void *nsarray) -{ - QStringList result; - NSArray *array = static_cast(nsarray); - for (NSUInteger i=0; i<[array count]; ++i) - result << nsstringToQString([array objectAtIndex:i]); - return result; -} - -void networkChangeCallback(SCDynamicStoreRef/* store*/, CFArrayRef changedKeys, void *info) -{ - for ( long i = 0; i < CFArrayGetCount(changedKeys); i++) { - - CFStringRef changed = (CFStringRef)CFArrayGetValueAtIndex(changedKeys, i); - if( cfstringRefToQstring(changed).contains("/Network/Global/IPv4")) { - QCoreWlanEngine* wlanEngine = static_cast(info); - wlanEngine->requestUpdate(); - } - } - return; -} - -QScanThread::QScanThread(QObject *parent) - :QThread(parent), interfaceName() -{ -} - -QScanThread::~QScanThread() -{ -} - -void QScanThread::quit() -{ - wait(); -} - -void QScanThread::run() -{ -#if defined(MAC_SDK_10_6) - getUserProfiles(); - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - QStringList found; - mutex.lock(); - CWInterface *currentInterface; - if(interfaceName.isEmpty()) { - currentInterface = [CWInterface interfaceWithName:nil]; - interfaceName = nsstringToQString([currentInterface name]); - } else { - currentInterface = [CWInterface interfaceWithName:qstringToNSString(interfaceName)]; - } - mutex.unlock(); - - if([currentInterface power]) { - NSError *err = nil; - NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], kCWScanKeyMerge, - [NSNumber numberWithInteger:100], kCWScanKeyRestTime, nil]; - - NSArray* apArray = [currentInterface scanForNetworksWithParameters:parametersDict error:&err]; - CWNetwork *apNetwork; - - if (!err) { - for(uint row=0; row < [apArray count]; row++ ) { - apNetwork = [apArray objectAtIndex:row]; - - const QString networkSsid = nsstringToQString([apNetwork ssid]); - found.append(networkSsid); - - QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined; - - bool known = isKnownSsid(networkSsid); - if( [currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) { - if( networkSsid == nsstringToQString( [currentInterface ssid])) { - state = QNetworkConfiguration::Active; - } - } - if(state == QNetworkConfiguration::Undefined) { - if(known) { - state = QNetworkConfiguration::Discovered; - } else { - state = QNetworkConfiguration::Undefined; - } - } - - QNetworkConfiguration::Purpose purpose = QNetworkConfiguration::UnknownPurpose; - if([[apNetwork securityMode] intValue] == kCWSecurityModeOpen) { - purpose = QNetworkConfiguration::PublicPurpose; - } else { - purpose = QNetworkConfiguration::PrivatePurpose; - } - - found.append(foundNetwork(networkSsid, networkSsid, state, interfaceName, purpose)); - - } //end row - }//end error - }// endwifi power - -// add known configurations that are not around. - QMapIterator > i(userProfiles); - while (i.hasNext()) { - i.next(); - - QString networkName = i.key(); - const QString id = networkName; - - if(!found.contains(id)) { - QString networkSsid = getSsidFromNetworkName(networkName); - const QString ssidId = QString::number(qHash(QLatin1String("corewlan:") + networkSsid)); - QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined; - QString interfaceName; - QMapIterator ij(i.value()); - while (ij.hasNext()) { - ij.next(); - interfaceName = ij.value(); - } - - if( [currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) { - if( networkSsid == nsstringToQString([currentInterface ssid])) { - state = QNetworkConfiguration::Active; - } - } - if(state == QNetworkConfiguration::Undefined) { - if( userProfiles.contains(networkName) - && found.contains(ssidId)) { - state = QNetworkConfiguration::Discovered; - } - } - - if(state == QNetworkConfiguration::Undefined) { - state = QNetworkConfiguration::Defined; - } - - found.append(foundNetwork(id, networkName, state, interfaceName, QNetworkConfiguration::UnknownPurpose)); - } - } - emit networksChanged(); - [pool release]; -#endif -} - -QStringList QScanThread::foundNetwork(const QString &id, const QString &name, const QNetworkConfiguration::StateFlags state, const QString &interfaceName, const QNetworkConfiguration::Purpose purpose) -{ - QStringList found; - QMutexLocker locker(&mutex); - QNetworkConfigurationPrivate *ptr = new QNetworkConfigurationPrivate; - - ptr->name = name; - ptr->isValid = true; - ptr->id = id; - ptr->state = state; - ptr->type = QNetworkConfiguration::InternetAccessPoint; - ptr->bearer = QLatin1String("WLAN"); - ptr->purpose = purpose; - ptr->internet = true; - ptr->serviceInterface = QNetworkInterface::interfaceFromName(interfaceName); - - fetchedConfigurations.append( ptr); - configurationInterface[name] = interfaceName; - - locker.unlock(); - locker.relock(); - found.append(id); - return found; -} - -QList QScanThread::getConfigurations() -{ - QMutexLocker locker(&mutex); - - QList foundConfigurations; - - for (int i = 0; i < fetchedConfigurations.count(); ++i) { - QNetworkConfigurationPrivate *config = new QNetworkConfigurationPrivate; - config->name = fetchedConfigurations.at(i)->name; - config->isValid = fetchedConfigurations.at(i)->isValid; - config->id = fetchedConfigurations.at(i)->id; - config->state = fetchedConfigurations.at(i)->state; - config->bearer = fetchedConfigurations.at(i)->bearer; - config->type = fetchedConfigurations.at(i)->type; - config->roamingSupported = fetchedConfigurations.at(i)->roamingSupported; - config->purpose = fetchedConfigurations.at(i)->purpose; - config->internet = fetchedConfigurations.at(i)->internet; - foundConfigurations.append(config); - } - - return foundConfigurations; -} - -void QScanThread::getUserProfiles() -{ -#if defined(MAC_SDK_10_6) - QMutexLocker locker(&mutex); - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - userProfiles.clear(); - - NSArray *wifiInterfaces = [CWInterface supportedInterfaces]; - for(uint row=0; row < [wifiInterfaces count]; row++ ) { - - CWInterface *wifiInterface = [CWInterface interfaceWithName: [wifiInterfaces objectAtIndex:row]]; - if (![wifiInterface power]) - continue; - - NSString *nsInterfaceName = [wifiInterface name]; -// add user configured system networks - SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"Qt corewlan", nil, nil); - NSDictionary * airportPlist = (NSDictionary *)SCDynamicStoreCopyValue(dynRef, (CFStringRef)[NSString stringWithFormat:@"Setup:/Network/Interface/%@/AirPort", nsInterfaceName]); - CFRelease(dynRef); - - NSDictionary *prefNetDict = [airportPlist objectForKey:@"PreferredNetworks"]; - - NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"]; - NSEnumerator *ssidEnumerator = [thisSsidarray objectEnumerator]; - NSString *ssidkey; - while ((ssidkey = [ssidEnumerator nextObject])) { - QString thisSsid = nsstringToQString(ssidkey); - if(!userProfiles.contains(thisSsid)) { - QMap map; - map.insert(thisSsid, nsstringToQString(nsInterfaceName)); - userProfiles.insert(thisSsid, map); - } - } - CFRelease(airportPlist); - - // 802.1X user profiles - QString userProfilePath = QDir::homePath() + "/Library/Preferences/com.apple.eap.profiles.plist"; - NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile:qstringToNSString(userProfilePath)] autorelease]; - NSString *profileStr= @"Profiles"; - NSString *nameStr = @"UserDefinedName"; - NSString *networkSsidStr = @"Wireless Network"; - - id profileKey; - NSEnumerator *dictEnumerator = [eapDict objectEnumerator]; - while ((profileKey = [dictEnumerator nextObject])) { - - if ([profileStr isEqualToString:profileKey]) { - NSDictionary *itemDict = [eapDict objectForKey:profileKey]; - id itemKey; - NSEnumerator *dictEnumerator = [thisSsidarray objectEnumerator]; - while ((itemKey = [dictEnumerator nextObject])) { - - NSInteger dictSize = [itemKey count]; - id objects[dictSize]; - id keys[dictSize]; - - [itemKey getObjects:objects andKeys:keys]; - QString networkName; - QString ssid; - for(int i = 0; i < dictSize; i++) { - if([nameStr isEqualToString:keys[i]]) { - networkName = nsstringToQString(objects[i]); - } - if([networkSsidStr isEqualToString:keys[i]]) { - ssid = nsstringToQString(objects[i]); - } - if(!userProfiles.contains(networkName) - && !ssid.isEmpty()) { - QMap map; - map.insert(ssid, nsstringToQString(nsInterfaceName)); - userProfiles.insert(networkName, map); - } - } - } - } - } - } - - [pool release]; -#endif -} - -QString QScanThread::getSsidFromNetworkName(const QString &name) -{ - QMutexLocker locker(&mutex); - QMapIterator > i(userProfiles); - while (i.hasNext()) { - i.next(); - QMap map = i.value(); - QMapIterator ij(i.value()); - while (ij.hasNext()) { - ij.next(); - const QString networkNameHash = QString::number(qHash(QLatin1String("corewlan:") +i.key())); - if(name == i.key() || name == networkNameHash) { - return ij.key(); - } - } - } - return QString(); -} - -QString QScanThread::getNetworkNameFromSsid(const QString &ssid) -{ - QMutexLocker locker(&mutex); - QMapIterator > i(userProfiles); - while (i.hasNext()) { - i.next(); - QMap map = i.value(); - QMapIterator ij(i.value()); - while (ij.hasNext()) { - ij.next(); - if(ij.key() == ssid) { - return i.key(); - } - } - } - return QString(); -} - -bool QScanThread::isKnownSsid(const QString &ssid) -{ - QMutexLocker locker(&mutex); - - QMapIterator > i(userProfiles); - while (i.hasNext()) { - i.next(); - QMap map = i.value(); - if(map.keys().contains(ssid)) { - return true; - } - } - return false; -} - - -QCoreWlanEngine::QCoreWlanEngine(QObject *parent) -: QNetworkSessionEngine(parent) -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - getAllScInterfaces(); - scanThread = new QScanThread(this); - connect(scanThread, SIGNAL(networksChanged()), - this, SIGNAL(configurationsChanged())); - - QTimer::singleShot(0,this,SLOT(init())); - [pool release]; -} - -QCoreWlanEngine::~QCoreWlanEngine() -{ - QNetworkConfigurationPrivate* cpPriv = 0; - foundConfigurations.clear(); - while(!foundConfigurations.isEmpty()) { - cpPriv = foundConfigurations.takeFirst(); - delete cpPriv; - } -} - -void QCoreWlanEngine::init() -{ -#ifdef MAC_SDK_10_6 - if([[CWInterface supportedInterfaces] count] > 0 && !listener) { - listener = [[QNSListener alloc] init]; - hasWifi = true; - } else { - hasWifi = false; - } -#endif - storeSession = NULL; - scanThread->start(); - - startNetworkChangeLoop(); -} - - -QList QCoreWlanEngine::getConfigurations(bool *ok) -{ - if (ok) - *ok = true; - foundConfigurations.clear(); - - QNetworkConfigurationPrivate* cpPriv = 0; - QMutexLocker locker(&mutex); - QList fetchedConfigurations = scanThread->getConfigurations(); -locker.unlock(); - - for (int i = 0; i < fetchedConfigurations.count(); ++i) { - - QNetworkConfigurationPrivate *config = new QNetworkConfigurationPrivate(); - cpPriv = fetchedConfigurations.at(i); - config->name = cpPriv->name; - config->isValid = cpPriv->isValid; - config->id = cpPriv->id; - config->state = cpPriv->state; - config->type = cpPriv->type; - config->roamingSupported = cpPriv->roamingSupported; - config->purpose = cpPriv->purpose; - config->internet = cpPriv->internet; - config->serviceInterface = cpPriv->serviceInterface; - config->bearer = cpPriv->bearer; - - foundConfigurations.append(config); - delete cpPriv; - } - - - return foundConfigurations; -} - -QString QCoreWlanEngine::getInterfaceFromId(const QString &id) -{ - return scanThread->configurationInterface.value(id); -} - -bool QCoreWlanEngine::hasIdentifier(const QString &id) -{ - return scanThread->configurationInterface.contains(id); -} - -void QCoreWlanEngine::connectToId(const QString &id) -{ - QString interfaceString = getInterfaceFromId(id); - - if(networkInterfaces.value(interfaceString) == "WLAN") { -#if defined(MAC_SDK_10_6) - NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; - CWInterface *wifiInterface = [CWInterface interfaceWithName: qstringToNSString(interfaceString)]; - - if([wifiInterface power]) { - NSError *err = nil; - NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0]; - - QString wantedSsid = 0; - bool using8021X = false; - - if(scanThread->getNetworkNameFromSsid(id) != id) { - NSArray *array = [CW8021XProfile allUser8021XProfiles]; - for (NSUInteger i=0; i<[array count]; ++i) { - - if(id == nsstringToQString([[array objectAtIndex:i] userDefinedName]) - || id == nsstringToQString([[array objectAtIndex:i] ssid]) ) { - QString thisName = scanThread->getSsidFromNetworkName(id); - if(thisName.isEmpty()) { - wantedSsid = id; - } else { - wantedSsid = thisName; - } - [params setValue: [array objectAtIndex:i] forKey:kCWAssocKey8021XProfile]; - using8021X = true; - break; - } - } - } - - if(!using8021X) { - QString wantedNetwork; - QMapIterator > i(scanThread->userProfiles); - while (i.hasNext()) { - i.next(); - wantedNetwork = i.key(); - if(id == wantedNetwork) { - wantedSsid = scanThread->getSsidFromNetworkName(wantedNetwork); - break; - } - } - } - - NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], kCWScanKeyMerge, - [NSNumber numberWithInt:kCWScanTypeFast], kCWScanKeyScanType, - [NSNumber numberWithInteger:100], kCWScanKeyRestTime, - qstringToNSString(wantedSsid), kCWScanKeySSID, - nil]; - - NSArray *scanArray = [wifiInterface scanForNetworksWithParameters:parametersDict error:&err]; - if(!err) { - for(uint row=0; row < [scanArray count]; row++ ) { - CWNetwork *apNetwork = [scanArray objectAtIndex:row]; - if(wantedSsid == nsstringToQString([apNetwork ssid])) { - - if(!using8021X) { - SecKeychainAttribute attributes[3]; - - NSString *account = [apNetwork ssid]; - NSString *keyKind = @"AirPort network password"; - NSString *keyName = account; - - attributes[0].tag = kSecAccountItemAttr; - attributes[0].data = (void *)[account UTF8String]; - attributes[0].length = [account length]; - - attributes[1].tag = kSecDescriptionItemAttr; - attributes[1].data = (void *)[keyKind UTF8String]; - attributes[1].length = [keyKind length]; - - attributes[2].tag = kSecLabelItemAttr; - attributes[2].data = (void *)[keyName UTF8String]; - attributes[2].length = [keyName length]; - - SecKeychainAttributeList attributeList = {3,attributes}; - - SecKeychainSearchRef searchRef; - OSErr result = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &attributeList, &searchRef); -Q_UNUSED(result); - NSString *password = @""; - SecKeychainItemRef searchItem; - OSStatus resultStatus; - resultStatus = SecKeychainSearchCopyNext(searchRef, &searchItem); - - if (resultStatus == errSecSuccess) { - UInt32 realPasswordLength; - SecKeychainAttribute attributesW[8]; - attributesW[0].tag = kSecAccountItemAttr; - SecKeychainAttributeList listW = {1,attributesW}; - char *realPassword; - OSStatus status = SecKeychainItemCopyContent(searchItem, NULL, &listW, &realPasswordLength,(void **)&realPassword); - - if (status == noErr) { - if (realPassword != NULL) { - - QByteArray pBuf; - pBuf.resize(realPasswordLength); - pBuf.prepend(realPassword); - pBuf.insert(realPasswordLength,'\0'); - - password = [NSString stringWithUTF8String:pBuf]; - } - } - - CFRelease(searchItem); - SecKeychainItemFreeContent(&listW, realPassword); - } else { - qDebug() << "SecKeychainSearchCopyNext error" << cfstringRefToQstring(SecCopyErrorMessageString(resultStatus, NULL)); - } - [params setValue: password forKey: kCWAssocKeyPassphrase]; - } // end using8021X - - bool result = [wifiInterface associateToNetwork: apNetwork parameters:[NSDictionary dictionaryWithDictionary:params] error:&err]; - - if(!result) { - emit connectionError(id, ConnectError); - } else { - [autoreleasepool release]; - return; - } - } - } - } else { - qDebug() <<"ERROR"<< nsstringToQString([err localizedDescription ]); - } - - emit connectionError(id, InterfaceLookupError); - [autoreleasepool release]; - - } else { - qDebug() << "wifi power off"; - // not wifi - } -#endif - } - emit connectionError(id, OperationNotSupported); -} - -void QCoreWlanEngine::disconnectFromId(const QString &id) -{ - QString interfaceString = getInterfaceFromId(id); - if(networkInterfaces.value(getInterfaceFromId(id)) == "WLAN") { //wifi only for now -#if defined(MAC_SDK_10_6) - NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; - CWInterface *wifiInterface = [CWInterface interfaceWithName: qstringToNSString(interfaceString)]; - [wifiInterface disassociate]; - if([[wifiInterface interfaceState]intValue] != kCWInterfaceStateInactive) { - emit connectionError(id, DisconnectionError); - } - [autoreleasepool release]; - return; -#endif - } else { - - } - emit connectionError(id, OperationNotSupported); -} - -void QCoreWlanEngine::requestUpdate() -{ - getAllScInterfaces(); - scanThread->getUserProfiles(); - scanThread->start(); -} - -QCoreWlanEngine *QCoreWlanEngine::instance() -{ - return coreWlanEngine(); -} - -bool QCoreWlanEngine::isWifiReady(const QString &wifiDeviceName) -{ -#if defined(MAC_SDK_10_6) - if([[CWInterface supportedInterfaces] count] > 0 ) { - CWInterface *defaultInterface = [CWInterface interfaceWithName: qstringToNSString(wifiDeviceName)]; - if([defaultInterface power]) - return true; - } -#else - Q_UNUSED(wifiDeviceName); -#endif - return false; -} - -bool QCoreWlanEngine::getAllScInterfaces() -{ - networkInterfaces.clear(); - NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; - - CFArrayRef interfaces = SCNetworkInterfaceCopyAll(); - if (interfaces != NULL) { - CFIndex interfaceCount; - CFIndex interfaceIndex; - interfaceCount = CFArrayGetCount(interfaces); - for (interfaceIndex = 0; interfaceIndex < interfaceCount; interfaceIndex++) { - NSAutoreleasePool *looppool = [[NSAutoreleasePool alloc] init]; - - CFStringRef bsdName; - CFTypeRef thisInterface = CFArrayGetValueAtIndex(interfaces, interfaceIndex); - bsdName = SCNetworkInterfaceGetBSDName((SCNetworkInterfaceRef)thisInterface); - QString interfaceName = cfstringRefToQstring(bsdName); - QString typeStr; - CFStringRef type = SCNetworkInterfaceGetInterfaceType((SCNetworkInterfaceRef)thisInterface); - if ( CFEqual(type, kSCNetworkInterfaceTypeIEEE80211)) { - typeStr = "WLAN"; -// } else if (CFEqual(type, kSCNetworkInterfaceTypeBluetooth)) { -// typeStr = "Bluetooth"; - } else if(CFEqual(type, kSCNetworkInterfaceTypeEthernet)) { - typeStr = "Ethernet"; - } else if(CFEqual(type, kSCNetworkInterfaceTypeFireWire)) { - typeStr = "Ethernet"; //ok a bit fudged - } - if(!networkInterfaces.contains(interfaceName) && !typeStr.isEmpty()) { - networkInterfaces.insert(interfaceName,typeStr); - } - [looppool release]; - } - } - CFRelease(interfaces); - - [autoreleasepool drain]; - return true; -} - -void QCoreWlanEngine::startNetworkChangeLoop() -{ - storeSession = NULL; - - SCDynamicStoreContext dynStoreContext = { 0, this/*(void *)storeSession*/, NULL, NULL, NULL }; - storeSession = SCDynamicStoreCreate(NULL, - CFSTR("networkChangeCallback"), - networkChangeCallback, - &dynStoreContext); - if (!storeSession ) { - qDebug() << "could not open dynamic store: error:" << SCErrorString(SCError()); - return; - } - - CFMutableArrayRef notificationKeys; - notificationKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - CFMutableArrayRef patternsArray; - patternsArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - - CFStringRef storeKey; - storeKey = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, - kSCDynamicStoreDomainState, - kSCEntNetIPv4); - CFArrayAppendValue(notificationKeys, storeKey); - CFRelease(storeKey); - - storeKey = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, - kSCDynamicStoreDomainState, - kSCCompAnyRegex, - kSCEntNetIPv4); - CFArrayAppendValue(patternsArray, storeKey); - CFRelease(storeKey); - - if (!SCDynamicStoreSetNotificationKeys(storeSession , notificationKeys, patternsArray)) { - qDebug() << "register notification error:"<< SCErrorString(SCError()); - CFRelease(storeSession ); - CFRelease(notificationKeys); - CFRelease(patternsArray); - return; - } - CFRelease(notificationKeys); - CFRelease(patternsArray); - - runloopSource = SCDynamicStoreCreateRunLoopSource(NULL, storeSession , 0); - if (!runloopSource) { - qDebug() << "runloop source error:"<< SCErrorString(SCError()); - CFRelease(storeSession ); - return; - } - - CFRunLoopAddSource(CFRunLoopGetCurrent(), runloopSource, kCFRunLoopDefaultMode); - return; -} -#include "moc_qcorewlanengine_mac_p.cpp" - -QTM_END_NAMESPACE diff --git a/src/bearer/qcorewlanengine_mac_p.h b/src/bearer/qcorewlanengine_mac_p.h deleted file mode 100644 index b635a09..0000000 --- a/src/bearer/qcorewlanengine_mac_p.h +++ /dev/null @@ -1,150 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCOREWLANENGINE_P_H -#define QCOREWLANENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qnetworksessionengine_p.h" -#include "qnetworkconfiguration.h" - -#include -#include -#include -#include -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; -class QScanThread; - -class QCoreWlanEngine : public QNetworkSessionEngine -{ - Q_OBJECT - friend class QScanThread; - -public: - QCoreWlanEngine(QObject *parent = 0); - ~QCoreWlanEngine(); - - QList getConfigurations(bool *ok = 0); - QString getInterfaceFromId(const QString &id); - bool hasIdentifier(const QString &id); - - QString bearerName(const QString &id); - - void connectToId(const QString &id); - void disconnectFromId(const QString &id); - - void requestUpdate(); - - static QCoreWlanEngine *instance(); - QString interfaceName; - -private: - bool isWifiReady(const QString &dev); - QTimer pollTimer; - QList foundConfigurations; - - SCDynamicStoreRef storeSession; - CFRunLoopSourceRef runloopSource; - bool hasWifi; - QScanThread *scanThread; - QMutex mutex; - static bool getAllScInterfaces(); - -private Q_SLOTS: - void init(); - -protected: - void startNetworkChangeLoop(); -}; - -class QScanThread : public QThread -{ - Q_OBJECT - -public: - QScanThread(QObject *parent = 0); - ~QScanThread(); - - void quit(); - QList getConfigurations(); - QString interfaceName; - QMap configurationInterface; - void getUserProfiles(); - QString getNetworkNameFromSsid(const QString &ssid); - QString getSsidFromNetworkName(const QString &name); - bool isKnownSsid(const QString &ssid); - QMap > userProfiles; - -signals: - void networksChanged(); - -protected: - void run(); - -private: - QList fetchedConfigurations; - QMutex mutex; - QStringList foundNetwork(const QString &id, const QString &ssid, - const QNetworkConfiguration::StateFlags state, - const QString &interfaceName, - const QNetworkConfiguration::Purpose purpose); - -}; - - -QTM_END_NAMESPACE - -#endif - diff --git a/src/bearer/qgenericengine.cpp b/src/bearer/qgenericengine.cpp deleted file mode 100644 index e39be33..0000000 --- a/src/bearer/qgenericengine.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgenericengine_p.h" -#include "qnetworkconfiguration_p.h" - -#include -#include -#include -#include - -#include - -#ifdef Q_OS_WIN -#include "qnetworksessionengine_win_p.h" -#endif - -#ifdef Q_OS_LINUX -#include -#include -#include -#include -#include -#endif - -QTM_BEGIN_NAMESPACE - -Q_GLOBAL_STATIC(QGenericEngine, genericEngine) - -static QString qGetInterfaceType(const QString &interface) -{ -#ifdef Q_OS_WIN32 - unsigned long oid; - DWORD bytesWritten; - - NDIS_MEDIUM medium; - NDIS_PHYSICAL_MEDIUM physicalMedium; - - HANDLE handle = CreateFile((TCHAR *)QString("\\\\.\\%1").arg(interface).utf16(), 0, - FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); - if (handle == INVALID_HANDLE_VALUE) - return QLatin1String("Unknown"); - - oid = OID_GEN_MEDIA_SUPPORTED; - bytesWritten = 0; - bool result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid), - &medium, sizeof(medium), &bytesWritten, 0); - if (!result) { - CloseHandle(handle); - return QLatin1String("Unknown"); - } - - oid = OID_GEN_PHYSICAL_MEDIUM; - bytesWritten = 0; - result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid), - &physicalMedium, sizeof(physicalMedium), &bytesWritten, 0); - if (!result) { - CloseHandle(handle); - - if (medium == NdisMedium802_3) - return QLatin1String("Ethernet"); - else - return QLatin1String("Unknown"); - } - - CloseHandle(handle); - - if (medium == NdisMedium802_3) { - switch (physicalMedium) { - case NdisPhysicalMediumWirelessLan: - return QLatin1String("WLAN"); - case NdisPhysicalMediumBluetooth: - return QLatin1String("Bluetooth"); - case NdisPhysicalMediumWiMax: - return QLatin1String("WiMAX"); - default: -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "Physical Medium" << physicalMedium; -#endif - return QLatin1String("Ethernet"); - } - } - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << medium << physicalMedium; -#endif -#elif defined(Q_OS_LINUX) - int sock = socket(AF_INET, SOCK_DGRAM, 0); - - ifreq request; - strncpy(request.ifr_name, interface.toLocal8Bit().data(), sizeof(request.ifr_name)); - int result = ioctl(sock, SIOCGIFHWADDR, &request); - close(sock); - - if (result >= 0 && request.ifr_hwaddr.sa_family == ARPHRD_ETHER) - return QLatin1String("Ethernet"); -#else - Q_UNUSED(interface); -#endif - - return QLatin1String("Unknown"); -} - -QGenericEngine::QGenericEngine(QObject *parent) -: QNetworkSessionEngine(parent) -{ - connect(&pollTimer, SIGNAL(timeout()), this, SIGNAL(configurationsChanged())); - pollTimer.setInterval(10000); -} - -QGenericEngine::~QGenericEngine() -{ -} - -QList QGenericEngine::getConfigurations(bool *ok) -{ - if (ok) - *ok = true; - - QList foundConfigurations; - - // Immediately after connecting with a wireless access point - // QNetworkInterface::allInterfaces() will sometimes return an empty list. Calling it again a - // second time results in a non-empty list. If we loose interfaces we will end up removing - // network configurations which will break current sessions. - QList interfaces = QNetworkInterface::allInterfaces(); - if (interfaces.isEmpty()) - interfaces = QNetworkInterface::allInterfaces(); - - // create configuration for each interface - while (!interfaces.isEmpty()) { - QNetworkInterface interface = interfaces.takeFirst(); - - if (!interface.isValid()) - continue; - - // ignore loopback interface - if (interface.flags() & QNetworkInterface::IsLoopBack) - continue; - - // ignore WLAN interface handled in separate engine - if (qGetInterfaceType(interface.name()) == "WLAN") - continue; - - QNetworkConfigurationPrivate *cpPriv = new QNetworkConfigurationPrivate; - const QString humanReadableName = interface.humanReadableName(); - cpPriv->name = humanReadableName.isEmpty() ? interface.name() : humanReadableName; - cpPriv->isValid = true; - - uint identifier; - if (interface.index()) - identifier = qHash(QLatin1String("NLA:") + QString::number(interface.index())); - else - identifier = qHash(QLatin1String("NLA:") + interface.hardwareAddress()); - - cpPriv->id = QString::number(identifier); - cpPriv->state = QNetworkConfiguration::Discovered; - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - if (interface.name().isEmpty()) - cpPriv->bearer = QLatin1String("Unknown"); - else - cpPriv->bearer = qGetInterfaceType(interface.name()); - - if((interface.flags() & QNetworkInterface::IsUp) && !interface.addressEntries().isEmpty()) - cpPriv->state |= QNetworkConfiguration::Active; - - configurationInterface[identifier] = interface.name(); - - foundConfigurations.append(cpPriv); - } - - pollTimer.start(); - - return foundConfigurations; -} - -QString QGenericEngine::getInterfaceFromId(const QString &id) -{ - return configurationInterface.value(id.toUInt()); -} - -bool QGenericEngine::hasIdentifier(const QString &id) -{ - return configurationInterface.contains(id.toUInt()); -} - -/*QString QGenericEngine::bearerName(const QString &id) -{ - QString interface = getInterfaceFromId(id); - - if (interface.isEmpty()) - return QLatin1String("Unknown"); - - return qGetInterfaceType(interface); -}*/ - -void QGenericEngine::connectToId(const QString &id) -{ - emit connectionError(id, OperationNotSupported); -} - -void QGenericEngine::disconnectFromId(const QString &id) -{ - emit connectionError(id, OperationNotSupported); -} - -void QGenericEngine::requestUpdate() -{ - emit configurationsChanged(); -} - -QGenericEngine *QGenericEngine::instance() -{ - return genericEngine(); -} - -#include "moc_qgenericengine_p.cpp" -QTM_END_NAMESPACE - diff --git a/src/bearer/qgenericengine_p.h b/src/bearer/qgenericengine_p.h deleted file mode 100644 index e1b9722..0000000 --- a/src/bearer/qgenericengine_p.h +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGENERICENGINE_P_H -#define QGENERICENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qnetworksessionengine_p.h" - -#include -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; - -class QGenericEngine : public QNetworkSessionEngine -{ - Q_OBJECT - -public: - QGenericEngine(QObject *parent = 0); - ~QGenericEngine(); - - QList getConfigurations(bool *ok = 0); - QString getInterfaceFromId(const QString &id); - bool hasIdentifier(const QString &id); - - //QString bearerName(const QString &id); - - void connectToId(const QString &id); - void disconnectFromId(const QString &id); - - void requestUpdate(); - - static QGenericEngine *instance(); - -private: - QMap configurationInterface; - QTimer pollTimer; -}; - -QTM_END_NAMESPACE - -#endif - diff --git a/src/bearer/qnativewifiengine_win.cpp b/src/bearer/qnativewifiengine_win.cpp deleted file mode 100644 index 2903d3d..0000000 --- a/src/bearer/qnativewifiengine_win.cpp +++ /dev/null @@ -1,730 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnativewifiengine_win_p.h" -#include "qnetworkconfiguration_p.h" - -#include -#include -#include - -#include - -#include -#undef interface - -QTM_BEGIN_NAMESPACE - -Q_GLOBAL_STATIC(QNativeWifiEngine, nativeWifiEngine) - -#define WLAN_MAX_NAME_LENGTH 256 -#define WLAN_MAX_PHY_TYPE_NUMBER 8 -#define WLAN_NOTIFICATION_SOURCE_ALL 0x0000ffff -#define WLAN_AVAILABLE_NETWORK_CONNECTED 1 -#define WLAN_AVAILABLE_NETWORK_HAS_PROFILE 2 -#define DOT11_SSID_MAX_LENGTH 32 - -struct WLAN_NOTIFICATION_DATA { - DWORD NotificationSource; - DWORD NotificationCode; - GUID InterfaceGuid; - DWORD dwDataSize; - PVOID pData; -}; - -enum WLAN_INTERFACE_STATE { - wlan_interface_state_not_ready = 0, - wlan_interface_state_connected, - wlan_interface_state_ad_hoc_network_formed, - wlan_interface_state_disconnecting, - wlan_interface_state_disconnected, - wlan_interface_state_associating, - wlan_interface_state_discovering, - wlan_interface_state_authenticating -}; - -struct WLAN_INTERFACE_INFO { - GUID InterfaceGuid; - WCHAR strInterfaceDescription[WLAN_MAX_NAME_LENGTH]; - WLAN_INTERFACE_STATE isState; -}; - -struct WLAN_INTERFACE_INFO_LIST { - DWORD dwNumberOfItems; - DWORD dwIndex; - WLAN_INTERFACE_INFO InterfaceInfo[1]; -}; - -struct DOT11_SSID { - ULONG uSSIDLength; - UCHAR ucSSID[DOT11_SSID_MAX_LENGTH]; -}; - -struct NDIS_OBJECT_HEADER { - UCHAR Type; - UCHAR Revision; - USHORT Size; -}; - -typedef UCHAR DOT11_MAC_ADDRESS[6]; -struct DOT11_BSSID_LIST { - NDIS_OBJECT_HEADER Header; - ULONG uNumberOfEntries; - ULONG uTotalNumOfEntries; - DOT11_MAC_ADDRESS BSSIDs[1]; -}; - -enum DOT11_BSS_TYPE { - dot11_BSS_type_infrastructure = 1, - dot11_BSS_type_independent = 2, - dot11_BSS_type_any = 3 -}; - -enum DOT11_PHY_TYPE { - dot11_phy_type_unknown = 0, - dot11_phy_type_any = dot11_phy_type_unknown, - dot11_phy_type_fhss = 1, - dot11_phy_type_dsss = 2, - dot11_phy_type_irbaseband = 3, - dot11_phy_type_ofdm = 4, - dot11_phy_type_hrdsss = 5, - dot11_phy_type_erp = 6, - dot11_phy_type_ht = 7, - dot11_phy_type_IHV_start = 0x80000000, - dot11_phy_type_IHV_end = 0xffffffff -}; - -enum DOT11_AUTH_ALGORITHM { - DOT11_AUTH_ALGO_80211_OPEN = 1, - DOT11_AUTH_ALGO_80211_SHARED_KEY = 2, - DOT11_AUTH_ALGO_WPA = 3, - DOT11_AUTH_ALGO_WPA_PSK = 4, - DOT11_AUTH_ALGO_WPA_NONE = 5, - DOT11_AUTH_ALGO_RSNA = 6, - DOT11_AUTH_ALGO_RSNA_PSK = 7, - DOT11_AUTH_ALGO_IHV_START = 0x80000000, - DOT11_AUTH_ALGO_IHV_END = 0xffffffff -}; - -enum DOT11_CIPHER_ALGORITHM { - DOT11_CIPHER_ALGO_NONE = 0x00, - DOT11_CIPHER_ALGO_WEP40 = 0x01, - DOT11_CIPHER_ALGO_TKIP = 0x02, - DOT11_CIPHER_ALGO_CCMP = 0x04, - DOT11_CIPHER_ALGO_WEP104 = 0x05, - DOT11_CIPHER_ALGO_WPA_USE_GROUP = 0x100, - DOT11_CIPHER_ALGO_RSN_USE_GROUP = 0x100, - DOT11_CIPHER_ALGO_WEP = 0x101, - DOT11_CIPHER_ALGO_IHV_START = 0x80000000, - DOT11_CIPHER_ALGO_IHV_END = 0xffffffff -}; - -struct WLAN_AVAILABLE_NETWORK { - WCHAR strProfileName[WLAN_MAX_NAME_LENGTH]; - DOT11_SSID dot11Ssid; - DOT11_BSS_TYPE dot11BssType; - ULONG uNumberOfBssids; - BOOL bNetworkConnectable; - DWORD wlanNotConnectableReason; - ULONG uNumberOfPhyTypes; - DOT11_PHY_TYPE dot11PhyTypes[WLAN_MAX_PHY_TYPE_NUMBER]; - BOOL bMorePhyTypes; - ULONG wlanSignalQuality; - BOOL bSecurityEnabled; - DOT11_AUTH_ALGORITHM dot11DefaultAuthAlgorithm; - DOT11_CIPHER_ALGORITHM dot11DefaultCipherAlgorithm; - DWORD dwFlags; - DWORD dwReserved; -}; - -struct WLAN_AVAILABLE_NETWORK_LIST { - DWORD dwNumberOfItems; - DWORD dwIndex; - WLAN_AVAILABLE_NETWORK Network[1]; -}; - -enum WLAN_INTF_OPCODE { - wlan_intf_opcode_autoconf_start = 0x000000000, - wlan_intf_opcode_autoconf_enabled, - wlan_intf_opcode_background_scan_enabled, - wlan_intf_opcode_media_streaming_mode, - wlan_intf_opcode_radio_state, - wlan_intf_opcode_bss_type, - wlan_intf_opcode_interface_state, - wlan_intf_opcode_current_connection, - wlan_intf_opcode_channel_number, - wlan_intf_opcode_supported_infrastructure_auth_cipher_pairs, - wlan_intf_opcode_supported_adhoc_auth_cipher_pairs, - wlan_intf_opcode_supported_country_or_region_string_list, - wlan_intf_opcode_current_operation_mode, - wlan_intf_opcode_supported_safe_mode, - wlan_intf_opcode_certified_safe_mode, - wlan_intf_opcode_autoconf_end = 0x0fffffff, - wlan_intf_opcode_msm_start = 0x10000100, - wlan_intf_opcode_statistics, - wlan_intf_opcode_rssi, - wlan_intf_opcode_msm_end = 0x1fffffff, - wlan_intf_opcode_security_start = 0x20010000, - wlan_intf_opcode_security_end = 0x2fffffff, - wlan_intf_opcode_ihv_start = 0x30000000, - wlan_intf_opcode_ihv_end = 0x3fffffff -}; - -enum WLAN_OPCODE_VALUE_TYPE { - wlan_opcode_value_type_query_only = 0, - wlan_opcode_value_type_set_by_group_policy, - wlan_opcode_value_type_set_by_user, - wlan_opcode_value_type_invalid -}; - -enum WLAN_CONNECTION_MODE { - wlan_connection_mode_profile = 0, - wlan_connection_mode_temporary_profile, - wlan_connection_mode_discovery_secure, - wlan_connection_mode_discovery_unsecure, - wlan_connection_mode_auto, - wlan_connection_mode_invalid -}; - -struct WLAN_CONNECTION_PARAMETERS { - WLAN_CONNECTION_MODE wlanConnectionMode; - LPCWSTR strProfile; - DOT11_SSID *pDot11Ssid; - DOT11_BSSID_LIST *pDesiredBssidList; - DOT11_BSS_TYPE dot11BssType; - DWORD dwFlags; -}; - -struct WLAN_RAW_DATA { - DWORD dwDataSize; - BYTE DataBlob[1]; -}; - -enum WLAN_NOTIFICATION_ACM { - wlan_notification_acm_start = 0, - wlan_notification_acm_autoconf_enabled, - wlan_notification_acm_autoconf_disabled, - wlan_notification_acm_background_scan_enabled, - wlan_notification_acm_background_scan_disabled, - wlan_notification_acm_bss_type_change, - wlan_notification_acm_power_setting_change, - wlan_notification_acm_scan_complete, - wlan_notification_acm_scan_fail, - wlan_notification_acm_connection_start, - wlan_notification_acm_connection_complete, - wlan_notification_acm_connection_attempt_fail, - wlan_notification_acm_filter_list_change, - wlan_notification_acm_interface_arrival, - wlan_notification_acm_interface_removal, - wlan_notification_acm_profile_change, - wlan_notification_acm_profile_name_change, - wlan_notification_acm_profiles_exhausted, - wlan_notification_acm_network_not_available, - wlan_notification_acm_network_available, - wlan_notification_acm_disconnecting, - wlan_notification_acm_disconnected, - wlan_notification_acm_adhoc_network_state_change, - wlan_notification_acm_end -}; - -struct WLAN_ASSOCIATION_ATTRIBUTES { - DOT11_SSID dot11Ssid; - DOT11_BSS_TYPE dot11BssType; - DOT11_MAC_ADDRESS dot11Bssid; - DOT11_PHY_TYPE dot11PhyType; - ULONG uDot11PhyIndex; - ULONG wlanSignalQuality; - ULONG ulRxRate; - ULONG ulTxRate; -}; - -struct WLAN_SECURITY_ATTRIBUTES { - BOOL bSecurityEnabled; - BOOL bOneXEnabled; - DOT11_AUTH_ALGORITHM dot11AuthAlgorithm; - DOT11_CIPHER_ALGORITHM dot11CipherAlgorithm; -}; - -struct WLAN_CONNECTION_ATTRIBUTES { - WLAN_INTERFACE_STATE isState; - WLAN_CONNECTION_MODE wlanConnectionMode; - WCHAR strProfileName[WLAN_MAX_NAME_LENGTH]; - WLAN_ASSOCIATION_ATTRIBUTES wlanAssociationAttributes; - WLAN_SECURITY_ATTRIBUTES wlanSecurityAttributes; -}; - -typedef void (WINAPI *WLAN_NOTIFICATION_CALLBACK)(WLAN_NOTIFICATION_DATA *, PVOID); - -typedef DWORD (WINAPI *WlanOpenHandleProto) - (DWORD dwClientVersion, PVOID pReserved, PDWORD pdwNegotiatedVersion, PHANDLE phClientHandle); -typedef DWORD (WINAPI *WlanRegisterNotificationProto) - (HANDLE hClientHandle, DWORD dwNotifSource, BOOL bIgnoreDuplicate, - WLAN_NOTIFICATION_CALLBACK funcCallback, PVOID pCallbackContext, - PVOID pReserved, PDWORD pdwPrevNotifSource); -typedef DWORD (WINAPI *WlanEnumInterfacesProto) - (HANDLE hClientHandle, PVOID pReserved, WLAN_INTERFACE_INFO_LIST **ppInterfaceList); -typedef DWORD (WINAPI *WlanGetAvailableNetworkListProto) - (HANDLE hClientHandle, const GUID* pInterfaceGuid, DWORD dwFlags, PVOID pReserved, - WLAN_AVAILABLE_NETWORK_LIST **ppAvailableNetworkList); -typedef DWORD (WINAPI *WlanQueryInterfaceProto) - (HANDLE hClientHandle, const GUID *pInterfaceGuid, WLAN_INTF_OPCODE OpCode, PVOID pReserved, - PDWORD pdwDataSize, PVOID *ppData, WLAN_OPCODE_VALUE_TYPE *pWlanOpcodeValueType); -typedef DWORD (WINAPI *WlanConnectProto) - (HANDLE hClientHandle, const GUID *pInterfaceGuid, - const WLAN_CONNECTION_PARAMETERS *pConnectionParameters, PVOID pReserved); -typedef DWORD (WINAPI *WlanDisconnectProto) - (HANDLE hClientHandle, const GUID *pInterfaceGuid, PVOID pReserved); -typedef DWORD (WINAPI *WlanScanProto) - (HANDLE hClientHandle, const GUID *pInterfaceGuid, const DOT11_SSID *pDot11Ssid, - const WLAN_RAW_DATA *pIeData, PVOID pReserved); -typedef VOID (WINAPI *WlanFreeMemoryProto)(PVOID pMemory); -typedef DWORD (WINAPI *WlanCloseHandleProto)(HANDLE hClientHandle, PVOID pReserved); - -static WlanOpenHandleProto local_WlanOpenHandle = 0; -static WlanRegisterNotificationProto local_WlanRegisterNotification = 0; -static WlanEnumInterfacesProto local_WlanEnumInterfaces = 0; -static WlanGetAvailableNetworkListProto local_WlanGetAvailableNetworkList = 0; -static WlanQueryInterfaceProto local_WlanQueryInterface = 0; -static WlanConnectProto local_WlanConnect = 0; -static WlanDisconnectProto local_WlanDisconnect = 0; -static WlanScanProto local_WlanScan = 0; -static WlanFreeMemoryProto local_WlanFreeMemory = 0; -static WlanCloseHandleProto local_WlanCloseHandle = 0; - -Q_GLOBAL_STATIC_WITH_ARGS(QMutex, dynamicLoadMutex, (QMutex::Recursive)); - -static void resolveLibrary() -{ - static volatile bool triedResolve = false; - - if (!triedResolve) { -#ifndef QT_NO_THREAD - QMutexLocker locker(dynamicLoadMutex()); -#endif - - if (!triedResolve) { - local_WlanOpenHandle = (WlanOpenHandleProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanOpenHandle"); - local_WlanRegisterNotification = (WlanRegisterNotificationProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanRegisterNotification"); - local_WlanEnumInterfaces = (WlanEnumInterfacesProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanEnumInterfaces"); - local_WlanGetAvailableNetworkList = (WlanGetAvailableNetworkListProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanGetAvailableNetworkList"); - local_WlanQueryInterface = (WlanQueryInterfaceProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanQueryInterface"); - local_WlanConnect = (WlanConnectProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanConnect"); - local_WlanDisconnect = (WlanDisconnectProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanDisconnect"); - local_WlanScan = (WlanScanProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanScan"); - local_WlanFreeMemory = (WlanFreeMemoryProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanFreeMemory"); - local_WlanCloseHandle = (WlanCloseHandleProto) - QLibrary::resolve(QLatin1String("wlanapi.dll"), "WlanCloseHandle"); - - triedResolve = true; - } - } -} - -void qNotificationCallback(WLAN_NOTIFICATION_DATA *data, QNativeWifiEngine *d) -{ - Q_UNUSED(d); - - switch (data->NotificationCode) { - case wlan_notification_acm_connection_complete: - case wlan_notification_acm_disconnected: - d->emitConfigurationsChanged(); - break; - default: - qDebug() << "wlan unknown notification"; - } -} - -QNativeWifiEngine::QNativeWifiEngine(QObject *parent) -: QNetworkSessionEngine(parent), handle(0) -{ - DWORD clientVersion; - - DWORD result = local_WlanOpenHandle(1, 0, &clientVersion, &handle); - if (result != ERROR_SUCCESS) { - if (result != ERROR_SERVICE_NOT_ACTIVE) - qWarning("%s: WlanOpenHandle failed with error %ld\n", __FUNCTION__, result); - - return; - } - - result = local_WlanRegisterNotification(handle, WLAN_NOTIFICATION_SOURCE_ALL, true, - WLAN_NOTIFICATION_CALLBACK(qNotificationCallback), - this, 0, 0); - if (result != ERROR_SUCCESS) - qWarning("%s: WlanRegisterNotification failed with error %ld\n", __FUNCTION__, result); - - // On Windows XP SP2 and SP3 only connection and disconnection notifications are available. - // We need to poll for changes in available wireless networks. - connect(&pollTimer, SIGNAL(timeout()), this, SIGNAL(configurationsChanged())); - pollTimer.setInterval(10000); -} - -QNativeWifiEngine::~QNativeWifiEngine() -{ - local_WlanCloseHandle(handle, 0); -} - -QList QNativeWifiEngine::getConfigurations(bool *ok) -{ - if (ok) - *ok = false; - - QList foundConfigurations; - - // enumerate interfaces - WLAN_INTERFACE_INFO_LIST *interfaceList; - DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result); - return foundConfigurations; - } - - for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) { - const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i]; - - WLAN_AVAILABLE_NETWORK_LIST *networkList; - result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid, - 3, 0, &networkList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanGetAvailableNetworkList failed with error %ld\n", - __FUNCTION__, result); - continue; - } - - QStringList seenNetworks; - - for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) { - WLAN_AVAILABLE_NETWORK &network = networkList->Network[j]; - - QString networkName; - - if (network.strProfileName[0] != 0) { - networkName = QString::fromWCharArray(network.strProfileName); - } else { - networkName = QByteArray(reinterpret_cast(network.dot11Ssid.ucSSID), - network.dot11Ssid.uSSIDLength); - } - - // don't add duplicate networks - if (seenNetworks.contains(networkName)) - continue; - else - seenNetworks.append(networkName); - - QNetworkConfigurationPrivate *cpPriv = new QNetworkConfigurationPrivate; - - cpPriv->isValid = true; - - cpPriv->name = networkName; - cpPriv->id = QString::number(qHash(QLatin1String("WLAN:") + cpPriv->name)); - - if (!(network.dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE)) - cpPriv->state = QNetworkConfiguration::Undefined; - - if (network.strProfileName[0] != 0) { - if (network.bNetworkConnectable) { - if (network.dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED) - cpPriv->state = QNetworkConfiguration::Active; - else - cpPriv->state = QNetworkConfiguration::Discovered; - } else { - cpPriv->state = QNetworkConfiguration::Defined; - } - } - - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - cpPriv->bearer = QLatin1String("WLAN"); - - - foundConfigurations.append(cpPriv); - } - - local_WlanFreeMemory(networkList); - } - - local_WlanFreeMemory(interfaceList); - - if (ok) - *ok = true; - - pollTimer.start(); - - return foundConfigurations; -} - -QString QNativeWifiEngine::getInterfaceFromId(const QString &id) -{ - // enumerate interfaces - WLAN_INTERFACE_INFO_LIST *interfaceList; - DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result); - return QString(); - } - - for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) { - const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i]; - - DWORD dataSize; - WLAN_CONNECTION_ATTRIBUTES *connectionAttributes; - result = local_WlanQueryInterface(handle, &interface.InterfaceGuid, - wlan_intf_opcode_current_connection, 0, &dataSize, - reinterpret_cast(&connectionAttributes), 0); - if (result != ERROR_SUCCESS) { - if (result != ERROR_INVALID_STATE) - qWarning("%s: WlanQueryInterface failed with error %ld\n", __FUNCTION__, result); - - continue; - } - - if (qHash(QLatin1String("WLAN:") + - QString::fromWCharArray(connectionAttributes->strProfileName)) == id.toUInt()) { - QString guid("{%1-%2-%3-%4%5-%6%7%8%9%10%11}"); - - guid = guid.arg(interface.InterfaceGuid.Data1, 8, 16, QChar('0')); - guid = guid.arg(interface.InterfaceGuid.Data2, 4, 16, QChar('0')); - guid = guid.arg(interface.InterfaceGuid.Data3, 4, 16, QChar('0')); - for (int i = 0; i < 8; ++i) - guid = guid.arg(interface.InterfaceGuid.Data4[i], 2, 16, QChar('0')); - - local_WlanFreeMemory(connectionAttributes); - - return guid.toUpper(); - } - - local_WlanFreeMemory(connectionAttributes); - local_WlanFreeMemory(interfaceList); - } - - return QString(); -} - -bool QNativeWifiEngine::hasIdentifier(const QString &id) -{ - // enumerate interfaces - WLAN_INTERFACE_INFO_LIST *interfaceList; - DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result); - return false; - } - - for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) { - const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i]; - - WLAN_AVAILABLE_NETWORK_LIST *networkList; - result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid, - 3, 0, &networkList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanGetAvailableNetworkList failed with error %ld\n", - __FUNCTION__, result); - continue; - } - - for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) { - WLAN_AVAILABLE_NETWORK &network = networkList->Network[j]; - - QString networkName; - - if (network.strProfileName[0] != 0) { - networkName = QString::fromWCharArray(network.strProfileName); - } else { - networkName = QByteArray(reinterpret_cast(network.dot11Ssid.ucSSID), - network.dot11Ssid.uSSIDLength); - } - - if (qHash(QLatin1String("WLAN:") + networkName) == id.toUInt()) { - local_WlanFreeMemory(networkList); - local_WlanFreeMemory(interfaceList); - return true; - } - } - - local_WlanFreeMemory(networkList); - } - - local_WlanFreeMemory(interfaceList); - - return false; -} - -/*QString QNativeWifiEngine::bearerName(const QString &) -{ - return QLatin1String("WLAN"); -}*/ - -void QNativeWifiEngine::connectToId(const QString &id) -{ - WLAN_INTERFACE_INFO_LIST *interfaceList; - DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result); - emit connectionError(id, InterfaceLookupError); - return; - } - - QString profile; - - for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) { - const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i]; - - WLAN_AVAILABLE_NETWORK_LIST *networkList; - result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid, - 3, 0, &networkList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanGetAvailableNetworkList failed with error %ld\n", - __FUNCTION__, result); - continue; - } - - for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) { - WLAN_AVAILABLE_NETWORK &network = networkList->Network[j]; - - profile = QString::fromWCharArray(network.strProfileName); - - if (qHash(QLatin1String("WLAN:") + profile) == id.toUInt()) - break; - else - profile.clear(); - } - - local_WlanFreeMemory(networkList); - - if (!profile.isEmpty()) { - WLAN_CONNECTION_PARAMETERS parameters; - parameters.wlanConnectionMode = wlan_connection_mode_profile; - parameters.strProfile = reinterpret_cast(profile.utf16()); - parameters.pDot11Ssid = 0; - parameters.pDesiredBssidList = 0; - parameters.dot11BssType = dot11_BSS_type_any; - parameters.dwFlags = 0; - - DWORD result = local_WlanConnect(handle, &interface.InterfaceGuid, ¶meters, 0); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanConnect failed with error %ld\n", __FUNCTION__, result); - emit connectionError(id, ConnectError); - break; - } - - break; - } - } - - local_WlanFreeMemory(interfaceList); - - if (profile.isEmpty()) - emit connectionError(id, InterfaceLookupError); -} - -void QNativeWifiEngine::disconnectFromId(const QString &id) -{ - QString interface = getInterfaceFromId(id); - - if (interface.isEmpty()) { - emit connectionError(id, InterfaceLookupError); - return; - } - - QStringList split = interface.mid(1, interface.length() - 2).split('-'); - - GUID guid; - guid.Data1 = split.at(0).toUInt(0, 16); - guid.Data2 = split.at(1).toUShort(0, 16); - guid.Data3 = split.at(2).toUShort(0, 16); - guid.Data4[0] = split.at(3).left(2).toUShort(0, 16); - guid.Data4[1] = split.at(3).right(2).toUShort(0, 16); - for (int i = 0; i < 6; ++i) - guid.Data4[i + 2] = split.at(4).mid(i*2, 2).toUShort(0, 16); - - DWORD result = local_WlanDisconnect(handle, &guid, 0); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanDisconnect failed with error %ld\n", __FUNCTION__, result); - emit connectionError(id, DisconnectionError); - return; - } -} - -void QNativeWifiEngine::requestUpdate() -{ - // enumerate interfaces - WLAN_INTERFACE_INFO_LIST *interfaceList; - DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList); - if (result != ERROR_SUCCESS) { - qWarning("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result); - return; - } - - for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) { - result = local_WlanScan(handle, &interfaceList->InterfaceInfo[i].InterfaceGuid, 0, 0, 0); - if (result != ERROR_SUCCESS) - qWarning("%s: WlanScan failed with error %ld\n", __FUNCTION__, result); - } -} - -QNativeWifiEngine *QNativeWifiEngine::instance() -{ - resolveLibrary(); - - // native wifi dll not available - if (!local_WlanOpenHandle) - return 0; - - QNativeWifiEngine *engine = nativeWifiEngine(); - - // could not initialise subsystem - if (engine && engine->handle == 0) - return 0; - - return engine; -} - -#include "moc_qnativewifiengine_win_p.cpp" - -QTM_END_NAMESPACE diff --git a/src/bearer/qnativewifiengine_win_p.h b/src/bearer/qnativewifiengine_win_p.h deleted file mode 100644 index 96123b8..0000000 --- a/src/bearer/qnativewifiengine_win_p.h +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNATIVEWIFIENGINE_P_H -#define QNATIVEWIFIENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qnetworksessionengine_p.h" - -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; - -class QNativeWifiEngine : public QNetworkSessionEngine -{ - Q_OBJECT - -public: - QNativeWifiEngine(QObject *parent = 0); - ~QNativeWifiEngine(); - - QList getConfigurations(bool *ok = 0); - QString getInterfaceFromId(const QString &id); - bool hasIdentifier(const QString &id); - - //QString bearerName(const QString &id); - - void connectToId(const QString &id); - void disconnectFromId(const QString &id); - - void requestUpdate(); - - inline void emitConfigurationsChanged() { emit configurationsChanged(); } - - static QNativeWifiEngine *instance(); - -private: - QTimer pollTimer; - - Qt::HANDLE handle; -}; - -QTM_END_NAMESPACE - -#endif diff --git a/src/bearer/qnetworkconfigmanager.cpp b/src/bearer/qnetworkconfigmanager.cpp index 2317232..2d67e76 100644 --- a/src/bearer/qnetworkconfigmanager.cpp +++ b/src/bearer/qnetworkconfigmanager.cpp @@ -39,15 +39,7 @@ ** ****************************************************************************/ -#include "qnetworkconfigmanager.h" - -#ifdef Q_OS_SYMBIAN -#include "qnetworkconfigmanager_s60_p.h" -#elif (defined(Q_WS_MAEMO_6) || defined(Q_WS_MAEMO_5)) -#include "qnetworkconfigmanager_maemo_p.h" -#else #include "qnetworkconfigmanager_p.h" -#endif #include @@ -219,16 +211,16 @@ QNetworkConfigurationManager::QNetworkConfigurationManager( QObject* parent ) : QObject(parent) { QNetworkConfigurationManagerPrivate* priv = connManager(); - connect(priv, SIGNAL(configurationAdded(QNetworkConfiguration)), - this, SIGNAL(configurationAdded(QNetworkConfiguration))); - connect(priv, SIGNAL(configurationRemoved(QNetworkConfiguration)), - this, SIGNAL(configurationRemoved(QNetworkConfiguration))); - connect(priv, SIGNAL(configurationUpdateComplete()), + connect(priv, SIGNAL(configurationAdded(const QNetworkConfiguration&)), + this, SIGNAL(configurationAdded(const QNetworkConfiguration&))); + connect(priv, SIGNAL(configurationRemoved(const QNetworkConfiguration&)), + this, SIGNAL(configurationRemoved(const QNetworkConfiguration&))); + connect(&(priv->impl), SIGNAL(updateCompleted()), this, SIGNAL(updateCompleted())); - connect(priv, SIGNAL(onlineStateChanged(bool)), + connect(&(priv->impl), SIGNAL(onlineStateChanged(bool)), this, SIGNAL(onlineStateChanged(bool))); - connect(priv, SIGNAL(configurationChanged(QNetworkConfiguration)), - this, SIGNAL(configurationChanged(QNetworkConfiguration))); + connect(priv, SIGNAL(configurationChanged(const QNetworkConfiguration&)), + this, SIGNAL(configurationChanged(const QNetworkConfiguration&))); } /*! @@ -250,7 +242,7 @@ QNetworkConfigurationManager::~QNetworkConfigurationManager() */ QNetworkConfiguration QNetworkConfigurationManager::defaultConfiguration() const { - return connManager()->defaultConfiguration(); + return connManager()->impl.defaultConfiguration(); } /*! @@ -280,29 +272,12 @@ QNetworkConfiguration QNetworkConfigurationManager::defaultConfiguration() const */ QList QNetworkConfigurationManager::allConfigurations(QNetworkConfiguration::StateFlags filter) const { + QT_PREPEND_NAMESPACE(QNetworkConfiguration::StateFlags) f((int)filter); QList result; - QNetworkConfigurationManagerPrivate* conPriv = connManager(); - - //find all InternetAccessPoints - foreach (const QString &ii, conPriv->accessPointConfigurations.keys()) { - QExplicitlySharedDataPointer p = - conPriv->accessPointConfigurations.value(ii); - if ( (p->state & filter) == filter ) { - QNetworkConfiguration pt; - pt.d = conPriv->accessPointConfigurations.value(ii); - result << pt; - } - } + QListIterator iter(connManager()->impl.allConfigurations(f)); - //find all service networks - foreach (const QString &ii, conPriv->snapConfigurations.keys()) { - QExplicitlySharedDataPointer p = - conPriv->snapConfigurations.value(ii); - if ( (p->state & filter) == filter ) { - QNetworkConfiguration pt; - pt.d = conPriv->snapConfigurations.value(ii); - result << pt; - } + while (iter.hasNext()) { + result.append(iter.next()); } return result; @@ -316,16 +291,7 @@ QList QNetworkConfigurationManager::allConfigurations(QNe */ QNetworkConfiguration QNetworkConfigurationManager::configurationFromIdentifier(const QString& identifier) const { - QNetworkConfigurationManagerPrivate* conPriv = connManager(); - QNetworkConfiguration item; - if (conPriv->accessPointConfigurations.contains(identifier)) - item.d = conPriv->accessPointConfigurations.value(identifier); - else if (conPriv->snapConfigurations.contains(identifier)) - item.d = conPriv->snapConfigurations.value(identifier); - else if (conPriv->userChoiceConfigurations.contains(identifier)) - item.d = conPriv->userChoiceConfigurations.value(identifier); - return item; - + return connManager()->impl.configurationFromIdentifier(identifier); } /*! @@ -347,10 +313,7 @@ QNetworkConfiguration QNetworkConfigurationManager::configurationFromIdentifier( */ bool QNetworkConfigurationManager::isOnline() const { - QNetworkConfigurationManagerPrivate* conPriv = connManager(); - Q_UNUSED(conPriv); - QList activeConfigs = allConfigurations(QNetworkConfiguration::Active); - return activeConfigs.count() > 0; + return connManager()->impl.isOnline(); } /*! @@ -358,7 +321,7 @@ bool QNetworkConfigurationManager::isOnline() const */ QNetworkConfigurationManager::Capabilities QNetworkConfigurationManager::capabilities() const { - return connManager()->capFlags; + return (QNetworkConfigurationManager::Capabilities)(int)connManager()->impl.capabilities(); } /*! @@ -377,10 +340,36 @@ QNetworkConfigurationManager::Capabilities QNetworkConfigurationManager::capabil */ void QNetworkConfigurationManager::updateConfigurations() { - connManager()->performAsyncConfigurationUpdate(); + connManager()->impl.updateConfigurations(); +} + +QNetworkConfigurationManagerPrivate::QNetworkConfigurationManagerPrivate() +{ + connect(&impl, SIGNAL(configurationAdded(const QNetworkConfiguration&)), + this, SLOT(_q_configurationAdded(const QNetworkConfiguration&))); + connect(&impl, SIGNAL(configurationRemoved(const QNetworkConfiguration&)), + this, SLOT(_q_configurationRemoved(const QNetworkConfiguration&))); + connect(&impl, SIGNAL(configurationChanged(const QNetworkConfiguration&)), + this, SLOT(_q_configurationChanged(const QNetworkConfiguration&))); +} + +void QNetworkConfigurationManagerPrivate::_q_configurationAdded(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config) +{ + emit configurationAdded(config); +} + +void QNetworkConfigurationManagerPrivate::_q_configurationRemoved(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config) +{ + emit configurationRemoved(config); +} + +void QNetworkConfigurationManagerPrivate::_q_configurationChanged(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config) +{ + emit configurationChanged(config); } #include "moc_qnetworkconfigmanager.cpp" +#include "moc_qnetworkconfigmanager_p.cpp" QTM_END_NAMESPACE diff --git a/src/bearer/qnetworkconfigmanager.h b/src/bearer/qnetworkconfigmanager.h index fcc46f2..69c3cf2 100644 --- a/src/bearer/qnetworkconfigmanager.h +++ b/src/bearer/qnetworkconfigmanager.h @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#ifndef QNETWORKCONFIGURATIONMANAGER_H -#define QNETWORKCONFIGURATIONMANAGER_H +#ifndef QTM_NETWORKCONFIGURATIONMANAGER_H +#define QTM_NETWORKCONFIGURATIONMANAGER_H #include "qmobilityglobal.h" @@ -98,5 +98,5 @@ QTM_END_NAMESPACE QT_END_HEADER -#endif //QNETWORKCONFIGURATIONMANAGER_H +#endif //QTM_NETWORKCONFIGURATIONMANAGER_H diff --git a/src/bearer/qnetworkconfigmanager_maemo.cpp b/src/bearer/qnetworkconfigmanager_maemo.cpp deleted file mode 100644 index 00d26b0..0000000 --- a/src/bearer/qnetworkconfigmanager_maemo.cpp +++ /dev/null @@ -1,910 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "qnetworkconfigmanager_maemo_p.h" - -#include -#include - -#include -#include -#include -#include -#include - -QTM_BEGIN_NAMESPACE - -/* The IapAddTimer is a helper class that makes sure we update - * the configuration only after all db additions to certain - * iap are finished (after a certain timeout) - */ -class _IapAddTimer : public QObject -{ - Q_OBJECT - -public: - _IapAddTimer() {} - ~_IapAddTimer() - { - if (timer.isActive()) { - QObject::disconnect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); - timer.stop(); - } - } - - void add(QString& iap_id, QNetworkConfigurationManagerPrivate *d); - - QString iap_id; - QTimer timer; - QNetworkConfigurationManagerPrivate *d; - -public Q_SLOTS: - void timeout(); -}; - - -void _IapAddTimer::add(QString& id, QNetworkConfigurationManagerPrivate *d_ptr) -{ - iap_id = id; - d = d_ptr; - - if (timer.isActive()) { - QObject::disconnect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); - timer.stop(); - } - timer.setSingleShot(true); - QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); - timer.start(1500); -} - - -void _IapAddTimer::timeout() -{ - d->addConfiguration(iap_id); -} - - -class IapAddTimer { - QHash timers; - -public: - IapAddTimer() {} - ~IapAddTimer() {} - - void add(QString& iap_id, QNetworkConfigurationManagerPrivate *d); - void del(QString& iap_id); - void removeAll(); -}; - - -void IapAddTimer::removeAll() -{ - QHashIterator i(timers); - while (i.hasNext()) { - i.next(); - _IapAddTimer *t = i.value(); - delete t; - } - timers.clear(); -} - - -void IapAddTimer::add(QString& iap_id, QNetworkConfigurationManagerPrivate *d) -{ - if (timers.contains(iap_id)) { - _IapAddTimer *iap = timers.value(iap_id); - iap->add(iap_id, d); - } else { - _IapAddTimer *iap = new _IapAddTimer; - iap->add(iap_id, d); - timers.insert(iap_id, iap); - } -} - -void IapAddTimer::del(QString& iap_id) -{ - if (timers.contains(iap_id)) { - _IapAddTimer *iap = timers.take(iap_id); - delete iap; - } -} - - -class IapMonitor : public Maemo::IAPMonitor -{ -public: - IapMonitor() : first_call(true) { } - - void setup(QNetworkConfigurationManagerPrivate *d); - void cleanup(); - -protected: - void iapAdded(const QString &iapId); - void iapRemoved(const QString &iapId); - -private: - bool first_call; - - QNetworkConfigurationManagerPrivate *d; - IapAddTimer timers; -}; - -Q_GLOBAL_STATIC(IapMonitor, iapMonitor); - - -void IapMonitor::setup(QNetworkConfigurationManagerPrivate *d_ptr) -{ - if (first_call) { - d = d_ptr; - first_call = false; - } -} - - -void IapMonitor::cleanup() -{ - if (!first_call) { - timers.removeAll(); - first_call = true; - } -} - - -void IapMonitor::iapAdded(const QString &iap_id) -{ - /* We cannot know when the IAP is fully added to db, so a timer is - * installed instead. When the timer expires we hope that IAP is added ok. - */ - QString id = iap_id; - timers.add(id, d); -} - - -void IapMonitor::iapRemoved(const QString &iap_id) -{ - QString id = iap_id; - d->deleteConfiguration(id); -} - -void QNetworkConfigurationManagerPrivate::registerPlatformCapabilities() -{ - capFlags |= QNetworkConfigurationManager::CanStartAndStopInterfaces; - capFlags |= QNetworkConfigurationManager::DataStatistics; - capFlags |= QNetworkConfigurationManager::ForcedRoaming; - capFlags |= QNetworkConfigurationManager::NetworkSessionRequired; -} - -void QNetworkConfigurationManagerPrivate::init() -{ - // Setup DBus Interface for ICD - m_dbusInterface = new QDBusInterface(ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_PATH, - ICD_DBUS_API_INTERFACE, - QDBusConnection::systemBus(), - this); - connect(&m_scanTimer, SIGNAL(timeout()), this, SLOT(finishAsyncConfigurationUpdate())); - m_scanTimer.setSingleShot(true); - - /* Turn on IAP state monitoring */ - startListeningStateSignalsForAllConnections(); - - /* Turn on IAP add/remove monitoring */ - iapMonitor()->setup(this); - - /* We create a default configuration which is a pseudo config */ - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - cpPriv->name = "UserChoice"; - cpPriv->state = QNetworkConfiguration::Discovered; - cpPriv->isValid = true; - cpPriv->id = OSSO_IAP_ANY; - cpPriv->type = QNetworkConfiguration::UserChoice; - cpPriv->purpose = QNetworkConfiguration::UnknownPurpose; - cpPriv->roamingSupported = false; - cpPriv->manager = this; - QExplicitlySharedDataPointer ptr(cpPriv); - userChoiceConfigurations.insert(cpPriv->id, ptr); -} - -static inline QString network_attrs_to_security(uint network_attrs) -{ - uint cap = 0; - nwattr2cap(network_attrs, &cap); /* from libicd-network-wlan-dev.h */ - if (cap & WLANCOND_OPEN) - return "NONE"; - else if (cap & WLANCOND_WEP) - return "WEP"; - else if (cap & WLANCOND_WPA_PSK) - return "WPA_PSK"; - else if (cap & WLANCOND_WPA_EAP) - return "WPA_EAP"; - return ""; -} - - -struct SSIDInfo { - QString iap_id; - QString wlan_security; -}; - - -void QNetworkConfigurationManagerPrivate::configurationChanged(QNetworkConfigurationPrivate *ptr) -{ - QNetworkConfiguration item; - item.d = ptr; - emit configurationChanged(item); -} - -void QNetworkConfigurationManagerPrivate::deleteConfiguration(QString& iap_id) -{ - /* Called when IAPs are deleted in db, in this case we do not scan - * or read all the IAPs from db because it might take too much power - * (multiple applications would need to scan and read all IAPs from db) - */ - if (accessPointConfigurations.contains(iap_id)) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.take(iap_id); - if (priv.data()) { - priv->isValid = false; -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "IAP" << iap_id << "was removed from storage."; -#endif - - QNetworkConfiguration item; - item.d = priv; - emit configurationRemoved(item); - } else - qWarning("Configuration not found for IAP %s", iap_id.toAscii().data()); - } else { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug("IAP: %s, already missing from the known list", iap_id.toAscii().data()); -#endif - } -} - - -quint32 QNetworkConfigurationManagerPrivate::getNetworkAttrs(bool is_iap_id, - const QString& iap_id, - const QString& iap_type, - QString security_method) -{ - guint network_attr = 0; - dbus_uint32_t cap = 0; - - if (iap_type == "WLAN_INFRA") - cap |= WLANCOND_INFRA; - else if (iap_type == "WLAN_ADHOC") - cap |= WLANCOND_ADHOC; - - if (security_method.isEmpty() && (cap & (WLANCOND_INFRA | WLANCOND_ADHOC))) { - Maemo::IAPConf saved_ap(iap_id); - security_method = saved_ap.value("wlan_security").toString(); - } - - if (!security_method.isEmpty()) { - if (security_method == "WEP") - cap |= WLANCOND_WEP; - else if (security_method == "WPA_PSK") - cap |= WLANCOND_WPA_PSK; - else if (security_method == "WPA_EAP") - cap |= WLANCOND_WPA_EAP; - else if (security_method == "NONE") - cap |= WLANCOND_OPEN; - - if (cap & (WLANCOND_WPA_PSK | WLANCOND_WPA_EAP)) { - Maemo::IAPConf saved_iap(iap_id); - bool wpa2_only = saved_iap.value("EAP_wpa2_only_mode").toBool(); - if (wpa2_only) { - cap |= WLANCOND_WPA2; - } - } - } - - cap2nwattr(cap, &network_attr); - if (is_iap_id) - network_attr |= ICD_NW_ATTR_IAPNAME; - - return (quint32)network_attr; -} - - -void QNetworkConfigurationManagerPrivate::addConfiguration(QString& iap_id) -{ - // Note: When new IAP is created, this function gets called multiple times - // in a row. - // For example: Empty type & name for WLAN was stored into newly - // created IAP data in gconf when this function gets - // called for the first time. - // WLAN type & name are updated into IAP data in gconf - // as soon as WLAN connection is up and running. - // => And this function gets called again. - - if (!accessPointConfigurations.contains(iap_id)) { - Maemo::IAPConf saved_iap(iap_id); - QString iap_type = saved_iap.value("type").toString(); - QString iap_name = saved_iap.value("name").toString(); - QByteArray ssid = saved_iap.value("wlan_ssid").toByteArray(); - if (!iap_type.isEmpty() && !iap_name.isEmpty()) { - // Check if new IAP is actually Undefined WLAN configuration - // Note: SSID is used as an iap id for Undefined WLAN configurations - // => configuration must be searched using SSID - if (!ssid.isEmpty() && accessPointConfigurations.contains(ssid)) { - QExplicitlySharedDataPointer ptr = accessPointConfigurations.take(ssid); - if (ptr.data()) { - ptr->id = iap_id; - ptr->iap_type = iap_type; - ptr->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString()); - ptr->network_id = ssid; - ptr->service_id = saved_iap.value("service_id").toString(); - ptr->service_type = saved_iap.value("service_type").toString(); - if (m_onlineIapId == iap_id) { - ptr->state = QNetworkConfiguration::Active; - } else { - ptr->state = QNetworkConfiguration::Defined; - } - accessPointConfigurations.insert(iap_id, ptr); - configurationChanged(ptr.data()); - } - } else { - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - cpPriv->name = saved_iap.value("name").toString(); - if (cpPriv->name.isEmpty()) - cpPriv->name = iap_id; - cpPriv->isValid = true; - cpPriv->id = iap_id; - cpPriv->iap_type = iap_type; - cpPriv->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString()); - cpPriv->service_id = saved_iap.value("service_id").toString(); - cpPriv->service_type = saved_iap.value("service_type").toString(); - if (iap_type.startsWith(QLatin1String("WLAN"))) { - QByteArray ssid = saved_iap.value("wlan_ssid").toByteArray(); - if (ssid.isEmpty()) { - qWarning() << "Cannot get ssid for" << iap_id; - } - cpPriv->network_id = ssid; - } - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - if (m_onlineIapId == iap_id) { - cpPriv->state = QNetworkConfiguration::Active; - } else { - cpPriv->state = QNetworkConfiguration::Defined; - } - cpPriv->manager = this; - - QExplicitlySharedDataPointer ptr(cpPriv); - accessPointConfigurations.insert(iap_id, ptr); - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug("IAP: %s, name: %s, added to known list", iap_id.toAscii().data(), cpPriv->name.toAscii().data()); -#endif - QNetworkConfiguration item; - item.d = ptr; - emit configurationAdded(item); - } - } else { - qWarning("IAP %s does not have \"type\" or \"name\" fields defined, skipping this IAP.", iap_id.toAscii().data()); - } - } else { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "IAP" << iap_id << "already in db."; -#endif - - /* Check if the data in db changed and update configuration accordingly - */ - QExplicitlySharedDataPointer ptr = accessPointConfigurations.value(iap_id); - if (ptr.data()) { - Maemo::IAPConf changed_iap(iap_id); - QString iap_type = changed_iap.value("type").toString(); - bool update_needed = false; /* if IAP type or ssid changed, we need to change the state */ - - ptr->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString()); - ptr->service_id = changed_iap.value("service_id").toString(); - ptr->service_type = changed_iap.value("service_type").toString(); - - if (!iap_type.isEmpty()) { - ptr->name = changed_iap.value("name").toString(); - if (ptr->name.isEmpty()) - ptr->name = iap_id; - ptr->isValid = true; - if (ptr->iap_type != iap_type) { - ptr->iap_type = iap_type; - update_needed = true; - } - if (iap_type.startsWith(QLatin1String("WLAN"))) { - QByteArray ssid = changed_iap.value("wlan_ssid").toByteArray(); - if (ssid.isEmpty()) { - qWarning() << "Cannot get ssid for" << iap_id; - } - if (ptr->network_id != ssid) { - ptr->network_id = ssid; - update_needed = true; - } - } - } - if (update_needed) { - ptr->type = QNetworkConfiguration::InternetAccessPoint; - if (m_onlineIapId == iap_id) { - if (ptr->state < QNetworkConfiguration::Active) { - ptr->state = QNetworkConfiguration::Active; - configurationChanged(ptr.data()); - } - } else if (ptr->state < QNetworkConfiguration::Defined) { - ptr->state = QNetworkConfiguration::Defined; - configurationChanged(ptr.data()); - } - } - } else { - qWarning("Cannot find IAP %s from current configuration although it should be there.", iap_id.toAscii().data()); - } - } -} - -void QNetworkConfigurationManagerPrivate::updateConfigurations() -{ - doUpdateConfigurations(); -} - -void QNetworkConfigurationManagerPrivate::doUpdateConfigurations(QList scanned) -{ - /* Contains all known iap_ids from storage */ - QList knownConfigs = accessPointConfigurations.keys(); - - /* Contains all known WLAN network ids (like ssid) from storage */ - QMultiHash notDiscoveredWLANConfigs; - - QList all_iaps; - Maemo::IAPConf::getAll(all_iaps); - - foreach (const QString &iap_id, all_iaps) { - QByteArray ssid; - - Maemo::IAPConf saved_ap(iap_id); - bool is_temporary = saved_ap.value("temporary").toBool(); - if (is_temporary) { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "IAP" << iap_id << "is temporary, skipping it."; -#endif - continue; - } - - QString iap_type = saved_ap.value("type").toString(); - if (iap_type.startsWith(QLatin1String("WLAN"))) { - ssid = saved_ap.value("wlan_ssid").toByteArray(); - if (ssid.isEmpty()) { - qWarning() << "Cannot get ssid for" << iap_id; - continue; - } - - QString security_method = saved_ap.value("wlan_security").toString(); - SSIDInfo *info = new SSIDInfo; - info->iap_id = iap_id; - info->wlan_security = security_method; - notDiscoveredWLANConfigs.insert(ssid, info); - } else if (iap_type.isEmpty()) { - qWarning() << "IAP" << iap_id << "network type is not set! Skipping it"; - continue; - } else { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "IAP" << iap_id << "network type is" << iap_type; -#endif - ssid.clear(); - } - - if (!accessPointConfigurations.contains(iap_id)) { - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - cpPriv->name = saved_ap.value("name").toString(); - if (cpPriv->name.isEmpty()) { - if (!ssid.isEmpty() && ssid.size() > 0) - cpPriv->name = ssid.data(); - else - cpPriv->name = iap_id; - } - cpPriv->isValid = true; - cpPriv->id = iap_id; - cpPriv->network_id = ssid; - cpPriv->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString()); - cpPriv->iap_type = iap_type; - cpPriv->service_id = saved_ap.value("service_id").toString(); - cpPriv->service_type = saved_ap.value("service_type").toString(); - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - cpPriv->state = QNetworkConfiguration::Defined; - cpPriv->manager = this; - - QExplicitlySharedDataPointer ptr(cpPriv); - accessPointConfigurations.insert(iap_id, ptr); - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug("IAP: %s, name: %s, ssid: %s, added to known list", iap_id.toAscii().data(), cpPriv->name.toAscii().data(), !ssid.isEmpty() ? ssid.data() : "-"); -#endif - } else { - knownConfigs.removeOne(iap_id); -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug("IAP: %s, ssid: %s, already exists in the known list", iap_id.toAscii().data(), !ssid.isEmpty() ? ssid.data() : "-"); -#endif - } - } - - /* This is skipped in the first update as scanned size is zero */ - if (!scanned.isEmpty()) - for (int i=0; i priv = accessPointConfigurations.value(iapid); - if (priv.data()) { - bool stateChanged = false; - // Check if state is not already Discovered or Active - if (priv->state < QNetworkConfiguration::Discovered) { - priv->state = QNetworkConfiguration::Discovered; /* Defined is set automagically */ - stateChanged = true; - } - priv->network_attrs = ap.scan.network_attrs; - priv->service_id = ap.scan.service_id; - priv->service_type = ap.scan.service_type; - priv->service_attrs = ap.scan.service_attrs; - - if (stateChanged) { - configurationChanged(priv.data()); - } -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug("IAP: %s, ssid: %s, discovered", iapid.toAscii().data(), priv->network_id.data()); -#endif - - if (!ap.scan.network_type.startsWith(QLatin1String("WLAN"))) - continue; // not a wlan AP - - /* Remove scanned AP from discovered WLAN configurations so that we can - * emit configurationRemoved signal later - */ - QList known_iaps = notDiscoveredWLANConfigs.values(priv->network_id); - rescan_list: - if (!known_iaps.isEmpty()) { - for (int k=0; kiap_id << "security" << iap->wlan_security << "scan" << network_attrs_to_security(ap.scan.network_attrs); -#endif - - if (iap->wlan_security == - network_attrs_to_security(ap.scan.network_attrs)) { - /* Remove IAP from the list */ - notDiscoveredWLANConfigs.remove(priv->network_id, iap); -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "Removed IAP" << iap->iap_id << "from unknown config"; -#endif - known_iaps.removeAt(k); - delete iap; - goto rescan_list; - } - } - } - } else { - qWarning() << "IAP" << iapid << "is missing in configuration."; - } - - } else { - /* Non saved access point data */ - QByteArray scanned_ssid = ap.scan.network_id; - if (!accessPointConfigurations.contains(scanned_ssid)) { - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - QString hrs = scanned_ssid.data(); - - cpPriv->name = ap.network_name.isEmpty() ? hrs : ap.network_name; - cpPriv->isValid = true; - cpPriv->id = scanned_ssid.data(); // Note: id is now ssid, it should be set to IAP id if the IAP is saved - cpPriv->network_id = scanned_ssid; - cpPriv->iap_type = ap.scan.network_type; - cpPriv->network_attrs = ap.scan.network_attrs; - cpPriv->service_id = ap.scan.service_id; - cpPriv->service_type = ap.scan.service_type; - cpPriv->service_attrs = ap.scan.service_attrs; - cpPriv->manager = this; - - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - cpPriv->state = QNetworkConfiguration::Undefined; - - QExplicitlySharedDataPointer ptr(cpPriv); - accessPointConfigurations.insert(cpPriv->id, ptr); - - #ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "IAP with network id" << cpPriv->id << "was found in the scan."; - #endif - - QNetworkConfiguration item; - item.d = ptr; - emit configurationAdded(item); - } else { - knownConfigs.removeOne(scanned_ssid); - } - } - } - - if (!firstUpdate) { - // Update Defined status to all defined WLAN IAPs which - // could not be found when access points were scanned - QHashIterator i(notDiscoveredWLANConfigs); - while (i.hasNext()) { - i.next(); - SSIDInfo *iap = i.value(); - QString iap_id = iap->iap_id; - //qDebug() << i.key() << ": " << iap_id; - - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iap_id); - if (priv.data()) { - // WLAN AccessPoint configuration could not be Discovered - // => Make sure that configuration state is Defined - if (priv->state > QNetworkConfiguration::Defined) { - priv->state = QNetworkConfiguration::Defined; - configurationChanged(priv.data()); - } - } - } - - /* Remove non existing iaps since last update */ - foreach (const QString &oldIface, knownConfigs) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.take(oldIface); - if (priv.data()) { - priv->isValid = false; - QNetworkConfiguration item; - item.d = priv; - emit configurationRemoved(item); - //if we would have SNAP support we would have to remove the references - //from existing ServiceNetworks to the removed access point configuration - } - } - } - - QMutableHashIterator i(notDiscoveredWLANConfigs); - while (i.hasNext()) { - i.next(); - SSIDInfo *iap = i.value(); - delete iap; - i.remove(); - } - - if (!firstUpdate) - emit configurationUpdateComplete(); - - if (firstUpdate) - firstUpdate = false; -} - -QNetworkConfiguration QNetworkConfigurationManagerPrivate::defaultConfiguration() -{ - /* Here we just return [ANY] request to icd and let the icd decide which - * IAP to connect. - */ - QNetworkConfiguration item; - if (userChoiceConfigurations.contains(OSSO_IAP_ANY)) - item.d = userChoiceConfigurations.value(OSSO_IAP_ANY); - return item; -} - -void QNetworkConfigurationManagerPrivate::startListeningStateSignalsForAllConnections() -{ - // Start listening ICD_DBUS_API_STATE_SIG signals - m_dbusInterface->connection().connect(ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_PATH, - ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_STATE_SIG, - this, SLOT(connectionStateSignalsSlot(QDBusMessage))); - - // Calling ICD_DBUS_API_STATE_REQ makes sure that initial state will be updated immediately - m_gettingInitialConnectionState = true; - m_dbusInterface->call(ICD_DBUS_API_STATE_REQ); -} - -void QNetworkConfigurationManagerPrivate::connectionStateSignalsSlot(QDBusMessage msg) -{ - QList arguments = msg.arguments(); - if (arguments[1].toUInt() != 0 || arguments.count() < 8) { - return; - } - - QString iapid = arguments[5].toByteArray().data(); - uint icd_connection_state = arguments[7].toUInt(); - - switch (icd_connection_state) { - case ICD_STATE_CONNECTED: - { - QExplicitlySharedDataPointer ptr = accessPointConfigurations.value(iapid); - if (ptr.data()) { - ptr->type = QNetworkConfiguration::InternetAccessPoint; - if (ptr->state != QNetworkConfiguration::Active) { - ptr->state = QNetworkConfiguration::Active; - if (!m_gettingInitialConnectionState) { - configurationChanged(ptr.data()); - if (m_onlineIapId.isEmpty()) { - emit onlineStateChanged(true); - } - } - m_onlineIapId = iapid; - } - } else { - // This gets called when new WLAN IAP is created using Connection dialog - // At this point Undefined WLAN configuration has SSID as iap id - // => Because of that configuration can not be found from - // accessPointConfigurations using correct iap id - emit onlineStateChanged(true); - m_onlineIapId = iapid; - } - break; - } - case ICD_STATE_DISCONNECTED: - { - QExplicitlySharedDataPointer ptr = accessPointConfigurations.value(iapid); - if (ptr.data()) { - ptr->type = QNetworkConfiguration::InternetAccessPoint; - if (ptr->state == QNetworkConfiguration::Active) { - ptr->state = QNetworkConfiguration::Discovered; - if (!m_gettingInitialConnectionState) { - configurationChanged(ptr.data()); - - // Note: If ICD switches used IAP from one to another: - // 1) new IAP is reported to be online first - // 2) old IAP is reported to be offline then - // => Device can be reported to be offline only - // if last known online IAP is reported to be disconnected - if (iapid == m_onlineIapId) { - // It's known that there is only one global ICD connection - // => Because ICD state was reported to be DISCONNECTED, Device is offline - m_onlineIapId.clear(); - emit onlineStateChanged(false); - } - } - } - } else { - // Disconnected IAP was not found from accessPointConfigurations - // => Reason: Online IAP was removed which resulted ICD to disconnect - if (iapid == m_onlineIapId) { - // It's known that there is only one global ICD connection - // => Because ICD state was reported to be DISCONNECTED, Device is offline - m_onlineIapId.clear(); - emit onlineStateChanged(false); - } - } - break; - } - default: - break; - } - - emit iapStateChanged(iapid, icd_connection_state); - - m_gettingInitialConnectionState = false; -} - -void QNetworkConfigurationManagerPrivate::performAsyncConfigurationUpdate() -{ - if (m_scanGoingOn) { - return; - } - m_scanGoingOn = true; - - m_dbusInterface->connection().connect(ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_PATH, - ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_SCAN_SIG, - this, SLOT(asyncUpdateConfigurationsSlot(QDBusMessage))); - - QDBusMessage msg = m_dbusInterface->call(ICD_DBUS_API_SCAN_REQ, - (uint)ICD_SCAN_REQUEST_ACTIVE); - m_typesToBeScanned = msg.arguments()[0].value(); - m_scanTimer.start(ICD_SHORT_SCAN_TIMEOUT); -} - -void QNetworkConfigurationManagerPrivate::cancelAsyncConfigurationUpdate() -{ - if (!m_scanGoingOn) { - return; - } - m_scanGoingOn = false; - - if (m_scanTimer.isActive()) { - m_scanTimer.stop(); - } - - m_dbusInterface->connection().disconnect(ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_PATH, - ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_SCAN_SIG, - this, SLOT(asyncUpdateConfigurationsSlot(QDBusMessage))); - - // Stop scanning rounds by calling ICD_DBUS_API_SCAN_CANCEL - // <=> If ICD_DBUS_API_SCAN_CANCEL is not called, new scanning round will - // be started after the module scan timeout. - m_dbusInterface->call(ICD_DBUS_API_SCAN_CANCEL); -} - -void QNetworkConfigurationManagerPrivate::finishAsyncConfigurationUpdate() -{ - cancelAsyncConfigurationUpdate(); - doUpdateConfigurations(m_scanResult); - m_scanResult.clear(); -} - -void QNetworkConfigurationManagerPrivate::asyncUpdateConfigurationsSlot(QDBusMessage msg) -{ - QList arguments = msg.arguments(); - uint icd_scan_status = arguments.takeFirst().toUInt(); - if (icd_scan_status == ICD_SCAN_COMPLETE) { - m_typesToBeScanned.removeOne(arguments[6].toString()); - if (!m_typesToBeScanned.count()) { - finishAsyncConfigurationUpdate(); - } - } else { - Maemo::IcdScanResult scanResult; - scanResult.status = icd_scan_status; - scanResult.timestamp = arguments.takeFirst().toUInt(); - scanResult.scan.service_type = arguments.takeFirst().toString(); - scanResult.service_name = arguments.takeFirst().toString(); - scanResult.scan.service_attrs = arguments.takeFirst().toUInt(); - scanResult.scan.service_id = arguments.takeFirst().toString(); - scanResult.service_priority = arguments.takeFirst().toInt(); - scanResult.scan.network_type = arguments.takeFirst().toString(); - scanResult.network_name = arguments.takeFirst().toString(); - scanResult.scan.network_attrs = arguments.takeFirst().toUInt(); - scanResult.scan.network_id = arguments.takeFirst().toByteArray(); - scanResult.network_priority = arguments.takeFirst().toInt(); - scanResult.signal_strength = arguments.takeFirst().toInt(); - scanResult.station_id = arguments.takeFirst().toString(); - scanResult.signal_dB = arguments.takeFirst().toInt(); - - m_scanResult.append(scanResult); - } -} - -void QNetworkConfigurationManagerPrivate::cleanup() -{ - if (m_scanGoingOn) { - m_scanTimer.stop(); - m_dbusInterface->call(ICD_DBUS_API_SCAN_CANCEL); - } - iapMonitor()->cleanup(); -} - -#include "qnetworkconfigmanager_maemo.moc" -#include "moc_qnetworkconfigmanager_maemo_p.cpp" - -QTM_END_NAMESPACE diff --git a/src/bearer/qnetworkconfigmanager_maemo_p.h b/src/bearer/qnetworkconfigmanager_maemo_p.h deleted file mode 100644 index 50e17ed..0000000 --- a/src/bearer/qnetworkconfigmanager_maemo_p.h +++ /dev/null @@ -1,166 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKCONFIGURATIONMANAGERPRIVATE_H -#define QNETWORKCONFIGURATIONMANAGERPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of the QLibrary class. This header file may change from -// version to version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include - -#include "qnetworkconfigmanager.h" -#include "qnetworkconfiguration_maemo_p.h" - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; - -class QNetworkConfigurationManagerPrivate : public QObject -{ - Q_OBJECT -public: - QNetworkConfigurationManagerPrivate() - : QObject(0), capFlags(0), firstUpdate(true), onlineConfigurations(0), m_scanGoingOn(false) - { - registerPlatformCapabilities(); - g_type_init(); - updateConfigurations(); - init(); - } - - virtual ~QNetworkConfigurationManagerPrivate() - { - QList configIdents = snapConfigurations.keys(); - foreach(const QString oldIface, configIdents) { - QExplicitlySharedDataPointer priv = snapConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - - configIdents = accessPointConfigurations.keys(); - foreach(const QString oldIface, configIdents) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - - configIdents = userChoiceConfigurations.keys(); - foreach(const QString oldIface, configIdents) { - QExplicitlySharedDataPointer priv = userChoiceConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - - cleanup(); - } - - QNetworkConfiguration defaultConfiguration(); - - void init(); - - QNetworkConfigurationManager::Capabilities capFlags; - void registerPlatformCapabilities(); - - void performAsyncConfigurationUpdate(); - void doUpdateConfigurations(QList scanned = QList()); - void startListeningStateSignalsForAllConnections(); - - //this table contains an up to date list of all configs at any time. - //it must be updated if configurations change, are added/removed or - //the members of ServiceNetworks change - QHash > accessPointConfigurations; - QHash > snapConfigurations; - QHash > userChoiceConfigurations; - bool firstUpdate; - int onlineConfigurations; - friend class IapMonitor; - void cleanup(); - void deleteConfiguration(QString &iap_id); - void addConfiguration(QString &iap_id); - void configurationChanged(QNetworkConfigurationPrivate *ptr); - quint32 getNetworkAttrs(bool is_iap_id, const QString& iap_id, - const QString& iap_type, QString security_method); - - QDBusInterface *m_dbusInterface; - QTimer m_scanTimer; - bool m_gettingInitialConnectionState; - bool m_scanGoingOn; - QStringList m_typesToBeScanned; - QList m_scanResult; - QString m_onlineIapId; - - friend class QNetworkSessionPrivate; - -public slots: - void updateConfigurations(); - -private slots: - void cancelAsyncConfigurationUpdate(); - void finishAsyncConfigurationUpdate(); - void asyncUpdateConfigurationsSlot(QDBusMessage msg); - void connectionStateSignalsSlot(QDBusMessage msg); - -Q_SIGNALS: - void configurationAdded(const QNetworkConfiguration& config); - void configurationRemoved(const QNetworkConfiguration& config); - void configurationUpdateComplete(); - void configurationChanged(const QNetworkConfiguration& config); - void onlineStateChanged(bool isOnline); - - void iapStateChanged(const QString& iapid, uint icd_connection_state); -}; - -QTM_END_NAMESPACE - -#endif //QNETWORKCONFIGURATIONMANAGERPRIVATE_H diff --git a/src/bearer/qnetworkconfigmanager_p.cpp b/src/bearer/qnetworkconfigmanager_p.cpp deleted file mode 100644 index 5612144..0000000 --- a/src/bearer/qnetworkconfigmanager_p.cpp +++ /dev/null @@ -1,453 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnetworkconfigmanager_p.h" -#include "qgenericengine_p.h" - -#ifdef Q_OS_WIN -#include "qnlaengine_win_p.h" -#endif -#ifdef Q_OS_WIN32 -#include "qnativewifiengine_win_p.h" -#endif -#if defined(BACKEND_NM) -#include "qnmwifiengine_unix_p.h" -#endif -#ifdef Q_OS_DARWIN -#include "qcorewlanengine_mac_p.h" -#endif - -#include -#include -#include - -QTM_BEGIN_NAMESPACE - -void QNetworkConfigurationManagerPrivate::registerPlatformCapabilities() -{ - capFlags = QNetworkConfigurationManager::ForcedRoaming; -} - -void QNetworkConfigurationManagerPrivate::configurationAdded(QNetworkConfigurationPrivate *cpPriv, QNetworkSessionEngine *engine) -{ - QExplicitlySharedDataPointer ptr(new QNetworkConfigurationPrivate); - - ptr.data()->isValid = cpPriv->isValid; - ptr.data()->name = cpPriv->name; - ptr.data()->id = cpPriv->id; - ptr.data()->state = cpPriv->state; - ptr.data()->type = cpPriv->type; - ptr.data()->roamingSupported = cpPriv->roamingSupported; - ptr.data()->purpose = cpPriv->purpose; - ptr.data()->internet = cpPriv->internet; - ptr.data()->bearer = cpPriv->bearer; - - accessPointConfigurations.insert(cpPriv->id, ptr); - configurationEngine.insert(cpPriv->id, engine); - - if (!firstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - emit configurationAdded(item); - } - - if (ptr.data()->state == QNetworkConfiguration::Active) { - ++onlineConfigurations; - if (!firstUpdate && onlineConfigurations == 1) - emit onlineStateChanged(true); - } -} - -void QNetworkConfigurationManagerPrivate::configurationRemoved(const QString &id) -{ - if (!accessPointConfigurations.contains(id)) - return; - - QExplicitlySharedDataPointer ptr = - accessPointConfigurations.take(id); - - configurationEngine.remove(id); - - ptr.data()->isValid = false; - - if (!firstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - emit configurationRemoved(item); - } - - if (ptr.data()->state == QNetworkConfiguration::Active) { - --onlineConfigurations; - if (!firstUpdate && onlineConfigurations == 0) - emit onlineStateChanged(false); - } -} - -void QNetworkConfigurationManagerPrivate::configurationChanged(QNetworkConfigurationPrivate *cpPriv) -{ - if (!accessPointConfigurations.contains(cpPriv->id)) - return; - - QExplicitlySharedDataPointer ptr = - accessPointConfigurations.value(cpPriv->id); - - if (ptr.data()->isValid != cpPriv->isValid || - ptr.data()->name != cpPriv->name || - ptr.data()->id != cpPriv->id || - ptr.data()->state != cpPriv->state || - ptr.data()->type != cpPriv->type || - ptr.data()->roamingSupported != cpPriv->roamingSupported || - ptr.data()->purpose != cpPriv->purpose || - ptr.data()->bearer != cpPriv->bearer || - ptr.data()->internet != cpPriv->internet) { - - const QNetworkConfiguration::StateFlags oldState = ptr.data()->state; - - ptr.data()->isValid = cpPriv->isValid; - ptr.data()->name = cpPriv->name; - ptr.data()->id = cpPriv->id; - ptr.data()->state = cpPriv->state; - ptr.data()->type = cpPriv->type; - ptr.data()->roamingSupported = cpPriv->roamingSupported; - ptr.data()->purpose = cpPriv->purpose; - ptr.data()->internet = cpPriv->internet; - ptr.data()->bearer = cpPriv->bearer; - - if (!firstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - emit configurationChanged(item); - } - - if (ptr.data()->state == QNetworkConfiguration::Active && oldState != ptr.data()->state) { - // configuration went online - ++onlineConfigurations; - if (!firstUpdate && onlineConfigurations == 1) - emit onlineStateChanged(true); - } else if (ptr.data()->state != QNetworkConfiguration::Active && oldState == QNetworkConfiguration::Active) { - // configuration went offline - --onlineConfigurations; - if (!firstUpdate && onlineConfigurations == 0) - emit onlineStateChanged(false); - } - } -} - -void QNetworkConfigurationManagerPrivate::updateInternetServiceConfiguration() -{ - if (!snapConfigurations.contains(QLatin1String("Internet Service Network"))) { - QNetworkConfigurationPrivate *serviceNetwork = new QNetworkConfigurationPrivate; - serviceNetwork->name = tr("Internet"); - serviceNetwork->isValid = true; - serviceNetwork->id = QLatin1String("Internet Service Network"); - serviceNetwork->state = QNetworkConfiguration::Defined; - serviceNetwork->type = QNetworkConfiguration::ServiceNetwork; - - QExplicitlySharedDataPointer ptr(serviceNetwork); - - snapConfigurations.insert(serviceNetwork->id, ptr); - - if (!firstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - emit configurationAdded(item); - } - } - - QExplicitlySharedDataPointer ptr = - snapConfigurations.value(QLatin1String("Internet Service Network")); - - QList > serviceNetworkMembers; - - QHash >::const_iterator i = - accessPointConfigurations.constBegin(); - - QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Defined; - while (i != accessPointConfigurations.constEnd()) { - QExplicitlySharedDataPointer child = i.value(); - - if (child.data()->internet && ((child.data()->state & QNetworkConfiguration::Defined) - == QNetworkConfiguration::Defined)) { - serviceNetworkMembers.append(child); - - state |= child.data()->state; - } - - ++i; - } - - - if (ptr.data()->state != state || ptr.data()->serviceNetworkMembers != serviceNetworkMembers) { - ptr.data()->state = state; - ptr.data()->serviceNetworkMembers = serviceNetworkMembers; - - QNetworkConfiguration item; - item.d = ptr; - emit configurationChanged(item); - } -} - -void QNetworkConfigurationManagerPrivate::updateConfigurations() -{ - if (firstUpdate) { - updateState = NotUpdating; - onlineConfigurations = 0; - -#if defined (Q_OS_DARWIN) - coreWifi = QCoreWlanEngine::instance(); - if (coreWifi) { - connect(coreWifi, SIGNAL(configurationsChanged()), - this, SLOT(updateConfigurations())); - } -#else -#if defined(BACKEND_NM) - nmWifi = QNmWifiEngine::instance(); - if (nmWifi) { - connect(nmWifi, SIGNAL(configurationsChanged()), - this, SLOT(updateConfigurations())); - } else { -#endif - generic = QGenericEngine::instance(); - if (generic) { - connect(generic, SIGNAL(configurationsChanged()), - this, SLOT(updateConfigurations())); - } -#if defined(BACKEND_NM) - } -#endif -#endif - -#ifdef Q_OS_WIN - nla = QNlaEngine::instance(); - if (nla) { - connect(nla, SIGNAL(configurationsChanged()), - this, SLOT(updateConfigurations())); - } -#endif - -#ifdef Q_OS_WIN32 - nativeWifi = QNativeWifiEngine::instance(); - if (nativeWifi) { - connect(nativeWifi, SIGNAL(configurationsChanged()), - this, SLOT(updateConfigurations())); - - capFlags |= QNetworkConfigurationManager::CanStartAndStopInterfaces; - } -#endif - } - - QNetworkSessionEngine *engine = qobject_cast(sender()); - if (updateState & Updating && engine) { -#if defined (Q_OS_DARWIN) - if (engine == coreWifi) - updateState &= ~CoreWifiUpdating; -#else -#if defined(BACKEND_NM) - if (engine == nmWifi) - updateState &= ~NmUpdating; - else if (engine == generic) - updateState &= ~GenericUpdating; -#else - if (engine == generic) - updateState &= ~GenericUpdating; -#endif -#endif - -#ifdef Q_OS_WIN - else if (engine == nla) - updateState &= ~NlaUpdating; -#ifdef Q_OS_WIN32 - else if (engine == nativeWifi) - updateState &= ~NativeWifiUpdating; -#endif -#endif - } - QList engines; - if (firstUpdate) { -#if defined (Q_OS_DARWIN) - if (coreWifi) - engines << coreWifi; -#else -#if defined(BACKEND_NM) - if (nmWifi) - engines << nmWifi; - else if (generic) - engines << generic; -#else - if (generic) - engines << generic; -#endif -#endif - -#ifdef Q_OS_WIN - if (nla) - engines << nla; -#ifdef Q_OS_WIN32 - if (nativeWifi) - engines << nativeWifi; -#endif -#endif - } else if (engine) { - engines << engine; - } - - while (!engines.isEmpty()) { - engine = engines.takeFirst(); - - bool ok; - QList foundConfigurations = engine->getConfigurations(&ok); - - // Find removed configurations. - QList removedIdentifiers = configurationEngine.keys(); - for (int i = 0; i < foundConfigurations.count(); ++i) - removedIdentifiers.removeOne(foundConfigurations.at(i)->id); - - // Update or add configurations. - while (!foundConfigurations.isEmpty()) { - QNetworkConfigurationPrivate *cpPriv = foundConfigurations.takeFirst(); - - if (accessPointConfigurations.contains(cpPriv->id)) - configurationChanged(cpPriv); - else - configurationAdded(cpPriv, engine); - - delete cpPriv; - } - - // Remove configurations. - while (!removedIdentifiers.isEmpty()) { - const QString id = removedIdentifiers.takeFirst(); - - if (configurationEngine.value(id) == engine) - configurationRemoved(id); - } - } - - updateInternetServiceConfiguration(); - - if (updateState == Updating) { - updateState = NotUpdating; - emit configurationUpdateComplete(); - } - - if (firstUpdate) - firstUpdate = false; -} - -/*! - Returns the first active configuration found, if one exists; otherwise returns the first - discovered configuration found, if one exists; otherwise returns an empty configuration. - - \internal -*/ -QNetworkConfiguration QNetworkConfigurationManagerPrivate::defaultConfiguration() -{ - QExplicitlySharedDataPointer firstActive; - QExplicitlySharedDataPointer firstDiscovered; - - QHash >::const_iterator i = - accessPointConfigurations.constBegin(); - while (i != accessPointConfigurations.constEnd()) { - QNetworkConfigurationPrivate *priv = i.value().data(); - - if (!firstActive && priv->isValid && - (priv->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) - firstActive = i.value(); - if (!firstDiscovered && priv->isValid && - (priv->state & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) - firstDiscovered = i.value(); - - ++i; - } - - QNetworkConfiguration item; - - if (firstActive) - item.d = firstActive; - else if (firstDiscovered) - item.d = firstDiscovered; - - return item; -} - -void QNetworkConfigurationManagerPrivate::performAsyncConfigurationUpdate() -{ - updateState = Updating; -#if defined (Q_OS_DARWIN) - if (coreWifi) { - updateState |= CoreWifiUpdating; - coreWifi->requestUpdate(); - } -#else -#if defined(BACKEND_NM) - if (nmWifi) { - updateState |= NmUpdating; - nmWifi->requestUpdate(); - } else if (generic) { - updateState |= GenericUpdating; - generic->requestUpdate(); - } -#else - if (generic) { - updateState |= GenericUpdating; - generic->requestUpdate(); - } -#endif -#endif -#ifdef Q_OS_WIN - if (nla) { - updateState |= NlaUpdating; - nla->requestUpdate(); - } -#endif - -#ifdef Q_OS_WIN32 - if (nativeWifi) { - updateState |= NativeWifiUpdating; - nativeWifi->requestUpdate(); - } -#endif -} - -#include "moc_qnetworkconfigmanager_p.cpp" - -QTM_END_NAMESPACE - diff --git a/src/bearer/qnetworkconfigmanager_p.h b/src/bearer/qnetworkconfigmanager_p.h index be726d4..6f992eb 100644 --- a/src/bearer/qnetworkconfigmanager_p.h +++ b/src/bearer/qnetworkconfigmanager_p.h @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#ifndef QNETWORKCONFIGURATIONMANAGERPRIVATE_H -#define QNETWORKCONFIGURATIONMANAGERPRIVATE_H +#ifndef QTM_NETWORKCONFIGURATIONMANAGERPRIVATE_H +#define QTM_NETWORKCONFIGURATIONMANAGERPRIVATE_H // // W A R N I N G @@ -54,125 +54,31 @@ // #include "qnetworkconfigmanager.h" -#include "qnetworkconfiguration_p.h" +#include "qnetworkconfiguration.h" +#include "qnetworkconfigmanageradaptor_p.h" -#include -#include +#include QTM_BEGIN_NAMESPACE -#ifdef BEARER_ENGINE -class QNetworkSessionEngine; -class QGenericEngine; -class QNlaEngine; -class QNativeWifiEngine; -class QNmWifiEngine; -class QCoreWlanEngine; -#endif - - -class QNetworkConfigurationManagerPrivate : public QObject +class QNetworkConfigurationManagerPrivate : public QNetworkConfigurationManagerAdaptor { Q_OBJECT public: - QNetworkConfigurationManagerPrivate() - : QObject(0), capFlags(0), firstUpdate(true) - { - registerPlatformCapabilities(); - updateConfigurations(); - } - - virtual ~QNetworkConfigurationManagerPrivate() - { - QList configIdents = snapConfigurations.keys(); - foreach(const QString oldIface, configIdents) { - QExplicitlySharedDataPointer priv = snapConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - - configIdents = accessPointConfigurations.keys(); - foreach(const QString oldIface, configIdents) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - } - - QNetworkConfiguration defaultConfiguration(); - - QNetworkConfigurationManager::Capabilities capFlags; - void registerPlatformCapabilities(); - - void performAsyncConfigurationUpdate(); - - //this table contains an up to date list of all configs at any time. - //it must be updated if configurations change, are added/removed or - //the members of ServiceNetworks change - QHash > accessPointConfigurations; - QHash > snapConfigurations; - QHash > userChoiceConfigurations; -#ifdef BEARER_ENGINE - QHash configurationEngine; -#endif - bool firstUpdate; - -public slots: - void updateConfigurations(); + QNetworkConfigurationManagerPrivate(); + QT_PREPEND_NAMESPACE(QNetworkConfigurationManager) impl; Q_SIGNALS: void configurationAdded(const QNetworkConfiguration& config); void configurationRemoved(const QNetworkConfiguration& config); - void configurationUpdateComplete(); void configurationChanged(const QNetworkConfiguration& config); - void onlineStateChanged(bool isOnline); - -private: -#ifdef BEARER_ENGINE - void updateInternetServiceConfiguration(); - - void abort(); -#endif - -#ifdef BEARER_ENGINE - QGenericEngine *generic; -#ifdef Q_OS_WIN - QNlaEngine *nla; -#ifndef Q_OS_WINCE - QNativeWifiEngine *nativeWifi; -#endif -#endif -#ifdef BACKEND_NM - QNmWifiEngine *nmWifi; -#endif -#ifdef Q_OS_DARWIN - QCoreWlanEngine *coreWifi; -#endif - - uint onlineConfigurations; - - enum EngineUpdate { - NotUpdating = 0x00, - Updating = 0x01, - GenericUpdating = 0x02, - NlaUpdating = 0x04, - NativeWifiUpdating = 0x08, - NmUpdating = 0x20, - CoreWifiUpdating = 0x40, - }; - Q_DECLARE_FLAGS(EngineUpdateState, EngineUpdate) - - EngineUpdateState updateState; -#endif -private Q_SLOTS: -#ifdef BEARER_ENGINE - void configurationAdded(QNetworkConfigurationPrivate *cpPriv, QNetworkSessionEngine *engine); - void configurationRemoved(const QString &id); - void configurationChanged(QNetworkConfigurationPrivate *cpPriv); -#endif +protected: + void _q_configurationAdded(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config); + void _q_configurationRemoved(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config); + void _q_configurationChanged(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config); }; QTM_END_NAMESPACE -#endif //QNETWORKCONFIGURATIONMANAGERPRIVATE_H +#endif //QTM_NETWORKCONFIGURATIONMANAGERPRIVATE_H diff --git a/src/bearer/qnetworkconfigmanager_s60_p.cpp b/src/bearer/qnetworkconfigmanager_s60_p.cpp deleted file mode 100644 index be89786..0000000 --- a/src/bearer/qnetworkconfigmanager_s60_p.cpp +++ /dev/null @@ -1,1273 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnetworkconfigmanager_s60_p.h" - -#include -#include -#include -#include -#include -#include // For randgen seeding -#include // For randgen seeding - - -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG -#include -#endif - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - #include - #include - #include - #include - #include - #include -#else - #include - #include - #include -#endif - -QTM_BEGIN_NAMESPACE - -static const int KUserChoiceIAPId = 0; - -QNetworkConfigurationManagerPrivate::QNetworkConfigurationManagerPrivate() - : QObject(0), CActive(CActive::EPriorityHigh), capFlags(0), - iFirstUpdate(true), iInitOk(true), iUpdatePending(false), - iTimeToWait(0) -{ - CActiveScheduler::Add(this); - - // Seed the randomgenerator - qsrand(QTime(0,0,0).secsTo(QTime::currentTime()) + QCoreApplication::applicationPid()); - - registerPlatformCapabilities(); - TRAPD(error, ipCommsDB = CCommsDatabase::NewL(EDatabaseTypeIAP)); - if (error != KErrNone) { - iInitOk = false; - return; - } - - TRAP_IGNORE(iConnectionMonitor.ConnectL()); -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - TRAP_IGNORE(iConnectionMonitor.SetUintAttribute(EBearerIdAll, 0, KBearerGroupThreshold, 1)); -#endif - TRAP_IGNORE(iConnectionMonitor.NotifyEventL(*this)); - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - TRAP(error, iCmManager.OpenL()); - if (error != KErrNone) { - iInitOk = false; - return; - } -#endif - - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - cpPriv->name = "UserChoice"; - cpPriv->bearer = QNetworkConfigurationPrivate::BearerUnknown; - cpPriv->state = QNetworkConfiguration::Discovered; - cpPriv->isValid = true; - cpPriv->id = QString::number(qHash(KUserChoiceIAPId)); - cpPriv->numericId = KUserChoiceIAPId; - cpPriv->connectionId = 0; - cpPriv->type = QNetworkConfiguration::UserChoice; - cpPriv->purpose = QNetworkConfiguration::UnknownPurpose; - cpPriv->roamingSupported = false; - cpPriv->manager = this; - QExplicitlySharedDataPointer ptr(cpPriv); - userChoiceConfigurations.insert(cpPriv->id, ptr); - updateConfigurations(); - updateStatesToSnaps(); - updateAvailableAccessPoints(); // On first time updates synchronously (without WLAN scans) - // Start monitoring IAP and/or SNAP changes in Symbian CommsDB - startCommsDatabaseNotifications(); - iFirstUpdate = false; -} - -QNetworkConfigurationManagerPrivate::~QNetworkConfigurationManagerPrivate() -{ - Cancel(); - - foreach (const QString &oldIface, snapConfigurations.keys()) { - QExplicitlySharedDataPointer priv = snapConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - - foreach (const QString &oldIface, accessPointConfigurations.keys()) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - } - - foreach (const QString &oldIface, userChoiceConfigurations.keys()) { - QExplicitlySharedDataPointer priv = userChoiceConfigurations.take(oldIface); - priv->isValid = false; - priv->id.clear(); - priv->manager = 0; - } - - delete ipAccessPointsAvailabilityScanner; - iConnectionMonitor.CancelNotifications(); - iConnectionMonitor.Close(); - - // CCommsDatabase destructor and RCmManager.Close() use cleanup stack. Since QNetworkConfigurationManager - // is a global static, but the time we are here, E32Main() has been exited already and - // the thread's default cleanup stack has been deleted. Without this line, a - // 'E32USER-CBase 69' -panic will occur. - CTrapCleanup* cleanup = CTrapCleanup::New(); -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - iCmManager.Close(); -#endif - delete ipCommsDB; - delete cleanup; -} - -void QNetworkConfigurationManagerPrivate::delayedConfigurationUpdate() -{ - if (iUpdatePending) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug("QNCM delayed configuration update (ECommit or ERecover occurred)."); -#endif - TRAPD(error, updateConfigurationsL()); - if (error == KErrNone) { - updateStatesToSnaps(); - } - iUpdatePending = false; - // Start monitoring again. - if (!IsActive()) { - SetActive(); - // Start waiting for new notification - ipCommsDB->RequestNotification(iStatus); - } - } -} - -void QNetworkConfigurationManagerPrivate::registerPlatformCapabilities() -{ - capFlags |= QNetworkConfigurationManager::CanStartAndStopInterfaces; - capFlags |= QNetworkConfigurationManager::DirectConnectionRouting; - capFlags |= QNetworkConfigurationManager::SystemSessionSupport; -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - capFlags |= QNetworkConfigurationManager::ApplicationLevelRoaming; - capFlags |= QNetworkConfigurationManager::ForcedRoaming; -#endif - capFlags |= QNetworkConfigurationManager::DataStatistics; - capFlags |= QNetworkConfigurationManager::NetworkSessionRequired; -} - -void QNetworkConfigurationManagerPrivate::performAsyncConfigurationUpdate() -{ - if (!iInitOk || iUpdateGoingOn) { - return; - } - iUpdateGoingOn = true; - - stopCommsDatabaseNotifications(); - updateConfigurations(); // Synchronous call - updateAvailableAccessPoints(); // Asynchronous call -} - -void QNetworkConfigurationManagerPrivate::updateConfigurations() -{ - if (!iInitOk) { - return; - } - TRAP_IGNORE(updateConfigurationsL()); -} - -void QNetworkConfigurationManagerPrivate::updateConfigurationsL() -{ - QList knownConfigs = accessPointConfigurations.keys(); - QList knownSnapConfigs = snapConfigurations.keys(); - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - // S60 version is >= Series60 3rd Edition Feature Pack 2 - TInt error = KErrNone; - - // Loop through all IAPs - RArray connectionMethods; // IAPs - CleanupClosePushL(connectionMethods); - iCmManager.ConnectionMethodL(connectionMethods); - for(int i = 0; i < connectionMethods.Count(); i++) { - RCmConnectionMethod connectionMethod = iCmManager.ConnectionMethodL(connectionMethods[i]); - CleanupClosePushL(connectionMethod); - TUint32 iapId = connectionMethod.GetIntAttributeL(CMManager::ECmIapId); - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId)); - if (accessPointConfigurations.contains(ident)) { - knownConfigs.removeOne(ident); - } else { - QNetworkConfigurationPrivate* cpPriv = NULL; - TRAP(error, cpPriv = configFromConnectionMethodL(connectionMethod)); - if (error == KErrNone) { - QExplicitlySharedDataPointer ptr(cpPriv); - accessPointConfigurations.insert(cpPriv->id, ptr); - if (!iFirstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - // Emit configuration added. Connected slots may throw execptions - // which propagate here --> must be converted to leaves (standard - // std::exception would cause any TRAP trapping this function to terminate - // program). - QT_TRYCATCH_LEAVING(updateActiveAccessPoints()); - updateStatesToSnaps(); - QT_TRYCATCH_LEAVING(emit configurationAdded(item)); - } - } - } - CleanupStack::PopAndDestroy(&connectionMethod); - } - CleanupStack::PopAndDestroy(&connectionMethods); - - // Loop through all SNAPs - RArray destinations; - CleanupClosePushL(destinations); - iCmManager.AllDestinationsL(destinations); - for(int i = 0; i < destinations.Count(); i++) { - RCmDestination destination; - - // Some destinatsions require ReadDeviceData -capability (MMS/WAP) - // The below function will leave in these cases. Don't. Proceed to - // next destination (if any). - TRAPD(error, destination = iCmManager.DestinationL(destinations[i])); - if (error == KErrPermissionDenied) { - continue; - } else { - User::LeaveIfError(error); - } - - CleanupClosePushL(destination); - QString ident = QT_BEARERMGMT_CONFIGURATION_SNAP_PREFIX+QString::number(qHash(destination.Id())); - if (snapConfigurations.contains(ident)) { - knownSnapConfigs.removeOne(ident); - } else { - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - HBufC *pName = destination.NameLC(); - QT_TRYCATCH_LEAVING(cpPriv->name = QString::fromUtf16(pName->Ptr(),pName->Length())); - CleanupStack::PopAndDestroy(pName); - pName = NULL; - cpPriv->isValid = true; - cpPriv->id = ident; - cpPriv->numericId = destination.Id(); - cpPriv->connectionId = 0; - cpPriv->state = QNetworkConfiguration::Defined; - cpPriv->type = QNetworkConfiguration::ServiceNetwork; - cpPriv->purpose = QNetworkConfiguration::UnknownPurpose; - cpPriv->roamingSupported = false; - cpPriv->manager = this; - - QExplicitlySharedDataPointer ptr(cpPriv); - snapConfigurations.insert(ident, ptr); - if (!iFirstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - QT_TRYCATCH_LEAVING(updateActiveAccessPoints()); - updateStatesToSnaps(); - QT_TRYCATCH_LEAVING(emit configurationAdded(item)); - } - } - QExplicitlySharedDataPointer privSNAP = snapConfigurations.value(ident); - - for (int j=0; j < destination.ConnectionMethodCount(); j++) { - RCmConnectionMethod connectionMethod = destination.ConnectionMethodL(j); - CleanupClosePushL(connectionMethod); - - TUint32 iapId = connectionMethod.GetIntAttributeL(CMManager::ECmIapId); - QString iface = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId)); - // Check that IAP can be found from accessPointConfigurations list - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iface); - if (priv.data() == 0) { - QNetworkConfigurationPrivate* cpPriv = NULL; - TRAP(error, cpPriv = configFromConnectionMethodL(connectionMethod)); - if (error == KErrNone) { - QExplicitlySharedDataPointer ptr(cpPriv); - ptr.data()->serviceNetworkPtr = privSNAP; - accessPointConfigurations.insert(cpPriv->id, ptr); - privSNAP->serviceNetworkMembers.append(ptr); - if (!iFirstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - QT_TRYCATCH_LEAVING(updateActiveAccessPoints()); - updateStatesToSnaps(); - QT_TRYCATCH_LEAVING(emit configurationAdded(item)); - } - } - } else { - knownConfigs.removeOne(iface); - // Check that IAP can be found from related SNAP's configuration list - bool iapFound = false; - for (int i=0; iserviceNetworkMembers.count(); i++) { - if (privSNAP->serviceNetworkMembers[i]->numericId == iapId) { - iapFound = true; - break; - } - } - if (!iapFound) { - priv.data()->serviceNetworkPtr = privSNAP; - privSNAP->serviceNetworkMembers.append(priv); - } - } - CleanupStack::PopAndDestroy(&connectionMethod); - } - if (privSNAP->serviceNetworkMembers.count() > 1) { - // Roaming is supported only if SNAP contains more than one IAP - privSNAP->roamingSupported = true; - } - CleanupStack::PopAndDestroy(&destination); - } - CleanupStack::PopAndDestroy(&destinations); - -#else - // S60 version is < Series60 3rd Edition Feature Pack 2 - CCommsDbTableView* pDbTView = ipCommsDB->OpenTableLC(TPtrC(IAP)); - - // Loop through all IAPs - TUint32 apId = 0; - TInt retVal = pDbTView->GotoFirstRecord(); - while (retVal == KErrNone) { - pDbTView->ReadUintL(TPtrC(COMMDB_ID), apId); - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); - if (accessPointConfigurations.contains(ident)) { - knownConfigs.removeOne(ident); - } else { - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - if (readNetworkConfigurationValuesFromCommsDb(apId, cpPriv)) { - QExplicitlySharedDataPointer ptr(cpPriv); - accessPointConfigurations.insert(ident, ptr); - if (!iFirstUpdate) { - QNetworkConfiguration item; - item.d = ptr; - QT_TRYCATCH_LEAVING(updateActiveAccessPoints()); - updateStatesToSnaps(); - QT_TRYCATCH_LEAVING(emit configurationAdded(item)); - } - } else { - delete cpPriv; - } - } - retVal = pDbTView->GotoNextRecord(); - } - CleanupStack::PopAndDestroy(pDbTView); -#endif - - QT_TRYCATCH_LEAVING(updateActiveAccessPoints()); - - foreach (const QString &oldIface, knownConfigs) { - //remove non existing IAP - QExplicitlySharedDataPointer priv = accessPointConfigurations.take(oldIface); - priv->isValid = false; - if (!iFirstUpdate) { - QNetworkConfiguration item; - item.d = priv; - QT_TRYCATCH_LEAVING(emit configurationRemoved(item)); - } - // Remove non existing IAP from SNAPs - foreach (const QString &iface, snapConfigurations.keys()) { - QExplicitlySharedDataPointer priv2 = snapConfigurations.value(iface); - // => Check if one of the IAPs of the SNAP is active - for (int i=0; iserviceNetworkMembers.count(); i++) { - if (priv2->serviceNetworkMembers[i]->numericId == priv->numericId) { - priv2->serviceNetworkMembers.removeAt(i); - break; - } - } - } - } - foreach (const QString &oldIface, knownSnapConfigs) { - //remove non existing SNAPs - QExplicitlySharedDataPointer priv = snapConfigurations.take(oldIface); - priv->isValid = false; - if (!iFirstUpdate) { - QNetworkConfiguration item; - item.d = priv; - QT_TRYCATCH_LEAVING(emit configurationRemoved(item)); - } - } -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - updateStatesToSnaps(); -#endif -} - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE -QNetworkConfigurationPrivate* QNetworkConfigurationManagerPrivate::configFromConnectionMethodL( - RCmConnectionMethod& connectionMethod) -{ - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - TUint32 iapId = connectionMethod.GetIntAttributeL(CMManager::ECmIapId); - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId)); - - HBufC *pName = connectionMethod.GetStringAttributeL(CMManager::ECmName); - CleanupStack::PushL(pName); - QT_TRYCATCH_LEAVING(cpPriv->name = QString::fromUtf16(pName->Ptr(),pName->Length())); - CleanupStack::PopAndDestroy(pName); - pName = NULL; - - TUint32 bearerId = connectionMethod.GetIntAttributeL(CMManager::ECmCommsDBBearerType); - switch (bearerId) { - case KCommDbBearerCSD: - cpPriv->bearer = QNetworkConfigurationPrivate::Bearer2G; - break; - case KCommDbBearerWcdma: - cpPriv->bearer = QNetworkConfigurationPrivate::BearerWCDMA; - break; - case KCommDbBearerLAN: - cpPriv->bearer = QNetworkConfigurationPrivate::BearerEthernet; - break; - case KCommDbBearerVirtual: - cpPriv->bearer = QNetworkConfigurationPrivate::BearerUnknown; - break; - case KCommDbBearerPAN: - cpPriv->bearer = QNetworkConfigurationPrivate::BearerUnknown; - break; - case KCommDbBearerWLAN: - cpPriv->bearer = QNetworkConfigurationPrivate::BearerWLAN; - break; - default: - cpPriv->bearer = QNetworkConfigurationPrivate::BearerUnknown; - break; - } - - TInt error = KErrNone; - TUint32 bearerType = connectionMethod.GetIntAttributeL(CMManager::ECmBearerType); - switch (bearerType) { - case KUidPacketDataBearerType: - // "Packet data" Bearer => Mapping is done using "Access point name" - TRAP(error, pName = connectionMethod.GetStringAttributeL(CMManager::EPacketDataAPName)); - break; - case KUidWlanBearerType: - // "Wireless LAN" Bearer => Mapping is done using "WLAN network name" = SSID - TRAP(error, pName = connectionMethod.GetStringAttributeL(CMManager::EWlanSSID)); - break; - } - if (!pName) { - // "Data call" Bearer or "High Speed (GSM)" Bearer => Mapping is done using "Dial-up number" - TRAP(error, pName = connectionMethod.GetStringAttributeL(CMManager::EDialDefaultTelNum)); - } - - if (error == KErrNone && pName) { - CleanupStack::PushL(pName); - QT_TRYCATCH_LEAVING(cpPriv->mappingName = QString::fromUtf16(pName->Ptr(),pName->Length())); - CleanupStack::PopAndDestroy(pName); - pName = NULL; - } - - cpPriv->state = QNetworkConfiguration::Defined; - TBool isConnected = connectionMethod.GetBoolAttributeL(CMManager::ECmConnected); - if (isConnected) { - cpPriv->state = QNetworkConfiguration::Active; - } - - cpPriv->isValid = true; - cpPriv->id = ident; - cpPriv->numericId = iapId; - cpPriv->connectionId = 0; - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - cpPriv->purpose = QNetworkConfiguration::UnknownPurpose; - cpPriv->roamingSupported = false; - cpPriv->manager = this; - return cpPriv; -} -#else -bool QNetworkConfigurationManagerPrivate::readNetworkConfigurationValuesFromCommsDb( - TUint32 aApId, QNetworkConfigurationPrivate* apNetworkConfiguration) -{ - TRAPD(error, readNetworkConfigurationValuesFromCommsDbL(aApId,apNetworkConfiguration)); - if (error != KErrNone) { - return false; - } - return true; -} - -void QNetworkConfigurationManagerPrivate::readNetworkConfigurationValuesFromCommsDbL( - TUint32 aApId, QNetworkConfigurationPrivate* apNetworkConfiguration) -{ - CApDataHandler* pDataHandler = CApDataHandler::NewLC(*ipCommsDB); - CApAccessPointItem* pAPItem = CApAccessPointItem::NewLC(); - TBuf name; - - CApUtils* pApUtils = CApUtils::NewLC(*ipCommsDB); - TUint32 apId = pApUtils->WapIdFromIapIdL(aApId); - - pDataHandler->AccessPointDataL(apId,*pAPItem); - pAPItem->ReadTextL(EApIapName, name); - if (name.Compare(_L("Easy WLAN")) == 0) { - // "Easy WLAN" won't be accepted to the Configurations list - User::Leave(KErrNotFound); - } - - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(aApId)); - - QT_TRYCATCH_LEAVING(apNetworkConfiguration->name = QString::fromUtf16(name.Ptr(),name.Length())); - apNetworkConfiguration->isValid = true; - apNetworkConfiguration->id = ident; - apNetworkConfiguration->numericId = aApId; - apNetworkConfiguration->connectionId = 0; - apNetworkConfiguration->state = (QNetworkConfiguration::Defined); - apNetworkConfiguration->type = QNetworkConfiguration::InternetAccessPoint; - apNetworkConfiguration->purpose = QNetworkConfiguration::UnknownPurpose; - apNetworkConfiguration->roamingSupported = false; - switch (pAPItem->BearerTypeL()) { - case EApBearerTypeCSD: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::Bearer2G; - break; - case EApBearerTypeGPRS: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::Bearer2G; - break; - case EApBearerTypeHSCSD: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::BearerHSPA; - break; - case EApBearerTypeCDMA: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::BearerCDMA2000; - break; - case EApBearerTypeWLAN: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::BearerWLAN; - break; - case EApBearerTypeLAN: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::BearerEthernet; - break; - case EApBearerTypeLANModem: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::BearerEthernet; - break; - default: - apNetworkConfiguration->bearer = QNetworkConfigurationPrivate::BearerUnknown; - break; - } - apNetworkConfiguration->manager = this; - - CleanupStack::PopAndDestroy(pApUtils); - CleanupStack::PopAndDestroy(pAPItem); - CleanupStack::PopAndDestroy(pDataHandler); -} -#endif - -QNetworkConfiguration QNetworkConfigurationManagerPrivate::defaultConfiguration() -{ - QNetworkConfiguration config; - - if (iInitOk) { - stopCommsDatabaseNotifications(); - TRAP_IGNORE(config = defaultConfigurationL()); - startCommsDatabaseNotifications(); - } - return config; -} - -QNetworkConfiguration QNetworkConfigurationManagerPrivate::defaultConfigurationL() -{ - QNetworkConfiguration item; - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - // Check Default Connection (SNAP or IAP) - TCmDefConnValue defaultConnectionValue; - iCmManager.ReadDefConnL(defaultConnectionValue); - if (defaultConnectionValue.iType == ECmDefConnDestination) { - QString iface = QT_BEARERMGMT_CONFIGURATION_SNAP_PREFIX+QString::number(qHash(defaultConnectionValue.iId)); - QExplicitlySharedDataPointer priv = snapConfigurations.value(iface); - if (priv.data() != 0) { - item.d = priv; - } - } else if (defaultConnectionValue.iType == ECmDefConnConnectionMethod) { - QString iface = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(defaultConnectionValue.iId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iface); - if (priv.data() != 0) { - item.d = priv; - } - } -#endif - - if (!item.isValid()) { - QString iface = QString::number(qHash(KUserChoiceIAPId)); - QExplicitlySharedDataPointer priv = userChoiceConfigurations.value(iface); - if (priv.data() != 0) { - item.d = priv; - } - } - - return item; -} - -void QNetworkConfigurationManagerPrivate::updateActiveAccessPoints() -{ - bool online = false; - QList inactiveConfigs = accessPointConfigurations.keys(); - - TRequestStatus status; - TUint connectionCount; - iConnectionMonitor.GetConnectionCount(connectionCount, status); - User::WaitForRequest(status); - - // Go through all connections and set state of related IAPs to Active. - // Status needs to be checked carefully, because ConnMon lists also e.g. - // WLAN connections that are being currently tried --> we don't want to - // state these as active. - TUint connectionId; - TUint subConnectionCount; - TUint apId; - TInt connectionStatus; - if (status.Int() == KErrNone) { - for (TUint i = 1; i <= connectionCount; i++) { - iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount); - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status); - User::WaitForRequest(status); - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - if (!priv.data()) { - // If IAP was not found, check if the update was about EasyWLAN - priv = configurationFromEasyWlan(apId, connectionId); - // Change the ident correspondingly - if (priv.data()) { - ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(priv.data()->numericId)); - } - } -#endif - if (priv.data()) { - iConnectionMonitor.GetIntAttribute(connectionId, subConnectionCount, KConnectionStatus, connectionStatus, status); - User::WaitForRequest(status); - - if (connectionStatus == KLinkLayerOpen) { - online = true; - inactiveConfigs.removeOne(ident); - priv.data()->connectionId = connectionId; - // Configuration is Active - changeConfigurationStateTo(priv, QNetworkConfiguration::Active); - } - } - } - } - - // Make sure that state of rest of the IAPs won't be Active - foreach (const QString &iface, inactiveConfigs) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iface); - if (priv.data()) { - // Configuration is either Defined or Discovered - changeConfigurationStateAtMaxTo(priv, QNetworkConfiguration::Discovered); - } - } - - if (iOnline != online) { - iOnline = online; - emit this->onlineStateChanged(online); - } -} - -void QNetworkConfigurationManagerPrivate::updateAvailableAccessPoints() -{ - if (!ipAccessPointsAvailabilityScanner) { - ipAccessPointsAvailabilityScanner = new AccessPointsAvailabilityScanner(*this, iConnectionMonitor); - } - if (ipAccessPointsAvailabilityScanner) { - // Scanning may take a while because WLAN scanning will be done (if device supports WLAN). - ipAccessPointsAvailabilityScanner->StartScanning(); - } -} - -void QNetworkConfigurationManagerPrivate::accessPointScanningReady(TBool scanSuccessful, TConnMonIapInfo iapInfo) -{ - iUpdateGoingOn = false; - if (scanSuccessful) { - QList unavailableConfigs = accessPointConfigurations.keys(); - - // Set state of returned IAPs to Discovered - // if state is not already Active - for(TUint i=0; i priv = accessPointConfigurations.value(ident); - if (priv.data()) { - unavailableConfigs.removeOne(ident); - if (priv.data()->state < QNetworkConfiguration::Active) { - // Configuration is either Discovered or Active - changeConfigurationStateAtMinTo(priv, QNetworkConfiguration::Discovered); - } - } - } - - // Make sure that state of rest of the IAPs won't be Active - foreach (const QString &iface, unavailableConfigs) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iface); - if (priv.data()) { - // Configuration is Defined - changeConfigurationStateAtMaxTo(priv, QNetworkConfiguration::Discovered); - } - } - } - - updateStatesToSnaps(); - - if (!iFirstUpdate) { - startCommsDatabaseNotifications(); - emit this->configurationUpdateComplete(); - } -} - -void QNetworkConfigurationManagerPrivate::updateStatesToSnaps() -{ - // Go through SNAPs and set correct state to SNAPs - foreach (const QString &iface, snapConfigurations.keys()) { - bool discovered = false; - bool active = false; - QExplicitlySharedDataPointer priv = snapConfigurations.value(iface); - // => Check if one of the IAPs of the SNAP is discovered or active - // => If one of IAPs is active, also SNAP is active - // => If one of IAPs is discovered but none of the IAPs is active, SNAP is discovered - for (int i=0; iserviceNetworkMembers.count(); i++) { - QExplicitlySharedDataPointer priv2 = priv->serviceNetworkMembers[i]; - if ((priv->serviceNetworkMembers[i]->state & QNetworkConfiguration::Active) - == QNetworkConfiguration::Active) { - active = true; - break; - } else if ((priv->serviceNetworkMembers[i]->state & QNetworkConfiguration::Discovered) - == QNetworkConfiguration::Discovered) { - discovered = true; - } - } - if (active) { - changeConfigurationStateTo(priv, QNetworkConfiguration::Active); - } else if (discovered) { - changeConfigurationStateTo(priv, QNetworkConfiguration::Discovered); - } else { - changeConfigurationStateTo(priv, QNetworkConfiguration::Defined); - } - } -} - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE -void QNetworkConfigurationManagerPrivate::updateMobileBearerToConfigs(TConnMonBearerInfo bearerInfo) -{ - foreach (const QString &ii, accessPointConfigurations.keys()) { - QExplicitlySharedDataPointer p = - accessPointConfigurations.value(ii); - if (p->bearer >= QNetworkConfigurationPrivate::Bearer2G && - p->bearer <= QNetworkConfigurationPrivate::BearerHSPA) { - switch (bearerInfo) { - case EBearerInfoCSD: p->bearer = QNetworkConfigurationPrivate::Bearer2G; break; - case EBearerInfoWCDMA: p->bearer = QNetworkConfigurationPrivate::BearerWCDMA; break; - case EBearerInfoCDMA2000: p->bearer = QNetworkConfigurationPrivate::BearerCDMA2000; break; - case EBearerInfoGPRS: p->bearer = QNetworkConfigurationPrivate::Bearer2G; break; - case EBearerInfoHSCSD: p->bearer = QNetworkConfigurationPrivate::Bearer2G; break; - case EBearerInfoEdgeGPRS: p->bearer = QNetworkConfigurationPrivate::Bearer2G; break; - case EBearerInfoWcdmaCSD: p->bearer = QNetworkConfigurationPrivate::BearerWCDMA; break; - case EBearerInfoHSDPA: p->bearer = QNetworkConfigurationPrivate::BearerHSPA; break; - case EBearerInfoHSUPA: p->bearer = QNetworkConfigurationPrivate::BearerHSPA; break; - case EBearerInfoHSxPA: p->bearer = QNetworkConfigurationPrivate::BearerHSPA; break; - } - } - } -} -#endif - -bool QNetworkConfigurationManagerPrivate::changeConfigurationStateTo(QExplicitlySharedDataPointer& sharedData, - QNetworkConfiguration::StateFlags newState) -{ - if (newState != sharedData.data()->state) { - sharedData.data()->state = newState; - QNetworkConfiguration item; - item.d = sharedData; - if (!iFirstUpdate) { - emit configurationChanged(item); - } - return true; - } - return false; -} - -/* changeConfigurationStateAtMinTo function does not overwrite possible better - * state (e.g. Discovered state does not overwrite Active state) but - * makes sure that state is at minimum given state. -*/ -bool QNetworkConfigurationManagerPrivate::changeConfigurationStateAtMinTo(QExplicitlySharedDataPointer& sharedData, - QNetworkConfiguration::StateFlags newState) -{ - if ((newState | sharedData.data()->state) != sharedData.data()->state) { - sharedData.data()->state = (sharedData.data()->state | newState); - QNetworkConfiguration item; - item.d = sharedData; - if (!iFirstUpdate) { - emit configurationChanged(item); - } - return true; - } - return false; -} - -/* changeConfigurationStateAtMaxTo function overwrites possible better - * state (e.g. Discovered state overwrites Active state) and - * makes sure that state is at maximum given state (e.g. Discovered state - * does not overwrite Defined state). -*/ -bool QNetworkConfigurationManagerPrivate::changeConfigurationStateAtMaxTo(QExplicitlySharedDataPointer& sharedData, - QNetworkConfiguration::StateFlags newState) -{ - if ((newState & sharedData.data()->state) != sharedData.data()->state) { - sharedData.data()->state = (newState & sharedData.data()->state); - QNetworkConfiguration item; - item.d = sharedData; - if (!iFirstUpdate) { - emit configurationChanged(item); - } - return true; - } - return false; -} - -void QNetworkConfigurationManagerPrivate::startCommsDatabaseNotifications() -{ - if (!iWaitingCommsDatabaseNotifications) { - iWaitingCommsDatabaseNotifications = ETrue; - if (!IsActive()) { - SetActive(); - // Start waiting for new notification - ipCommsDB->RequestNotification(iStatus); - } - } -} - -void QNetworkConfigurationManagerPrivate::stopCommsDatabaseNotifications() -{ - if (iWaitingCommsDatabaseNotifications) { - iWaitingCommsDatabaseNotifications = EFalse; - if (!IsActive()) { - SetActive(); - // Make sure that notifier recorded events will not be returned - // as soon as the client issues the next RequestNotification() request. - ipCommsDB->RequestNotification(iStatus); - ipCommsDB->CancelRequestNotification(); - } else { - ipCommsDB->CancelRequestNotification(); - } - } -} - -void QNetworkConfigurationManagerPrivate::RunL() -{ - if (iStatus != KErrCancel) { - // By default, start relistening notifications. Stop only if interesting event occurred. - iWaitingCommsDatabaseNotifications = true; - RDbNotifier::TEvent event = STATIC_CAST(RDbNotifier::TEvent, iStatus.Int()); - switch (event) { - case RDbNotifier::ECommit: /** A transaction has been committed. */ - case RDbNotifier::ERecover: /** The database has been recovered */ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug("QNCM CommsDB event (of type RDbNotifier::TEvent) received: %d", iStatus.Int()); -#endif - // Mark that there is update pending. No need to ask more events, - // as we know we will be updating anyway when the timer expires. - if (!iUpdatePending) { - iUpdatePending = true; - iWaitingCommsDatabaseNotifications = false; - // Update after random time, so that many processes won't - // start updating simultaneously - updateConfigurationsAfterRandomTime(); - } - break; - default: - // Do nothing - break; - } - } - if (iWaitingCommsDatabaseNotifications) { - if (!IsActive()) { - SetActive(); - // Start waiting for new notification - ipCommsDB->RequestNotification(iStatus); - } - } -} - -void QNetworkConfigurationManagerPrivate::DoCancel() -{ - ipCommsDB->CancelRequestNotification(); -} - -void QNetworkConfigurationManagerPrivate::EventL(const CConnMonEventBase& aEvent) -{ - switch (aEvent.EventType()) { -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - case EConnMonBearerInfoChange: - { - CConnMonBearerInfoChange* realEvent; - realEvent = (CConnMonBearerInfoChange*) &aEvent; - TUint connectionId = realEvent->ConnectionId(); - if (connectionId == EBearerIdAll) { - //Network level event - TConnMonBearerInfo bearerInfo = (TConnMonBearerInfo)realEvent->BearerInfo(); - updateMobileBearerToConfigs(bearerInfo); - } - break; - } -#endif - case EConnMonConnectionStatusChange: - { - CConnMonConnectionStatusChange* realEvent; - realEvent = (CConnMonConnectionStatusChange*) &aEvent; - TInt connectionStatus = realEvent->ConnectionStatus(); -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNCM Connection status : " << QString::number(connectionStatus) << " , connection monitor Id : " << realEvent->ConnectionId(); -#endif - if (connectionStatus == KConfigDaemonStartingRegistration) { - TUint connectionId = realEvent->ConnectionId(); - TUint subConnectionCount = 0; - TUint apId; - TRequestStatus status; - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status); - User::WaitForRequest(status); - - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - if (!priv.data()) { - // Check if status was regarding EasyWLAN - priv = configurationFromEasyWlan(apId, connectionId); - } -#endif - if (priv.data()) { - priv.data()->connectionId = connectionId; - QT_TRYCATCH_LEAVING(emit this->configurationStateChanged(priv.data()->numericId, connectionId, QNetworkSession::Connecting)); - } - } else if (connectionStatus == KLinkLayerOpen) { - // Connection has been successfully opened - TUint connectionId = realEvent->ConnectionId(); - TUint subConnectionCount = 0; - TUint apId; - TRequestStatus status; - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status); - User::WaitForRequest(status); - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - if (!priv.data()) { - // Check for EasyWLAN - priv = configurationFromEasyWlan(apId, connectionId); - } -#endif - if (priv.data()) { - priv.data()->connectionId = connectionId; - // Configuration is Active - QT_TRYCATCH_LEAVING( - if (changeConfigurationStateTo(priv, QNetworkConfiguration::Active)) { - updateStatesToSnaps(); - } - emit this->configurationStateChanged(priv.data()->numericId, connectionId, QNetworkSession::Connected); - if (!iOnline) { - iOnline = true; - emit this->onlineStateChanged(iOnline); - } - ); - } - } else if (connectionStatus == KConfigDaemonStartingDeregistration) { - TUint connectionId = realEvent->ConnectionId(); - QExplicitlySharedDataPointer priv = dataByConnectionId(connectionId); - if (priv.data()) { - QT_TRYCATCH_LEAVING(emit this->configurationStateChanged(priv.data()->numericId, connectionId, QNetworkSession::Closing)); - } - } else if (connectionStatus == KLinkLayerClosed || - connectionStatus == KConnectionClosed) { - // Connection has been closed. Which of the above events is reported, depends on the Symbian - // platform. - TUint connectionId = realEvent->ConnectionId(); - QExplicitlySharedDataPointer priv = dataByConnectionId(connectionId); - if (priv.data()) { - // Configuration is either Defined or Discovered - QT_TRYCATCH_LEAVING( - if (changeConfigurationStateAtMaxTo(priv, QNetworkConfiguration::Discovered)) { - updateStatesToSnaps(); - } - emit this->configurationStateChanged(priv.data()->numericId, connectionId, QNetworkSession::Disconnected); - ); - } - - bool online = false; - foreach (const QString &iface, accessPointConfigurations.keys()) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iface); - if (priv.data()->state == QNetworkConfiguration::Active) { - online = true; - break; - } - } - if (iOnline != online) { - iOnline = online; - QT_TRYCATCH_LEAVING(emit this->onlineStateChanged(iOnline)); - } - } - } - break; - - case EConnMonIapAvailabilityChange: - { - CConnMonIapAvailabilityChange* realEvent; - realEvent = (CConnMonIapAvailabilityChange*) &aEvent; - TConnMonIapInfo iaps = realEvent->IapAvailability(); - QList unDiscoveredConfigs = accessPointConfigurations.keys(); - for ( TUint i = 0; i < iaps.Count(); i++ ) { - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iaps.iIap[i].iIapId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(ident); - if (priv.data()) { - // Configuration is either Discovered or Active - QT_TRYCATCH_LEAVING(changeConfigurationStateAtMinTo(priv, QNetworkConfiguration::Discovered)); - unDiscoveredConfigs.removeOne(ident); - } - } - foreach (const QString &iface, unDiscoveredConfigs) { - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(iface); - if (priv.data()) { - // Configuration is Defined - QT_TRYCATCH_LEAVING(changeConfigurationStateAtMaxTo(priv, QNetworkConfiguration::Defined)); - } - } - // Something has in IAPs, update states to SNAPs - updateStatesToSnaps(); - } - break; - - case EConnMonCreateConnection: - { - // This event is caught to keep connection monitor IDs up-to-date. - CConnMonCreateConnection* realEvent; - realEvent = (CConnMonCreateConnection*) &aEvent; - TUint subConnectionCount = 0; - TUint apId; - TUint connectionId = realEvent->ConnectionId(); - TRequestStatus status; - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status); - User::WaitForRequest(status); - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(apId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(ident); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - if (!priv.data()) { - // If IAP was not found, check if the update was about EasyWLAN - priv = configurationFromEasyWlan(apId, connectionId); - } -#endif - if (priv.data()) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNCM updating connection monitor ID : from, to, whose: " << priv.data()->connectionId << connectionId << priv->name; -#endif - priv.data()->connectionId = connectionId; - } - } - break; - default: - // For unrecognized events - break; - } -} - -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) -// Tries to derive configuration from EasyWLAN. -// First checks if the interface brought up was EasyWLAN, then derives the real SSID, -// and looks up configuration based on that one. -QExplicitlySharedDataPointer QNetworkConfigurationManagerPrivate::configurationFromEasyWlan(TUint32 apId, TUint connectionId) -{ - if (apId == iCmManager.EasyWlanIdL()) { - TRequestStatus status; - TBuf<50> easyWlanNetworkName; - iConnectionMonitor.GetStringAttribute( connectionId, 0, KNetworkName, - easyWlanNetworkName, status ); - User::WaitForRequest(status); - if (status.Int() == KErrNone) { - QString realSSID = QString::fromUtf16(easyWlanNetworkName.Ptr(), easyWlanNetworkName.Length()); - - // Browser through all items and check their name for match - QNetworkConfiguration item; - QHash >::const_iterator i = - accessPointConfigurations.constBegin(); - while (i != accessPointConfigurations.constEnd()) { - QExplicitlySharedDataPointer priv = i.value(); - if (priv.data()->name == realSSID) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNCM EasyWlan uses real SSID: " << realSSID; -#endif - return priv; - } - ++i; - } - } - } - return QExplicitlySharedDataPointer(); -} - -bool QNetworkConfigurationManagerPrivate::easyWlanTrueIapId(TUint32& trueIapId) -{ - // Check if this is easy wlan id in the first place - if (trueIapId != iCmManager.EasyWlanIdL()) { - return false; - } - // Loop through all connections that connection monitor is aware - // and check for IAPs based on easy WLAN - TRequestStatus status; - TUint connectionCount; - iConnectionMonitor.GetConnectionCount(connectionCount, status); - User::WaitForRequest(status); - TUint connectionId; - TUint subConnectionCount; - TUint apId; - if (status.Int() == KErrNone) { - for (TUint i = 1; i <= connectionCount; i++) { - iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount); - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status); - User::WaitForRequest(status); - if (apId == trueIapId) { - QExplicitlySharedDataPointer priv = - configurationFromEasyWlan(apId, connectionId); - if (priv.data()) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNCM easyWlanTrueIapId(), found true IAP ID: " << priv.data()->numericId; -#endif - trueIapId = priv.data()->numericId; - return true; - } - } - } - } - return false; -} - -#endif - -// Sessions may use this function to report configuration state changes, -// because on some Symbian platforms (especially Symbian^3) all state changes are not -// reported by the RConnectionMonitor, in particular in relation to stop() call, -// whereas they _are_ reported on RConnection progress notifier used by sessions --> centralize -// this data here so that other sessions may benefit from it too (not all sessions necessarily have -// RConnection progress notifiers available but they relay on having e.g. disconnected information from -// manager). Currently only 'Disconnected' state is of interest because it has proven to be troublesome. -void QNetworkConfigurationManagerPrivate::configurationStateChangeReport(TUint32 accessPointId, QNetworkSession::State newState) -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNCM A session reported state change for IAP ID: " << accessPointId << " whose new state is: " << newState; -#endif - switch (newState) { - case QNetworkSession::Disconnected: - { - QString ident = QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(accessPointId)); - QExplicitlySharedDataPointer priv = accessPointConfigurations.value(ident); - if (priv.data()) { - // Configuration is either Defined or Discovered - if (changeConfigurationStateAtMaxTo(priv, QNetworkConfiguration::Discovered)) { - updateStatesToSnaps(); - } - emit this->configurationStateChanged( - priv.data()->numericId, priv.data()->connectionId, QNetworkSession::Disconnected); - } - } - break; - default: - break; - } -} - -// Waits for 2..6 seconds. -void QNetworkConfigurationManagerPrivate::updateConfigurationsAfterRandomTime() -{ - iTimeToWait = (qAbs(qrand()) % 68) * 100; - if (iTimeToWait < 1000) { - iTimeToWait = 1000; - } -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug("QNCM waiting random time: %d ms", iTimeToWait); -#endif - QTimer::singleShot(iTimeToWait, this, SLOT(delayedConfigurationUpdate())); -} - -QExplicitlySharedDataPointer QNetworkConfigurationManagerPrivate::dataByConnectionId(TUint aConnectionId) -{ - QNetworkConfiguration item; - QHash >::const_iterator i = - accessPointConfigurations.constBegin(); - while (i != accessPointConfigurations.constEnd()) { - QExplicitlySharedDataPointer priv = i.value(); - if (priv.data()->connectionId == aConnectionId) { - return priv; - } - ++i; - } - return QExplicitlySharedDataPointer(); -} - -AccessPointsAvailabilityScanner::AccessPointsAvailabilityScanner(QNetworkConfigurationManagerPrivate& owner, - RConnectionMonitor& connectionMonitor) - : CActive(CActive::EPriorityHigh), iOwner(owner), iConnectionMonitor(connectionMonitor) -{ - CActiveScheduler::Add(this); -} - -AccessPointsAvailabilityScanner::~AccessPointsAvailabilityScanner() -{ - Cancel(); -} - -void AccessPointsAvailabilityScanner::DoCancel() -{ - iConnectionMonitor.CancelAsyncRequest(EConnMonGetPckgAttribute); -} - -void AccessPointsAvailabilityScanner::StartScanning() -{ - if (iOwner.iFirstUpdate) { - // On first update (the mgr is being instantiated) update only those bearers who - // don't need time-consuming scans (WLAN). - // Note: EBearerIdWCDMA covers also GPRS bearer - iConnectionMonitor.GetPckgAttribute(EBearerIdWCDMA, 0, KIapAvailability, iIapBuf, iStatus); - User::WaitForRequest(iStatus); - if (iStatus.Int() == KErrNone) { - iOwner.accessPointScanningReady(true,iIapBuf()); - } - } else { - iConnectionMonitor.GetPckgAttribute(EBearerIdAll, 0, KIapAvailability, iIapBuf, iStatus); - if (!IsActive()) { - SetActive(); - } - } -} - -void AccessPointsAvailabilityScanner::RunL() -{ - if (iStatus.Int() != KErrNone) { - iIapBuf().iCount = 0; - QT_TRYCATCH_LEAVING(iOwner.accessPointScanningReady(false,iIapBuf())); - } else { - QT_TRYCATCH_LEAVING(iOwner.accessPointScanningReady(true,iIapBuf())); - } -} -#include "moc_qnetworkconfigmanager_s60_p.cpp" -QTM_END_NAMESPACE diff --git a/src/bearer/qnetworkconfigmanager_s60_p.h b/src/bearer/qnetworkconfigmanager_s60_p.h deleted file mode 100644 index 02bfb73..0000000 --- a/src/bearer/qnetworkconfigmanager_s60_p.h +++ /dev/null @@ -1,209 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKCONFIGURATIONMANAGERPRIVATE_H -#define QNETWORKCONFIGURATIONMANAGERPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -#include -#include -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - #include -#endif - -// Uncomment and compile QtBearer to gain detailed state tracing -// #define QT_BEARERMGMT_SYMBIAN_DEBUG - -#define QT_BEARERMGMT_CONFIGURATION_SNAP_PREFIX "S_" -#define QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX "I_" - -class CCommsDatabase; -class QEventLoop; - -QT_BEGIN_NAMESPACE -class QTimer; -QT_END_NAMESPACE - -QTM_BEGIN_NAMESPACE - -class QNetworkSessionPrivate; -class AccessPointsAvailabilityScanner; - -class QNetworkConfigurationManagerPrivate : public QObject, public CActive, public MConnectionMonitorObserver -{ - Q_OBJECT - -public: - QNetworkConfigurationManagerPrivate(); - virtual ~QNetworkConfigurationManagerPrivate(); - - QNetworkConfiguration defaultConfiguration(); - void performAsyncConfigurationUpdate(); - -Q_SIGNALS: - void configurationAdded(const QNetworkConfiguration& config); - void configurationRemoved(const QNetworkConfiguration& config); - void configurationUpdateComplete(); - void configurationChanged(const QNetworkConfiguration& config); - void onlineStateChanged(bool isOnline); - - void configurationStateChanged(TUint32 accessPointId, TUint32 connMonId, - QNetworkSession::State newState); - -public Q_SLOTS: - void updateConfigurations(); - void delayedConfigurationUpdate(); - -private: - void registerPlatformCapabilities(); - void updateStatesToSnaps(); - bool changeConfigurationStateTo(QExplicitlySharedDataPointer& sharedData, - QNetworkConfiguration::StateFlags newState); - bool changeConfigurationStateAtMinTo(QExplicitlySharedDataPointer& sharedData, - QNetworkConfiguration::StateFlags newState); - bool changeConfigurationStateAtMaxTo(QExplicitlySharedDataPointer& sharedData, - QNetworkConfiguration::StateFlags newState); -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - void updateMobileBearerToConfigs(TConnMonBearerInfo bearerInfo); - QNetworkConfigurationPrivate* configFromConnectionMethodL(RCmConnectionMethod& connectionMethod); -#else - bool readNetworkConfigurationValuesFromCommsDb( - TUint32 aApId, QNetworkConfigurationPrivate* apNetworkConfiguration); - void readNetworkConfigurationValuesFromCommsDbL( - TUint32 aApId, QNetworkConfigurationPrivate* apNetworkConfiguration); -#endif - - void updateConfigurationsL(); - void updateActiveAccessPoints(); - void updateAvailableAccessPoints(); - void accessPointScanningReady(TBool scanSuccessful, TConnMonIapInfo iapInfo); - void startCommsDatabaseNotifications(); - void stopCommsDatabaseNotifications(); - void updateConfigurationsAfterRandomTime(); - - QNetworkConfiguration defaultConfigurationL(); - TBool GetS60PlatformVersion(TUint& aMajor, TUint& aMinor) const; - void startMonitoringIAPData(TUint32 aIapId); - QExplicitlySharedDataPointer dataByConnectionId(TUint aConnectionId); - -protected: - // From CActive - void RunL(); - void DoCancel(); - -private: - // MConnectionMonitorObserver - void EventL(const CConnMonEventBase& aEvent); - // For QNetworkSessionPrivate to indicate about state changes - void configurationStateChangeReport(TUint32 accessPointId, - QNetworkSession::State newState); -#ifdef OCC_FUNCTIONALITY_AVAILABLE - QExplicitlySharedDataPointer configurationFromEasyWlan(TUint32 apId, TUint connectionId); - bool easyWlanTrueIapId(TUint32& trueIapId); -#endif - -public: // Data - //this table contains an up to date list of all configs at any time. - //it must be updated if configurations change, are added/removed or - //the members of ServiceNetworks change - QHash > accessPointConfigurations; - QHash > snapConfigurations; - QHash > userChoiceConfigurations; - QNetworkConfigurationManager::Capabilities capFlags; - -private: // Data - bool iFirstUpdate; - CCommsDatabase* ipCommsDB; - RConnectionMonitor iConnectionMonitor; - - TBool iWaitingCommsDatabaseNotifications; - TBool iOnline; - TBool iInitOk; - TBool iUpdateGoingOn; - TBool iUpdatePending; - TUint iTimeToWait; - - AccessPointsAvailabilityScanner* ipAccessPointsAvailabilityScanner; - - friend class QNetworkSessionPrivate; - friend class AccessPointsAvailabilityScanner; - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - RCmManager iCmManager; -#endif -}; - -class AccessPointsAvailabilityScanner : public CActive -{ -public: - AccessPointsAvailabilityScanner(QNetworkConfigurationManagerPrivate& owner, - RConnectionMonitor& connectionMonitor); - ~AccessPointsAvailabilityScanner(); - - void StartScanning(); - -protected: // From CActive - void RunL(); - void DoCancel(); - -private: // Data - QNetworkConfigurationManagerPrivate& iOwner; - RConnectionMonitor& iConnectionMonitor; - TConnMonIapInfoBuf iIapBuf; -}; - -QTM_END_NAMESPACE - -#endif //QNETWORKCONFIGURATIONMANAGERPRIVATE_H diff --git a/src/bearer/qnetworkconfigmanageradaptor_p.h b/src/bearer/qnetworkconfigmanageradaptor_p.h new file mode 100644 index 0000000..52c73ca --- /dev/null +++ b/src/bearer/qnetworkconfigmanageradaptor_p.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#ifndef QNETWORKCONFIGMANAGERADAPTOR_P_H_ +#define QNETWORKCONFIGMANAGERADAPTOR_P_H_ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE +//this class exists only to workaround moc issues with namespaces +class QNetworkConfigurationManagerAdaptor : public QObject +{ + Q_OBJECT +protected Q_SLOTS: + virtual void _q_configurationAdded(const QNetworkConfiguration& config) = 0; + virtual void _q_configurationRemoved(const QNetworkConfiguration& config) = 0; + virtual void _q_configurationChanged(const QNetworkConfiguration& config) = 0; +}; +QT_END_NAMESPACE + +#endif /* QNETWORKCONFIGMANAGERADAPTOR_P_H_ */ diff --git a/src/bearer/qnetworkconfiguration.cpp b/src/bearer/qnetworkconfiguration.cpp index 52d1ac4..5754196 100644 --- a/src/bearer/qnetworkconfiguration.cpp +++ b/src/bearer/qnetworkconfiguration.cpp @@ -41,14 +41,6 @@ #include "qnetworkconfiguration.h" -#ifdef Q_OS_SYMBIAN -#include "qnetworkconfiguration_s60_p.h" -#elif defined(Q_WS_MAEMO_6) || defined(Q_WS_MAEMO_5) -#include "qnetworkconfiguration_maemo_p.h" -#else -#include "qnetworkconfiguration_p.h" -#endif - QTM_BEGIN_NAMESPACE /*! @@ -194,7 +186,7 @@ QTM_BEGIN_NAMESPACE \sa isValid() */ QNetworkConfiguration::QNetworkConfiguration() - : d(0) + : QT_PREPEND_NAMESPACE(QNetworkConfiguration)() { } @@ -202,16 +194,22 @@ QNetworkConfiguration::QNetworkConfiguration() Creates a copy of the QNetworkConfiguration object contained in \a other. */ QNetworkConfiguration::QNetworkConfiguration(const QNetworkConfiguration& other) - : d(other.d) + : QT_PREPEND_NAMESPACE(QNetworkConfiguration)(other) { } +QNetworkConfiguration::QNetworkConfiguration(const QT_PREPEND_NAMESPACE(QNetworkConfiguration) &other) + : QT_PREPEND_NAMESPACE(QNetworkConfiguration)(other) +{ +} + + /*! Copies the content of the QNetworkConfiguration object contained in \a other into this one. */ QNetworkConfiguration& QNetworkConfiguration::operator=(const QNetworkConfiguration& other) { - d = other.d; + QT_PREPEND_NAMESPACE(QNetworkConfiguration)::operator=(other); return *this; } @@ -228,13 +226,7 @@ QNetworkConfiguration::~QNetworkConfiguration() */ bool QNetworkConfiguration::operator==(const QNetworkConfiguration& other) const { - if (!d) - return !other.d; - - if (!other.d) - return false; - - return (d == other.d); + return QT_PREPEND_NAMESPACE(QNetworkConfiguration)::operator==(other); } /*! @@ -252,7 +244,7 @@ bool QNetworkConfiguration::operator==(const QNetworkConfiguration& other) const */ QString QNetworkConfiguration::name() const { - return d ? d->name : QString(); + return QT_PREPEND_NAMESPACE(QNetworkConfiguration)::name(); } /*! @@ -261,7 +253,7 @@ QString QNetworkConfiguration::name() const */ QString QNetworkConfiguration::identifier() const { - return d ? d->id : QString(); + return QT_PREPEND_NAMESPACE(QNetworkConfiguration)::identifier(); } /*! @@ -274,7 +266,7 @@ QString QNetworkConfiguration::identifier() const */ QNetworkConfiguration::Type QNetworkConfiguration::type() const { - return d ? d->type : QNetworkConfiguration::Invalid; + return (QNetworkConfiguration::Type)QT_PREPEND_NAMESPACE(QNetworkConfiguration)::type(); } /*! @@ -289,7 +281,7 @@ QNetworkConfiguration::Type QNetworkConfiguration::type() const */ bool QNetworkConfiguration::isValid() const { - return d ? d->isValid : false; + return QT_PREPEND_NAMESPACE(QNetworkConfiguration)::isValid(); } /*! @@ -297,7 +289,8 @@ bool QNetworkConfiguration::isValid() const */ QNetworkConfiguration::StateFlags QNetworkConfiguration::state() const { - return d ? d->state : QNetworkConfiguration::Undefined; + int rv = QT_PREPEND_NAMESPACE(QNetworkConfiguration)::state(); + return (QNetworkConfiguration::StateFlags)rv; } /*! @@ -309,7 +302,8 @@ QNetworkConfiguration::StateFlags QNetworkConfiguration::state() const */ QNetworkConfiguration::Purpose QNetworkConfiguration::purpose() const { - return d ? d->purpose : QNetworkConfiguration::UnknownPurpose; + int rv = QT_PREPEND_NAMESPACE(QNetworkConfiguration)::purpose(); + return (QNetworkConfiguration::Purpose)rv; } /*! @@ -317,7 +311,7 @@ QNetworkConfiguration::Purpose QNetworkConfiguration::purpose() const */ bool QNetworkConfiguration::isRoamingAvailable() const { - return d ? d->roamingSupported : false; + return QT_PREPEND_NAMESPACE(QNetworkConfiguration)::isRoamingAvailable(); } /*! @@ -327,24 +321,12 @@ bool QNetworkConfiguration::isRoamingAvailable() const */ QList QNetworkConfiguration::children() const { - QList results; - if (type() != QNetworkConfiguration::ServiceNetwork || !isValid() ) - return results; - - QMutableListIterator > iter(d->serviceNetworkMembers); - QExplicitlySharedDataPointer p(0); - while(iter.hasNext()) { - p = iter.next(); - //if we have an invalid member get rid of it -> was deleted earlier on - if (!p->isValid) - iter.remove(); - - QNetworkConfiguration item; - item.d = p; - results << item; + QList rv; + QList result = QT_PREPEND_NAMESPACE(QNetworkConfiguration)::children(); + foreach (const QT_PREPEND_NAMESPACE(QNetworkConfiguration) &item, result) { + rv.append(QNetworkConfiguration(item)); } - - return results; + return rv; } /*! @@ -391,10 +373,7 @@ QList QNetworkConfiguration::children() const */ QString QNetworkConfiguration::bearerName() const { - if (!isValid()) - return QString(); - - return d->bearerName(); + return QT_PREPEND_NAMESPACE(QNetworkConfiguration)::bearerName(); } diff --git a/src/bearer/qnetworkconfiguration.h b/src/bearer/qnetworkconfiguration.h index 5c3dc4c..c84839a 100644 --- a/src/bearer/qnetworkconfiguration.h +++ b/src/bearer/qnetworkconfiguration.h @@ -39,21 +39,22 @@ ** ****************************************************************************/ -#ifndef QNETWORKCONFIGURATION_H -#define QNETWORKCONFIGURATION_H +#ifndef QTM_NETWORKCONFIGURATION_H +#define QTM_NETWORKCONFIGURATION_H #include "qmobilityglobal.h" #include #include #include +#include QT_BEGIN_HEADER QTM_BEGIN_NAMESPACE class QNetworkConfigurationPrivate; -class Q_BEARER_EXPORT QNetworkConfiguration +class Q_BEARER_EXPORT QNetworkConfiguration : QT_PREPEND_NAMESPACE(QNetworkConfiguration) { public: QNetworkConfiguration(); @@ -100,15 +101,18 @@ public: bool isValid() const; private: + QNetworkConfiguration(const QT_PREPEND_NAMESPACE(QNetworkConfiguration) &); friend class QNetworkConfigurationPrivate; friend class QNetworkConfigurationManager; friend class QNetworkConfigurationManagerPrivate; friend class QNetworkSessionPrivate; - QExplicitlySharedDataPointer d; + friend class QNetworkSession; + //'d' is removed, but the base class has the same 'd' so class size remains the same. + //QExplicitlySharedDataPointer d; }; QTM_END_NAMESPACE QT_END_HEADER -#endif //QNETWORKCONFIGURATION_H +#endif //QTM_NETWORKCONFIGURATION_H diff --git a/src/bearer/qnetworkconfiguration_maemo_p.h b/src/bearer/qnetworkconfiguration_maemo_p.h deleted file mode 100644 index 6a9aa22..0000000 --- a/src/bearer/qnetworkconfiguration_maemo_p.h +++ /dev/null @@ -1,125 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKCONFIGURATIONPRIVATE_H -#define QNETWORKCONFIGURATIONPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -#include "qnetworkconfiguration.h" - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationManagerPrivate; - -class QNetworkConfigurationPrivate : public QSharedData -{ -public: - QNetworkConfigurationPrivate () - : isValid(false), type(QNetworkConfiguration::Invalid), - roamingSupported(false), purpose(QNetworkConfiguration::UnknownPurpose), - network_attrs(0), service_attrs(0), manager(0) - { - } - - ~QNetworkConfigurationPrivate() - { - //release pointers to member configurations - serviceNetworkMembers.clear(); - } - - QString name; - bool isValid; - QString id; - QNetworkConfiguration::StateFlags state; - QNetworkConfiguration::Type type; - bool roamingSupported; - QNetworkConfiguration::Purpose purpose; - - QList > serviceNetworkMembers; - QNetworkInterface serviceInterface; - - /* In Maemo the id field (defined above) is the IAP id (which typically is UUID) */ - QByteArray network_id; /* typically WLAN ssid or similar */ - QString iap_type; /* is this one WLAN or GPRS */ - QString bearerName() const - { - if (iap_type == "WLAN_INFRA" || - iap_type == "WLAN_ADHOC") - return QString("WLAN"); - else if (iap_type == "GPRS") - return QString("HSPA"); - - //return whatever it is - //this may have to be split up later on - return iap_type; - } - - quint32 network_attrs; /* network attributes for this IAP, this is the value returned by icd and passed to it when connecting */ - - QString service_type; - QString service_id; - quint32 service_attrs; - - QNetworkConfigurationManagerPrivate *manager; - -private: - - // disallow detaching - QNetworkConfigurationPrivate &operator=(const QNetworkConfigurationPrivate &other); - QNetworkConfigurationPrivate(const QNetworkConfigurationPrivate &other); -}; - -QTM_END_NAMESPACE - -#endif //QNETWORKCONFIGURATIONPRIVATE_H diff --git a/src/bearer/qnetworkconfiguration_p.h b/src/bearer/qnetworkconfiguration_p.h deleted file mode 100644 index 4ef3d1d..0000000 --- a/src/bearer/qnetworkconfiguration_p.h +++ /dev/null @@ -1,110 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKCONFIGURATIONPRIVATE_H -#define QNETWORKCONFIGURATIONPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qnetworkconfiguration.h" -#include -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate : public QSharedData -{ -public: - QNetworkConfigurationPrivate () - : isValid(false), type(QNetworkConfiguration::Invalid), - roamingSupported(false), purpose(QNetworkConfiguration::UnknownPurpose) - { -#ifdef BEARER_ENGINE - internet = false; -#endif - } - - ~QNetworkConfigurationPrivate() - { - //release pointers to member configurations - serviceNetworkMembers.clear(); - } - - QString name; - QString bearer; - inline QString bearerName() const - { - return bearer; - } - - bool isValid; - QString id; - QNetworkConfiguration::StateFlags state; - QNetworkConfiguration::Type type; - bool roamingSupported; - QNetworkConfiguration::Purpose purpose; - -#ifdef BEARER_ENGINE - bool internet; -#endif - - QList > serviceNetworkMembers; - QNetworkInterface serviceInterface; - -private: - - // disallow detaching - QNetworkConfigurationPrivate &operator=(const QNetworkConfigurationPrivate &other); - QNetworkConfigurationPrivate(const QNetworkConfigurationPrivate &other); -}; - -QTM_END_NAMESPACE - -#endif //QNETWORKCONFIGURATIONPRIVATE_H diff --git a/src/bearer/qnetworkconfiguration_s60_p.cpp b/src/bearer/qnetworkconfiguration_s60_p.cpp deleted file mode 100644 index c75e683..0000000 --- a/src/bearer/qnetworkconfiguration_s60_p.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnetworkconfiguration_s60_p.h" - -QTM_BEGIN_NAMESPACE - -QNetworkConfigurationPrivate::QNetworkConfigurationPrivate() - : isValid(false), type(QNetworkConfiguration::Invalid), - roamingSupported(false), purpose(QNetworkConfiguration::UnknownPurpose), - bearer(QNetworkConfigurationPrivate::BearerUnknown), numericId(0), - connectionId(0), manager(0) -{ -} - -QNetworkConfigurationPrivate::~QNetworkConfigurationPrivate() -{ - //release pointers to member configurations - serviceNetworkMembers.clear(); -} - -QString QNetworkConfigurationPrivate::bearerName() const -{ - switch (bearer) { - case QNetworkConfigurationPrivate::BearerEthernet: return QLatin1String("Ethernet"); - case QNetworkConfigurationPrivate::BearerWLAN: return QLatin1String("WLAN"); - case QNetworkConfigurationPrivate::Bearer2G: return QLatin1String("2G"); - case QNetworkConfigurationPrivate::BearerCDMA2000: return QLatin1String("CDMA2000"); - case QNetworkConfigurationPrivate::BearerWCDMA: return QLatin1String("WCDMA"); - case QNetworkConfigurationPrivate::BearerHSPA: return QLatin1String("HSPA"); - case QNetworkConfigurationPrivate::BearerBluetooth: return QLatin1String("Bluetooth"); - case QNetworkConfigurationPrivate::BearerWiMAX: return QLatin1String("WiMAX"); - default: return QString(); - } -} - - -QTM_END_NAMESPACE diff --git a/src/bearer/qnetworkconfiguration_s60_p.h b/src/bearer/qnetworkconfiguration_s60_p.h deleted file mode 100644 index d591c39..0000000 --- a/src/bearer/qnetworkconfiguration_s60_p.h +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKCONFIGURATIONPRIVATE_H -#define QNETWORKCONFIGURATIONPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate : public QSharedData -{ -public: - enum Bearer { - BearerEthernet, - BearerWLAN, - Bearer2G, - BearerCDMA2000, - BearerWCDMA, - BearerHSPA, - BearerBluetooth, - BearerWiMAX, - BearerUnknown = -1 - }; - - QNetworkConfigurationPrivate(); - ~QNetworkConfigurationPrivate(); - - QString name; - bool isValid; - QString id; - QNetworkConfiguration::StateFlags state; - QNetworkConfiguration::Type type; - bool roamingSupported; - QNetworkConfiguration::Purpose purpose; - - QList > serviceNetworkMembers; - - QNetworkConfigurationPrivate::Bearer bearer; - QString bearerName() const; - // So called IAP id from the platform. Remains constant as long as the - // platform is aware of the configuration ie. it is stored in the databases - // --> does not depend on whether connections are currently open or not. - // In practice is the same for the lifetime of the QNetworkConfiguration. - TUint32 numericId; - // So called connection id, or connection monitor ID. A dynamic ID assigned - // by RConnectionMonitor whenever a new connection is opened. ConnectionID and - // numericId/IAP id have 1-to-1 mapping during the lifetime of the connection at - // connection monitor. Notably however it changes whenever a new connection to - // a given IAP is created. In a sense it is constant during the time the - // configuration remains between states Discovered..Active..Discovered, do not - // however relay on this. - TUint connectionId; - - TAny* manager; - - QString mappingName; - - QExplicitlySharedDataPointer serviceNetworkPtr; - -private: - // disallow detaching - QNetworkConfigurationPrivate &operator=(const QNetworkConfigurationPrivate &other); - QNetworkConfigurationPrivate(const QNetworkConfigurationPrivate &other); -}; - -QTM_END_NAMESPACE - -#endif //QNETWORKCONFIGURATIONPRIVATE_H - diff --git a/src/bearer/qnetworkmanagerservice_p.cpp b/src/bearer/qnetworkmanagerservice_p.cpp deleted file mode 100644 index f183c22..0000000 --- a/src/bearer/qnetworkmanagerservice_p.cpp +++ /dev/null @@ -1,916 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "qnetworkmanagerservice_p.h" -#include "qnmdbushelper_p.h" - -QTM_BEGIN_NAMESPACE - -class QNetworkManagerInterfacePrivate -{ -public: - QDBusInterface *connectionInterface; - bool valid; -}; - -QNetworkManagerInterface::QNetworkManagerInterface(QObject *parent) - : QObject(parent) -{ - d = new QNetworkManagerInterfacePrivate(); - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - QLatin1String(NM_DBUS_PATH), - QLatin1String(NM_DBUS_INTERFACE), - QDBusConnection::systemBus()); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), - this,SIGNAL(propertiesChanged( const QString &, QMap))); - connect(nmDBusHelper,SIGNAL(pathForStateChanged(const QString &, quint32)), - this, SIGNAL(stateChanged(const QString&, quint32))); - -} - -QNetworkManagerInterface::~QNetworkManagerInterface() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerInterface::isValid() -{ - return d->valid; -} - -bool QNetworkManagerInterface::setConnections() -{ - if(!isValid() ) - return false; - bool allOk = false; - if (!QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - QLatin1String(NM_DBUS_PATH), - QLatin1String(NM_DBUS_INTERFACE), - QLatin1String("PropertiesChanged"), - nmDBusHelper,SLOT(slotPropertiesChanged( QMap)))) { - allOk = true; - } - if (!QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - QLatin1String(NM_DBUS_PATH), - QLatin1String(NM_DBUS_INTERFACE), - QLatin1String("DeviceAdded"), - this,SIGNAL(deviceAdded(QDBusObjectPath)))) { - allOk = true; - } - if (!QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - QLatin1String(NM_DBUS_PATH), - QLatin1String(NM_DBUS_INTERFACE), - QLatin1String("DeviceRemoved"), - this,SIGNAL(deviceRemoved(QDBusObjectPath)))) { - allOk = true; - } - - return allOk; -} - -QDBusInterface *QNetworkManagerInterface::connectionInterface() const -{ - return d->connectionInterface; -} - -QList QNetworkManagerInterface::getDevices() const -{ - QDBusReply > reply = d->connectionInterface->call(QLatin1String("GetDevices")); - return reply.value(); -} - -void QNetworkManagerInterface::activateConnection( const QString &serviceName, - QDBusObjectPath connectionPath, - QDBusObjectPath devicePath, - QDBusObjectPath specificObject) -{ - QDBusPendingCall pendingCall = d->connectionInterface->asyncCall(QLatin1String("ActivateConnection"), - QVariant(serviceName), - QVariant::fromValue(connectionPath), - QVariant::fromValue(devicePath), - QVariant::fromValue(specificObject)); - - QDBusPendingCallWatcher *callWatcher = new QDBusPendingCallWatcher(pendingCall, this); - connect(callWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - this, SIGNAL(activationFinished(QDBusPendingCallWatcher*))); -} - -void QNetworkManagerInterface::deactivateConnection(QDBusObjectPath connectionPath) const -{ - d->connectionInterface->call(QLatin1String("DeactivateConnection"), QVariant::fromValue(connectionPath)); -} - -bool QNetworkManagerInterface::wirelessEnabled() const -{ - return d->connectionInterface->property("WirelessEnabled").toBool(); -} - -bool QNetworkManagerInterface::wirelessHardwareEnabled() const -{ - return d->connectionInterface->property("WirelessHardwareEnabled").toBool(); -} - -QList QNetworkManagerInterface::activeConnections() const -{ - QVariant prop = d->connectionInterface->property("ActiveConnections"); - return prop.value >(); -} - -quint32 QNetworkManagerInterface::state() -{ - return d->connectionInterface->property("State").toUInt(); -} - -class QNetworkManagerInterfaceAccessPointPrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerInterfaceAccessPoint::QNetworkManagerInterfaceAccessPoint(const QString &dbusPathName, QObject *parent) - : QObject(parent) -{ - d = new QNetworkManagerInterfaceAccessPointPrivate(); - d->path = dbusPathName; - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_ACCESS_POINT), - QDBusConnection::systemBus()); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; - -} - -QNetworkManagerInterfaceAccessPoint::~QNetworkManagerInterfaceAccessPoint() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerInterfaceAccessPoint::isValid() -{ - return d->valid; -} - -bool QNetworkManagerInterfaceAccessPoint::setConnections() -{ - if(!isValid() ) - return false; - - bool allOk = false; - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), - this,SIGNAL(propertiesChanged( const QString &, QMap))); - - if(QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_ACCESS_POINT), - QLatin1String("PropertiesChanged"), - nmDBusHelper,SLOT(slotPropertiesChanged( QMap))) ) { - allOk = true; - - } - return allOk; -} - -QDBusInterface *QNetworkManagerInterfaceAccessPoint::connectionInterface() const -{ - return d->connectionInterface; -} - -quint32 QNetworkManagerInterfaceAccessPoint::flags() const -{ - return d->connectionInterface->property("Flags").toUInt(); -} - -quint32 QNetworkManagerInterfaceAccessPoint::wpaFlags() const -{ - return d->connectionInterface->property("WpaFlags").toUInt(); -} - -quint32 QNetworkManagerInterfaceAccessPoint::rsnFlags() const -{ - return d->connectionInterface->property("RsnFlags").toUInt(); -} - -QString QNetworkManagerInterfaceAccessPoint::ssid() const -{ - return d->connectionInterface->property("Ssid").toString(); -} - -quint32 QNetworkManagerInterfaceAccessPoint::frequency() const -{ - return d->connectionInterface->property("Frequency").toUInt(); -} - -QString QNetworkManagerInterfaceAccessPoint::hwAddress() const -{ - return d->connectionInterface->property("HwAddress").toString(); -} - -quint32 QNetworkManagerInterfaceAccessPoint::mode() const -{ - return d->connectionInterface->property("Mode").toUInt(); -} - -quint32 QNetworkManagerInterfaceAccessPoint::maxBitrate() const -{ - return d->connectionInterface->property("MaxBitrate").toUInt(); -} - -quint32 QNetworkManagerInterfaceAccessPoint::strength() const -{ - return d->connectionInterface->property("Strength").toUInt(); -} - -class QNetworkManagerInterfaceDevicePrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerInterfaceDevice::QNetworkManagerInterfaceDevice(const QString &deviceObjectPath, QObject *parent) - : QObject(parent) -{ - d = new QNetworkManagerInterfaceDevicePrivate(); - d->path = deviceObjectPath; - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE), - QDBusConnection::systemBus()); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; -} - -QNetworkManagerInterfaceDevice::~QNetworkManagerInterfaceDevice() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerInterfaceDevice::isValid() -{ - return d->valid; -} - -bool QNetworkManagerInterfaceDevice::setConnections() -{ - if(!isValid() ) - return false; - - bool allOk = false; - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper,SIGNAL(pathForStateChanged(const QString &, quint32)), - this, SIGNAL(stateChanged(const QString&, quint32))); - if(QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE), - QLatin1String("StateChanged"), - nmDBusHelper,SLOT(deviceStateChanged(quint32)))) { - allOk = true; - } - return allOk; -} - -QDBusInterface *QNetworkManagerInterfaceDevice::connectionInterface() const -{ - return d->connectionInterface; -} - -QString QNetworkManagerInterfaceDevice::udi() const -{ - return d->connectionInterface->property("Udi").toString(); -} - -QNetworkInterface QNetworkManagerInterfaceDevice::networkInterface() const -{ - return QNetworkInterface::interfaceFromName(d->connectionInterface->property("Interface").toString()); -} - -quint32 QNetworkManagerInterfaceDevice::ip4Address() const -{ - return d->connectionInterface->property("Ip4Address").toUInt(); -} - -quint32 QNetworkManagerInterfaceDevice::state() const -{ - return d->connectionInterface->property("State").toUInt(); -} - -quint32 QNetworkManagerInterfaceDevice::deviceType() const -{ - return d->connectionInterface->property("DeviceType").toUInt(); -} - -QDBusObjectPath QNetworkManagerInterfaceDevice::ip4config() const -{ - QVariant prop = d->connectionInterface->property("Ip4Config"); - return prop.value(); -} - -class QNetworkManagerInterfaceDeviceWiredPrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerInterfaceDeviceWired::QNetworkManagerInterfaceDeviceWired(const QString &ifaceDevicePath, QObject *parent) -{ - d = new QNetworkManagerInterfaceDeviceWiredPrivate(); - d->path = ifaceDevicePath; - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRED), - QDBusConnection::systemBus(), parent); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; -} - -QNetworkManagerInterfaceDeviceWired::~QNetworkManagerInterfaceDeviceWired() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerInterfaceDeviceWired::isValid() -{ - - return d->valid; -} - -bool QNetworkManagerInterfaceDeviceWired::setConnections() -{ - if(!isValid() ) - return false; - - bool allOk = false; - - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), - this,SIGNAL(propertiesChanged( const QString &, QMap))); - if(QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRED), - QLatin1String("PropertiesChanged"), - nmDBusHelper,SLOT(slotPropertiesChanged( QMap))) ) { - allOk = true; - } - return allOk; -} - -QDBusInterface *QNetworkManagerInterfaceDeviceWired::connectionInterface() const -{ - return d->connectionInterface; -} - -QString QNetworkManagerInterfaceDeviceWired::hwAddress() const -{ - return d->connectionInterface->property("HwAddress").toString(); -} - -quint32 QNetworkManagerInterfaceDeviceWired::speed() const -{ - return d->connectionInterface->property("Speed").toUInt(); -} - -bool QNetworkManagerInterfaceDeviceWired::carrier() const -{ - return d->connectionInterface->property("Carrier").toBool(); -} - -class QNetworkManagerInterfaceDeviceWirelessPrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerInterfaceDeviceWireless::QNetworkManagerInterfaceDeviceWireless(const QString &ifaceDevicePath, QObject *parent) -{ - d = new QNetworkManagerInterfaceDeviceWirelessPrivate(); - d->path = ifaceDevicePath; - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), - QDBusConnection::systemBus(), parent); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; -} - -QNetworkManagerInterfaceDeviceWireless::~QNetworkManagerInterfaceDeviceWireless() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerInterfaceDeviceWireless::isValid() -{ - return d->valid; -} - -bool QNetworkManagerInterfaceDeviceWireless::setConnections() -{ - if(!isValid() ) - return false; - - bool allOk = false; - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), - this,SIGNAL(propertiesChanged( const QString &, QMap))); - - connect(nmDBusHelper, SIGNAL(pathForAccessPointAdded(const QString &,QDBusObjectPath)), - this,SIGNAL(accessPointAdded(const QString &,QDBusObjectPath))); - - connect(nmDBusHelper, SIGNAL(pathForAccessPointRemoved(const QString &,QDBusObjectPath)), - this,SIGNAL(accessPointRemoved(const QString &,QDBusObjectPath))); - - if(!QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), - QLatin1String("AccessPointAdded"), - nmDBusHelper, SLOT(slotAccessPointAdded( QDBusObjectPath )))) { - allOk = true; - } - - - if(!QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), - QLatin1String("AccessPointRemoved"), - nmDBusHelper, SLOT(slotAccessPointRemoved( QDBusObjectPath )))) { - allOk = true; - } - - - if(!QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), - QLatin1String("PropertiesChanged"), - nmDBusHelper,SLOT(slotPropertiesChanged( QMap)))) { - allOk = true; - } - - return allOk; -} - -QDBusInterface *QNetworkManagerInterfaceDeviceWireless::connectionInterface() const -{ - return d->connectionInterface; -} - -QList QNetworkManagerInterfaceDeviceWireless::getAccessPoints() -{ - QDBusReply > reply = d->connectionInterface->call(QLatin1String("GetAccessPoints")); - return reply.value(); -} - -QString QNetworkManagerInterfaceDeviceWireless::hwAddress() const -{ - return d->connectionInterface->property("HwAddress").toString(); -} - -quint32 QNetworkManagerInterfaceDeviceWireless::mode() const -{ - return d->connectionInterface->property("Mode").toUInt(); -} - -quint32 QNetworkManagerInterfaceDeviceWireless::bitrate() const -{ - return d->connectionInterface->property("Bitrate").toUInt(); -} - -QDBusObjectPath QNetworkManagerInterfaceDeviceWireless::activeAccessPoint() const -{ - return d->connectionInterface->property("ActiveAccessPoint").value(); -} - -quint32 QNetworkManagerInterfaceDeviceWireless::wirelessCapabilities() const -{ - return d->connectionInterface->property("WirelelessCapabilities").toUInt(); -} - -class QNetworkManagerSettingsPrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerSettings::QNetworkManagerSettings(const QString &settingsService, QObject *parent) - : QObject(parent) -{ - d = new QNetworkManagerSettingsPrivate(); - d->path = settingsService; - d->connectionInterface = new QDBusInterface(settingsService, - QLatin1String(NM_DBUS_PATH_SETTINGS), - QLatin1String(NM_DBUS_IFACE_SETTINGS), - QDBusConnection::systemBus()); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; -} - -QNetworkManagerSettings::~QNetworkManagerSettings() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerSettings::isValid() -{ - return d->valid; -} - -bool QNetworkManagerSettings::setConnections() -{ - bool allOk = false; - - if (!QDBusConnection::systemBus().connect(d->path, QLatin1String(NM_DBUS_PATH_SETTINGS), - QLatin1String(NM_DBUS_IFACE_SETTINGS), QLatin1String("NewConnection"), - this, SIGNAL(newConnection(QDBusObjectPath)))) { - allOk = true; - } - - return allOk; -} - -QList QNetworkManagerSettings::listConnections() -{ - QDBusReply > reply = d->connectionInterface->call(QLatin1String("ListConnections")); - return reply.value(); -} - -QDBusInterface *QNetworkManagerSettings::connectionInterface() const -{ - return d->connectionInterface; -} - - -class QNetworkManagerSettingsConnectionPrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - QString service; - QNmSettingsMap settingsMap; - bool valid; -}; - -QNetworkManagerSettingsConnection::QNetworkManagerSettingsConnection(const QString &settingsService, const QString &connectionObjectPath, QObject *parent) -{ - qDBusRegisterMetaType(); - d = new QNetworkManagerSettingsConnectionPrivate(); - d->path = connectionObjectPath; - d->service = settingsService; - d->connectionInterface = new QDBusInterface(settingsService, - d->path, - QLatin1String(NM_DBUS_IFACE_SETTINGS_CONNECTION), - QDBusConnection::systemBus(), parent); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; - QDBusReply< QNmSettingsMap > rep = d->connectionInterface->call(QLatin1String("GetSettings")); - d->settingsMap = rep.value(); -} - -QNetworkManagerSettingsConnection::~QNetworkManagerSettingsConnection() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerSettingsConnection::isValid() -{ - return d->valid; -} - -bool QNetworkManagerSettingsConnection::setConnections() -{ - if(!isValid() ) - return false; - - bool allOk = false; - if(!QDBusConnection::systemBus().connect(d->service, d->path, - QLatin1String(NM_DBUS_IFACE_SETTINGS_CONNECTION), QLatin1String("NewConnection"), - this, SIGNAL(updated(QNmSettingsMap)))) { - allOk = true; - } - - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper, SIGNAL(pathForSettingsRemoved(const QString &)), - this,SIGNAL(removed( const QString &))); - - if (!QDBusConnection::systemBus().connect(d->service, d->path, - QLatin1String(NM_DBUS_IFACE_SETTINGS_CONNECTION), QLatin1String("Removed"), - nmDBusHelper, SIGNAL(slotSettingsRemoved()))) { - allOk = true; - } - - return allOk; -} - -QDBusInterface *QNetworkManagerSettingsConnection::connectionInterface() const -{ - return d->connectionInterface; -} - -QNmSettingsMap QNetworkManagerSettingsConnection::getSettings() -{ - QDBusReply< QNmSettingsMap > rep = d->connectionInterface->call(QLatin1String("GetSettings")); - d->settingsMap = rep.value(); - return d->settingsMap; -} - -NMDeviceType QNetworkManagerSettingsConnection::getType() -{ - const QString devType = - d->settingsMap.value(QLatin1String("connection")).value(QLatin1String("type")).toString(); - - if (devType == QLatin1String("802-3-ethernet")) - return DEVICE_TYPE_802_3_ETHERNET; - else if (devType == QLatin1String("802-11-wireless")) - return DEVICE_TYPE_802_11_WIRELESS; - else - return DEVICE_TYPE_UNKNOWN; -} - -bool QNetworkManagerSettingsConnection::isAutoConnect() -{ - const QVariant autoConnect = - d->settingsMap.value(QLatin1String("connection")).value(QLatin1String("autoconnect")); - - // NetworkManager default is to auto connect - if (!autoConnect.isValid()) - return true; - - return autoConnect.toBool(); -} - -quint64 QNetworkManagerSettingsConnection::getTimestamp() -{ - qDebug() << d->settingsMap.value(QLatin1String("connection")); - - return d->settingsMap.value(QLatin1String("connection")) - .value(QLatin1String("timestamp")).toUInt(); -} - -QString QNetworkManagerSettingsConnection::getId() -{ - return d->settingsMap.value(QLatin1String("connection")).value(QLatin1String("id")).toString(); -} - -QString QNetworkManagerSettingsConnection::getUuid() -{ - const QString id = d->settingsMap.value(QLatin1String("connection")) - .value(QLatin1String("uuid")).toString(); - - // is no uuid, return the connection path - return id.isEmpty() ? d->connectionInterface->path() : id; -} - -QString QNetworkManagerSettingsConnection::getSsid() -{ - return d->settingsMap.value(QLatin1String("802-11-wireless")) - .value(QLatin1String("ssid")).toString(); -} - -QString QNetworkManagerSettingsConnection::getMacAddress() -{ - NMDeviceType type = getType(); - - if (type == DEVICE_TYPE_802_3_ETHERNET) { - return d->settingsMap.value(QLatin1String("802-3-ethernet")) - .value(QLatin1String("mac-address")).toString(); - } else if (type == DEVICE_TYPE_802_11_WIRELESS) { - return d->settingsMap.value(QLatin1String("802-11-wireless")) - .value(QLatin1String("mac-address")).toString(); - } else { - return QString(); - } -} - -QStringList QNetworkManagerSettingsConnection::getSeenBssids() -{ - if (getType() == DEVICE_TYPE_802_11_WIRELESS) { - return d->settingsMap.value(QLatin1String("802-11-wireless")) - .value(QLatin1String("seen-bssids")).toStringList(); - } else { - return QStringList(); - } -} - -class QNetworkManagerConnectionActivePrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerConnectionActive::QNetworkManagerConnectionActive( const QString &activeConnectionObjectPath, QObject *parent) -{ - d = new QNetworkManagerConnectionActivePrivate(); - d->path = activeConnectionObjectPath; - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_ACTIVE_CONNECTION), - QDBusConnection::systemBus(), parent); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; -} - -QNetworkManagerConnectionActive::~QNetworkManagerConnectionActive() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerConnectionActive::isValid() -{ - return d->valid; -} - -bool QNetworkManagerConnectionActive::setConnections() -{ - if(!isValid() ) - return false; - - bool allOk = false; - nmDBusHelper = new QNmDBusHelper(this); - connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), - this,SIGNAL(propertiesChanged( const QString &, QMap))); - if(QDBusConnection::systemBus().connect(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_ACTIVE_CONNECTION), - QLatin1String("PropertiesChanged"), - nmDBusHelper,SLOT(slotPropertiesChanged( QMap))) ) { - allOk = true; - } - - return allOk; -} - -QDBusInterface *QNetworkManagerConnectionActive::connectionInterface() const -{ - return d->connectionInterface; -} - -QString QNetworkManagerConnectionActive::serviceName() const -{ - return d->connectionInterface->property("ServiceName").toString(); -} - -QDBusObjectPath QNetworkManagerConnectionActive::connection() const -{ - QVariant prop = d->connectionInterface->property("Connection"); - return prop.value(); -} - -QDBusObjectPath QNetworkManagerConnectionActive::specificObject() const -{ - QVariant prop = d->connectionInterface->property("SpecificObject"); - return prop.value(); -} - -QList QNetworkManagerConnectionActive::devices() const -{ - QVariant prop = d->connectionInterface->property("Devices"); - return prop.value >(); -} - -quint32 QNetworkManagerConnectionActive::state() const -{ - return d->connectionInterface->property("State").toUInt(); -} - -bool QNetworkManagerConnectionActive::defaultRoute() const -{ - return d->connectionInterface->property("Default").toBool(); -} - -class QNetworkManagerIp4ConfigPrivate -{ -public: - QDBusInterface *connectionInterface; - QString path; - bool valid; -}; - -QNetworkManagerIp4Config::QNetworkManagerIp4Config( const QString &deviceObjectPath, QObject *parent) -{ - d = new QNetworkManagerIp4ConfigPrivate(); - d->path = deviceObjectPath; - d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), - d->path, - QLatin1String(NM_DBUS_INTERFACE_IP4_CONFIG), - QDBusConnection::systemBus(), parent); - if (!d->connectionInterface->isValid()) { - d->valid = false; - return; - } - d->valid = true; -} - -QNetworkManagerIp4Config::~QNetworkManagerIp4Config() -{ - delete d->connectionInterface; - delete d; -} - -bool QNetworkManagerIp4Config::isValid() -{ - return d->valid; -} - -QStringList QNetworkManagerIp4Config::domains() const -{ - return d->connectionInterface->property("Domains").toStringList(); -} - -#include "moc_qnetworkmanagerservice_p.cpp" - -QTM_END_NAMESPACE diff --git a/src/bearer/qnetworkmanagerservice_p.h b/src/bearer/qnetworkmanagerservice_p.h deleted file mode 100644 index 7d22105..0000000 --- a/src/bearer/qnetworkmanagerservice_p.h +++ /dev/null @@ -1,440 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKMANAGERSERVICE_H -#define QNETWORKMANAGERSERVICE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. - -#include - -#include -#include -#include -#include -#include -#include -#include - - -#include -#include -#include -#include -#include "qnmdbushelper_p.h" - -#ifndef NETWORK_MANAGER_H -typedef enum NMDeviceType -{ - DEVICE_TYPE_UNKNOWN = 0, - DEVICE_TYPE_802_3_ETHERNET, - DEVICE_TYPE_802_11_WIRELESS, - DEVICE_TYPE_GSM, - DEVICE_TYPE_CDMA -} NMDeviceType; - -typedef enum -{ - NM_DEVICE_STATE_UNKNOWN = 0, - NM_DEVICE_STATE_UNMANAGED, - NM_DEVICE_STATE_UNAVAILABLE, - NM_DEVICE_STATE_DISCONNECTED, - NM_DEVICE_STATE_PREPARE, - NM_DEVICE_STATE_CONFIG, - NM_DEVICE_STATE_NEED_AUTH, - NM_DEVICE_STATE_IP_CONFIG, - NM_DEVICE_STATE_ACTIVATED, - NM_DEVICE_STATE_FAILED -} NMDeviceState; - -#define NM_DBUS_SERVICE "org.freedesktop.NetworkManager" - -#define NM_DBUS_PATH "/org/freedesktop/NetworkManager" -#define NM_DBUS_INTERFACE "org.freedesktop.NetworkManager" -#define NM_DBUS_INTERFACE_DEVICE NM_DBUS_INTERFACE ".Device" -#define NM_DBUS_INTERFACE_DEVICE_WIRED NM_DBUS_INTERFACE_DEVICE ".Wired" -#define NM_DBUS_INTERFACE_DEVICE_WIRELESS NM_DBUS_INTERFACE_DEVICE ".Wireless" -#define NM_DBUS_PATH_ACCESS_POINT NM_DBUS_PATH "/AccessPoint" -#define NM_DBUS_INTERFACE_ACCESS_POINT NM_DBUS_INTERFACE ".AccessPoint" - -#define NM_DBUS_PATH_SETTINGS "/org/freedesktop/NetworkManagerSettings" - -#define NM_DBUS_IFACE_SETTINGS_CONNECTION "org.freedesktop.NetworkManagerSettings.Connection" -#define NM_DBUS_IFACE_SETTINGS "org.freedesktop.NetworkManagerSettings" -#define NM_DBUS_INTERFACE_ACTIVE_CONNECTION NM_DBUS_INTERFACE ".Connection.Active" -#define NM_DBUS_INTERFACE_IP4_CONFIG NM_DBUS_INTERFACE ".IP4Config" - -#define NM_DBUS_SERVICE_USER_SETTINGS "org.freedesktop.NetworkManagerUserSettings" -#define NM_DBUS_SERVICE_SYSTEM_SETTINGS "org.freedesktop.NetworkManagerSystemSettings" - -#define NM_802_11_AP_FLAGS_NONE 0x00000000 -#define NM_802_11_AP_FLAGS_PRIVACY 0x00000001 -#endif - -QTM_BEGIN_NAMESPACE -typedef QMap< QString, QMap > QNmSettingsMap; -typedef QList ServerThing; -QTM_END_NAMESPACE - - -Q_DECLARE_METATYPE(QTM_PREPEND_NAMESPACE(QNmSettingsMap)) -Q_DECLARE_METATYPE(QTM_PREPEND_NAMESPACE(ServerThing)) - -QTM_BEGIN_NAMESPACE - -class QNetworkManagerInterfacePrivate; -class QNetworkManagerInterface : public QObject -{ - Q_OBJECT - -public: - - QNetworkManagerInterface(QObject *parent = 0); - ~QNetworkManagerInterface(); - - QList getDevices() const; - void activateConnection(const QString &serviceName, QDBusObjectPath connection, QDBusObjectPath device, QDBusObjectPath specificObject); - void deactivateConnection(QDBusObjectPath connectionPath) const; - - QDBusObjectPath path() const; - QDBusInterface *connectionInterface() const; - - bool wirelessEnabled() const; - bool wirelessHardwareEnabled() const; - QList activeConnections() const; - quint32 state(); - bool setConnections(); - bool isValid(); - -Q_SIGNALS: - void deviceAdded(QDBusObjectPath); - void deviceRemoved(QDBusObjectPath); - void propertiesChanged( const QString &, QMap); - void stateChanged(const QString&, quint32); - void activationFinished(QDBusPendingCallWatcher*); - -private Q_SLOTS: -private: - QNetworkManagerInterfacePrivate *d; - QNmDBusHelper *nmDBusHelper; -}; - -class QNetworkManagerInterfaceAccessPointPrivate; -class QNetworkManagerInterfaceAccessPoint : public QObject -{ - Q_OBJECT - -public: - - enum DeviceState { - Unknown = 0, - Unmanaged, - Unavailable, - Disconnected, - Prepare, - Config, - NeedAuthentication, - IpConfig, - Activated, - Failed - }; - - enum ApFlag { - ApNone = 0x0, - Privacy = 0x1 - }; - - Q_DECLARE_FLAGS(ApFlags, ApFlag); - - enum ApSecurityFlag { - ApSecurityNone = 0x0, - PairWep40 = 0x1, - PairWep104 = 0x2, - PairTkip = 0x4, - PairCcmp = 0x8, - GroupWep40 = 0x10, - GroupWep104 = 0x20, - GroupTkip = 0x40, - GroupCcmp = 0x80, - KeyPsk = 0x100, - Key8021x = 0x200 - }; - - Q_DECLARE_FLAGS(ApSecurityFlags, ApSecurityFlag); - - explicit QNetworkManagerInterfaceAccessPoint(const QString &dbusPathName, QObject *parent = 0); - ~QNetworkManagerInterfaceAccessPoint(); - - QDBusInterface *connectionInterface() const; - - quint32 flags() const; - quint32 wpaFlags() const; - quint32 rsnFlags() const; - QString ssid() const; - quint32 frequency() const; - QString hwAddress() const; - quint32 mode() const; - quint32 maxBitrate() const; - quint32 strength() const; - bool setConnections(); - bool isValid(); - -Q_SIGNALS: - void propertiesChanged(QMap ); - void propertiesChanged( const QString &, QMap); -private: - QNetworkManagerInterfaceAccessPointPrivate *d; - QNmDBusHelper *nmDBusHelper; - -}; - -class QNetworkManagerInterfaceDevicePrivate; -class QNetworkManagerInterfaceDevice : public QObject -{ - Q_OBJECT - -public: - - explicit QNetworkManagerInterfaceDevice(const QString &deviceObjectPath, QObject *parent = 0); - ~QNetworkManagerInterfaceDevice(); - - QString udi() const; - QNetworkInterface networkInterface() const; - QDBusInterface *connectionInterface() const; - quint32 ip4Address() const; - quint32 state() const; - quint32 deviceType() const; - - QDBusObjectPath ip4config() const; - bool setConnections(); - bool isValid(); - -Q_SIGNALS: - void stateChanged(const QString &, quint32); - -private: - QNetworkManagerInterfaceDevicePrivate *d; - QNmDBusHelper *nmDBusHelper; -}; - -class QNetworkManagerInterfaceDeviceWiredPrivate; -class QNetworkManagerInterfaceDeviceWired : public QObject -{ - Q_OBJECT - -public: - - explicit QNetworkManagerInterfaceDeviceWired(const QString &ifaceDevicePath, - QObject *parent = 0); - ~QNetworkManagerInterfaceDeviceWired(); - - QDBusInterface *connectionInterface() const; - QString hwAddress() const; - quint32 speed() const; - bool carrier() const; - bool setConnections(); - bool isValid(); - -Q_SIGNALS: - void propertiesChanged( const QString &, QMap); -private: - QNetworkManagerInterfaceDeviceWiredPrivate *d; - QNmDBusHelper *nmDBusHelper; -}; - -class QNetworkManagerInterfaceDeviceWirelessPrivate; -class QNetworkManagerInterfaceDeviceWireless : public QObject -{ - Q_OBJECT - -public: - - enum DeviceCapability { - None = 0x0, - Wep40 = 0x1, - Wep104 = 0x2, - Tkip = 0x4, - Ccmp = 0x8, - Wpa = 0x10, - Rsn = 0x20 - }; - - explicit QNetworkManagerInterfaceDeviceWireless(const QString &ifaceDevicePath, - QObject *parent = 0); - ~QNetworkManagerInterfaceDeviceWireless(); - - QDBusObjectPath path() const; - QList getAccessPoints(); - QDBusInterface *connectionInterface() const; - - QString hwAddress() const; - quint32 mode() const; - quint32 bitrate() const; - QDBusObjectPath activeAccessPoint() const; - quint32 wirelessCapabilities() const; - bool setConnections(); - bool isValid(); - -Q_SIGNALS: - void propertiesChanged( const QString &, QMap); - void accessPointAdded(const QString &,QDBusObjectPath); - void accessPointRemoved(const QString &,QDBusObjectPath); -private: - QNetworkManagerInterfaceDeviceWirelessPrivate *d; - QNmDBusHelper *nmDBusHelper; -}; - -class QNetworkManagerSettingsPrivate; -class QNetworkManagerSettings : public QObject -{ - Q_OBJECT - -public: - - explicit QNetworkManagerSettings(const QString &settingsService, QObject *parent = 0); - ~QNetworkManagerSettings(); - - QDBusInterface *connectionInterface() const; - QList listConnections(); - bool setConnections(); - bool isValid(); - -Q_SIGNALS: - void newConnection(QDBusObjectPath); -private: - QNetworkManagerSettingsPrivate *d; -}; - -class QNetworkManagerSettingsConnectionPrivate; -class QNetworkManagerSettingsConnection : public QObject -{ - Q_OBJECT - -public: - - QNetworkManagerSettingsConnection(const QString &settingsService, const QString &connectionObjectPath, QObject *parent = 0); - ~QNetworkManagerSettingsConnection(); - - QDBusInterface *connectionInterface() const; - QNmSettingsMap getSettings(); - bool setConnections(); - NMDeviceType getType(); - bool isAutoConnect(); - quint64 getTimestamp(); - QString getId(); - QString getUuid(); - QString getSsid(); - QString getMacAddress(); - QStringList getSeenBssids(); - bool isValid(); - -Q_SIGNALS: - - void updated(QMap< QString, QMap > s); - void removed(const QString &); - -private: - QNmDBusHelper *nmDBusHelper; - QNetworkManagerSettingsConnectionPrivate *d; -}; - -class QNetworkManagerConnectionActivePrivate; -class QNetworkManagerConnectionActive : public QObject -{ - Q_OBJECT - -public: - - enum ActiveConnectionState { - Unknown = 0, - Activating = 1, - Activated = 2 - }; - - explicit QNetworkManagerConnectionActive(const QString &dbusPathName, QObject *parent = 0); - ~ QNetworkManagerConnectionActive(); - - QDBusInterface *connectionInterface() const; - QString serviceName() const; - QDBusObjectPath connection() const; - QDBusObjectPath specificObject() const; - QList devices() const; - quint32 state() const; - bool defaultRoute() const; - bool setConnections(); - bool isValid(); - - -Q_SIGNALS: - void propertiesChanged(QList); - void propertiesChanged( const QString &, QMap); -private: - QNetworkManagerConnectionActivePrivate *d; - QNmDBusHelper *nmDBusHelper; -}; - -class QNetworkManagerIp4ConfigPrivate; -class QNetworkManagerIp4Config : public QObject -{ - Q_OBJECT - -public: - explicit QNetworkManagerIp4Config(const QString &dbusPathName, QObject *parent = 0); - ~QNetworkManagerIp4Config(); - - QStringList domains() const; - bool isValid(); - - private: - QNetworkManagerIp4ConfigPrivate *d; -}; -QTM_END_NAMESPACE - - -#endif //QNETWORKMANAGERSERVICE_H diff --git a/src/bearer/qnetworksession.cpp b/src/bearer/qnetworksession.cpp index 9dedff1..3c02340 100644 --- a/src/bearer/qnetworksession.cpp +++ b/src/bearer/qnetworksession.cpp @@ -39,18 +39,7 @@ ** ****************************************************************************/ -#include -#include - -#include "qnetworksession.h" - -#ifdef Q_OS_SYMBIAN -#include "qnetworksession_s60_p.h" -#elif defined(Q_WS_MAEMO_6) || defined(Q_WS_MAEMO_5) -#include "qnetworksession_maemo_p.h" -#else #include "qnetworksession_p.h" -#endif QTM_BEGIN_NAMESPACE @@ -229,12 +218,18 @@ QTM_BEGIN_NAMESPACE QNetworkSession::QNetworkSession(const QNetworkConfiguration& connectionConfig, QObject* parent) : QObject(parent) { - d = new QNetworkSessionPrivate; + d = new QNetworkSessionPrivate(connectionConfig); d->q = this; - d->publicConfig = connectionConfig; - d->syncStateWithInterface(); - QObject::connect(d, SIGNAL(quitPendingWaitsForOpened()), - this, SIGNAL(opened())); + //connect implementation signals to ours... + QObject::connect(&(d->impl), SIGNAL(opened()), this, SIGNAL(opened())); + QObject::connect(&(d->impl), SIGNAL(closed()), this, SIGNAL(closed())); + QObject::connect(&(d->impl), SIGNAL(newConfigurationActivated()), this, SIGNAL(newConfigurationActivated())); + //and ones requiring translation + QObject::connect(&(d->impl), SIGNAL(stateChanged(QNetworkSession::State)), + d, SLOT(_q_stateChanged(QNetworkSession::State))); + QObject::connect(&(d->impl), SIGNAL(error(QNetworkSession::SessionError)), + d, SLOT(_q_error(QNetworkSession::SessionError))); + //preferredConfigurationChanged is not connected here because it has side effects, see connectNotify } /*! @@ -264,7 +259,7 @@ QNetworkSession::~QNetworkSession() */ void QNetworkSession::open() { - d->open(); + d->impl.open(); } /*! @@ -286,27 +281,7 @@ void QNetworkSession::open() */ bool QNetworkSession::waitForOpened(int msecs) { - if (d->isOpen) - return true; - - if (d->state != Connecting) - return false; - - QEventLoop* loop = new QEventLoop(this); - QObject::connect(d, SIGNAL(quitPendingWaitsForOpened()), - loop, SLOT(quit())); - QObject::connect(this, SIGNAL(error(QNetworkSession::SessionError)), - loop, SLOT(quit())); - - //final call - if (msecs>=0) - QTimer::singleShot(msecs, loop, SLOT(quit())); - - loop->exec(); - loop->disconnect(); - loop->deleteLater(); - - return d->isOpen; + return d->impl.waitForOpened(msecs); } /*! @@ -325,7 +300,7 @@ bool QNetworkSession::waitForOpened(int msecs) */ void QNetworkSession::close() { - d->close(); + d->impl.close(); } /*! @@ -340,7 +315,7 @@ void QNetworkSession::close() */ void QNetworkSession::stop() { - d->stop(); + d->impl.stop(); } /*! @@ -350,7 +325,7 @@ void QNetworkSession::stop() */ QNetworkConfiguration QNetworkSession::configuration() const { - return d->publicConfig; + return d->impl.configuration(); } /* @@ -419,7 +394,7 @@ QNetworkConfiguration QNetworkSession::configuration() const */ QNetworkInterface QNetworkSession::interface() const { - return d->currentInterface(); + return d->impl.interface(); } /*! @@ -430,7 +405,7 @@ QNetworkInterface QNetworkSession::interface() const */ bool QNetworkSession::isOpen() const { - return d->isOpen; + return d->impl.isOpen(); } /*! @@ -452,7 +427,7 @@ bool QNetworkSession::isOpen() const */ QNetworkSession::State QNetworkSession::state() const { - return d->state; + return (QNetworkSession::State)d->impl.state(); } /*! @@ -462,7 +437,7 @@ QNetworkSession::State QNetworkSession::state() const */ QNetworkSession::SessionError QNetworkSession::error() const { - return d->error(); + return (QNetworkSession::SessionError)d->impl.error(); } /*! @@ -473,7 +448,7 @@ QNetworkSession::SessionError QNetworkSession::error() const */ QString QNetworkSession::errorString() const { - return d->errorString(); + return d->impl.errorString(); } /*! @@ -531,27 +506,8 @@ QString QNetworkSession::errorString() const */ QVariant QNetworkSession::sessionProperty(const QString& key) const { - if (!d->publicConfig.isValid()) - return QVariant(); - - if (key == "ActiveConfiguration") { - if (!d->isOpen) - return QString(); - else - return d->activeConfig.identifier(); - } - - if (key == "UserChoiceConfiguration") { - if (!d->isOpen || d->publicConfig.type() != QNetworkConfiguration::UserChoice) - return QString(); - - if (d->serviceConfig.isValid()) - return d->serviceConfig.identifier(); - else - return d->activeConfig.identifier(); - } - - return d->sessionProperty(key); + //all the public documented properties are string/bool so this should be safe + return d->impl.sessionProperty(key); } /*! @@ -564,11 +520,7 @@ QVariant QNetworkSession::sessionProperty(const QString& key) const */ void QNetworkSession::setSessionProperty(const QString& key, const QVariant& value) { - if (key == "ActiveConfiguration" - || key == "UserChoiceConfiguration") - return; - - d->setSessionProperty(key, value); + d->impl.setSessionProperty(key, value); } /*! @@ -581,7 +533,7 @@ void QNetworkSession::setSessionProperty(const QString& key, const QVariant& val */ void QNetworkSession::migrate() { - d->migrate(); + d->impl.migrate(); } /*! @@ -593,7 +545,7 @@ void QNetworkSession::ignore() { // Needed on at least Symbian platform: the roaming must be explicitly // ignore()'d or migrate()'d - d->ignore(); + d->impl.ignore(); } /*! @@ -606,7 +558,7 @@ void QNetworkSession::ignore() */ void QNetworkSession::accept() { - d->accept(); + d->impl.accept(); } /*! @@ -618,7 +570,7 @@ void QNetworkSession::accept() */ void QNetworkSession::reject() { - d->reject(); + d->impl.reject(); } @@ -638,7 +590,7 @@ void QNetworkSession::reject() */ quint64 QNetworkSession::bytesWritten() const { - return d->bytesWritten(); + return d->impl.bytesWritten(); } /*! @@ -657,7 +609,7 @@ quint64 QNetworkSession::bytesWritten() const */ quint64 QNetworkSession::bytesReceived() const { - return d->bytesReceived(); + return d->impl.bytesReceived(); } /*! @@ -665,7 +617,7 @@ quint64 QNetworkSession::bytesReceived() const */ quint64 QNetworkSession::activeTime() const { - return d->activeTime(); + return d->impl.activeTime(); } /*! @@ -683,12 +635,11 @@ void QNetworkSession::connectNotify(const char *signal) { QObject::connectNotify(signal); //check for preferredConfigurationChanged() signal connect notification - //This is not required on all platforms -#ifdef Q_OS_SYMBIAN if (qstrcmp(signal, SIGNAL(preferredConfigurationChanged(QNetworkConfiguration,bool))) == 0) { - d->setALREnabled(true); + //connecting the implementation signal here allows implementation's connectNotify trigger to enable app level roaming + QObject::connect(&(d->impl), SIGNAL(preferredConfigurationChanged(const QNetworkConfiguration&, bool)), + d, SLOT(_q_preferredConfigurationChanged(const QNetworkConfiguration&, bool))); } -#endif } /*! @@ -703,14 +654,36 @@ void QNetworkSession::disconnectNotify(const char *signal) { QObject::disconnectNotify(signal); //check for preferredConfigurationChanged() signal disconnect notification - //This is not required on all platforms #ifdef Q_OS_SYMBIAN if (qstrcmp(signal, SIGNAL(preferredConfigurationChanged(QNetworkConfiguration,bool))) == 0) { - d->setALREnabled(false); + //disconnecting the implementation signal here allows implementation's connectNotify trigger to disable app level roaming + QObject::disconnect(&(d->impl), SIGNAL(preferredConfigurationChanged(const QNetworkConfiguration&, bool)), + d, SLOT(_q_preferredConfigurationChanged(const QNetworkConfiguration&, bool))); } #endif } +QNetworkSessionPrivate::QNetworkSessionPrivate(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config) + : impl(config) +{ +} + +void QNetworkSessionPrivate::_q_stateChanged(QT_PREPEND_NAMESPACE(QNetworkSession::State) state) +{ + emit q->stateChanged((QNetworkSession::State)state); +} + +void QNetworkSessionPrivate::_q_error(QT_PREPEND_NAMESPACE(QNetworkSession::SessionError) err) +{ + emit q->error(QNetworkSession::SessionError(err)); +} + +void QNetworkSessionPrivate::_q_preferredConfigurationChanged(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config, bool isSeamless) +{ + emit q->preferredConfigurationChanged(config, isSeamless); +} + #include "moc_qnetworksession.cpp" +#include "moc_qnetworksession_p.cpp" QTM_END_NAMESPACE diff --git a/src/bearer/qnetworksession.h b/src/bearer/qnetworksession.h index 8df3644..0459187 100644 --- a/src/bearer/qnetworksession.h +++ b/src/bearer/qnetworksession.h @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#ifndef QNETWORKSESSION_H -#define QNETWORKSESSION_H +#ifndef QTM_NETWORKSESSION_H +#define QTM_NETWORKSESSION_H #include "qmobilityglobal.h" @@ -131,4 +131,4 @@ QTM_END_NAMESPACE QT_END_HEADER -#endif //QNETWORKSESSION_H +#endif //QTM_NETWORKSESSION_H diff --git a/src/bearer/qnetworksession_maemo.cpp b/src/bearer/qnetworksession_maemo.cpp deleted file mode 100644 index 96bfa6b..0000000 --- a/src/bearer/qnetworksession_maemo.cpp +++ /dev/null @@ -1,1038 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "qnetworksession_maemo_p.h" - -#include -#include -#include - -#include -#include -#include - - -QDBusArgument &operator<<(QDBusArgument &argument, - const QtMobility::ICd2DetailsDBusStruct &icd2) -{ - argument.beginStructure(); - argument << icd2.serviceType; - argument << icd2.serviceAttributes; - argument << icd2.setviceId; - argument << icd2.networkType; - argument << icd2.networkAttributes; - argument << icd2.networkId; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, - QtMobility::ICd2DetailsDBusStruct &icd2) -{ - argument.beginStructure(); - argument >> icd2.serviceType; - argument >> icd2.serviceAttributes; - argument >> icd2.setviceId; - argument >> icd2.networkType; - argument >> icd2.networkAttributes; - argument >> icd2.networkId; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, - QtMobility::ICd2DetailsList &detailsList) -{ - argument.beginArray(); - detailsList.clear(); - - while (!argument.atEnd()) { - QtMobility::ICd2DetailsDBusStruct element; - argument >> element; - detailsList.append(element); - } - - argument.endArray(); - return argument; -} - -QDBusArgument &operator<<(QDBusArgument &argument, - const QtMobility::ICd2DetailsList &detailsList) -{ - argument.beginArray(qMetaTypeId()); - for (int i = 0; i < detailsList.count(); ++i) - argument << detailsList[i]; - argument.endArray(); - return argument; -} - -QTM_BEGIN_NAMESPACE - -static QHash properties; - -static QString get_network_interface(); - -void QNetworkSessionPrivate::iapStateChanged(const QString& iapid, uint icd_connection_state) -{ - if ((publicConfig.type() == QNetworkConfiguration::UserChoice) && opened) { - updateIdentifier(iapid); - } - - if (((publicConfig.type() == QNetworkConfiguration::UserChoice) && (activeConfig.d->id == iapid)) || - (publicConfig.d->id == iapid)) { - switch (icd_connection_state) { - case ICD_STATE_CONNECTING: - updateState(QNetworkSession::Connecting); - break; - case ICD_STATE_CONNECTED: - updateState(QNetworkSession::Connected); - break; - case ICD_STATE_DISCONNECTING: - updateState(QNetworkSession::Closing); - break; - case ICD_STATE_DISCONNECTED: - updateState(QNetworkSession::Disconnected); - break; - default: - break; - } - } -} - -void QNetworkSessionPrivate::cleanupSession(void) -{ - QObject::disconnect(q, SIGNAL(stateChanged(QNetworkSession::State)), this, SLOT(updateProxies(QNetworkSession::State))); -} - - -void QNetworkSessionPrivate::updateState(QNetworkSession::State newState) -{ - if (newState != state) { - if (newState == QNetworkSession::Disconnected) { - if (isOpen) { - // The Session was aborted by the user or system - lastError = QNetworkSession::SessionAbortedError; - emit q->error(lastError); - emit q->closed(); - } - if (m_stopTimer.isActive()) { - // Session was closed by calling stop() - m_stopTimer.stop(); - } - isOpen = false; - opened = false; - currentNetworkInterface.clear(); - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - copyConfig(publicConfig, activeConfig); - activeConfig.d->state = QNetworkConfiguration::Defined; - } else { - if (!activeConfig.isValid()) { - // Active configuration (IAP) was removed from system - // => Connection was disconnected and configuration became - // invalid - // => Also Session state must be changed to invalid - newState = QNetworkSession::Invalid; - } - } - } else if (newState == QNetworkSession::Connected) { - if (opened) { - isOpen = true; - } - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - activeConfig.d->state = QNetworkConfiguration::Active; - activeConfig.d->type = QNetworkConfiguration::InternetAccessPoint; - } - publicConfig.d->state = QNetworkConfiguration::Active; - } - - if (newState != state) { - state = newState; - emit q->stateChanged(newState); - } - } -} - - -void QNetworkSessionPrivate::updateIdentifier(const QString &newId) -{ - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - activeConfig.d->network_attrs |= ICD_NW_ATTR_IAPNAME; - activeConfig.d->id = newId; - } else { - publicConfig.d->network_attrs |= ICD_NW_ATTR_IAPNAME; - if (publicConfig.d->id != newId) { - qWarning() << "Your config id changed from" << publicConfig.d->id << "to" << newId; - publicConfig.d->id = newId; - } - } -} - - -QNetworkSessionPrivate::Statistics QNetworkSessionPrivate::getStatistics() const -{ - /* This could be also implemented by using the Maemo::Icd::statistics() - * that gets the statistics data for a specific IAP. Change if - * necessary. - */ - Maemo::Icd icd; - QList stats_results; - Statistics stats = { 0, 0, 0}; - - if (!icd.statistics(stats_results)) - return stats; - - foreach (const Maemo::IcdStatisticsResult &res, stats_results) { - if (res.params.network_attrs & ICD_NW_ATTR_IAPNAME) { - /* network_id is the IAP UUID */ - if (QString(res.params.network_id.data()) == activeConfig.identifier()) { - stats.txData = res.bytes_sent; - stats.rxData = res.bytes_received; - stats.activeTime = res.time_active; - } - } else { - /* We probably will never get to this branch */ - QNetworkConfigurationPrivate *d = activeConfig.d.data(); - if (res.params.network_id == d->network_id) { - stats.txData = res.bytes_sent; - stats.rxData = res.bytes_received; - stats.activeTime = res.time_active; - } - } - } - - return stats; -} - - -quint64 QNetworkSessionPrivate::bytesWritten() const -{ - return getStatistics().txData; -} - -quint64 QNetworkSessionPrivate::bytesReceived() const -{ - return getStatistics().rxData; -} - -quint64 QNetworkSessionPrivate::activeTime() const -{ - return getStatistics().activeTime; -} - - -QNetworkConfiguration& QNetworkSessionPrivate::copyConfig(QNetworkConfiguration &fromConfig, QNetworkConfiguration &toConfig, bool deepCopy) -{ - if (deepCopy) { - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - QExplicitlySharedDataPointer ptr(cpPriv); - toConfig.d = ptr; - } - - toConfig.d->name = fromConfig.d->name; - toConfig.d->isValid = fromConfig.d->isValid; - // Note that we do not copy id field here as the publicConfig does - // not contain a valid IAP id. - toConfig.d->state = fromConfig.d->state; - toConfig.d->type = fromConfig.d->type; - toConfig.d->roamingSupported = fromConfig.d->roamingSupported; - toConfig.d->purpose = fromConfig.d->purpose; - toConfig.d->network_id = fromConfig.d->network_id; - toConfig.d->iap_type = fromConfig.d->iap_type; - toConfig.d->network_attrs = fromConfig.d->network_attrs; - toConfig.d->service_type = fromConfig.d->service_type; - toConfig.d->service_id = fromConfig.d->service_id; - toConfig.d->service_attrs = fromConfig.d->service_attrs; - toConfig.d->manager = fromConfig.d->manager; - - return toConfig; -} - - -/* This is called by QNetworkSession constructor and it updates the current - * state of the configuration. - */ -void QNetworkSessionPrivate::syncStateWithInterface() -{ - /* Initially we are not active although the configuration might be in - * connected state. - */ - isOpen = false; - opened = false; - - QObject::connect(&manager, SIGNAL(updateCompleted()), this, SLOT(networkConfigurationsChanged())); - - if (publicConfig.d.data()) { - QNetworkConfigurationManagerPrivate* mgr = (QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager; - if (mgr) { - connect(mgr, SIGNAL(iapStateChanged(const QString&, uint)), - this, SLOT(iapStateChanged(const QString&, uint))); - } else { - qWarning()<<"Manager object not set when trying to connect iapStateChanged signal. Your configuration object is not correctly setup, did you remember to call manager.updateConfigurations() before creating session object?"; - state = QNetworkSession::Invalid; - lastError = QNetworkSession::UnknownSessionError; - return; - } - } - - QObject::connect(q, SIGNAL(stateChanged(QNetworkSession::State)), this, SLOT(updateProxies(QNetworkSession::State))); - - state = QNetworkSession::Invalid; - lastError = QNetworkSession::UnknownSessionError; - - switch (publicConfig.type()) { - case QNetworkConfiguration::InternetAccessPoint: - activeConfig = publicConfig; - break; - case QNetworkConfiguration::ServiceNetwork: - serviceConfig = publicConfig; - break; - case QNetworkConfiguration::UserChoice: - // active config will contain correct data after open() has succeeded - copyConfig(publicConfig, activeConfig); - - /* We create new configuration that holds the actual configuration - * returned by icd. This way publicConfig still contains the - * original user specified configuration. - * - * Note that the new activeConfig configuration is not inserted - * to configurationManager as manager class will get the newly - * connected configuration from gconf when the IAP is saved. - * This configuration manager update is done by IapMonitor class. - * If the ANY connection fails in open(), then the configuration - * data is not saved to gconf and will not be added to - * configuration manager IAP list. - */ -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug()<<"New configuration created for" << publicConfig.identifier(); -#endif - break; - default: - /* Invalid configuration, no point continuing */ - return; - } - - if (!activeConfig.isValid()) - return; - - /* Get the initial state from icd */ - Maemo::Icd icd; - QList state_results; - - /* Update the active config from first connection, this is ok as icd - * supports only one connection anyway. - */ - if (icd.state(state_results) && !state_results.isEmpty()) { - /* If we did not get full state back, then we are not - * connected and can skip the next part. - */ - if (!(state_results.first().params.network_attrs == 0 && - state_results.first().params.network_id.isEmpty())) { - - /* If we try to connect to specific IAP and we get results back - * that tell the icd is actually connected to another IAP, - * then do not update current state etc. - */ - if (publicConfig.type() == QNetworkConfiguration::UserChoice || - publicConfig.d->id == state_results.first().params.network_id) { - switch (state_results.first().state) { - case ICD_STATE_DISCONNECTED: - state = QNetworkSession::Disconnected; - if (activeConfig.d.data()) - activeConfig.d->isValid = true; - break; - case ICD_STATE_CONNECTING: - state = QNetworkSession::Connecting; - if (activeConfig.d.data()) - activeConfig.d->isValid = true; - break; - case ICD_STATE_CONNECTED: - { - if (!state_results.first().error.isEmpty()) - break; - - const QString id = state_results.first().params.network_id; - - QNetworkConfigurationManagerPrivate *mgr = (QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager; - if (mgr->accessPointConfigurations.contains(id)) { - //we don't want the copied data if the config is already known by the manager - //just reuse it so that existing references to the old data get the same update - QExplicitlySharedDataPointer priv = mgr->accessPointConfigurations.value(id); - activeConfig.d = priv; - } - - state = QNetworkSession::Connected; - activeConfig.d->network_id = state_results.first().params.network_id; - activeConfig.d->id = activeConfig.d->network_id; - activeConfig.d->network_attrs = state_results.first().params.network_attrs; - activeConfig.d->iap_type = state_results.first().params.network_type; - activeConfig.d->service_type = state_results.first().params.service_type; - activeConfig.d->service_id = state_results.first().params.service_id; - activeConfig.d->service_attrs = state_results.first().params.service_attrs; - activeConfig.d->type = QNetworkConfiguration::InternetAccessPoint; - activeConfig.d->state = QNetworkConfiguration::Active; - activeConfig.d->isValid = true; - currentNetworkInterface = get_network_interface(); - - Maemo::IAPConf iap_name(activeConfig.d->id); - QString name_value = iap_name.value("name").toString(); - if (!name_value.isEmpty()) - activeConfig.d->name = name_value; - else - activeConfig.d->name = activeConfig.d->id; - - // Add the new active configuration to manager or update the old config - mgr = (QNetworkConfigurationManagerPrivate*)activeConfig.d.data()->manager; - if (!(mgr->accessPointConfigurations.contains(activeConfig.d->id))) { - QExplicitlySharedDataPointer ptr = activeConfig.d; - mgr->accessPointConfigurations.insert(activeConfig.d->id, ptr); - - QNetworkConfiguration item; - item.d = ptr; - emit mgr->configurationAdded(item); - -#ifdef BEARER_MANAGEMENT_DEBUG - //qDebug()<<"New configuration"<id<<"added to manager in sync"; -#endif - - } - } - break; - - case ICD_STATE_DISCONNECTING: - state = QNetworkSession::Closing; - if (activeConfig.d.data()) - activeConfig.d->isValid = true; - break; - default: - break; - } - } - } else { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "status_req tells icd is not connected"; -#endif - } - } else { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "status_req did not return any results from icd"; -#endif - } - - networkConfigurationsChanged(); -} - - -void QNetworkSessionPrivate::networkConfigurationsChanged() -{ - if (serviceConfig.isValid()) - updateStateFromServiceNetwork(); - else - updateStateFromActiveConfig(); -} - - -void QNetworkSessionPrivate::updateStateFromServiceNetwork() -{ - QNetworkSession::State oldState = state; - - foreach (const QNetworkConfiguration &config, serviceConfig.children()) { - if ((config.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active) - continue; - - if (activeConfig != config) { - activeConfig = config; - emit q->newConfigurationActivated(); - } - - state = QNetworkSession::Connected; - if (state != oldState) - emit q->stateChanged(state); - - return; - } - - if (serviceConfig.children().isEmpty()) - state = QNetworkSession::NotAvailable; - else - state = QNetworkSession::Disconnected; - - if (state != oldState) - emit q->stateChanged(state); -} - - -void QNetworkSessionPrivate::clearConfiguration(QNetworkConfiguration &config) -{ - config.d->network_id.clear(); - config.d->iap_type.clear(); - config.d->network_attrs = 0; - config.d->service_type.clear(); - config.d->service_id.clear(); - config.d->service_attrs = 0; -} - - -void QNetworkSessionPrivate::updateStateFromActiveConfig() -{ - QNetworkSession::State oldState = state; - - bool newActive = false; - - if (!activeConfig.d.data()) - return; - - if (!activeConfig.isValid()) { - state = QNetworkSession::Invalid; - clearConfiguration(activeConfig); - } else if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - state = QNetworkSession::Connected; - newActive = opened; - } else if ((activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) { - state = QNetworkSession::Disconnected; - } else if ((activeConfig.state() & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) { - state = QNetworkSession::NotAvailable; - } else if ((activeConfig.state() & QNetworkConfiguration::Undefined) == QNetworkConfiguration::Undefined) { - state = QNetworkSession::NotAvailable; - } - - bool oldActive = isOpen; - isOpen = newActive; - - if (!oldActive && isOpen) - emit quitPendingWaitsForOpened(); - - if (oldActive && !isOpen) - emit q->closed(); - - if (oldState != state) { - emit q->stateChanged(state); - - if (state == QNetworkSession::Disconnected && oldActive) { -#ifdef BEARER_MANAGEMENT_DEBUG - //qDebug()<<"session aborted error emitted for"<error(lastError); - } - } - -#ifdef BEARER_MANAGEMENT_DEBUG - //qDebug()<<"oldState ="<ifa_next) { - if (ifa->ifa_addr) { - family = ifa->ifa_addr->sa_family; - if (family != AF_INET) { - continue; /* Currently only IPv4 is supported by icd dbus interface */ - } - if (((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr == addr.s_addr) { - iface = QString(ifa->ifa_name); - break; - } - } - } - - freeifaddrs(ifaddr); - return iface; -} - - -void QNetworkSessionPrivate::open() -{ - if (m_stopTimer.isActive()) { - m_stopTimer.stop(); - } - if (!publicConfig.isValid()) { - lastError = QNetworkSession::InvalidConfigurationError; - emit q->error(lastError); - return; - } - if (serviceConfig.isValid()) { - lastError = QNetworkSession::OperationNotSupportedError; - emit q->error(lastError); - } else if (!isOpen) { - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - /* Caller is trying to connect to default IAP. - * At this time we will not know the IAP details so we just - * connect and update the active config when the IAP is - * connected. - */ - opened = true; - state = QNetworkSession::Connecting; - emit q->stateChanged(state); - QTimer::singleShot(0, this, SLOT(do_open())); - return; - } - - /* User is connecting to one specific IAP. If that IAP is not - * in discovered state we cannot continue. - */ - if ((activeConfig.state() & QNetworkConfiguration::Discovered) != - QNetworkConfiguration::Discovered) { - lastError =QNetworkSession::InvalidConfigurationError; - emit q->error(lastError); - return; - } - opened = true; - - if ((activeConfig.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active) { - state = QNetworkSession::Connecting; - emit q->stateChanged(state); - QTimer::singleShot(0, this, SLOT(do_open())); - return; - } - isOpen = (activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active; - if (isOpen) - emit quitPendingWaitsForOpened(); - } else { - /* We seem to be active so inform caller */ - emit quitPendingWaitsForOpened(); - } -} - -void QNetworkSessionPrivate::do_open() -{ - icd_connection_flags flags = connectFlags; - QString iap = publicConfig.identifier(); - - if (state == QNetworkSession::Connected) { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "Already connected to" << activeConfig.identifier(); -#endif - emit q->stateChanged(QNetworkSession::Connected); - emit quitPendingWaitsForOpened(); - return; - } - - if (publicConfig.type() == QNetworkConfiguration::UserChoice) - config = activeConfig; - else - config = publicConfig; - - if (iap == OSSO_IAP_ANY) { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "connecting to default IAP" << iap; -#endif - m_connectRequestTimer.start(ICD_LONG_CONNECT_TIMEOUT); - m_dbusInterface->asyncCall(ICD_DBUS_API_CONNECT_REQ, (uint)flags); // Return value ignored - m_asynchCallActive = true; - } else { - ICd2DetailsDBusStruct icd2; - icd2.serviceType = config.d->service_type; - icd2.serviceAttributes = config.d->service_attrs; - icd2.setviceId = config.d->service_id; - icd2.networkType = config.d->iap_type; - icd2.networkAttributes = config.d->network_attrs; - if (config.d->network_attrs & ICD_NW_ATTR_IAPNAME) { - icd2.networkId = QByteArray(iap.toLatin1()); - } else { - icd2.networkId = config.d->network_id; - } - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug("connecting to %s/%s/0x%x/%s/0x%x/%s", - icd2.networkId.data(), - icd2.networkType.toAscii().constData(), - icd2.networkAttributes, - icd2.serviceType.toAscii().constData(), - icd2.serviceAttributes, - icd2.setviceId.toAscii().constData()); -#endif - - ICd2DetailsList paramArray; - paramArray.append(icd2); - m_connectRequestTimer.start(ICD_LONG_CONNECT_TIMEOUT); - m_dbusInterface->asyncCall(ICD_DBUS_API_CONNECT_REQ, (uint)flags, QVariant::fromValue(paramArray)); // Return value ignored - m_asynchCallActive = true; - } -} - - void QNetworkSessionPrivate::stateChange(const QDBusMessage& rep) -{ - if (m_asynchCallActive == true) { - if (m_connectRequestTimer.isActive()) - m_connectRequestTimer.stop(); - m_asynchCallActive = false; - - QString result = rep.arguments().at(5).toString(); // network id or empty string - QString connected_iap = result; - if (connected_iap.isEmpty()) { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "connect to"<< publicConfig.identifier() << "failed, result is empty"; -#endif - updateState(QNetworkSession::Disconnected); - emit q->error(QNetworkSession::SessionAbortedError); - if (publicConfig.type() == QNetworkConfiguration::UserChoice) - copyConfig(publicConfig, activeConfig); - return; - } - - /* If the user tried to connect to some specific connection (foo) - * and we were already connected to some other connection (bar), - * then we cannot activate this session although icd has a valid - * connection to somewhere. - */ - if ((publicConfig.type() != QNetworkConfiguration::UserChoice) && - (connected_iap != config.identifier())) { - updateState(QNetworkSession::Disconnected); - emit q->error(QNetworkSession::UnknownSessionError); - return; - } - - /* Did we connect to non saved IAP? */ - if (!(config.d->network_attrs & ICD_NW_ATTR_IAPNAME)) { - /* Because the connection succeeded, the IAP is now known. - */ - config.d->network_attrs |= ICD_NW_ATTR_IAPNAME; - config.d->id = connected_iap; - } - - /* User might have changed the IAP name when a new IAP was saved */ - Maemo::IAPConf iap_name(config.d->id); - QString name = iap_name.value("name").toString(); - if (!name.isEmpty()) - config.d->name = name; - - config.d->iap_type = rep.arguments().at(3).toString(); // connect_result.connect.network_type; - config.d->isValid = true; - config.d->state = QNetworkConfiguration::Active; - config.d->type = QNetworkConfiguration::InternetAccessPoint; - - startTime = QDateTime::currentDateTime(); - updateState(QNetworkSession::Connected); - //currentNetworkInterface = get_network_interface(); -#ifdef BEARER_MANAGEMENT_DEBUG - //qDebug() << "connected to" << result << config.d->name << "at" << currentNetworkInterface; -#endif - - /* We first check if the configuration already exists in the manager - * and if it is not found there, we then insert it. Note that this - * is only done for user choice config only because it can be missing - * from config manager list. - */ - if (publicConfig.d->type == QNetworkConfiguration::UserChoice) { -#ifdef BEARER_MANAGEMENT_DEBUG -#if 0 - QList configs; - QNetworkConfigurationManagerPrivate *conPriv = (QNetworkConfigurationManagerPrivate*)config.d.data()->manager; - QList cpsIdents = conPriv->accessPointConfigurations.keys(); - foreach( QString ii, cpsIdents) { - QExplicitlySharedDataPointer p = - conPriv->accessPointConfigurations.value(ii); - QNetworkConfiguration pt; - pt.d = conPriv->accessPointConfigurations.value(ii); - configs << pt; - } - - int all = configs.count(); - qDebug() << "All configurations:" << all; - foreach(QNetworkConfiguration p, configs) { - qDebug() << p.name() <<": isvalid->" <"<< p.type() << - " roaming->" << p.isRoamingAvailable() << "identifier->" << p.identifier() << - " purpose->" << p.purpose() << " state->" << p.state(); - } -#endif -#endif - QNetworkConfigurationManagerPrivate *mgr = (QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager; - if (!mgr->accessPointConfigurations.contains(result)) { - QExplicitlySharedDataPointer ptr = config.d; - mgr->accessPointConfigurations.insert(result, ptr); - - QNetworkConfiguration item; - item.d = ptr; - emit mgr->configurationAdded(item); - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug()<<"New configuration"< priv = mgr->accessPointConfigurations.value(result); - QNetworkConfiguration reference; - reference.d = priv; - copyConfig(config, reference, false); - reference.d.data()->id = result; // Note: Id was not copied in copyConfig() function - config = reference; - activeConfig = reference; - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug()<<"Existing configuration"<error(QNetworkSession::UnknownSessionError); -} - -void QNetworkSessionPrivate::close() -{ - if (m_connectRequestTimer.isActive()) - m_connectRequestTimer.stop(); - - if (serviceConfig.isValid()) { - lastError = QNetworkSession::OperationNotSupportedError; - emit q->error(lastError); - } else if (isOpen) { - opened = false; - isOpen = false; - emit q->closed(); - } -} - - -void QNetworkSessionPrivate::stop() -{ - if (m_connectRequestTimer.isActive()) - m_connectRequestTimer.stop(); - - if (serviceConfig.isValid()) { - lastError = QNetworkSession::OperationNotSupportedError; - emit q->error(lastError); - } else { - if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - if (!m_stopTimer.isActive()) { - Maemo::Icd icd; -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "stopping session" << publicConfig.identifier(); -#endif - state = QNetworkSession::Closing; - emit q->stateChanged(state); - - opened = false; - isOpen = false; - - icd.disconnect(ICD_CONNECTION_FLAG_APPLICATION_EVENT); - startTime = QDateTime(); - - /* Note: Session state will change to disconnected - * as soon as QNetworkConfigurationManager sends - * corresponding iapStateChanged signal. - */ - - // Make sure that this Session will send closed signal - // even though ICD connection will not ever get closed - m_stopTimer.start(ICD_SHORT_CONNECT_TIMEOUT); // 10 seconds wait - } - } else { - opened = false; - isOpen = false; - emit q->closed(); - } - } -} - -void QNetworkSessionPrivate::finishStopBySendingClosedSignal() -{ - if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - state = QNetworkSession::Connected; - emit q->stateChanged(state); - } - emit q->closed(); -} - -void QNetworkSessionPrivate::migrate() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - - -void QNetworkSessionPrivate::accept() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - - -void QNetworkSessionPrivate::ignore() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - - -void QNetworkSessionPrivate::reject() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - - -QNetworkInterface QNetworkSessionPrivate::currentInterface() const -{ - if (!publicConfig.isValid() || state != QNetworkSession::Connected) - return QNetworkInterface(); - - if (currentNetworkInterface.isEmpty()) - return QNetworkInterface(); - - return QNetworkInterface::interfaceFromName(currentNetworkInterface); -} - - -void QNetworkSessionPrivate::setSessionProperty(const QString& key, const QVariant& value) -{ - if (value.isValid()) { - properties.insert(key, value); - - if (key == "ConnectInBackground") { - bool v = value.toBool(); - if (v) - connectFlags = ICD_CONNECTION_FLAG_APPLICATION_EVENT; - else - connectFlags = ICD_CONNECTION_FLAG_USER_EVENT; - } - } else { - properties.remove(key); - - /* Set default value when property is removed */ - if (key == "ConnectInBackground") - connectFlags = ICD_CONNECTION_FLAG_USER_EVENT; - } -} - - -QVariant QNetworkSessionPrivate::sessionProperty(const QString& key) const -{ - return properties.value(key); -} - - -QString QNetworkSessionPrivate::errorString() const -{ - QString errorStr; - switch(q->error()) { - case QNetworkSession::RoamingError: - errorStr = QObject::tr("Roaming error"); - break; - case QNetworkSession::SessionAbortedError: - errorStr = QObject::tr("Session aborted by user or system"); - break; - case QNetworkSession::InvalidConfigurationError: - errorStr = QObject::tr("The specified configuration cannot be used."); - break; - default: - case QNetworkSession::UnknownSessionError: - errorStr = QObject::tr("Unidentified Error"); - break; - } - return errorStr; -} - - -QNetworkSession::SessionError QNetworkSessionPrivate::error() const -{ - return QNetworkSession::UnknownSessionError; -} - - -void QNetworkSessionPrivate::updateProxies(QNetworkSession::State newState) -{ - if ((newState == QNetworkSession::Connected) && - (newState != currentState)) - updateProxyInformation(); - else if ((newState == QNetworkSession::Disconnected) && - (currentState == QNetworkSession::Closing)) - clearProxyInformation(); - - currentState = newState; -} - - -void QNetworkSessionPrivate::updateProxyInformation() -{ - Maemo::ProxyConf::update(); -} - - -void QNetworkSessionPrivate::clearProxyInformation() -{ - Maemo::ProxyConf::clear(); -} - - -#include "moc_qnetworksession_maemo_p.cpp" - -QTM_END_NAMESPACE diff --git a/src/bearer/qnetworksession_maemo_p.h b/src/bearer/qnetworksession_maemo_p.h deleted file mode 100644 index 7b10405..0000000 --- a/src/bearer/qnetworksession_maemo_p.h +++ /dev/null @@ -1,228 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKSESSIONPRIVATE_H -#define QNETWORKSESSIONPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of the QLibrary class. This header file may change from -// version to version without notice, or even be removed. -// -// We mean it. -// -#include "qnetworkconfigmanager_maemo_p.h" -#include "qnetworksession.h" - -#include -#include -#include -#include - -#include - -QTM_BEGIN_NAMESPACE - -struct ICd2DetailsDBusStruct -{ - QString serviceType; - uint serviceAttributes; - QString setviceId; - QString networkType; - uint networkAttributes; - QByteArray networkId; -}; - -typedef QList ICd2DetailsList; - -class QNetworkSessionPrivate : public QObject -{ - Q_OBJECT -public: - QNetworkSessionPrivate() : - isOpen(false), - connectFlags(ICD_CONNECTION_FLAG_USER_EVENT), - currentState(QNetworkSession::Invalid), - m_asynchCallActive(false) - { - m_stopTimer.setSingleShot(true); - connect(&m_stopTimer, SIGNAL(timeout()), this, SLOT(finishStopBySendingClosedSignal())); - - QDBusConnection systemBus = QDBusConnection::systemBus(); - - m_dbusInterface = new QDBusInterface(ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_PATH, - ICD_DBUS_API_INTERFACE, - systemBus, - this); - - systemBus.connect(ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_PATH, - ICD_DBUS_API_INTERFACE, - ICD_DBUS_API_CONNECT_SIG, - this, - SLOT(stateChange(const QDBusMessage&))); - - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - - m_connectRequestTimer.setSingleShot(true); - connect(&m_connectRequestTimer, SIGNAL(timeout()), this, SLOT(connectTimeout())); - } - - ~QNetworkSessionPrivate() - { - cleanupSession(); - } - - //called by QNetworkSession constructor and ensures - //that the state is immediately updated (w/o actually opening - //a session). Also this function should take care of - //notification hooks to discover future state changes. - void syncStateWithInterface(); - - QNetworkInterface currentInterface() const; - QVariant sessionProperty(const QString& key) const; - void setSessionProperty(const QString& key, const QVariant& value); - - void open(); - void close(); - void stop(); - void migrate(); - void accept(); - void ignore(); - void reject(); - - QString errorString() const; //must return translated string - QNetworkSession::SessionError error() const; - - quint64 bytesWritten() const; - quint64 bytesReceived() const; - quint64 activeTime() const; - -private: - void updateStateFromServiceNetwork(); - void updateStateFromActiveConfig(); - -Q_SIGNALS: - //releases any pending waitForOpened() calls - void quitPendingWaitsForOpened(); - -private Q_SLOTS: - void do_open(); - void networkConfigurationsChanged(); - void iapStateChanged(const QString& iapid, uint icd_connection_state); - void updateProxies(QNetworkSession::State newState); - void finishStopBySendingClosedSignal(); - void stateChange(const QDBusMessage& rep); - void connectTimeout(); - -private: - QNetworkConfigurationManager manager; - - struct Statistics { - quint64 txData; - quint64 rxData; - quint64 activeTime; - }; - - // The config set on QNetworkSession. - QNetworkConfiguration publicConfig; - QNetworkConfiguration config; - - // If publicConfig is a ServiceNetwork this is a copy of publicConfig. - // If publicConfig is an UserChoice that is resolved to a ServiceNetwork this is the actual - // ServiceNetwork configuration. - QNetworkConfiguration serviceConfig; - - // This is the actual active configuration currently in use by the session. - // Either a copy of publicConfig or one of serviceConfig.children(). - QNetworkConfiguration activeConfig; - - QNetworkConfiguration& copyConfig(QNetworkConfiguration &fromConfig, QNetworkConfiguration &toConfig, bool deepCopy = true); - void clearConfiguration(QNetworkConfiguration &config); - - QNetworkSession::State state; - bool isOpen; - bool opened; - icd_connection_flags connectFlags; - - QNetworkSession::SessionError lastError; - - QNetworkSession* q; - friend class QNetworkSession; - - QDateTime startTime; - QString currentNetworkInterface; - friend class IcdListener; - void updateState(QNetworkSession::State); - void updateIdentifier(const QString &newId); - Statistics getStatistics() const; - void cleanupSession(void); - - void updateProxyInformation(); - void clearProxyInformation(); - QNetworkSession::State currentState; - - QDBusInterface *m_dbusInterface; - - QTimer m_stopTimer; - - bool m_asynchCallActive; - QTimer m_connectRequestTimer; -}; - -QTM_END_NAMESPACE - -// Marshall the ICd2DetailsDBusStruct data into a D-Bus argument -QDBusArgument &operator<<(QDBusArgument &argument, const QtMobility::ICd2DetailsDBusStruct &icd2); - -// Retrieve the ICd2DetailsDBusStruct data from the D-Bus argument -const QDBusArgument &operator>>(const QDBusArgument &argument, QtMobility::ICd2DetailsDBusStruct &icd2); - -Q_DECLARE_METATYPE(QtMobility::ICd2DetailsDBusStruct); -Q_DECLARE_METATYPE(QtMobility::ICd2DetailsList); - -#endif //QNETWORKSESSIONPRIVATE_H - diff --git a/src/bearer/qnetworksession_p.cpp b/src/bearer/qnetworksession_p.cpp deleted file mode 100644 index 6a34e5c..0000000 --- a/src/bearer/qnetworksession_p.cpp +++ /dev/null @@ -1,534 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnetworksession_p.h" -#include "qnetworksession.h" -#include "qnetworksessionengine_p.h" -#include "qgenericengine_p.h" - -#ifdef Q_OS_WIN -#include "qnlaengine_win_p.h" -#endif -#ifdef Q_OS_WIN32 -#include "qnativewifiengine_win_p.h" -#endif -#ifdef Q_OS_DARWIN -#include "qcorewlanengine_mac_p.h" -#endif -#include -#include -#include - -#include - -#if defined(BACKEND_NM) -#include "qnmwifiengine_unix_p.h" -#endif - -QTM_BEGIN_NAMESPACE - -#if defined(BACKEND_NM) -static bool NetworkManagerAvailable() -{ - if (QDBusConnection::systemBus().isConnected()) { - QDBusConnectionInterface *dbiface = QDBusConnection::systemBus().interface(); - QDBusReply reply = dbiface->isServiceRegistered("org.freedesktop.NetworkManager"); - if (reply.isValid()) - return reply.value(); - } - return false; -} -#endif - -static QNetworkSessionEngine *getEngineFromId(const QString &id) -{ -#ifdef Q_OS_WIN - QNlaEngine *nla = QNlaEngine::instance(); - if (nla && nla->hasIdentifier(id)) - return nla; -#endif - -#ifdef Q_OS_WIN32 - QNativeWifiEngine *nativeWifi = QNativeWifiEngine::instance(); - if (nativeWifi && nativeWifi->hasIdentifier(id)) - return nativeWifi; -#endif - -#if defined(BACKEND_NM) - if(NetworkManagerAvailable()) { - QNmWifiEngine *nmwiifi = QNmWifiEngine::instance(); - if (nmwiifi && nmwiifi->hasIdentifier(id)) - return nmwiifi; - } -#endif -#ifdef Q_OS_DARWIN - QCoreWlanEngine *coreWifi = QCoreWlanEngine::instance(); - if (coreWifi && coreWifi->hasIdentifier(id)) - return coreWifi; - -#endif - QGenericEngine *generic = QGenericEngine::instance(); - if (generic && generic->hasIdentifier(id)) - return generic; - - return 0; -} - -class QNetworkSessionManagerPrivate : public QObject -{ - Q_OBJECT - -public: - QNetworkSessionManagerPrivate(QObject *parent = 0); - ~QNetworkSessionManagerPrivate(); - - void forceSessionClose(const QNetworkConfiguration &config); - -Q_SIGNALS: - void forcedSessionClose(const QNetworkConfiguration &config); -}; - -#include "qnetworksession_p.moc" - -Q_GLOBAL_STATIC(QNetworkSessionManagerPrivate, sessionManager); - -QNetworkSessionManagerPrivate::QNetworkSessionManagerPrivate(QObject *parent) -: QObject(parent) -{ -} - -QNetworkSessionManagerPrivate::~QNetworkSessionManagerPrivate() -{ -} - -void QNetworkSessionManagerPrivate::forceSessionClose(const QNetworkConfiguration &config) -{ - emit forcedSessionClose(config); -} - -void QNetworkSessionPrivate::syncStateWithInterface() -{ - connect(&manager, SIGNAL(updateCompleted()), this, SLOT(networkConfigurationsChanged())); - connect(&manager, SIGNAL(configurationChanged(QNetworkConfiguration)), - this, SLOT(configurationChanged(QNetworkConfiguration))); - connect(sessionManager(), SIGNAL(forcedSessionClose(QNetworkConfiguration)), - this, SLOT(forcedSessionClose(QNetworkConfiguration))); - - opened = false; - state = QNetworkSession::Invalid; - lastError = QNetworkSession::UnknownSessionError; - - qRegisterMetaType - ("QNetworkSessionEngine::ConnectionError"); - - switch (publicConfig.type()) { - case QNetworkConfiguration::InternetAccessPoint: - activeConfig = publicConfig; - engine = getEngineFromId(activeConfig.identifier()); - if (engine) { - connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)), - this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)), - Qt::QueuedConnection); - } - break; - case QNetworkConfiguration::ServiceNetwork: - serviceConfig = publicConfig; - // Defer setting engine and signals until open(). - // fall through - case QNetworkConfiguration::UserChoice: - // Defer setting serviceConfig and activeConfig until open(). - // fall through - default: - engine = 0; - } - - networkConfigurationsChanged(); -} - -void QNetworkSessionPrivate::open() -{ - if (serviceConfig.isValid()) { - lastError = QNetworkSession::OperationNotSupportedError; - emit q->error(lastError); - } else if (!isOpen) { - if ((activeConfig.state() & QNetworkConfiguration::Discovered) != - QNetworkConfiguration::Discovered) { - lastError =QNetworkSession::InvalidConfigurationError; - emit q->error(lastError); - return; - } - opened = true; - - if ((activeConfig.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active && - (activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) { - state = QNetworkSession::Connecting; - emit q->stateChanged(state); - - engine->connectToId(activeConfig.identifier()); - } - - isOpen = (activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active; - if (isOpen) - emit quitPendingWaitsForOpened(); - } -} - -void QNetworkSessionPrivate::close() -{ - if (serviceConfig.isValid()) { - lastError = QNetworkSession::OperationNotSupportedError; - emit q->error(lastError); - } else if (isOpen) { - opened = false; - isOpen = false; - emit q->closed(); - } -} - -void QNetworkSessionPrivate::stop() -{ - if (serviceConfig.isValid()) { - lastError = QNetworkSession::OperationNotSupportedError; - emit q->error(lastError); - } else { - if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - state = QNetworkSession::Closing; - emit q->stateChanged(state); - - engine->disconnectFromId(activeConfig.identifier()); - - sessionManager()->forceSessionClose(activeConfig); - } - - opened = false; - isOpen = false; - emit q->closed(); - } -} - -void QNetworkSessionPrivate::migrate() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - -void QNetworkSessionPrivate::accept() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - -void QNetworkSessionPrivate::ignore() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - -void QNetworkSessionPrivate::reject() -{ - qWarning("This platform does not support roaming (%s).", __FUNCTION__); -} - -QNetworkInterface QNetworkSessionPrivate::currentInterface() const -{ - if (!publicConfig.isValid() || !engine || state != QNetworkSession::Connected) - return QNetworkInterface(); - - QString interface = engine->getInterfaceFromId(activeConfig.identifier()); - - if (interface.isEmpty()) - return QNetworkInterface(); - return QNetworkInterface::interfaceFromName(interface); -} - -QVariant QNetworkSessionPrivate::sessionProperty(const QString& /*key*/) const -{ - return QVariant(); -} - -void QNetworkSessionPrivate::setSessionProperty(const QString& /*key*/, const QVariant& /*value*/) -{ -} - -/*QString QNetworkSessionPrivate::bearerName() const -{ - if (!publicConfig.isValid() || !engine) - return QString(); - - return engine->bearerName(activeConfig.identifier()); -}*/ - -QString QNetworkSessionPrivate::errorString() const -{ - switch (lastError) { - case QNetworkSession::UnknownSessionError: - return tr("Unknown session error."); - case QNetworkSession::SessionAbortedError: - return tr("The session was aborted by the user or system."); - case QNetworkSession::OperationNotSupportedError: - return tr("The requested operation is not supported by the system."); - case QNetworkSession::InvalidConfigurationError: - return tr("The specified configuration cannot be used."); - case QNetworkSession::RoamingError: - return tr("Roaming was aborted or is not possible."); - - } - - return QString(); -} - -QNetworkSession::SessionError QNetworkSessionPrivate::error() const -{ - return lastError; -} - -quint64 QNetworkSessionPrivate::bytesWritten() const -{ -#if defined(BACKEND_NM) - if( NetworkManagerAvailable() && state == QNetworkSession::Connected ) { - if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) { - foreach (const QNetworkConfiguration &config, publicConfig.children()) { - if ((config.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - return static_cast(getEngineFromId(config.d->id))->sentDataForId(config.d->id); - } - } - } else { - return static_cast(getEngineFromId(activeConfig.d->id))->sentDataForId(activeConfig.d->id); - } - } -#endif - return tx_data; -} - -quint64 QNetworkSessionPrivate::bytesReceived() const -{ -#if defined(BACKEND_NM) - if( NetworkManagerAvailable() && state == QNetworkSession::Connected ) { - if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) { - foreach (const QNetworkConfiguration &config, publicConfig.children()) { - if ((config.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - return static_cast(getEngineFromId(activeConfig.d->id))->receivedDataForId(config.d->id); - } - } - } else { - return static_cast(getEngineFromId(activeConfig.d->id))->receivedDataForId(activeConfig.d->id); - } - } -#endif - return rx_data; -} - -quint64 QNetworkSessionPrivate::activeTime() const -{ -#if defined(BACKEND_NM) - if (startTime.isNull()) { - return 0; - } - if(state == QNetworkSession::Connected ) - return startTime.secsTo(QDateTime::currentDateTime()); -#endif - return m_activeTime; -} - -void QNetworkSessionPrivate::updateStateFromServiceNetwork() -{ - QNetworkSession::State oldState = state; - - foreach (const QNetworkConfiguration &config, serviceConfig.children()) { - if ((config.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active) - continue; - - if (activeConfig != config) { - if (engine) { - disconnect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)), - this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError))); - } - - activeConfig = config; - engine = getEngineFromId(activeConfig.identifier()); - if (engine) { - connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)), - this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)), - Qt::QueuedConnection); - } - emit q->newConfigurationActivated(); - } - - state = QNetworkSession::Connected; - if (state != oldState) - emit q->stateChanged(state); - - return; - } - - if (serviceConfig.children().isEmpty()) - state = QNetworkSession::NotAvailable; - else - state = QNetworkSession::Disconnected; - - if (state != oldState) - emit q->stateChanged(state); -} - -void QNetworkSessionPrivate::updateStateFromActiveConfig() -{ - QNetworkSession::State oldState = state; - - bool newActive = false; - - if (!activeConfig.isValid()) { - state = QNetworkSession::Invalid; - } else if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { - state = QNetworkSession::Connected; - newActive = opened; - } else if ((activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) { - state = QNetworkSession::Disconnected; - } else if ((activeConfig.state() & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) { - state = QNetworkSession::NotAvailable; - } else if ((activeConfig.state() & QNetworkConfiguration::Undefined) == QNetworkConfiguration::Undefined) { - state = QNetworkSession::NotAvailable; - } - - bool oldActive = isOpen; - isOpen = newActive; - - if (!oldActive && isOpen) - emit quitPendingWaitsForOpened(); - if (oldActive && !isOpen) - emit q->closed(); - - if (oldState != state) - emit q->stateChanged(state); -} - -void QNetworkSessionPrivate::networkConfigurationsChanged() -{ - if (serviceConfig.isValid()) - updateStateFromServiceNetwork(); - else - updateStateFromActiveConfig(); -#if defined(BACKEND_NM) - setActiveTimeStamp(); -#endif -} - -void QNetworkSessionPrivate::configurationChanged(const QNetworkConfiguration &config) -{ - if (serviceConfig.isValid() && (config == serviceConfig || config == activeConfig)) - updateStateFromServiceNetwork(); - else if (config == activeConfig) - updateStateFromActiveConfig(); -} - -void QNetworkSessionPrivate::forcedSessionClose(const QNetworkConfiguration &config) -{ - if (activeConfig == config) { - opened = false; - isOpen = false; - - emit q->closed(); - - lastError = QNetworkSession::SessionAbortedError; - emit q->error(lastError); - } -} - -void QNetworkSessionPrivate::connectionError(const QString &id, QNetworkSessionEngine::ConnectionError error) -{ - if (activeConfig.identifier() == id) { - networkConfigurationsChanged(); - switch (error) { - case QNetworkSessionEngine::OperationNotSupported: - lastError = QNetworkSession::OperationNotSupportedError; - opened = false; - break; - case QNetworkSessionEngine::InterfaceLookupError: - case QNetworkSessionEngine::ConnectError: - case QNetworkSessionEngine::DisconnectionError: - default: - lastError = QNetworkSession::UnknownSessionError; - } - emit q->error(lastError); - } -} - -#if defined(BACKEND_NM) -void QNetworkSessionPrivate::setActiveTimeStamp() -{ - if(NetworkManagerAvailable()) { - startTime = QDateTime(); - return; - } - QString interface = currentInterface().hardwareAddress().toLower(); - const QString devicePath = QLatin1String("/org/freedesktop/Hal/devices/net_") + - interface.replace(QLatin1Char(':'), QLatin1Char('_')); - - QString path; - QString serviceName; - QScopedPointer ifaceD(new QNetworkManagerInterface()); - - foreach (const QDBusObjectPath &conpath, ifaceD->activeConnections()) { - QScopedPointer conDetails(new QNetworkManagerConnectionActive(conpath.path())); - const QDBusObjectPath connection = conDetails->connection(); - serviceName = conDetails->serviceName(); - foreach (const QDBusObjectPath &device, conDetails->devices()) { - if(device.path() == devicePath) { - path = connection.path(); - } - break; - } - } - - if(serviceName.isEmpty()) - return; - - QScopedPointer settingsiface(new QNetworkManagerSettings(serviceName)); - foreach (const QDBusObjectPath &path, settingsiface->listConnections()) { - QScopedPointer sysIface; - sysIface.reset(new QNetworkManagerSettingsConnection(serviceName, path.path())); - startTime = QDateTime::fromTime_t(sysIface->getTimestamp()); - // isOpen = (publicConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active; - } - if(startTime.isNull()) - startTime = QDateTime::currentDateTime(); -} -#endif - -#include "moc_qnetworksession_p.cpp" -QTM_END_NAMESPACE - diff --git a/src/bearer/qnetworksession_p.h b/src/bearer/qnetworksession_p.h index d8f9915..ad0a86f 100644 --- a/src/bearer/qnetworksession_p.h +++ b/src/bearer/qnetworksession_p.h @@ -55,110 +55,22 @@ #include "qnetworkconfigmanager_p.h" #include "qnetworksession.h" -#ifdef BEARER_ENGINE -#include "qnetworksessionengine_p.h" -#endif - -#include "qnetworksession.h" -#include -#include +#include "qnetworksessionadaptor_p.h" +#include QTM_BEGIN_NAMESPACE -#ifdef BEARER_ENGINE -class QNetworkSessionEngine; -#endif -class QNetworkSessionPrivate : public QObject +class QNetworkSessionPrivate : public QNetworkSessionAdaptor { Q_OBJECT public: - QNetworkSessionPrivate() : - tx_data(0), rx_data(0), m_activeTime(0), isOpen(false) - { - } - - ~QNetworkSessionPrivate() - { - } - - //called by QNetworkSession constructor and ensures - //that the state is immediately updated (w/o actually opening - //a session). Also this function should take care of - //notification hooks to discover future state changes. - void syncStateWithInterface(); - - QNetworkInterface currentInterface() const; - QVariant sessionProperty(const QString& key) const; - void setSessionProperty(const QString& key, const QVariant& value); - QString bearerName() const; - - void open(); - void close(); - void stop(); - void migrate(); - void accept(); - void ignore(); - void reject(); - - QString errorString() const; //must return translated string - QNetworkSession::SessionError error() const; - - quint64 bytesWritten() const; - quint64 bytesReceived() const; - quint64 activeTime() const; - -private: - void updateStateFromServiceNetwork(); - void updateStateFromActiveConfig(); - -Q_SIGNALS: - //releases any pending waitForOpened() calls - void quitPendingWaitsForOpened(); - -private Q_SLOTS: -#ifdef BEARER_ENGINE - void networkConfigurationsChanged(); - void configurationChanged(const QNetworkConfiguration &config); - void forcedSessionClose(const QNetworkConfiguration &config); - void connectionError(const QString &id, QNetworkSessionEngine::ConnectionError error); -#endif - -private: - QNetworkConfigurationManager manager; - - quint64 tx_data; - quint64 rx_data; - quint64 m_activeTime; - - // The config set on QNetworkSession. - QNetworkConfiguration publicConfig; - - // If publicConfig is a ServiceNetwork this is a copy of publicConfig. - // If publicConfig is an UserChoice that is resolved to a ServiceNetwork this is the actual - // ServiceNetwork configuration. - QNetworkConfiguration serviceConfig; - - // This is the actual active configuration currently in use by the session. - // Either a copy of publicConfig or one of serviceConfig.children(). - QNetworkConfiguration activeConfig; - - QNetworkSession::State state; - bool isOpen; - -#ifdef BEARER_ENGINE - bool opened; - - QNetworkSessionEngine *engine; -#endif - QNetworkSession::SessionError lastError; - - QNetworkSession* q; - friend class QNetworkSession; - -#if defined(BEARER_ENGINE) && defined(BACKEND_NM) - QDateTime startTime; - void setActiveTimeStamp(); -#endif + QNetworkSessionPrivate(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config); + QT_PREPEND_NAMESPACE(QNetworkSession) impl; + QNetworkSession *q; +protected: + void _q_stateChanged(QT_PREPEND_NAMESPACE(QNetworkSession::State)); + void _q_error(QT_PREPEND_NAMESPACE(QNetworkSession::SessionError)); + void _q_preferredConfigurationChanged(const QT_PREPEND_NAMESPACE(QNetworkConfiguration&) config, bool isSeamless); }; QTM_END_NAMESPACE diff --git a/src/bearer/qnetworksession_s60_p.cpp b/src/bearer/qnetworksession_s60_p.cpp deleted file mode 100644 index 080fa0c..0000000 --- a/src/bearer/qnetworksession_s60_p.cpp +++ /dev/null @@ -1,1428 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "qnetworksession_s60_p.h" -#include "qnetworkconfiguration_s60_p.h" -#include "qnetworkconfigmanager_s60_p.h" -#include -#include -#include -#include -#include - -QTM_BEGIN_NAMESPACE - -QNetworkSessionPrivate::QNetworkSessionPrivate() - : CActive(CActive::EPriorityUserInput), state(QNetworkSession::Invalid), - isOpen(false), iDynamicUnSetdefaultif(0), ipConnectionNotifier(0), - iHandleStateNotificationsFromManager(false), iFirstSync(true), iStoppedByUser(false), - iClosedByUser(false), iError(QNetworkSession::UnknownSessionError), iALREnabled(0), - iConnectInBackground(false), isOpening(false) -{ - CActiveScheduler::Add(this); - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - iMobility = NULL; -#endif - // Try to load "Open C" dll dynamically and - // try to attach to unsetdefaultif function dynamically. - // This is to avoid build breaks with old OpenC versions. - if (iOpenCLibrary.Load(_L("libc")) == KErrNone) { - iDynamicUnSetdefaultif = (TOpenCUnSetdefaultifFunction)iOpenCLibrary.Lookup(597); - } -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - "; - if (iDynamicUnSetdefaultif) - qDebug() << "dynamic unsetdefaultif() is present in PIPS library. "; - else - qDebug() << "dynamic unsetdefaultif() not present in PIPS library. "; -#endif - - TRAP_IGNORE(iConnectionMonitor.ConnectL()); -} - -QNetworkSessionPrivate::~QNetworkSessionPrivate() -{ - isOpen = false; - isOpening = false; - - // Cancel Connection Progress Notifications first. - // Note: ConnectionNotifier must be destroyed before Canceling RConnection::Start() - // => deleting ipConnectionNotifier results RConnection::CancelProgressNotification() - delete ipConnectionNotifier; - ipConnectionNotifier = NULL; - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (iMobility) { - delete iMobility; - iMobility = NULL; - } -#endif - - // Cancel possible RConnection::Start() - Cancel(); - iSocketServ.Close(); - - // Close global 'Open C' RConnection - // Clears also possible unsetdefaultif() flags. - setdefaultif(0); - - iConnectionMonitor.Close(); - iOpenCLibrary.Close(); -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - destroyed (and setdefaultif(0))"; -#endif -} - -void QNetworkSessionPrivate::configurationStateChanged(TUint32 accessPointId, TUint32 connMonId, QNetworkSession::State newState) -{ - if (iHandleStateNotificationsFromManager) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "configurationStateChanged from manager for IAP : " << QString::number(accessPointId) - << "connMon ID : " << QString::number(connMonId) << " : to a state: " << newState - << "whereas my current state is: " << state; -#else - Q_UNUSED(connMonId); -#endif - this->newState(newState, accessPointId); - } -} - -void QNetworkSessionPrivate::configurationRemoved(const QNetworkConfiguration& config) -{ - if (!publicConfig.d.data()) { - return; - } - if (config.d.data()->numericId == publicConfig.d.data()->numericId) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "configurationRemoved IAP: " << QString::number(publicConfig.d.data()->numericId) << " : going to State: Invalid"; -#endif - this->newState(QNetworkSession::Invalid, publicConfig.d.data()->numericId); - } -} - -void QNetworkSessionPrivate::configurationAdded(const QNetworkConfiguration& config) -{ - Q_UNUSED(config); - // If session is based on service network, some other app may create new access points - // to the SNAP --> synchronize session's state with that of interface's. - if (!publicConfig.d.data() || publicConfig.type() != QNetworkConfiguration::ServiceNetwork) { - return; - } -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "configurationAdded IAP: " << QString::number(config.d.data()->numericId); -#endif - syncStateWithInterface(); -} - -// Function sets the state of the session to match the state -// of the underlying interface (the configuration this session is based on) -void QNetworkSessionPrivate::syncStateWithInterface() -{ - if (!publicConfig.d || !publicConfig.d.data()) { - return; - } - if (iFirstSync) { - QObject::connect(((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager), SIGNAL(configurationStateChanged(TUint32, TUint32, QNetworkSession::State)), - this, SLOT(configurationStateChanged(TUint32, TUint32, QNetworkSession::State))); - // Listen to configuration removals, so that in case the configuration - // this session is based on is removed, session knows to enter Invalid -state. - QObject::connect(((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager), - SIGNAL(configurationRemoved(QNetworkConfiguration)), - this, SLOT(configurationRemoved(QNetworkConfiguration))); - // Connect to configuration additions, so that in case a configuration is added - // in a SNAP this session is based on, the session knows to synch its state with its - // interface. - QObject::connect(((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager), - SIGNAL(configurationAdded(QNetworkConfiguration)), - this, SLOT(configurationAdded(QNetworkConfiguration))); - } - // Start listening IAP state changes from QNetworkConfigurationManagerPrivate - iHandleStateNotificationsFromManager = true; - - // Check what is the state of the configuration this session is based on - // and set the session in appropriate state. -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "syncStateWithInterface() state of publicConfig is: " << publicConfig.d.data()->state; -#endif - switch (publicConfig.d.data()->state) { - case QNetworkConfiguration::Active: - newState(QNetworkSession::Connected); - break; - case QNetworkConfiguration::Discovered: - newState(QNetworkSession::Disconnected); - break; - case QNetworkConfiguration::Defined: - newState(QNetworkSession::NotAvailable); - break; - case QNetworkConfiguration::Undefined: - default: - newState(QNetworkSession::Invalid); - } -} - -QNetworkInterface QNetworkSessionPrivate::interface(TUint iapId) const -{ - QString interfaceName; - - TSoInetInterfaceInfo ifinfo; - TPckg ifinfopkg(ifinfo); - TSoInetIfQuery ifquery; - TPckg ifquerypkg(ifquery); - - // Open dummy socket for interface queries - RSocket socket; - TInt retVal = socket.Open(iSocketServ, _L("udp")); - if (retVal != KErrNone) { - return QNetworkInterface(); - } - - // Start enumerating interfaces - socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl); - while(socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, ifinfopkg) == KErrNone) { - ifquery.iName = ifinfo.iName; - TInt err = socket.GetOpt(KSoInetIfQueryByName, KSolInetIfQuery, ifquerypkg); - if(err == KErrNone && ifquery.iZone[1] == iapId) { // IAP ID is index 1 of iZone - if(ifinfo.iAddress.Address() > 0) { - interfaceName = QString::fromUtf16(ifinfo.iName.Ptr(),ifinfo.iName.Length()); - break; - } - } - } - - socket.Close(); - - if (interfaceName.isEmpty()) { - return QNetworkInterface(); - } - - return QNetworkInterface::interfaceFromName(interfaceName); -} - -QNetworkInterface QNetworkSessionPrivate::currentInterface() const -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "currentInterface() requested, state: " << state - << "publicConfig validity: " << publicConfig.isValid(); - if (activeInterface.isValid()) - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "interface is: " << activeInterface.humanReadableName(); -#endif - - if (!publicConfig.isValid() || state != QNetworkSession::Connected) { - return QNetworkInterface(); - } - - return activeInterface; -} - -QVariant QNetworkSessionPrivate::sessionProperty(const QString& key) const -{ - if (key == "ConnectInBackground") { - return QVariant(iConnectInBackground); - } - return QVariant(); -} - -void QNetworkSessionPrivate::setSessionProperty(const QString& key, const QVariant& value) -{ - // Valid value means adding property, invalid means removing it. - if (key == "ConnectInBackground") { - if (value.isValid()) { - iConnectInBackground = value.toBool(); - } else { - iConnectInBackground = EFalse; - } - } -} - -QString QNetworkSessionPrivate::errorString() const -{ - switch (iError) { - case QNetworkSession::UnknownSessionError: - return tr("Unknown session error."); - case QNetworkSession::SessionAbortedError: - return tr("The session was aborted by the user or system."); - case QNetworkSession::OperationNotSupportedError: - return tr("The requested operation is not supported by the system."); - case QNetworkSession::InvalidConfigurationError: - return tr("The specified configuration cannot be used."); - case QNetworkSession::RoamingError: - return tr("Roaming was aborted or is not possible."); - } - - return QString(); -} - -QNetworkSession::SessionError QNetworkSessionPrivate::error() const -{ - return iError; -} - -void QNetworkSessionPrivate::open() -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "open() called, session state is: " << state << " and isOpen is: " - << isOpen; -#endif - if (isOpen || isOpening) - return; - - isOpening = true; - - // Stop handling IAP state change signals from QNetworkConfigurationManagerPrivate - // => RConnection::ProgressNotification will be used for IAP/SNAP monitoring - iHandleStateNotificationsFromManager = false; - - // Configuration may have been invalidated after session creation by platform - // (e.g. configuration has been deleted). - if (!publicConfig.isValid()) { - newState(QNetworkSession::Invalid); - iError = QNetworkSession::InvalidConfigurationError; - emit q->error(iError); - return; - } - // If opening a undefined configuration, session emits error and enters - // NotAvailable -state. Note that we will try ones in 'defined' state to avoid excessive - // need for WLAN scans (via updateConfigurations()), because user may have walked - // into a WLAN range, but periodic background scan has not occurred yet --> - // we don't want to force application to make frequent updateConfigurations() calls - // to be able to try if e.g. home WLAN is available. - if (publicConfig.state() == QNetworkConfiguration::Undefined) { - newState(QNetworkSession::NotAvailable); - iError = QNetworkSession::InvalidConfigurationError; - emit q->error(iError); - return; - } - // Clear possible previous states - iStoppedByUser = false; - iClosedByUser = false; - - TInt error = iSocketServ.Connect(); - if (error != KErrNone) { - // Could not open RSocketServ - newState(QNetworkSession::Invalid); - iError = QNetworkSession::UnknownSessionError; - emit q->error(iError); - syncStateWithInterface(); - return; - } - - error = iConnection.Open(iSocketServ); - if (error != KErrNone) { - // Could not open RConnection - iSocketServ.Close(); - newState(QNetworkSession::Invalid); - iError = QNetworkSession::UnknownSessionError; - emit q->error(iError); - syncStateWithInterface(); - return; - } - - // Use RConnection::ProgressNotification for IAP/SNAP monitoring - // (<=> ConnectionProgressNotifier uses RConnection::ProgressNotification) - if (!ipConnectionNotifier) { - ipConnectionNotifier = new ConnectionProgressNotifier(*this,iConnection); - } - if (ipConnectionNotifier) { - ipConnectionNotifier->StartNotifications(); - } - - if (publicConfig.type() == QNetworkConfiguration::InternetAccessPoint) { -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - // With One Click Connectivity (Symbian^3 onwards) it is possible - // to connect silently, without any popups. - TConnPrefList pref; - TExtendedConnPref prefs; - prefs.SetIapId(publicConfig.d.data()->numericId); - if (iConnectInBackground) { - prefs.SetNoteBehaviour( TExtendedConnPref::ENoteBehaviourConnSilent ); - } - pref.AppendL(&prefs); -#else - TCommDbConnPref pref; - pref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); - pref.SetIapId(publicConfig.d.data()->numericId); -#endif - iConnection.Start(pref, iStatus); - if (!IsActive()) { - SetActive(); - } - // Avoid flip flop of states if the configuration is already - // active. IsOpen/opened() will indicate when ready. - if (state != QNetworkSession::Connected) { - newState(QNetworkSession::Connecting); - } - } else if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) { -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - // On Symbian^3 if service network is not reachable, it triggers a UI (aka EasyWLAN) where - // user can create new IAPs. To detect this, we need to store the number of IAPs - // there was before connection was started. - iKnownConfigsBeforeConnectionStart = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.keys(); - TConnPrefList snapPref; - TExtendedConnPref prefs; - prefs.SetSnapId(publicConfig.d.data()->numericId); - if (iConnectInBackground) { - prefs.SetNoteBehaviour( TExtendedConnPref::ENoteBehaviourConnSilent ); - } - snapPref.AppendL(&prefs); -#else - TConnSnapPref snapPref(publicConfig.d.data()->numericId); -#endif - iConnection.Start(snapPref, iStatus); - if (!IsActive()) { - SetActive(); - } - // Avoid flip flop of states if the configuration is already - // active. IsOpen/opened() will indicate when ready. - if (state != QNetworkSession::Connected) { - newState(QNetworkSession::Connecting); - } - } else if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - iKnownConfigsBeforeConnectionStart = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.keys(); - iConnection.Start(iStatus); - if (!IsActive()) { - SetActive(); - } - newState(QNetworkSession::Connecting); - } - - if (error != KErrNone) { - isOpen = false; - isOpening = false; - iError = QNetworkSession::UnknownSessionError; - emit q->error(iError); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - } - syncStateWithInterface(); - } -} - -TUint QNetworkSessionPrivate::iapClientCount(TUint aIAPId) const -{ - TRequestStatus status; - TUint connectionCount; - iConnectionMonitor.GetConnectionCount(connectionCount, status); - User::WaitForRequest(status); - if (status.Int() == KErrNone) { - for (TUint i = 1; i <= connectionCount; i++) { - TUint connectionId; - TUint subConnectionCount; - iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount); - TUint apId; - iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status); - User::WaitForRequest(status); - if (apId == aIAPId) { - TConnMonClientEnumBuf buf; - iConnectionMonitor.GetPckgAttribute(connectionId, 0, KClientInfo, buf, status); - User::WaitForRequest(status); - if (status.Int() == KErrNone) { - return buf().iCount; - } - } - } - } - return 0; -} - -void QNetworkSessionPrivate::close(bool allowSignals) -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "close() called, session state is: " << state << " and isOpen is : " - << isOpen; -#endif - - if (!isOpen && state != QNetworkSession::Connecting) { - return; - } - // Mark this session as closed-by-user so that we are able to report - // distinguish between stop() and close() state transitions - // when reporting. - iClosedByUser = true; - isOpen = false; - isOpening = false; - - serviceConfig = QNetworkConfiguration(); - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (iMobility) { - delete iMobility; - iMobility = NULL; - } -#endif - - if (ipConnectionNotifier && !iHandleStateNotificationsFromManager) { - ipConnectionNotifier->StopNotifications(); - // Start handling IAP state change signals from QNetworkConfigurationManagerPrivate - iHandleStateNotificationsFromManager = true; - } - - Cancel(); // closes iConnection - iSocketServ.Close(); - - // Close global 'Open C' RConnection. If OpenC supports, - // close the defaultif for good to avoid difficult timing - // and bouncing issues of network going immediately back up - // because of e.g. select() thread etc. - if (iDynamicUnSetdefaultif) { - iDynamicUnSetdefaultif(); - } else { - setdefaultif(0); - } - - // If UserChoice, go down immediately. If some other configuration, - // go down immediately if there is no reports expected from the platform; - // in practice Connection Monitor is aware of connections only after - // KFinishedSelection event, and hence reports only after that event, but - // that does not seem to be trusted on all Symbian versions --> safest - // to go down. - if (publicConfig.type() == QNetworkConfiguration::UserChoice || state == QNetworkSession::Connecting) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "going disconnected right away, since either UserChoice or Connecting"; -#endif - newState(QNetworkSession::Closing); - newState(QNetworkSession::Disconnected); - } - if (allowSignals) { - emit q->closed(); - } -} - -void QNetworkSessionPrivate::stop() -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "stop() called, session state is: " << state << " and isOpen is : " - << isOpen; -#endif - if (!isOpen && - publicConfig.isValid() && - publicConfig.type() == QNetworkConfiguration::InternetAccessPoint) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "since session is not open, using RConnectionMonitor to stop() the interface"; -#endif - iStoppedByUser = true; - // If the publicConfig is type of IAP, enumerate through connections at - // connection monitor. If publicConfig is active in that list, stop it. - // Otherwise there is nothing to stop. Note: because this QNetworkSession is not open, - // activeConfig is not usable. - TUint count; - TRequestStatus status; - iConnectionMonitor.GetConnectionCount(count, status); - User::WaitForRequest(status); - if (status.Int() != KErrNone) { - return; - } - TUint numSubConnections; // Not used but needed by GetConnectionInfo i/f - TUint connectionId; - for (TUint i = 1; i <= count; ++i) { - // Get (connection monitor's assigned) connection ID - TInt ret = iConnectionMonitor.GetConnectionInfo(i, connectionId, numSubConnections); - if (ret == KErrNone) { - // See if connection Id matches with our Id. If so, stop() it. - if (publicConfig.d.data()->connectionId == connectionId) { - ret = iConnectionMonitor.SetBoolAttribute(connectionId, - 0, // subConnectionId don't care - KConnectionStop, - ETrue); - } - } - // Enter disconnected state right away since the session is not even open. - // Symbian^3 connection monitor does not emit KLinkLayerClosed when - // connection is stopped via connection monitor. - newState(QNetworkSession::Disconnected); - } - } else if (isOpen) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "since session is open, using RConnection to stop() the interface"; -#endif - // Since we are open, use RConnection to stop the interface - isOpen = false; - isOpening = false; - iStoppedByUser = true; - newState(QNetworkSession::Closing); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - // Start handling IAP state change signals from QNetworkConfigurationManagerPrivate - iHandleStateNotificationsFromManager = true; - } - iConnection.Stop(RConnection::EStopAuthoritative); - isOpen = true; - isOpening = false; - close(false); - emit q->closed(); - } -} - -void QNetworkSessionPrivate::migrate() -{ -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (iMobility) { - // Close global 'Open C' RConnection. If openC supports, use the 'heavy' - // version to block all subsequent requests. - if (iDynamicUnSetdefaultif) { - iDynamicUnSetdefaultif(); - } else { - setdefaultif(0); - } - // Start migrating to new IAP - iMobility->MigrateToPreferredCarrier(); - } -#endif -} - -void QNetworkSessionPrivate::ignore() -{ -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (iMobility) { - iMobility->IgnorePreferredCarrier(); - - if (!iALRUpgradingConnection) { - newState(QNetworkSession::Disconnected); - } else { - newState(QNetworkSession::Connected,iOldRoamingIap); - } - } -#endif -} - -void QNetworkSessionPrivate::accept() -{ -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (iMobility) { - iMobility->NewCarrierAccepted(); - - QNetworkConfiguration newActiveConfig = activeConfiguration(iNewRoamingIap); - - // Use name of the new IAP to open global 'Open C' RConnection - QByteArray nameAsByteArray = newActiveConfig.name().toUtf8(); - ifreq ifr; - memset(&ifr, 0, sizeof(struct ifreq)); - strcpy(ifr.ifr_name, nameAsByteArray.constData()); - setdefaultif(&ifr); - - newState(QNetworkSession::Connected, iNewRoamingIap); - } -#endif -} - -void QNetworkSessionPrivate::reject() -{ -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (iMobility) { - iMobility->NewCarrierRejected(); - - if (!iALRUpgradingConnection) { - newState(QNetworkSession::Disconnected); - } else { - QNetworkConfiguration newActiveConfig = activeConfiguration(iOldRoamingIap); - - // Use name of the old IAP to open global 'Open C' RConnection - QByteArray nameAsByteArray = newActiveConfig.name().toUtf8(); - ifreq ifr; - memset(&ifr, 0, sizeof(struct ifreq)); - strcpy(ifr.ifr_name, nameAsByteArray.constData()); - setdefaultif(&ifr); - - newState(QNetworkSession::Connected, iOldRoamingIap); - } - } -#endif -} - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE -void QNetworkSessionPrivate::PreferredCarrierAvailable(TAccessPointInfo aOldAPInfo, - TAccessPointInfo aNewAPInfo, - TBool aIsUpgrade, - TBool aIsSeamless) -{ - iOldRoamingIap = aOldAPInfo.AccessPoint(); - iNewRoamingIap = aNewAPInfo.AccessPoint(); - newState(QNetworkSession::Roaming); - if (iALREnabled > 0) { - iALRUpgradingConnection = aIsUpgrade; - QList configs = publicConfig.children(); - for (int i=0; i < configs.count(); i++) { - if (configs[i].d.data()->numericId == aNewAPInfo.AccessPoint()) { - // Any slot connected to the signal might throw an std::exception, - // which must not propagate into Symbian code (this function is a callback - // from platform). We could convert exception to a symbian Leave, but since the - // prototype of this function bans this (no trailing 'L'), we just catch - // and drop. - QT_TRY { - emit q->preferredConfigurationChanged(configs[i],aIsSeamless); - } - QT_CATCH (std::exception&) {} - } - } - } else { - migrate(); - } -} - -void QNetworkSessionPrivate::NewCarrierActive(TAccessPointInfo /*aNewAPInfo*/, TBool /*aIsSeamless*/) -{ - if (iALREnabled > 0) { - QT_TRY { - emit q->newConfigurationActivated(); - } - QT_CATCH (std::exception&) {} - } else { - accept(); - } -} - -void QNetworkSessionPrivate::Error(TInt /*aError*/) -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "roaming Error() occurred, isOpen is: " << isOpen; -#endif - if (isOpen) { - isOpen = false; - isOpening = false; - activeConfig = QNetworkConfiguration(); - serviceConfig = QNetworkConfiguration(); - iError = QNetworkSession::RoamingError; - emit q->error(iError); - Cancel(); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - } - QT_TRY { - syncStateWithInterface(); - // In some cases IAP is still in Connected state when - // syncStateWithInterface(); is called - // => Following call makes sure that Session state - // changes immediately to Disconnected. - newState(QNetworkSession::Disconnected); - emit q->closed(); - } - QT_CATCH (std::exception&) {} - } else if (iStoppedByUser) { - // If the user of this session has called the stop() and - // configuration is based on internet SNAP, this needs to be - // done here because platform might roam. - QT_TRY { - newState(QNetworkSession::Disconnected); - } - QT_CATCH (std::exception&) {} - } -} -#endif - -void QNetworkSessionPrivate::setALREnabled(bool enabled) -{ - if (enabled) { - iALREnabled++; - } else { - iALREnabled--; - } -} - -QNetworkConfiguration QNetworkSessionPrivate::bestConfigFromSNAP(const QNetworkConfiguration& snapConfig) const -{ - QNetworkConfiguration config; - QList subConfigurations = snapConfig.children(); - for (int i = 0; i < subConfigurations.count(); i++ ) { - if (subConfigurations[i].state() == QNetworkConfiguration::Active) { - config = subConfigurations[i]; - break; - } else if (!config.isValid() && subConfigurations[i].state() == QNetworkConfiguration::Discovered) { - config = subConfigurations[i]; - } - } - if (!config.isValid() && subConfigurations.count() > 0) { - config = subConfigurations[0]; - } - return config; -} - -quint64 QNetworkSessionPrivate::bytesWritten() const -{ - return transferredData(KUplinkData); -} - -quint64 QNetworkSessionPrivate::bytesReceived() const -{ - return transferredData(KDownlinkData); -} - -quint64 QNetworkSessionPrivate::transferredData(TUint dataType) const -{ - if (!publicConfig.isValid()) { - return 0; - } - - QNetworkConfiguration config; - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - if (serviceConfig.isValid()) { - config = serviceConfig; - } else { - if (activeConfig.isValid()) { - config = activeConfig; - } - } - } else { - config = publicConfig; - } - - if (!config.isValid()) { - return 0; - } - - TUint count; - TRequestStatus status; - iConnectionMonitor.GetConnectionCount(count, status); - User::WaitForRequest(status); - if (status.Int() != KErrNone) { - return 0; - } - - TUint transferredData = 0; - TUint numSubConnections; - TUint connectionId; - bool configFound; - for (TUint i = 1; i <= count; i++) { - TInt ret = iConnectionMonitor.GetConnectionInfo(i, connectionId, numSubConnections); - if (ret == KErrNone) { - TUint apId; - iConnectionMonitor.GetUintAttribute(connectionId, 0, KIAPId, apId, status); - User::WaitForRequest(status); - if (status.Int() == KErrNone) { - configFound = false; - if (config.type() == QNetworkConfiguration::ServiceNetwork) { - QList configs = config.children(); - for (int i=0; i < configs.count(); i++) { - if (configs[i].d.data()->numericId == apId) { - configFound = true; - break; - } - } - } else if (config.d.data()->numericId == apId) { - configFound = true; - } - if (configFound) { - TUint tData; - iConnectionMonitor.GetUintAttribute(connectionId, 0, dataType, tData, status ); - User::WaitForRequest(status); - if (status.Int() == KErrNone) { - transferredData += tData; - } - } - } - } - } - - return transferredData; -} - -quint64 QNetworkSessionPrivate::activeTime() const -{ - if (!isOpen || startTime.isNull()) { - return 0; - } - return startTime.secsTo(QDateTime::currentDateTime()); -} - -QNetworkConfiguration QNetworkSessionPrivate::activeConfiguration(TUint32 iapId) const -{ - if (iapId == 0) { - _LIT(KSetting, "IAP\\Id"); - iConnection.GetIntSetting(KSetting, iapId); -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - // Check if this is an Easy WLAN configuration. On Symbian^3 RConnection may report - // the used configuration as 'EasyWLAN' IAP ID if someone has just opened the configuration - // from WLAN Scan dialog, _and_ that connection is still up. We need to find the - // real matching configuration. Function alters the Easy WLAN ID to real IAP ID (only if easy WLAN): - ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->easyWlanTrueIapId(iapId); -#endif - } - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) { - // Try to search IAP from the used SNAP using IAP Id - QList children = publicConfig.children(); - for (int i=0; i < children.count(); i++) { - if (children[i].d.data()->numericId == iapId) { - return children[i]; - } - } - - // Given IAP Id was not found from the used SNAP - // => Try to search matching IAP using mappingName - // mappingName contains: - // 1. "Access point name" for "Packet data" Bearer - // 2. "WLAN network name" (= SSID) for "Wireless LAN" Bearer - // 3. "Dial-up number" for "Data call Bearer" or "High Speed (GSM)" Bearer - // <=> Note: It's possible that in this case reported IAP is - // clone of the one of the IAPs of the used SNAP - // => If mappingName matches, clone has been found - QNetworkConfiguration pt; - pt.d = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.value(QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId))); - if (pt.d) { - for (int i=0; i < children.count(); i++) { - if (children[i].d.data()->mappingName == pt.d.data()->mappingName) { - return children[i]; - } - } - } else { -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - // On Symbian^3 (only, not earlier or Symbian^4) if the SNAP was not reachable, it triggers - // user choice type of activity (EasyWLAN). As a result, a new IAP may be created, and - // hence if was not found yet. Therefore update configurations and see if there is something new. - // 1. Update knowledge from the databases. - ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->updateConfigurations(); - // 2. Check if new configuration was created during connection creation - QList knownConfigs = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.keys(); -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "opened configuration was not known beforehand, looking for new."; -#endif - if (knownConfigs.count() > iKnownConfigsBeforeConnectionStart.count()) { - // Configuration count increased => new configuration was created - // => Search new, created configuration - QString newIapId; - for (int i=0; i < iKnownConfigsBeforeConnectionStart.count(); i++) { - if (knownConfigs[i] != iKnownConfigsBeforeConnectionStart[i]) { - newIapId = knownConfigs[i]; - break; - } - } - if (newIapId.isEmpty()) { - newIapId = knownConfigs[knownConfigs.count()-1]; - } - pt.d = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.value(newIapId); - if (pt.d) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "new configuration was found, name, IAP id: " << pt.name() << pt.identifier(); -#endif - return pt; - } - } -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "configuration was not found, returning invalid."; -#endif -#endif - // Given IAP Id was not found from known IAPs array - return QNetworkConfiguration(); - } - // Matching IAP was not found from used SNAP - // => IAP from another SNAP is returned - // (Note: Returned IAP matches to given IAP Id) - return pt; - } -#endif - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - if (publicConfig.d.data()->manager) { - QNetworkConfiguration pt; - // Try to found User Selected IAP from known IAPs (accessPointConfigurations) - pt.d = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.value(QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId))); - if (pt.d) { - return pt; - } else { - // Check if new (WLAN) IAP was created in IAP/SNAP dialog - // 1. Sync internal configurations array to commsdb first - ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->updateConfigurations(); - // 2. Check if new configuration was created during connection creation - QList knownConfigs = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.keys(); - if (knownConfigs.count() > iKnownConfigsBeforeConnectionStart.count()) { - // Configuration count increased => new configuration was created - // => Search new, created configuration - QString newIapId; - for (int i=0; i < iKnownConfigsBeforeConnectionStart.count(); i++) { - if (knownConfigs[i] != iKnownConfigsBeforeConnectionStart[i]) { - newIapId = knownConfigs[i]; - break; - } - } - if (newIapId.isEmpty()) { - newIapId = knownConfigs[knownConfigs.count()-1]; - } - pt.d = ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->accessPointConfigurations.value(newIapId); - if (pt.d) { - return pt; - } - } - } - } - return QNetworkConfiguration(); - } - - return publicConfig; -} - -void QNetworkSessionPrivate::RunL() -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "RConnection::RunL with status code: " << iStatus.Int(); -#endif - TInt statusCode = iStatus.Int(); - - switch (statusCode) { - case KErrNone: // Connection created successfully - { - TInt error = KErrNone; - QNetworkConfiguration newActiveConfig = activeConfiguration(); - if (!newActiveConfig.isValid()) { - // RConnection startup was successful but no configuration - // was found. That indicates that user has chosen to create a - // new WLAN configuration (from scan results), but that new - // configuration does not have access to Internet (Internet - // Connectivity Test, ICT, failed). - error = KErrGeneral; - } else { - // Use name of the IAP to open global 'Open C' RConnection - ifreq ifr; - memset(&ifr, 0, sizeof(struct ifreq)); - QByteArray nameAsByteArray = newActiveConfig.name().toUtf8(); - strcpy(ifr.ifr_name, nameAsByteArray.constData()); - error = setdefaultif(&ifr); - } - if (error != KErrNone) { - isOpen = false; - isOpening = false; - iError = QNetworkSession::UnknownSessionError; - QT_TRYCATCH_LEAVING(emit q->error(iError)); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - } - if (!newActiveConfig.isValid()) { - // No valid configuration, bail out. - // Status updates from QNCM won't be received correctly - // because there is no configuration to associate them with so transit here. - iConnection.Close(); - newState(QNetworkSession::Closing); - newState(QNetworkSession::Disconnected); - } else { - Cancel(); - } - QT_TRYCATCH_LEAVING(syncStateWithInterface()); - return; - } - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) { - // Activate ALR monitoring - iMobility = CActiveCommsMobilityApiExt::NewL(iConnection, *this); - } -#endif - isOpen = true; - isOpening = false; - activeConfig = newActiveConfig; - activeInterface = interface(activeConfig.d.data()->numericId); - if (publicConfig.type() == QNetworkConfiguration::UserChoice) { - QNetworkConfiguration pt; - pt.d = activeConfig.d.data()->serviceNetworkPtr; - serviceConfig = pt; - } - - startTime = QDateTime::currentDateTime(); - - QT_TRYCATCH_LEAVING({ - newState(QNetworkSession::Connected); - emit quitPendingWaitsForOpened(); - }); - } - break; - case KErrNotFound: // Connection failed - isOpen = false; - isOpening = false; - activeConfig = QNetworkConfiguration(); - serviceConfig = QNetworkConfiguration(); - iError = QNetworkSession::InvalidConfigurationError; - QT_TRYCATCH_LEAVING(emit q->error(iError)); - Cancel(); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - } - QT_TRYCATCH_LEAVING(syncStateWithInterface()); - break; - case KErrCancel: // Connection attempt cancelled - case KErrAlreadyExists: // Connection already exists - default: - isOpen = false; - isOpening = false; - activeConfig = QNetworkConfiguration(); - serviceConfig = QNetworkConfiguration(); - if (statusCode == KErrCancel) { - iError = QNetworkSession::SessionAbortedError; - } else if (publicConfig.state() == QNetworkConfiguration::Undefined || - publicConfig.state() == QNetworkConfiguration::Defined) { - iError = QNetworkSession::InvalidConfigurationError; - } else { - iError = QNetworkSession::UnknownSessionError; - } - QT_TRYCATCH_LEAVING(emit q->error(iError)); - Cancel(); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - } - QT_TRYCATCH_LEAVING(syncStateWithInterface()); - break; - } -} - -void QNetworkSessionPrivate::DoCancel() -{ - iConnection.Close(); -} - -// Enters newState if feasible according to current state. -// AccessPointId may be given as parameter. If it is zero, state-change is assumed to -// concern this session's configuration. If non-zero, the configuration is looked up -// and checked if it matches the configuration this session is based on. -bool QNetworkSessionPrivate::newState(QNetworkSession::State newState, TUint accessPointId) -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " - << "NEW STATE, IAP ID : " << QString::number(accessPointId) << " , newState : " << QString::number(newState); -#endif - // Make sure that activeConfig is always updated when SNAP is signaled to be - // connected. - if (isOpen && publicConfig.type() == QNetworkConfiguration::ServiceNetwork && - newState == QNetworkSession::Connected) { - activeConfig = activeConfiguration(accessPointId); - activeInterface = interface(activeConfig.d.data()->numericId); - } - - // Make sure that same state is not signaled twice in a row. - if (state == newState) { - return true; - } - - // Make sure that Connecting state does not overwrite Roaming state - if (state == QNetworkSession::Roaming && newState == QNetworkSession::Connecting) { - return false; - } - - // Make sure that Connected state is not reported when Connection is - // already Closing. - // Note: Stopping connection results sometimes KLinkLayerOpen - // to be reported first (just before KLinkLayerClosed). - if (state == QNetworkSession::Closing && newState == QNetworkSession::Connected) { - return false; - } - - // Make sure that some lagging 'closing' state-changes do not overwrite - // if we are already disconnected or closed. - if (state == QNetworkSession::Disconnected && newState == QNetworkSession::Closing) { - return false; - } - - // Make sure that some lagging 'connecting' state-changes do not overwrite - // if we are already connected (may righfully still happen with roaming though). - if (state == QNetworkSession::Connected && newState == QNetworkSession::Connecting) { - return false; - } - - bool emitSessionClosed = false; - - // If we abruptly go down and user hasn't closed the session, we've been aborted. - // Note that session may be in 'closing' state and not in 'connected' state, because - // depending on platform the platform may report KConfigDaemonStartingDeregistration - // event before KLinkLayerClosed - if ((isOpen && state == QNetworkSession::Connected && newState == QNetworkSession::Disconnected) || - (isOpen && !iClosedByUser && newState == QNetworkSession::Disconnected)) { - // Active & Connected state should change directly to Disconnected state - // only when something forces connection to close (eg. when another - // application or session stops connection or when network drops - // unexpectedly). - isOpen = false; - isOpening = false; - activeConfig = QNetworkConfiguration(); - serviceConfig = QNetworkConfiguration(); - iError = QNetworkSession::SessionAbortedError; - emit q->error(iError); - Cancel(); - if (ipConnectionNotifier) { - ipConnectionNotifier->StopNotifications(); - } - // Start handling IAP state change signals from QNetworkConfigurationManagerPrivate - iHandleStateNotificationsFromManager = true; - emitSessionClosed = true; // Emit SessionClosed after state change has been reported - } - - bool retVal = false; - if (accessPointId == 0) { - state = newState; -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed A to: " << state; -#endif - emit q->stateChanged(state); - retVal = true; - } else { - if (publicConfig.type() == QNetworkConfiguration::InternetAccessPoint) { - if (publicConfig.d.data()->numericId == accessPointId) { - state = newState; -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed B to: " << state; -#endif - emit q->stateChanged(state); - retVal = true; - } - } else if (publicConfig.type() == QNetworkConfiguration::UserChoice && isOpen) { - if (activeConfig.d.data()->numericId == accessPointId) { - state = newState; -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed C to: " << state; -#endif - emit q->stateChanged(state); - retVal = true; - } - } else if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) { - QList subConfigurations = publicConfig.children(); - for (int i = 0; i < subConfigurations.count(); i++) { - if (subConfigurations[i].d.data()->numericId == accessPointId) { - if (newState != QNetworkSession::Disconnected) { - state = newState; -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed D to: " << state; -#endif - emit q->stateChanged(state); - retVal = true; - } else { - QNetworkConfiguration config = bestConfigFromSNAP(publicConfig); - if ((config.state() == QNetworkConfiguration::Defined) || - (config.state() == QNetworkConfiguration::Discovered)) { - activeConfig = QNetworkConfiguration(); - state = newState; -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed E to: " << state; -#endif - emit q->stateChanged(state); - retVal = true; - } else if (config.state() == QNetworkConfiguration::Active) { - // Connection to used IAP was closed, but there is another - // IAP that's active in used SNAP - // => Change state back to Connected - state = QNetworkSession::Connected; - emit q->stateChanged(state); - retVal = true; -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed F to: " << state; -#endif - } - } - } - } -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - // If the retVal is not true here, it means that the status update may apply to an IAP outside of - // SNAP (session is based on SNAP but follows IAP outside of it), which may occur on Symbian^3 EasyWlan. - if (retVal == false && activeConfig.d.data() && activeConfig.d.data()->numericId == accessPointId) { -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed G to: " << state; -#endif - if (newState == QNetworkSession::Disconnected) { - activeConfig = QNetworkConfiguration(); - } - state = newState; - emit q->stateChanged(state); - retVal = true; - } -#endif - } - } - if (emitSessionClosed) { - emit q->closed(); - } - if (state == QNetworkSession::Disconnected) { - // Just in case clear activeConfiguration. - activeConfig = QNetworkConfiguration(); - } - return retVal; -} - -void QNetworkSessionPrivate::handleSymbianConnectionStatusChange(TInt aConnectionStatus, - TInt aError, - TUint accessPointId) -{ -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << QString::number(accessPointId) << " , status : " << QString::number(aConnectionStatus); -#endif - switch (aConnectionStatus) - { - // Connection unitialised - case KConnectionUninitialised: - break; - - // Starting connetion selection - case KStartingSelection: - break; - - // Selection finished - case KFinishedSelection: - if (aError == KErrNone) - { - break; - } - else - { - // The user pressed e.g. "Cancel" and did not select an IAP - newState(QNetworkSession::Disconnected,accessPointId); - } - break; - - // Connection failure - case KConnectionFailure: - newState(QNetworkSession::NotAvailable); - break; - - // Prepearing connection (e.g. dialing) - case KPsdStartingConfiguration: - case KPsdFinishedConfiguration: - case KCsdFinishedDialling: - case KCsdScanningScript: - case KCsdGettingLoginInfo: - case KCsdGotLoginInfo: - break; - - case KConfigDaemonStartingRegistration: - // Creating connection (e.g. GPRS activation) - case KCsdStartingConnect: - case KCsdFinishedConnect: - newState(QNetworkSession::Connecting,accessPointId); - break; - - // Starting log in - case KCsdStartingLogIn: - break; - - // Finished login - case KCsdFinishedLogIn: - break; - - // Connection open - case KConnectionOpen: - break; - - case KLinkLayerOpen: - newState(QNetworkSession::Connected,accessPointId); - break; - - // Connection blocked or suspended - case KDataTransferTemporarilyBlocked: - break; - - case KConfigDaemonStartingDeregistration: - // Hangup or GRPS deactivation - case KConnectionStartingClose: - newState(QNetworkSession::Closing,accessPointId); - break; - - // Connection closed - case KConnectionClosed: - case KLinkLayerClosed: - newState(QNetworkSession::Disconnected,accessPointId); - // Report manager about this to make sure this event - // is received by all interseted parties (mediated by - // manager because it does always receive all events from - // connection monitor). -#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG - qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "reporting disconnection to manager."; -#endif - if (publicConfig.d.data()) { - ((QNetworkConfigurationManagerPrivate*)publicConfig.d.data()->manager)->configurationStateChangeReport(publicConfig.d.data()->numericId, QNetworkSession::Disconnected); - } - break; - // Unhandled state - default: - break; - } -} - -ConnectionProgressNotifier::ConnectionProgressNotifier(QNetworkSessionPrivate& owner, RConnection& connection) - : CActive(CActive::EPriorityUserInput), iOwner(owner), iConnection(connection) -{ - CActiveScheduler::Add(this); -} - -ConnectionProgressNotifier::~ConnectionProgressNotifier() -{ - Cancel(); -} - -void ConnectionProgressNotifier::StartNotifications() -{ - if (!IsActive()) { - SetActive(); - } - iConnection.ProgressNotification(iProgress, iStatus); -} - -void ConnectionProgressNotifier::StopNotifications() -{ - Cancel(); -} - -void ConnectionProgressNotifier::DoCancel() -{ - iConnection.CancelProgressNotification(); -} - -void ConnectionProgressNotifier::RunL() -{ - if (iStatus == KErrNone) { - QT_TRYCATCH_LEAVING(iOwner.handleSymbianConnectionStatusChange(iProgress().iStage, iProgress().iError)); - - SetActive(); - iConnection.ProgressNotification(iProgress, iStatus); - } -} - -#include "moc_qnetworksession_s60_p.cpp" - -QTM_END_NAMESPACE diff --git a/src/bearer/qnetworksession_s60_p.h b/src/bearer/qnetworksession_s60_p.h deleted file mode 100644 index e6a9aba..0000000 --- a/src/bearer/qnetworksession_s60_p.h +++ /dev/null @@ -1,223 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKSESSIONPRIVATE_H -#define QNETWORKSESSIONPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qnetworksession.h" - -#include - -#include -#include -#include -#include -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - #include -#endif -#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE) - #include -#endif - -QTM_BEGIN_NAMESPACE - -class ConnectionProgressNotifier; -typedef void (*TOpenCUnSetdefaultifFunction)(); - -class QNetworkSessionPrivate : public QObject, public CActive -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - , public MMobilityProtocolResp -#endif -{ - Q_OBJECT -public: - QNetworkSessionPrivate(); - ~QNetworkSessionPrivate(); - - //called by QNetworkSession constructor and ensures - //that the state is immediately updated (w/o actually opening - //a session). Also this function should take care of - //notification hooks to discover future state changes. - void syncStateWithInterface(); - - QNetworkInterface currentInterface() const; - QVariant sessionProperty(const QString& key) const; - void setSessionProperty(const QString& key, const QVariant& value); - - void setALREnabled(bool enabled); - - void open(); - void close(bool allowSignals = true); - void stop(); - void migrate(); - void accept(); - void ignore(); - void reject(); - - QString errorString() const; //must return translated string - QNetworkSession::SessionError error() const; - quint64 bytesWritten() const; - quint64 bytesReceived() const; - quint64 activeTime() const; - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE -public: // From MMobilityProtocolResp - void PreferredCarrierAvailable(TAccessPointInfo aOldAPInfo, - TAccessPointInfo aNewAPInfo, - TBool aIsUpgrade, - TBool aIsSeamless); - - void NewCarrierActive(TAccessPointInfo aNewAPInfo, TBool aIsSeamless); - - void Error(TInt aError); -#endif - -Q_SIGNALS: - //releases any pending waitForOpened() calls - void quitPendingWaitsForOpened(); - -protected: // From CActive - void RunL(); - void DoCancel(); - -private Q_SLOTS: - void configurationStateChanged(TUint32 accessPointId, TUint32 connMonId, QNetworkSession::State newState); - void configurationRemoved(const QNetworkConfiguration& config); - void configurationAdded(const QNetworkConfiguration& config); - -private: - TUint iapClientCount(TUint aIAPId) const; - quint64 transferredData(TUint dataType) const; - bool newState(QNetworkSession::State newState, TUint accessPointId = 0); - void handleSymbianConnectionStatusChange(TInt aConnectionStatus, TInt aError, TUint accessPointId = 0); - QNetworkConfiguration bestConfigFromSNAP(const QNetworkConfiguration& snapConfig) const; - QNetworkConfiguration activeConfiguration(TUint32 iapId = 0) const; - QNetworkInterface interface(TUint iapId) const; - -private: // data - // The config set on QNetworkSession - mutable QNetworkConfiguration publicConfig; - - // If publicConfig is a ServiceNetwork this is a copy of publicConfig. - // If publicConfig is an UserChoice that is resolved to a ServiceNetwork this is the actual - // ServiceNetwork configuration. - mutable QNetworkConfiguration serviceConfig; - - // This is the actual active configuration currently in use by the session. - // Either a copy of publicConfig or one of serviceConfig.children(). - mutable QNetworkConfiguration activeConfig; - - mutable QNetworkInterface activeInterface; - - QNetworkSession::State state; - bool isOpen; - - QNetworkSession* q; - QDateTime startTime; - - RLibrary iOpenCLibrary; - TOpenCUnSetdefaultifFunction iDynamicUnSetdefaultif; - - mutable RSocketServ iSocketServ; - mutable RConnection iConnection; - mutable RConnectionMonitor iConnectionMonitor; - ConnectionProgressNotifier* ipConnectionNotifier; - - bool iHandleStateNotificationsFromManager; - bool iFirstSync; - bool iStoppedByUser; - bool iClosedByUser; - -#ifdef SNAP_FUNCTIONALITY_AVAILABLE - CActiveCommsMobilityApiExt* iMobility; -#endif - - QNetworkSession::SessionError iError; - TInt iALREnabled; - TBool iALRUpgradingConnection; - TBool iConnectInBackground; - - QList iKnownConfigsBeforeConnectionStart; - - TUint32 iOldRoamingIap; - TUint32 iNewRoamingIap; - - bool isOpening; - - friend class QNetworkSession; - friend class ConnectionProgressNotifier; -}; - -class ConnectionProgressNotifier : public CActive -{ -public: - ConnectionProgressNotifier(QNetworkSessionPrivate& owner, RConnection& connection); - ~ConnectionProgressNotifier(); - - void StartNotifications(); - void StopNotifications(); - -protected: // From CActive - void RunL(); - void DoCancel(); - -private: // Data - QNetworkSessionPrivate& iOwner; - RConnection& iConnection; - TNifProgressBuf iProgress; - -}; - -QTM_END_NAMESPACE - -#endif //QNETWORKSESSIONPRIVATE_H - diff --git a/src/bearer/qnetworksessionadaptor_p.h b/src/bearer/qnetworksessionadaptor_p.h new file mode 100644 index 0000000..4d590ff --- /dev/null +++ b/src/bearer/qnetworksessionadaptor_p.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#ifndef QNETWORKSESSIONADAPTOR_P_H_ +#define QNETWORKSESSIONADAPTOR_P_H_ + + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE +//this class exists only to workaround moc issues with namespaces +class QNetworkSessionAdaptor : public QObject +{ + Q_OBJECT +protected Q_SLOTS: + virtual void _q_stateChanged(QNetworkSession::State) = 0; + virtual void _q_error(QNetworkSession::SessionError) = 0; + virtual void _q_preferredConfigurationChanged(const QNetworkConfiguration& config, bool isSeamless) = 0; +}; +QT_END_NAMESPACE + + +#endif /* QNETWORKSESSIONADAPTOR_P_H_ */ diff --git a/src/bearer/qnetworksessionengine.cpp b/src/bearer/qnetworksessionengine.cpp deleted file mode 100644 index 280838a..0000000 --- a/src/bearer/qnetworksessionengine.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnetworksessionengine_p.h" - -QTM_BEGIN_NAMESPACE - -QNetworkSessionEngine::QNetworkSessionEngine(QObject *parent) -: QObject(parent) -{ -} - -QNetworkSessionEngine::~QNetworkSessionEngine() -{ -} - -#include "moc_qnetworksessionengine_p.cpp" -QTM_END_NAMESPACE - diff --git a/src/bearer/qnetworksessionengine_p.h b/src/bearer/qnetworksessionengine_p.h deleted file mode 100644 index d856e15..0000000 --- a/src/bearer/qnetworksessionengine_p.h +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKSESSIONENGINE_P_H -#define QNETWORKSESSIONENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; -class QNetworkSessionEngine : public QObject -{ - Q_OBJECT - -public: - enum ConnectionError { - InterfaceLookupError = 0, - ConnectError, - OperationNotSupported, - DisconnectionError, - }; - - QNetworkSessionEngine(QObject *parent = 0); - virtual ~QNetworkSessionEngine(); - - virtual QList getConfigurations(bool *ok = 0) = 0; - virtual QString getInterfaceFromId(const QString &id) = 0; - virtual bool hasIdentifier(const QString &id) = 0; - - //virtual QString bearerName(const QString &id) = 0; - - virtual void connectToId(const QString &id) = 0; - virtual void disconnectFromId(const QString &id) = 0; - - virtual void requestUpdate() = 0; - -Q_SIGNALS: - void configurationsChanged(); - void connectionError(const QString &id, QNetworkSessionEngine::ConnectionError error); -}; - -QTM_END_NAMESPACE - -#endif diff --git a/src/bearer/qnetworksessionengine_win_p.h b/src/bearer/qnetworksessionengine_win_p.h deleted file mode 100644 index 94859b7..0000000 --- a/src/bearer/qnetworksessionengine_win_p.h +++ /dev/null @@ -1,145 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNETWORKSESSIONENGINE_WIN_P_H -#define QNETWORKSESSIONENGINE_WIN_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#undef interface -#include - -#ifndef NS_NLA - -#define NS_NLA 15 - -enum NLA_BLOB_DATA_TYPE { - NLA_RAW_DATA = 0, - NLA_INTERFACE = 1, - NLA_802_1X_LOCATION = 2, - NLA_CONNECTIVITY = 3, - NLA_ICS = 4 -}; - -enum NLA_CONNECTIVITY_TYPE { - NLA_NETWORK_AD_HOC = 0, - NLA_NETWORK_MANAGED = 1, - NLA_NETWORK_UNMANAGED = 2, - NLA_NETWORK_UNKNOWN = 3 -}; - -enum NLA_INTERNET { - NLA_INTERNET_UNKNOWN = 0, - NLA_INTERNET_NO = 1, - NLA_INTERNET_YES = 2 -}; - -struct NLA_BLOB { - struct { - NLA_BLOB_DATA_TYPE type; - DWORD dwSize; - DWORD nextOffset; - } header; - - union { - // NLA_RAW_DATA - CHAR rawData[1]; - - // NLA_INTERFACE - struct { - DWORD dwType; - DWORD dwSpeed; - CHAR adapterName[1]; - } interfaceData; - - // NLA_802_1X_LOCATION - struct { - CHAR information[1]; - } locationData; - - // NLA_CONNECTIVITY - struct { - NLA_CONNECTIVITY_TYPE type; - NLA_INTERNET internet; - } connectivity; - - // NLA_ICS - struct { - struct { - DWORD speed; - DWORD type; - DWORD state; - WCHAR machineName[256]; - WCHAR sharedAdapterName[256]; - } remote; - } ICS; - } data; -}; -#endif - -enum NDIS_MEDIUM { - NdisMedium802_3 = 0, -}; - -enum NDIS_PHYSICAL_MEDIUM { - NdisPhysicalMediumWirelessLan = 1, - NdisPhysicalMediumBluetooth = 10, - NdisPhysicalMediumWiMax = 12, -}; - -#define OID_GEN_MEDIA_SUPPORTED 0x00010103 -#define OID_GEN_PHYSICAL_MEDIUM 0x00010202 - -#define IOCTL_NDIS_QUERY_GLOBAL_STATS \ - CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD, 0, METHOD_OUT_DIRECT, FILE_ANY_ACCESS) - -#endif // QNETWORKSESSIONENGINE_WIN_P_H diff --git a/src/bearer/qnlaengine_win.cpp b/src/bearer/qnlaengine_win.cpp deleted file mode 100644 index abed0c6..0000000 --- a/src/bearer/qnlaengine_win.cpp +++ /dev/null @@ -1,600 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnlaengine_win_p.h" -#include "qnetworkconfiguration_p.h" - -#include -#include -#include -#include - -#include - -#include "qnetworksessionengine_win_p.h" - -QTM_BEGIN_NAMESPACE - -Q_GLOBAL_STATIC(QNlaEngine, nlaEngine) - -QWindowsSockInit::QWindowsSockInit() -: version(0) -{ - //### should we try for 2.2 on all platforms ?? - WSAData wsadata; - - // IPv6 requires Winsock v2.0 or better. - if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) { - qWarning("QBearerManagementAPI: WinSock v2.0 initialization failed."); - } else { - version = 0x20; - } -} - -QWindowsSockInit::~QWindowsSockInit() -{ - WSACleanup(); -} - -#ifdef BEARER_MANAGEMENT_DEBUG -static void printBlob(NLA_BLOB *blob) -{ - qDebug() << "==== BEGIN NLA_BLOB ===="; - - qDebug() << "type:" << blob->header.type; - qDebug() << "size:" << blob->header.dwSize; - qDebug() << "next offset:" << blob->header.nextOffset; - - switch (blob->header.type) { - case NLA_RAW_DATA: - qDebug() << "Raw Data"; - qDebug() << '\t' << blob->data.rawData; - break; - case NLA_INTERFACE: - qDebug() << "Interface"; - qDebug() << "\ttype:" << blob->data.interfaceData.dwType; - qDebug() << "\tspeed:" << blob->data.interfaceData.dwSpeed; - qDebug() << "\tadapter:" << blob->data.interfaceData.adapterName; - break; - case NLA_802_1X_LOCATION: - qDebug() << "802.1x Location"; - qDebug() << '\t' << blob->data.locationData.information; - break; - case NLA_CONNECTIVITY: - qDebug() << "Connectivity"; - qDebug() << "\ttype:" << blob->data.connectivity.type; - qDebug() << "\tinternet:" << blob->data.connectivity.internet; - break; - case NLA_ICS: - qDebug() << "ICS"; - qDebug() << "\tspeed:" << blob->data.ICS.remote.speed; - qDebug() << "\ttype:" << blob->data.ICS.remote.type; - qDebug() << "\tstate:" << blob->data.ICS.remote.state; - qDebug() << "\tmachine name:" << blob->data.ICS.remote.machineName; - qDebug() << "\tshared adapter name:" << blob->data.ICS.remote.sharedAdapterName; - break; - default: - qDebug() << "UNKNOWN BLOB TYPE"; - } - - qDebug() << "===== END NLA_BLOB ====="; -} -#endif - -static QString qGetInterfaceType(const QString &interface) -{ -#ifdef Q_OS_WINCE - Q_UNUSED(interface) -#else - unsigned long oid; - DWORD bytesWritten; - - NDIS_MEDIUM medium; - NDIS_PHYSICAL_MEDIUM physicalMedium; - - HANDLE handle = CreateFile((TCHAR *)QString("\\\\.\\%1").arg(interface).utf16(), 0, - FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); - if (handle == INVALID_HANDLE_VALUE) - return QLatin1String("Unknown"); - - oid = OID_GEN_MEDIA_SUPPORTED; - bytesWritten = 0; - bool result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid), - &medium, sizeof(medium), &bytesWritten, 0); - if (!result) { - CloseHandle(handle); - return QLatin1String("Unknown"); - } - - oid = OID_GEN_PHYSICAL_MEDIUM; - bytesWritten = 0; - result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid), - &physicalMedium, sizeof(physicalMedium), &bytesWritten, 0); - if (!result) { - CloseHandle(handle); - - if (medium == NdisMedium802_3) - return QLatin1String("Ethernet"); - else - return QLatin1String("Unknown"); - } - - CloseHandle(handle); - - if (medium == NdisMedium802_3) { - switch (physicalMedium) { - case NdisPhysicalMediumWirelessLan: - return QLatin1String("WLAN"); - case NdisPhysicalMediumBluetooth: - return QLatin1String("Bluetooth"); - case NdisPhysicalMediumWiMax: - return QLatin1String("WiMAX"); - default: -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "Physical Medium" << physicalMedium; -#endif - return QLatin1String("Ethernet"); - } - } - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << medium << physicalMedium; -#endif - -#endif - - return QLatin1String("Unknown"); -} - -class QNlaThread : public QThread -{ - Q_OBJECT - -public: - QNlaThread(QNlaEngine *parent = 0); - ~QNlaThread(); - - QList getConfigurations(); - - void forceUpdate(); - -protected: - virtual void run(); - -private: - void updateConfigurations(QList &configs); - DWORD parseBlob(NLA_BLOB *blob, QNetworkConfigurationPrivate *cpPriv) const; - QNetworkConfigurationPrivate *parseQuerySet(const WSAQUERYSET *querySet) const; - void fetchConfigurations(); - -signals: - void networksChanged(); - -private: - QMutex mutex; - HANDLE handle; - bool done; - QList fetchedConfigurations; -}; - -QNlaThread::QNlaThread(QNlaEngine *parent) -: QThread(parent), handle(0), done(false) -{ -} - -QNlaThread::~QNlaThread() -{ - mutex.lock(); - - done = true; - - if (handle) { - /* cancel completion event */ - if (WSALookupServiceEnd(handle) == SOCKET_ERROR) - qWarning("WSALookupServiceEnd error %d", WSAGetLastError()); - } - mutex.unlock(); - - wait(); -} - -QList QNlaThread::getConfigurations() -{ - QMutexLocker locker(&mutex); - - QList foundConfigurations; - - for (int i = 0; i < fetchedConfigurations.count(); ++i) { - QNetworkConfigurationPrivate *config = new QNetworkConfigurationPrivate; - config->name = fetchedConfigurations.at(i)->name; - config->isValid = fetchedConfigurations.at(i)->isValid; - config->id = fetchedConfigurations.at(i)->id; - config->state = fetchedConfigurations.at(i)->state; - config->type = fetchedConfigurations.at(i)->type; - config->roamingSupported = fetchedConfigurations.at(i)->roamingSupported; - config->purpose = fetchedConfigurations.at(i)->purpose; - config->internet = fetchedConfigurations.at(i)->internet; - if (QNlaEngine *engine = qobject_cast(parent())) { - config->bearer = engine->bearerName(config->id); - } - - foundConfigurations.append(config); - } - - return foundConfigurations; -} - -void QNlaThread::forceUpdate() -{ - mutex.lock(); - - if (handle) { - /* cancel completion event */ - if (WSALookupServiceEnd(handle) == SOCKET_ERROR) - qWarning("WSALookupServiceEnd error %d", WSAGetLastError()); - handle = 0; - } - mutex.unlock(); -} - -void QNlaThread::run() -{ - WSAEVENT changeEvent = WSACreateEvent(); - if (changeEvent == WSA_INVALID_EVENT) { - qWarning("WSACreateEvent error %d", WSAGetLastError()); - return; - } - - while (true) { - fetchConfigurations(); - - WSAQUERYSET qsRestrictions; - - memset(&qsRestrictions, 0, sizeof(qsRestrictions)); - qsRestrictions.dwSize = sizeof(qsRestrictions); - qsRestrictions.dwNameSpace = NS_NLA; - - mutex.lock(); - if (done) { - mutex.unlock(); - break; - } - int result = WSALookupServiceBegin(&qsRestrictions, LUP_RETURN_ALL, &handle); - mutex.unlock(); - - if (result == SOCKET_ERROR) { - qWarning("%s: WSALookupServiceBegin error %d", __FUNCTION__, WSAGetLastError()); - break; - } - - WSACOMPLETION completion; - WSAOVERLAPPED overlapped; - - memset(&overlapped, 0, sizeof(overlapped)); - overlapped.hEvent = changeEvent; - - memset(&completion, 0, sizeof(completion)); - completion.Type = NSP_NOTIFY_EVENT; - completion.Parameters.Event.lpOverlapped = &overlapped; - - DWORD bytesReturned = 0; - result = WSANSPIoctl(handle, SIO_NSP_NOTIFY_CHANGE, 0, 0, 0, 0, - &bytesReturned, &completion); - if (result == SOCKET_ERROR) { - int error = WSAGetLastError(); - if (error != WSA_IO_PENDING) { - qWarning("WSANSPIoctl error %d", error); - break; - } - } - -#ifndef Q_OS_WINCE - // Not interested in unrelated IO completion events - // although we also don't want to block them - while (WaitForSingleObjectEx(changeEvent, WSA_INFINITE, true) != WAIT_IO_COMPLETION) {} -#else - WaitForSingleObject(changeEvent, WSA_INFINITE); -#endif - - mutex.lock(); - if (handle) { - result = WSALookupServiceEnd(handle); - if (result == SOCKET_ERROR) { - qWarning("WSALookupServiceEnd error %d", WSAGetLastError()); - mutex.unlock(); - break; - } - handle = 0; - } - mutex.unlock(); - } - - WSACloseEvent(changeEvent); -} - -void QNlaThread::updateConfigurations(QList &configs) -{ - mutex.lock(); - - while (!fetchedConfigurations.isEmpty()) - delete fetchedConfigurations.takeFirst(); - - fetchedConfigurations = configs; - - mutex.unlock(); - - emit networksChanged(); -} - -DWORD QNlaThread::parseBlob(NLA_BLOB *blob, QNetworkConfigurationPrivate *cpPriv) const -{ -#ifdef BEARER_MANAGEMENT_DEBUG - printBlob(blob); -#endif - - switch (blob->header.type) { - case NLA_RAW_DATA: -#ifdef BEARER_MANAGEMENT_DEBUG - qWarning("%s: unhandled header type NLA_RAW_DATA", __FUNCTION__); -#endif - break; - case NLA_INTERFACE: - cpPriv->state = QNetworkConfiguration::Active; - if (QNlaEngine *engine = qobject_cast(parent())) { - engine->configurationInterface[cpPriv->id.toUInt()] = - QString(blob->data.interfaceData.adapterName); - } - break; - case NLA_802_1X_LOCATION: -#ifdef BEARER_MANAGEMENT_DEBUG - qWarning("%s: unhandled header type NLA_802_1X_LOCATION", __FUNCTION__); -#endif - break; - case NLA_CONNECTIVITY: - if (blob->data.connectivity.internet == NLA_INTERNET_YES) - cpPriv->internet = true; - else - cpPriv->internet = false; -#ifdef BEARER_MANAGEMENT_DEBUG - qWarning("%s: unhandled header type NLA_CONNECTIVITY", __FUNCTION__); -#endif - break; - case NLA_ICS: -#ifdef BEARER_MANAGEMENT_DEBUG - qWarning("%s: unhandled header type NLA_ICS", __FUNCTION__); -#endif - break; - default: -#ifdef BEARER_MANAGEMENT_DEBUG - qWarning("%s: unhandled header type %d", __FUNCTION__, blob->header.type); -#endif - ; - } - - return blob->header.nextOffset; -} - -QNetworkConfigurationPrivate *QNlaThread::parseQuerySet(const WSAQUERYSET *querySet) const -{ - QNetworkConfigurationPrivate *cpPriv = new QNetworkConfigurationPrivate; - - cpPriv->name = QString::fromWCharArray(querySet->lpszServiceInstanceName); - cpPriv->isValid = true; - cpPriv->id = QString::number(qHash(QLatin1String("NLA:") + cpPriv->name)); - cpPriv->state = QNetworkConfiguration::Defined; - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "size:" << querySet->dwSize; - qDebug() << "service instance name:" << QString::fromUtf16(querySet->lpszServiceInstanceName); - qDebug() << "service class id:" << querySet->lpServiceClassId; - qDebug() << "version:" << querySet->lpVersion; - qDebug() << "comment:" << QString::fromUtf16(querySet->lpszComment); - qDebug() << "namespace:" << querySet->dwNameSpace; - qDebug() << "namespace provider id:" << querySet->lpNSProviderId; - qDebug() << "context:" << QString::fromUtf16(querySet->lpszContext); - qDebug() << "number of protocols:" << querySet->dwNumberOfProtocols; - qDebug() << "protocols:" << querySet->lpafpProtocols; - qDebug() << "query string:" << QString::fromUtf16(querySet->lpszQueryString); - qDebug() << "number of cs addresses:" << querySet->dwNumberOfCsAddrs; - qDebug() << "cs addresses:" << querySet->lpcsaBuffer; - qDebug() << "output flags:" << querySet->dwOutputFlags; -#endif - - if (querySet->lpBlob) { -#ifdef BEARER_MANAGEMENT_DEBUG - qDebug() << "blob size:" << querySet->lpBlob->cbSize; - qDebug() << "blob data:" << querySet->lpBlob->pBlobData; -#endif - - DWORD offset = 0; - do { - NLA_BLOB *blob = reinterpret_cast(querySet->lpBlob->pBlobData + offset); - DWORD nextOffset = parseBlob(blob, cpPriv); - if (nextOffset == offset) - break; - else - offset = nextOffset; - } while (offset != 0 && offset < querySet->lpBlob->cbSize); - } - - return cpPriv; -} - -void QNlaThread::fetchConfigurations() -{ - QList foundConfigurations; - - WSAQUERYSET qsRestrictions; - HANDLE hLookup = 0; - - memset(&qsRestrictions, 0, sizeof(qsRestrictions)); - qsRestrictions.dwSize = sizeof(qsRestrictions); - qsRestrictions.dwNameSpace = NS_NLA; - - int result = WSALookupServiceBegin(&qsRestrictions, LUP_RETURN_ALL | LUP_DEEP, &hLookup); - if (result == SOCKET_ERROR) { - qWarning("%s: WSALookupServiceBegin error %d", __FUNCTION__, WSAGetLastError()); - mutex.lock(); - fetchedConfigurations.clear(); - mutex.unlock(); - } - - char buffer[0x10000]; - while (result == 0) { - DWORD bufferLength = sizeof(buffer); - result = WSALookupServiceNext(hLookup, LUP_RETURN_ALL, - &bufferLength, reinterpret_cast(buffer)); - - if (result == SOCKET_ERROR) { - int error = WSAGetLastError(); - - if (error == WSA_E_NO_MORE) - break; - - if (error == WSAEFAULT) { - qDebug() << "buffer not big enough" << bufferLength; - break; - } - - qWarning("WSALookupServiceNext error %d", WSAGetLastError()); - break; - } - - QNetworkConfigurationPrivate *cpPriv = - parseQuerySet(reinterpret_cast(buffer)); - - foundConfigurations.append(cpPriv); - } - - if (hLookup) { - result = WSALookupServiceEnd(hLookup); - if (result == SOCKET_ERROR) { - qWarning("WSALookupServiceEnd error %d", WSAGetLastError()); - } - } - - updateConfigurations(foundConfigurations); -} - -QNlaEngine::QNlaEngine(QObject *parent) -: QNetworkSessionEngine(parent), nlaThread(0) -{ - nlaThread = new QNlaThread(this); - connect(nlaThread, SIGNAL(networksChanged()), - this, SIGNAL(configurationsChanged())); - nlaThread->start(); - - qApp->processEvents(QEventLoop::ExcludeUserInputEvents); -} - -QNlaEngine::~QNlaEngine() -{ - delete nlaThread; -} - -QList QNlaEngine::getConfigurations(bool *ok) -{ - if (ok) - *ok = true; - - return nlaThread->getConfigurations(); -} - -QString QNlaEngine::getInterfaceFromId(const QString &id) -{ - return configurationInterface.value(id.toUInt()); -} - -bool QNlaEngine::hasIdentifier(const QString &id) -{ - if (configurationInterface.contains(id.toUInt())) - return true; - - bool result = false; - QList l = nlaThread->getConfigurations(); - while (!l.isEmpty()) { - QNetworkConfigurationPrivate* cpPriv = l.takeFirst(); - if (!result && cpPriv->id == id) { - result = true; - } - delete cpPriv; - } - - return result; -} - -QString QNlaEngine::bearerName(const QString &id) -{ - QString interface = getInterfaceFromId(id); - - if (interface.isEmpty()) - return QString(); - - return qGetInterfaceType(interface); -} - -void QNlaEngine::connectToId(const QString &id) -{ - emit connectionError(id, OperationNotSupported); -} - -void QNlaEngine::disconnectFromId(const QString &id) -{ - emit connectionError(id, OperationNotSupported); -} - -void QNlaEngine::requestUpdate() -{ - nlaThread->forceUpdate(); -} - -QNlaEngine *QNlaEngine::instance() -{ - return nlaEngine(); -} - -#include "qnlaengine_win.moc" -#include "moc_qnlaengine_win_p.cpp" -QTM_END_NAMESPACE - - - diff --git a/src/bearer/qnlaengine_win_p.h b/src/bearer/qnlaengine_win_p.h deleted file mode 100644 index 8284a36..0000000 --- a/src/bearer/qnlaengine_win_p.h +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNLAENGINE_P_H -#define QNLAENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qnetworksessionengine_p.h" - -#include - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; -class QNlaThread; - -class QWindowsSockInit -{ -public: - QWindowsSockInit(); - ~QWindowsSockInit(); - int version; -}; - -class QNlaEngine : public QNetworkSessionEngine -{ - Q_OBJECT - - friend class QNlaThread; - -public: - QNlaEngine(QObject *parent = 0); - ~QNlaEngine(); - - QList getConfigurations(bool *ok = 0); - QString getInterfaceFromId(const QString &id); - bool hasIdentifier(const QString &id); - - QString bearerName(const QString &id); - - void connectToId(const QString &id); - void disconnectFromId(const QString &id); - - void requestUpdate(); - - static QNlaEngine *instance(); - -private: - QWindowsSockInit winSock; - QNlaThread *nlaThread; - QMap configurationInterface; -}; - -QTM_END_NAMESPACE - -#endif diff --git a/src/bearer/qnmdbushelper.cpp b/src/bearer/qnmdbushelper.cpp deleted file mode 100644 index d1de622..0000000 --- a/src/bearer/qnmdbushelper.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// this class is for helping qdbus get stuff - -#include "qnmdbushelper_p.h" - -#if !defined(QT_NO_DBUS) && !defined(Q_OS_MAC) -#include "qnetworkmanagerservice_p.h" - -#include -#include -#include -#include -#endif - -#include - -QTM_BEGIN_NAMESPACE - - -QNmDBusHelper::QNmDBusHelper(QObject * parent) - : QObject(parent) -{ -} - -QNmDBusHelper::~QNmDBusHelper() -{ -} - -void QNmDBusHelper::deviceStateChanged(quint32 state) - { - QDBusMessage msg = this->message(); - if(state == NM_DEVICE_STATE_ACTIVATED - || state == NM_DEVICE_STATE_DISCONNECTED - || state == NM_DEVICE_STATE_UNAVAILABLE - || state == NM_DEVICE_STATE_FAILED) { - emit pathForStateChanged(msg.path(), state); - } - } - -void QNmDBusHelper::slotAccessPointAdded(QDBusObjectPath path) -{ - if(path.path().length() > 2) { - QDBusMessage msg = this->message(); - emit pathForAccessPointAdded(msg.path(), path); - } -} - -void QNmDBusHelper::slotAccessPointRemoved(QDBusObjectPath path) -{ - if(path.path().length() > 2) { - QDBusMessage msg = this->message(); - emit pathForAccessPointRemoved(msg.path(), path); - } -} - -void QNmDBusHelper::slotPropertiesChanged(QMap map) -{ - QDBusMessage msg = this->message(); - QMapIterator i(map); - while (i.hasNext()) { - i.next(); - if( i.key() == "State") { //state only applies to device interfaces - quint32 state = i.value().toUInt(); - if( state == NM_DEVICE_STATE_ACTIVATED - || state == NM_DEVICE_STATE_DISCONNECTED - || state == NM_DEVICE_STATE_UNAVAILABLE - || state == NM_DEVICE_STATE_FAILED) { - emit pathForPropertiesChanged( msg.path(), map); - } - } else if( i.key() == "ActiveAccessPoint") { - // qWarning() << __PRETTY_FUNCTION__ << i.key() << ": " << i.value().value().path(); - // } else if( i.key() == "Strength") - // qWarning() << __PRETTY_FUNCTION__ << i.key() << ": " << i.value().toUInt(); - // else - // qWarning() << __PRETTY_FUNCTION__ << i.key() << ": " << i.value(); - } - } -} - -void QNmDBusHelper::slotSettingsRemoved() -{ - QDBusMessage msg = this->message(); - emit pathForSettingsRemoved(msg.path()); -} - -#include "moc_qnmdbushelper_p.cpp" -QTM_END_NAMESPACE diff --git a/src/bearer/qnmdbushelper_p.h b/src/bearer/qnmdbushelper_p.h deleted file mode 100644 index d26ef2c..0000000 --- a/src/bearer/qnmdbushelper_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNMDBUSHELPERPRIVATE_H -#define QNMDBUSHELPERPRIVATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#if !defined(QT_NO_DBUS) && !defined(Q_OS_MAC) -#include -#include -#include -#endif - -QTM_BEGIN_NAMESPACE - -#if !defined(QT_NO_DBUS) && !defined(Q_OS_MAC) - -class QNmDBusHelper: public QObject, protected QDBusContext - { - Q_OBJECT - public: - QNmDBusHelper(QObject *parent = 0); - ~QNmDBusHelper(); - - public slots: - void deviceStateChanged(quint32); - void slotAccessPointAdded( QDBusObjectPath ); - void slotAccessPointRemoved( QDBusObjectPath ); - void slotPropertiesChanged( QMap); - void slotSettingsRemoved(); - -Q_SIGNALS: - void pathForStateChanged(const QString &, quint32); - void pathForAccessPointAdded(const QString &, QDBusObjectPath ); - void pathForAccessPointRemoved(const QString &, QDBusObjectPath ); - void pathForPropertiesChanged(const QString &, QMap); - void pathForSettingsRemoved(const QString &); -}; -#endif - -QTM_END_NAMESPACE - -#endif// QNMDBUSHELPERPRIVATE_H diff --git a/src/bearer/qnmwifiengine_unix.cpp b/src/bearer/qnmwifiengine_unix.cpp deleted file mode 100644 index 59b79e7..0000000 --- a/src/bearer/qnmwifiengine_unix.cpp +++ /dev/null @@ -1,838 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qnmwifiengine_unix_p.h" -#include "qnetworkconfiguration_p.h" -#include - -#include -#include - -#include -#include - -#include - -QTM_BEGIN_NAMESPACE -Q_GLOBAL_STATIC(QNmWifiEngine, nmWifiEngine) -typedef QList > QNmSettingsAddressMap; -QTM_END_NAMESPACE - -Q_DECLARE_METATYPE(QTM_PREPEND_NAMESPACE(QNmSettingsAddressMap)) - -QTM_BEGIN_NAMESPACE - -QNmWifiEngine::QNmWifiEngine(QObject *parent) -: QNetworkSessionEngine(parent) -{ - iface = new QNetworkManagerInterface(this); - if(!iface->isValid()) { - return; - } - iface->setConnections(); - connect(iface,SIGNAL(deviceAdded(QDBusObjectPath)), - this,SLOT(addDevice(QDBusObjectPath))); -// connect(iface,SIGNAL(deviceRemoved(QDBusObjectPath)), -// this,SLOT(removeDevice(QDBusObjectPath))); - connect(iface, SIGNAL(activationFinished(QDBusPendingCallWatcher*)), - this, SLOT(slotActivationFinished(QDBusPendingCallWatcher*))); - - foreach (const QDBusObjectPath &path, iface->getDevices()) - addDevice(path); - - QStringList connectionServices; - connectionServices << NM_DBUS_SERVICE_SYSTEM_SETTINGS; - connectionServices << NM_DBUS_SERVICE_USER_SETTINGS; - QNetworkManagerSettings *settingsiface; - foreach (const QString &service, connectionServices) { - settingsiface = new QNetworkManagerSettings(service, this); - settingsiface->setConnections(); - connect(settingsiface,SIGNAL(newConnection(QDBusObjectPath)), - this,(SLOT(newConnection(QDBusObjectPath)))); - } - - updated = false; -} - -QNmWifiEngine::~QNmWifiEngine() -{ -} - -QString QNmWifiEngine::getNameForConfiguration(QNetworkManagerInterfaceDevice *devIface) -{ - QString newname; - if (devIface->state() == NM_DEVICE_STATE_ACTIVATED) { - QString path = devIface->ip4config().path(); - QNetworkManagerIp4Config * ipIface; - ipIface = new QNetworkManagerIp4Config(path); - newname = ipIface->domains().join(" "); - delete ipIface; - } - //fallback to interface name - if(newname.isEmpty()) - newname = devIface->networkInterface().name(); - return newname; -} - - -QList QNmWifiEngine::getConfigurations(bool *ok) -{ - if (ok) - *ok = false; - - if(!updated) { - foundConfigurations.clear(); - if(knownSsids.isEmpty()) - updateKnownSsids(); - - scanForAccessPoints(); - updateActiveConnectionsPaths(); - knownConnections(); - - accessPointConnections(); - - updated = true; - } - return foundConfigurations; -} - -void QNmWifiEngine::knownConnections() -{ - QStringList connectionServices; - connectionServices << NM_DBUS_SERVICE_SYSTEM_SETTINGS; - connectionServices << NM_DBUS_SERVICE_USER_SETTINGS; - - QString connPath; - - QScopedPointer settingsiface; - foreach (const QString &service, connectionServices) { - QString ident; - settingsiface.reset(new QNetworkManagerSettings(service)); - - QNetworkManagerSettingsConnection *sysIface; - foreach (const QDBusObjectPath &path, settingsiface->listConnections()) { - ident = path.path(); - bool addIt = false; - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - sysIface = new QNetworkManagerSettingsConnection(service, path.path(), this); - sysIface->setConnections(); - connect(sysIface, SIGNAL(removed(QString)), - this,SLOT(settingsConnectionRemoved(QString))); - - cpPriv->name = sysIface->getId(); - cpPriv->isValid = true; - cpPriv->id = sysIface->getUuid(); - cpPriv->internet = true; - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - cpPriv->state = getStateForId(cpPriv->id); - - cpPriv->purpose = QNetworkConfiguration::PrivatePurpose; - - - if(sysIface->getType() == DEVICE_TYPE_802_3_ETHERNET) { - QString mac = sysIface->getMacAddress(); - if(!mac.length() > 2) { - QString devPath; - devPath = deviceConnectionPath(mac); - - QNetworkManagerInterfaceDevice devIface(devPath); - cpPriv->serviceInterface = devIface.networkInterface(); - QScopedPointer devWiredIface; - devWiredIface.reset(new QNetworkManagerInterfaceDeviceWired(devIface.connectionInterface()->path())); - cpPriv->internet = devWiredIface->carrier(); - - // use this mac addy - } else { - cpPriv->serviceInterface = getBestInterface( DEVICE_TYPE_802_3_ETHERNET, cpPriv->id); - } - - cpPriv->internet = true; - - addIt = true; - } else if(sysIface->getType() == DEVICE_TYPE_802_11_WIRELESS) { - QString mac = sysIface->getMacAddress();; - if(!mac.length() > 2) { - QString devPath; - devPath = deviceConnectionPath(mac); - - QNetworkManagerInterfaceDevice devIface(devPath); - cpPriv->serviceInterface = devIface.networkInterface(); - // use this mac addy - } else { - cpPriv->serviceInterface = getBestInterface( DEVICE_TYPE_802_11_WIRELESS, cpPriv->id); - } - addIt = true; - // get the wifi interface state first.. do we need this? - // QString activeAPPath = devWirelessIface->activeAccessPoint().path(); - } - if(addIt) { - foundConfigurations.append(cpPriv); - configurationInterface[cpPriv->id] = cpPriv->serviceInterface.name(); - cpPriv->bearer = bearerName(cpPriv->id); - } - } - } -} - -void QNmWifiEngine::accessPointConnections() -{ - QScopedPointer devIface; - foreach (const QDBusObjectPath &path, iface->getDevices()) { - devIface.reset(new QNetworkManagerInterfaceDevice(path.path())); - if(devIface->deviceType() == DEVICE_TYPE_802_11_WIRELESS) { - const QList apList = availableAccessPoints.uniqueKeys(); - - QList::const_iterator i; - for (i = apList.constBegin(); i != apList.constEnd(); ++i) { - QNetworkConfigurationPrivate* cpPriv; - cpPriv = addAccessPoint( devIface->connectionInterface()->path(), availableAccessPoints[*i]); - if(cpPriv->isValid) { - foundConfigurations.append(cpPriv); - configurationInterface[cpPriv->id] = cpPriv->serviceInterface.name(); - cpPriv->bearer = bearerName(cpPriv->id); - } - } - } - } -} - -QString QNmWifiEngine::getInterfaceFromId(const QString &id) -{ - return configurationInterface.value(id); -} - -bool QNmWifiEngine::hasIdentifier(const QString &id) -{ - if (configurationInterface.contains(id)) - return true; - - return false; -} - -QString QNmWifiEngine::bearerName(const QString &id) -{ - QString interface = getInterfaceFromId(id); - QScopedPointer devIface; - foreach (const QDBusObjectPath &path, iface->getDevices()) { - devIface.reset(new QNetworkManagerInterfaceDevice(path.path())); - - if(interface == devIface->networkInterface().name()) { - - switch(devIface->deviceType()) { - case DEVICE_TYPE_802_3_ETHERNET: - return QLatin1String("Ethernet"); - break; - case DEVICE_TYPE_802_11_WIRELESS: - return QLatin1String("WLAN"); - break; - case DEVICE_TYPE_GSM: - return QLatin1String("2G"); - break; - case DEVICE_TYPE_CDMA: - return QLatin1String("CDMA2000"); - break; - default: - break; - } - } - } - return QLatin1String("Unknown"); -} - -void QNmWifiEngine::connectToId(const QString &id) -{ - activatingConnectionPath = id; - QStringList connectionSettings = getConnectionPathForId(id); - if(connectionSettings.isEmpty()) { - emit connectionError(id, OperationNotSupported); - return; - } - - QDBusObjectPath connectionPath(connectionSettings.at(1)); - QString interface = getInterfaceFromId(id); - - interface = QNetworkInterface::interfaceFromName(interface).hardwareAddress().toLower(); - QString devPath; - devPath = deviceConnectionPath(interface); - QDBusObjectPath devicePath(devPath); - - iface->activateConnection( - connectionSettings.at(0), - connectionPath, - devicePath, - connectionPath); -} - -void QNmWifiEngine::disconnectFromId(const QString &id) -{ - QString activeConnectionPath = getActiveConnectionPath(id); - - if (!activeConnectionPath.isEmpty()) { - QScopedPointer activeCon; - activeCon.reset(new QNetworkManagerConnectionActive(activeConnectionPath)); - QScopedPointer settingsCon; - settingsCon.reset(new QNetworkManagerSettingsConnection(activeCon->serviceName(), activeCon->connection().path())); - - if(settingsCon->getType() == DEVICE_TYPE_802_3_ETHERNET) { //use depreciated value for now - emit connectionError(id, OperationNotSupported); - } else { - QDBusObjectPath dbpath(activeConnectionPath); - iface->deactivateConnection(dbpath); - activatingConnectionPath = ""; - } - } -} - -void QNmWifiEngine::requestUpdate() -{ - updated = false; - knownSsids.clear(); - availableAccessPoints.clear(); - emitConfigurationsChanged(); -} - -QNmWifiEngine *QNmWifiEngine::instance() -{ - if (QDBusConnection::systemBus().isConnected()) { - QDBusConnectionInterface *dbiface = QDBusConnection::systemBus().interface(); - QDBusReply reply = dbiface->isServiceRegistered("org.freedesktop.NetworkManager"); - if (reply.isValid() && reply.value()) - return nmWifiEngine(); - } - - return 0; -} - -void QNmWifiEngine::updateKnownSsids() -{ - QStringList connectionServices; - connectionServices << NM_DBUS_SERVICE_SYSTEM_SETTINGS; - connectionServices << NM_DBUS_SERVICE_USER_SETTINGS; - - QScopedPointer settingsiface; - foreach (const QString &service, connectionServices) { - settingsiface.reset(new QNetworkManagerSettings(service)); - foreach (const QDBusObjectPath &path, settingsiface->listConnections()) { - QNetworkManagerSettingsConnection sysIface(service, path.path()); - knownSsids << sysIface.getSsid(); - } - } -} - -void QNmWifiEngine::updateActiveConnectionsPaths() -{ //need to know which connection paths are currently active/connected - QScopedPointer dbIface; - activeConnectionPaths.clear(); - dbIface.reset(new QNetworkManagerInterface); - foreach (const QDBusObjectPath &conpath, dbIface->activeConnections()) - activeConnectionPaths << conpath.path(); -} - -QNetworkConfigurationPrivate * QNmWifiEngine::addAccessPoint( const QString &iPath, QDBusObjectPath path) -{ - - QScopedPointer devIface(new QNetworkManagerInterfaceDevice(iPath)); - QScopedPointer devWirelessIface(new QNetworkManagerInterfaceDeviceWireless(iPath)); - - QString activeAPPath = devWirelessIface->activeAccessPoint().path(); - - QScopedPointer accessPointIface(new QNetworkManagerInterfaceAccessPoint(path.path())); - - QString ident = accessPointIface->connectionInterface()->path(); - quint32 nmState = devIface->state(); - - QString ssid = accessPointIface->ssid(); - QString hwAddy = accessPointIface->hwAddress(); - QString sInterface = devIface->networkInterface().name(); - - QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate(); - bool addIt = true; - - if(addIt) { - - cpPriv->name = ssid; - cpPriv->isValid = true; - cpPriv->id = ident; - cpPriv->internet = true; - cpPriv->type = QNetworkConfiguration::InternetAccessPoint; - cpPriv->serviceInterface = devIface->networkInterface(); - - cpPriv->state = getAPState(nmState, knownSsids.contains(cpPriv->name)); - - if(activeAPPath == accessPointIface->connectionInterface()->path()) { - cpPriv->state = ( cpPriv->state | QNetworkConfiguration::Active); - } - if(accessPointIface->flags() == NM_802_11_AP_FLAGS_PRIVACY) - cpPriv->purpose = QNetworkConfiguration::PrivatePurpose; - else - cpPriv->purpose = QNetworkConfiguration::PublicPurpose; - return cpPriv; - } else { - cpPriv->isValid = false; - } - return cpPriv; -} - - - QNetworkConfiguration::StateFlags QNmWifiEngine::getAPState(qint32 nmState, bool isKnown) -{ - QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined; - // this is the state of the wifi device interface - if(isKnown) - state = ( QNetworkConfiguration::Defined); - - switch(nmState) { //device interface state, not AP state - case NM_DEVICE_STATE_UNKNOWN: - case NM_DEVICE_STATE_UNMANAGED: - case NM_DEVICE_STATE_UNAVAILABLE: - state = (QNetworkConfiguration::Undefined); - break; - case NM_DEVICE_STATE_DISCONNECTED: - { - if(isKnown) - state = ( state | QNetworkConfiguration::Discovered); - } - break; - case NM_DEVICE_STATE_PREPARE: - case NM_DEVICE_STATE_CONFIG: - case NM_DEVICE_STATE_NEED_AUTH: - case NM_DEVICE_STATE_IP_CONFIG: - if(isKnown) - state = ( state | QNetworkConfiguration::Discovered); - break; - case NM_DEVICE_STATE_ACTIVATED: - { - if(isKnown) - state = ( state | QNetworkConfiguration::Discovered); - } - break; - }; - return state; -} - -QString QNmWifiEngine::getActiveConnectionPath(const QString &id) -{ - QStringList connectionSettings = getConnectionPathForId(id); - QNetworkManagerInterface ifaceD; - QScopedPointer conDetailsD; - foreach (const QDBusObjectPath &path, ifaceD.activeConnections()) { - conDetailsD.reset(new QNetworkManagerConnectionActive( path.path())); - if(conDetailsD->connection().path() == connectionSettings.at(1) - && conDetailsD->serviceName() == connectionSettings.at(0)) - return path.path(); - } - return QString(); -} - - QNetworkConfiguration::StateFlags QNmWifiEngine::getStateFlag(quint32 nmstate) - { - QNetworkConfiguration::StateFlags flag; - switch (nmstate) { - case NM_DEVICE_STATE_UNKNOWN: - case NM_DEVICE_STATE_FAILED: - case NM_DEVICE_STATE_UNMANAGED: - flag = (QNetworkConfiguration::Undefined); - break; - case NM_DEVICE_STATE_PREPARE: - case NM_DEVICE_STATE_CONFIG: - case NM_DEVICE_STATE_NEED_AUTH: - case NM_DEVICE_STATE_IP_CONFIG: - case NM_DEVICE_STATE_UNAVAILABLE: - flag = (QNetworkConfiguration::Defined); - break; - case NM_DEVICE_STATE_DISCONNECTED: - flag = ( flag | QNetworkConfiguration::Discovered ); - break; - case NM_DEVICE_STATE_ACTIVATED: - { - flag = ( flag | QNetworkConfiguration::Discovered - | QNetworkConfiguration::Active ); - } - break; - default: - flag = ( QNetworkConfiguration::Defined); - break; - }; - return flag; - } - -void QNmWifiEngine::updateDeviceInterfaceState(const QString &/*path*/, quint32 nmState) -{ - if(nmState == NM_DEVICE_STATE_ACTIVATED - || nmState == NM_DEVICE_STATE_DISCONNECTED - || nmState == NM_DEVICE_STATE_UNAVAILABLE - || nmState == NM_DEVICE_STATE_FAILED) { - - QNetworkConfiguration::StateFlags state = (QNetworkConfiguration::Defined); - switch (nmState) { - case NM_DEVICE_STATE_UNKNOWN: - case NM_DEVICE_STATE_FAILED: - state = (QNetworkConfiguration::Undefined); - emit connectionError(activatingConnectionPath, ConnectError); - requestUpdate(); - break; - case NM_DEVICE_STATE_UNAVAILABLE: - state = (QNetworkConfiguration::Defined); - requestUpdate(); - break; - case NM_DEVICE_STATE_DISCONNECTED: - state = ( state | QNetworkConfiguration::Discovered ); - requestUpdate(); - break; - case NM_DEVICE_STATE_ACTIVATED: - { - state = ( state | QNetworkConfiguration::Discovered - | QNetworkConfiguration::Active ); - requestUpdate(); - } - break; - default: - state = ( QNetworkConfiguration::Defined); - break; - }; - } -} - -void QNmWifiEngine::addDevice(QDBusObjectPath path) -{ - QNetworkManagerInterfaceDevice *devIface = new QNetworkManagerInterfaceDevice(path.path(), this); - devIface->setConnections(); - connect(devIface,SIGNAL(stateChanged(const QString &, quint32)), - this, SLOT(updateDeviceInterfaceState(const QString&, quint32))); - - if(!devicePaths.contains(path.path())) - devicePaths << path.path(); - - switch(devIface->deviceType()) { - case DEVICE_TYPE_802_3_ETHERNET: - { - QNetworkManagerInterfaceDeviceWired * devWiredIface; - devWiredIface = new QNetworkManagerInterfaceDeviceWired(devIface->connectionInterface()->path(), this); - devWiredIface->setConnections(); - connect(devWiredIface, SIGNAL(propertiesChanged(const QString &,QMap)), - this,SLOT(cmpPropertiesChanged( const QString &, QMap))); - requestUpdate(); - } - break; - case DEVICE_TYPE_802_11_WIRELESS: - { - QNetworkManagerInterfaceDeviceWireless *devWirelessIface; - devWirelessIface = new QNetworkManagerInterfaceDeviceWireless(devIface->connectionInterface()->path(), this); - devWirelessIface->setConnections(); - - connect(devWirelessIface, SIGNAL(propertiesChanged(const QString &,QMap)), - this,SLOT(cmpPropertiesChanged( const QString &, QMap))); - - connect(devWirelessIface, SIGNAL(accessPointAdded(const QString &,QDBusObjectPath)), - this,SLOT(accessPointAdded(const QString &,QDBusObjectPath))); - - connect(devWirelessIface, SIGNAL(accessPointRemoved(const QString &,QDBusObjectPath)), - this,SLOT(accessPointRemoved(const QString &,QDBusObjectPath))); - requestUpdate(); - - } - break; - default: - break; - }; -} - -void QNmWifiEngine::cmpPropertiesChanged(const QString &path, QMap map) -{ - QMapIterator i(map); - while (i.hasNext()) { - i.next(); - if( i.key() == "State") { //only applies to device interfaces - updateDeviceInterfaceState(path, i.value().toUInt()); - } - if( i.key() == "ActiveAccessPoint") { - } - if( i.key() == "Carrier") { //someone got plugged in - } - } -} - -void QNmWifiEngine::accessPointRemoved( const QString &aPath, QDBusObjectPath /*oPath*/) -{ - if(aPath.contains("devices")) { - requestUpdate(); - } -} - -void QNmWifiEngine::accessPointAdded( const QString &/*aPath*/, QDBusObjectPath /*oPath*/) -{ - requestUpdate(); -} - -QNetworkConfiguration::StateFlags QNmWifiEngine::getStateForId(const QString &id) -{ - bool isAvailable = false; - QStringList conPath = getConnectionPathForId(id); - QString aconpath = getActiveConnectionPath(id); - - if(!aconpath.isEmpty()) { - //active connection - QNetworkManagerConnectionActive aConn(aconpath); - - QScopedPointer ifaceDevice; - QScopedPointer devWiredIface; - foreach (const QDBusObjectPath &dev, aConn.devices()) { - ifaceDevice.reset(new QNetworkManagerInterfaceDevice(dev.path())); - - if(ifaceDevice->deviceType() == DEVICE_TYPE_802_3_ETHERNET) { - - if(isAddressOfConnection(id, ifaceDevice->ip4Address())) { - // this is it! - return getStateFlag(ifaceDevice->state()); - } else { - continue; - } - - if(ifaceDevice->state() == NM_DEVICE_STATE_UNAVAILABLE || - ifaceDevice->state() == NM_DEVICE_STATE_DISCONNECTED) { - isAvailable = true; - - devWiredIface.reset(new QNetworkManagerInterfaceDeviceWired(ifaceDevice->connectionInterface()->path())); - if(!devWiredIface->carrier()) - return QNetworkConfiguration::Defined; - } - } else if(ifaceDevice->deviceType() == DEVICE_TYPE_802_11_WIRELESS) { - - } - - return getStateFlag(ifaceDevice->state()); - } - } else { - // not active - QScopedPointer sysIface; - sysIface.reset(new QNetworkManagerSettingsConnection(conPath.at(0),conPath.at(1))); - if(sysIface->isValid()) { - if(sysIface->getType() == DEVICE_TYPE_802_11_WIRELESS) { - QString ssid = sysIface->getSsid(); - bool ok = false; - - if(knownSsids.contains(ssid, Qt::CaseSensitive)) { - foreach (const QString &onessid, knownSsids) { - if(onessid == ssid && availableAccessPoints.contains(ssid)) { - ok = true; - break; - } - } - } - if(ok) - return getStateFlag(NM_DEVICE_STATE_DISCONNECTED); - else - return getStateFlag(NM_DEVICE_STATE_UNAVAILABLE); - } - } - } - - return QNetworkConfiguration::Defined; //not active, but we know this connection -} - -bool QNmWifiEngine::isAddressOfConnection(const QString &id, quint32 ipaddress) -{ - QStringList conPath = getConnectionPathForId(id); - QString aConPath = getActiveConnectionPath(id); - if(aConPath.isEmpty()) { - // not active - return false; - } - - QScopedPointer aConn; - aConn.reset(new QNetworkManagerConnectionActive(aConPath)); - QScopedPointer ifaceDevice; - foreach (const QDBusObjectPath &device, aConn->devices()) { - ifaceDevice.reset(new QNetworkManagerInterfaceDevice(device.path())); - if(ifaceDevice->ip4Address() == ipaddress) { - return true; - } - } - return false; -} - -QNetworkInterface QNmWifiEngine::getBestInterface( quint32 type, const QString &id) -{ - // check active connections first. - QStringList conIdPath = getConnectionPathForId(id); - - QNetworkInterface interface; - QScopedPointer aConn; - - foreach (const QString &conpath, activeConnectionPaths) { - aConn.reset(new QNetworkManagerConnectionActive(conpath)); - if(aConn->connection().path() == conIdPath.at(1) - && aConn->serviceName() == conIdPath.at(0)) { - - QList devs = aConn->devices(); - QNetworkManagerInterfaceDevice ifaceDevice(devs[0].path()); //just take the first one - return ifaceDevice.networkInterface(); - } - } - - //try guessing - QScopedPointer devIface; - foreach (const QDBusObjectPath &path, iface->getDevices()) { - devIface.reset(new QNetworkManagerInterfaceDevice(path.path())); - if(devIface->deviceType() == type ) { - if(devIface->state() == NM_DEVICE_STATE_DISCONNECTED) { - return devIface->networkInterface(); - } - } - } - return QNetworkInterface(); -} - -quint64 QNmWifiEngine::receivedDataForId(const QString &id) const -{ - if(configurationInterface.count() > 1) - return 0; - quint64 result = 0; - - QString devFile; - devFile = configurationInterface.value(id); - QFile rx("/sys/class/net/"+devFile+"/statistics/rx_bytes"); - if(rx.exists() && rx.open(QIODevice::ReadOnly | QIODevice::Text)) { - QTextStream in(&rx); - in >> result; - rx.close(); - } - return result; -} - -quint64 QNmWifiEngine::sentDataForId(const QString &id) const -{ - if(configurationInterface.count() > 1) - return 0; - quint64 result = 0; - QString devFile; - devFile = configurationInterface.value(id); - - QFile tx("/sys/class/net/"+devFile+"/statistics/tx_bytes"); - if(tx.exists() && tx.open(QIODevice::ReadOnly | QIODevice::Text)) { - QTextStream in(&tx); - in >> result; - tx.close(); - } - return result; -} - -void QNmWifiEngine::newConnection(QDBusObjectPath /*path*/) -{ - requestUpdate(); -} - -void QNmWifiEngine::settingsConnectionRemoved(const QString &/*path*/) -{ - requestUpdate(); -} - -void QNmWifiEngine::slotActivationFinished(QDBusPendingCallWatcher *openCall) -{ - QDBusPendingReply reply = *openCall; - if (reply.isError()) { - qWarning() <<"Error" << reply.error().name() << reply.error().message() - < devIface; - QScopedPointer devWirelessIface; - QScopedPointer accessPointIface; - foreach (const QDBusObjectPath &path, iface->getDevices()) { - devIface.reset(new QNetworkManagerInterfaceDevice(path.path())); - - if(devIface->deviceType() == DEVICE_TYPE_802_11_WIRELESS) { - - devWirelessIface.reset(new QNetworkManagerInterfaceDeviceWireless(devIface->connectionInterface()->path())); - ////////////// AccessPoints - - foreach (const QDBusObjectPath &path, devWirelessIface->getAccessPoints()) { - accessPointIface.reset(new QNetworkManagerInterfaceAccessPoint(path.path())); - const QString ssid = accessPointIface->ssid(); - availableAccessPoints.insert(ssid, path); - } - } - } -} - -QString QNmWifiEngine::deviceConnectionPath(const QString &mac) -{ - QString newMac = mac.toLower(); - newMac.replace(QLatin1Char(':'), QLatin1Char('_')); - //device object path might not contain just mac address - //might contain extra numbers on the end. thanks HAL - foreach (const QString &device, devicePaths) { - if(device.contains(newMac)) { - newMac = device; - break; - } - } - return newMac; -} - -QStringList QNmWifiEngine::getConnectionPathForId(const QString &uuid) -{ - QStringList connectionServices; - connectionServices << NM_DBUS_SERVICE_SYSTEM_SETTINGS; - connectionServices << NM_DBUS_SERVICE_USER_SETTINGS; - QScopedPointer settingsiface; - foreach (const QString &service, connectionServices) { - settingsiface.reset(new QNetworkManagerSettings(service)); - QScopedPointer sysIface; - foreach (const QDBusObjectPath &path, settingsiface->listConnections()) { - sysIface.reset(new QNetworkManagerSettingsConnection(service, path.path())); - if(sysIface->getUuid() == uuid) - return QStringList() << service << sysIface->connectionInterface()->path(); - } - } - return QStringList(); -} - -#include "moc_qnmwifiengine_unix_p.cpp" - -QTM_END_NAMESPACE - diff --git a/src/bearer/qnmwifiengine_unix_p.h b/src/bearer/qnmwifiengine_unix_p.h deleted file mode 100644 index 43fdac3..0000000 --- a/src/bearer/qnmwifiengine_unix_p.h +++ /dev/null @@ -1,159 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the Qt Mobility Components. -** -** $QT_BEGIN_LICENSE:LGPL$ -** GNU Lesser General Public License Usage -** This file may be used under the terms of the GNU Lesser General Public -** License version 2.1 as published by the Free Software Foundation and -** appearing in the file LICENSE.LGPL included in the packaging of this -** file. Please review the following information to ensure the GNU Lesser -** General Public License version 2.1 requirements will be met: -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU General -** Public License version 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of this -** file. Please review the following information to ensure the GNU General -** Public License version 3.0 requirements will be met: -** http://www.gnu.org/copyleft/gpl.html. -** -** Other Usage -** Alternatively, this file may be used in accordance with the terms and -** conditions contained in a signed written agreement between you and Nokia. -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QNMWIFIENGINE_P_H -#define QNMWIFIENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -//#include - -#include -#include -#include -#include - -#include "qnetworksessionengine_p.h" -#include -#include -#include - - -QTM_BEGIN_NAMESPACE - -class QNetworkConfigurationPrivate; - -class QNmWifiEngine : public QNetworkSessionEngine -{ - Q_OBJECT - -public: - QNmWifiEngine(QObject *parent = 0); - ~QNmWifiEngine(); - - QList getConfigurations(bool *ok = 0); - QString getInterfaceFromId(const QString &id); - bool hasIdentifier(const QString &id); - - QString bearerName(const QString &id); - - void connectToId(const QString &id); - void disconnectFromId(const QString &id); - - void requestUpdate(); - - static QNmWifiEngine *instance(); - - QStringList knownSsids; - inline void emitConfigurationsChanged() { emit configurationsChanged(); } - QNetworkConfigurationPrivate * addAccessPoint(const QString &, QDBusObjectPath ); - - QStringList getConnectionPathForId(const QString &uuid); - //QString getConnectionPathForId(const QString &name = QString()); - quint64 sentDataForId(const QString &id) const; - quint64 receivedDataForId(const QString &id) const; - -private: - bool updated; - QString activatingConnectionPath; - QStringList activeConnectionPaths; - - - QMap availableAccessPoints; - void scanForAccessPoints(); - - QStringList devicePaths; - - void updateActiveConnectionsPaths(); - void updateKnownSsids(); - void accessPointConnections(); - void knownConnections(); - QString deviceConnectionPath(const QString &mac); - - QList foundConfigurations; - // QHash > allConfigurations; - - QNetworkManagerInterface *iface; - - QNetworkConfiguration::StateFlags getAPState(qint32 vState, bool isKnown); - QNetworkConfiguration::StateFlags getStateFlag(quint32 nmstate); - - QString getActiveConnectionPath(const QString &identifier); - QString getNameForConfiguration(QNetworkManagerInterfaceDevice *devIface); - - QNetworkConfiguration::StateFlags getStateForId(const QString &id); - - QNetworkInterface getBestInterface(quint32 type, const QString &conPath); - - QMap configurationInterface; - - bool isAddressOfConnection(const QString &conPath, quint32 ipaddress); - -private slots: - void updateDeviceInterfaceState(const QString &, quint32); - void addDevice(QDBusObjectPath path); - -Q_SIGNALS: - void configurationChanged(const QNetworkConfiguration& config); - -private slots: - void accessPointAdded( const QString &aPath, QDBusObjectPath oPath); - void accessPointRemoved( const QString &aPath, QDBusObjectPath oPath); - void cmpPropertiesChanged(const QString &, QMap map); - void newConnection(QDBusObjectPath); - void settingsConnectionRemoved(const QString &); - void slotActivationFinished(QDBusPendingCallWatcher*); -}; - -QTM_END_NAMESPACE - -#endif - - diff --git a/tests/auto/qnetworkconfigmanager/qnetworkconfigmanager.pro b/tests/auto/qnetworkconfigmanager/qnetworkconfigmanager.pro index 87dc1f3..1d023f2 100644 --- a/tests/auto/qnetworkconfigmanager/qnetworkconfigmanager.pro +++ b/tests/auto/qnetworkconfigmanager/qnetworkconfigmanager.pro @@ -5,8 +5,6 @@ CONFIG += testcase QT = core network -INCLUDEPATH += ../../../src/bearer - include(../../../common.pri) CONFIG += mobility MOBILITY = bearer diff --git a/tests/auto/qnetworkconfigmanager/tst_qnetworkconfigmanager.cpp b/tests/auto/qnetworkconfigmanager/tst_qnetworkconfigmanager.cpp index 899f728..52304c4 100644 --- a/tests/auto/qnetworkconfigmanager/tst_qnetworkconfigmanager.cpp +++ b/tests/auto/qnetworkconfigmanager/tst_qnetworkconfigmanager.cpp @@ -43,8 +43,8 @@ #include #include "../qbearertestcommon.h" -#include "../../../src/bearer/qnetworkconfiguration.h" -#include "../../../src/bearer/qnetworkconfigmanager.h" +#include +#include #if defined(Q_WS_MAEMO_6) || defined(Q_WS_MAEMO_5) #include diff --git a/tests/auto/qnetworkconfiguration/qnetworkconfiguration.pro b/tests/auto/qnetworkconfiguration/qnetworkconfiguration.pro index ca11aaf..e228a41 100644 --- a/tests/auto/qnetworkconfiguration/qnetworkconfiguration.pro +++ b/tests/auto/qnetworkconfiguration/qnetworkconfiguration.pro @@ -5,8 +5,6 @@ CONFIG += testcase QT = core network -INCLUDEPATH += ../../../src/bearer - include(../../../common.pri) CONFIG += mobility MOBILITY = bearer diff --git a/tests/auto/qnetworkconfiguration/tst_qnetworkconfiguration.cpp b/tests/auto/qnetworkconfiguration/tst_qnetworkconfiguration.cpp index e3c17ff..5c23ea8 100644 --- a/tests/auto/qnetworkconfiguration/tst_qnetworkconfiguration.cpp +++ b/tests/auto/qnetworkconfiguration/tst_qnetworkconfiguration.cpp @@ -43,8 +43,8 @@ #include #include "../qbearertestcommon.h" -#include "../../../src/bearer/qnetworkconfiguration.h" -#include "../../../src/bearer/qnetworkconfigmanager.h" +#include +#include /* Although this unit test doesn't use QNetworkAccessManager diff --git a/tests/auto/qnetworksession/lackey/main.cpp b/tests/auto/qnetworksession/lackey/main.cpp index 0fa666f..ac57c46 100644 --- a/tests/auto/qnetworksession/lackey/main.cpp +++ b/tests/auto/qnetworksession/lackey/main.cpp @@ -42,9 +42,9 @@ #include #include #include -#include "../../../../src/bearer/qnetworkconfigmanager.h" -#include "../../../../src/bearer/qnetworkconfiguration.h" -#include "../../../../src/bearer/qnetworksession.h" +#include +#include +#include #include #include diff --git a/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.cpp b/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.cpp index 5729d87..5ea9812 100644 --- a/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.cpp +++ b/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.cpp @@ -46,8 +46,8 @@ #include #include #include "../../qbearertestcommon.h" -#include "../../../../src/bearer/qnetworkconfigmanager.h" -#include "../../../../src/bearer/qnetworksession.h" +#include +#include #if defined(Q_WS_MAEMO_6) || defined(Q_WS_MAEMO_5) #include diff --git a/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.pro b/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.pro index 06067e4..1ca0d80 100644 --- a/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.pro +++ b/tests/auto/qnetworksession/tst_qnetworksession/tst_qnetworksession.pro @@ -5,8 +5,6 @@ CONFIG += testcase QT = core network -INCLUDEPATH += ../../../../src/bearer - include(../../../../common.pri) CONFIG += mobility MOBILITY = bearer -- 1.6.5.1.1367.gcd48