ObjXMPP  Diff

Differences From Artifact [9754b2ecb4]:

To Artifact [b5eb472034]:


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
#import "XMPPXMLElementBuilder.h"
#import "namespaces.h"

#import <ObjFW/macros.h>

#define BUFFER_LENGTH 512

OF_ASSUME_NONNULL_BEGIN

@interface XMPPConnection ()

















- (void)XMPP_startStream;

- (void)XMPP_handleStream: (OFXMLElement *)element;
- (void)XMPP_handleTLS: (OFXMLElement *)element;
- (void)XMPP_handleSASL: (OFXMLElement *)element;



- (void)XMPP_handleStanza: (OFXMLElement *)element;
- (void)XMPP_sendAuth: (OFString *)authName;
- (void)XMPP_sendResourceBind;
- (void)XMPP_sendStreamError: (OFString *)condition
			text: (nullable OFString *)text;
- (void)XMPP_handleIQ: (XMPPIQ *)IQ;
- (void)XMPP_handleMessage: (XMPPMessage *)message;
- (void)XMPP_handlePresence: (XMPPPresence *)presence;
- (void)XMPP_handleFeatures: (OFXMLElement *)element;
- (void)XMPP_handleResourceBindForConnection: (XMPPConnection *)connection
					  IQ: (XMPPIQ *)IQ;
- (void)XMPP_sendSession;
- (void)XMPP_handleSessionForConnection: (XMPPConnection *)connection
				     IQ: (XMPPIQ *)IQ;
- (OFString *)XMPP_IDNAToASCII: (OFString *)domain;
- (XMPPMulticastDelegate *)XMPP_delegates;
@end

OF_ASSUME_NONNULL_END

@implementation XMPPConnection
@synthesize username = _username, resource = _resource, server = _server;
@synthesize domain = _domain, password = _password, language = _language;
@synthesize privateKeyFile = _privateKeyFile;
@synthesize certificateFile = _certificateFile, socket = _socket;
@synthesize encryptionRequired = _encryptionRequired, encrypted = _encrypted;
@synthesize supportsRosterVersioning = _supportsRosterVersioning;
@synthesize supportsStreamManagement = _supportsStreamManagement;

+ (instancetype)connection
{
	return [[[self alloc] init] autorelease];
}

- init
{
	self = [super init];

	@try {
		_port = 5222;
		_delegates = [[XMPPMulticastDelegate alloc] init];
		_callbacks = [[OFMutableDictionary alloc] init];







<
<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
|
|
>
>
>
|
|
|
|
|
<
<
<
<
|

|
|

|
|

<
<















|







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
#import "XMPPXMLElementBuilder.h"
#import "namespaces.h"

#import <ObjFW/macros.h>

#define BUFFER_LENGTH 512



@interface XMPPConnection ()
- (void)xmpp_socketDidConnect: (OFTCPSocket *)socket
		      context: (OFArray *)nextSRVRecords
		    exception: (id)exception;
- (void)xmpp_tryNextSRVRecord: (OFArray *)SRVRecords;
-  (void)xmpp_resolver: (OFDNSResolver *)resolver
  didResolveDomainName: (OFString *)domainName
	 answerRecords: (OFDictionary *)answerRecords
      authorityRecords: (OFDictionary *)authorityRecords
     additionalRecords: (OFDictionary *)additionalRecords
	       context: (OFString *)domainToASCII
	     exception: (id)exception;
-  (bool)xmpp_parseBuffer: (const void *)buffer
		   length: (size_t)length;
- (bool)xmpp_stream: (OFStream *)stream
  didReadIntoBuffer: (char *)buffer
	     length: (size_t)length
	  exception: (OFException *)exception;
- (void)xmpp_startStream;
- (void)xmpp_handleStanza: (OFXMLElement *)element;
- (void)xmpp_handleStream: (OFXMLElement *)element;
- (void)xmpp_handleTLS: (OFXMLElement *)element;
- (void)xmpp_handleSASL: (OFXMLElement *)element;
- (void)xmpp_handleIQ: (XMPPIQ *)IQ;
- (void)xmpp_handleMessage: (XMPPMessage *)message;
- (void)xmpp_handlePresence: (XMPPPresence *)presence;
- (void)xmpp_handleFeatures: (OFXMLElement *)element;
- (void)xmpp_sendAuth: (OFString *)authName;
- (void)xmpp_sendResourceBind;
- (void)xmpp_sendStreamError: (OFString *)condition
			text: (OFString *)text;




- (void)xmpp_handleResourceBindForConnection: (XMPPConnection *)connection
					  IQ: (XMPPIQ *)IQ;
- (void)xmpp_sendSession;
- (void)xmpp_handleSessionForConnection: (XMPPConnection *)connection
				     IQ: (XMPPIQ *)IQ;
- (OFString *)xmpp_IDNAToASCII: (OFString *)domain;
- (XMPPMulticastDelegate *)xmpp_delegates;
@end



@implementation XMPPConnection
@synthesize username = _username, resource = _resource, server = _server;
@synthesize domain = _domain, password = _password, language = _language;
@synthesize privateKeyFile = _privateKeyFile;
@synthesize certificateFile = _certificateFile, socket = _socket;
@synthesize encryptionRequired = _encryptionRequired, encrypted = _encrypted;
@synthesize supportsRosterVersioning = _supportsRosterVersioning;
@synthesize supportsStreamManagement = _supportsStreamManagement;

+ (instancetype)connection
{
	return [[[self alloc] init] autorelease];
}

- (instancetype)init
{
	self = [super init];

	@try {
		_port = 5222;
		_delegates = [[XMPPMulticastDelegate alloc] init];
		_callbacks = [[OFMutableDictionary alloc] init];
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
}

- (void)setServer: (OFString *)server
{
	OFString *old = _server;

	if (server != nil)
		_server = [self XMPP_IDNAToASCII: server];
	else
		_server = nil;

	[old release];
}

- (void)setDomain: (OFString *)domain







|







201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
}

- (void)setServer: (OFString *)server
{
	OFString *old = _server;

	if (server != nil)
		_server = [self xmpp_IDNAToASCII: server];
	else
		_server = nil;

	[old release];
}

- (void)setDomain: (OFString *)domain
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

		@try {
			_domain = [[OFString alloc] initWithUTF8String: srv];
		} @finally {
			free(srv);
		}

		_domainToASCII = [self XMPP_IDNAToASCII: _domain];
	} else {
		_domain = nil;
		_domainToASCII = nil;
	}

	[oldDomain release];
	[oldDomainToASCII release];







|







230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

		@try {
			_domain = [[OFString alloc] initWithUTF8String: srv];
		} @finally {
			free(srv);
		}

		_domainToASCII = [self xmpp_IDNAToASCII: _domain];
	} else {
		_domain = nil;
		_domainToASCII = nil;
	}

	[oldDomain release];
	[oldDomainToASCII release];
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
		}
	} else
		_password = nil;

	[old release];
}

