ObjXMPP  Diff

Differences From Artifact [7c6a173624]:

To Artifact [66ac2fa939]:


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
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







-
-
-
-
-
+
+
+
+
+










-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
+

-
+

-
+



-
+





-
+


-
+




-
+






-
+


-
+

-
+

-
+



-
+





-
+


-
+




-
+






-
+


-
+

-
+

-
-
+
+

-
+






-
+




-
-
+
+














-
+




-
+

-
-
+
+








-
+


-
+

-
+

-
+



-
+





-
+


-
+




-
+






-
+


-
+

-
+




-
+


-
+

-
+




-
+









-
+



-
+

-
-
-
+
+
+



-
+









+
-
-
+
+








-
-
+
+











-
-
-
-
-
+
+
+
+
+
















-
-
-
+
+
+




-
+

















-
-
+
+

-
-
+
+








-
-
-
-
+
+
+
+









-
-
-
-
+
+
+
+




-
-
-
+
+
+

-
-
+
+

-
-
-
-
-
+
+
+
+
+
+









-
+




-
+


-
+

-
+




-
+




-
+




-
+




-
+









-
+







-
+








-
+

-
+



-
+







-
-
-
+
+
+

-
+















-
-
+
+

















-
-
+
+








-
+














-
+


















-
+












-
+













-
-
-
+
+
+







}

