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