- (void)XMPP_socketDidConnect: (OFTCPSocket *)socket
		      context: (OFArray *)nextSRVRecords
		    exception: (id)exception
{
	char *buffer;

	if (exception != nil) {
		if (nextSRVRecords != nil) {
			[self XMPP_tryNextSRVRecord: nextSRVRecords];
			return;
		}

		[_delegates
		    broadcastSelector: @selector(connection:didThrowException:)
			   withObject: self
			   withObject: exception];
		return;
	}

	[self XMPP_startStream];

	buffer = [self allocMemoryWithSize: BUFFER_LENGTH];
	[_socket asyncReadIntoBuffer: buffer
			      length: BUFFER_LENGTH
			      target: self
			    selector: @selector(XMPP_stream:didReadIntoBuffer:
					  length:exception:)
			     context: nil];
}

- (void)XMPP_tryNextSRVRecord: (OFArray *)SRVRecords
{
	OFSRVDNSResourceRecord *record = [SRVRecords objectAtIndex: 0];

	SRVRecords = [SRVRecords objectsInRange:
	    of_range(1, [SRVRecords count] - 1)];
	if ([SRVRecords count] == 0)
		SRVRecords = nil;

	[_socket asyncConnectToHost: [record target]
			       port: [record port]
			     target: self
			   selector: @selector(XMPP_socketDidConnect:
					 context:exception:)
			    context: SRVRecords];
}

-  (void)XMPP_resolver: (OFDNSResolver *)resolver
  didResolveDomainName: (OFString *)domainName
	 answerRecords: (OFDictionary *)answerRecords
      authorityRecords: (OFDictionary *)authorityRecords
     additionalRecords: (OFDictionary *)additionalRecords
	       context: (OFString *)domainToASCII
	     exception: (id)exception
{







|







|










|





|




|











|




|







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
		}
	} else
		_password = nil;

	[old release];
}

- (void)xmpp_socketDidConnect: (OFTCPSocket *)socket
		      context: (OFArray *)nextSRVRecords
		    exception: (id)exception
{
	char *buffer;

	if (exception != nil) {
		if (nextSRVRecords != nil) {
			[self xmpp_tryNextSRVRecord: nextSRVRecords];
			return;
		}

		[_delegates
		    broadcastSelector: @selector(connection:didThrowException:)
			   withObject: self
			   withObject: exception];
		return;
	}

	[self xmpp_startStream];

	buffer = [self allocMemoryWithSize: BUFFER_LENGTH];
	[_socket asyncReadIntoBuffer: buffer
			      length: BUFFER_LENGTH
			      target: self
			    selector: @selector(xmpp_stream:didReadIntoBuffer:
					  length:exception:)
			     context: nil];
}

- (void)xmpp_tryNextSRVRecord: (OFArray *)SRVRecords
{
	OFSRVDNSResourceRecord *record = [SRVRecords objectAtIndex: 0];

	SRVRecords = [SRVRecords objectsInRange:
	    of_range(1, [SRVRecords count] - 1)];
	if ([SRVRecords count] == 0)
		SRVRecords = nil;

	[_socket asyncConnectToHost: [record target]
			       port: [record port]
			     target: self
			   selector: @selector(xmpp_socketDidConnect:
					 context:exception:)
			    context: SRVRecords];
}

