XmppConnection.java

  1package eu.siacs.conversations.xmpp;
  2
  3import java.io.IOException;
  4import java.io.InputStream;
  5import java.io.OutputStream;
  6import java.math.BigInteger;
  7import java.net.Socket;
  8import java.net.UnknownHostException;
  9import java.security.KeyManagementException;
 10import java.security.NoSuchAlgorithmException;
 11import java.security.SecureRandom;
 12import java.util.ArrayList;
 13import java.util.HashMap;
 14import java.util.Hashtable;
 15import java.util.List;
 16import java.util.Map.Entry;
 17
 18import javax.net.ssl.HostnameVerifier;
 19import javax.net.ssl.SSLContext;
 20import javax.net.ssl.SSLSocket;
 21import javax.net.ssl.SSLSocketFactory;
 22
 23import javax.net.ssl.X509TrustManager;
 24
 25import org.xmlpull.v1.XmlPullParserException;
 26
 27import de.duenndns.ssl.MemorizingTrustManager;
 28
 29import android.os.Bundle;
 30import android.os.PowerManager;
 31import android.os.PowerManager.WakeLock;
 32import android.os.SystemClock;
 33import android.util.Log;
 34import eu.siacs.conversations.entities.Account;
 35import eu.siacs.conversations.services.XmppConnectionService;
 36import eu.siacs.conversations.utils.CryptoHelper;
 37import eu.siacs.conversations.utils.DNSHelper;
 38import eu.siacs.conversations.utils.zlib.ZLibOutputStream;
 39import eu.siacs.conversations.utils.zlib.ZLibInputStream;
 40import eu.siacs.conversations.xml.Element;
 41import eu.siacs.conversations.xml.Tag;
 42import eu.siacs.conversations.xml.TagWriter;
 43import eu.siacs.conversations.xml.XmlReader;
 44import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 45import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 46import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
 47import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 48import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 49import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 50import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
 51import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
 52import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 53import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 54
 55public class XmppConnection implements Runnable {
 56
 57	protected Account account;
 58	private static final String LOGTAG = "xmppService";
 59
 60	private WakeLock wakeLock;
 61
 62	private SecureRandom mRandom;
 63
 64	private Socket socket;
 65	private XmlReader tagReader;
 66	private TagWriter tagWriter;
 67	
 68	private Features features = new Features(this);
 69
 70	private boolean shouldBind = true;
 71	private boolean shouldAuthenticate = true;
 72	private Element streamFeatures;
 73	private HashMap<String, List<String>> disco = new HashMap<String, List<String>>();
 74
 75	private String streamId = null;
 76	private int smVersion = 3;
 77
 78	private int stanzasReceived = 0;
 79	private int stanzasSent = 0;
 80
 81	public long lastPaketReceived = 0;
 82	public long lastPingSent = 0;
 83	public long lastConnect = 0;
 84	public long lastSessionStarted = 0;
 85
 86	private int attempt = 0;
 87
 88	private static final int PACKET_IQ = 0;
 89	private static final int PACKET_MESSAGE = 1;
 90	private static final int PACKET_PRESENCE = 2;
 91
 92	private Hashtable<String, PacketReceived> packetCallbacks = new Hashtable<String, PacketReceived>();
 93	private OnPresencePacketReceived presenceListener = null;
 94	private OnJinglePacketReceived jingleListener = null;
 95	private OnIqPacketReceived unregisteredIqListener = null;
 96	private OnMessagePacketReceived messageListener = null;
 97	private OnStatusChanged statusListener = null;
 98	private OnBindListener bindListener = null;
 99	private MemorizingTrustManager mMemorizingTrustManager;
100
101	public XmppConnection(Account account, XmppConnectionService service) {
102		this.mRandom = service.getRNG();
103		this.mMemorizingTrustManager = service.getMemorizingTrustManager();
104		this.account = account;
105		this.wakeLock = service.getPowerManager().newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
106				account.getJid());
107		tagWriter = new TagWriter();
108	}
109
110	protected void changeStatus(int nextStatus) {
111		if (account.getStatus() != nextStatus) {
112			if ((nextStatus == Account.STATUS_OFFLINE)
113					&& (account.getStatus() != Account.STATUS_CONNECTING)
114					&& (account.getStatus() != Account.STATUS_ONLINE)
115					&& (account.getStatus() != Account.STATUS_DISABLED)) {
116				return;
117			}
118			if (nextStatus == Account.STATUS_ONLINE) {
119				this.attempt = 0;
120			}
121			account.setStatus(nextStatus);
122			if (statusListener != null) {
123				statusListener.onStatusChanged(account);
124			}
125		}
126	}
127
128	protected void connect() {
129		Log.d(LOGTAG, account.getJid() + ": connecting");
130		lastConnect = SystemClock.elapsedRealtime();
131		this.attempt++;
132		try {
133			shouldAuthenticate = shouldBind = !account
134					.isOptionSet(Account.OPTION_REGISTER);
135			tagReader = new XmlReader(wakeLock);
136			tagWriter = new TagWriter();
137			packetCallbacks.clear();
138			this.changeStatus(Account.STATUS_CONNECTING);
139			Bundle namePort = DNSHelper.getSRVRecord(account.getServer());
140			if ("timeout".equals(namePort.getString("error"))) {
141				Log.d(LOGTAG, account.getJid() + ": dns timeout");
142				this.changeStatus(Account.STATUS_OFFLINE);
143				return;
144			}
145			String srvRecordServer = namePort.getString("name");
146			String srvIpServer = namePort.getString("ipv4");
147			int srvRecordPort = namePort.getInt("port");
148			if (srvRecordServer != null) {
149				if (srvIpServer != null) {
150					Log.d(LOGTAG, account.getJid() + ": using values from dns "
151							+ srvRecordServer + "[" + srvIpServer + "]:"
152							+ srvRecordPort);
153					socket = new Socket(srvIpServer, srvRecordPort);
154				} else {
155					Log.d(LOGTAG, account.getJid() + ": using values from dns "
156							+ srvRecordServer + ":" + srvRecordPort);
157					socket = new Socket(srvRecordServer, srvRecordPort);
158				}
159			} else {
160				socket = new Socket(account.getServer(), 5222);
161			}
162			OutputStream out = socket.getOutputStream();
163			tagWriter.setOutputStream(out);
164			InputStream in = socket.getInputStream();
165			tagReader.setInputStream(in);
166			tagWriter.beginDocument();
167			sendStartStream();
168			Tag nextTag;
169			while ((nextTag = tagReader.readTag()) != null) {
170				if (nextTag.isStart("stream")) {
171					processStream(nextTag);
172					break;
173				} else {
174					Log.d(LOGTAG, "found unexpected tag: " + nextTag.getName());
175					return;
176				}
177			}
178			if (socket.isConnected()) {
179				socket.close();
180			}
181		} catch (UnknownHostException e) {
182			this.changeStatus(Account.STATUS_SERVER_NOT_FOUND);
183			if (wakeLock.isHeld()) {
184				try { wakeLock.release();} catch (RuntimeException re) {}
185			}
186			return;
187		} catch (IOException e) {
188			this.changeStatus(Account.STATUS_OFFLINE);
189			if (wakeLock.isHeld()) {
190				try { wakeLock.release();} catch (RuntimeException re) {}
191			}
192			return;
193		} catch (NoSuchAlgorithmException e) {
194			this.changeStatus(Account.STATUS_OFFLINE);
195			Log.d(LOGTAG, "compression exception " + e.getMessage());
196			if (wakeLock.isHeld()) {
197				try { wakeLock.release();} catch (RuntimeException re) {}
198			}
199			return;
200		} catch (XmlPullParserException e) {
201			this.changeStatus(Account.STATUS_OFFLINE);
202			Log.d(LOGTAG, "xml exception " + e.getMessage());
203			if (wakeLock.isHeld()) {
204				try { wakeLock.release();} catch (RuntimeException re) {}
205			}
206			return;
207		}
208
209	}
210
211	@Override
212	public void run() {
213		connect();
214	}
215
216	private void processStream(Tag currentTag) throws XmlPullParserException,
217			IOException, NoSuchAlgorithmException {
218		Tag nextTag = tagReader.readTag();
219		while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
220			if (nextTag.isStart("error")) {
221				processStreamError(nextTag);
222			} else if (nextTag.isStart("features")) {
223				processStreamFeatures(nextTag);
224				if ((streamFeatures.getChildren().size() == 1)
225						&& (streamFeatures.hasChild("starttls"))
226						&& (!account.isOptionSet(Account.OPTION_USETLS))) {
227					changeStatus(Account.STATUS_SERVER_REQUIRES_TLS);
228				}
229			} else if (nextTag.isStart("proceed")) {
230				switchOverToTls(nextTag);
231			} else if (nextTag.isStart("compressed")) {
232				switchOverToZLib(nextTag);
233			} else if (nextTag.isStart("success")) {
234				Log.d(LOGTAG, account.getJid() + ": logged in");
235				tagReader.readTag();
236				tagReader.reset();
237				sendStartStream();
238				processStream(tagReader.readTag());
239				break;
240			} else if (nextTag.isStart("failure")) {
241				tagReader.readElement(nextTag);
242				changeStatus(Account.STATUS_UNAUTHORIZED);
243			} else if (nextTag.isStart("challenge")) {
244				String challange = tagReader.readElement(nextTag).getContent();
245				Element response = new Element("response");
246				response.setAttribute("xmlns",
247						"urn:ietf:params:xml:ns:xmpp-sasl");
248				response.setContent(CryptoHelper.saslDigestMd5(account,
249						challange,mRandom));
250				tagWriter.writeElement(response);
251			} else if (nextTag.isStart("enabled")) {
252				this.stanzasSent = 0;
253				Element enabled = tagReader.readElement(nextTag);
254				if ("true".equals(enabled.getAttribute("resume"))) {
255					this.streamId = enabled.getAttribute("id");
256					Log.d(LOGTAG, account.getJid() + ": stream managment("
257							+ smVersion + ") enabled (resumable)");
258				} else {
259					Log.d(LOGTAG, account.getJid() + ": stream managment("
260							+ smVersion + ") enabled");
261				}
262				this.lastSessionStarted = SystemClock.elapsedRealtime();
263				this.stanzasReceived = 0;
264				RequestPacket r = new RequestPacket(smVersion);
265				tagWriter.writeStanzaAsync(r);
266			} else if (nextTag.isStart("resumed")) {
267				lastPaketReceived = SystemClock.elapsedRealtime();
268				Log.d(LOGTAG, account.getJid() + ": session resumed");
269				tagReader.readElement(nextTag);
270				sendPing();
271				changeStatus(Account.STATUS_ONLINE);
272			} else if (nextTag.isStart("r")) {
273				tagReader.readElement(nextTag);
274				AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
275				tagWriter.writeStanzaAsync(ack);
276			} else if (nextTag.isStart("a")) {
277				Element ack = tagReader.readElement(nextTag);
278				lastPaketReceived = SystemClock.elapsedRealtime();
279				int serverSequence = Integer.parseInt(ack.getAttribute("h"));
280				if (serverSequence > this.stanzasSent) {
281					this.stanzasSent = serverSequence;
282				}
283			} else if (nextTag.isStart("failed")) {
284				tagReader.readElement(nextTag);
285				Log.d(LOGTAG, account.getJid() + ": resumption failed");
286				streamId = null;
287				if (account.getStatus() != Account.STATUS_ONLINE) {
288					sendBindRequest();
289				}
290			} else if (nextTag.isStart("iq")) {
291				processIq(nextTag);
292			} else if (nextTag.isStart("message")) {
293				processMessage(nextTag);
294			} else if (nextTag.isStart("presence")) {
295				processPresence(nextTag);
296			}
297			nextTag = tagReader.readTag();
298		}
299		if (account.getStatus() == Account.STATUS_ONLINE) {
300			account.setStatus(Account.STATUS_OFFLINE);
301			if (statusListener != null) {
302				statusListener.onStatusChanged(account);
303			}
304		}
305	}
306
307	private Element processPacket(Tag currentTag, int packetType)
308			throws XmlPullParserException, IOException {
309		Element element;
310		switch (packetType) {
311		case PACKET_IQ:
312			element = new IqPacket();
313			break;
314		case PACKET_MESSAGE:
315			element = new MessagePacket();
316			break;
317		case PACKET_PRESENCE:
318			element = new PresencePacket();
319			break;
320		default:
321			return null;
322		}
323		element.setAttributes(currentTag.getAttributes());
324		Tag nextTag = tagReader.readTag();
325		if (nextTag==null) {
326			throw new IOException("interrupted mid tag");
327		}
328		while (!nextTag.isEnd(element.getName())) {
329			if (!nextTag.isNo()) {
330				Element child = tagReader.readElement(nextTag);
331				if ((packetType == PACKET_IQ)
332						&& ("jingle".equals(child.getName()))) {
333					element = new JinglePacket();
334					element.setAttributes(currentTag.getAttributes());
335				}
336				element.addChild(child);
337			}
338			nextTag = tagReader.readTag();
339			if (nextTag==null) {
340				throw new IOException("interrupted mid tag");
341			}
342		}
343		++stanzasReceived;
344		lastPaketReceived = SystemClock.elapsedRealtime();
345		return element;
346	}
347
348	private void processIq(Tag currentTag) throws XmlPullParserException,
349			IOException {
350		IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
351
352		if (packet.getId() == null) {
353			return; // an iq packet without id is definitely invalid
354		}
355
356		if (packet instanceof JinglePacket) {
357			if (this.jingleListener != null) {
358				this.jingleListener.onJinglePacketReceived(account,
359						(JinglePacket) packet);
360			}
361		} else {
362			if (packetCallbacks.containsKey(packet.getId())) {
363				if (packetCallbacks.get(packet.getId()) instanceof OnIqPacketReceived) {
364					((OnIqPacketReceived) packetCallbacks.get(packet.getId()))
365							.onIqPacketReceived(account, packet);
366				}
367
368				packetCallbacks.remove(packet.getId());
369			} else if (this.unregisteredIqListener != null) {
370				this.unregisteredIqListener.onIqPacketReceived(account, packet);
371			}
372		}
373	}
374
375	private void processMessage(Tag currentTag) throws XmlPullParserException,
376			IOException {
377		MessagePacket packet = (MessagePacket) processPacket(currentTag,
378				PACKET_MESSAGE);
379		String id = packet.getAttribute("id");
380		if ((id != null) && (packetCallbacks.containsKey(id))) {
381			if (packetCallbacks.get(id) instanceof OnMessagePacketReceived) {
382				((OnMessagePacketReceived) packetCallbacks.get(id))
383						.onMessagePacketReceived(account, packet);
384			}
385			packetCallbacks.remove(id);
386		} else if (this.messageListener != null) {
387			this.messageListener.onMessagePacketReceived(account, packet);
388		}
389	}
390
391	private void processPresence(Tag currentTag) throws XmlPullParserException,
392			IOException {
393		PresencePacket packet = (PresencePacket) processPacket(currentTag,
394				PACKET_PRESENCE);
395		String id = packet.getAttribute("id");
396		if ((id != null) && (packetCallbacks.containsKey(id))) {
397			if (packetCallbacks.get(id) instanceof OnPresencePacketReceived) {
398				((OnPresencePacketReceived) packetCallbacks.get(id))
399						.onPresencePacketReceived(account, packet);
400			}
401			packetCallbacks.remove(id);
402		} else if (this.presenceListener != null) {
403			this.presenceListener.onPresencePacketReceived(account, packet);
404		}
405	}
406
407	private void sendCompressionZlib() throws IOException {
408		Element compress = new Element("compress");
409		compress.setAttribute("xmlns", "http://jabber.org/protocol/compress");
410		compress.addChild("method").setContent("zlib");
411		tagWriter.writeElement(compress);
412	}
413
414	private void switchOverToZLib(Tag currentTag)
415			throws XmlPullParserException, IOException,
416			NoSuchAlgorithmException {
417		tagReader.readTag(); // read tag close
418
419		if (!tagWriter.isActive()) {
420			throw new IOException();
421		}
422		tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
423				.getOutputStream()));
424		if (tagReader.getInputStream() == null) {
425			throw new IOException();
426		}
427		tagReader
428				.setInputStream(new ZLibInputStream(tagReader.getInputStream()));
429
430		sendStartStream();
431		Log.d(LOGTAG, account.getJid() + ": compression enabled");
432		processStream(tagReader.readTag());
433	}
434
435	private void sendStartTLS() throws IOException {
436		Tag startTLS = Tag.empty("starttls");
437		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
438		tagWriter.writeTag(startTLS);
439	}
440
441	private void switchOverToTls(Tag currentTag) throws XmlPullParserException,
442			IOException {
443		tagReader.readTag();
444		try {
445			SSLContext sc = SSLContext.getInstance("TLS");
446			sc.init(null, new X509TrustManager[] { this.mMemorizingTrustManager }, mRandom);
447			SSLSocketFactory factory = sc.getSocketFactory();
448			
449			HostnameVerifier verifier = this.mMemorizingTrustManager.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier());
450			SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,
451					socket.getInetAddress().getHostAddress(), socket.getPort(),
452					true);
453			
454			if (verifier != null && !verifier.verify(account.getServer(), sslSocket.getSession())) {
455				Log.d(LOGTAG, account.getJid() + ": host mismatch in TLS connection");
456				sslSocket.close();
457				throw new IOException();
458			}
459			tagReader.setInputStream(sslSocket.getInputStream());
460			tagWriter.setOutputStream(sslSocket.getOutputStream());
461			sendStartStream();
462			Log.d(LOGTAG, account.getJid() + ": TLS connection established");
463			processStream(tagReader.readTag());
464			sslSocket.close();
465		} catch (NoSuchAlgorithmException e1) {
466			e1.printStackTrace();
467		} catch (KeyManagementException e) {
468			e.printStackTrace();
469		}
470	}
471
472	private void sendSaslAuthPlain() throws IOException {
473		String saslString = CryptoHelper.saslPlain(account.getUsername(),
474				account.getPassword());
475		Element auth = new Element("auth");
476		auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
477		auth.setAttribute("mechanism", "PLAIN");
478		auth.setContent(saslString);
479		tagWriter.writeElement(auth);
480	}
481
482	private void sendSaslAuthDigestMd5() throws IOException {
483		Element auth = new Element("auth");
484		auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
485		auth.setAttribute("mechanism", "DIGEST-MD5");
486		tagWriter.writeElement(auth);
487	}
488
489	private void processStreamFeatures(Tag currentTag)
490			throws XmlPullParserException, IOException {
491		this.streamFeatures = tagReader.readElement(currentTag);
492		if (this.streamFeatures.hasChild("starttls")
493				&& account.isOptionSet(Account.OPTION_USETLS)) {
494			sendStartTLS();
495		} else if (compressionAvailable()) {
496			sendCompressionZlib();
497		} else if (this.streamFeatures.hasChild("register")
498				&& (account.isOptionSet(Account.OPTION_REGISTER))) {
499			sendRegistryRequest();
500		} else if (!this.streamFeatures.hasChild("register")
501				&& (account.isOptionSet(Account.OPTION_REGISTER))) {
502			changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED);
503			disconnect(true);
504		} else if (this.streamFeatures.hasChild("mechanisms")
505				&& shouldAuthenticate) {
506			List<String> mechanisms = extractMechanisms(streamFeatures
507					.findChild("mechanisms"));
508			if (mechanisms.contains("PLAIN")) {
509				sendSaslAuthPlain();
510			} else if (mechanisms.contains("DIGEST-MD5")) {
511				sendSaslAuthDigestMd5();
512			}
513		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
514				+ smVersion)
515				&& streamId != null) {
516			ResumePacket resume = new ResumePacket(this.streamId,
517					stanzasReceived, smVersion);
518			this.tagWriter.writeStanzaAsync(resume);
519		} else if (this.streamFeatures.hasChild("bind") && shouldBind) {
520			sendBindRequest();
521		}
522	}
523
524	private boolean compressionAvailable() {
525		if (!this.streamFeatures.hasChild("compression",
526				"http://jabber.org/features/compress"))
527			return false;
528		if (!ZLibOutputStream.SUPPORTED)
529			return false;
530		if (!account.isOptionSet(Account.OPTION_USECOMPRESSION))
531			return false;
532
533		Element compression = this.streamFeatures.findChild("compression",
534				"http://jabber.org/features/compress");
535		for (Element child : compression.getChildren()) {
536			if (!"method".equals(child.getName()))
537				continue;
538
539			if ("zlib".equalsIgnoreCase(child.getContent())) {
540				return true;
541			}
542		}
543		return false;
544	}
545
546	private List<String> extractMechanisms(Element stream) {
547		ArrayList<String> mechanisms = new ArrayList<String>(stream
548				.getChildren().size());
549		for (Element child : stream.getChildren()) {
550			mechanisms.add(child.getContent());
551		}
552		return mechanisms;
553	}
554
555	private void sendRegistryRequest() {
556		IqPacket register = new IqPacket(IqPacket.TYPE_GET);
557		register.query("jabber:iq:register");
558		register.setTo(account.getServer());
559		sendIqPacket(register, new OnIqPacketReceived() {
560
561			@Override
562			public void onIqPacketReceived(Account account, IqPacket packet) {
563				Element instructions = packet.query().findChild("instructions");
564				if (packet.query().hasChild("username")
565						&& (packet.query().hasChild("password"))) {
566					IqPacket register = new IqPacket(IqPacket.TYPE_SET);
567					Element username = new Element("username")
568							.setContent(account.getUsername());
569					Element password = new Element("password")
570							.setContent(account.getPassword());
571					register.query("jabber:iq:register").addChild(username);
572					register.query().addChild(password);
573					sendIqPacket(register, new OnIqPacketReceived() {
574
575						@Override
576						public void onIqPacketReceived(Account account,
577								IqPacket packet) {
578							if (packet.getType() == IqPacket.TYPE_RESULT) {
579								account.setOption(Account.OPTION_REGISTER,
580										false);
581								changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
582							} else if (packet.hasChild("error")
583									&& (packet.findChild("error")
584											.hasChild("conflict"))) {
585								changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
586							} else {
587								changeStatus(Account.STATUS_REGISTRATION_FAILED);
588								Log.d(LOGTAG, packet.toString());
589							}
590							disconnect(true);
591						}
592					});
593				} else {
594					changeStatus(Account.STATUS_REGISTRATION_FAILED);
595					disconnect(true);
596					Log.d(LOGTAG, account.getJid()
597							+ ": could not register. instructions are"
598							+ instructions.getContent());
599				}
600			}
601		});
602	}
603
604	private void sendBindRequest() throws IOException {
605		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
606		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
607				.addChild("resource").setContent(account.getResource());
608		this.sendUnboundIqPacket(iq, new OnIqPacketReceived() {
609			@Override
610			public void onIqPacketReceived(Account account, IqPacket packet) {
611				Element bind = packet.findChild("bind");
612				if (bind!=null) {
613					Element jid = bind.findChild("jid");
614					if (jid!=null) {
615						account.setResource(jid.getContent().split("/")[1]);
616						if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
617							smVersion = 3;
618							EnablePacket enable = new EnablePacket(smVersion);
619							tagWriter.writeStanzaAsync(enable);
620						} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
621							smVersion = 2;
622							EnablePacket enable = new EnablePacket(smVersion);
623							tagWriter.writeStanzaAsync(enable);
624						}
625						sendServiceDiscoveryInfo(account.getServer());
626						sendServiceDiscoveryItems(account.getServer());
627						if (bindListener != null) {
628							bindListener.onBind(account);
629						}
630						changeStatus(Account.STATUS_ONLINE);
631					} else {
632						disconnect(true);
633					}
634				} else {
635					disconnect(true);
636				}
637			}
638		});
639		if (this.streamFeatures.hasChild("session")) {
640			Log.d(LOGTAG, account.getJid() + ": sending deprecated session");
641			IqPacket startSession = new IqPacket(IqPacket.TYPE_SET);
642			startSession.addChild("session",
643					"urn:ietf:params:xml:ns:xmpp-session");
644			this.sendUnboundIqPacket(startSession, null);
645		}
646	}
647
648	private void sendServiceDiscoveryInfo(final String server) {
649		IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
650		iq.setTo(server);
651		iq.query("http://jabber.org/protocol/disco#info");
652		this.sendIqPacket(iq, new OnIqPacketReceived() {
653
654			@Override
655			public void onIqPacketReceived(Account account, IqPacket packet) {
656				List<Element> elements = packet.query().getChildren();
657				List<String> features = new ArrayList<String>();
658				for (int i = 0; i < elements.size(); ++i) {
659					if (elements.get(i).getName().equals("feature")) {
660						features.add(elements.get(i).getAttribute("var"));
661					}
662				}
663				disco.put(server, features);
664
665				if (account.getServer().equals(server)) {
666					enableAdvancedStreamFeatures();
667				}
668			}
669		});
670	}
671
672	private void enableAdvancedStreamFeatures() {
673		if (getFeatures().carbons()) {
674			sendEnableCarbons();
675		}
676	}
677
678	private void sendServiceDiscoveryItems(final String server) {
679		IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
680		iq.setTo(server);
681		iq.query("http://jabber.org/protocol/disco#items");
682		this.sendIqPacket(iq, new OnIqPacketReceived() {
683
684			@Override
685			public void onIqPacketReceived(Account account, IqPacket packet) {
686				List<Element> elements = packet.query().getChildren();
687				for (int i = 0; i < elements.size(); ++i) {
688					if (elements.get(i).getName().equals("item")) {
689						String jid = elements.get(i).getAttribute("jid");
690						sendServiceDiscoveryInfo(jid);
691					}
692				}
693			}
694		});
695	}
696
697	private void sendEnableCarbons() {
698		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
699		iq.addChild("enable", "urn:xmpp:carbons:2");
700		this.sendIqPacket(iq, new OnIqPacketReceived() {
701
702			@Override
703			public void onIqPacketReceived(Account account, IqPacket packet) {
704				if (!packet.hasChild("error")) {
705					Log.d(LOGTAG, account.getJid()
706							+ ": successfully enabled carbons");
707				} else {
708					Log.d(LOGTAG, account.getJid()
709							+ ": error enableing carbons " + packet.toString());
710				}
711			}
712		});
713	}
714
715	private void processStreamError(Tag currentTag) {
716		Log.d(LOGTAG, "processStreamError");
717	}
718
719	private void sendStartStream() throws IOException {
720		Tag stream = Tag.start("stream:stream");
721		stream.setAttribute("from", account.getJid());
722		stream.setAttribute("to", account.getServer());
723		stream.setAttribute("version", "1.0");
724		stream.setAttribute("xml:lang", "en");
725		stream.setAttribute("xmlns", "jabber:client");
726		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
727		tagWriter.writeTag(stream);
728	}
729
730	private String nextRandomId() {
731		return new BigInteger(50, mRandom).toString(32);
732	}
733
734	public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) {
735		if (packet.getId() == null) {
736			String id = nextRandomId();
737			packet.setAttribute("id", id);
738		}
739		packet.setFrom(account.getFullJid());
740		this.sendPacket(packet, callback);
741	}
742
743	public void sendUnboundIqPacket(IqPacket packet, OnIqPacketReceived callback) {
744		if (packet.getId() == null) {
745			String id = nextRandomId();
746			packet.setAttribute("id", id);
747		}
748		this.sendPacket(packet, callback);
749	}
750
751	public void sendMessagePacket(MessagePacket packet) {
752		this.sendPacket(packet, null);
753	}
754
755	public void sendPresencePacket(PresencePacket packet) {
756		this.sendPacket(packet, null);
757	}
758	
759	private synchronized void sendPacket(final AbstractStanza packet,
760			PacketReceived callback) {
761		// TODO dont increment stanza count if packet = request packet or ack;
762		++stanzasSent;
763		tagWriter.writeStanzaAsync(packet);
764		if (callback != null) {
765			if (packet.getId() == null) {
766				packet.setId(nextRandomId());
767			}
768			packetCallbacks.put(packet.getId(), callback);
769		}
770	}
771
772	public void sendPing() {
773		if (streamFeatures.hasChild("sm")) {
774			tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
775		} else {
776			IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
777			iq.setFrom(account.getFullJid());
778			iq.addChild("ping", "urn:xmpp:ping");
779			this.sendIqPacket(iq, null);
780		}
781	}
782
783	public void setOnMessagePacketReceivedListener(
784			OnMessagePacketReceived listener) {
785		this.messageListener = listener;
786	}
787
788	public void setOnUnregisteredIqPacketReceivedListener(
789			OnIqPacketReceived listener) {
790		this.unregisteredIqListener = listener;
791	}
792
793	public void setOnPresencePacketReceivedListener(
794			OnPresencePacketReceived listener) {
795		this.presenceListener = listener;
796	}
797
798	public void setOnJinglePacketReceivedListener(
799			OnJinglePacketReceived listener) {
800		this.jingleListener = listener;
801	}
802
803	public void setOnStatusChangedListener(OnStatusChanged listener) {
804		this.statusListener = listener;
805	}
806
807	public void setOnBindListener(OnBindListener listener) {
808		this.bindListener = listener;
809	}
810
811	public void disconnect(boolean force) {
812		changeStatus(Account.STATUS_OFFLINE);
813		Log.d(LOGTAG, "disconnecting");
814		try {
815			if (force) {
816				socket.close();
817				return;
818			}
819			new Thread(new Runnable() {
820
821				@Override
822				public void run() {
823					if (tagWriter.isActive()) {
824						tagWriter.finish();
825						try {
826							while (!tagWriter.finished()) {
827								Log.d(LOGTAG, "not yet finished");
828								Thread.sleep(100);
829							}
830							tagWriter.writeTag(Tag.end("stream:stream"));
831						} catch (IOException e) {
832							Log.d(LOGTAG, "io exception during disconnect");
833						} catch (InterruptedException e) {
834							Log.d(LOGTAG, "interrupted");
835						}
836					}
837				}
838			}).start();
839		} catch (IOException e) {
840			Log.d(LOGTAG, "io exception during disconnect");
841		}
842	}
843
844	public List<String> findDiscoItemsByFeature(String feature) {
845		List<String> items = new ArrayList<String>();
846		for (Entry<String, List<String>> cursor : disco.entrySet()) {
847			if (cursor.getValue().contains(feature)) {
848				items.add(cursor.getKey());
849			}
850		}
851		return items;
852	}
853	
854	public String findDiscoItemByFeature(String feature) {
855		List<String> items = findDiscoItemsByFeature(feature);
856		if (items.size()>=1) {
857			return items.get(0);
858		}
859		return null;
860	}
861
862	public void r() {
863		this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
864	}
865
866	public int getReceivedStanzas() {
867		return this.stanzasReceived;
868	}
869
870	public int getSentStanzas() {
871		return this.stanzasSent;
872	}
873
874	public String getMucServer() {
875		return findDiscoItemByFeature("http://jabber.org/protocol/muc");
876	}
877
878	public int getTimeToNextAttempt() {
879		int interval = (int) (25 * Math.pow(1.5, attempt));
880		int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
881		return interval - secondsSinceLast;
882	}
883
884	public int getAttempt() {
885		return this.attempt;
886	}
887	
888	public Features getFeatures() {
889		return this.features;
890	}
891	
892	public class Features {
893		XmppConnection connection;
894		public Features(XmppConnection connection) {
895			this.connection = connection;
896		}
897		
898		private boolean hasDiscoFeature(String server, String feature) {
899			if (!connection.disco.containsKey(server)) {
900				return false;
901			}
902			return connection.disco.get(server).contains(feature);
903		}
904		
905		public boolean carbons() {
906			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
907		}
908		
909		public boolean sm() {
910			if (connection.streamFeatures == null) {
911				return false;
912			} else {
913				return connection.streamFeatures.hasChild("sm");
914			}
915		}
916		
917		public boolean pubsub() {
918			return hasDiscoFeature(account.getServer(), "http://jabber.org/protocol/pubsub#publish");
919		}
920		
921		public boolean rosterVersioning() {
922			if (connection.streamFeatures == null) {
923				return false;
924			} else {
925				return connection.streamFeatures.hasChild("ver");
926			}
927		}
928	}
929}