/XMPP_Demo/Core/XMPPStream.m
Objective C | 1956 lines | 1307 code | 445 blank | 204 comment | 225 complexity | 8520742c9f4cfb1871c53159bbc259db MD5 | raw file
- #import "XMPP.h"
- #import "XMPPParser.h"
- #import "XMPPLogging.h"
- #import "XMPPInternal.h"
- #import "XMPPSRVResolver.h"
- #import "NSData+XMPP.h"
- #import <objc/runtime.h>
- #import <libkern/OSAtomic.h>
- #if TARGET_OS_IPHONE
- // Note: You may need to add the CFNetwork Framework to your project
- #import <CFNetwork/CFNetwork.h>
- #endif
- #if ! __has_feature(objc_arc)
- #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
- #endif
- /**
- * Does ARC support support GCD objects?
- * It does if the minimum deployment target is iOS 6+ or Mac OS X 10.8+
- **/
- #if TARGET_OS_IPHONE
- // Compiling for iOS
- #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 // iOS 6.0 or later
- #define NEEDS_DISPATCH_RETAIN_RELEASE 0
- #else // iOS 5.X or earlier
- #define NEEDS_DISPATCH_RETAIN_RELEASE 1
- #endif
- #else
- // Compiling for Mac OS X
- #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 // Mac OS X 10.8 or later
- #define NEEDS_DISPATCH_RETAIN_RELEASE 0
- #else
- #define NEEDS_DISPATCH_RETAIN_RELEASE 1 // Mac OS X 10.7 or earlier
- #endif
- #endif
- // Log levels: off, error, warn, info, verbose
- #if DEBUG
- static const int xmppLogLevel = XMPP_LOG_LEVEL_INFO | XMPP_LOG_FLAG_SEND_RECV; // | XMPP_LOG_FLAG_TRACE;
- #else
- static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN;
- #endif
- /**
- * Seeing a return statements within an inner block
- * can sometimes be mistaken for a return point of the enclosing method.
- * This makes inline blocks a bit easier to read.
- **/
- #define return_from_block return
- // Define the timeouts (in seconds) for retreiving various parts of the XML stream
- #define TIMEOUT_XMPP_WRITE -1
- #define TIMEOUT_XMPP_READ_START 10
- #define TIMEOUT_XMPP_READ_STREAM -1
- // Define the tags we'll use to differentiate what it is we're currently reading or writing
- #define TAG_XMPP_READ_START 100
- #define TAG_XMPP_READ_STREAM 101
- #define TAG_XMPP_WRITE_START 200
- #define TAG_XMPP_WRITE_STREAM 201
- #define TAG_XMPP_WRITE_RECEIPT 202
- NSString *const XMPPStreamErrorDomain = @"XMPPStreamErrorDomain";
- NSString *const XMPPStreamDidChangeMyJIDNotification = @"XMPPStreamDidChangeMyJID";
- enum XMPPStreamFlags
- {
- kP2PInitiator = 1 << 0, // If set, we are the P2P initializer
- kIsSecure = 1 << 1, // If set, connection has been secured via SSL/TLS
- kIsAuthenticated = 1 << 2, // If set, authentication has succeeded
- kDidStartNegotiation = 1 << 3, // If set, negotiation has started at least once
- };
- enum XMPPStreamConfig
- {
- kP2PMode = 1 << 0, // If set, the XMPPStream was initialized in P2P mode
- kResetByteCountPerConnection = 1 << 1, // If set, byte count should be reset per connection
- #if TARGET_OS_IPHONE
- kEnableBackgroundingOnSocket = 1 << 2, // If set, the VoIP flag should be set on the socket
- #endif
- };
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark -
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- @interface XMPPStream ()
- {
- dispatch_queue_t xmppQueue;
-
- dispatch_queue_t willSendIqQueue;
- dispatch_queue_t willSendMessageQueue;
- dispatch_queue_t willSendPresenceQueue;
-
- dispatch_queue_t willReceiveIqQueue;
- dispatch_queue_t willReceiveMessageQueue;
- dispatch_queue_t willReceivePresenceQueue;
-
- dispatch_queue_t didReceiveIqQueue;
-
- GCDMulticastDelegate <XMPPStreamDelegate> *multicastDelegate;
-
- int state;
-
- GCDAsyncSocket *asyncSocket;
-
- UInt64 numberOfBytesSent;
- UInt64 numberOfBytesReceived;
-
- XMPPParser *parser;
- NSError *parserError;
-
- Byte flags;
- Byte config;
-
- NSString *hostName;
- UInt16 hostPort;
-
- id <XMPPSASLAuthentication> auth;
-
- XMPPJID *myJID_setByClient;
- XMPPJID *myJID_setByServer;
- XMPPJID *remoteJID;
-
- XMPPPresence *myPresence;
- NSXMLElement *rootElement;
-
- NSTimeInterval keepAliveInterval;
- dispatch_source_t keepAliveTimer;
- NSTimeInterval lastSendReceiveTime;
- NSData *keepAliveData;
-
- NSMutableArray *registeredModules;
- NSMutableDictionary *autoDelegateDict;
-
- XMPPSRVResolver *srvResolver;
- NSArray *srvResults;
- NSUInteger srvResultsIndex;
-
- NSMutableArray *receipts;
-
- NSThread *xmppUtilityThread;
- NSRunLoop *xmppUtilityRunLoop;
-
- id userTag;
- }
- - (void)setIsSecure:(BOOL)flag;
- - (void)setIsAuthenticated:(BOOL)flag;
- - (void)continueSendIQ:(XMPPIQ *)iq withTag:(long)tag;
- - (void)continueSendMessage:(XMPPMessage *)message withTag:(long)tag;
- - (void)continueSendPresence:(XMPPPresence *)presence withTag:(long)tag;
- - (void)startNegotiation;
- - (void)sendOpeningNegotiation;
- - (void)continueStartTLS:(NSMutableDictionary *)settings;
- - (void)continueHandleBinding:(NSString *)alternativeResource;
- - (void)setupKeepAliveTimer;
- - (void)keepAlive;
- - (void)continueReceiveMessage:(XMPPMessage *)message;
- - (void)continueReceiveIQ:(XMPPIQ *)iq;
- - (void)continueReceivePresence:(XMPPPresence *)presence;
- @end
- @interface XMPPElementReceipt (PrivateAPI)
- - (void)signalSuccess;
- - (void)signalFailure;
- @end
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark -
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- @implementation XMPPStream
- @synthesize tag = userTag;
- /**
- * Shared initialization between the various init methods.
- **/
- - (void)commonInit
- {
- xmppQueue = dispatch_queue_create("xmpp", NULL);
-
- willSendIqQueue = dispatch_queue_create("xmpp.willSendIq", NULL);
- willSendMessageQueue = dispatch_queue_create("xmpp.willSendMessage", NULL);
- willSendPresenceQueue = dispatch_queue_create("xmpp.willSendPresence", NULL);
-
- willReceiveIqQueue = dispatch_queue_create("xmpp.willReceiveIq", NULL);
- willReceiveMessageQueue = dispatch_queue_create("xmpp.willReceiveMessage", NULL);
- willReceivePresenceQueue = dispatch_queue_create("xmpp.willReceivePresence", NULL);
-
- didReceiveIqQueue = dispatch_queue_create("xmpp.didReceiveIq", NULL);
-
- multicastDelegate = (GCDMulticastDelegate <XMPPStreamDelegate> *)[[GCDMulticastDelegate alloc] init];
-
- state = STATE_XMPP_DISCONNECTED;
-
- flags = 0;
- config = 0;
-
- numberOfBytesSent = 0;
- numberOfBytesReceived = 0;
-
- hostPort = 5222;
- keepAliveInterval = DEFAULT_KEEPALIVE_INTERVAL;
- keepAliveData = [@" " dataUsingEncoding:NSUTF8StringEncoding];
-
- registeredModules = [[NSMutableArray alloc] init];
- autoDelegateDict = [[NSMutableDictionary alloc] init];
-
- receipts = [[NSMutableArray alloc] init];
-
- // Setup and start the utility thread.
- // We need to be careful to ensure the thread doesn't retain a reference to us longer than necessary.
-
- xmppUtilityThread = [[NSThread alloc] initWithTarget:[self class] selector:@selector(xmppThreadMain) object:nil];
- [[xmppUtilityThread threadDictionary] setObject:self forKey:@"XMPPStream"];
- [xmppUtilityThread start];
- }
- /**
- * Standard XMPP initialization.
- * The stream is a standard client to server connection.
- **/
- - (id)init
- {
- if ((self = [super init]))
- {
- // Common initialization
- [self commonInit];
-
- // Initialize socket
- asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:xmppQueue];
- }
- return self;
- }
- /**
- * Peer to Peer XMPP initialization.
- * The stream is a direct client to client connection as outlined in XEP-0174.
- **/
- - (id)initP2PFrom:(XMPPJID *)jid
- {
- if ((self = [super init]))
- {
- // Common initialization
- [self commonInit];
-
- // Store JID
- myJID_setByClient = jid;
-
- // We do not initialize the socket, since the connectP2PWithSocket: method might be used.
-
- // Initialize configuration
- config = kP2PMode;
- }
- return self;
- }
- /**
- * Standard deallocation method.
- * Every object variable declared in the header file should be released here.
- **/
- - (void)dealloc
- {
- #if NEEDS_DISPATCH_RETAIN_RELEASE
- dispatch_release(xmppQueue);
- dispatch_release(willSendIqQueue);
- dispatch_release(willSendMessageQueue);
- dispatch_release(willSendPresenceQueue);
- dispatch_release(willReceiveIqQueue);
- dispatch_release(willReceiveMessageQueue);
- dispatch_release(willReceivePresenceQueue);
- dispatch_release(didReceiveIqQueue);
- #endif
-
- [asyncSocket setDelegate:nil delegateQueue:NULL];
- [asyncSocket disconnect];
-
- [parser setDelegate:nil delegateQueue:NULL];
-
- if (keepAliveTimer)
- {
- dispatch_source_cancel(keepAliveTimer);
- }
-
- for (XMPPElementReceipt *receipt in receipts)
- {
- [receipt signalFailure];
- }
-
- [[self class] performSelector:@selector(xmppThreadStop)
- onThread:xmppUtilityThread
- withObject:nil
- waitUntilDone:NO];
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Properties
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- @synthesize xmppQueue;
- - (XMPPStreamState)state
- {
- __block XMPPStreamState result = STATE_XMPP_DISCONNECTED;
-
- dispatch_block_t block = ^{
- result = (XMPPStreamState)state;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (NSString *)hostName
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return hostName;
- }
- else
- {
- __block NSString *result;
-
- dispatch_sync(xmppQueue, ^{
- result = hostName;
- });
-
- return result;
- }
- }
- - (void)setHostName:(NSString *)newHostName
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- if (hostName != newHostName)
- {
- hostName = [newHostName copy];
- }
- }
- else
- {
- NSString *newHostNameCopy = [newHostName copy];
-
- dispatch_async(xmppQueue, ^{
- hostName = newHostNameCopy;
- });
-
- }
- }
- - (UInt16)hostPort
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return hostPort;
- }
- else
- {
- __block UInt16 result;
-
- dispatch_sync(xmppQueue, ^{
- result = hostPort;
- });
-
- return result;
- }
- }
- - (void)setHostPort:(UInt16)newHostPort
- {
- dispatch_block_t block = ^{
- hostPort = newHostPort;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (XMPPJID *)myJID
- {
- __block XMPPJID *result = nil;
-
- dispatch_block_t block = ^{
-
- if (myJID_setByServer)
- result = myJID_setByServer;
- else
- result = myJID_setByClient;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (void)setMyJID_setByClient:(XMPPJID *)newMyJID
- {
- // XMPPJID is an immutable class (copy == retain)
-
- dispatch_block_t block = ^{
-
- if (![myJID_setByClient isEqualToJID:newMyJID])
- {
- myJID_setByClient = newMyJID;
-
- if (myJID_setByServer == nil)
- {
- [[NSNotificationCenter defaultCenter] postNotificationName:XMPPStreamDidChangeMyJIDNotification
- object:self];
- }
- }
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (void)setMyJID_setByServer:(XMPPJID *)newMyJID
- {
- // XMPPJID is an immutable class (copy == retain)
-
- dispatch_block_t block = ^{
-
- if (![myJID_setByServer isEqualToJID:newMyJID])
- {
- XMPPJID *oldMyJID;
- if (myJID_setByServer)
- oldMyJID = myJID_setByServer;
- else
- oldMyJID = myJID_setByClient;
-
- myJID_setByServer = newMyJID;
-
- if (![oldMyJID isEqualToJID:newMyJID])
- {
- [[NSNotificationCenter defaultCenter] postNotificationName:XMPPStreamDidChangeMyJIDNotification
- object:self];
- }
- }
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (void)setMyJID:(XMPPJID *)newMyJID
- {
- [self setMyJID_setByClient:newMyJID];
- }
- - (XMPPJID *)remoteJID
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return remoteJID;
- }
- else
- {
- __block XMPPJID *result;
-
- dispatch_sync(xmppQueue, ^{
- result = remoteJID;
- });
-
- return result;
- }
- }
- - (XMPPPresence *)myPresence
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return myPresence;
- }
- else
- {
- __block XMPPPresence *result;
-
- dispatch_sync(xmppQueue, ^{
- result = myPresence;
- });
-
- return result;
- }
- }
- - (NSTimeInterval)keepAliveInterval
- {
- __block NSTimeInterval result = 0.0;
-
- dispatch_block_t block = ^{
- result = keepAliveInterval;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (void)setKeepAliveInterval:(NSTimeInterval)interval
- {
- dispatch_block_t block = ^{
-
- if (keepAliveInterval != interval)
- {
- if (interval <= 0.0)
- keepAliveInterval = interval;
- else
- keepAliveInterval = MAX(interval, MIN_KEEPALIVE_INTERVAL);
-
- [self setupKeepAliveTimer];
- }
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (char)keepAliveWhitespaceCharacter
- {
- __block char keepAliveChar = ' ';
-
- dispatch_block_t block = ^{
-
- NSString *keepAliveString = [[NSString alloc] initWithData:keepAliveData encoding:NSUTF8StringEncoding];
- if ([keepAliveString length] > 0)
- {
- keepAliveChar = (char)[keepAliveString characterAtIndex:0];
- }
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return keepAliveChar;
- }
- - (void)setKeepAliveWhitespaceCharacter:(char)keepAliveChar
- {
- dispatch_block_t block = ^{
-
- if (keepAliveChar == ' ' || keepAliveChar == '\n' || keepAliveChar == '\t')
- {
- keepAliveData = [[NSString stringWithFormat:@"%c", keepAliveChar] dataUsingEncoding:NSUTF8StringEncoding];
- }
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (UInt64)numberOfBytesSent
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return numberOfBytesSent;
- }
- else
- {
- __block UInt64 result;
-
- dispatch_sync(xmppQueue, ^{
- result = numberOfBytesSent;
- });
-
- return result;
- }
- }
- - (UInt64)numberOfBytesReceived
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return numberOfBytesReceived;
- }
- else
- {
- __block UInt64 result;
-
- dispatch_sync(xmppQueue, ^{
- result = numberOfBytesReceived;
- });
-
- return result;
- }
- }
- - (BOOL)resetByteCountPerConnection
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{
- result = (config & kResetByteCountPerConnection) ? YES : NO;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (void)setResetByteCountPerConnection:(BOOL)flag
- {
- dispatch_block_t block = ^{
- if (flag)
- config |= kResetByteCountPerConnection;
- else
- config &= ~kResetByteCountPerConnection;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- #if TARGET_OS_IPHONE
- - (BOOL)enableBackgroundingOnSocket
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{
- result = (config & kEnableBackgroundingOnSocket) ? YES : NO;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (void)setEnableBackgroundingOnSocket:(BOOL)flag
- {
- dispatch_block_t block = ^{
- if (flag)
- config |= kEnableBackgroundingOnSocket;
- else
- config &= ~kEnableBackgroundingOnSocket;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- #endif
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Configuration
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue
- {
- // Asynchronous operation (if outside xmppQueue)
-
- dispatch_block_t block = ^{
- [multicastDelegate addDelegate:delegate delegateQueue:delegateQueue];
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue
- {
- // Synchronous operation
-
- dispatch_block_t block = ^{
- [multicastDelegate removeDelegate:delegate delegateQueue:delegateQueue];
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
- }
- - (void)removeDelegate:(id)delegate
- {
- // Synchronous operation
-
- dispatch_block_t block = ^{
- [multicastDelegate removeDelegate:delegate];
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
- }
- /**
- * Returns YES if the stream was opened in P2P mode.
- * In other words, the stream was created via initP2PFrom: to use XEP-0174.
- **/
- - (BOOL)isP2P
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return (config & kP2PMode) ? YES : NO;
- }
- else
- {
- __block BOOL result;
-
- dispatch_sync(xmppQueue, ^{
- result = (config & kP2PMode) ? YES : NO;
- });
-
- return result;
- }
- }
- - (BOOL)isP2PInitiator
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return ((config & kP2PMode) && (flags & kP2PInitiator));
- }
- else
- {
- __block BOOL result;
-
- dispatch_sync(xmppQueue, ^{
- result = ((config & kP2PMode) && (flags & kP2PInitiator));
- });
-
- return result;
- }
- }
- - (BOOL)isP2PRecipient
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return ((config & kP2PMode) && !(flags & kP2PInitiator));
- }
- else
- {
- __block BOOL result;
-
- dispatch_sync(xmppQueue, ^{
- result = ((config & kP2PMode) && !(flags & kP2PInitiator));
- });
-
- return result;
- }
- }
- - (BOOL)didStartNegotiation
- {
- NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue");
-
- return (flags & kDidStartNegotiation) ? YES : NO;
- }
- - (void)setDidStartNegotiation:(BOOL)flag
- {
- NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue");
-
- if (flag)
- flags |= kDidStartNegotiation;
- else
- flags &= ~kDidStartNegotiation;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Connection State
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * Returns YES if the connection is closed, and thus no stream is open.
- * If the stream is neither disconnected, nor connected, then a connection is currently being established.
- **/
- - (BOOL)isDisconnected
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{
- result = (state == STATE_XMPP_DISCONNECTED);
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- /**
- * Returns YES if the connection is open, and the stream has been properly established.
- * If the stream is neither disconnected, nor connected, then a connection is currently being established.
- **/
- - (BOOL)isConnected
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{
- result = (state == STATE_XMPP_CONNECTED);
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark C2S Connection
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- - (BOOL)connectToHost:(NSString *)host onPort:(UInt16)port error:(NSError **)errPtr
- {
- NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue");
-
- XMPPLogTrace();
-
- BOOL result = [asyncSocket connectToHost:host onPort:port error:errPtr];
-
- if (result && [self resetByteCountPerConnection])
- {
- numberOfBytesSent = 0;
- numberOfBytesReceived = 0;
- }
-
- return result;
- }
- - (BOOL)connect:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = NO;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_DISCONNECTED)
- {
- NSString *errMsg = @"Attempting to connect while already connected or connecting.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if ([self isP2P])
- {
- NSString *errMsg = @"P2P streams must use either connectTo:withAddress: or connectP2PWithSocket:.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidType userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (myJID_setByClient == nil)
- {
- // Note: If you wish to use anonymous authentication, you should still set myJID prior to calling connect.
- // You can simply set it to something like "anonymous@<domain>", where "<domain>" is the proper domain.
- // After the authentication process, you can query the myJID property to see what your assigned JID is.
- //
- // Setting myJID allows the framework to follow the xmpp protocol properly,
- // and it allows the framework to connect to servers without a DNS entry.
- //
- // For example, one may setup a private xmpp server for internal testing on their local network.
- // The xmpp domain of the server may be something like "testing.mycompany.com",
- // but since the server is internal, an IP (192.168.1.22) is used as the hostname to connect.
- //
- // Proper connection requires a TCP connection to the IP (192.168.1.22),
- // but the xmpp handshake requires the xmpp domain (testing.mycompany.com).
-
- NSString *errMsg = @"You must set myJID before calling connect.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info];
-
- result = NO;
- return_from_block;
- }
- // Notify delegates
- [multicastDelegate xmppStreamWillConnect:self];
- if ([hostName length] == 0)
- {
- // Resolve the hostName via myJID SRV resolution
-
- state = STATE_XMPP_RESOLVING_SRV;
-
- srvResolver = [[XMPPSRVResolver alloc] initWithdDelegate:self delegateQueue:xmppQueue resolverQueue:NULL];
-
- srvResults = nil;
- srvResultsIndex = 0;
-
- NSString *srvName = [XMPPSRVResolver srvNameFromXMPPDomain:[myJID_setByClient domain]];
-
- [srvResolver startWithSRVName:srvName timeout:30.0];
-
- result = YES;
- }
- else
- {
- // Open TCP connection to the configured hostName.
-
- state = STATE_XMPP_CONNECTING;
-
- NSError *connectErr = nil;
- result = [self connectToHost:hostName onPort:hostPort error:&connectErr];
-
- if (!result)
- {
- err = connectErr;
- state = STATE_XMPP_DISCONNECTED;
- }
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- - (BOOL)oldSchoolSecureConnect:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = NO;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- // Go through the regular connect routine
- NSError *connectErr = nil;
- result = [self connect:&connectErr];
-
- if (result)
- {
- // Mark the secure flag.
- // We will check the flag in socket:didConnectToHost:port:
-
- [self setIsSecure:YES];
- }
- else
- {
- err = connectErr;
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark P2P Connection
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * Starts a P2P connection to the given user and given address.
- * This method only works with XMPPStream objects created using the initP2P method.
- *
- * The given address is specified as a sockaddr structure wrapped in a NSData object.
- * For example, a NSData object returned from NSNetservice's addresses method.
- **/
- - (BOOL)connectTo:(XMPPJID *)jid withAddress:(NSData *)remoteAddr error:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = YES;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_DISCONNECTED)
- {
- NSString *errMsg = @"Attempting to connect while already connected or connecting.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (![self isP2P])
- {
- NSString *errMsg = @"Non P2P streams must use the connect: method";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidType userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- // Turn on P2P initiator flag
- flags |= kP2PInitiator;
-
- // Store remoteJID
- remoteJID = [jid copy];
-
- NSAssert((asyncSocket == nil), @"Forgot to release the previous asyncSocket instance.");
- // Notify delegates
- [multicastDelegate xmppStreamWillConnect:self];
- // Update state
- state = STATE_XMPP_CONNECTING;
-
- // Initailize socket
- asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:xmppQueue];
-
- NSError *connectErr = nil;
- result = [asyncSocket connectToAddress:remoteAddr error:&connectErr];
-
- if (result == NO)
- {
- err = connectErr;
- state = STATE_XMPP_DISCONNECTED;
- }
- else if ([self resetByteCountPerConnection])
- {
- numberOfBytesSent = 0;
- numberOfBytesReceived = 0;
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- /**
- * Starts a P2P connection with the given accepted socket.
- * This method only works with XMPPStream objects created using the initP2P method.
- *
- * The given socket should be a socket that has already been accepted.
- * The remoteJID will be extracted from the opening stream negotiation.
- **/
- - (BOOL)connectP2PWithSocket:(GCDAsyncSocket *)acceptedSocket error:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = YES;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_DISCONNECTED)
- {
- NSString *errMsg = @"Attempting to connect while already connected or connecting.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (![self isP2P])
- {
- NSString *errMsg = @"Non P2P streams must use the connect: method";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidType userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (acceptedSocket == nil)
- {
- NSString *errMsg = @"Parameter acceptedSocket is nil.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidParameter userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- // Turn off P2P initiator flag
- flags &= ~kP2PInitiator;
-
- NSAssert((asyncSocket == nil), @"Forgot to release the previous asyncSocket instance.");
-
- // Store and configure socket
- asyncSocket = acceptedSocket;
- [asyncSocket setDelegate:self delegateQueue:xmppQueue];
-
- // Notify delegates
- [multicastDelegate xmppStream:self socketDidConnect:asyncSocket];
- // Update state
- state = STATE_XMPP_CONNECTING;
-
- if ([self resetByteCountPerConnection])
- {
- numberOfBytesSent = 0;
- numberOfBytesReceived = 0;
- }
-
- // Start the XML stream
- [self startNegotiation];
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Disconnect
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * Closes the connection to the remote host.
- **/
- - (void)disconnect
- {
- XMPPLogTrace();
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_DISCONNECTED)
- {
- [multicastDelegate xmppStreamWasToldToDisconnect:self];
-
- if (state == STATE_XMPP_RESOLVING_SRV)
- {
- [srvResolver stop];
- srvResolver = nil;
-
- state = STATE_XMPP_DISCONNECTED;
-
- [multicastDelegate xmppStreamDidDisconnect:self withError:nil];
- }
- else
- {
- [asyncSocket disconnect];
-
- // Everthing will be handled in socketDidDisconnect:withError:
- }
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
- }
- - (void)disconnectAfterSending
- {
- XMPPLogTrace();
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_DISCONNECTED)
- {
- [multicastDelegate xmppStreamWasToldToDisconnect:self];
-
- if (state == STATE_XMPP_RESOLVING_SRV)
- {
- [srvResolver stop];
- srvResolver = nil;
-
- state = STATE_XMPP_DISCONNECTED;
-
- [multicastDelegate xmppStreamDidDisconnect:self withError:nil];
- }
- else
- {
- NSString *termStr = @"</stream:stream>";
- NSData *termData = [termStr dataUsingEncoding:NSUTF8StringEncoding];
-
- XMPPLogSend(@"SEND: %@", termStr);
- numberOfBytesSent += [termData length];
-
- [asyncSocket writeData:termData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM];
- [asyncSocket disconnectAfterWriting];
-
- // Everthing will be handled in socketDidDisconnect:withError:
- }
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Security
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * Returns YES if SSL/TLS has been used to secure the connection.
- **/
- - (BOOL)isSecure
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return (flags & kIsSecure) ? YES : NO;
- }
- else
- {
- __block BOOL result;
-
- dispatch_sync(xmppQueue, ^{
- result = (flags & kIsSecure) ? YES : NO;
- });
-
- return result;
- }
- }
- - (void)setIsSecure:(BOOL)flag
- {
- dispatch_block_t block = ^{
- if(flag)
- flags |= kIsSecure;
- else
- flags &= ~kIsSecure;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- - (BOOL)supportsStartTLS
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- // The root element can be properly queried for authentication mechanisms anytime after the
- // stream:features are received, and TLS has been setup (if required)
- if (state >= STATE_XMPP_POST_NEGOTIATION)
- {
- NSXMLElement *features = [rootElement elementForName:@"stream:features"];
- NSXMLElement *starttls = [features elementForName:@"starttls" xmlns:@"urn:ietf:params:xml:ns:xmpp-tls"];
-
- result = (starttls != nil);
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (void)sendStartTLSRequest
- {
- NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue");
-
- XMPPLogTrace();
-
- NSString *starttls = @"<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>";
-
- NSData *outgoingData = [starttls dataUsingEncoding:NSUTF8StringEncoding];
-
- XMPPLogSend(@"SEND: %@", starttls);
- numberOfBytesSent += [outgoingData length];
-
- [asyncSocket writeData:outgoingData
- withTimeout:TIMEOUT_XMPP_WRITE
- tag:TAG_XMPP_WRITE_STREAM];
- }
- - (BOOL)secureConnection:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = YES;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_CONNECTED)
- {
- NSString *errMsg = @"Please wait until the stream is connected.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if ([self isSecure])
- {
- NSString *errMsg = @"The connection is already secure.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (![self supportsStartTLS])
- {
- NSString *errMsg = @"The server does not support startTLS.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- // Update state
- state = STATE_XMPP_STARTTLS_1;
-
- // Send the startTLS XML request
- [self sendStartTLSRequest];
-
- // We do not mark the stream as secure yet.
- // We're waiting to receive the <proceed/> response from the
- // server before we actually start the TLS handshake.
-
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Registration
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * This method checks the stream features of the connected server to determine if in-band registartion is supported.
- * If we are not connected to a server, this method simply returns NO.
- **/
- - (BOOL)supportsInBandRegistration
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- // The root element can be properly queried for authentication mechanisms anytime after the
- // stream:features are received, and TLS has been setup (if required)
- if (state >= STATE_XMPP_POST_NEGOTIATION)
- {
- NSXMLElement *features = [rootElement elementForName:@"stream:features"];
- NSXMLElement *reg = [features elementForName:@"register" xmlns:@"http://jabber.org/features/iq-register"];
-
- result = (reg != nil);
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- /**
- * This method attempts to register a new user on the server using the given username and password.
- * The result of this action will be returned via the delegate methods.
- *
- * If the XMPPStream is not connected, or the server doesn't support in-band registration, this method does nothing.
- **/
- - (BOOL)registerWithPassword:(NSString *)password error:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = YES;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_CONNECTED)
- {
- NSString *errMsg = @"Please wait until the stream is connected.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (myJID_setByClient == nil)
- {
- NSString *errMsg = @"You must set myJID before calling registerWithPassword:error:.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (![self supportsInBandRegistration])
- {
- NSString *errMsg = @"The server does not support in band registration.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- NSString *username = [myJID_setByClient user];
-
- NSXMLElement *queryElement = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:register"];
- [queryElement addChild:[NSXMLElement elementWithName:@"username" stringValue:username]];
- [queryElement addChild:[NSXMLElement elementWithName:@"password" stringValue:password]];
-
- NSXMLElement *iqElement = [NSXMLElement elementWithName:@"iq"];
- [iqElement addAttributeWithName:@"type" stringValue:@"set"];
- [iqElement addChild:queryElement];
-
- NSString *outgoingStr = [iqElement compactXMLString];
- NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding];
-
- XMPPLogSend(@"SEND: %@", outgoingStr);
- numberOfBytesSent += [outgoingData length];
-
- [asyncSocket writeData:outgoingData
- withTimeout:TIMEOUT_XMPP_WRITE
- tag:TAG_XMPP_WRITE_STREAM];
-
- // Update state
- state = STATE_XMPP_REGISTERING;
-
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark Authentication
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- - (NSArray *)supportedAuthenticationMechanisms
- {
- __block NSMutableArray *result = [[NSMutableArray alloc] init];
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- // The root element can be properly queried for authentication mechanisms anytime after the
- // stream:features are received, and TLS has been setup (if required).
-
- if (state >= STATE_XMPP_POST_NEGOTIATION)
- {
- NSXMLElement *features = [rootElement elementForName:@"stream:features"];
- NSXMLElement *mech = [features elementForName:@"mechanisms" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"];
-
- NSArray *mechanisms = [mech elementsForName:@"mechanism"];
-
- for (NSXMLElement *mechanism in mechanisms)
- {
- [result addObject:[mechanism stringValue]];
- }
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- /**
- * This method checks the stream features of the connected server to determine
- * if the given authentication mechanism is supported.
- *
- * If we are not connected to a server, this method simply returns NO.
- **/
- - (BOOL)supportsAuthenticationMechanism:(NSString *)mechanismType
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- // The root element can be properly queried for authentication mechanisms anytime after the
- // stream:features are received, and TLS has been setup (if required).
-
- if (state >= STATE_XMPP_POST_NEGOTIATION)
- {
- NSXMLElement *features = [rootElement elementForName:@"stream:features"];
- NSXMLElement *mech = [features elementForName:@"mechanisms" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"];
-
- NSArray *mechanisms = [mech elementsForName:@"mechanism"];
-
- for (NSXMLElement *mechanism in mechanisms)
- {
- if ([[mechanism stringValue] isEqualToString:mechanismType])
- {
- result = YES;
- break;
- }
- }
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (BOOL)authenticate:(id <XMPPSASLAuthentication>)inAuth error:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- __block BOOL result = NO;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_CONNECTED)
- {
- NSString *errMsg = @"Please wait until the stream is connected.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (myJID_setByClient == nil)
- {
- NSString *errMsg = @"You must set myJID before calling authenticate:error:.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- // Change state.
- // We do this now because when we invoke the start method below,
- // it may in turn invoke our sendAuthElement method, which expects us to be in STATE_XMPP_AUTH.
- state = STATE_XMPP_AUTH;
-
- if ([inAuth start:&err])
- {
- auth = inAuth;
- result = YES;
- }
- else
- {
- // Unable to start authentication for some reason.
- // Revert back to connected state.
- state = STATE_XMPP_CONNECTED;
- }
- }};
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- /**
- * This method applies to standard password authentication schemes only.
- * This is NOT the primary authentication method.
- *
- * @see authenticate:error:
- *
- * This method exists for backwards compatibility, and may disappear in future versions.
- **/
- - (BOOL)authenticateWithPassword:(NSString *)inPassword error:(NSError **)errPtr
- {
- XMPPLogTrace();
-
- // The given password parameter could be mutable
- NSString *password = [inPassword copy];
-
-
- __block BOOL result = YES;
- __block NSError *err = nil;
-
- dispatch_block_t block = ^{ @autoreleasepool {
-
- if (state != STATE_XMPP_CONNECTED)
- {
- NSString *errMsg = @"Please wait until the stream is connected.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- if (myJID_setByClient == nil)
- {
- NSString *errMsg = @"You must set myJID before calling authenticate:error:.";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info];
-
- result = NO;
- return_from_block;
- }
-
- // Choose the best authentication method.
- //
- // P.S. - This method is deprecated.
-
- id <XMPPSASLAuthentication> someAuth = nil;
-
- if ([self supportsDigestMD5Authentication])
- {
- someAuth = [[XMPPDigestMD5Authentication alloc] initWithStream:self password:password];
- result = [self authenticate:someAuth error:&err];
- }
- else if ([self supportsPlainAuthentication])
- {
- someAuth = [[XMPPPlainAuthentication alloc] initWithStream:self password:password];
- result = [self authenticate:someAuth error:&err];
- }
- else if ([self supportsDeprecatedDigestAuthentication])
- {
- someAuth = [[XMPPDeprecatedDigestAuthentication alloc] initWithStream:self password:password];
- result = [self authenticate:someAuth error:&err];
- }
- else if ([self supportsDeprecatedPlainAuthentication])
- {
- someAuth = [[XMPPDeprecatedDigestAuthentication alloc] initWithStream:self password:password];
- result = [self authenticate:someAuth error:&err];
- }
- else
- {
- NSString *errMsg = @"No suitable authentication method found";
- NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
-
- err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info];
-
- result = NO;
- }
- }};
-
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- if (errPtr)
- *errPtr = err;
-
- return result;
- }
- - (BOOL)isAuthenticated
- {
- __block BOOL result = NO;
-
- dispatch_block_t block = ^{
- result = (flags & kIsAuthenticated) ? YES : NO;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_sync(xmppQueue, block);
-
- return result;
- }
- - (void)setIsAuthenticated:(BOOL)flag
- {
- dispatch_block_t block = ^{
- if(flag)
- flags |= kIsAuthenticated;
- else
- flags &= ~kIsAuthenticated;
- };
-
- if (dispatch_get_current_queue() == xmppQueue)
- block();
- else
- dispatch_async(xmppQueue, block);
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #pragma mark General Methods
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * This method will return the root element of the document.
- * This element contains the opening <stream:stream/> and <stream:features/> tags received from the server
- * when the XML stream was opened.
- *
- * Note: The rootElement is empty, and does not contain all the XML elements the stream has received during it's
- * connection. This is done for performance reasons and for the obvious benefit of being more memory efficient.
- **/
- - (NSXMLElement *)rootElement
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return rootElement;
- }
- else
- {
- __block NSXMLElement *result = nil;
-
- dispatch_sync(xmppQueue, ^{
- result = [rootElement copy];
- });
-
- return result;
- }
- }
- /**
- * Returns the version attribute from the servers's <stream:stream/> element.
- * This should be at least 1.0 to be RFC 3920 compliant.
- * If no version number was set, the server is not RFC compliant, and 0 is returned.
- **/
- - (float)serverXmppStreamVersionNumber
- {
- if (dispatch_get_current_queue() == xmppQueue)
- {
- return [rootElement attributeFloatValueForName:@"version" withDefaultValue:0.0F];
- }
- else
- {
- __block float result;
-
- dispatch_sync(xmppQueue, ^{
- result = [rootElement attributeFloatValueForName:@"version" withDefaultValue:0.0F];
- });
-
- return result;
- }
- }
- - (void)sendIQ:(XMPPIQ *)iq withTag:(long)tag
- {
- NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue");
- NSAssert(state == STATE_XMPP_CONNECTED, @"Invoked with incorrect state");
-
- // We're getting ready to send an IQ.
- // Notify delegates to allow them to optionally alter/filter the outgoing IQ.
-
- SEL selector = @selector(xmppStream:willSendIQ:);
-
- if (![multicastDelegate hasDelegateThatRespondsToSelector:selector])
- {
- // None of the delegates implement the method.
- // Use a shortcut.
-
- [self continueSendIQ:iq withTag:tag];
- }
- else
- {
- // Notify all interested delegates.
- // This must be done serially to allow them to alter the element in a thread-safe manner.
-
- GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator];
-
- dispatch_async(willSendIqQueue, ^{ @autoreleasepool {
-
- // Allow delegates to modify and/or filter outgoing element
-
- __block XMPPIQ *modifiedIQ = iq;
-
- id del;
- dispatch_queue_t dq;
-
- while (modifiedIQ && [delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector])
- {
- #if DEBUG
- {
- char methodReturnType[32];
-
- Method method = class_getInstanceMethod([del class], selector);
- method_getReturnType(method, methodReturnType, sizeof(methodReturnType));
-
- if (strcmp(methodReturnType, @encode(XMPPIQ*)) != 0)
- {
- NSAssert(NO, @"Method xmppStream:willSendIQ: is no longer void (see XMPPStream.h). "
- @"Culprit = %@", NSStringFromClass([del class]));
- }
- }
- #endif
-
- dispatch_sync(dq, ^{ @autoreleasepool {
-
- modifiedIQ = [del xmppStream:self willSendIQ:modifiedIQ];
-
- }});
- }
-
- if (modifiedIQ)
- {
- dispatch_async(xmppQueue, ^{ @autoreleasepool {
-
- if (state == STATE_XMPP_CONNECTED) {
- [self continueSendIQ:modifiedIQ withTag:tag];
- }
- }});
- }
- }});
- }
- }
- - (void)sendMessage:(XMPPMessage *)message withTag:(long)tag
- {
- NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue");
- NSAssert(state == STATE_XMPP_CONNECTED, @"Invoked with incorrect state");
-
- // We're getting ready to send a message.
- // Notify delegates to allow them to optionally alter/filter the outgoing message.
-
- SEL selector = @selector(xmppStream:willSendMessage:);
-
- if (![multicastDelegate hasDelegateThatRespondsToSelector:selector])
- {
- // None of the delegates implement the method.
- // Use a shortcut.
-
- [self continueSendMessage:message withTag:tag];
- }
- else
- {
- // Notify all interested delegates.
- // This must be done serially to allow them to alter the element in a thread-safe manner.
-
- GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator];
-
- dispatch_async(willSendMessageQueue, ^{ @autoreleasepool {
-
- // Allow delegates to modify outgoing element
-
- __block XMPPMessage *modifiedMessage = message;
-
- id del;
- dispatch_queue_t dq;
-
- while (modifiedMessage && [delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector])
- {
- #if DEBUG
- {
- char metho