-  (void)xmpp_resolver: (OFDNSResolver *)resolver
  didResolveDomainName: (OFString *)domainName
	 answerRecords: (OFDictionary *)answerRecords
      authorityRecords: (OFDictionary *)authorityRecords
     additionalRecords: (OFDictionary *)additionalRecords
	       context: (OFString *)domainToASCII
	     exception: (id)exception
{
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
	[records makeImmutable];

	if ([records count] == 0) {
		/* Fall back to A / AAA record. */
		[_socket asyncConnectToHost: domainToASCII
				       port: _port
				     target: self
				   selector: @selector(XMPP_socketDidConnect:
						 context:exception:)
				    context: nil];
		return;
	}

	[self XMPP_tryNextSRVRecord: records];
}

- (void)asyncConnect
{
	void *pool = objc_autoreleasePoolPush();

	if (_socket != nil)
		@throw [OFAlreadyConnectedException exception];

	_socket = [[OFTCPSocket alloc] init];

	if (_server != nil)
		[_socket asyncConnectToHost: _server
				       port: _port
				     target: self
				   selector: @selector(XMPP_socketDidConnect:
						 context:exception:)
				    context: nil];
	else
		[[OFThread DNSResolver]
		    asyncResolveHost: _domainToASCII
			      target: self
			    selector: @selector(XMPP_resolver:
					  didResolveDomainName:answerRecords:
					  authorityRecords:additionalRecords:
					  context:exception:)
			     context: _domainToASCII];

	objc_autoreleasePoolPop(pool);
}

-  (bool)XMPP_parseBuffer: (const void *)buffer
		   length: (size_t)length
{
	if ([_socket isAtEndOfStream]) {
		[_delegates broadcastSelector: @selector(connectionWasClosed:)
				   withObject: self];
		return false;
	}

	@try {
		[_parser parseBuffer: buffer
			     length: length];
	} @catch (OFMalformedXMLException *e) {
		[self XMPP_sendStreamError: @"bad-format"
				      text: nil];
		[self close];
		return false;
	}

	return true;
}

- (void)parseBuffer: (const void *)buffer
	     length: (size_t)length
{
	[self XMPP_parseBuffer: buffer
			length: length];

	[_oldParser release];
	[_oldElementBuilder release];

	_oldParser = nil;
	_oldElementBuilder = nil;
}

- (bool)XMPP_stream: (OFStream *)stream
  didReadIntoBuffer: (char *)buffer
	     length: (size_t)length
	  exception: (OFException *)exception
{
	if (exception != nil) {
		[_delegates broadcastSelector: @selector(connection:
						   didThrowException:)
				   withObject: self
				   withObject: exception];
		[self close];
		return false;
	}

	@try {
		if (![self XMPP_parseBuffer: buffer
				     length: length])
			return false;
	} @catch (id e) {
		[_delegates broadcastSelector: @selector(connection:
						   didThrowException:)
				   withObject: self
				   withObject: e];







|





|















|






|








|












|











|









|














|







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
	[records makeImmutable];

	if ([records count] == 0) {
		/* Fall back to A / AAA record. */
		[_socket asyncConnectToHost: domainToASCII
				       port: _port
				     target: self
				   selector: @selector(xmpp_socketDidConnect:
						 context:exception:)
				    context: nil];
		return;
	}

	[self xmpp_tryNextSRVRecord: records];
}

- (void)asyncConnect
{
	void *pool = objc_autoreleasePoolPush();

	if (_socket != nil)
		@throw [OFAlreadyConnectedException exception];

	_socket = [[OFTCPSocket alloc] init];

	if (_server != nil)
		[_socket asyncConnectToHost: _server
				       port: _port
				     target: self
				   selector: @selector(xmpp_socketDidConnect:
						 context:exception:)
				    context: nil];
	else
		[[OFThread DNSResolver]
		    asyncResolveHost: _domainToASCII
			      target: self
			    selector: @selector(xmpp_resolver:
					  didResolveDomainName:answerRecords:
					  authorityRecords:additionalRecords:
					  context:exception:)
			     context: _domainToASCII];

	objc_autoreleasePoolPop(pool);
}

-  (bool)xmpp_parseBuffer: (const void *)buffer
		   length: (size_t)length
{
	if ([_socket isAtEndOfStream]) {
		[_delegates broadcastSelector: @selector(connectionWasClosed:)
				   withObject: self];
		return false;
	}

	@try {
		[_parser parseBuffer: buffer
			     length: length];
	} @catch (OFMalformedXMLException *e) {
		[self xmpp_sendStreamError: @"bad-format"
				      text: nil];
		[self close];
		return false;
	}

	return true;
}

- (void)parseBuffer: (const void *)buffer
	     length: (size_t)length
{
	[self xmpp_parseBuffer: buffer
			length: length];

	[_oldParser release];
	[_oldElementBuilder release];

	_oldParser = nil;
	_oldElementBuilder = nil;
}

- (bool)xmpp_stream: (OFStream *)stream
  didReadIntoBuffer: (char *)buffer
	     length: (size_t)length
	  exception: (OFException *)exception
{
	if (exception != nil) {
		[_delegates broadcastSelector: @selector(connection:
						   didThrowException:)
				   withObject: self
				   withObject: exception];
		[self close];
		return false;
	}

	@try {
		if (![self xmpp_parseBuffer: buffer
				     length: length])
			return false;
	} @catch (id e) {
		[_delegates broadcastSelector: @selector(connection:
						   didThrowException:)
				   withObject: self
				   withObject: e];
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455

		_oldParser = nil;
		_oldElementBuilder = nil;

		[_socket asyncReadIntoBuffer: buffer
				      length: BUFFER_LENGTH
				      target: self
				    selector: @selector(XMPP_stream:
						  didReadIntoBuffer:length:
						  exception:)
				     context: nil];

		return false;
	}








|







454
455
456
457
458
459
460
461
462
463
464
465
466
467
468

		_oldParser = nil;
		_oldElementBuilder = nil;

		[_socket asyncReadIntoBuffer: buffer
				      length: BUFFER_LENGTH
				      target: self
				    selector: @selector(xmpp_stream:
						  didReadIntoBuffer:length:
						  exception:)
				     context: nil];

		return false;
	}

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
		// No dedicated stream error for this, may not even be XMPP
		[self close];
		[_socket close];
		return;
	}

	if (![prefix isEqual: @"stream"]) {
		[self XMPP_sendStreamError: @"bad-namespace-prefix"
				      text: nil];
		return;
	}

	if (![NS isEqual: XMPP_NS_STREAM]) {
		[self XMPP_sendStreamError: @"invalid-namespace"
				      text: nil];
		return;
	}

	for (OFXMLAttribute *attribute in attributes) {
		if ([[attribute name] isEqual: @"from"] &&
		    ![[attribute stringValue] isEqual: _domain]) {
			[self XMPP_sendStreamError: @"invalid-from"
					      text: nil];
			return;
		}
		if ([[attribute name] isEqual: @"version"] &&
		    ![[attribute stringValue] isEqual: @"1.0"]) {
			[self XMPP_sendStreamError: @"unsupported-version"
					      text: nil];
			return;
		}
	}

	[parser setDelegate: _elementBuilder];
}







