-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathXMPPStream.h
1146 lines (1025 loc) · 49.9 KB
/
XMPPStream.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import <Foundation/Foundation.h>
#import "XMPPSASLAuthentication.h"
#import "XMPPCustomBinding.h"
#import "GCDMulticastDelegate.h"
@import KissXML;
@import CocoaAsyncSocket;
NS_ASSUME_NONNULL_BEGIN
@class XMPPSRVResolver;
@class XMPPParser;
@class XMPPJID;
@class XMPPIQ;
@class XMPPMessage;
@class XMPPPresence;
@class XMPPModule;
@class XMPPElement;
@class XMPPElementReceipt;
@protocol XMPPStreamDelegate;
#if TARGET_OS_IPHONE
#define MIN_KEEPALIVE_INTERVAL 20.0 // 20 Seconds
#define DEFAULT_KEEPALIVE_INTERVAL 120.0 // 2 Minutes
#else
#define MIN_KEEPALIVE_INTERVAL 10.0 // 10 Seconds
#define DEFAULT_KEEPALIVE_INTERVAL 300.0 // 5 Minutes
#endif
extern NSString *const XMPPStreamErrorDomain;
typedef NS_ENUM(NSUInteger, XMPPStreamErrorCode) {
XMPPStreamInvalidType, // Attempting to access P2P methods in a non-P2P stream, or vice-versa
XMPPStreamInvalidState, // Invalid state for requested action, such as connect when already connected
XMPPStreamInvalidProperty, // Missing a required property, such as myJID
XMPPStreamInvalidParameter, // Invalid parameter, such as a nil JID
XMPPStreamUnsupportedAction, // The server doesn't support the requested action
};
typedef NS_ENUM(NSUInteger, XMPPStreamStartTLSPolicy) {
XMPPStreamStartTLSPolicyAllowed, // TLS will be used if the server requires it
XMPPStreamStartTLSPolicyPreferred, // TLS will be used if the server offers it
XMPPStreamStartTLSPolicyRequired // TLS will be used if the server offers it, else the stream won't connect
};
extern const NSTimeInterval XMPPStreamTimeoutNone;
@interface XMPPStream : NSObject <GCDAsyncSocketDelegate>
/**
* Standard XMPP initialization.
* The stream is a standard client to server connection.
*
* P2P streams using XEP-0174 are also supported.
* See the P2P section below.
**/
- (instancetype)init;
/**
* Peer to Peer XMPP initialization.
* The stream is a direct client to client connection as outlined in XEP-0174.
**/
- (instancetype)initP2PFrom:(XMPPJID *)myJID;
/**
* XMPPStream uses a multicast delegate.
* This allows one to add multiple delegates to a single XMPPStream instance,
* which makes it easier to separate various components and extensions.
*
* For example, if you were implementing two different custom extensions on top of XMPP,
* you could put them in separate classes, and simply add each as a delegate.
**/
- (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
- (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
- (void)removeDelegate:(id)delegate;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Properties
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The server's hostname that should be used to make the TCP connection.
* This may be a domain name (e.g. "deusty.com") or an IP address (e.g. "70.85.193.226").
*
* Note that this may be different from the virtual xmpp hostname.
* Just as HTTP servers can support mulitple virtual hosts from a single server, so too can xmpp servers.
* A prime example is google via google apps.
*
* For example, say you own the domain "mydomain.com".
* If you go to mydomain.com in a web browser,
* you are directed to your apache server running on your webserver somewhere in the cloud.
* But you use google apps for your email and xmpp needs.
* So if somebody sends you an email, it actually goes to google's servers, where you later access it from.
* Similarly, you connect to google's servers to #to xmpp.
*
* In the example above, your hostname is "talk.google.com" and your JID is "me@mydomain.com".
*
* This hostName property is optional.
* If you do not set the hostName, then the framework will follow the xmpp specification using jid's domain.
* That is, it first do an SRV lookup (as specified in the xmpp RFC).
* If that fails, it will fall back to simply attempting to connect to the jid's domain.
**/
@property (readwrite, copy, nullable) NSString *hostName;
/**
* The port the xmpp server is running on.
* If you do not explicitly set the port, the default port will be used.
* If you set the port to zero, the default port will be used.
*
* The default port is 5222.
**/
@property (readwrite, assign) UInt16 hostPort;
/**
* The stream's policy on when to Start TLS.
*
* The default is XMPPStreamStartTLSPolicyAllowed.
*
* @see XMPPStreamStartTLSPolicy
**/
@property (readwrite, assign) XMPPStreamStartTLSPolicy startTLSPolicy;
/**
* The JID of the user.
*
* This value is required, and is used in many parts of the underlying implementation.
* When connecting, the domain of the JID is used to properly specify the correct xmpp virtual host.
* It is used during registration to supply the username of the user to create an account for.
* It is used during authentication to supply the username of the user to authenticate with.
* And the resource may be used post-authentication during the required xmpp resource binding step.
*
* A proper JID is of the form user@domain/resource.
* For example: robbiehanson@deusty.com/work
*
* The resource is optional, in the sense that if one is not supplied,
* one will be automatically generated for you (either by us or by the server).
*
* Please note:
* Resource collisions are handled in different ways depending on server configuration.
*
* For example:
* You are signed in with user1@domain.com/home on your desktop.
* Then you attempt to # with user1@domain.com/home on your laptop.
*
* The server could possibly:
* - Reject the resource request for the laptop.
* - Accept the resource request for the laptop, and immediately disconnect the desktop.
* - Automatically assign the laptop another resource without a conflict.
*
* For this reason, you may wish to check the myJID variable after the stream has been connected,
* just in case the resource was changed by the server.
**/
@property (readwrite, copy, nullable) XMPPJID *myJID;
/**
* Only used in P2P streams.
**/
@property (strong, readonly, nullable) XMPPJID *remoteJID;
/**
* Many routers will teardown a socket mapping if there is no activity on the socket.
* For this reason, the xmpp stream supports sending keep-alive data.
* This is simply whitespace, which is ignored by the xmpp protocol.
*
* Keep-alive data is only sent in the absence of any other data being sent/received.
*
* The default value is defined in DEFAULT_KEEPALIVE_INTERVAL.
* The minimum value is defined in MIN_KEEPALIVE_INTERVAL.
*
* To disable keep-alive, set the interval to zero (or any non-positive number).
*
* The keep-alive timer (if enabled) fires every (keepAliveInterval / 4) seconds.
* Upon firing it checks when data was last sent/received,
* and sends keep-alive data if the elapsed time has exceeded the keepAliveInterval.
* Thus the effective resolution of the keepalive timer is based on the interval.
*
* @see keepAliveWhitespaceCharacter
**/
@property (readwrite, assign) NSTimeInterval keepAliveInterval;
/**
* The keep-alive mechanism sends whitespace which is ignored by the xmpp protocol.
* The default whitespace character is a space (' ').
*
* This can be changed, for whatever reason, to another whitespace character.
* Valid whitespace characters are space(' '), tab('\t') and newline('\n').
*
* If you attempt to set the character to any non-whitespace character, the attempt is ignored.
*
* @see keepAliveInterval
**/
@property (readwrite, assign) char keepAliveWhitespaceCharacter;
/**
* Represents the last sent presence element concerning the presence of myJID on the server.
* In other words, it represents the presence as others see us.
*
* This excludes presence elements sent concerning subscriptions, MUC rooms, etc.
*
* @see resendMyPresence
**/
@property (strong, readonly, nullable) XMPPPresence *myPresence;
/**
* Returns the total number of bytes bytes sent/received by the xmpp stream.
*
* By default this is the byte count since the xmpp stream object has been created.
* If the stream has connected/disconnected/reconnected multiple times,
* the count will be the summation of all connections.
*
* The functionality may optionaly be changed to count only the current socket connection.
* @see resetByteCountPerConnection
**/
@property (readonly) uint64_t numberOfBytesSent;
@property (readonly) uint64_t numberOfBytesReceived;
/**
* Same as the individual properties,
* but provides a way to fetch them in one atomic operation.
**/
- (void)getNumberOfBytesSent:(uint64_t *)bytesSentPtr numberOfBytesReceived:(uint64_t *)bytesReceivedPtr;
/**
* Affects the funtionality of the byte counter.
*
* The default value is NO.
*
* If set to YES, the byte count will be reset just prior to a new connection (in the connect methods).
**/
@property (readwrite, assign) BOOL resetByteCountPerConnection;
/**
* The tag property allows you to associate user defined information with the stream.
* Tag values are not used internally, and should not be used by xmpp modules.
**/
@property (readwrite, strong, nullable) id tag;
/**
* RFC 6121 states that starting a session is no longer required.
* To skip this step set skipStartSession to YES.
*
* [RFC3921] specified one additional
* precondition: formal establishment of an instant messaging and
* presence session. Implementation and deployment experience has
* shown that this additional step is unnecessary. However, for
* backward compatibility an implementation MAY still offer that
* feature. This enables older software to connect while letting
* newer software save a round trip.
*
* The default value is NO.
**/
@property (readwrite, assign) BOOL skipStartSession;
/**
* Validates that a response element is FROM the jid that the request element was sent TO.
* Supports validating responses when request didn't specify a TO.
*
* @see isValidResponseElementFrom:forRequestElementTo:
* @see isValidResponseElement:forRequestElement:
*
* The default value is NO.
**/
@property (readwrite, assign) BOOL validatesResponses;
#if TARGET_OS_IPHONE
/**
* If set, the kCFStreamNetworkServiceTypeVoIP flags will be set on the underlying CFRead/Write streams.
*
* The default value is NO.
**/
@property (readwrite, assign) BOOL enableBackgroundingOnSocket DEPRECATED_MSG_ATTRIBUTE("Background sockets are no longer available on iOS 10. You must use PushKit and the XEP-0357 module instead.");
#endif
/**
* By default, IPv6 is now preferred over IPv4 to satisfy Apple's June 2016
* DNS64/NAT64 requirements for app approval. Disabling this option may cause
* issues during app approval.
*
* https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/UnderstandingandPreparingfortheIPv6Transition/UnderstandingandPreparingfortheIPv6Transition.html
*
* This new default may cause connectivity issues for misconfigured servers that have
* both A and AAAA DNS records but don't respond to IPv6. A proper solution to this
* is to fix your XMPP server and/or DNS entries. However, when Happy Eyeballs
* (RFC 6555) is implemented upstream in GCDAsyncSocket it should resolve the issue
* of misconfigured servers because it will try both the preferred protocol (IPv6) and
* and fallback protocol (IPv4) after a 300ms delay.
*
* Any changes to this option MUST be done before calling connect.
*
* The default value is YES.
**/
@property (assign, readwrite) BOOL preferIPv6;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark 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.
**/
@property (atomic, readonly) BOOL isDisconnected;
/**
* Returns YES is the connection is currently connecting
**/
@property (atomic, readonly) BOOL isConnecting;
/**
* 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.
*
* If this method returns YES, then it is ready for you to start sending and receiving elements.
**/
@property (atomic, readonly) BOOL isConnected;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connect & Disconnect
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Connects to the configured hostName on the configured hostPort.
* The timeout is optional. To not time out use XMPPStreamTimeoutNone.
* If the hostName or myJID are not set, this method will return NO and set the error parameter.
**/
- (BOOL)connectWithTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr;
/**
* THIS IS DEPRECATED BY THE XMPP SPECIFICATION.
*
* The xmpp specification outlines the proper use of SSL/TLS by negotiating
* the startTLS upgrade within the stream negotiation.
* This method exists for those ancient servers that still require the connection to be secured prematurely.
* The timeout is optional. To not time out use XMPPStreamTimeoutNone.
*
* Note: Such servers generally use port 5223 for this, which you will need to set.
**/
- (BOOL)oldSchoolSecureConnectWithTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr DEPRECATED_MSG_ATTRIBUTE("DO NOT USE. THIS IS DEPRECATED BY THE XMPP SPECIFICATION.");
/**
* Starts a P2P connection to the given user and given address.
* The timeout is optional. To not time out use XMPPStreamTimeoutNone.
* 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 *)remoteJID
withAddress:(NSData *)remoteAddr
withTimeout:(NSTimeInterval)timeout
error:(NSError **)errPtr;
/**
* 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;
/**
* Aborts any in-progress connection attempt. Has no effect if the stream is already connected or disconnected.
*
* Will dispatch the xmppStreamWasToldToAbortConnect: delegate method.
**/
- (void)abortConnecting;
/**
* Disconnects from the remote host by closing the underlying TCP socket connection.
* The terminating </stream:stream> element is not sent to the server.
*
* This method is synchronous.
* Meaning that the disconnect will happen immediately, even if there are pending elements yet to be sent.
*
* The xmppStreamDidDisconnect:withError: delegate method will immediately be dispatched onto the delegate queue.
**/
- (void)disconnect;
/**
* Disconnects from the remote host by sending the terminating </stream:stream> element,
* and then closing the underlying TCP socket connection.
*
* This method is asynchronous.
* The disconnect will happen after all pending elements have been sent.
* Attempting to send elements after this method has been called will not work (the elements won't get sent).
**/
- (void)disconnectAfterSending;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Security
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns YES if SSL/TLS was used to establish a connection to the server.
*
* Some servers may require an "upgrade to TLS" in order to start communication,
* so even if the connection was not explicitly secured, an ugrade to TLS may have occured.
*
* See also the xmppStream:willSecureWithSettings: delegate method.
**/
@property (atomic, readonly) BOOL isSecure;
/**
* Returns whether or not the server supports securing the connection via SSL/TLS.
*
* Some servers will actually require a secure connection,
* in which case the stream will attempt to secure the connection during the opening process.
*
* If the connection has already been secured, this method may return NO.
**/
@property (atomic, readonly) BOOL supportsStartTLS;
/**
* Attempts to secure the connection via SSL/TLS.
*
* This method is asynchronous.
* The SSL/TLS handshake will occur in the background, and
* the xmppStreamDidSecure: delegate method will be called after the TLS process has completed.
*
* This method returns immediately.
* If the secure process was started, it will return YES.
* If there was an issue while starting the security process,
* this method will return NO and set the error parameter.
*
* The errPtr parameter is optional - you may pass nil.
*
* You may wish to configure the security settings via the xmppStream:willSecureWithSettings: delegate method.
*
* If the SSL/TLS handshake fails, the connection will be closed.
* The reason for the error will be reported via the xmppStreamDidDisconnect:withError: delegate method.
* The error parameter will be an NSError object, and may have an error domain of kCFStreamErrorDomainSSL.
* The corresponding error code is documented in Apple's Security framework, in SecureTransport.h
**/
- (BOOL)secureConnection:(NSError **)errPtr;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Registration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* In Band Registration.
* Creating a user account on the xmpp server within the xmpp protocol.
*
* The registerWithElements:error: method is asynchronous.
* It will return immediately, and the delegate methods are used to determine success.
* See the xmppStreamDidRegister: and xmppStream:didNotRegister: methods.
*
* If there is something immediately wrong, such as the stream is not connected,
* this method will return NO and set the error.
*
* The errPtr parameter is optional - you may pass nil.
*
* registerWithPassword:error: is a convience method for creating an account using the given username and password.
*
* Security Note:
* The password will be sent in the clear unless the stream has been secured.
**/
@property (atomic, readonly) BOOL supportsInBandRegistration;
- (BOOL)registerWithElements:(NSArray<NSXMLElement*> *)elements error:(NSError **)errPtr;
- (BOOL)registerWithPassword:(NSString *)password error:(NSError **)errPtr;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Authentication
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns the server's list of supported authentication mechanisms.
* Each item in the array will be of type NSString.
*
* For example, if the server supplied this stanza within it's reported stream:features:
*
* <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
* <mechanism>DIGEST-MD5</mechanism>
* <mechanism>PLAIN</mechanism>
* </mechanisms>
*
* Then this method would return [@"DIGEST-MD5", @"PLAIN"].
**/
@property (atomic, readonly) NSArray<NSString*> *supportedAuthenticationMechanisms;
/**
* Returns whether or not the given authentication mechanism name was specified in the
* server's list of supported authentication mechanisms.
*
* Note: The authentication classes often provide a category on XMPPStream, adding useful methods.
*
* @see XMPPPlainAuthentication - supportsPlainAuthentication
* @see XMPPDigestMD5Authentication - supportsDigestMD5Authentication
* @see XMPPXFacebookPlatformAuthentication - supportsXFacebookPlatformAuthentication
* @see XMPPDeprecatedPlainAuthentication - supportsDeprecatedPlainAuthentication
* @see XMPPDeprecatedDigestAuthentication - supportsDeprecatedDigestAuthentication
**/
- (BOOL)supportsAuthenticationMechanism:(NSString *)mechanism;
/**
* This is the root authentication method.
* All other authentication methods go through this one.
*
* This method attempts to start the authentication process given the auth instance.
* That is, this method will invoke start: on the given auth instance.
* If it returns YES, then the stream will enter into authentication mode.
* It will then continually invoke the handleAuth: method on the given instance until authentication is complete.
*
* This method is asynchronous.
*
* If there is something immediately wrong, such as the stream is not connected,
* the method will return NO and set the error.
* Otherwise the delegate callbacks are used to communicate auth success or failure.
*
* @see xmppStreamDidAuthenticate:
* @see xmppStream:didNotAuthenticate:
*
* @see authenticateWithPassword:error:
*
* Note: The security process is abstracted in order to provide flexibility,
* and allow developers to easily implement their own custom authentication protocols.
* The authentication classes often provide a category on XMPPStream, adding useful methods.
*
* @see XMPPXFacebookPlatformAuthentication - authenticateWithFacebookAccessToken:error:
**/
- (BOOL)authenticate:(id <XMPPSASLAuthentication>)auth error:(NSError **)errPtr;
/**
* 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 *)password error:(NSError **)errPtr;
/**
* Returns whether or not the xmpp stream is currently authenticating with the XMPP Server.
**/
@property (atomic, readonly) BOOL isAuthenticating;
/**
* Returns whether or not the xmpp stream has successfully authenticated with the server.
**/
@property (atomic, readonly) BOOL isAuthenticated;
/**
* Returns the date when the xmpp stream successfully authenticated with the server.
**/
@property (atomic, readonly, nullable) NSDate *authenticationDate;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Compression
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns the server's list of supported compression methods in accordance to XEP-0138: Stream Compression
* Each item in the array will be of type NSString.
*
* For example, if the server supplied this stanza within it's reported stream:features:
*
* <compression xmlns='http://jabber.org/features/compress'>
* <method>zlib</method>
* <method>lzw</method>
* </compression>
*
* Then this method would return [@"zlib", @"lzw"].
**/
@property (atomic, readonly) NSArray<NSString*> *supportedCompressionMethods;
/**
* Returns whether or not the given compression method name was specified in the
* server's list of supported compression methods.
*
* Note: The XMPPStream doesn't currently support any compression methods
**/
- (BOOL)supportsCompressionMethod:(NSString *)compressionMethod;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Server Info
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 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.
*
* If multiple <stream:features/> have been received during the course of stream negotiation,
* the root element contains only the most recent (current) version.
*
* Note: The rootElement is "empty", in-so-far as it 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.
**/
@property (atomic, readonly, nullable) NSXMLElement *rootElement;
/**
* 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;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Sending
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Sends the given XML element.
* If the stream is not yet connected, this method does nothing.
**/
- (void)sendElement:(NSXMLElement *)element;
/**
* Just like the sendElement: method above,
* but allows you to receive a receipt that can later be used to verify the element has been sent.
*
* If you later want to check to see if the element has been sent:
*
* if ([receipt wait:0]) {
* // Element has been sent
* }
*
* If you later want to wait until the element has been sent:
*
* if ([receipt wait:-1]) {
* // Element was sent
* } else {
* // Element failed to send due to disconnection
* }
*
* It is important to understand what it means when [receipt wait:timeout] returns YES.
* It does NOT mean the server has received the element.
* It only means the data has been queued for sending in the underlying OS socket buffer.
*
* So at this point the OS will do everything in its capacity to send the data to the server,
* which generally means the server will eventually receive the data.
* Unless, of course, something horrible happens such as a network failure,
* or a system crash, or the server crashes, etc.
*
* Even if you close the xmpp stream after this point, the OS will still do everything it can to send the data.
**/
- (void)sendElement:(NSXMLElement *)element andGetReceipt:(XMPPElementReceipt * _Nullable * _Nullable)receiptPtr;
/**
* Fetches and resends the myPresence element (if available) in a single atomic operation.
*
* There are various xmpp extensions that hook into the xmpp stream and append information to outgoing presence stanzas.
* For example, the XMPPCapabilities module automatically appends capabilities information (as a hash).
* When these modules need to update/change their appended information,
* they should use this method to do so.
*
* The alternative is to fetch the myPresence element, and resend it manually using the sendElement method.
* However, that is 2 seperate operations, and the user, may send a different presence element inbetween.
* Using this method guarantees everything is done as an atomic operation.
**/
- (void)resendMyPresence;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Stanza Validation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Validates that a response element is FROM the jid that the request element was sent TO.
* Supports validating responses when request didn't specify a TO.
**/
- (BOOL)isValidResponseElementFrom:(XMPPJID *)from forRequestElementTo:(XMPPJID *)to;
- (BOOL)isValidResponseElement:(XMPPElement *)response forRequestElement:(XMPPElement *)request;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Module Plug-In System
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The XMPPModule class automatically invokes these methods when it is activated/deactivated.
*
* The registerModule method registers the module with the xmppStream.
* If there are any other modules that have requested to be automatically added as delegates to modules of this type,
* then those modules are automatically added as delegates during the asynchronous execution of this method.
*
* The registerModule method is asynchronous.
*
* The unregisterModule method unregisters the module with the xmppStream,
* and automatically removes it as a delegate of any other module.
*
* The unregisterModule method is fully synchronous.
* That is, after this method returns, the module will not be scheduled in any more delegate calls from other modules.
* However, if the module was already scheduled in an existing asynchronous delegate call from another module,
* the scheduled delegate invocation remains queued and will fire in the near future.
* Since the delegate invocation is already queued,
* the module's retainCount has been incremented,
* and the module will not be deallocated until after the delegate invocation has fired.
**/
- (void)registerModule:(XMPPModule *)module;
- (void)unregisterModule:(XMPPModule *)module;
/**
* Automatically registers the given delegate with all current and future registered modules of the given class.
*
* That is, the given delegate will be added to the delegate list ([module addDelegate:delegate delegateQueue:dq]) to
* all current and future registered modules that respond YES to [module isKindOfClass:aClass].
*
* This method is used by modules to automatically integrate with other modules.
* For example, a module may auto-add itself as a delegate to XMPPCapabilities
* so that it can broadcast its implemented features.
*
* This may also be useful to clients, for example, to add a delegate to instances of something like XMPPChatRoom,
* where there may be multiple instances of the module that get created during the course of an xmpp session.
*
* If you auto register on multiple queues, you can remove all registrations with a single
* call to removeAutoDelegate::: by passing NULL as the 'dq' parameter.
*
* If you auto register for multiple classes, you can remove all registrations with a single
* call to removeAutoDelegate::: by passing nil as the 'aClass' parameter.
**/
- (void)autoAddDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue toModulesOfClass:(Class)aClass;
- (void)removeAutoDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue fromModulesOfClass:(Class)aClass;
/**
* Allows for enumeration of the currently registered modules.
*
* This may be useful if the stream needs to be queried for modules of a particular type.
**/
- (void)enumerateModulesWithBlock:(void (^)(XMPPModule *module, NSUInteger idx, BOOL *stop))block;
/**
* Allows for enumeration of the currently registered modules that are a kind of Class.
* idx is in relation to all modules not just those of the given class.
**/
- (void)enumerateModulesOfClass:(Class)aClass withBlock:(void (^)(XMPPModule *module, NSUInteger idx, BOOL *stop))block;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Utilities
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Generates and returns a new autoreleased UUID.
* UUIDs (Universally Unique Identifiers) may also be known as GUIDs (Globally Unique Identifiers).
*
* The UUID is generated using the CFUUID library, which generates a unique 128 bit value.
* The uuid is then translated into a string using the standard format for UUIDs:
* "68753A44-4D6F-1226-9C60-0050E4C00067"
*
* This method is most commonly used to generate a unique id value for an xmpp element.
**/
@property (nonatomic, readonly) NSString *generateUUID;
@property (nonatomic, class, readonly) NSString *generateUUID;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface XMPPElementReceipt : NSObject
{
uint32_t atomicFlags;
dispatch_semaphore_t semaphore;
}
/**
* Element receipts allow you to check to see if the element has been sent.
* The timeout parameter allows you to do any of the following:
*
* - Do an instantaneous check (pass timeout == 0)
* - Wait until the element has been sent (pass timeout < 0)
* - Wait up to a certain amount of time (pass timeout > 0)
*
* It is important to understand what it means when [receipt wait:timeout] returns YES.
* It does NOT mean the server has received the element.
* It only means the data has been queued for sending in the underlying OS socket buffer.
*
* So at this point the OS will do everything in its capacity to send the data to the server,
* which generally means the server will eventually receive the data.
* Unless, of course, something horrible happens such as a network failure,
* or a system crash, or the server crashes, etc.
*
* Even if you close the xmpp stream after this point, the OS will still do everything it can to send the data.
**/
- (BOOL)wait:(NSTimeInterval)timeout;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@protocol XMPPStreamDelegate
@optional
/**
* This method is called before the stream begins the connection process.
*
* If developing an iOS app that runs in the background, this may be a good place to indicate
* that this is a task that needs to continue running in the background.
**/
- (void)xmppStreamWillConnect:(XMPPStream *)sender;
/**
* This method is called after the tcp socket has connected to the remote host.
* It may be used as a hook for various things, such as updating the UI or extracting the server's IP address.
*
* If developing an iOS app that runs in the background,
* please use XMPPStream's enableBackgroundingOnSocket property as opposed to doing it directly on the socket here.
**/
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket;
/**
* This method is called after a TCP connection has been established with the server,
* and the opening XML stream negotiation has started.
**/
- (void)xmppStreamDidStartNegotiation:(XMPPStream *)sender;
/**
* This method is called immediately prior to the stream being secured via TLS/SSL.
* Note that this delegate may be called even if you do not explicitly invoke the startTLS method.
* Servers have the option of requiring connections to be secured during the opening process.
* If this is the case, the XMPPStream will automatically attempt to properly secure the connection.
*
* The dictionary of settings is what will be passed to the startTLS method of the underlying GCDAsyncSocket.
* The GCDAsyncSocket header file contains a discussion of the available key/value pairs,
* as well as the security consequences of various options.
* It is recommended reading if you are planning on implementing this method.
*
* The dictionary of settings that are initially passed will be an empty dictionary.
* If you choose not to implement this method, or simply do not edit the dictionary,
* then the default settings will be used.
* That is, the kCFStreamSSLPeerName will be set to the configured host name,
* and the default security validation checks will be performed.
*
* This means that authentication will fail if the name on the X509 certificate of
* the server does not match the value of the hostname for the xmpp stream.
* It will also fail if the certificate is self-signed, or if it is expired, etc.
*
* These settings are most likely the right fit for most production environments,
* but may need to be tweaked for development or testing,
* where the development server may be using a self-signed certificate.
*
* Note: If your development server is using a self-signed certificate,
* you likely need to add GCDAsyncSocketManuallyEvaluateTrust=YES to the settings.
* Then implement the xmppStream:didReceiveTrust:completionHandler: delegate method to perform custom validation.
**/
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary<NSString*,NSObject*>*)settings;
/**
* Allows a delegate to hook into the TLS handshake and manually validate the peer it's connecting to.
*
* This is only called if the stream is secured with settings that include:
* - GCDAsyncSocketManuallyEvaluateTrust == YES
* That is, if a delegate implements xmppStream:willSecureWithSettings:, and plugs in that key/value pair.
*
* Thus this delegate method is forwarding the TLS evaluation callback from the underlying GCDAsyncSocket.
*
* Typically the delegate will use SecTrustEvaluate (and related functions) to properly validate the peer.
*
* Note from Apple's documentation:
* Because [SecTrustEvaluate] might look on the network for certificates in the certificate chain,
* [it] might block while attempting network access. You should never call it from your main thread;
* call it only from within a function running on a dispatch queue or on a separate thread.
*
* This is why this method uses a completionHandler block rather than a normal return value.
* The idea is that you should be performing SecTrustEvaluate on a background thread.
* The completionHandler block is thread-safe, and may be invoked from a background queue/thread.
* It is safe to invoke the completionHandler block even if the socket has been closed.
*
* Keep in mind that you can do all kinds of cool stuff here.
* For example:
*
* If your development server is using a self-signed certificate,
* then you could embed info about the self-signed cert within your app, and use this callback to ensure that
* you're actually connecting to the expected dev server.
*
* Also, you could present certificates that don't pass SecTrustEvaluate to the client.
* That is, if SecTrustEvaluate comes back with problems, you could invoke the completionHandler with NO,
* and then ask the client if the cert can be trusted. This is similar to how most browsers act.
*
* Generally, only one delegate should implement this method.
* However, if multiple delegates implement this method, then the first to invoke the completionHandler "wins".
* And subsequent invocations of the completionHandler are ignored.
**/
- (void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust
completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler;
/**
* This method is called after the stream has been secured via SSL/TLS.
* This method may be called if the server required a secure connection during the opening process,
* or if the secureConnection: method was manually invoked.
**/
- (void)xmppStreamDidSecure:(XMPPStream *)sender;
/**
* This method is called after the XML stream has been fully opened.
* More precisely, this method is called after an opening <xml/> and <stream:stream/> tag have been sent and received,
* and after the stream features have been received, and any required features have been fullfilled.
* At this point it's safe to begin communication with the server.
**/
- (void)xmppStreamDidConnect:(XMPPStream *)sender;
/**
* This method is called after registration of a new user has successfully finished.
* If registration fails for some reason, the xmppStream:didNotRegister: method will be called instead.
**/
- (void)xmppStreamDidRegister:(XMPPStream *)sender;
/**
* This method is called if registration fails.
**/
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error;
/**
* This method is called after authentication has successfully finished.
* If authentication fails for some reason, the xmppStream:didNotAuthenticate: method will be called instead.
**/
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender;
/**
* This method is called if authentication fails.
**/
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error;
/**
* Binding a JID resource is a standard part of the authentication process,
* and occurs after SASL authentication completes (which generally authenticates the JID username).
*
* This delegate method allows for a custom binding procedure to be used.
* For example:
* - a custom SASL authentication scheme might combine auth with binding
* - stream management (xep-0198) replaces binding if it can resume a previous session
*
* Return nil (or don't implement this method) if you wish to use the standard binding procedure.
**/
- (nullable id <XMPPCustomBinding>)xmppStreamWillBind:(XMPPStream *)sender;
/**
* This method is called if the XMPP server doesn't allow our resource of choice
* because it conflicts with an existing resource.
*
* Return an alternative resource or return nil to let the server automatically pick a resource for us.
**/
- (nullable NSString *)xmppStream:(XMPPStream *)sender alternativeResourceForConflictingResource:(NSString *)conflictingResource;
/**
* These methods are called before their respective XML elements are broadcast as received to the rest of the stack.
* These methods can be used to modify elements on the fly.
* (E.g. perform custom decryption so the rest of the stack sees readable text.)
*
* You may also filter incoming elements by returning nil.
*
* When implementing these methods to modify the element, you do not need to copy the given element.
* You can simply edit the given element, and return it.
* The reason these methods return an element, instead of void, is to allow filtering.
*
* Concerning thread-safety, delegates implementing the method are invoked one-at-a-time to
* allow thread-safe modification of the given elements.
*
* You should NOT implement these methods unless you have good reason to do so.
* For general processing and notification of received elements, please use xmppStream:didReceiveX: methods.
*
* @see xmppStream:didReceiveIQ:
* @see xmppStream:didReceiveMessage:
* @see xmppStream:didReceivePresence:
**/
- (nullable XMPPIQ *)xmppStream:(XMPPStream *)sender willReceiveIQ:(XMPPIQ *)iq;
- (nullable XMPPMessage *)xmppStream:(XMPPStream *)sender willReceiveMessage:(XMPPMessage *)message;
- (nullable XMPPPresence *)xmppStream:(XMPPStream *)sender willReceivePresence:(XMPPPresence *)presence;
/**
* This method is called if any of the xmppStream:willReceiveX: methods filter the incoming stanza.
*
* It may be useful for some extensions to know that something was received,
* even if it was filtered for some reason.
**/
- (void)xmppStreamDidFilterStanza:(XMPPStream *)sender;
/**
* These methods are called after their respective XML elements are received on the stream.
*
* In the case of an IQ, the delegate method should return YES if it has or will respond to the given IQ.
* If the IQ is of type 'get' or 'set', and no delegates respond to the IQ,
* then xmpp stream will automatically send an error response.
*
* Concerning thread-safety, delegates shouldn't modify the given elements.
* As documented in NSXML / KissXML, elements are read-access thread-safe, but write-access thread-unsafe.
* If you have need to modify an element for any reason,
* you should copy the element first, and then modify and use the copy.
**/
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq;
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message;
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence;
/**
* This method is called if an XMPP error is received.
* In other words, a <stream:error/>.
*
* However, this method may also be called for any unrecognized xml stanzas.
*