aboutsummaryrefslogtreecommitdiffstats
path: root/src/eu/siacs/conversations/xmpp/XmppConnection.java
blob: b2829c6ea52860246e158630e33b9e91b198fe3e (plain)
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
package eu.siacs.conversations.xmpp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.xmlpull.v1.XmlPullParserException;

import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.util.Log;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.DNSHelper;
import eu.siacs.conversations.utils.zlib.ZLibOutputStream;
import eu.siacs.conversations.utils.zlib.ZLibInputStream;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Tag;
import eu.siacs.conversations.xml.TagWriter;
import eu.siacs.conversations.xml.XmlReader;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;

public class XmppConnection implements Runnable {

	protected Account account;
	private static final String LOGTAG = "xmppService";

	private WakeLock wakeLock;

	private SecureRandom mRandom;

	private Socket socket;
	private XmlReader tagReader;
	private TagWriter tagWriter;

	private boolean shouldBind = true;
	private boolean shouldAuthenticate = true;
	private Element streamFeatures;
	private HashMap<String, List<String>> disco = new HashMap<String, List<String>>();

	private String streamId = null;
	private int smVersion = 3;

	private int stanzasReceived = 0;
	private int stanzasSent = 0;

	public long lastPaketReceived = 0;
	public long lastPingSent = 0;
	public long lastConnect = 0;
	public long lastSessionStarted = 0;

	private int attempt = 0;

	private static final int PACKET_IQ = 0;
	private static final int PACKET_MESSAGE = 1;
	private static final int PACKET_PRESENCE = 2;

	private Hashtable<String, PacketReceived> packetCallbacks = new Hashtable<String, PacketReceived>();
	private OnPresencePacketReceived presenceListener = null;
	private OnJinglePacketReceived jingleListener = null;
	private OnIqPacketReceived unregisteredIqListener = null;
	private OnMessagePacketReceived messageListener = null;
	private OnStatusChanged statusListener = null;
	private OnTLSExceptionReceived tlsListener = null;
	private OnBindListener bindListener = null;