|





|







|





|







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
		// No dedicated stream error for this, may not even be XMPP
		[self close];
		[_socket close];
		return;
	}

	if (![prefix isEqual: @"stream"]) {
		[self xmpp_sendStreamError: @"bad-namespace-prefix"
				      text: nil];
		return;
	}

	if (![NS isEqual: XMPP_NS_STREAM]) {
		[self xmpp_sendStreamError: @"invalid-namespace"
				      text: nil];
		return;
	}

	for (OFXMLAttribute *attribute in attributes) {
		if ([[attribute name] isEqual: @"from"] &&
		    ![[attribute stringValue] isEqual: _domain]) {
			[self xmpp_sendStreamError: @"invalid-from"
					      text: nil];
			return;
		}
		if ([[attribute name] isEqual: @"version"] &&
		    ![[attribute stringValue] isEqual: @"1.0"]) {
			[self xmpp_sendStreamError: @"unsupported-version"
					      text: nil];
			return;
		}
	}

	[parser setDelegate: _elementBuilder];
}
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
	      forNamespace: XMPP_NS_STREAM];

	[_delegates broadcastSelector: @selector(connection:didReceiveElement:)
			   withObject: self
			   withObject: element];

	if ([[element namespace] isEqual: XMPP_NS_CLIENT])
		[self XMPP_handleStanza: element];

	if ([[element namespace] isEqual: XMPP_NS_STREAM])
		[self XMPP_handleStream: element];

	if ([[element namespace] isEqual: XMPP_NS_STARTTLS])
		[self XMPP_handleTLS: element];

	if ([[element namespace] isEqual: XMPP_NS_SASL])
		[self XMPP_handleSASL: element];
}

- (void)elementBuilder: (OFXMLElementBuilder *)builder
  didNotExpectCloseTag: (OFString *)name
		prefix: (OFString *)prefix
	     namespace: (OFString *)ns
{
	if (![name isEqual: @"stream"] || ![prefix isEqual: @"stream"] ||
	    ![ns isEqual: XMPP_NS_STREAM])
		@throw [OFMalformedXMLException exception];
	else {
		[self close];
	}
}

- (void)XMPP_startStream
{
	OFString *langString = @"";

	/* Make sure we don't get any old events */
	[_parser setDelegate: nil];
	[_elementBuilder setDelegate: nil];








|


|


|


|















|







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
	      forNamespace: XMPP_NS_STREAM];

	[_delegates broadcastSelector: @selector(connection:didReceiveElement:)
			   withObject: self
			   withObject: element];

	if ([[element namespace] isEqual: XMPP_NS_CLIENT])
		[self xmpp_handleStanza: element];

	if ([[element namespace] isEqual: XMPP_NS_STREAM])
		[self xmpp_handleStream: element];

	if ([[element namespace] isEqual: XMPP_NS_STARTTLS])
		[self xmpp_handleTLS: element];

	if ([[element namespace] isEqual: XMPP_NS_SASL])
		[self xmpp_handleSASL: element];
}

