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