	public XmppConnection(Account account, XmppConnectionService service) {
		this.mRandom = service.getRNG();
		this.account = account;
		this.wakeLock = service.getPowerManager().newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
				account.getJid());
		tagWriter = new TagWriter();
	}

	protected void changeStatus(int nextStatus) {
		if (account.getStatus() != nextStatus) {
			if ((nextStatus == Account.STATUS_OFFLINE)
					&& (account.getStatus() != Account.STATUS_CONNECTING)
					&& (account.getStatus() != Account.STATUS_ONLINE)
					&& (account.getStatus() != Account.STATUS_DISABLED)) {
				return;
			}
			if (nextStatus == Account.STATUS_ONLINE) {
				this.attempt = 0;
			}
			account.setStatus(nextStatus);
			if (statusListener != null) {
				statusListener.onStatusChanged(account);
			}
		}
	}

	protected void connect() {
		Log.d(LOGTAG, account.getJid() + ": connecting");
		lastConnect = SystemClock.elapsedRealtime();
		this.attempt++;
		try {
			shouldAuthenticate = shouldBind = !account
					.isOptionSet(Account.OPTION_REGISTER);
			tagReader = new XmlReader(wakeLock);
			tagWriter = new TagWriter();
			packetCallbacks.clear();
			this.changeStatus(Account.STATUS_CONNECTING);
			Bundle namePort = DNSHelper.getSRVRecord(account.getServer());
			if ("timeout".equals(namePort.getString("error"))) {
				Log.d(LOGTAG, account.getJid() + ": dns timeout");
				this.changeStatus(Account.STATUS_OFFLINE);
				return;
			}
			String srvRecordServer = namePort.getString("name");
			String srvIpServer = namePort.getString("ipv4");
			int srvRecordPort = namePort.getInt("port");
			if (srvRecordServer != null) {
				if (srvIpServer != null) {
					Log.d(LOGTAG, account.getJid() + ": using values from dns "
							+ srvRecordServer + "[" + srvIpServer + "]:"
							+ srvRecordPort);
					socket = new Socket(srvIpServer, srvRecordPort);
				} else {
					Log.d(LOGTAG, account.getJid() + ": using values from dns "
							+ srvRecordServer + ":" + srvRecordPort);
					socket = new Socket(srvRecordServer, srvRecordPort);
				}
			} else {
				socket = new Socket(account.getServer(), 5222);
			}
			OutputStream out = socket.getOutputStream();
			tagWriter.setOutputStream(out);
			InputStream in = socket.getInputStream();
			tagReader.setInputStream(in);
			tagWriter.beginDocument();
			sendStartStream();
			Tag nextTag;
			while ((nextTag = tagReader.readTag()) != null) {
				if (nextTag.isStart("stream")) {
					processStream(nextTag);
					break;
				} else {
					Log.d(LOGTAG, "found unexpected tag: " + nextTag.getName());
					return;
				}
			}
			if (socket.isConnected()) {
				socket.close();
			}
		} catch (UnknownHostException e) {
			this.changeStatus(Account.STATUS_SERVER_NOT_FOUND);
			if (wakeLock.isHeld()) {
				try { wakeLock.release();} catch (RuntimeException re) {}
			}
			return;
		} catch (IOException e) {
			if (account.getStatus() != Account.STATUS_TLS_ERROR) {
				this.changeStatus(Account.STATUS_OFFLINE);
			}
			if (wakeLock.isHeld()) {
				try { wakeLock.release();} catch (RuntimeException re) {}
			}
			return;
		} catch (NoSuchAlgorithmException e) {
			this.changeStatus(Account.STATUS_OFFLINE);
			Log.d(LOGTAG, "compression exception " + e.getMessage());
			if (wakeLock.isHeld()) {
				try { wakeLock.release();} catch (RuntimeException re) {}
			}
			return;
		} catch (XmlPullParserException e) {
			this.changeStatus(Account.STATUS_OFFLINE);
			Log.d(LOGTAG, "xml exception " + e.getMessage());
			if (wakeLock.isHeld()) {
				try { wakeLock.release();} catch (RuntimeException re) {}
			}
			return;
		}

	}

	@Override
	public void run() {
		connect();
	}

	private void processStream(Tag currentTag) throws XmlPullParserException,
			IOException, NoSuchAlgorithmException {
		Tag nextTag = tagReader.readTag();
		while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
			if (nextTag.isStart("error")) {
				processStreamError(nextTag);
			} else if (nextTag.isStart("features")) {
				processStreamFeatures(nextTag);
				if ((streamFeatures.getChildren().size() == 1)
						&& (streamFeatures.hasChild("starttls"))
						&& (!account.isOptionSet(Account.OPTION_USETLS))) {
					changeStatus(Account.STATUS_SERVER_REQUIRES_TLS);
				}
			} else if (nextTag.isStart("proceed")) {
				switchOverToTls(nextTag);
			} else if (nextTag.isStart("compressed")) {
				switchOverToZLib(nextTag);
			} else if (nextTag.isStart("success")) {
				Log.d(LOGTAG, account.getJid() + ": logged in");
				tagReader.readTag();
				tagReader.reset();
				sendStartStream();
				processStream(tagReader.readTag());
				break;
			} else if (nextTag.isStart("failure")) {
				tagReader.readElement(nextTag);
				changeStatus(Account.STATUS_UNAUTHORIZED);
			} else if (nextTag.isStart("challenge")) {
				String challange = tagReader.readElement(nextTag).getContent();
				Element response = new Element("response");
				response.setAttribute("xmlns",
						"urn:ietf:params:xml:ns:xmpp-sasl");
				response.setContent(CryptoHelper.saslDigestMd5(account,
						challange,mRandom));
				tagWriter.writeElement(response);
			} else if (nextTag.isStart("enabled")) {
				this.stanzasSent = 0;
				Element enabled = tagReader.readElement(nextTag);
				if ("true".equals(enabled.getAttribute("resume"))) {
					this.streamId = enabled.getAttribute("id");
					Log.d(LOGTAG, account.getJid() + ": stream managment("
							+ smVersion + ") enabled (resumable)");
				} else {
					Log.d(LOGTAG, account.getJid() + ": stream managment("
							+ smVersion + ") enabled");
				}
				this.lastSessionStarted = SystemClock.elapsedRealtime();
				this.stanzasReceived = 0;
				RequestPacket r = new RequestPacket(smVersion);
				tagWriter.writeStanzaAsync(r);
			} else if (nextTag.isStart("resumed")) {
				lastPaketReceived = SystemClock.elapsedRealtime();
				Log.d(LOGTAG, account.getJid() + ": session resumed");
				tagReader.readElement(nextTag);
				sendPing();
				changeStatus(Account.STATUS_ONLINE);
			} else if (nextTag.isStart("r")) {
				tagReader.readElement(nextTag);
				AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
				tagWriter.writeStanzaAsync(ack);
			} else if (nextTag.isStart("a")) {
				Element ack = tagReader.readElement(nextTag);
				lastPaketReceived = SystemClock.elapsedRealtime();
				int serverSequence = Integer.parseInt(ack.getAttribute("h"));
				if (serverSequence > this.stanzasSent) {
					this.stanzasSent = serverSequence;
				}
			} else if (nextTag.isStart("failed")) {
				tagReader.readElement(nextTag);
				Log.d(LOGTAG, account.getJid() + ": resumption failed");
				streamId = null;
				if (account.getStatus() != Account.STATUS_ONLINE) {
					sendBindRequest();
				}
			} else if (nextTag.isStart("iq")) {
				processIq(nextTag);
			} else if (nextTag.isStart("message")) {
				processMessage(nextTag);
			} else if (nextTag.isStart("presence")) {
				processPresence(nextTag);
			}
			nextTag = tagReader.readTag();
		}
		if (account.getStatus() == Account.STATUS_ONLINE) {
			account.setStatus(Account.STATUS_OFFLINE);
			if (statusListener != null) {
				statusListener.onStatusChanged(account);
			}
		}
	}

	private Element processPacket(Tag currentTag, int packetType)
			throws XmlPullParserException, IOException {
		Element element;
		switch (packetType) {
		case PACKET_IQ:
			element = new IqPacket();
			break;
		case PACKET_MESSAGE:
			element = new MessagePacket();
			break;
		case PACKET_PRESENCE:
			element = new PresencePacket();
			break;
		default:
			return null;
		}
		element.setAttributes(currentTag.getAttributes());
		Tag nextTag = tagReader.readTag();
		if (nextTag==null) {
			throw new IOException("interrupted mid tag");
		}
		while (!nextTag.isEnd(element.getName())) {
			if (!nextTag.isNo()) {
				Element child = tagReader.readElement(nextTag);
				if ((packetType == PACKET_IQ)
						&& ("jingle".equals(child.getName()))) {
					element = new JinglePacket();
					element.setAttributes(currentTag.getAttributes());
				}
				element.addChild(child);
			}
			nextTag = tagReader.readTag();
			if (nextTag==null) {
				throw new IOException("interrupted mid tag");
			}
		}
		++stanzasReceived;
		lastPaketReceived = SystemClock.elapsedRealtime();
		return element;
	}

	private void processIq(Tag currentTag) throws XmlPullParserException,
			IOException {
		IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);

		if (packet.getId() == null) {
			return; // an iq packet without id is definitely invalid
		}

		if (packet instanceof JinglePacket) {
			if (this.jingleListener != null) {
				this.jingleListener.onJinglePacketReceived(account,
						(JinglePacket) packet);
			}
		} else {
			if (packetCallbacks.containsKey(packet.getId())) {
				if (packetCallbacks.get(packet.getId()) instanceof OnIqPacketReceived) {
					((OnIqPacketReceived) packetCallbacks.get(packet.getId()))
							.onIqPacketReceived(account, packet);
				}

				packetCallbacks.remove(packet.getId());
			} else if (this.unregisteredIqListener != null) {
				this.unregisteredIqListener.onIqPacketReceived(account, packet);
			}
		}
	}

	private void processMessage(Tag currentTag) throws XmlPullParserException,
			IOException {
		MessagePacket packet = (MessagePacket) processPacket(currentTag,
				PACKET_MESSAGE);
		String id = packet.getAttribute("id");
		if ((id != null) && (packetCallbacks.containsKey(id))) {
			if (packetCallbacks.get(id) instanceof OnMessagePacketReceived) {
				((OnMessagePacketReceived) packetCallbacks.get(id))
						.onMessagePacketReceived(account, packet);
			}
			packetCallbacks.remove(id);
		} else if (this.messageListener != null) {
			this.messageListener.onMessagePacketReceived(account, packet);
		}
	}

	private void processPresence(Tag currentTag) throws XmlPullParserException,
			IOException {
		PresencePacket packet = (PresencePacket) processPacket(currentTag,
				PACKET_PRESENCE);
		String id = packet.getAttribute("id");
		if ((id != null) && (packetCallbacks.containsKey(id))) {
			if (packetCallbacks.get(id) instanceof OnPresencePacketReceived) {
				((OnPresencePacketReceived) packetCallbacks.get(id))
						.onPresencePacketReceived(account, packet);
			}
			packetCallbacks.remove(id);
		} else if (this.presenceListener != null) {
			this.presenceListener.onPresencePacketReceived(account, packet);
		}
	}

	private void sendCompressionZlib() throws IOException {
		Element compress = new Element("compress");
		compress.setAttribute("xmlns", "http://jabber.org/protocol/compress");
		compress.addChild("method").setContent("zlib");
		tagWriter.writeElement(compress);
	}

	private void switchOverToZLib(Tag currentTag)
			throws XmlPullParserException, IOException,
			NoSuchAlgorithmException {
		tagReader.readTag(); // read tag close

		tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
				.getOutputStream()));
		tagReader
				.setInputStream(new ZLibInputStream(tagReader.getInputStream()));

		sendStartStream();
		Log.d(LOGTAG, account.getJid() + ": compression enabled");
		processStream(tagReader.readTag());
	}

	private void sendStartTLS() throws IOException {
		Tag startTLS = Tag.empty("starttls");
		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
		tagWriter.writeTag(startTLS);
	}

	private void switchOverToTls(Tag currentTag) throws XmlPullParserException,
			IOException {
		tagReader.readTag();
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			TrustManagerFactory tmf = TrustManagerFactory
					.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			try {
				tmf.init((KeyStore) null);
			} catch (KeyStoreException e1) {
				e1.printStackTrace();
			}

			TrustManager[] trustManagers = tmf.getTrustManagers();
			final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];

			TrustManager[] wrappedTrustManagers = new TrustManager[] { new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
					origTrustmanager.checkClientTrusted(chain, authType);
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
					try {
						origTrustmanager.checkServerTrusted(chain, authType);
					} catch (CertificateException e) {
						if (e.getCause() instanceof CertPathValidatorException) {
							String sha;
							try {
								MessageDigest sha1 = MessageDigest
										.getInstance("SHA1");
								sha1.update(chain[0].getEncoded());
								sha = CryptoHelper.bytesToHex(sha1.digest());
								if (!sha.equals(account.getSSLFingerprint())) {
									changeStatus(Account.STATUS_TLS_ERROR);
									if (tlsListener != null) {
										tlsListener.onTLSExceptionReceived(sha,
												account);
									}
									throw new CertificateException();
								}
							} catch (NoSuchAlgorithmException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						} else {
							throw new CertificateException();
						}
					}
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return origTrustmanager.getAcceptedIssuers();
				}

			} };
			sc.init(null, wrappedTrustManagers, null);
			SSLSocketFactory factory = sc.getSocketFactory();
			SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,
					socket.getInetAddress().getHostAddress(), socket.getPort(),
					true);
			tagReader.setInputStream(sslSocket.getInputStream());
			tagWriter.setOutputStream(sslSocket.getOutputStream());
			sendStartStream();
			Log.d(LOGTAG, account.getJid() + ": TLS connection established");
			processStream(tagReader.readTag());
			sslSocket.close();
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void sendSaslAuthPlain() throws IOException {
		String saslString = CryptoHelper.saslPlain(account.getUsername(),
				account.getPassword());
		Element auth = new Element("auth");
		auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
		auth.setAttribute("mechanism", "PLAIN");
		auth.setContent(saslString);
		tagWriter.writeElement(auth);
	}

	private void sendSaslAuthDigestMd5() throws IOException {
		Element auth = new Element("auth");
		auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
		auth.setAttribute("mechanism", "DIGEST-MD5");
		tagWriter.writeElement(auth);
	}

	private void processStreamFeatures(Tag currentTag)
			throws XmlPullParserException, IOException {
		this.streamFeatures = tagReader.readElement(currentTag);
		if (this.streamFeatures.hasChild("starttls")
				&& account.isOptionSet(Account.OPTION_USETLS)) {
			sendStartTLS();
		} else if (compressionAvailable()) {
			sendCompressionZlib();
		} else if (this.streamFeatures.hasChild("register")
				&& (account.isOptionSet(Account.OPTION_REGISTER))) {
			sendRegistryRequest();
		} else if (!this.streamFeatures.hasChild("register")
				&& (account.isOptionSet(Account.OPTION_REGISTER))) {
			changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED);
			disconnect(true);
		} else if (this.streamFeatures.hasChild("mechanisms")
				&& shouldAuthenticate) {
			List<String> mechanisms = extractMechanisms(streamFeatures
					.findChild("mechanisms"));
			if (mechanisms.contains("PLAIN")) {
				sendSaslAuthPlain();
			} else if (mechanisms.contains("DIGEST-MD5")) {
				sendSaslAuthDigestMd5();
			}
		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
				+ smVersion)
				&& streamId != null) {
			ResumePacket resume = new ResumePacket(this.streamId,
					stanzasReceived, smVersion);
			this.tagWriter.writeStanzaAsync(resume);
		} else if (this.streamFeatures.hasChild("bind") && shouldBind) {
			sendBindRequest();
		}
	}

	private boolean compressionAvailable() {
		if (!this.streamFeatures.hasChild("compression",
				"http://jabber.org/features/compress"))
			return false;
		if (!ZLibOutputStream.SUPPORTED)
			return false;
		if (!account.isOptionSet(Account.OPTION_USECOMPRESSION))
			return false;

		Element compression = this.streamFeatures.findChild("compression",
				"http://jabber.org/features/compress");
		for (Element child : compression.getChildren()) {
			if (!"method".equals(child.getName()))
				continue;

			if ("zlib".equalsIgnoreCase(child.getContent())) {
				return true;
			}
		}
		return false;
	}

	private List<String> extractMechanisms(Element stream) {
		ArrayList<String> mechanisms = new ArrayList<String>(stream
				.getChildren().size());
		for (Element child : stream.getChildren()) {
			mechanisms.add(child.getContent());
		}
		return mechanisms;
	}

	private void sendRegistryRequest() {
		IqPacket register = new IqPacket(IqPacket.TYPE_GET);
		register.query("jabber:iq:register");
		register.setTo(account.getServer());
		sendIqPacket(register, new OnIqPacketReceived() {

			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				Element instructions = packet.query().findChild("instructions");
				if (packet.query().hasChild("username")
						&& (packet.query().hasChild("password"))) {
					IqPacket register = new IqPacket(IqPacket.TYPE_SET);
					Element username = new Element("username")
							.setContent(account.getUsername());
					Element password = new Element("password")
							.setContent(account.getPassword());
					register.query("jabber:iq:register").addChild(username);
					register.query().addChild(password);
					sendIqPacket(register, new OnIqPacketReceived() {

						@Override
						public void onIqPacketReceived(Account account,
								IqPacket packet) {
							if (packet.getType() == IqPacket.TYPE_RESULT) {
								account.setOption(Account.OPTION_REGISTER,
										false);
								changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
							} else if (packet.hasChild("error")
									&& (packet.findChild("error")
											.hasChild("conflict"))) {
								changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
							} else {
								changeStatus(Account.STATUS_REGISTRATION_FAILED);
								Log.d(LOGTAG, packet.toString());
							}
							disconnect(true);
						}
					});
				} else {
					changeStatus(Account.STATUS_REGISTRATION_FAILED);
					disconnect(true);
					Log.d(LOGTAG, account.getJid()
							+ ": could not register. instructions are"
							+ instructions.getContent());
				}
			}
		});
	}

	private void sendBindRequest() throws IOException {
		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
				.addChild("resource").setContent(account.getResource());
		this.sendUnboundIqPacket(iq, new OnIqPacketReceived() {
			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				String resource = packet.findChild("bind").findChild("jid")
						.getContent().split("/")[1];
				account.setResource(resource);
				if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
					smVersion = 3;
					EnablePacket enable = new EnablePacket(smVersion);
					tagWriter.writeStanzaAsync(enable);
				} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
					smVersion = 2;
					EnablePacket enable = new EnablePacket(smVersion);
					tagWriter.writeStanzaAsync(enable);
				}
				sendServiceDiscoveryInfo(account.getServer());
				sendServiceDiscoveryItems(account.getServer());
				if (bindListener != null) {
					bindListener.onBind(account);
				}

				changeStatus(Account.STATUS_ONLINE);
			}
		});
		if (this.streamFeatures.hasChild("session")) {
			Log.d(LOGTAG, account.getJid() + ": sending deprecated session");
			IqPacket startSession = new IqPacket(IqPacket.TYPE_SET);
			startSession.addChild("session",
					"urn:ietf:params:xml:ns:xmpp-session");
			this.sendUnboundIqPacket(startSession, null);
		}
	}

	private void sendServiceDiscoveryInfo(final String server) {
		IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
		iq.setTo(server);
		iq.query("http://jabber.org/protocol/disco#info");
		this.sendIqPacket(iq, new OnIqPacketReceived() {

			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				List<Element> elements = packet.query().getChildren();
				List<String> features = new ArrayList<String>();
				for (int i = 0; i < elements.size(); ++i) {
					if (elements.get(i).getName().equals("feature")) {
						features.add(elements.get(i).getAttribute("var"));
					}
				}
				disco.put(server, features);

				if (account.getServer().equals(server)) {
					enableAdvancedStreamFeatures();
				}
			}
		});
	}

	private void enableAdvancedStreamFeatures() {
		if (hasFeaturesCarbon()) {
			sendEnableCarbons();
		}
	}

	private void sendServiceDiscoveryItems(final String server) {
		IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
		iq.setTo(server);
		iq.query("http://jabber.org/protocol/disco#items");
		this.sendIqPacket(iq, new OnIqPacketReceived() {

			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				List<Element> elements = packet.query().getChildren();
				for (int i = 0; i < elements.size(); ++i) {
					if (elements.get(i).getName().equals("item")) {
						String jid = elements.get(i).getAttribute("jid");
						sendServiceDiscoveryInfo(jid);
					}
				}
			}
		});
	}

	private void sendEnableCarbons() {
		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
		iq.addChild("enable", "urn:xmpp:carbons:2");
		this.sendIqPacket(iq, new OnIqPacketReceived() {

			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				if (!packet.hasChild("error")) {
					Log.d(LOGTAG, account.getJid()
							+ ": successfully enabled carbons");
				} else {
					Log.d(LOGTAG, account.getJid()
							+ ": error enableing carbons " + packet.toString());
				}
			}
		});
	}

	private void processStreamError(Tag currentTag) {
		Log.d(LOGTAG, "processStreamError");
	}

	private void sendStartStream() throws IOException {
		Tag stream = Tag.start("stream:stream");
		stream.setAttribute("from", account.getJid());
		stream.setAttribute("to", account.getServer());
		stream.setAttribute("version", "1.0");
		stream.setAttribute("xml:lang", "en");
		stream.setAttribute("xmlns", "jabber:client");
		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
		tagWriter.writeTag(stream);
	}

	private String nextRandomId() {
		return new BigInteger(50, mRandom).toString(32);
	}

	public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) {
		if (packet.getId() == null) {
			String id = nextRandomId();
			packet.setAttribute("id", id);
		}
		packet.setFrom(account.getFullJid());
		this.sendPacket(packet, callback);
	}

	public void sendUnboundIqPacket(IqPacket packet, OnIqPacketReceived callback) {
		if (packet.getId() == null) {
			String id = nextRandomId();
			packet.setAttribute("id", id);
		}
		this.sendPacket(packet, callback);
	}

	public void sendMessagePacket(MessagePacket packet) {
		this.sendPacket(packet, null);
	}

	public void sendMessagePacket(MessagePacket packet,
			OnMessagePacketReceived callback) {
		this.sendPacket(packet, callback);
	}

	public void sendPresencePacket(PresencePacket packet) {
		this.sendPacket(packet, null);
	}

	public void sendPresencePacket(PresencePacket packet,
			OnPresencePacketReceived callback) {
		this.sendPacket(packet, callback);
	}

	private synchronized void sendPacket(final AbstractStanza packet,
			PacketReceived callback) {
		// TODO dont increment stanza count if packet = request packet or ack;
		++stanzasSent;
		tagWriter.writeStanzaAsync(packet);
		if (callback != null) {
			if (packet.getId() == null) {
				packet.setId(nextRandomId());
			}
			packetCallbacks.put(packet.getId(), callback);
		}
	}

	public void sendPing() {
		if (streamFeatures.hasChild("sm")) {
			tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
		} else {
			IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
			iq.setFrom(account.getFullJid());
			iq.addChild("ping", "urn:xmpp:ping");
			this.sendIqPacket(iq, null);
		}
	}

	public void setOnMessagePacketReceivedListener(
			OnMessagePacketReceived listener) {
		this.messageListener = listener;
	}

	public void setOnUnregisteredIqPacketReceivedListener(
			OnIqPacketReceived listener) {
		this.unregisteredIqListener = listener;
	}

	public void setOnPresencePacketReceivedListener(
			OnPresencePacketReceived listener) {
		this.presenceListener = listener;
	}

	public void setOnJinglePacketReceivedListener(
			OnJinglePacketReceived listener) {
		this.jingleListener = listener;
	}

	public void setOnStatusChangedListener(OnStatusChanged listener) {
		this.statusListener = listener;
	}

	public void setOnTLSExceptionReceivedListener(
			OnTLSExceptionReceived listener) {
		this.tlsListener = listener;
	}

	public void setOnBindListener(OnBindListener listener) {
		this.bindListener = listener;
	}

	public void disconnect(boolean force) {
		changeStatus(Account.STATUS_OFFLINE);
		Log.d(LOGTAG, "disconnecting");
		try {
			if (force) {
				socket.close();
				return;
			}
			new Thread(new Runnable() {

				@Override
				public void run() {
					if (tagWriter.isActive()) {
						tagWriter.finish();
						try {
							while (!tagWriter.finished()) {
								Log.d(LOGTAG, "not yet finished");
								Thread.sleep(100);
							}
							tagWriter.writeTag(Tag.end("stream:stream"));
						} catch (IOException e) {
							Log.d(LOGTAG, "io exception during disconnect");
						} catch (InterruptedException e) {
							Log.d(LOGTAG, "interrupted");
						}
					}
				}
			}).start();
		} catch (IOException e) {
			Log.d(LOGTAG, "io exception during disconnect");
		}
	}

	public boolean hasFeatureRosterManagment() {
		if (this.streamFeatures == null) {
			return false;
		} else {
			return this.streamFeatures.hasChild("ver");
		}
	}

	public boolean hasFeatureStreamManagment() {
		if (this.streamFeatures == null) {
			return false;
		} else {
			return this.streamFeatures.hasChild("sm");
		}
	}

	public boolean hasFeaturesCarbon() {
		return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
	}

	public boolean hasDiscoFeature(String server, String feature) {
		if (!disco.containsKey(server)) {
			return false;
		}
		return disco.get(server).contains(feature);
	}

	public List<String> findDiscoItemsByFeature(String feature) {
		List<String> items = new ArrayList<String>();
		Iterator<Entry<String, List<String>>> it = this.disco.entrySet()
				.iterator();
		while (it.hasNext()) {
			Entry<String, List<String>> pairs = it.next();
			if (pairs.getValue().contains(feature)) {
				items.add(pairs.getKey());
			}
			it.remove();
		}
		return items;
	}
	
	public String findDiscoItemByFeature(String feature) {
		List<String> items = findDiscoItemsByFeature(feature);
		if (items.size()>=1) {
			return items.get(0);
		}
		return null;
	}

	public void r() {
		this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
	}

	public int getReceivedStanzas() {
		return this.stanzasReceived;
	}

	public int getSentStanzas() {
		return this.stanzasSent;
	}

	public String getMucServer() {
		return findDiscoItemByFeature("http://jabber.org/protocol/muc");
	}

	public int getTimeToNextAttempt() {
		int interval = (int) (25 * Math.pow(1.5, attempt));
		int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
		return interval - secondsSinceLast;
	}

	public int getAttempt() {
		return this.attempt;
	}
}