- (void)elementBuilder: (OFXMLElementBuilder *)builder
  didNotExpectCloseTag: (OFString *)name
		prefix: (OFString *)prefix
	     namespace: (OFString *)ns
{
	if (![name isEqual: @"stream"] || ![prefix isEqual: @"stream"] ||
	    ![ns isEqual: XMPP_NS_STREAM])
		@throw [OFMalformedXMLException exception];
	else {
		[self close];
	}
}

- (void)xmpp_startStream
{
	OFString *langString = @"";

	/* Make sure we don't get any old events */
	[_parser setDelegate: nil];
	[_elementBuilder setDelegate: nil];

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
	[_JID release];
	_JID = nil;
	_streamOpen = _needsSession = _encrypted = false;
	_supportsRosterVersioning = _supportsStreamManagement = false;
	_lastID = 0;
}

- (void)XMPP_handleStanza: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"iq"]) {
		[self XMPP_handleIQ: [XMPPIQ stanzaWithElement: element]];
		return;
	}

	if ([[element name] isEqual: @"message"]) {
		[self XMPP_handleMessage:
		    [XMPPMessage stanzaWithElement: element]];
		return;
	}

	if ([[element name] isEqual: @"presence"]) {
		[self XMPP_handlePresence:
		    [XMPPPresence stanzaWithElement: element]];
		return;
	}

	[self XMPP_sendStreamError: @"unsupported-stanza-type"
			      text: nil];
}


- (void)XMPP_handleStream: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"features"]) {
		[self XMPP_handleFeatures: element];
		return;
	}

	if ([[element name] isEqual: @"error"]) {
		OFString *condition, *reason;
		[self close];
		[_socket close]; // Remote has already closed his stream







|


|




|





|




|




|


|







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
	[_JID release];
	_JID = nil;
	_streamOpen = _needsSession = _encrypted = false;
	_supportsRosterVersioning = _supportsStreamManagement = false;
	_lastID = 0;
}

- (void)xmpp_handleStanza: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"iq"]) {
		[self xmpp_handleIQ: [XMPPIQ stanzaWithElement: element]];
		return;
	}

	if ([[element name] isEqual: @"message"]) {
		[self xmpp_handleMessage:
		    [XMPPMessage stanzaWithElement: element]];
		return;
	}

	if ([[element name] isEqual: @"presence"]) {
		[self xmpp_handlePresence:
		    [XMPPPresence stanzaWithElement: element]];
		return;
	}

	[self xmpp_sendStreamError: @"unsupported-stanza-type"
			      text: nil];
}


- (void)xmpp_handleStream: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"features"]) {
		[self xmpp_handleFeatures: element];
		return;
	}

	if ([[element name] isEqual: @"error"]) {
		OFString *condition, *reason;
		[self close];
		[_socket close]; // Remote has already closed his stream
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
				     reason: reason];
		return;
	}

	assert(0);
}

- (void)XMPP_handleTLS: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"proceed"]) {
		/* FIXME: Catch errors here */
		SSLSocket *newSock;

		[_delegates broadcastSelector: @selector(
						   connectionWillUpgradeToTLS:)







|







845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
				     reason: reason];
		return;
	}

	assert(0);
}

- (void)xmpp_handleTLS: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"proceed"]) {
		/* FIXME: Catch errors here */
		SSLSocket *newSock;

		[_delegates broadcastSelector: @selector(
						   connectionWillUpgradeToTLS:)
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
		_encrypted = true;

		[_delegates broadcastSelector: @selector(
						   connectionDidUpgradeToTLS:)
				   withObject: self];

		/* Stream restart */
		[self XMPP_startStream];

		return;
	}

	if ([[element name] isEqual: @"failure"])
		/* TODO: Find/create an exception to throw here */
		@throw [OFException exception];

	assert(0);
}

- (void)XMPP_handleSASL: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"challenge"]) {
		OFXMLElement *responseTag;
		OFData *challenge =
		    [OFData dataWithBase64EncodedString: [element stringValue]];
		OFData *response = [_authModule continueWithData: challenge];








|











|







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
		_encrypted = true;

		[_delegates broadcastSelector: @selector(
						   connectionDidUpgradeToTLS:)
				   withObject: self];

		/* Stream restart */
		[self xmpp_startStream];

		return;
	}

	if ([[element name] isEqual: @"failure"])
		/* TODO: Find/create an exception to throw here */
		@throw [OFException exception];

	assert(0);
}

- (void)xmpp_handleSASL: (OFXMLElement *)element
{
	if ([[element name] isEqual: @"challenge"]) {
		OFXMLElement *responseTag;
		OFData *challenge =
		    [OFData dataWithBase64EncodedString: [element stringValue]];
		OFData *response = [_authModule continueWithData: challenge];

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
		    dataWithBase64EncodedString: [element stringValue]]];

		[_delegates broadcastSelector: @selector(
						   connectionWasAuthenticated:)
				   withObject: self];

		/* Stream restart */
		[self XMPP_startStream];

		return;
	}

	if ([[element name] isEqual: @"failure"]) {
		/* FIXME: Do more parsing/handling */
		@throw [XMPPAuthFailedException
		    exceptionWithConnection: self
				     reason: [element XMLString]];
	}

	assert(0);
}

