42 #include <SystemConfiguration/SCNetworkConfiguration.h> 44 @interface QT_MANGLE_NAMESPACE(QNSListener) : NSObject
51 - (void)notificationHandler:(NSNotification *)notification;
61 @implementation QT_MANGLE_NAMESPACE(QNSListener)
66 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
67 notificationCenter = [NSNotificationCenter defaultCenter];
68 currentInterface = [CWInterface interfaceWithName:nil];
69 [
notificationCenter addObserver:self selector:@selector(notificationHandler:) name:kCWPowerDidChangeNotification object:nil];
71 [autoreleasepool release];
100 - (void)notificationHandler:(NSNotification *)notification
103 engine->requestUpdate();
113 for (
long i = 0; i < CFArrayGetCount(changedKeys); i++) {
116 if( changed.
contains(
"/Network/Global/IPv4")) {
141 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
144 CWInterface *currentInterface = [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceName)];
147 if([currentInterface power]) {
149 NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
150 [NSNumber numberWithBool:YES], kCWScanKeyMerge,
151 [NSNumber numberWithInt:kCWScanTypeFast], kCWScanKeyScanType,
152 [NSNumber numberWithInteger:100], kCWScanKeyRestTime, nil];
154 NSArray* apArray = [currentInterface scanForNetworksWithParameters:parametersDict error:&err];
155 CWNetwork *apNetwork;
159 for(
uint row=0; row < [apArray count]; row++ ) {
160 apNetwork = [apArray objectAtIndex:row];
168 if( [currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) {
181 if([[apNetwork securityMode] intValue] == kCWSecurityModeOpen) {
193 QMapIterator<QString, QMap<QString,QString> > i(
userProfiles);
194 while (i.hasNext()) {
205 QMapIterator<QString, QString> ij(i.value());
206 while (ij.hasNext()) {
208 interfaceName = ij.value();
211 if( [currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) {
231 [autoreleasepool release];
264 return foundConfigurations;
271 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
274 NSArray *wifiInterfaces = [CWInterface supportedInterfaces];
275 for(
uint row=0; row < [wifiInterfaces count]; row++ ) {
277 CWInterface *wifiInterface = [CWInterface interfaceWithName: [wifiInterfaces objectAtIndex:row]];
278 if ( ![wifiInterface power] )
281 NSString *nsInterfaceName = [wifiInterface name];
283 SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (
CFStringRef)
@"Qt corewlan", nil, nil);
284 NSDictionary * airportPlist = (NSDictionary *)SCDynamicStoreCopyValue(dynRef, (
CFStringRef)[NSString stringWithFormat:@"Setup:/Network/Interface/%@/AirPort", nsInterfaceName]);
286 if(airportPlist != nil) {
287 NSDictionary *prefNetDict = [airportPlist objectForKey:@"PreferredNetworks"];
289 NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"];
290 for(NSString *ssidkey in thisSsidarray) {
298 CFRelease(airportPlist);
303 NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile: (NSString *)QCFString::toCFStringRef(userProfilePath)] autorelease];
305 NSString *profileStr=
@"Profiles";
306 NSString *nameStr =
@"UserDefinedName";
307 NSString *networkSsidStr =
@"Wireless Network";
308 for (
id profileKey in eapDict) {
309 if ([profileStr isEqualToString:profileKey]) {
310 NSDictionary *itemDict = [eapDict objectForKey:profileKey];
311 for (
id itemKey in itemDict) {
313 NSInteger dictSize = [itemKey count];
314 id objects[dictSize];
317 [itemKey getObjects:objects andKeys:keys];
320 for(
int i = 0; i < dictSize; i++) {
321 if([nameStr isEqualToString:keys[i]]) {
324 if([networkSsidStr isEqualToString:keys[i]]) {
339 [autoreleasepool release];
346 QMapIterator<QString, QMap<QString,QString> > i(
userProfiles);
347 while (i.hasNext()) {
350 QMapIterator<QString, QString> ij(i.value());
351 while (ij.hasNext()) {
354 if(name == i.key() || name == networkNameHash) {
366 QMapIterator<QString, QMap<QString,QString> > i(
userProfiles);
367 while (i.hasNext()) {
370 QMapIterator<QString, QString> ij(i.value());
371 while (ij.hasNext()) {
373 if(ij.key() == ssid) {
385 QMapIterator<QString, QMap<QString,QString> > i(
userProfiles);
386 while (i.hasNext()) {
416 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
418 if([[CWInterface supportedInterfaces] count] > 0 && !
listener) {
419 listener = [[QT_MANGLE_NAMESPACE(QNSListener) alloc] init];
428 [autoreleasepool release];
449 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
452 CWInterface *wifiInterface =
453 [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceString)];
455 if ([wifiInterface power]) {
457 NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
466 bool using8021X =
false;
468 NSArray *array = [CW8021XProfile allUser8021XProfiles];
470 for (NSUInteger i = 0; i < [array count]; ++i) {
475 if (
id == networkNameHashCheck ||
id == ssidHash) {
480 wantedSsid = thisName;
482 [params setValue: [array objectAtIndex:i] forKey:kCWAssocKey8021XProfile];
492 while (i.hasNext()) {
494 wantedNetwork = i.key();
496 if (
id == networkNameHash) {
502 NSDictionary *scanParameters = [NSDictionary dictionaryWithObjectsAndKeys:
503 [NSNumber numberWithBool:YES], kCWScanKeyMerge,
504 [NSNumber numberWithInt:kCWScanTypeFast], kCWScanKeyScanType,
505 [NSNumber numberWithInteger:100], kCWScanKeyRestTime,
506 (NSString *)QCFString::toCFStringRef(wantedSsid), kCWScanKeySSID,
509 NSArray *scanArray = [wifiInterface scanForNetworksWithParameters:scanParameters error:&err];
512 for(
uint row=0; row < [scanArray count]; row++ ) {
513 CWNetwork *apNetwork = [scanArray objectAtIndex:row];
518 SecKeychainAttribute attributes[3];
520 NSString *account = [apNetwork ssid];
521 NSString *keyKind =
@"AirPort network password";
524 attributes[0].tag = kSecAccountItemAttr;
525 attributes[0].
data = (
void *)[account UTF8String];
526 attributes[0].length = [account length];
528 attributes[1].tag = kSecDescriptionItemAttr;
529 attributes[1].data = (
void *)[keyKind UTF8String];
530 attributes[1].length = [keyKind length];
532 attributes[2].tag = kSecLabelItemAttr;
533 attributes[2].data = (
void *)[keyName UTF8String];
534 attributes[2].length = [keyName length];
536 SecKeychainAttributeList attributeList = {3,attributes};
538 SecKeychainSearchRef searchRef;
539 SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &attributeList, &searchRef);
541 NSString *password =
@"";
542 SecKeychainItemRef searchItem;
544 if (SecKeychainSearchCopyNext(searchRef, &searchItem) == noErr) {
545 UInt32 realPasswordLength;
546 SecKeychainAttribute attributesW[8];
547 attributesW[0].tag = kSecAccountItemAttr;
548 SecKeychainAttributeList listW = {1,attributesW};
550 OSStatus status = SecKeychainItemCopyContent(searchItem, NULL, &listW, &realPasswordLength,(
void **)&realPassword);
552 if (status == noErr) {
553 if (realPassword != NULL) {
556 pBuf.
resize(realPasswordLength);
558 pBuf.
insert(realPasswordLength,
'\0');
560 password = [NSString stringWithUTF8String:pBuf];
562 SecKeychainItemFreeContent(&listW, realPassword);
565 CFRelease(searchItem);
567 qDebug() <<
"SecKeychainSearchCopyNext error";
569 [params setValue: password forKey: kCWAssocKeyPassphrase];
573 bool result = [wifiInterface associateToNetwork: apNetwork parameters:[NSDictionary dictionaryWithDictionary:params] error:&err];
594 [autoreleasepool release];
602 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
604 CWInterface *wifiInterface =
605 [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceString)];
607 [wifiInterface disassociate];
608 if ([[wifiInterface interfaceState]intValue] != kCWInterfaceStateInactive) {
613 [autoreleasepool release];
626 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
628 NSArray *wifiInterfaces = [CWInterface supportedInterfaces];
629 for (
uint row = 0; row < [wifiInterfaces count]; ++row) {
634 if ([wifiInterfaces count] == 0)
636 [autoreleasepool release];
642 bool haswifi =
false;
644 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
645 CWInterface *defaultInterface = [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(wifiDeviceName)];
646 if([defaultInterface power]) {
649 [autoreleasepool release];
688 SCDynamicStoreContext dynStoreContext = { 0,
this, NULL, NULL, NULL };
690 CFSTR(
"networkChangeCallback"),
694 qWarning() <<
"could not open dynamic store: error:" << SCErrorString(SCError());
698 CFMutableArrayRef notificationKeys;
699 notificationKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
700 CFMutableArrayRef patternsArray;
701 patternsArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
704 storeKey = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
705 kSCDynamicStoreDomainState,
707 CFArrayAppendValue(notificationKeys, storeKey);
710 storeKey = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
711 kSCDynamicStoreDomainState,
714 CFArrayAppendValue(patternsArray, storeKey);
717 if (!SCDynamicStoreSetNotificationKeys(
storeSession , notificationKeys, patternsArray)) {
718 qWarning() <<
"register notification error:"<< SCErrorString(SCError());
720 CFRelease(notificationKeys);
721 CFRelease(patternsArray);
724 CFRelease(notificationKeys);
725 CFRelease(patternsArray);
729 qWarning() <<
"runloop source error:"<< SCErrorString(SCError());
734 CFRunLoopAddSource(CFRunLoopGetCurrent(),
runloopSource, kCFRunLoopDefaultMode);
760 while (!foundConfigurations.
isEmpty()) {
768 bool changed =
false;
830 return getBytes(interfaceStr,
false);
843 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
846 NSString *filePath =
@"/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist";
847 NSDictionary* plistDict = [[[NSDictionary alloc] initWithContentsOfFile:filePath] autorelease];
850 NSString *input =
@"KnownNetworks";
851 NSString *timeStampStr =
@"_timeStamp";
853 NSString *ssidStr =
@"SSID_STR";
855 for (
id key in plistDict) {
856 if ([input isEqualToString:
key]) {
858 NSDictionary *knownNetworksDict = [plistDict objectForKey:key];
859 if(knownNetworksDict == nil)
861 for (
id networkKey in knownNetworksDict) {
862 bool isFound =
false;
863 NSDictionary *itemDict = [knownNetworksDict objectForKey:networkKey];
866 NSInteger dictSize = [itemDict count];
867 id objects[dictSize];
870 [itemDict getObjects:objects andKeys:keys];
872 for(
int i = 0; i < dictSize; i++) {
873 if([ssidStr isEqualToString:keys[i]]) {
875 if(ident == identifier) {
879 if(ok && [timeStampStr isEqualToString:keys[i]]) {
880 timestamp = (
quint64)[objects[i] timeIntervalSince1970];
890 [autoreleasepool release];
896 struct ifaddrs *ifAddressList, *ifAddress;
897 struct if_data *if_data;
901 if(getifaddrs(&ifAddressList) == 0) {
902 for(ifAddress = ifAddressList; ifAddress; ifAddress = ifAddress->ifa_next) {
903 if(interfaceName == ifAddress->ifa_name) {
904 if_data = (
struct if_data*)ifAddress->ifa_data;
906 bytes = if_data->ifi_ibytes;
909 bytes = if_data->ifi_obytes;
914 freeifaddrs(ifAddressList);
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
QBool contains(QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
bool requiresPolling() const
uint qHash(const QProcEnvKey &key)
const struct __CFString * CFStringRef
static QString keyName(const QString &rKey)
Purpose
Specifies the purpose of the configuration.
static mach_timebase_info_data_t info
#define QT_END_NAMESPACE
This macro expands to.
void lock()
Locks the mutex.
void disconnectFromId(const QString &id)
QList< QNetworkConfigurationPrivate * > getConfigurations()
bool hasIdentifier(const QString &id)
QNetworkConfiguration::StateFlags state
QScanThread(QObject *parent=0)
void configurationChanged(QNetworkConfigurationPrivatePointer config)
CWInterface * currentInterface
The QByteArray class provides an array of bytes.
Q_INVOKABLE void initialize()
quint64 bytesWritten(const QString &id)
void unlock()
Unlocks this mutex locker.
static QString toQString(CFStringRef cfstr)
State
This enum describes the connectivity state of the session.
static LibLoadStatus status
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
QString getSsidFromNetworkName(const QString &name)
quint64 bytesReceived(const QString &id)
NSNotificationCenter * notificationCenter
QByteArray & prepend(char c)
Prepends the character ch to this byte array.
The QString class provides a Unicode character string.
quint64 startTime(const QString &id)
The QObject class is the base class of all Qt objects.
QChar * data()
Returns a pointer to the data stored in the QString.
QNetworkConfiguration::BearerType bearerType
QCoreWlanEngine(QObject *parent=0)
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
void getUserConfigurations()
void relock()
Relocks an unlocked mutex locker.
Q_CORE_EXPORT void qDebug(const char *,...)
void append(const T &t)
Inserts value at the end of the list.
QList< QNetworkConfigurationPrivate * > fetchedConfigurations
QFuture< void > map(Sequence &sequence, MapFunction function)
#define QT_BEGIN_NAMESPACE
This macro expands to.
QBool contains(const T &t) const
Returns true if the list contains an occurrence of value; otherwise returns false.
QHash< QString, QNetworkConfigurationPrivatePointer > accessPointConfigurations
QNetworkConfigurationPrivatePointer defaultConfiguration()
T takeFirst()
Removes the first item in the list and returns it.
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
QMap< QString, QMap< QString, QString > > userProfiles
const T value(const Key &key) const
Returns the value associated with the key key.
The QStringList class provides a list of strings.
void startNetworkChangeLoop()
void configurationAdded(QNetworkConfigurationPrivatePointer config)
Q_CORE_EXPORT void qWarning(const char *,...)
QNetworkSessionPrivate * createSessionBackend()
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
CFRunLoopSourceRef runloopSource
void connectToId(const QString &id)
const T * ptr(const T &t)
QList< Key > keys() const
Returns a list containing all the keys in the map in ascending order.
void clear()
Removes all items from the list.
QString getInterfaceFromId(const QString &id)
void unlock()
Unlocks the mutex.
QMap< QString, QString > configurationInterface
QString getNetworkNameFromSsid(const QString &ssid)
bool isWifiReady(const QString &dev)
SCDynamicStoreRef storeSession
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
QNetworkConfiguration::Purpose purpose
void run()
The starting point for the thread.
QExplicitlySharedDataPointer< QNetworkConfigurationPrivate > QNetworkConfigurationPrivatePointer
Q_INVOKABLE void requestUpdate()
QNetworkConfiguration::Type type
void start(Priority=InheritPriority)
Begins execution of the thread by calling run().
#define QT_MANGLE_NAMESPACE(name)
iterator insert(const Key &key, const T &value)
Inserts a new item with the key key and a value of value.
bool isKnownSsid(const QString &ssid)
QObject * parent() const
Returns a pointer to the parent object.
bool wait(unsigned long time=ULONG_MAX)
Blocks the thread until either of these conditions is met:
quint64 getBytes(const QString &interfaceName, bool b)
void resize(int size)
Sets the size of the byte array to size bytes.
void configurationRemoved(QNetworkConfigurationPrivatePointer config)
void networkChangeCallback(SCDynamicStoreRef, CFArrayRef changedKeys, void *info)
bool contains(const Key &key) const
Returns true if the map contains an item with key key; otherwise returns false.
QNetworkSession::State sessionStateForId(const QString &id)
void connectionError(const QString &id, QBearerEngineImpl::ConnectionError error)
QStringList foundNetwork(const QString &id, const QString &ssid, const QNetworkConfiguration::StateFlags state, const QString &interfaceName, const QNetworkConfiguration::Purpose purpose)
static QNSListener * listener
QList< QNetworkConfigurationPrivate * > foundConfigurations
QNetworkConfigurationManager::Capabilities capabilities() const
const struct __CFArray * CFArrayRef
The QThread class provides a platform-independent way to manage threads.
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
void clear()
Removes all items from the map.
The QList class is a template class that provides lists.
int removeAll(const T &t)
Removes all occurrences of value in the list and returns the number of entries removed.
QByteArray & insert(int i, char c)
Inserts character ch at index position i in the byte array.
static QString homePath()
Returns the absolute path of the user's home directory.