- init
{
	self = [super init];

	@try {
		port = 5222;
		encrypted = NO;
		streamOpen = NO;
		delegates = [[XMPPMulticastDelegate alloc] init];
		callbacks = [[OFMutableDictionary alloc] init];
		_port = 5222;
		_encrypted = NO;
		_streamOpen = NO;
		_delegates = [[XMPPMulticastDelegate alloc] init];
		_callbacks = [[OFMutableDictionary alloc] init];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	[sock release];
	[parser release];
	[elementBuilder release];
	[username release];
	[password release];
	[privateKeyFile release];
	[certificateFile release];
	[server release];
	[domain release];
	[resource release];
	[JID release];
	[delegates release];
	[callbacks release];
	[authModule release];
	[_socket release];
	[_parser release];
	[_elementBuilder release];
	[_username release];
	[_password release];
	[_privateKeyFile release];
	[_certificateFile release];
	[_server release];
	[_domain release];
	[_resource release];
	[_JID release];
	[_delegates release];
	[_callbacks release];
	[_authModule release];

	[super dealloc];
}

- (void)setUsername: (OFString*)username_
- (void)setUsername: (OFString*)username
{
	OFString *old = username;
	OFString *old = _username;

	if (username_ != nil) {
	if (username != nil) {
		char *node;
		Stringprep_rc rc;

		if ((rc = stringprep_profile([username_ UTF8String], &node,
		if ((rc = stringprep_profile([username UTF8String], &node,
		    "SASLprep", 0)) != STRINGPREP_OK)
			@throw [XMPPStringPrepFailedException
			    exceptionWithClass: [self class]
				    connection: self
				       profile: @"SASLprep"
					string: username_];
					string: username];

		@try {
			username = [[OFString alloc] initWithUTF8String: node];
			_username = [[OFString alloc] initWithUTF8String: node];
		} @finally {
			free(node);
		}
	} else
		username = nil;
		_username = nil;

	[old release];
}

- (OFString*)username
{
	return [[username copy] autorelease];
	return [[_username copy] autorelease];
}

- (void)setResource: (OFString*)resource_
- (void)setResource: (OFString*)resource
{
	OFString *old = resource;
	OFString *old = _resource;

	if (resource_ != nil) {
	if (resource != nil) {
		char *res;
		Stringprep_rc rc;

		if ((rc = stringprep_profile([resource_ UTF8String], &res,
		if ((rc = stringprep_profile([resource UTF8String], &res,
		    "Resourceprep", 0)) != STRINGPREP_OK)
			@throw [XMPPStringPrepFailedException
			    exceptionWithClass: [self class]
				    connection: self
				       profile: @"Resourceprep"
					string: resource_];
					string: resource];

		@try {
			resource = [[OFString alloc] initWithUTF8String: res];
			_resource = [[OFString alloc] initWithUTF8String: res];
		} @finally {
			free(res);
		}
	} else
		resource = nil;
		_resource = nil;

	[old release];
}

- (OFString*)resource
{
	return [[resource copy] autorelease];
	return [[_resource copy] autorelease];
}

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

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

	[old release];
}

- (OFString*)server
{
	return [[server copy] autorelease];
	return [[_server copy] autorelease];
}

- (void)setDomain: (OFString*)domain_
{
	OFString *oldDomain = domain;
	OFString *oldDomainToASCII = domainToASCII;
	OFString *oldDomain = _domain;
	OFString *oldDomainToASCII = _domainToASCII;

	if (domain_ != nil) {
		char *srv;
		Stringprep_rc rc;

		if ((rc = stringprep_profile([domain_ UTF8String], &srv,
		    "Nameprep", 0)) != STRINGPREP_OK)
			@throw [XMPPStringPrepFailedException
			    exceptionWithClass: [self class]
				    connection: self
				       profile: @"Nameprep"
					string: domain_];

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

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

	[oldDomain release];
	[oldDomainToASCII release];
}

- (OFString*)domain
{
	return [[domain copy] autorelease];
	return [[_domain copy] autorelease];
}

- (void)setPassword: (OFString*)password_
- (void)setPassword: (OFString*)password
{
	OFString *old = password;
	OFString *old = _password;

	if (password_ != nil) {
	if (password != nil) {
		char *pass;
		Stringprep_rc rc;

		if ((rc = stringprep_profile([password_ UTF8String], &pass,
		if ((rc = stringprep_profile([password UTF8String], &pass,
		    "SASLprep", 0)) != STRINGPREP_OK)
			@throw [XMPPStringPrepFailedException
			    exceptionWithClass: [self class]
				    connection: self
				       profile: @"SASLprep"
					string: password_];
					string: password];

		@try {
			password = [[OFString alloc] initWithUTF8String: pass];
			_password = [[OFString alloc] initWithUTF8String: pass];
		} @finally {
			free(pass);
		}
	} else
		password = nil;
		_password = nil;

	[old release];
}

- (OFString*)password
{
	return [[password copy] autorelease];
	return [[_password copy] autorelease];
}

- (void)setPrivateKeyFile: (OFString*)file
- (void)setPrivateKeyFile: (OFString*)privateKeyFile
{
	OF_SETTER(privateKeyFile, file, YES, YES)
	OF_SETTER(_privateKeyFile, privateKeyFile, YES, YES)
}

- (OFString*)privateKeyFile
{
	OF_GETTER(privateKeyFile, YES)
	OF_GETTER(_privateKeyFile, YES)
}

- (void)setCertificateFile: (OFString*)file
- (void)setCertificateFile: (OFString*)certificateFile
{
	OF_SETTER(certificateFile, file, YES, YES)
	OF_SETTER(_certificateFile, certificateFile, YES, YES)
}

- (OFString*)certificateFile
{
	OF_GETTER(certificateFile, YES)
	OF_GETTER(_certificateFile, YES)
}

- (void)connect
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	XMPPSRVEntry *candidate = nil;
	XMPPSRVLookup *SRVLookup = nil;
	OFEnumerator *enumerator;

	if (sock != nil)
	if (_socket != nil)
		@throw [OFAlreadyConnectedException
		    exceptionWithClass: [self class]];

	sock = [[OFTCPSocket alloc] init];
	_socket = [[OFTCPSocket alloc] init];

	if (server)
		[sock connectToHost: server
			       port: port];
	if (_server)
		[_socket connectToHost: _server
				  port: _port];
	else {
		@try {
			SRVLookup = [XMPPSRVLookup
			    lookupWithDomain: domainToASCII];
			    lookupWithDomain: _domainToASCII];
		} @catch (id e) {
		}

		enumerator = [SRVLookup objectEnumerator];

		/* Iterate over SRV records, if any */
		if ((candidate = [enumerator nextObject]) != nil) {
			do {
				@try {
					[_socket
					[sock connectToHost: [candidate target]
						       port: [candidate port]];
					    connectToHost: [candidate target]
						     port: [candidate port]];
					break;
				} @catch (OFAddressTranslationFailedException
				    *e) {
				} @catch (OFConnectionFailedException *e) {
				}
			} while ((candidate = [enumerator nextObject]) != nil);
		} else
			/* No SRV records -> fall back to A / AAAA record */
			[sock connectToHost: domainToASCII
				       port: port];
			[_socket connectToHost: _domainToASCII
					  port: _port];
	}

	[self XMPP_startStream];

	[pool release];
}

- (void)handleConnection
{
	char *buffer = [self allocMemoryWithSize: BUFFER_LENGTH];

	[sock asyncReadIntoBuffer: buffer
			   length: BUFFER_LENGTH
			   target: self
			 selector: @selector(stream:didReadIntoBuffer:length:
				       exception:)];
	[_socket asyncReadIntoBuffer: buffer
			      length: BUFFER_LENGTH
			      target: self
			    selector: @selector(stream:didReadIntoBuffer:length:
					  exception:)];
}

- (void)asyncConnectAndHandle
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];

	[[[[XMPPConnection_ConnectThread alloc]
	    initWithSourceThread: [OFThread currentThread]
		      connection: self] autorelease] start];

	[pool release];
}

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

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

	return YES;
}

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

	[oldParser release];
	[oldElementBuilder release];
	[_oldParser release];
	[_oldElementBuilder release];

	oldParser = nil;
	oldElementBuilder = nil;
	_oldParser = nil;
	_oldElementBuilder = nil;
}

-      (BOOL)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];
		[_delegates broadcastSelector: @selector(connection:
						   didThrowException:)
				   withObject: self
				   withObject: exception];
		[self close];
		return NO;
	}

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

	if (oldParser != nil || oldElementBuilder != nil) {
		[oldParser release];
		[oldElementBuilder release];
	if (_oldParser != nil || _oldElementBuilder != nil) {
		[_oldParser release];
		[_oldElementBuilder release];

		oldParser = nil;
		oldElementBuilder = nil;
		_oldParser = nil;
		_oldElementBuilder = nil;

		[sock asyncReadIntoBuffer: buffer
				   length: BUFFER_LENGTH
				   target: self
				 selector: @selector(stream:didReadIntoBuffer:
					       length:exception:)];
		[_socket asyncReadIntoBuffer: buffer
				      length: BUFFER_LENGTH
				      target: self
				    selector: @selector(stream:
						  didReadIntoBuffer:length:
						  exception:)];

		return NO;
	}

	return YES;
}

- (OFTCPSocket*)socket
{
	return [[sock retain] autorelease];
	return [[_socket retain] autorelease];
}

- (BOOL)encryptionRequired
{
	return encryptionRequired;
	return _encryptionRequired;
}

- (void)setEncryptionRequired: (BOOL)required
- (void)setEncryptionRequired: (BOOL)encryptionRequired
{
	encryptionRequired = required;
	_encryptionRequired = encryptionRequired;
}

- (BOOL)encrypted
{
	return encrypted;
	return _encrypted;
}

- (BOOL)streamOpen
{
	return streamOpen;
	return _streamOpen;
}

- (BOOL)supportsRosterVersioning
{
	return supportsRosterVersioning;
	return _supportsRosterVersioning;
}

- (BOOL)supportsStreamManagement
{
	return supportsStreamManagement;
	return _supportsStreamManagement;
}

- (BOOL)checkCertificateAndGetReason: (OFString**)reason
{
	X509Certificate *cert;
	OFDictionary *SANs;
	BOOL serviceSpecific = NO;

	@try {
		[sock verifyPeerCertificate];
		[_socket verifyPeerCertificate];
	} @catch (SSLInvalidCertificateException *e) {
		if (reason != NULL)
			*reason = [[[e reason] copy] autorelease];

		return NO;
	}

	cert = [sock peerCertificate];
	cert = [_socket peerCertificate];
	SANs = [cert subjectAlternativeName];

	if ([[SANs objectForKey: @"otherName"]
		objectForKey: OID_SRVName] != nil ||
	     [SANs objectForKey: @"dNSName"] != nil ||
	     [SANs objectForKey: @"uniformResourceIdentifier"] != nil)
		serviceSpecific = YES;

	if ([cert hasSRVNameMatchingDomain: domainToASCII
	if ([cert hasSRVNameMatchingDomain: _domainToASCII
				   service: @"xmpp-client"] ||
	    [cert hasDNSNameMatchingDomain: domainToASCII])
	    [cert hasDNSNameMatchingDomain: _domainToASCII])
		return YES;

	if (!serviceSpecific &&
	    [cert hasCommonNameMatchingDomain: domainToASCII])
	    [cert hasCommonNameMatchingDomain: _domainToASCII])
		return YES;

	return NO;
}

- (void)sendStanza: (OFXMLElement*)element
{
	[delegates broadcastSelector: @selector(connection:didSendElement:)
			  withObject: self
			  withObject: element];
	[_delegates broadcastSelector: @selector(connection:didSendElement:)
			   withObject: self
			   withObject: element];

	[sock writeString: [element XMLString]];
	[_socket writeString: [element XMLString]];
}

-   (void)sendIQ: (XMPPIQ*)iq
  callbackTarget: (id)target
	selector: (SEL)selector
{
	OFAutoreleasePool *pool;
	XMPPCallback *callback;

	if (![iq ID])
		[iq setID: [self generateStanzaID]];

	pool = [[OFAutoreleasePool alloc] init];
	callback = [XMPPCallback callbackWithTarget: target
					   selector: selector];
	[callbacks setObject: callback
		      forKey: [iq ID]];
	[_callbacks setObject: callback
		       forKey: [iq ID]];
	[pool release];

	[self sendStanza: iq];
}

#ifdef OF_HAVE_BLOCKS
-  (void)sendIQ: (XMPPIQ*)iq
  callbackBlock: (xmpp_callback_block_t)block
{
	OFAutoreleasePool *pool;
	XMPPCallback *callback;

	if (![iq ID])
		[iq setID: [self generateStanzaID]];

	pool = [[OFAutoreleasePool alloc] init];
	callback = [XMPPCallback callbackWithBlock: block];
	[callbacks setObject: callback
		      forKey: [iq ID]];
	[_callbacks setObject: callback
		       forKey: [iq ID]];
	[pool release];

	[self sendStanza: iq];
}
#endif

- (OFString*)generateStanzaID
{
	return [OFString stringWithFormat: @"objxmpp_%u", lastID++];
	return [OFString stringWithFormat: @"objxmpp_%u", _lastID++];
}

-    (void)parser: (OFXMLParser*)p
  didStartElement: (OFString*)name
	   prefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attributes
{
	OFEnumerator *enumerator;
	OFXMLAttribute *attribute;

	if (![name isEqual: @"stream"]) {
		// No dedicated stream error for this, may not even be XMPP
		[self close];
		[sock 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;
	}

	enumerator = [attributes objectEnumerator];
	while ((attribute = [enumerator nextObject]) != nil) {
		if ([[attribute name] isEqual: @"from"] &&
		    ![[attribute stringValue] isEqual: domain]) {
		    ![[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];
	[_parser setDelegate: _elementBuilder];
}

- (void)elementBuilder: (OFXMLElementBuilder*)builder
       didBuildElement: (OFXMLElement*)element
{
	/* Ignore whitespace elements */
	if ([element name] == nil)
		return;

	[element setDefaultNamespace: XMPP_NS_CLIENT];
	[element setPrefix: @"stream"
	      forNamespace: XMPP_NS_STREAM];

	[delegates broadcastSelector: @selector(connection:didReceiveElement:)
			  withObject: self
			  withObject: element];
	[_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];

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
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







-
-
+
+





-
-
+
+

-
-
+
+

-
-
+
+

-
+

-
+

-
-
-
-
-
+
+
+
+
+

-
+




-
-
+
+


-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+







}

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

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

	/*
	 * We can't release them now, as we are currently inside them. Release
	 * them the next time the parser returns.
	 */
	oldParser = parser;
	oldElementBuilder = elementBuilder;
	_oldParser = _parser;
	_oldElementBuilder = _elementBuilder;

	parser = [[OFXMLParser alloc] init];
	[parser setDelegate: self];
	_parser = [[OFXMLParser alloc] init];
	[_parser setDelegate: self];

	elementBuilder = [[XMPPXMLElementBuilder alloc] init];
	[elementBuilder setDelegate: self];
	_elementBuilder = [[XMPPXMLElementBuilder alloc] init];
	[_elementBuilder setDelegate: self];

	if (language != nil)
	if (_language != nil)
		langString = [OFString stringWithFormat: @"xml:lang='%@' ",
							 language];
							 _language];

	[sock writeFormat: @"<?xml version='1.0'?>\n"
			   @"<stream:stream to='%@' "
			   @"xmlns='" XMPP_NS_CLIENT @"' "
			   @"xmlns:stream='" XMPP_NS_STREAM @"' %@"
			   @"version='1.0'>", domain, langString];
	[_socket writeFormat: @"<?xml version='1.0'?>\n"
			      @"<stream:stream to='%@' "
			      @"xmlns='" XMPP_NS_CLIENT @"' "
			      @"xmlns:stream='" XMPP_NS_STREAM @"' %@"
			      @"version='1.0'>", _domain, langString];

	streamOpen = YES;
	_streamOpen = YES;
}

- (void)close
{
	if (streamOpen)
		[sock writeString: @"</stream:stream>"];
	if (_streamOpen)
		[_socket writeString: @"</stream:stream>"];


	[oldParser release];
	oldParser = nil;
	[oldElementBuilder release];
	oldElementBuilder = nil;
	[authModule release];
	authModule = nil;
	[sock release];
	sock = nil;
	[JID release];
	JID = nil;
	streamOpen = needsSession = encrypted = NO;
	supportsRosterVersioning = supportsStreamManagement = NO;
	lastID = 0;
	[_oldParser release];
	_oldParser = nil;
	[_oldElementBuilder release];
	_oldElementBuilder = nil;
	[_authModule release];
	_authModule = nil;
	[_socket release];
	_socket = nil;
	[_JID release];
	_JID = nil;
	_streamOpen = _needsSession = _encrypted = NO;
	_supportsRosterVersioning = _supportsStreamManagement = NO;
	_lastID = 0;
}

- (void)XMPP_handleStanza: (OFXMLElement*)element
{
	if ([[element name] isEqual: @"iq"]) {
		[self XMPP_handleIQ: [XMPPIQ stanzaWithElement: element]];
		return;
782
783
784
785
786
787
788
789

790
791
792
793
794
795
796
784
785
786
787
788
789
790

791
792
793
794
795
796
797
798







-
+







		[self XMPP_handleFeatures: element];
		return;
	}

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

		if ([element elementForName: @"bad-format"
				  namespace: XMPP_NS_XMPP_STREAM])
			condition = @"bad-format";
		else if ([element elementForName: @"bad-namespace-prefix"
				       namespace: XMPP_NS_XMPP_STREAM])
			condition = @"bad-namespace-prefix";
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
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







-
-
-
+
+
+

-
-
-
-
-
+
+
+
+
+

-
+

-
-
-
+
+
+




















-
+

















-
+


-
-
-
+
+
+








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

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

		newSock = [[SSLSocket alloc] initWithSocket: sock
					     privateKeyFile: privateKeyFile
					    certificateFile: certificateFile];
		[sock release];
		sock = newSock;
		newSock = [[SSLSocket alloc] initWithSocket: _socket
					     privateKeyFile: _privateKeyFile
					    certificateFile: _certificateFile];
		[_socket release];
		_socket = newSock;

		encrypted = YES;
		_encrypted = YES;

		[delegates broadcastSelector: @selector(
						  connectionDidUpgradeToTLS:)
				  withObject: self];
		[_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 exceptionWithClass: [self class]];

	assert(0);
}

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

		responseTag = [OFXMLElement elementWithName: @"response"
						  namespace: XMPP_NS_SASL];
		if (response) {
			if ([response count] == 0)
				[responseTag setStringValue: @"="];
			else
				[responseTag setStringValue:
				    [response stringByBase64Encoding]];
		}

		[self sendStanza: responseTag];
		return;
	}

	if ([[element name] isEqual: @"success"]) {
		[authModule continueWithData: [OFDataArray
		[_authModule continueWithData: [OFDataArray
		    dataArrayWithBase64EncodedString: [element stringValue]]];

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

		/* Stream restart */
		[self XMPP_startStream];

		return;
	}

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
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
1184



1185
1186
1187
1188
1189
1190
1191
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
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



1184
1185
1186
1187
1188
1189
1190
1191
1192
1193







-
+


-
+



-
-
-
-
+
+
+
+










-
-
-
+
+
+




-
-
-
+
+
+




-
+









-
+






-
+





-
+



-
+









-
+

-
+





-
-
-
+
+
+








-
-
-
+
+
+







-
-
-
-
+
+
+
+








-
+












-
+


















-
+


-
+





-
+


-
+

-
+

-
+




















-
+



















-
+

-
+




-
-
-
+
+
+







}

- (void)XMPP_handleIQ: (XMPPIQ*)iq
{
	BOOL handled = NO;
	XMPPCallback *callback;

	if ((callback = [callbacks objectForKey: [iq ID]])) {
	if ((callback = [_callbacks objectForKey: [iq ID]])) {
		[callback runWithIQ: iq
			 connection: self];
		[callbacks removeObjectForKey: [iq ID]];
		[_callbacks removeObjectForKey: [iq ID]];
		return;
	}

	handled = [delegates broadcastSelector: @selector(
						    connection:didReceiveIQ:)
				    withObject: self
				    withObject: iq];
	handled = [_delegates broadcastSelector: @selector(
						     connection:didReceiveIQ:)
				     withObject: self
				     withObject: iq];

	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];
	[_delegates broadcastSelector: @selector(connection:didReceiveMessage:)
			   withObject: self
			   withObject: message];
}

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

- (void)XMPP_handleFeatures: (OFXMLElement*)element
{
	OFXMLElement *starttls = [element elementForName: @"starttls"
	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];
	OFXMLElement *mechs = [element elementForName: @"mechanisms"
					    namespace: XMPP_NS_SASL];
	OFMutableSet *mechanisms = [OFMutableSet set];

	if (!encrypted && starttls != nil) {
	if (!_encrypted && startTLS != nil) {
		[self sendStanza:
		    [OFXMLElement elementWithName: @"starttls"
					namespace: XMPP_NS_STARTTLS]];
		return;
	}

	if (encryptionRequired && !encrypted)
	if (_encryptionRequired && !_encrypted)
		/* TODO: Find/create an exception to throw here */
		@throw [OFException exceptionWithClass: [self class]];

	if ([element elementForName: @"ver"
			  namespace: XMPP_NS_ROSTERVER] != nil)
		supportsRosterVersioning = YES;
		_supportsRosterVersioning = YES;

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

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

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

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

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

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

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

		assert(0);
	}

	if (session != nil)
		needsSession = YES;
		_needsSession = YES;

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

	assert(0);
}

- (void)XMPP_sendAuth: (OFString*)authName
{
	OFXMLElement *authTag;
	OFDataArray *initialMessage = [authModule initialMessage];
	OFDataArray *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;
	XMPPIQ *IQ;
	OFXMLElement *bind;

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

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

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

	[iq addChild: bind];
	[IQ addChild: bind];

	[self	    sendIQ: iq
	[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];
	[_parser setDelegate: nil];
	[self sendStanza: error];
	[self close];
}

- (void)XMPP_handleResourceBindForConnection: (XMPPConnection*)connection
					  IQ: (XMPPIQ*)iq
{
	OFXMLElement *bindElement;
	OFXMLElement *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]];
	_JID = [[XMPPJID alloc] initWithString: [jidElement stringValue]];

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

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

- (void)XMPP_sendSession
{
	XMPPIQ *iq;

	iq = [XMPPIQ IQWithType: @"set"
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208



1209
1210
1211
1212
1213
1214
1215
1201
1202
1203
1204
1205
1206
1207



1208
1209
1210
1211
1212
1213
1214
1215
1216
1217







-
-
-
+
+
+








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

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

- (OFString*)XMPP_IDNAToASCII: (OFString*)domain_
{
	OFString *ret;
	char *cDomain;
	Idna_rc rc;
1229
1230
1231
1232
1233
1234
1235
1236

1237
1238
1239

1240
1241

1242
1243
1244
1245
1246

1247
1248
1249

1250
1251

1252
1253
1254
1255

1256
1257
1258
1259
1260

1261
1262
1263

1264
1265

1266
1267
1268
1269
1270

1271
1272
1273
1274
1275

1276
1277
1278
1279
1280

1281
1282
1283
1284
1285

1286
1287
1231
1232
1233
1234
1235
1236
1237

1238
1239
1240

1241
1242

1243
1244
1245
1246
1247

1248
1249
1250

1251
1252

1253
1254
1255
1256

1257
1258
1259
1260
1261

1262
1263
1264

1265
1266

1267
1268
1269
1270
1271

1272
1273
1274
1275
1276

1277
1278
1279
1280
1281

1282
1283
1284
1285
1286

1287
1288
1289







-
+


-
+

-
+




-
+


-
+

-
+



-
+




-
+


-
+

-
+




-
+




-
+




-
+




-
+


	}

	return ret;
}

- (XMPPJID*)JID
{
	return [[JID copy] autorelease];
	return [[_JID copy] autorelease];
}

- (void)setPort: (uint16_t)port_
- (void)setPort: (uint16_t)port
{
	port = port_;
	_port = port;
}

- (uint16_t)port
{
	return port;
	return _port;
}

- (void)setDataStorage: (id <XMPPStorage>)dataStorage_
- (void)setDataStorage: (id <XMPPStorage>)dataStorage
{
	if (streamOpen)
	if (_streamOpen)
		@throw [OFInvalidArgumentException
		    exceptionWithClass: [self class]];

	dataStorage = dataStorage_;
	_dataStorage = dataStorage;
}

- (id <XMPPStorage>)dataStorage
{
	return dataStorage;
	return _dataStorage;
}

- (void)setLanguage: (OFString*)language_
- (void)setLanguage: (OFString*)language
{
	OF_SETTER(language, language_, YES, YES)
	OF_SETTER(_language, language, YES, YES)
}

- (OFString*)language
{
	OF_GETTER(language, YES)
	OF_GETTER(_language, YES)
}

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

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

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