- (void)XMPP_handleIQ: (XMPPIQ *)IQ
{
	bool handled = false;
	XMPPCallback *callback;
	OFString *key;

	if ((key = [[IQ from] fullJID]) == nil)
		key = [_JID bareJID];







|














|







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
		    dataWithBase64EncodedString: [element stringValue]]];

		[_delegates broadcastSelector: @selector(
						   connectionWasAuthenticated:)
				   withObject: self];

		/* Stream restart */
		[self xmpp_startStream];

		return;
	}

	if ([[element name] isEqual: @"failure"]) {
		/* FIXME: Do more parsing/handling */
		@throw [XMPPAuthFailedException
		    exceptionWithConnection: self
				     reason: [element XMLString]];
	}

	assert(0);
}

- (void)xmpp_handleIQ: (XMPPIQ *)IQ
{
	bool handled = false;
	XMPPCallback *callback;
	OFString *key;

	if ((key = [[IQ from] fullJID]) == nil)
		key = [_JID bareJID];
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
	if (!handled && ![[IQ type] isEqual: @"error"] &&
	    ![[IQ type] isEqual: @"result"]) {
		[self sendStanza: [IQ errorIQWithType: @"cancel"
					    condition: @"service-unavailable"]];
	}
}

- (void)XMPP_handleMessage: (XMPPMessage *)message
{
	[_delegates broadcastSelector: @selector(connection:didReceiveMessage:)
			   withObject: self
			   withObject: message];
}

- (void)XMPP_handlePresence: (XMPPPresence *)presence
{
	[_delegates broadcastSelector: @selector(connection:didReceivePresence:)
			   withObject: self
			   withObject: presence];
}

- (void)XMPP_handleFeatures: (OFXMLElement *)element
{
	OFXMLElement *startTLS = [element elementForName: @"starttls"
					       namespace: XMPP_NS_STARTTLS];
	OFXMLElement *bind = [element elementForName: @"bind"
					   namespace: XMPP_NS_BIND];
	OFXMLElement *session = [element elementForName: @"session"
					      namespace: XMPP_NS_SESSION];







|






|






|







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
	if (!handled && ![[IQ type] isEqual: @"error"] &&
	    ![[IQ type] isEqual: @"result"]) {
		[self sendStanza: [IQ errorIQWithType: @"cancel"
					    condition: @"service-unavailable"]];
	}
}

- (void)xmpp_handleMessage: (XMPPMessage *)message
{
	[_delegates broadcastSelector: @selector(connection:didReceiveMessage:)
			   withObject: self
			   withObject: message];
}

- (void)xmpp_handlePresence: (XMPPPresence *)presence
{
	[_delegates broadcastSelector: @selector(connection:didReceivePresence:)
			   withObject: self
			   withObject: presence];
}

- (void)xmpp_handleFeatures: (OFXMLElement *)element
{
	OFXMLElement *startTLS = [element elementForName: @"starttls"
					       namespace: XMPP_NS_STARTTLS];
	OFXMLElement *bind = [element elementForName: @"bind"
					   namespace: XMPP_NS_BIND];
	OFXMLElement *session = [element elementForName: @"session"
					      namespace: XMPP_NS_SESSION];
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
		_supportsRosterVersioning = true;

	if ([element elementForName: @"sm"
			  namespace: XMPP_NS_SM] != nil)
		_supportsStreamManagement = true;

	if (mechs != nil) {
		OFEnumerator *enumerator;
		OFXMLElement *mech;

		enumerator = [[mechs children] objectEnumerator];
		while ((mech = [enumerator nextObject]) != nil)
			[mechanisms addObject: [mech stringValue]];

		if (_privateKeyFile != nil && _certificateFile != nil &&
		    [mechanisms containsObject: @"EXTERNAL"]) {
			_authModule = [[XMPPEXTERNALAuth alloc] init];
			[self XMPP_sendAuth: @"EXTERNAL"];
			return;
		}

		if ([mechanisms containsObject: @"SCRAM-SHA-1-PLUS"]) {
			_authModule = [[XMPPSCRAMAuth alloc]
			    initWithAuthcid: _username
				   password: _password
				 connection: self
				       hash: [OFSHA1Hash class]
			      plusAvailable: true];
			[self XMPP_sendAuth: @"SCRAM-SHA-1-PLUS"];
			return;
		}

		if ([mechanisms containsObject: @"SCRAM-SHA-1"]) {
			_authModule = [[XMPPSCRAMAuth alloc]
			    initWithAuthcid: _username
				   password: _password
				 connection: self
				       hash: [OFSHA1Hash class]
			      plusAvailable: false];
			[self XMPP_sendAuth: @"SCRAM-SHA-1"];
			return;
		}

		if ([mechanisms containsObject: @"PLAIN"] && _encrypted) {
			_authModule = [[XMPPPLAINAuth alloc]
			    initWithAuthcid: _username
				   password: _password];
			[self XMPP_sendAuth: @"PLAIN"];
			return;
		}

		assert(0);
	}

	if (session != nil && [session elementForName: @"optional"
					    namespace: XMPP_NS_SESSION] == nil)
		_needsSession = true;

	if (bind != nil) {
		[self XMPP_sendResourceBind];
		return;
	}

	assert(0);
}

- (void)XMPP_sendAuth: (OFString *)authName
{
	OFXMLElement *authTag;
	OFData *initialMessage = [_authModule initialMessage];

	authTag = [OFXMLElement elementWithName: @"auth"
				      namespace: XMPP_NS_SASL];
	[authTag addAttributeWithName: @"mechanism"
			  stringValue: authName];
	if (initialMessage) {
		if ([initialMessage count] == 0)
			[authTag setStringValue: @"="];
		else
			[authTag setStringValue:
			    [initialMessage stringByBase64Encoding]];
	}

	[self sendStanza: authTag];
}

- (void)XMPP_sendResourceBind
{
	XMPPIQ *IQ;
	OFXMLElement *bind;

	IQ = [XMPPIQ IQWithType: @"set"
			     ID: [self generateStanzaID]];

	bind = [OFXMLElement elementWithName: @"bind"
				   namespace: XMPP_NS_BIND];

	if (_resource != nil)
		[bind addChild: [OFXMLElement elementWithName: @"resource"
						    namespace: XMPP_NS_BIND
						  stringValue: _resource]];

	[IQ addChild: bind];

	[self	    sendIQ: IQ
	    callbackTarget: self
		  selector: @selector(XMPP_handleResourceBindForConnection:
				IQ:)];
}

- (void)XMPP_sendStreamError: (OFString *)condition
			text: (OFString *)text
{
	OFXMLElement *error = [OFXMLElement
	    elementWithName: @"error"
		  namespace: XMPP_NS_STREAM];
	[error setPrefix: @"stream"
	    forNamespace: XMPP_NS_STREAM];
	[error addChild: [OFXMLElement elementWithName: condition
					     namespace: XMPP_NS_XMPP_STREAM]];
	if (text)
		[error addChild: [OFXMLElement
		    elementWithName: @"text"
			  namespace: XMPP_NS_XMPP_STREAM
			stringValue: text]];
	[_parser setDelegate: nil];
	[self sendStanza: error];
	[self close];
}

- (void)XMPP_handleResourceBindForConnection: (XMPPConnection *)connection
					  IQ: (XMPPIQ *)IQ
{
	OFXMLElement *bindElement, *JIDElement;

	assert([[IQ type] isEqual: @"result"]);

	bindElement = [IQ elementForName: @"bind"
			       namespace: XMPP_NS_BIND];

	assert(bindElement != nil);

	JIDElement = [bindElement elementForName: @"jid"
				       namespace: XMPP_NS_BIND];
	_JID = [[XMPPJID alloc] initWithString: [JIDElement stringValue]];

	if (_needsSession) {
		[self XMPP_sendSession];
		return;
	}

	[_delegates broadcastSelector: @selector(connection:wasBoundToJID:)
			   withObject: self
			   withObject: _JID];
}

- (void)XMPP_sendSession
{
	XMPPIQ *IQ = [XMPPIQ IQWithType: @"set"
				     ID: [self generateStanzaID]];

	[IQ addChild: [OFXMLElement elementWithName: @"session"
					  namespace: XMPP_NS_SESSION]];

	[self	    sendIQ: IQ
	    callbackTarget: self
		  selector: @selector(XMPP_handleSessionForConnection:IQ:)];
}

- (void)XMPP_handleSessionForConnection: (XMPPConnection *)connection
				     IQ: (XMPPIQ *)IQ
{
	if (![[IQ type] isEqual: @"result"])
		OF_ENSURE(0);

	[_delegates broadcastSelector: @selector(connection:wasBoundToJID:)
			   withObject: self
			   withObject: _JID];
}

- (OFString *)XMPP_IDNAToASCII: (OFString *)domain
{
	OFString *ret;
	char *cDomain;
	Idna_rc rc;

	if ((rc = idna_to_ascii_8z([domain UTF8String],
	    &cDomain, IDNA_USE_STD3_ASCII_RULES)) != IDNA_SUCCESS)







<
|
<
<
<





|










|










|







|











|






|



















|



















|



|



















|
















|








|









|


|










|







1009
1010
1011
1012
1013
1014
1015

1016



1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
		_supportsRosterVersioning = true;

	if ([element elementForName: @"sm"
			  namespace: XMPP_NS_SM] != nil)
		_supportsStreamManagement = true;

	if (mechs != nil) {

		for (OFXMLElement *mech in [mechs children])



			[mechanisms addObject: [mech stringValue]];

		if (_privateKeyFile != nil && _certificateFile != nil &&
		    [mechanisms containsObject: @"EXTERNAL"]) {
			_authModule = [[XMPPEXTERNALAuth alloc] init];
			[self xmpp_sendAuth: @"EXTERNAL"];
			return;
		}

		if ([mechanisms containsObject: @"SCRAM-SHA-1-PLUS"]) {
			_authModule = [[XMPPSCRAMAuth alloc]
			    initWithAuthcid: _username
				   password: _password
				 connection: self
				       hash: [OFSHA1Hash class]
			      plusAvailable: true];
			[self xmpp_sendAuth: @"SCRAM-SHA-1-PLUS"];
			return;
		}

		if ([mechanisms containsObject: @"SCRAM-SHA-1"]) {
			_authModule = [[XMPPSCRAMAuth alloc]
			    initWithAuthcid: _username
				   password: _password
				 connection: self
				       hash: [OFSHA1Hash class]
			      plusAvailable: false];
			[self xmpp_sendAuth: @"SCRAM-SHA-1"];
			return;
		}

		if ([mechanisms containsObject: @"PLAIN"] && _encrypted) {
			_authModule = [[XMPPPLAINAuth alloc]
			    initWithAuthcid: _username
				   password: _password];
			[self xmpp_sendAuth: @"PLAIN"];
			return;
		}

		assert(0);
	}

	if (session != nil && [session elementForName: @"optional"
					    namespace: XMPP_NS_SESSION] == nil)
		_needsSession = true;

	if (bind != nil) {
		[self xmpp_sendResourceBind];
		return;
	}

	assert(0);
}

- (void)xmpp_sendAuth: (OFString *)authName
{
	OFXMLElement *authTag;
	OFData *initialMessage = [_authModule initialMessage];

	authTag = [OFXMLElement elementWithName: @"auth"
				      namespace: XMPP_NS_SASL];
	[authTag addAttributeWithName: @"mechanism"
			  stringValue: authName];
	if (initialMessage) {
		if ([initialMessage count] == 0)
			[authTag setStringValue: @"="];
		else
			[authTag setStringValue:
			    [initialMessage stringByBase64Encoding]];
	}

	[self sendStanza: authTag];
}

- (void)xmpp_sendResourceBind
{
	XMPPIQ *IQ;
	OFXMLElement *bind;

	IQ = [XMPPIQ IQWithType: @"set"
			     ID: [self generateStanzaID]];

	bind = [OFXMLElement elementWithName: @"bind"
				   namespace: XMPP_NS_BIND];

	if (_resource != nil)
		[bind addChild: [OFXMLElement elementWithName: @"resource"
						    namespace: XMPP_NS_BIND
						  stringValue: _resource]];

	[IQ addChild: bind];

	[self	    sendIQ: IQ
	    callbackTarget: self
		  selector: @selector(xmpp_handleResourceBindForConnection:
				IQ:)];
}

- (void)xmpp_sendStreamError: (OFString *)condition
			text: (OFString *)text
{
	OFXMLElement *error = [OFXMLElement
	    elementWithName: @"error"
		  namespace: XMPP_NS_STREAM];
	[error setPrefix: @"stream"
	    forNamespace: XMPP_NS_STREAM];
	[error addChild: [OFXMLElement elementWithName: condition
					     namespace: XMPP_NS_XMPP_STREAM]];
	if (text)
		[error addChild: [OFXMLElement
		    elementWithName: @"text"
			  namespace: XMPP_NS_XMPP_STREAM
			stringValue: text]];
	[_parser setDelegate: nil];
	[self sendStanza: error];
	[self close];
}

- (void)xmpp_handleResourceBindForConnection: (XMPPConnection *)connection
					  IQ: (XMPPIQ *)IQ
{
	OFXMLElement *bindElement, *JIDElement;

	assert([[IQ type] isEqual: @"result"]);

	bindElement = [IQ elementForName: @"bind"
			       namespace: XMPP_NS_BIND];

	assert(bindElement != nil);

	JIDElement = [bindElement elementForName: @"jid"
				       namespace: XMPP_NS_BIND];
	_JID = [[XMPPJID alloc] initWithString: [JIDElement stringValue]];

	if (_needsSession) {
		[self xmpp_sendSession];
		return;
	}

	[_delegates broadcastSelector: @selector(connection:wasBoundToJID:)
			   withObject: self
			   withObject: _JID];
}

- (void)xmpp_sendSession
{
	XMPPIQ *IQ = [XMPPIQ IQWithType: @"set"
				     ID: [self generateStanzaID]];

	[IQ addChild: [OFXMLElement elementWithName: @"session"
					  namespace: XMPP_NS_SESSION]];

	[self	    sendIQ: IQ
	    callbackTarget: self
		  selector: @selector(xmpp_handleSessionForConnection:IQ:)];
}

- (void)xmpp_handleSessionForConnection: (XMPPConnection *)connection
				     IQ: (XMPPIQ *)IQ
{
	if (![[IQ type] isEqual: @"result"])
		OF_ENSURE(0);

	[_delegates broadcastSelector: @selector(connection:wasBoundToJID:)
			   withObject: self
			   withObject: _JID];
}

- (OFString *)xmpp_IDNAToASCII: (OFString *)domain
{
	OFString *ret;
	char *cDomain;
	Idna_rc rc;

	if ((rc = idna_to_ascii_8z([domain UTF8String],
	    &cDomain, IDNA_USE_STD3_ASCII_RULES)) != IDNA_SUCCESS)
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
}

- (void)removeDelegate: (id <XMPPConnectionDelegate>)delegate
{
	[_delegates removeDelegate: delegate];
}

- (XMPPMulticastDelegate *)XMPP_delegates
{
	return _delegates;
}
@end







|




1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
}

- (void)removeDelegate: (id <XMPPConnectionDelegate>)delegate
{
	[_delegates removeDelegate: delegate];
}

- (XMPPMulticastDelegate *)xmpp_delegates
{
	return _delegates;
}
@end